Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reload chainTypes #2505

Merged
merged 10 commits into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/node-core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed
- Fixed project upgrade missing reload network chainTypes when `onProjectChange` (#2505)

## [13.0.1] - 2024-07-29
### Fixed
- Fixed get and set data not been deepCloned and data is not mutable
Expand Down
3 changes: 2 additions & 1 deletion packages/node-core/src/api.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,14 @@ export interface IApiConnectionSpecific<A = any, SA = any, B extends Array<any>
handleError(error: Error): ApiConnectionError;
apiConnect(): Promise<void>;
apiDisconnect(): Promise<void>;
updateChainTypes?(chainTypes: unknown): Promise<void>;
}

export abstract class ApiService<
A = any,
SA = any,
B extends Array<any> = any[],
Connection extends IApiConnectionSpecific<A, SA, B> = IApiConnectionSpecific<A, SA, B>
Connection extends IApiConnectionSpecific<A, SA, B> = IApiConnectionSpecific<A, SA, B>,
> implements IApi<A, SA, B>
{
constructor(
Expand Down
7 changes: 7 additions & 0 deletions packages/node-core/src/indexer/connectionPool.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,4 +250,11 @@ export class ConnectionPoolService<T extends IApiConnectionSpecific<any, any, an
this.lastCacheFlushTime = Date.now();
await this.handleConnectionStateChange();
}

async updateChainTypes(newChainTypes: unknown): Promise<void> {
for (const endpoint in this.allApi) {
await this.allApi[endpoint].updateChainTypes?.(newChainTypes);
}
logger.info(`Network chain types updated!`);
}
}
4 changes: 3 additions & 1 deletion packages/node/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed
- Fixed api not reloading new deployment chainTypes when project upgrades (#2505)

## [5.0.1] - 2024-07-29
### Fixed
- Fixed default Timezone to UTC in dockerfile and package.json (#2505)
Expand All @@ -15,7 +18,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- Breaking change: Update with `@subql/node-core`, require indexing environment timezone set to UTC (#2495)
- Update SubqueryProject to use code from node-core (#2496)

### Fixed
- Bump with `@subql/node-core`, fixed various issues causing poi inconsistency (#2497)

Expand Down
6 changes: 5 additions & 1 deletion packages/node/src/indexer/api.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,10 +206,14 @@ export class ApiService
});
},
);

return this;
}

async updateChainTypes(): Promise<void> {
const chainTypes = await updateChainTypesHasher(this.project.chainTypes);
await this.connectionPoolService.updateChainTypes(chainTypes);
}

updateBlockFetching(): void {
const onlyEventHandlers = isOnlyEventHandlers(this.project);
const skipTransactions =
Expand Down
13 changes: 12 additions & 1 deletion packages/node/src/indexer/apiPromise.connection.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors
// SPDX-License-Identifier: GPL-3.0

import assert from 'assert';
import { ApiPromise, WsProvider } from '@polkadot/api';
import { ApiOptions } from '@polkadot/api/types';
import { ProviderInterface } from '@polkadot/rpc-provider/types';
import { RegisteredTypes } from '@polkadot/types/types';
import {
Expand Down Expand Up @@ -83,6 +83,7 @@ export class ApiPromiseConnection
noInitWarn: true,
...args.chainTypes,
};

const api = await ApiPromise.create(apiOption);
return new ApiPromiseConnection(api, fetchBlocksBatches);
}
Expand Down Expand Up @@ -123,6 +124,16 @@ export class ApiPromiseConnection
await this.unsafeApi.disconnect();
}

async updateChainTypes(chainTypes: RegisteredTypes): Promise<void> {
// Typeof Decorate<'promise' | 'rxjs'>, but we need to access this private method
const currentApiOptions = (this.unsafeApi as any)._options as ApiOptions;
const apiOption = {
...currentApiOptions,
...chainTypes,
};
Comment on lines +130 to +133
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const apiOption = {
...currentApiOptions,
...chainTypes,
};
const apiOption: ApiOptions = {
...currentApiOptions,
chainTypes,
};

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this.unsafeApi = await ApiPromise.create(apiOption);
}

handleError = ApiPromiseConnection.handleError;

static handleError(e: Error): ApiConnectionError {
Expand Down
139 changes: 139 additions & 0 deletions packages/node/src/indexer/project.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors
// SPDX-License-Identifier: GPL-3.0

import { EventEmitter2 } from '@nestjs/event-emitter';
import {
ConnectionPoolService,
ConnectionPoolStateManager,
NodeConfig,
ProjectUpgradeService,
} from '@subql/node-core';
import { SubstrateDatasourceKind, SubstrateHandlerKind } from '@subql/types';
import { GraphQLSchema } from 'graphql';
import { SubqueryProject } from '../configure/SubqueryProject';
import { ApiService } from './api.service';
import { ApiPromiseConnection } from './apiPromise.connection';
import { DsProcessorService } from './ds-processor.service';
import { DynamicDsService } from './dynamic-ds.service';
import { ProjectService } from './project.service';

const nodeConfig = new NodeConfig({
subquery: 'test',
subqueryName: 'test',
networkEndpoint: ['https://polkadot.api.onfinality.io/public'],
dictionaryTimeout: 10,
});

function testSubqueryProject(): SubqueryProject {
return {
id: 'test',
root: './',
network: {
endpoint: ['https://polkadot.api.onfinality.io/public'],
chainId:
'0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3',
},
dataSources: [
{
kind: SubstrateDatasourceKind.Runtime,
startBlock: 1,
mapping: {
file: '',
handlers: [
{ handler: 'testSandbox', kind: SubstrateHandlerKind.Event },
],
},
},
],
schema: new GraphQLSchema({}),
templates: [],
chainTypes: {
types: {
TestType: 'u32',
},
},
applyCronTimestamps: () => jest.fn(),
} as unknown as SubqueryProject;
}

const demoProjects = [
testSubqueryProject(),
{
parent: {
utilBlock: 5,
reference: '0',
},
...testSubqueryProject(),
},
] as SubqueryProject[];

jest.setTimeout(10_000);

describe('ProjectService', () => {
let service: ProjectService;

const apiService = new ApiService(
demoProjects[0],
new ConnectionPoolService<ApiPromiseConnection>(
nodeConfig,
new ConnectionPoolStateManager(),
),
new EventEmitter2(),
nodeConfig,
);

beforeEach(async () => {
// Api service init at bootstrap
await apiService.init();

const projectUpgradeService = await ProjectUpgradeService.create(
demoProjects[0],
(id) => Promise.resolve(demoProjects[parseInt(id, 10)]),
1,
);

(projectUpgradeService as any).init = jest.fn();
(projectUpgradeService as any).updateIndexedDeployments = jest.fn();

service = new ProjectService(
{
validateProjectCustomDatasources: jest.fn(),
} as unknown as DsProcessorService,
apiService,
null as unknown as any,
null as unknown as any,
{ query: jest.fn() } as unknown as any,
demoProjects[0],
projectUpgradeService,
{
initCoreTables: jest.fn(),
storeCache: { metadata: {}, flushCache: jest.fn() },
} as unknown as any,
{ unsafe: false } as unknown as NodeConfig,
{
getDynamicDatasources: jest.fn().mockResolvedValue([]),
init: jest.fn(),
} as unknown as DynamicDsService,
null as unknown as any,
null as unknown as any,
);

// Mock db related returns
(service as any).ensureProject = jest.fn().mockResolvedValue('mock-schema');
(service as any).ensureMetadata = jest.fn();
(service as any).initDbSchema = jest.fn();
(service as any).initUnfinalizedInternal = jest
.fn()
.mockResolvedValue(undefined);
});

it('reload chainTypes when project changed, on init', async () => {
const spyOnApiUpdateChainTypes = jest.spyOn(apiService, 'updateChainTypes');
// mock last processed height
(service as any).getLastProcessedHeight = jest.fn().mockResolvedValue(4);

await service.init(5);

expect(spyOnApiUpdateChainTypes).toHaveBeenCalledTimes(1);
});
});
4 changes: 3 additions & 1 deletion packages/node/src/indexer/project.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ export class ProjectService extends BaseProjectService<
return getTimestamp(block);
}

protected onProjectChange(project: SubqueryProject): void | Promise<void> {
protected async onProjectChange(project: SubqueryProject): Promise<void> {
// Only network with chainTypes require to reload
await this.apiService.updateChainTypes();
this.apiService.updateBlockFetching();
}
}
Loading