@subql/node-ethereum 0.1.1 → 0.2.0

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +5 -1
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/indexer/blockDispatcher/base-block-dispatcher.d.ts +40 -0
  4. package/dist/indexer/blockDispatcher/base-block-dispatcher.js +97 -0
  5. package/dist/indexer/blockDispatcher/base-block-dispatcher.js.map +1 -0
  6. package/dist/indexer/blockDispatcher/block-dispatcher.service.d.ts +23 -0
  7. package/dist/indexer/blockDispatcher/block-dispatcher.service.js +134 -0
  8. package/dist/indexer/blockDispatcher/block-dispatcher.service.js.map +1 -0
  9. package/dist/indexer/blockDispatcher/index.d.ts +4 -0
  10. package/dist/indexer/blockDispatcher/index.js +10 -0
  11. package/dist/indexer/blockDispatcher/index.js.map +1 -0
  12. package/dist/indexer/blockDispatcher/worker-block-dispatcher.service.d.ts +20 -0
  13. package/dist/indexer/blockDispatcher/worker-block-dispatcher.service.js +170 -0
  14. package/dist/indexer/blockDispatcher/worker-block-dispatcher.service.js.map +1 -0
  15. package/dist/indexer/dynamic-ds.service.d.ts +1 -0
  16. package/dist/indexer/dynamic-ds.service.js +19 -12
  17. package/dist/indexer/dynamic-ds.service.js.map +1 -1
  18. package/dist/indexer/fetch.module.js +3 -3
  19. package/dist/indexer/fetch.module.js.map +1 -1
  20. package/dist/indexer/fetch.service.d.ts +6 -4
  21. package/dist/indexer/fetch.service.js +45 -16
  22. package/dist/indexer/fetch.service.js.map +1 -1
  23. package/dist/indexer/indexer.manager.d.ts +1 -0
  24. package/dist/indexer/indexer.manager.js +2 -1
  25. package/dist/indexer/indexer.manager.js.map +1 -1
  26. package/dist/indexer/project.service.d.ts +3 -0
  27. package/dist/indexer/project.service.js +18 -0
  28. package/dist/indexer/project.service.js.map +1 -1
  29. package/dist/indexer/worker/worker.service.d.ts +1 -0
  30. package/dist/indexer/worker/worker.service.js.map +1 -1
  31. package/dist/main.js +3 -0
  32. package/dist/main.js.map +1 -1
  33. package/dist/subcommands/reindex.init.js +1 -0
  34. package/dist/subcommands/reindex.init.js.map +1 -1
  35. package/dist/subcommands/reindex.module.js +10 -1
  36. package/dist/subcommands/reindex.module.js.map +1 -1
  37. package/dist/subcommands/reindex.service.d.ts +4 -3
  38. package/dist/subcommands/reindex.service.js +21 -42
  39. package/dist/subcommands/reindex.service.js.map +1 -1
  40. package/dist/utils/project.js +21 -0
  41. package/dist/utils/project.js.map +1 -1
  42. package/dist/utils/reindex.d.ts +5 -0
  43. package/dist/utils/reindex.js +48 -0
  44. package/dist/utils/reindex.js.map +1 -0
  45. package/dist/yargs.d.ts +7 -1
  46. package/dist/yargs.js +6 -0
  47. package/dist/yargs.js.map +1 -1
  48. package/package.json +5 -5
  49. package/dist/indexer/worker/block-dispatcher.service.d.ts +0 -69
  50. package/dist/indexer/worker/block-dispatcher.service.js +0 -356
  51. package/dist/indexer/worker/block-dispatcher.service.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"dynamic-ds.service.js","sourceRoot":"","sources":["../../src/indexer/dynamic-ds.service.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;;;;;;;;;;;;;AAEtC,oDAA4B;AAC5B,2CAA4C;AAC5C,4DAAiE;AACjE,gDAA2D;AAC3D,mCAAmC;AAEnC,kEAA+E;AAC/E,iEAA4D;AAE5D,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,YAAY,CAAC,CAAC;AAEvC,MAAM,YAAY,GAAG,oBAAoB,CAAC;AAC1C,MAAM,cAAc,GAAG,KAAK,CAAC;AAStB,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IAI3B,YACmB,kBAAsC,EACtC,OAAwB;QADxB,uBAAkB,GAAlB,kBAAkB,CAAoB;QACtC,YAAO,GAAP,OAAO,CAAiB;IACxC,CAAC;IAEJ,IAAI,CAAC,YAA0B;QAC7B,IAAI,CAA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4CAAgB","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport assert from 'assert';\nimport { Injectable } from '@nestjs/common';\nimport { isCustomDs, isRuntimeDs } from '@subql/common-ethereum';\nimport { getLogger, MetadataRepo } from '@subql/node-core';\nimport { cloneDeep } from 'lodash';\nimport { Transaction } from 'sequelize/types';\nimport { SubqlProjectDs, SubqueryProject } from '../configure/SubqueryProject';\nimport { DsProcessorService } from './ds-processor.service';\n\nconst logger = getLogger('dynamic-ds');\n\nconst METADATA_KEY = 'dynamicDatasources';\nconst TEMP_DS_PREFIX = 'ds_';\n\ninterface DatasourceParams {\n templateName: string;\n args?: Record<string, unknown>;\n startBlock: number;\n}\n\n@Injectable()\nexport class DynamicDsService {\n private metaDataRepo: MetadataRepo;\n private tempDsRecords: Record<string, string>;\n\n constructor(\n private readonly dsProcessorService: DsProcessorService,\n private readonly project: SubqueryProject,\n ) {}\n\n init(metaDataRepo: MetadataRepo): void {\n this.metaDataRepo = metaDataRepo;\n }\n\n private _datasources: SubqlProjectDs[];\n\n async createDynamicDatasource(\n params: DatasourceParams,\n tx: Transaction,\n ): Promise<SubqlProjectDs> {\n try {\n const ds = await this.getDatasource(params);\n\n await this.saveDynamicDatasourceParams(params, tx);\n\n logger.info(\n `Created new dynamic datasource from template: \"${params.templateName}\"`,\n );\n\n if (!this._datasources) this._datasources = [];\n this._datasources.push(ds);\n\n return ds;\n } catch (e) {\n logger.error(e.message);\n process.exit(1);\n }\n }\n\n async getDynamicDatasources(): Promise<SubqlProjectDs[]> {\n if (!this._datasources) {\n try {\n const params = await this.getDynamicDatasourceParams();\n\n this._datasources = await Promise.all(\n params.map((params) => this.getDatasource(params)),\n );\n } catch (e) {\n logger.error(`Unable to get dynamic datasources:\\n${e.message}`);\n process.exit(1);\n }\n }\n\n return this._datasources;\n }\n\n deleteTempDsRecords(blockHeight: number) {\n delete this.tempDsRecords[TEMP_DS_PREFIX + blockHeight];\n }\n\n private async getDynamicDatasourceParams(\n blockHeight?: number,\n ): Promise<DatasourceParams[]> {\n assert(this.metaDataRepo, `Model _metadata does not exist`);\n const record = await this.metaDataRepo.findByPk(METADATA_KEY);\n let results = record?.value;\n\n if (!results || typeof results !== 'string') {\n if (blockHeight !== undefined) {\n results = this.tempDsRecords?.[TEMP_DS_PREFIX + blockHeight];\n if (!results || typeof results !== 'string') {\n return [];\n }\n } else {\n return [];\n }\n }\n\n return JSON.parse(results);\n }\n\n private async saveDynamicDatasourceParams(\n dsParams: DatasourceParams,\n tx: Transaction,\n ): Promise<void> {\n const existing = await this.getDynamicDatasourceParams(dsParams.startBlock);\n\n assert(this.metaDataRepo, `Model _metadata does not exist`);\n const dsRecords = JSON.stringify([...existing, dsParams]);\n await this.metaDataRepo\n .upsert({ key: METADATA_KEY, value: dsRecords }, { transaction: tx })\n .then(() => {\n this.tempDsRecords = {\n ...this.tempDsRecords,\n ...{ [TEMP_DS_PREFIX + dsParams.startBlock]: dsRecords },\n };\n });\n }\n\n private async getDatasource(\n params: DatasourceParams,\n ): Promise<SubqlProjectDs> {\n const template = cloneDeep(\n this.project.templates.find((t) => t.name === params.templateName),\n );\n\n if (!template) {\n throw new Error(\n `Unable to find matching template in project for name: \"${params.templateName}\"`,\n );\n }\n\n logger.info(\n `Initialised dynamic datasource from template: \"${params.templateName}\"`,\n );\n\n const dsObj = {\n ...template,\n startBlock: params.startBlock,\n } as SubqlProjectDs;\n delete dsObj.name;\n try {\n if (isCustomDs(dsObj)) {\n dsObj.processor.options = {\n ...dsObj.processor.options,\n ...params.args,\n };\n await this.dsProcessorService.validateCustomDs([dsObj]);\n } else if (isRuntimeDs(dsObj)) {\n // XXX add any modifications to the ds here\n }\n\n return dsObj;\n } catch (e) {\n throw new Error(`Unable to create dynamic datasource.\\n ${e.message}`);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"dynamic-ds.service.js","sourceRoot":"","sources":["../../src/indexer/dynamic-ds.service.ts"],"names":[],"mappings":";AAA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IACP,CAAC;IAEO,KAAK,CAAC,aAAa,CACzB,MAAwB;QAExB,MAAM,QAAQ,GAAG,IAAA,kBAAS,EACxB,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,YAAY,CAAC,CACnE,CAAC;QAEF,IAAI,CAAC,QAAQ,EAAE;YACb,MAAM,IAAI,KAAK,CACb,0DAA0D,MAAM,CAAC,YAAY,GAAG,CACjF,CAAC;SACH;QAED,MAAM,CAAC,IAAI,CACT,kDAAkD,MAAM,CAAC,YAAY,GAAG,CACzE,CAAC;QAEF,MAAM,KAAK,GAAG,gCACT,QAAQ,KACX,UAAU,EAAE,MAAM,CAAC,UAAU,GACZ,CAAC;QACpB,OAAO,KAAK,CAAC,IAAI,CAAC;QAClB,IAAI;YACF,IAAI,IAAA,4BAAU,EAAC,KAAK,CAAC,EAAE;gBACrB,KAAK,CAAC,SAAS,CAAC,OAAO,mCAClB,KAAK,CAAC,SAAS,CAAC,OAAO,GACvB,MAAM,CAAC,IAAI,CACf,CAAC;gBACF,MAAM,IAAI,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;aACzD;iBAAM,IAAI,IAAA,6BAAW,EAAC,KAAK,CAAC,EAAE;gBAC7B,2CAA2C;aAC5C;YAED,OAAO,KAAK,CAAC;SACd;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;SACxE;IACH,CAAC;CACF,CAAA;AA5JY,gBAAgB;IAD5B,IAAA,mBAAU,GAAE;qCAM4B,yCAAkB;QAC7B,iCAAe;GANhC,gBAAgB,CA4J5B;AA5JY,4CAAgB","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport assert from 'assert';\nimport { Injectable } from '@nestjs/common';\nimport { isCustomDs, isRuntimeDs } from '@subql/common-ethereum';\nimport { getLogger, MetadataRepo } from '@subql/node-core';\nimport { cloneDeep, isEqual, unionWith } from 'lodash';\nimport { Transaction } from 'sequelize/types';\nimport { SubqlProjectDs, SubqueryProject } from '../configure/SubqueryProject';\nimport { DsProcessorService } from './ds-processor.service';\n\nconst logger = getLogger('dynamic-ds');\n\nconst METADATA_KEY = 'dynamicDatasources';\nconst TEMP_DS_PREFIX = 'ds_';\n\ninterface DatasourceParams {\n templateName: string;\n args?: Record<string, unknown>;\n startBlock: number;\n}\n\n@Injectable()\nexport class DynamicDsService {\n private metaDataRepo: MetadataRepo;\n private tempDsRecords: Record<string, string>;\n\n constructor(\n private readonly dsProcessorService: DsProcessorService,\n private readonly project: SubqueryProject,\n ) {}\n\n init(metaDataRepo: MetadataRepo): void {\n this.metaDataRepo = metaDataRepo;\n }\n\n private _datasources: SubqlProjectDs[];\n\n async resetDynamicDatasource(targetHeight: number, tx: Transaction) {\n const dynamicDs = await this.getDynamicDatasourceParams();\n if (dynamicDs.length !== 0) {\n const filteredDs = dynamicDs.filter(\n (ds) => ds.startBlock <= targetHeight,\n );\n const dsRecords = JSON.stringify(filteredDs);\n await this.metaDataRepo.upsert(\n { key: METADATA_KEY, value: dsRecords },\n { transaction: tx },\n );\n }\n }\n\n async createDynamicDatasource(\n params: DatasourceParams,\n tx: Transaction,\n ): Promise<SubqlProjectDs> {\n try {\n const ds = await this.getDatasource(params);\n\n await this.saveDynamicDatasourceParams(params, tx);\n\n logger.info(\n `Created new dynamic datasource from template: \"${params.templateName}\"`,\n );\n\n if (!this._datasources) this._datasources = [];\n this._datasources.push(ds);\n\n return ds;\n } catch (e) {\n logger.error(e.message);\n process.exit(1);\n }\n }\n\n async getDynamicDatasources(): Promise<SubqlProjectDs[]> {\n if (!this._datasources) {\n try {\n const params = await this.getDynamicDatasourceParams();\n\n this._datasources = await Promise.all(\n params.map((params) => this.getDatasource(params)),\n );\n } catch (e) {\n logger.error(`Unable to get dynamic datasources:\\n${e.message}`);\n process.exit(1);\n }\n }\n\n return this._datasources;\n }\n\n deleteTempDsRecords(blockHeight: number) {\n delete this.tempDsRecords[TEMP_DS_PREFIX + blockHeight];\n }\n\n private async getDynamicDatasourceParams(\n blockHeight?: number,\n ): Promise<DatasourceParams[]> {\n assert(this.metaDataRepo, `Model _metadata does not exist`);\n const record = await this.metaDataRepo.findByPk(METADATA_KEY);\n\n let results: DatasourceParams[] = [];\n\n const metaResults: DatasourceParams[] = JSON.parse(\n (record?.value as string) ?? '[]',\n );\n if (metaResults.length) {\n results = [...metaResults];\n }\n\n if (blockHeight !== undefined) {\n const tempResults: DatasourceParams[] = JSON.parse(\n this.tempDsRecords?.[TEMP_DS_PREFIX + blockHeight] ?? '[]',\n );\n if (tempResults.length) {\n results = unionWith(results, tempResults, isEqual);\n }\n }\n\n return results;\n }\n\n private async saveDynamicDatasourceParams(\n dsParams: DatasourceParams,\n tx: Transaction,\n ): Promise<void> {\n const existing = await this.getDynamicDatasourceParams(dsParams.startBlock);\n\n assert(this.metaDataRepo, `Model _metadata does not exist`);\n const dsRecords = JSON.stringify([...existing, dsParams]);\n await this.metaDataRepo\n .upsert({ key: METADATA_KEY, value: dsRecords }, { transaction: tx })\n .then(() => {\n this.tempDsRecords = {\n ...this.tempDsRecords,\n [TEMP_DS_PREFIX + dsParams.startBlock]: dsRecords,\n };\n });\n }\n\n private async getDatasource(\n params: DatasourceParams,\n ): Promise<SubqlProjectDs> {\n const template = cloneDeep(\n this.project.templates.find((t) => t.name === params.templateName),\n );\n\n if (!template) {\n throw new Error(\n `Unable to find matching template in project for name: \"${params.templateName}\"`,\n );\n }\n\n logger.info(\n `Initialised dynamic datasource from template: \"${params.templateName}\"`,\n );\n\n const dsObj = {\n ...template,\n startBlock: params.startBlock,\n } as SubqlProjectDs;\n delete dsObj.name;\n try {\n if (isCustomDs(dsObj)) {\n dsObj.processor.options = {\n ...dsObj.processor.options,\n ...params.args,\n };\n await this.dsProcessorService.validateCustomDs([dsObj]);\n } else if (isRuntimeDs(dsObj)) {\n // XXX add any modifications to the ds here\n }\n\n return dsObj;\n } catch (e) {\n throw new Error(`Unable to create dynamic datasource.\\n ${e.message}`);\n }\n }\n}\n"]}
@@ -14,6 +14,7 @@ const event_emitter_1 = require("@nestjs/event-emitter");
14
14
  const node_core_1 = require("@subql/node-core");
15
15
  const SubqueryProject_1 = require("../configure/SubqueryProject");
16
16
  const api_service_ethereum_1 = require("../ethereum/api.service.ethereum");
17
+ const blockDispatcher_1 = require("./blockDispatcher");
17
18
  const dictionary_service_1 = require("./dictionary.service");
18
19
  const ds_processor_service_1 = require("./ds-processor.service");
19
20
  const dynamic_ds_service_1 = require("./dynamic-ds.service");
@@ -21,7 +22,6 @@ const fetch_service_1 = require("./fetch.service");
21
22
  const indexer_manager_1 = require("./indexer.manager");
22
23
  const project_service_1 = require("./project.service");
23
24
  const sandbox_service_1 = require("./sandbox.service");
24
- const block_dispatcher_service_1 = require("./worker/block-dispatcher.service");
25
25
  let FetchModule = class FetchModule {
26
26
  };
27
27
  FetchModule = __decorate([
@@ -41,8 +41,8 @@ FetchModule = __decorate([
41
41
  {
42
42
  provide: 'IBlockDispatcher',
43
43
  useFactory: (nodeConfig, eventEmitter, projectService, apiService, indexerManager) => nodeConfig.workers !== undefined
44
- ? new block_dispatcher_service_1.WorkerBlockDispatcherService(nodeConfig, eventEmitter, projectService)
45
- : new block_dispatcher_service_1.BlockDispatcherService(apiService, nodeConfig, indexerManager, eventEmitter, projectService),
44
+ ? new blockDispatcher_1.WorkerBlockDispatcherService(nodeConfig, eventEmitter, projectService)
45
+ : new blockDispatcher_1.BlockDispatcherService(apiService, nodeConfig, indexerManager, eventEmitter, projectService),
46
46
  inject: [
47
47
  node_core_1.NodeConfig,
48
48
  event_emitter_1.EventEmitter2,
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.module.js","sourceRoot":"","sources":["../../src/indexer/fetch.module.ts"],"names":[],"mappings":";AAAA,gEA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;KACpC,CAAC;GACW,WAAW,CAAG;AAAd,kCAAW","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Module } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport {\n BenchmarkService,\n MmrService,\n StoreService,\n PoiService,\n ApiService,\n NodeConfig,\n} from '@subql/node-core';\nimport { SubqueryProject } from '../configure/SubqueryProject';\nimport { EthereumApiService } from '../ethereum/api.service.ethereum';\nimport { DictionaryService } from './dictionary.service';\nimport { DsProcessorService } from './ds-processor.service';\nimport { DynamicDsService } from './dynamic-ds.service';\nimport { FetchService } from './fetch.service';\nimport { IndexerManager } from './indexer.manager';\nimport { ProjectService } from './project.service';\nimport { SandboxService } from './sandbox.service';\nimport {\n BlockDispatcherService,\n WorkerBlockDispatcherService,\n} from './worker/block-dispatcher.service';\n\n@Module({\n providers: [\n StoreService,\n {\n provide: ApiService,\n useFactory: async (project: SubqueryProject) => {\n const apiService = new EthereumApiService(project);\n\n await apiService.init();\n return apiService;\n },\n inject: [SubqueryProject],\n },\n IndexerManager,\n {\n provide: 'IBlockDispatcher',\n useFactory: (\n nodeConfig: NodeConfig,\n eventEmitter: EventEmitter2,\n projectService: ProjectService,\n apiService: ApiService,\n indexerManager: IndexerManager,\n ) =>\n nodeConfig.workers !== undefined\n ? new WorkerBlockDispatcherService(\n nodeConfig,\n eventEmitter,\n projectService,\n )\n : new BlockDispatcherService(\n apiService,\n nodeConfig,\n indexerManager,\n eventEmitter,\n projectService,\n ),\n inject: [\n NodeConfig,\n EventEmitter2,\n ProjectService,\n ApiService,\n IndexerManager,\n ],\n },\n FetchService,\n BenchmarkService,\n DictionaryService,\n SandboxService,\n DsProcessorService,\n DynamicDsService,\n PoiService,\n MmrService,\n ProjectService,\n ],\n exports: [StoreService, MmrService],\n})\nexport class FetchModule {}\n"]}
1
+ {"version":3,"file":"fetch.module.js","sourceRoot":"","sources":["../../src/indexer/fetch.module.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C,wBAAY,EAAE,sBAAU,CAAC;KACpC,CAAC;GACW,WAAW,CAAG;AAAd,kCAAW","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Module } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport {\n BenchmarkService,\n MmrService,\n StoreService,\n PoiService,\n ApiService,\n NodeConfig,\n} from '@subql/node-core';\nimport { SubqueryProject } from '../configure/SubqueryProject';\nimport { EthereumApiService } from '../ethereum/api.service.ethereum';\nimport {\n BlockDispatcherService,\n WorkerBlockDispatcherService,\n} from './blockDispatcher';\nimport { DictionaryService } from './dictionary.service';\nimport { DsProcessorService } from './ds-processor.service';\nimport { DynamicDsService } from './dynamic-ds.service';\nimport { FetchService } from './fetch.service';\nimport { IndexerManager } from './indexer.manager';\nimport { ProjectService } from './project.service';\nimport { SandboxService } from './sandbox.service';\n\n@Module({\n providers: [\n StoreService,\n {\n provide: ApiService,\n useFactory: async (project: SubqueryProject) => {\n const apiService = new EthereumApiService(project);\n\n await apiService.init();\n return apiService;\n },\n inject: [SubqueryProject],\n },\n IndexerManager,\n {\n provide: 'IBlockDispatcher',\n useFactory: (\n nodeConfig: NodeConfig,\n eventEmitter: EventEmitter2,\n projectService: ProjectService,\n apiService: ApiService,\n indexerManager: IndexerManager,\n ) =>\n nodeConfig.workers !== undefined\n ? new WorkerBlockDispatcherService(\n nodeConfig,\n eventEmitter,\n projectService,\n )\n : new BlockDispatcherService(\n apiService,\n nodeConfig,\n indexerManager,\n eventEmitter,\n projectService,\n ),\n inject: [\n NodeConfig,\n EventEmitter2,\n ProjectService,\n ApiService,\n IndexerManager,\n ],\n },\n FetchService,\n BenchmarkService,\n DictionaryService,\n SandboxService,\n DsProcessorService,\n DynamicDsService,\n PoiService,\n MmrService,\n ProjectService,\n ],\n exports: [StoreService, MmrService],\n})\nexport class FetchModule {}\n"]}
@@ -4,9 +4,9 @@ import { SchedulerRegistry } from '@nestjs/schedule';
4
4
  import { ApiService, NodeConfig } from '@subql/node-core';
5
5
  import { DictionaryQueryEntry, ApiWrapper } from '@subql/types-ethereum';
6
6
  import { SubqueryProject } from '../configure/SubqueryProject';
7
+ import { IBlockDispatcher } from './blockDispatcher';
7
8
  import { DictionaryService } from './dictionary.service';
8
9
  import { DynamicDsService } from './dynamic-ds.service';
9
- import { IBlockDispatcher } from './worker/block-dispatcher.service';
10
10
  export declare class FetchService implements OnApplicationShutdown {
11
11
  private apiService;
12
12
  private nodeConfig;
@@ -19,21 +19,22 @@ export declare class FetchService implements OnApplicationShutdown {
19
19
  private latestBestHeight;
20
20
  private latestFinalizedHeight;
21
21
  private isShutdown;
22
- private useDictionary;
23
22
  private dictionaryQueryEntries?;
24
23
  private batchSizeScale;
25
24
  private templateDynamicDatasouces;
25
+ private dictionaryGenesisMatches;
26
26
  constructor(apiService: ApiService, nodeConfig: NodeConfig, project: SubqueryProject, blockDispatcher: IBlockDispatcher, dictionaryService: DictionaryService, dynamicDsService: DynamicDsService, eventEmitter: EventEmitter2, schedulerRegistry: SchedulerRegistry);
27
27
  onApplicationShutdown(): void;
28
28
  get api(): ApiWrapper;
29
29
  syncDynamicDatascourcesFromMeta(): Promise<void>;
30
- getDictionaryQueryEntries(): DictionaryQueryEntry[];
30
+ buildDictionaryQueryEntries(startBlock: number): DictionaryQueryEntry[];
31
31
  updateDictionary(): void;
32
+ private get useDictionary();
32
33
  init(startHeight: number): Promise<void>;
33
34
  checkBatchScale(): void;
34
35
  getFinalizedBlockHead(): Promise<void>;
35
36
  getBestBlockHead(): Promise<void>;
36
- startLoop(initBlockHeight: number): Promise<void>;
37
+ private startLoop;
37
38
  getModulos(): number[];
38
39
  getModuloBlocks(startHeight: number, endHeight: number): number[];
39
40
  getEnqueuedModuloBlocks(startBlockHeight: number): number[];
@@ -41,4 +42,5 @@ export declare class FetchService implements OnApplicationShutdown {
41
42
  private nextEndBlockHeight;
42
43
  private dictionaryValidation;
43
44
  resetForNewDs(blockHeight: number): Promise<void>;
45
+ resetForIncorrectBestBlock(blockHeight: number): Promise<void>;
44
46
  }
@@ -91,6 +91,7 @@ let FetchService = class FetchService {
91
91
  this.eventEmitter = eventEmitter;
92
92
  this.schedulerRegistry = schedulerRegistry;
93
93
  this.isShutdown = false;
94
+ this.dictionaryGenesisMatches = true;
94
95
  this.batchSizeScale = 1;
95
96
  }
96
97
  onApplicationShutdown() {
@@ -103,11 +104,15 @@ let FetchService = class FetchService {
103
104
  this.templateDynamicDatasouces =
104
105
  await this.dynamicDsService.getDynamicDatasources();
105
106
  }
106
- // TODO: if custom ds doesn't support dictionary, use baseFilter, if yes, let
107
- getDictionaryQueryEntries() {
107
+ buildDictionaryQueryEntries(startBlock) {
108
108
  const queryEntries = [];
109
- const dataSources = this.project.dataSources;
110
- for (const ds of dataSources.concat(this.templateDynamicDatasouces)) {
109
+ // Only run the ds that is equal or less than startBlock
110
+ // sort array from lowest ds.startBlock to highest
111
+ const filteredDs = this.project.dataSources
112
+ .concat(this.templateDynamicDatasouces)
113
+ .filter((ds) => ds.startBlock <= startBlock)
114
+ .sort((a, b) => a.startBlock - b.startBlock);
115
+ for (const ds of filteredDs) {
111
116
  for (const handler of ds.mapping.handlers) {
112
117
  let filterList;
113
118
  filterList = [handler.filter];
@@ -148,11 +153,13 @@ let FetchService = class FetchService {
148
153
  return (0, lodash_1.uniqBy)(queryEntries, (item) => `${item.entity}|${JSON.stringify((0, lodash_1.sortBy)(item.conditions, (c) => c.field))}`);
149
154
  }
150
155
  updateDictionary() {
156
+ this.dictionaryService.buildDictionaryEntryMap(this.project.dataSources.concat(this.templateDynamicDatasouces), this.buildDictionaryQueryEntries.bind(this));
157
+ }
158
+ get useDictionary() {
151
159
  var _a;
152
- this.dictionaryQueryEntries = this.getDictionaryQueryEntries();
153
- this.useDictionary =
154
- !!((_a = this.dictionaryQueryEntries) === null || _a === void 0 ? void 0 : _a.length) &&
155
- !!this.project.network.dictionary;
160
+ return (!!this.project.network.dictionary &&
161
+ this.dictionaryGenesisMatches &&
162
+ !!this.dictionaryService.getDictionaryQueryEntries((_a = this.blockDispatcher.latestBufferedHeight) !== null && _a !== void 0 ? _a : Math.min(...this.project.dataSources.map((ds) => ds.startBlock))).length);
156
163
  }
157
164
  async init(startHeight) {
158
165
  if (this.api) {
@@ -187,9 +194,11 @@ let FetchService = class FetchService {
187
194
  const currentFinalizedHeight = await this.api.getFinalizedBlockHeight();
188
195
  if (this.latestFinalizedHeight !== currentFinalizedHeight) {
189
196
  this.latestFinalizedHeight = currentFinalizedHeight;
190
- this.eventEmitter.emit(node_core_1.IndexerEvent.BlockTarget, {
191
- height: this.latestFinalizedHeight,
192
- });
197
+ if (!this.nodeConfig.unfinalizedBlocks) {
198
+ this.eventEmitter.emit(node_core_1.IndexerEvent.BlockTarget, {
199
+ height: this.latestFinalizedHeight,
200
+ });
201
+ }
193
202
  }
194
203
  }
195
204
  catch (e) {
@@ -208,6 +217,11 @@ let FetchService = class FetchService {
208
217
  this.eventEmitter.emit(node_core_1.IndexerEvent.BlockBest, {
209
218
  height: this.latestBestHeight,
210
219
  });
220
+ if (this.nodeConfig.unfinalizedBlocks) {
221
+ this.eventEmitter.emit(node_core_1.IndexerEvent.BlockTarget, {
222
+ height: this.latestBestHeight,
223
+ });
224
+ }
211
225
  }
212
226
  }
213
227
  catch (e) {
@@ -259,8 +273,11 @@ let FetchService = class FetchService {
259
273
  while (!this.isShutdown) {
260
274
  startBlockHeight = getStartBlockHeight();
261
275
  scaledBatchSize = Math.max(Math.round(this.batchSizeScale * this.nodeConfig.batchSize), Math.min(MINIMUM_BATCH_SIZE, this.nodeConfig.batchSize * 3));
276
+ const latestHeight = this.nodeConfig.unfinalizedBlocks
277
+ ? this.latestBestHeight
278
+ : this.latestFinalizedHeight;
262
279
  if (this.blockDispatcher.freeSize < scaledBatchSize ||
263
- startBlockHeight > this.latestFinalizedHeight) {
280
+ startBlockHeight > latestHeight) {
264
281
  await (0, node_core_1.delay)(1);
265
282
  continue;
266
283
  }
@@ -268,7 +285,7 @@ let FetchService = class FetchService {
268
285
  const queryEndBlock = startBlockHeight + DICTIONARY_MAX_QUERY_SIZE;
269
286
  const moduloBlocks = this.getModuloBlocks(startBlockHeight, queryEndBlock);
270
287
  try {
271
- const dictionary = await this.dictionaryService.getDictionary(startBlockHeight, queryEndBlock, scaledBatchSize, this.dictionaryQueryEntries);
288
+ const dictionary = await this.dictionaryService.scopedDictionaryEntries(startBlockHeight, queryEndBlock, scaledBatchSize);
272
289
  if (startBlockHeight !== getStartBlockHeight()) {
273
290
  logger.debug(`Queue was reset for new DS, discarding dictionary query result`);
274
291
  continue;
@@ -298,7 +315,7 @@ let FetchService = class FetchService {
298
315
  }
299
316
  }
300
317
  const endHeight = this.nextEndBlockHeight(startBlockHeight, scaledBatchSize);
301
- if (this.getModulos().length === handlers.length) {
318
+ if (handlers.length && this.getModulos().length === handlers.length) {
302
319
  this.blockDispatcher.enqueueBlocks(this.getEnqueuedModuloBlocks(startBlockHeight));
303
320
  }
304
321
  else {
@@ -309,14 +326,21 @@ let FetchService = class FetchService {
309
326
  nextEndBlockHeight(startBlockHeight, scaledBatchSize) {
310
327
  let endBlockHeight = startBlockHeight + scaledBatchSize - 1;
311
328
  if (endBlockHeight > this.latestFinalizedHeight) {
312
- endBlockHeight = this.latestFinalizedHeight;
329
+ if (this.nodeConfig.unfinalizedBlocks) {
330
+ if (endBlockHeight >= this.latestBestHeight) {
331
+ endBlockHeight = this.latestBestHeight;
332
+ }
333
+ }
334
+ else {
335
+ endBlockHeight = this.latestFinalizedHeight;
336
+ }
313
337
  }
314
338
  return endBlockHeight;
315
339
  }
316
340
  dictionaryValidation({ _metadata: metaData }, startBlockHeight) {
317
341
  if (metaData.genesisHash !== this.api.getGenesisHash()) {
318
342
  logger.error('The dictionary that you have specified does not match the chain you are indexing, it will be ignored. Please update your project manifest to reference the correct dictionary');
319
- this.useDictionary = false;
343
+ this.dictionaryGenesisMatches = false;
320
344
  this.eventEmitter.emit(node_core_1.IndexerEvent.UsingDictionary, {
321
345
  value: Number(this.useDictionary),
322
346
  });
@@ -336,6 +360,11 @@ let FetchService = class FetchService {
336
360
  this.updateDictionary();
337
361
  this.blockDispatcher.flushQueue(blockHeight);
338
362
  }
363
+ async resetForIncorrectBestBlock(blockHeight) {
364
+ await this.syncDynamicDatascourcesFromMeta();
365
+ this.updateDictionary();
366
+ this.blockDispatcher.flushQueue(blockHeight);
367
+ }
339
368
  };
340
369
  __decorate([
341
370
  (0, schedule_1.Interval)(CHECK_MEMORY_INTERVAL),
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.service.js","sourceRoot":"","sources":["../../src/indexer/fetch.service.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;;;;;;;;;;;;;AAEtC,2CAA2E;AAC3E,yDAAsD;AACtD,+CAA+D;AAC/D,4DAIgC;AAChC,gDAQ0B;AAO1B,mCAA+C;AAC/C,kEAA+E;AAC/E,+DAA0D;AAC1D,4CAAkE;AAClE,6DAAyD;AACzD,6DAAwD;AAGxD,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,OAAO,CAAC,CAAC;AAClC,IAAI,mBAAmB,GAAG,IAAI,CAAC;AAC/B,MAAM,yBAAyB,GAAG,KAAK,CAAC;AACxC,MAAM,qBAAqB,GAAG,KAAK,CAAC;AACpC,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAE7B,SAAS,uBAAuB,CAC9B,MAAyB;IAEzB,MAAM,UAAU,GAAG,EAAE,CAAC;IACtB,IAAI,MAAM,CAAC,OAAO,EAAE;QAClB,UAAU,CAAC,IAAI,CAAC;YACd,KAAK,EAAE,SAAS;YAChB,KAAK,EAAE,MAAM,CAAC,OAAO,CAAC,WAAW,EAAE;SACpC,CAAC,CAAC;KACJ;IACD,IAAI,MAAM,CAAC,MAAM,EAAE;QACjB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IA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CAAC,+BAA+B,EAAE,CAAC;QAC7C,IAAI,CAAC,gBAAgB,CAAC,mBAAmB,CAAC,WAAW,CAAC,CAAC;QACvD,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACxB,IAAI,CAAC,eAAe,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;IAC/C,CAAC;CACF,CAAA;AAtOC;IAAC,IAAA,mBAAQ,EAAC,qBAAqB,CAAC;;;;mDAS/B;AAGK;IADL,IAAA,mBAAQ,EAAC,mBAAmB,GAAG,IAAI,CAAC;;;;yDAiBpC;AAGK;IADL,IAAA,mBAAQ,EAAC,mBAAmB,GAAG,IAAI,CAAC;;;;oDAiBpC;AArKU,YAAY;IADxB,IAAA,mBAAU,GAAE;IAcR,WAAA,IAAA,eAAM,EAAC,kBAAkB,CAAC,CAAA;qCAHP,sBAAU;QACV,sBAAU;QACb,iCAAe,UAEL,sCAAiB;QAClB,qCAAgB;QACpB,6BAAa;QACR,4BAAiB;GAjBnC,YAAY,CA4VxB;AA5VY,oCAAY","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Inject, Injectable, OnApplicationShutdown } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport { Interval, SchedulerRegistry } from '@nestjs/schedule';\nimport {\n isCustomDs,\n EthereumHandlerKind,\n SubqlHandlerFilter,\n} from '@subql/common-ethereum';\nimport {\n ApiService,\n Dictionary,\n checkMemoryUsage,\n delay,\n getLogger,\n IndexerEvent,\n NodeConfig,\n} from '@subql/node-core';\nimport {\n DictionaryQueryEntry,\n ApiWrapper,\n EthereumLogFilter,\n EthereumTransactionFilter,\n} from '@subql/types-ethereum';\nimport { range, sortBy, uniqBy } from 'lodash';\nimport { SubqlProjectDs, SubqueryProject } from '../configure/SubqueryProject';\nimport { calcInterval } from '../ethereum/utils.ethereum';\nimport { eventToTopic, functionToSighash } from '../utils/string';\nimport { DictionaryService } from './dictionary.service';\nimport { DynamicDsService } from './dynamic-ds.service';\nimport { IBlockDispatcher } from './worker/block-dispatcher.service';\n\nconst logger = getLogger('fetch');\nlet BLOCK_TIME_VARIANCE = 5000;\nconst DICTIONARY_MAX_QUERY_SIZE = 10000;\nconst CHECK_MEMORY_INTERVAL = 60000;\nconst MINIMUM_BATCH_SIZE = 5;\nconst INTERVAL_PERCENT = 0.9;\n\nfunction eventFilterToQueryEntry(\n filter: EthereumLogFilter,\n): DictionaryQueryEntry {\n const conditions = [];\n if (filter.address) {\n conditions.push({\n field: 'address',\n value: filter.address.toLowerCase(),\n });\n }\n if (filter.topics) {\n for (let i = 0; i < Math.min(filter.topics.length, 4); i++) {\n const topic = filter.topics[i];\n if (!topic) {\n continue;\n }\n const field = `topics${i}`;\n conditions.push({ field, value: eventToTopic(topic) });\n }\n }\n return {\n entity: 'evmLogs',\n conditions,\n };\n}\n\nfunction callFilterToQueryEntry(\n filter: EthereumTransactionFilter,\n): DictionaryQueryEntry {\n const conditions = [];\n if (filter.from) {\n conditions.push({\n field: 'from',\n value: filter.from.toLowerCase(),\n });\n }\n if (filter.to) {\n conditions.push({\n field: 'to',\n value: filter.to.toLowerCase(),\n });\n }\n if (filter.function) {\n conditions.push({\n field: 'func',\n value: functionToSighash(filter.function),\n });\n }\n return {\n entity: 'evmTransactions',\n conditions,\n };\n}\n\n@Injectable()\nexport class FetchService implements OnApplicationShutdown {\n private latestBestHeight: number;\n private latestFinalizedHeight: number;\n private isShutdown = false;\n private useDictionary: boolean;\n private dictionaryQueryEntries?: DictionaryQueryEntry[];\n private batchSizeScale: number;\n private templateDynamicDatasouces: SubqlProjectDs[];\n\n constructor(\n private apiService: ApiService,\n private nodeConfig: NodeConfig,\n private project: SubqueryProject,\n @Inject('IBlockDispatcher') private blockDispatcher: IBlockDispatcher,\n private dictionaryService: DictionaryService,\n private dynamicDsService: DynamicDsService,\n private eventEmitter: EventEmitter2,\n private schedulerRegistry: SchedulerRegistry,\n ) {\n this.batchSizeScale = 1;\n }\n\n onApplicationShutdown(): void {\n this.isShutdown = true;\n }\n\n get api(): ApiWrapper {\n return this.apiService.api;\n }\n\n async syncDynamicDatascourcesFromMeta(): Promise<void> {\n this.templateDynamicDatasouces =\n await this.dynamicDsService.getDynamicDatasources();\n }\n\n // TODO: if custom ds doesn't support dictionary, use baseFilter, if yes, let\n getDictionaryQueryEntries(): DictionaryQueryEntry[] {\n const queryEntries: DictionaryQueryEntry[] = [];\n\n const dataSources = this.project.dataSources;\n for (const ds of dataSources.concat(this.templateDynamicDatasouces)) {\n for (const handler of ds.mapping.handlers) {\n let filterList: SubqlHandlerFilter[];\n filterList = [handler.filter];\n filterList = filterList.filter((f) => f);\n if (!filterList.length) return [];\n switch (handler.kind) {\n case EthereumHandlerKind.Block:\n return [];\n case EthereumHandlerKind.Call: {\n for (const filter of filterList as EthereumTransactionFilter[]) {\n if (\n filter.from !== undefined ||\n filter.to !== undefined ||\n filter.function\n ) {\n queryEntries.push(callFilterToQueryEntry(filter));\n } else {\n return [];\n }\n }\n break;\n }\n case EthereumHandlerKind.Event: {\n for (const filter of filterList as EthereumLogFilter[]) {\n if (filter.address || filter.topics) {\n queryEntries.push(eventFilterToQueryEntry(filter));\n } else {\n return [];\n }\n }\n break;\n }\n default:\n }\n }\n }\n\n return uniqBy(\n queryEntries,\n (item) =>\n `${item.entity}|${JSON.stringify(\n sortBy(item.conditions, (c) => c.field),\n )}`,\n );\n }\n\n updateDictionary(): void {\n this.dictionaryQueryEntries = this.getDictionaryQueryEntries();\n this.useDictionary =\n !!this.dictionaryQueryEntries?.length &&\n !!this.project.network.dictionary;\n }\n\n async init(startHeight: number): Promise<void> {\n if (this.api) {\n const CHAIN_INTERVAL = calcInterval(this.api) * INTERVAL_PERCENT;\n\n BLOCK_TIME_VARIANCE = Math.min(BLOCK_TIME_VARIANCE, CHAIN_INTERVAL);\n\n this.schedulerRegistry.addInterval(\n 'getLatestBlockHead',\n setInterval(() => void this.getBestBlockHead(), BLOCK_TIME_VARIANCE),\n );\n }\n await this.syncDynamicDatascourcesFromMeta();\n this.updateDictionary();\n this.eventEmitter.emit(IndexerEvent.UsingDictionary, {\n value: Number(this.useDictionary),\n });\n await this.getFinalizedBlockHead();\n await this.getBestBlockHead();\n\n await this.blockDispatcher.init(this.resetForNewDs.bind(this));\n\n void this.startLoop(startHeight);\n }\n\n @Interval(CHECK_MEMORY_INTERVAL)\n checkBatchScale(): void {\n if (this.nodeConfig['scale-batch-size']) {\n const scale = checkMemoryUsage(this.batchSizeScale, this.nodeConfig);\n\n if (this.batchSizeScale !== scale) {\n this.batchSizeScale = scale;\n }\n }\n }\n\n @Interval(BLOCK_TIME_VARIANCE * 1000)\n async getFinalizedBlockHead(): Promise<void> {\n if (!this.api) {\n logger.debug(`Skip fetch finalized block until API is ready`);\n return;\n }\n try {\n const currentFinalizedHeight = await this.api.getFinalizedBlockHeight();\n if (this.latestFinalizedHeight !== currentFinalizedHeight) {\n this.latestFinalizedHeight = currentFinalizedHeight;\n this.eventEmitter.emit(IndexerEvent.BlockTarget, {\n height: this.latestFinalizedHeight,\n });\n }\n } catch (e) {\n logger.warn(e, `Having a problem when get finalized block`);\n }\n }\n\n @Interval(BLOCK_TIME_VARIANCE * 1000)\n async getBestBlockHead(): Promise<void> {\n if (!this.api) {\n logger.debug(`Skip fetch best block until API is ready`);\n return;\n }\n try {\n const currentBestHeight = await this.api.getLastHeight();\n if (this.latestBestHeight !== currentBestHeight) {\n this.latestBestHeight = currentBestHeight;\n this.eventEmitter.emit(IndexerEvent.BlockBest, {\n height: this.latestBestHeight,\n });\n }\n } catch (e) {\n logger.warn(e, `Having a problem when get best block`);\n }\n }\n\n async startLoop(initBlockHeight: number): Promise<void> {\n await this.fillNextBlockBuffer(initBlockHeight);\n }\n\n getModulos(): number[] {\n const modulos: number[] = [];\n for (const ds of this.project.dataSources) {\n if (isCustomDs(ds)) {\n continue;\n }\n for (const handler of ds.mapping.handlers) {\n if (\n handler.kind === EthereumHandlerKind.Block &&\n handler.filter &&\n handler.filter.modulo\n ) {\n modulos.push(handler.filter.modulo);\n }\n }\n }\n return modulos;\n }\n\n getModuloBlocks(startHeight: number, endHeight: number): number[] {\n const modulos = this.getModulos();\n const moduloBlocks: number[] = [];\n for (let i = startHeight; i < endHeight; i++) {\n if (modulos.find((m) => i % m === 0)) {\n moduloBlocks.push(i);\n }\n }\n return moduloBlocks;\n }\n\n getEnqueuedModuloBlocks(startBlockHeight: number): number[] {\n return this.getModuloBlocks(\n startBlockHeight,\n this.nodeConfig.batchSize * Math.max(...this.getModulos()) +\n startBlockHeight,\n ).slice(0, this.nodeConfig.batchSize);\n }\n\n async fillNextBlockBuffer(initBlockHeight: number): Promise<void> {\n let startBlockHeight: number;\n let scaledBatchSize: number;\n const handlers = [].concat(\n ...this.project.dataSources.map((ds) => ds.mapping.handlers),\n );\n\n const getStartBlockHeight = (): number => {\n return this.blockDispatcher.latestBufferedHeight\n ? this.blockDispatcher.latestBufferedHeight + 1\n : initBlockHeight;\n };\n\n while (!this.isShutdown) {\n startBlockHeight = getStartBlockHeight();\n\n scaledBatchSize = Math.max(\n Math.round(this.batchSizeScale * this.nodeConfig.batchSize),\n Math.min(MINIMUM_BATCH_SIZE, this.nodeConfig.batchSize * 3),\n );\n if (\n this.blockDispatcher.freeSize < scaledBatchSize ||\n startBlockHeight > this.latestFinalizedHeight\n ) {\n await delay(1);\n continue;\n }\n if (this.useDictionary) {\n const queryEndBlock = startBlockHeight + DICTIONARY_MAX_QUERY_SIZE;\n const moduloBlocks = this.getModuloBlocks(\n startBlockHeight,\n queryEndBlock,\n );\n try {\n const dictionary = await this.dictionaryService.getDictionary(\n startBlockHeight,\n queryEndBlock,\n scaledBatchSize,\n this.dictionaryQueryEntries,\n );\n\n if (startBlockHeight !== getStartBlockHeight()) {\n logger.debug(\n `Queue was reset for new DS, discarding dictionary query result`,\n );\n continue;\n }\n\n if (\n dictionary &&\n this.dictionaryValidation(dictionary, startBlockHeight)\n ) {\n let { batchBlocks } = dictionary;\n\n batchBlocks = batchBlocks\n .concat(moduloBlocks)\n .sort((a, b) => a - b);\n if (batchBlocks.length === 0) {\n // There we're no blocks in this query range, we can set a new height we're up to\n this.blockDispatcher.latestBufferedHeight = Math.min(\n queryEndBlock - 1,\n dictionary._metadata.lastProcessedHeight,\n );\n } else {\n const maxBlockSize = Math.min(\n batchBlocks.length,\n this.blockDispatcher.freeSize,\n );\n batchBlocks = batchBlocks.slice(0, maxBlockSize);\n this.blockDispatcher.enqueueBlocks(batchBlocks);\n }\n continue; // skip nextBlockRange() way\n }\n // else use this.nextBlockRange()\n } catch (e) {\n logger.debug(`Fetch dictionary stopped: ${e.message}`);\n this.eventEmitter.emit(IndexerEvent.SkipDictionary);\n }\n }\n const endHeight = this.nextEndBlockHeight(\n startBlockHeight,\n scaledBatchSize,\n );\n\n if (this.getModulos().length === handlers.length) {\n this.blockDispatcher.enqueueBlocks(\n this.getEnqueuedModuloBlocks(startBlockHeight),\n );\n } else {\n this.blockDispatcher.enqueueBlocks(\n range(startBlockHeight, endHeight + 1),\n );\n }\n }\n }\n\n private nextEndBlockHeight(\n startBlockHeight: number,\n scaledBatchSize: number,\n ): number {\n let endBlockHeight = startBlockHeight + scaledBatchSize - 1;\n\n if (endBlockHeight > this.latestFinalizedHeight) {\n endBlockHeight = this.latestFinalizedHeight;\n }\n return endBlockHeight;\n }\n\n private dictionaryValidation(\n { _metadata: metaData }: Dictionary,\n startBlockHeight: number,\n ): boolean {\n if (metaData.genesisHash !== this.api.getGenesisHash()) {\n logger.error(\n 'The dictionary that you have specified does not match the chain you are indexing, it will be ignored. Please update your project manifest to reference the correct dictionary',\n );\n this.useDictionary = false;\n this.eventEmitter.emit(IndexerEvent.UsingDictionary, {\n value: Number(this.useDictionary),\n });\n this.eventEmitter.emit(IndexerEvent.SkipDictionary);\n return false;\n }\n if (metaData.lastProcessedHeight < startBlockHeight) {\n logger.warn(\n `Dictionary indexed block is behind current indexing block height`,\n );\n this.eventEmitter.emit(IndexerEvent.SkipDictionary);\n return false;\n }\n return true;\n }\n\n async resetForNewDs(blockHeight: number): Promise<void> {\n await this.syncDynamicDatascourcesFromMeta();\n this.dynamicDsService.deleteTempDsRecords(blockHeight);\n this.updateDictionary();\n this.blockDispatcher.flushQueue(blockHeight);\n }\n}\n"]}
1
+ {"version":3,"file":"fetch.service.js","sourceRoot":"","sources":["../../src/indexer/fetch.service.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;;;;;;;;;;;;;AAEtC,2CAA2E;AAC3E,yDAAsD;AACtD,+CAA+D;AAC/D,4DAIgC;AAChC,gDAQ0B;AAO1B,mCAA+C;AAC/C,kEAA+E;AAC/E,+DAA0D;AAC1D,4CAAkE;AAElE,6DAAyD;AACzD,6DAAwD;AAExD,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,OAAO,CAAC,CAAC;AAClC,IAAI,mBAAmB,GAAG,IAAI,CAAC;AAC/B,MAAM,yBAAyB,GAAG,KAAK,CAAC;AACxC,MAAM,qBAAqB,GAAG,KAAK,CAAC;AACpC,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAE7B,SAAS,uBAAuB,CAC9B,MAAyB;IAEzB,MAAM,UAAU,GAAG,EAAE,CAAC;IACtB,IAAI,MAAM,CAAC,OAAO,EAAE;QAClB,UAAU,CAAC,IAAI,CAAC;YACd,KAAK,EAAE,SAAS;YAChB,KAAK,EAAE,MAAM,CAAC,OAAO,CAAC,WAAW,EAAE;SACpC,CAAC,CAAC;KACJ;IACD,IAAI,MAAM,CAAC,MAAM,EAAE;QACjB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;YAC1D,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YAC/B,IAAI,CAAC,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,WAAmB;QAClD,MAAM,IAAI,CAAC,+BAA+B,EAAE,CAAC;QAC7C,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACxB,IAAI,CAAC,eAAe,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;IAC/C,CAAC;CACF,CAAA;AAjQC;IAAC,IAAA,mBAAQ,EAAC,qBAAqB,CAAC;;;;mDAS/B;AAGK;IADL,IAAA,mBAAQ,EAAC,mBAAmB,GAAG,IAAI,CAAC;;;;yDAmBpC;AAGK;IADL,IAAA,mBAAQ,EAAC,mBAAmB,GAAG,IAAI,CAAC;;;;oDAuBpC;AA7LU,YAAY;IADxB,IAAA,mBAAU,GAAE;IAcR,WAAA,IAAA,eAAM,EAAC,kBAAkB,CAAC,CAAA;qCAHP,sBAAU;QACV,sBAAU;QACb,iCAAe,UAEL,sCAAiB;QAClB,qCAAgB;QACpB,6BAAa;QACR,4BAAiB;GAjBnC,YAAY,CAuYxB;AAvYY,oCAAY","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Inject, Injectable, OnApplicationShutdown } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport { Interval, SchedulerRegistry } from '@nestjs/schedule';\nimport {\n isCustomDs,\n EthereumHandlerKind,\n SubqlHandlerFilter,\n} from '@subql/common-ethereum';\nimport {\n ApiService,\n Dictionary,\n checkMemoryUsage,\n delay,\n getLogger,\n IndexerEvent,\n NodeConfig,\n} from '@subql/node-core';\nimport {\n DictionaryQueryEntry,\n ApiWrapper,\n EthereumLogFilter,\n EthereumTransactionFilter,\n} from '@subql/types-ethereum';\nimport { range, sortBy, uniqBy } from 'lodash';\nimport { SubqlProjectDs, SubqueryProject } from '../configure/SubqueryProject';\nimport { calcInterval } from '../ethereum/utils.ethereum';\nimport { eventToTopic, functionToSighash } from '../utils/string';\nimport { IBlockDispatcher } from './blockDispatcher';\nimport { DictionaryService } from './dictionary.service';\nimport { DynamicDsService } from './dynamic-ds.service';\n\nconst logger = getLogger('fetch');\nlet BLOCK_TIME_VARIANCE = 5000;\nconst DICTIONARY_MAX_QUERY_SIZE = 10000;\nconst CHECK_MEMORY_INTERVAL = 60000;\nconst MINIMUM_BATCH_SIZE = 5;\nconst INTERVAL_PERCENT = 0.9;\n\nfunction eventFilterToQueryEntry(\n filter: EthereumLogFilter,\n): DictionaryQueryEntry {\n const conditions = [];\n if (filter.address) {\n conditions.push({\n field: 'address',\n value: filter.address.toLowerCase(),\n });\n }\n if (filter.topics) {\n for (let i = 0; i < Math.min(filter.topics.length, 4); i++) {\n const topic = filter.topics[i];\n if (!topic) {\n continue;\n }\n const field = `topics${i}`;\n conditions.push({ field, value: eventToTopic(topic) });\n }\n }\n return {\n entity: 'evmLogs',\n conditions,\n };\n}\n\nfunction callFilterToQueryEntry(\n filter: EthereumTransactionFilter,\n): DictionaryQueryEntry {\n const conditions = [];\n if (filter.from) {\n conditions.push({\n field: 'from',\n value: filter.from.toLowerCase(),\n });\n }\n if (filter.to) {\n conditions.push({\n field: 'to',\n value: filter.to.toLowerCase(),\n });\n }\n if (filter.function) {\n conditions.push({\n field: 'func',\n value: functionToSighash(filter.function),\n });\n }\n return {\n entity: 'evmTransactions',\n conditions,\n };\n}\n\n@Injectable()\nexport class FetchService implements OnApplicationShutdown {\n private latestBestHeight: number;\n private latestFinalizedHeight: number;\n private isShutdown = false;\n private dictionaryQueryEntries?: DictionaryQueryEntry[];\n private batchSizeScale: number;\n private templateDynamicDatasouces: SubqlProjectDs[];\n private dictionaryGenesisMatches = true;\n\n constructor(\n private apiService: ApiService,\n private nodeConfig: NodeConfig,\n private project: SubqueryProject,\n @Inject('IBlockDispatcher') private blockDispatcher: IBlockDispatcher,\n private dictionaryService: DictionaryService,\n private dynamicDsService: DynamicDsService,\n private eventEmitter: EventEmitter2,\n private schedulerRegistry: SchedulerRegistry,\n ) {\n this.batchSizeScale = 1;\n }\n\n onApplicationShutdown(): void {\n this.isShutdown = true;\n }\n\n get api(): ApiWrapper {\n return this.apiService.api;\n }\n\n async syncDynamicDatascourcesFromMeta(): Promise<void> {\n this.templateDynamicDatasouces =\n await this.dynamicDsService.getDynamicDatasources();\n }\n\n buildDictionaryQueryEntries(startBlock: number): DictionaryQueryEntry[] {\n const queryEntries: DictionaryQueryEntry[] = [];\n\n // Only run the ds that is equal or less than startBlock\n // sort array from lowest ds.startBlock to highest\n const filteredDs = this.project.dataSources\n .concat(this.templateDynamicDatasouces)\n .filter((ds) => ds.startBlock <= startBlock)\n .sort((a, b) => a.startBlock - b.startBlock);\n\n for (const ds of filteredDs) {\n for (const handler of ds.mapping.handlers) {\n let filterList: SubqlHandlerFilter[];\n filterList = [handler.filter];\n filterList = filterList.filter((f) => f);\n if (!filterList.length) return [];\n switch (handler.kind) {\n case EthereumHandlerKind.Block:\n return [];\n case EthereumHandlerKind.Call: {\n for (const filter of filterList as EthereumTransactionFilter[]) {\n if (\n filter.from !== undefined ||\n filter.to !== undefined ||\n filter.function\n ) {\n queryEntries.push(callFilterToQueryEntry(filter));\n } else {\n return [];\n }\n }\n break;\n }\n case EthereumHandlerKind.Event: {\n for (const filter of filterList as EthereumLogFilter[]) {\n if (filter.address || filter.topics) {\n queryEntries.push(eventFilterToQueryEntry(filter));\n } else {\n return [];\n }\n }\n break;\n }\n default:\n }\n }\n }\n\n return uniqBy(\n queryEntries,\n (item) =>\n `${item.entity}|${JSON.stringify(\n sortBy(item.conditions, (c) => c.field),\n )}`,\n );\n }\n\n updateDictionary(): void {\n this.dictionaryService.buildDictionaryEntryMap<SubqlProjectDs>(\n this.project.dataSources.concat(this.templateDynamicDatasouces),\n this.buildDictionaryQueryEntries.bind(this),\n );\n }\n\n private get useDictionary(): boolean {\n return (\n !!this.project.network.dictionary &&\n this.dictionaryGenesisMatches &&\n !!this.dictionaryService.getDictionaryQueryEntries(\n this.blockDispatcher.latestBufferedHeight ??\n Math.min(...this.project.dataSources.map((ds) => ds.startBlock)),\n ).length\n );\n }\n\n async init(startHeight: number): Promise<void> {\n if (this.api) {\n const CHAIN_INTERVAL = calcInterval(this.api) * INTERVAL_PERCENT;\n\n BLOCK_TIME_VARIANCE = Math.min(BLOCK_TIME_VARIANCE, CHAIN_INTERVAL);\n\n this.schedulerRegistry.addInterval(\n 'getLatestBlockHead',\n setInterval(() => void this.getBestBlockHead(), BLOCK_TIME_VARIANCE),\n );\n }\n await this.syncDynamicDatascourcesFromMeta();\n this.updateDictionary();\n this.eventEmitter.emit(IndexerEvent.UsingDictionary, {\n value: Number(this.useDictionary),\n });\n await this.getFinalizedBlockHead();\n await this.getBestBlockHead();\n\n await this.blockDispatcher.init(this.resetForNewDs.bind(this));\n\n void this.startLoop(startHeight);\n }\n\n @Interval(CHECK_MEMORY_INTERVAL)\n checkBatchScale(): void {\n if (this.nodeConfig['scale-batch-size']) {\n const scale = checkMemoryUsage(this.batchSizeScale, this.nodeConfig);\n\n if (this.batchSizeScale !== scale) {\n this.batchSizeScale = scale;\n }\n }\n }\n\n @Interval(BLOCK_TIME_VARIANCE * 1000)\n async getFinalizedBlockHead(): Promise<void> {\n if (!this.api) {\n logger.debug(`Skip fetch finalized block until API is ready`);\n return;\n }\n try {\n const currentFinalizedHeight = await this.api.getFinalizedBlockHeight();\n if (this.latestFinalizedHeight !== currentFinalizedHeight) {\n this.latestFinalizedHeight = currentFinalizedHeight;\n if (!this.nodeConfig.unfinalizedBlocks) {\n this.eventEmitter.emit(IndexerEvent.BlockTarget, {\n height: this.latestFinalizedHeight,\n });\n }\n }\n } catch (e) {\n logger.warn(e, `Having a problem when get finalized block`);\n }\n }\n\n @Interval(BLOCK_TIME_VARIANCE * 1000)\n async getBestBlockHead(): Promise<void> {\n if (!this.api) {\n logger.debug(`Skip fetch best block until API is ready`);\n return;\n }\n try {\n const currentBestHeight = await this.api.getLastHeight();\n if (this.latestBestHeight !== currentBestHeight) {\n this.latestBestHeight = currentBestHeight;\n this.eventEmitter.emit(IndexerEvent.BlockBest, {\n height: this.latestBestHeight,\n });\n\n if (this.nodeConfig.unfinalizedBlocks) {\n this.eventEmitter.emit(IndexerEvent.BlockTarget, {\n height: this.latestBestHeight,\n });\n }\n }\n } catch (e) {\n logger.warn(e, `Having a problem when get best block`);\n }\n }\n\n private async startLoop(initBlockHeight: number): Promise<void> {\n await this.fillNextBlockBuffer(initBlockHeight);\n }\n\n getModulos(): number[] {\n const modulos: number[] = [];\n for (const ds of this.project.dataSources) {\n if (isCustomDs(ds)) {\n continue;\n }\n for (const handler of ds.mapping.handlers) {\n if (\n handler.kind === EthereumHandlerKind.Block &&\n handler.filter &&\n handler.filter.modulo\n ) {\n modulos.push(handler.filter.modulo);\n }\n }\n }\n return modulos;\n }\n\n getModuloBlocks(startHeight: number, endHeight: number): number[] {\n const modulos = this.getModulos();\n const moduloBlocks: number[] = [];\n for (let i = startHeight; i < endHeight; i++) {\n if (modulos.find((m) => i % m === 0)) {\n moduloBlocks.push(i);\n }\n }\n return moduloBlocks;\n }\n\n getEnqueuedModuloBlocks(startBlockHeight: number): number[] {\n return this.getModuloBlocks(\n startBlockHeight,\n this.nodeConfig.batchSize * Math.max(...this.getModulos()) +\n startBlockHeight,\n ).slice(0, this.nodeConfig.batchSize);\n }\n\n async fillNextBlockBuffer(initBlockHeight: number): Promise<void> {\n let startBlockHeight: number;\n let scaledBatchSize: number;\n const handlers = [].concat(\n ...this.project.dataSources.map((ds) => ds.mapping.handlers),\n );\n\n const getStartBlockHeight = (): number => {\n return this.blockDispatcher.latestBufferedHeight\n ? this.blockDispatcher.latestBufferedHeight + 1\n : initBlockHeight;\n };\n\n while (!this.isShutdown) {\n startBlockHeight = getStartBlockHeight();\n\n scaledBatchSize = Math.max(\n Math.round(this.batchSizeScale * this.nodeConfig.batchSize),\n Math.min(MINIMUM_BATCH_SIZE, this.nodeConfig.batchSize * 3),\n );\n const latestHeight = this.nodeConfig.unfinalizedBlocks\n ? this.latestBestHeight\n : this.latestFinalizedHeight;\n\n if (\n this.blockDispatcher.freeSize < scaledBatchSize ||\n startBlockHeight > latestHeight\n ) {\n await delay(1);\n continue;\n }\n\n if (this.useDictionary) {\n const queryEndBlock = startBlockHeight + DICTIONARY_MAX_QUERY_SIZE;\n const moduloBlocks = this.getModuloBlocks(\n startBlockHeight,\n queryEndBlock,\n );\n\n try {\n const dictionary =\n await this.dictionaryService.scopedDictionaryEntries(\n startBlockHeight,\n queryEndBlock,\n scaledBatchSize,\n );\n\n if (startBlockHeight !== getStartBlockHeight()) {\n logger.debug(\n `Queue was reset for new DS, discarding dictionary query result`,\n );\n continue;\n }\n\n if (\n dictionary &&\n this.dictionaryValidation(dictionary, startBlockHeight)\n ) {\n let { batchBlocks } = dictionary;\n\n batchBlocks = batchBlocks\n .concat(moduloBlocks)\n .sort((a, b) => a - b);\n if (batchBlocks.length === 0) {\n // There we're no blocks in this query range, we can set a new height we're up to\n this.blockDispatcher.latestBufferedHeight = Math.min(\n queryEndBlock - 1,\n dictionary._metadata.lastProcessedHeight,\n );\n } else {\n const maxBlockSize = Math.min(\n batchBlocks.length,\n this.blockDispatcher.freeSize,\n );\n batchBlocks = batchBlocks.slice(0, maxBlockSize);\n this.blockDispatcher.enqueueBlocks(batchBlocks);\n }\n continue; // skip nextBlockRange() way\n }\n // else use this.nextBlockRange()\n } catch (e) {\n logger.debug(`Fetch dictionary stopped: ${e.message}`);\n this.eventEmitter.emit(IndexerEvent.SkipDictionary);\n }\n }\n\n const endHeight = this.nextEndBlockHeight(\n startBlockHeight,\n scaledBatchSize,\n );\n\n if (handlers.length && this.getModulos().length === handlers.length) {\n this.blockDispatcher.enqueueBlocks(\n this.getEnqueuedModuloBlocks(startBlockHeight),\n );\n } else {\n this.blockDispatcher.enqueueBlocks(\n range(startBlockHeight, endHeight + 1),\n );\n }\n }\n }\n\n private nextEndBlockHeight(\n startBlockHeight: number,\n scaledBatchSize: number,\n ): number {\n let endBlockHeight = startBlockHeight + scaledBatchSize - 1;\n\n if (endBlockHeight > this.latestFinalizedHeight) {\n if (this.nodeConfig.unfinalizedBlocks) {\n if (endBlockHeight >= this.latestBestHeight) {\n endBlockHeight = this.latestBestHeight;\n }\n } else {\n endBlockHeight = this.latestFinalizedHeight;\n }\n }\n return endBlockHeight;\n }\n\n private dictionaryValidation(\n { _metadata: metaData }: Dictionary,\n startBlockHeight: number,\n ): boolean {\n if (metaData.genesisHash !== this.api.getGenesisHash()) {\n logger.error(\n 'The dictionary that you have specified does not match the chain you are indexing, it will be ignored. Please update your project manifest to reference the correct dictionary',\n );\n this.dictionaryGenesisMatches = false;\n this.eventEmitter.emit(IndexerEvent.UsingDictionary, {\n value: Number(this.useDictionary),\n });\n this.eventEmitter.emit(IndexerEvent.SkipDictionary);\n return false;\n }\n if (metaData.lastProcessedHeight < startBlockHeight) {\n logger.warn(\n `Dictionary indexed block is behind current indexing block height`,\n );\n this.eventEmitter.emit(IndexerEvent.SkipDictionary);\n return false;\n }\n return true;\n }\n\n async resetForNewDs(blockHeight: number): Promise<void> {\n await this.syncDynamicDatascourcesFromMeta();\n this.dynamicDsService.deleteTempDsRecords(blockHeight);\n this.updateDictionary();\n this.blockDispatcher.flushQueue(blockHeight);\n }\n\n async resetForIncorrectBestBlock(blockHeight: number): Promise<void> {\n await this.syncDynamicDatascourcesFromMeta();\n this.updateDictionary();\n this.blockDispatcher.flushQueue(blockHeight);\n }\n}\n"]}
@@ -23,6 +23,7 @@ export declare class IndexerManager {
23
23
  indexBlock(blockContent: EthereumBlockWrapper): Promise<{
24
24
  dynamicDsCreated: boolean;
25
25
  operationHash: Uint8Array;
26
+ reindexBlockHeight: null;
26
27
  }>;
27
28
  start(): Promise<void>;
28
29
  private filterDataSources;
@@ -74,7 +74,7 @@ let IndexerManager = class IndexerManager {
74
74
  { key: 'lastProcessedTimestamp', value: Date.now() },
75
75
  ], { transaction: tx });
76
76
  // Db Metadata increase BlockCount, in memory ref to block-dispatcher _processedBlockCount
77
- await this.storeService.incrementBlockCount(tx);
77
+ await this.storeService.incrementJsonbCount('processedBlockCount', tx);
78
78
  // Need calculate operationHash to ensure correct offset insert all time
79
79
  operationHash = this.storeService.getOperationMerkleRoot();
80
80
  if (this.nodeConfig.proofOfIndex) {
@@ -96,6 +96,7 @@ let IndexerManager = class IndexerManager {
96
96
  return {
97
97
  dynamicDsCreated,
98
98
  operationHash,
99
+ reindexBlockHeight: null,
99
100
  };
100
101
  }
101
102
  async start() {
@@ -1 +1 @@
1
- {"version":3,"file":"indexer.manager.js","sourceRoot":"","sources":["../../src/indexer/indexer.manager.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;;;;;;;;;;AAEtC,2CAA4C;AAC5C,yCAAiD;AACjD,4DAUgC;AAChC,gDAU0B;AAQ1B,yCAAsC;AACtC,kEAA+E;AAE/E,+DAAkE;AAClE,oCAAwC;AACxC,iEAGgC;AAChC,6DAAwD;AACxD,uDAAmD;AACnD,uDAAmD;AAEnD,MAAM,gBAAgB,GAAG,IAAA,eAAQ,EAAC,MAAM,CAAC,CAAC;AAE1C,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,SAAS,CAAC,CAAC;AAG7B,IAAM,cAAc,GAApB,MAAM,cAAc;IAIzB,YACU,YAA0B,EAC1B,UAAsB,EACtB,UAAsB,EACtB,SAAoB,EACpB,OAAwB,EACxB,UAAsB,EACtB,cAA8B,EAC9B,gBAAkC,EAClC,kBAAsC,EACtC,cAA8B;QAT9B,iBAAY,GAAZ,YAAY,CAAc;QAC1B,eAAU,GAAV,UAAU,CAAY;QACtB,eAAU,GAAV,UAAU,CAAY;QACtB,cAAS,GAAT,SAAS,CAAW;QACpB,YAAO,GAAP,OAAO,CAAiB;QACxB,eAAU,GAAV,UAAU,CAAY;QACtB,mBAAc,GAAd,cAAc,CAAgB;QAC9B,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,uBAAkB,GAAlB,kBAAkB,CAAoB;QACtC,mBAAc,GAAd,cAAc,CAAgB;QAEtC,MAAM,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;QAErC,IAA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E;qCAMa,wBAAY;QACd,sBAAU;QACV,sBAAU;QACX,qBAAS;QACX,iCAAe;QACZ,sBAAU;QACN,gCAAc;QACZ,qCAAgB;QACd,yCAAkB;QACtB,gCAAc;GAd7B,cAAc,CA0U1B;AA1UY,wCAAc;AAkV3B,MAAM,gBAAgB,GAAG;IACvB,CAAC,qCAAmB,CAAC,KAAK,CAAC,EAAE,yCAAuB;IACpD,CAAC,qCAAmB,CAAC,KAAK,CAAC,EAAE,yCAAuB;IACpD,CAAC,qCAAmB,CAAC,IAAI,CAAC,EAAE,wCAAsB;CACnD,CAAC;AAEF,MAAM,aAAa,GAAG;IACpB,CAAC,qCAAmB,CAAC,KAAK,CAAC,EAAE,qCAAoB,CAAC,qBAAqB;IACvE,CAAC,qCAAmB,CAAC,KAAK,CAAC,EAAE,qCAAoB,CAAC,mBAAmB;IACrE,CAAC,qCAAmB,CAAC,IAAI,CAAC,EAAE,qCAAoB,CAAC,2BAA2B;CAC7E,CAAC;AAEF,MAAM,aAAa,GAAG;IACpB,CAAC,qCAAmB,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,IAAmB,EAAE,EAAE,CAAC,IAAI;IAChE,CAAC,qCAAmB,CAAC,KAAK,CAAC,EAAE,CAAC,GAAgB,EAAE,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC;IACzE,CAAC,qCAAmB,CAAC,IAAI,CAAC,EAAE,CAAC,GAAgB,EAAE,EAAE,CAC/C,GAAG,CAAC,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC;CACjC,CAAC","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Injectable } from '@nestjs/common';\nimport { hexToU8a, u8aEq } from '@polkadot/util';\nimport {\n isBlockHandlerProcessor,\n isCallHandlerProcessor,\n isEventHandlerProcessor,\n isCustomDs,\n isRuntimeDs,\n SubqlEthereumCustomDataSource,\n SubqlCustomHandler,\n EthereumHandlerKind,\n EthereumRuntimeHandlerInputMap,\n} from '@subql/common-ethereum';\nimport {\n ApiService,\n PoiBlock,\n StoreService,\n PoiService,\n NodeConfig,\n getLogger,\n profiler,\n profilerWrap,\n IndexerSandbox,\n} from '@subql/node-core';\nimport {\n EthereumTransaction,\n EthereumLog,\n SubqlRuntimeHandler,\n EthereumBlockWrapper,\n EthereumBlock,\n} from '@subql/types-ethereum';\nimport { Sequelize } from 'sequelize';\nimport { SubqlProjectDs, SubqueryProject } from '../configure/SubqueryProject';\nimport { EthereumApi } from '../ethereum';\nimport { EthereumBlockWrapped } from '../ethereum/block.ethereum';\nimport { yargsOptions } from '../yargs';\nimport {\n asSecondLayerHandlerProcessor_1_0_0,\n DsProcessorService,\n} from './ds-processor.service';\nimport { DynamicDsService } from './dynamic-ds.service';\nimport { ProjectService } from './project.service';\nimport { SandboxService } from './sandbox.service';\n\nconst NULL_MERKEL_ROOT = hexToU8a('0x00');\n\nconst logger = getLogger('indexer');\n\n@Injectable()\nexport class IndexerManager {\n private api: EthereumApi;\n private filteredDataSources: SubqlProjectDs[];\n\n constructor(\n private storeService: StoreService,\n private apiService: ApiService,\n private poiService: PoiService,\n private sequelize: Sequelize,\n private project: SubqueryProject,\n private nodeConfig: NodeConfig,\n private sandboxService: SandboxService,\n private dynamicDsService: DynamicDsService,\n private dsProcessorService: DsProcessorService,\n private projectService: ProjectService,\n ) {\n logger.info('indexer manager start');\n\n this.api = this.apiService.api;\n }\n\n @profiler(yargsOptions.argv.profiler)\n async indexBlock(\n blockContent: EthereumBlockWrapper,\n ): Promise<{ dynamicDsCreated: boolean; operationHash: Uint8Array }> {\n const { blockHeight } = blockContent;\n let dynamicDsCreated = false;\n const tx = await this.sequelize.transaction();\n this.storeService.setTransaction(tx);\n this.storeService.setBlockHeight(blockHeight);\n\n let operationHash = NULL_MERKEL_ROOT;\n let poiBlockHash: Uint8Array;\n\n try {\n this.filteredDataSources = this.filterDataSources(blockHeight);\n\n const datasources = this.filteredDataSources.concat(\n ...(await this.dynamicDsService.getDynamicDatasources()),\n );\n\n await this.indexBlockData(\n blockContent,\n datasources,\n // eslint-disable-next-line @typescript-eslint/require-await\n async (ds: SubqlProjectDs) => {\n const vm = this.sandboxService.getDsProcessorWrapper(\n ds,\n this.api,\n blockContent,\n );\n\n // Inject function to create ds into vm\n vm.freeze(\n async (templateName: string, args?: Record<string, unknown>) => {\n const newDs = await this.dynamicDsService.createDynamicDatasource(\n {\n templateName,\n args,\n startBlock: blockHeight,\n },\n tx,\n );\n // Push the newly created dynamic ds to be processed this block on any future extrinsics/events\n datasources.push(newDs);\n dynamicDsCreated = true;\n },\n 'createDynamicDatasource',\n );\n\n return vm;\n },\n );\n\n await this.storeService.setMetadataBatch(\n [\n { key: 'lastProcessedHeight', value: blockHeight },\n { key: 'lastProcessedTimestamp', value: Date.now() },\n ],\n { transaction: tx },\n );\n // Db Metadata increase BlockCount, in memory ref to block-dispatcher _processedBlockCount\n await this.storeService.incrementBlockCount(tx);\n\n // Need calculate operationHash to ensure correct offset insert all time\n operationHash = this.storeService.getOperationMerkleRoot();\n if (this.nodeConfig.proofOfIndex) {\n //check if operation is null, then poi will not be inserted\n if (!u8aEq(operationHash, NULL_MERKEL_ROOT)) {\n const poiBlock = PoiBlock.create(\n blockHeight,\n blockContent.block.hash,\n operationHash,\n await this.poiService.getLatestPoiBlockHash(),\n this.project.id,\n );\n poiBlockHash = poiBlock.hash;\n await this.storeService.setPoi(poiBlock, { transaction: tx });\n this.poiService.setLatestPoiBlockHash(poiBlockHash);\n await this.storeService.setMetadataBatch(\n [{ key: 'lastPoiHeight', value: blockHeight }],\n { transaction: tx },\n );\n }\n }\n } catch (e) {\n await tx.rollback();\n throw e;\n }\n\n await tx.commit();\n\n return {\n dynamicDsCreated,\n operationHash,\n };\n }\n\n async start(): Promise<void> {\n await this.projectService.init();\n logger.info('indexer manager started');\n }\n\n private filterDataSources(nextProcessingHeight: number): SubqlProjectDs[] {\n const filteredDs = this.projectService.dataSources.filter(\n (ds) => ds.startBlock <= nextProcessingHeight,\n );\n\n if (filteredDs.length === 0) {\n logger.error(\n `Your start block is greater than the current indexed block height in your database. Either change your startBlock (project.yaml) to <= ${nextProcessingHeight}\n or delete your database and start again from the currently specified startBlock`,\n );\n process.exit(1);\n }\n // perform filter for custom ds\n if (!filteredDs.length) {\n logger.error(`Did not find any datasources with associated processor`);\n process.exit(1);\n }\n return filteredDs;\n }\n\n private async indexBlockData(\n { block, logs, transactions }: EthereumBlockWrapper,\n dataSources: SubqlProjectDs[],\n getVM: (d: SubqlProjectDs) => Promise<IndexerSandbox>,\n ): Promise<void> {\n await this.indexBlockContent(block, dataSources, getVM);\n\n for (const log of logs) {\n await this.indexEvent(log, dataSources, getVM);\n }\n\n for (const tx of transactions) {\n await this.indexExtrinsic(tx, dataSources, getVM);\n }\n }\n\n private async indexBlockContent(\n block: EthereumBlock,\n dataSources: SubqlProjectDs[],\n getVM: (d: SubqlProjectDs) => Promise<IndexerSandbox>,\n ): Promise<void> {\n for (const ds of dataSources) {\n await this.indexData(EthereumHandlerKind.Block, block, ds, getVM);\n }\n }\n\n private async indexExtrinsic(\n tx: EthereumTransaction,\n dataSources: SubqlProjectDs[],\n getVM: (d: SubqlProjectDs) => Promise<IndexerSandbox>,\n ): Promise<void> {\n for (const ds of dataSources) {\n await this.indexData(EthereumHandlerKind.Call, tx, ds, getVM);\n }\n }\n\n private async indexEvent(\n log: EthereumLog,\n dataSources: SubqlProjectDs[],\n getVM: (d: SubqlProjectDs) => Promise<IndexerSandbox>,\n ): Promise<void> {\n for (const ds of dataSources) {\n await this.indexData(EthereumHandlerKind.Event, log, ds, getVM);\n }\n }\n\n private async indexData<K extends EthereumHandlerKind>(\n kind: K,\n data: EthereumRuntimeHandlerInputMap[K],\n ds: SubqlProjectDs,\n getVM: (ds: SubqlProjectDs) => Promise<IndexerSandbox>,\n ): Promise<void> {\n let vm: IndexerSandbox;\n if (isRuntimeDs(ds)) {\n const handlers = (ds.mapping.handlers as SubqlRuntimeHandler[]).filter(\n (h) =>\n h.kind === kind &&\n FilterTypeMap[kind](data as any, h.filter as any, ds.options.address),\n );\n\n if (!handlers.length) {\n return;\n }\n const parsedData = await DataAbiParser[kind](this.api)(data, ds);\n\n for (const handler of handlers) {\n vm = vm ?? (await getVM(ds));\n this.nodeConfig.profiler\n ? await profilerWrap(\n vm.securedExec.bind(vm),\n 'handlerPerformance',\n handler.handler,\n )(handler.handler, [parsedData])\n : await vm.securedExec(handler.handler, [parsedData]);\n }\n } else if (isCustomDs(ds)) {\n const handlers = this.filterCustomDsHandlers<K>(\n ds,\n data,\n ProcessorTypeMap[kind],\n (data, baseFilter) => {\n switch (kind) {\n case EthereumHandlerKind.Block:\n return EthereumBlockWrapped.filterBlocksProcessor(\n data as EthereumBlock,\n baseFilter,\n );\n case EthereumHandlerKind.Call:\n return EthereumBlockWrapped.filterTransactionsProcessor(\n data as EthereumTransaction,\n baseFilter,\n );\n case EthereumHandlerKind.Event:\n return EthereumBlockWrapped.filterLogsProcessor(\n data as EthereumLog,\n baseFilter,\n );\n default:\n throw new Error('Unsupported handler kind');\n }\n },\n );\n\n if (!handlers.length) {\n return;\n }\n\n const parsedData = await DataAbiParser[kind](this.api)(data, ds);\n\n for (const handler of handlers) {\n vm = vm ?? (await getVM(ds));\n await this.transformAndExecuteCustomDs(ds, vm, handler, parsedData);\n }\n }\n }\n\n private filterCustomDsHandlers<K extends EthereumHandlerKind>(\n ds: SubqlEthereumCustomDataSource<string, any>,\n data: EthereumRuntimeHandlerInputMap[K],\n baseHandlerCheck: ProcessorTypeMap[K],\n baseFilter: (\n data: EthereumRuntimeHandlerInputMap[K],\n baseFilter: any,\n ) => boolean,\n ): SubqlCustomHandler[] {\n const plugin = this.dsProcessorService.getDsProcessor(ds);\n\n return ds.mapping.handlers\n .filter((handler) => {\n const processor = plugin.handlerProcessors[handler.kind];\n if (baseHandlerCheck(processor)) {\n processor.baseFilter;\n\n return baseFilter(data, processor.baseFilter);\n }\n return false;\n })\n .filter((handler) => {\n const processor = asSecondLayerHandlerProcessor_1_0_0(\n plugin.handlerProcessors[handler.kind],\n );\n\n try {\n return processor.filterProcessor({\n filter: handler.filter,\n input: data,\n ds,\n });\n } catch (e) {\n logger.error(e, 'Failed to run ds processer filter.');\n throw e;\n }\n });\n }\n\n private async transformAndExecuteCustomDs<K extends EthereumHandlerKind>(\n ds: SubqlEthereumCustomDataSource<string, any>,\n vm: IndexerSandbox,\n handler: SubqlCustomHandler,\n data: EthereumRuntimeHandlerInputMap[K],\n ): Promise<void> {\n const plugin = this.dsProcessorService.getDsProcessor(ds);\n const assets = await this.dsProcessorService.getAssets(ds);\n\n const processor = asSecondLayerHandlerProcessor_1_0_0(\n plugin.handlerProcessors[handler.kind],\n );\n\n const transformedData = await processor\n .transformer({\n input: data,\n ds,\n api: this.api,\n filter: handler.filter,\n assets,\n })\n .catch((e) => {\n logger.error(e, 'Failed to transform data with ds processor.');\n throw e;\n });\n\n // We can not run this in parallel. the transformed data items may be dependent on one another.\n // An example of this is with Acala EVM packing multiple EVM logs into a single Substrate event\n for (const _data of transformedData) {\n await vm.securedExec(handler.handler, [_data]);\n }\n }\n}\n\ntype ProcessorTypeMap = {\n [EthereumHandlerKind.Block]: typeof isBlockHandlerProcessor;\n [EthereumHandlerKind.Event]: typeof isEventHandlerProcessor;\n [EthereumHandlerKind.Call]: typeof isCallHandlerProcessor;\n};\n\nconst ProcessorTypeMap = {\n [EthereumHandlerKind.Block]: isBlockHandlerProcessor,\n [EthereumHandlerKind.Event]: isEventHandlerProcessor,\n [EthereumHandlerKind.Call]: isCallHandlerProcessor,\n};\n\nconst FilterTypeMap = {\n [EthereumHandlerKind.Block]: EthereumBlockWrapped.filterBlocksProcessor,\n [EthereumHandlerKind.Event]: EthereumBlockWrapped.filterLogsProcessor,\n [EthereumHandlerKind.Call]: EthereumBlockWrapped.filterTransactionsProcessor,\n};\n\nconst DataAbiParser = {\n [EthereumHandlerKind.Block]: () => (data: EthereumBlock) => data,\n [EthereumHandlerKind.Event]: (api: EthereumApi) => api.parseLog.bind(api),\n [EthereumHandlerKind.Call]: (api: EthereumApi) =>\n api.parseTransaction.bind(api),\n};\n"]}
1
+ {"version":3,"file":"indexer.manager.js","sourceRoot":"","sources":["../../src/indexer/indexer.manager.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;;;;;;;;;;AAEtC,2CAA4C;AAC5C,yCAAiD;AACjD,4DAUgC;AAChC,gDAU0B;AAQ1B,yCAAsC;AACtC,kEAA+E;AAE/E,+DAAkE;AAClE,oCAAwC;AACxC,iEAGgC;AAChC,6DAAwD;AACxD,uDAAmD;AACnD,uDAAmD;AAEnD,MAAM,gBAAgB,GAAG,IAAA,eAAQ,EAAC,MAAM,CAAC,CAAC;AAE1C,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,SAAS,CAAC,CAAC;AAG7B,IAAM,cAAc,GAApB,MAAM,cAAc;IAIzB,YACU,YAA0B,EAC1B,UAAsB,EACtB,UAAsB,EACtB,SAAoB,EACpB,OAAwB,EACxB,UAAsB,EACtB,cAA8B,EAC9B,gBAAkC,EAClC,kBAAsC,EACtC,cAA8B;QAT9B,iBAAY,GAAZ,YAAY,CAAc;QAC1B,eAAU,GAAV,UAAU,CAAY;QACtB,eAAU,GAAV,UAAU,CAAY;QACtB,cAAS,GAAT,SAAS,CAAW;QACpB,YAAO,GAAP,OAAO,CAAiB;QACxB,eAAU,GAAV,UAAU,CAAY;QACtB,mBAAc,GAAd,cAAc,CAAgB;QAC9B,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,uBAAkB,GAAlB,kBAAkB,CAAoB;QACtC,mBAAc,GAAd,cAAc,CAAgB;QAEtC,MAAM,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;QAErC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;IACjC,CAAC;IAGK,AAAN,KAAK,CAAC,UAAU,CAAC,YAAkC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QACZ,sBAAU;QACN,gCAAc;QACZ,qCAAgB;QACd,yCAAkB;QACtB,gCAAc;GAd7B,cAAc,CA6U1B;AA7UY,wCAAc;AAqV3B,MAAM,gBAAgB,GAAG;IACvB,CAAC,qCAAmB,CAAC,KAAK,CAAC,EAAE,yCAAuB;IACpD,CAAC,qCAAmB,CAAC,KAAK,CAAC,EAAE,yCAAuB;IACpD,CAAC,qCAAmB,CAAC,IAAI,CAAC,EAAE,wCAAsB;CACnD,CAAC;AAEF,MAAM,aAAa,GAAG;IACpB,CAAC,qCAAmB,CAAC,KAAK,CAAC,EAAE,qCAAoB,CAAC,qBAAqB;IACvE,CAAC,qCAAmB,CAAC,KAAK,CAAC,EAAE,qCAAoB,CAAC,mBAAmB;IACrE,CAAC,qCAAmB,CAAC,IAAI,CAAC,EAAE,qCAAoB,CAAC,2BAA2B;CAC7E,CAAC;AAEF,MAAM,aAAa,GAAG;IACpB,CAAC,qCAAmB,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,IAAmB,EAAE,EAAE,CAAC,IAAI;IAChE,CAAC,qCAAmB,CAAC,KAAK,CAAC,EAAE,CAAC,GAAgB,EAAE,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC;IACzE,CAAC,qCAAmB,CAAC,IAAI,CAAC,EAAE,CAAC,GAAgB,EAAE,EAAE,CAC/C,GAAG,CAAC,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC;CACjC,CAAC","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Injectable } from '@nestjs/common';\nimport { hexToU8a, u8aEq } from '@polkadot/util';\nimport {\n isBlockHandlerProcessor,\n isCallHandlerProcessor,\n isEventHandlerProcessor,\n isCustomDs,\n isRuntimeDs,\n SubqlEthereumCustomDataSource,\n SubqlCustomHandler,\n EthereumHandlerKind,\n EthereumRuntimeHandlerInputMap,\n} from '@subql/common-ethereum';\nimport {\n ApiService,\n PoiBlock,\n StoreService,\n PoiService,\n NodeConfig,\n getLogger,\n profiler,\n profilerWrap,\n IndexerSandbox,\n} from '@subql/node-core';\nimport {\n EthereumTransaction,\n EthereumLog,\n SubqlRuntimeHandler,\n EthereumBlockWrapper,\n EthereumBlock,\n} from '@subql/types-ethereum';\nimport { Sequelize } from 'sequelize';\nimport { SubqlProjectDs, SubqueryProject } from '../configure/SubqueryProject';\nimport { EthereumApi } from '../ethereum';\nimport { EthereumBlockWrapped } from '../ethereum/block.ethereum';\nimport { yargsOptions } from '../yargs';\nimport {\n asSecondLayerHandlerProcessor_1_0_0,\n DsProcessorService,\n} from './ds-processor.service';\nimport { DynamicDsService } from './dynamic-ds.service';\nimport { ProjectService } from './project.service';\nimport { SandboxService } from './sandbox.service';\n\nconst NULL_MERKEL_ROOT = hexToU8a('0x00');\n\nconst logger = getLogger('indexer');\n\n@Injectable()\nexport class IndexerManager {\n private api: EthereumApi;\n private filteredDataSources: SubqlProjectDs[];\n\n constructor(\n private storeService: StoreService,\n private apiService: ApiService,\n private poiService: PoiService,\n private sequelize: Sequelize,\n private project: SubqueryProject,\n private nodeConfig: NodeConfig,\n private sandboxService: SandboxService,\n private dynamicDsService: DynamicDsService,\n private dsProcessorService: DsProcessorService,\n private projectService: ProjectService,\n ) {\n logger.info('indexer manager start');\n\n this.api = this.apiService.api;\n }\n\n @profiler(yargsOptions.argv.profiler)\n async indexBlock(blockContent: EthereumBlockWrapper): Promise<{\n dynamicDsCreated: boolean;\n operationHash: Uint8Array;\n reindexBlockHeight: null;\n }> {\n const { blockHeight } = blockContent;\n let dynamicDsCreated = false;\n const tx = await this.sequelize.transaction();\n this.storeService.setTransaction(tx);\n this.storeService.setBlockHeight(blockHeight);\n\n let operationHash = NULL_MERKEL_ROOT;\n let poiBlockHash: Uint8Array;\n\n try {\n this.filteredDataSources = this.filterDataSources(blockHeight);\n\n const datasources = this.filteredDataSources.concat(\n ...(await this.dynamicDsService.getDynamicDatasources()),\n );\n\n await this.indexBlockData(\n blockContent,\n datasources,\n // eslint-disable-next-line @typescript-eslint/require-await\n async (ds: SubqlProjectDs) => {\n const vm = this.sandboxService.getDsProcessorWrapper(\n ds,\n this.api,\n blockContent,\n );\n\n // Inject function to create ds into vm\n vm.freeze(\n async (templateName: string, args?: Record<string, unknown>) => {\n const newDs = await this.dynamicDsService.createDynamicDatasource(\n {\n templateName,\n args,\n startBlock: blockHeight,\n },\n tx,\n );\n // Push the newly created dynamic ds to be processed this block on any future extrinsics/events\n datasources.push(newDs);\n dynamicDsCreated = true;\n },\n 'createDynamicDatasource',\n );\n\n return vm;\n },\n );\n\n await this.storeService.setMetadataBatch(\n [\n { key: 'lastProcessedHeight', value: blockHeight },\n { key: 'lastProcessedTimestamp', value: Date.now() },\n ],\n { transaction: tx },\n );\n // Db Metadata increase BlockCount, in memory ref to block-dispatcher _processedBlockCount\n await this.storeService.incrementJsonbCount('processedBlockCount', tx);\n\n // Need calculate operationHash to ensure correct offset insert all time\n operationHash = this.storeService.getOperationMerkleRoot();\n if (this.nodeConfig.proofOfIndex) {\n //check if operation is null, then poi will not be inserted\n if (!u8aEq(operationHash, NULL_MERKEL_ROOT)) {\n const poiBlock = PoiBlock.create(\n blockHeight,\n blockContent.block.hash,\n operationHash,\n await this.poiService.getLatestPoiBlockHash(),\n this.project.id,\n );\n poiBlockHash = poiBlock.hash;\n await this.storeService.setPoi(poiBlock, { transaction: tx });\n this.poiService.setLatestPoiBlockHash(poiBlockHash);\n await this.storeService.setMetadataBatch(\n [{ key: 'lastPoiHeight', value: blockHeight }],\n { transaction: tx },\n );\n }\n }\n } catch (e) {\n await tx.rollback();\n throw e;\n }\n\n await tx.commit();\n\n return {\n dynamicDsCreated,\n operationHash,\n reindexBlockHeight: null,\n };\n }\n\n async start(): Promise<void> {\n await this.projectService.init();\n logger.info('indexer manager started');\n }\n\n private filterDataSources(nextProcessingHeight: number): SubqlProjectDs[] {\n const filteredDs = this.projectService.dataSources.filter(\n (ds) => ds.startBlock <= nextProcessingHeight,\n );\n\n if (filteredDs.length === 0) {\n logger.error(\n `Your start block is greater than the current indexed block height in your database. Either change your startBlock (project.yaml) to <= ${nextProcessingHeight}\n or delete your database and start again from the currently specified startBlock`,\n );\n process.exit(1);\n }\n // perform filter for custom ds\n if (!filteredDs.length) {\n logger.error(`Did not find any datasources with associated processor`);\n process.exit(1);\n }\n return filteredDs;\n }\n\n private async indexBlockData(\n { block, logs, transactions }: EthereumBlockWrapper,\n dataSources: SubqlProjectDs[],\n getVM: (d: SubqlProjectDs) => Promise<IndexerSandbox>,\n ): Promise<void> {\n await this.indexBlockContent(block, dataSources, getVM);\n\n for (const log of logs) {\n await this.indexEvent(log, dataSources, getVM);\n }\n\n for (const tx of transactions) {\n await this.indexExtrinsic(tx, dataSources, getVM);\n }\n }\n\n private async indexBlockContent(\n block: EthereumBlock,\n dataSources: SubqlProjectDs[],\n getVM: (d: SubqlProjectDs) => Promise<IndexerSandbox>,\n ): Promise<void> {\n for (const ds of dataSources) {\n await this.indexData(EthereumHandlerKind.Block, block, ds, getVM);\n }\n }\n\n private async indexExtrinsic(\n tx: EthereumTransaction,\n dataSources: SubqlProjectDs[],\n getVM: (d: SubqlProjectDs) => Promise<IndexerSandbox>,\n ): Promise<void> {\n for (const ds of dataSources) {\n await this.indexData(EthereumHandlerKind.Call, tx, ds, getVM);\n }\n }\n\n private async indexEvent(\n log: EthereumLog,\n dataSources: SubqlProjectDs[],\n getVM: (d: SubqlProjectDs) => Promise<IndexerSandbox>,\n ): Promise<void> {\n for (const ds of dataSources) {\n await this.indexData(EthereumHandlerKind.Event, log, ds, getVM);\n }\n }\n\n private async indexData<K extends EthereumHandlerKind>(\n kind: K,\n data: EthereumRuntimeHandlerInputMap[K],\n ds: SubqlProjectDs,\n getVM: (ds: SubqlProjectDs) => Promise<IndexerSandbox>,\n ): Promise<void> {\n let vm: IndexerSandbox;\n if (isRuntimeDs(ds)) {\n const handlers = (ds.mapping.handlers as SubqlRuntimeHandler[]).filter(\n (h) =>\n h.kind === kind &&\n FilterTypeMap[kind](data as any, h.filter as any, ds.options.address),\n );\n\n if (!handlers.length) {\n return;\n }\n const parsedData = await DataAbiParser[kind](this.api)(data, ds);\n\n for (const handler of handlers) {\n vm = vm ?? (await getVM(ds));\n this.nodeConfig.profiler\n ? await profilerWrap(\n vm.securedExec.bind(vm),\n 'handlerPerformance',\n handler.handler,\n )(handler.handler, [parsedData])\n : await vm.securedExec(handler.handler, [parsedData]);\n }\n } else if (isCustomDs(ds)) {\n const handlers = this.filterCustomDsHandlers<K>(\n ds,\n data,\n ProcessorTypeMap[kind],\n (data, baseFilter) => {\n switch (kind) {\n case EthereumHandlerKind.Block:\n return EthereumBlockWrapped.filterBlocksProcessor(\n data as EthereumBlock,\n baseFilter,\n );\n case EthereumHandlerKind.Call:\n return EthereumBlockWrapped.filterTransactionsProcessor(\n data as EthereumTransaction,\n baseFilter,\n );\n case EthereumHandlerKind.Event:\n return EthereumBlockWrapped.filterLogsProcessor(\n data as EthereumLog,\n baseFilter,\n );\n default:\n throw new Error('Unsupported handler kind');\n }\n },\n );\n\n if (!handlers.length) {\n return;\n }\n\n const parsedData = await DataAbiParser[kind](this.api)(data, ds);\n\n for (const handler of handlers) {\n vm = vm ?? (await getVM(ds));\n await this.transformAndExecuteCustomDs(ds, vm, handler, parsedData);\n }\n }\n }\n\n private filterCustomDsHandlers<K extends EthereumHandlerKind>(\n ds: SubqlEthereumCustomDataSource<string, any>,\n data: EthereumRuntimeHandlerInputMap[K],\n baseHandlerCheck: ProcessorTypeMap[K],\n baseFilter: (\n data: EthereumRuntimeHandlerInputMap[K],\n baseFilter: any,\n ) => boolean,\n ): SubqlCustomHandler[] {\n const plugin = this.dsProcessorService.getDsProcessor(ds);\n\n return ds.mapping.handlers\n .filter((handler) => {\n const processor = plugin.handlerProcessors[handler.kind];\n if (baseHandlerCheck(processor)) {\n processor.baseFilter;\n\n return baseFilter(data, processor.baseFilter);\n }\n return false;\n })\n .filter((handler) => {\n const processor = asSecondLayerHandlerProcessor_1_0_0(\n plugin.handlerProcessors[handler.kind],\n );\n\n try {\n return processor.filterProcessor({\n filter: handler.filter,\n input: data,\n ds,\n });\n } catch (e) {\n logger.error(e, 'Failed to run ds processer filter.');\n throw e;\n }\n });\n }\n\n private async transformAndExecuteCustomDs<K extends EthereumHandlerKind>(\n ds: SubqlEthereumCustomDataSource<string, any>,\n vm: IndexerSandbox,\n handler: SubqlCustomHandler,\n data: EthereumRuntimeHandlerInputMap[K],\n ): Promise<void> {\n const plugin = this.dsProcessorService.getDsProcessor(ds);\n const assets = await this.dsProcessorService.getAssets(ds);\n\n const processor = asSecondLayerHandlerProcessor_1_0_0(\n plugin.handlerProcessors[handler.kind],\n );\n\n const transformedData = await processor\n .transformer({\n input: data,\n ds,\n api: this.api,\n filter: handler.filter,\n assets,\n })\n .catch((e) => {\n logger.error(e, 'Failed to transform data with ds processor.');\n throw e;\n });\n\n // We can not run this in parallel. the transformed data items may be dependent on one another.\n // An example of this is with Acala EVM packing multiple EVM logs into a single Substrate event\n for (const _data of transformedData) {\n await vm.securedExec(handler.handler, [_data]);\n }\n }\n}\n\ntype ProcessorTypeMap = {\n [EthereumHandlerKind.Block]: typeof isBlockHandlerProcessor;\n [EthereumHandlerKind.Event]: typeof isEventHandlerProcessor;\n [EthereumHandlerKind.Call]: typeof isCallHandlerProcessor;\n};\n\nconst ProcessorTypeMap = {\n [EthereumHandlerKind.Block]: isBlockHandlerProcessor,\n [EthereumHandlerKind.Event]: isEventHandlerProcessor,\n [EthereumHandlerKind.Call]: isCallHandlerProcessor,\n};\n\nconst FilterTypeMap = {\n [EthereumHandlerKind.Block]: EthereumBlockWrapped.filterBlocksProcessor,\n [EthereumHandlerKind.Event]: EthereumBlockWrapped.filterLogsProcessor,\n [EthereumHandlerKind.Call]: EthereumBlockWrapped.filterTransactionsProcessor,\n};\n\nconst DataAbiParser = {\n [EthereumHandlerKind.Block]: () => (data: EthereumBlock) => data,\n [EthereumHandlerKind.Event]: (api: EthereumApi) => api.parseLog.bind(api),\n [EthereumHandlerKind.Call]: (api: EthereumApi) =>\n api.parseTransaction.bind(api),\n};\n"]}
@@ -24,6 +24,7 @@ export declare class ProjectService {
24
24
  get dataSources(): SubqlProjectDs[];
25
25
  get blockOffset(): number;
26
26
  get startHeight(): number;
27
+ get isHistorical(): boolean;
27
28
  private getExistingProjectSchema;
28
29
  init(): Promise<void>;
29
30
  private ensureProject;
@@ -37,4 +38,6 @@ export declare class ProjectService {
37
38
  setBlockOffset(offset: number): Promise<void>;
38
39
  getProcessedBlockCount(): Promise<number>;
39
40
  private getStartBlockFromDataSources;
41
+ reindex(targetBlockHeight: number): Promise<void>;
42
+ n: any;
40
43
  }
@@ -23,6 +23,7 @@ const node_core_1 = require("@subql/node-core");
23
23
  const sequelize_1 = require("sequelize");
24
24
  const SubqueryProject_1 = require("../configure/SubqueryProject");
25
25
  const project_1 = require("../utils/project");
26
+ const reindex_1 = require("../utils/reindex");
26
27
  const ds_processor_service_1 = require("./ds-processor.service");
27
28
  const dynamic_ds_service_1 = require("./dynamic-ds.service");
28
29
  // eslint-disable-next-line @typescript-eslint/no-var-requires
@@ -54,6 +55,10 @@ let ProjectService = class ProjectService {
54
55
  get startHeight() {
55
56
  return this._startHeight;
56
57
  }
58
+ get isHistorical() {
59
+ return this.storeService.historical;
60
+ }
61
+ // eslint-disable-next-line @typescript-eslint/require-await
57
62
  async getExistingProjectSchema() {
58
63
  return (0, node_core_1.getExistingProjectSchema)(this.nodeConfig, this.sequelize);
59
64
  }
@@ -85,6 +90,10 @@ let ProjectService = class ProjectService {
85
90
  await this.poiService.init(this.schema);
86
91
  }
87
92
  }
93
+ if (this.nodeConfig.unfinalizedBlocks && !this.isHistorical) {
94
+ logger.error('Unfinalized blocks cannot be enabled without historical. You will need to reindex your project to enable historical');
95
+ process.exit(1);
96
+ }
88
97
  }
89
98
  async ensureProject() {
90
99
  let schema = await this.getExistingProjectSchema();
@@ -127,6 +136,8 @@ let ProjectService = class ProjectService {
127
136
  'genesisHash',
128
137
  'chainId',
129
138
  'processedBlockCount',
139
+ 'lastFinalizedVerifiedHeight',
140
+ 'schemaMigrationCount',
130
141
  ];
131
142
  const entries = await metadataRepo.findAll({
132
143
  where: {
@@ -184,6 +195,9 @@ let ProjectService = class ProjectService {
184
195
  value: packageVersion,
185
196
  });
186
197
  }
198
+ if (!keyValue.schemaMigrationCount) {
199
+ await metadataRepo.upsert({ key: 'schemaMigrationCount', value: 0 });
200
+ }
187
201
  return metadataRepo;
188
202
  }
189
203
  async upsertMetadataBlockOffset(height) {
@@ -241,6 +255,10 @@ let ProjectService = class ProjectService {
241
255
  return Math.min(...startBlocksList);
242
256
  }
243
257
  }
258
+ async reindex(targetBlockHeight) {
259
+ const lastProcessedHeight = await this.getLastProcessedHeight();
260
+ return (0, reindex_1.reindex)(this.getStartBlockFromDataSources(), await this.getMetadataBlockOffset(), targetBlockHeight, lastProcessedHeight, this.storeService, this.dynamicDsService, this.mmrService, this.sequelize);
261
+ }
244
262
  };
245
263
  ProjectService = __decorate([
246
264
  (0, common_1.Injectable)(),