From bd2a1f54fca56a50a2c8421af365e0c108850acf Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Wed, 15 Aug 2018 16:20:45 +0200 Subject: [PATCH] Track subscriptions per method (#134) * Track subscriptions per method * Update subscription tests * Correct newHead un/subscribe methods --- packages/api-provider/src/mock/mocks.ts | 2 +- packages/api-provider/src/mock/state.spec.js | 2 +- .../api-provider/src/mock/subscribe.spec.js | 12 +++---- .../api-provider/src/mock/unsubscribe.spec.js | 12 +++---- packages/api-provider/src/ws/index.ts | 28 ++++++++++----- .../src/ws/onMessageSubscribe.spec.js | 4 ++- packages/api-provider/src/ws/types.d.ts | 36 ------------------- .../api-provider/src/ws/unsubscribe.spec.js | 4 +-- packages/api-provider/test/e2e.test.js | 4 +-- packages/api/src/create/formatResult.spec.js | 2 +- packages/api/src/create/methodSubscribe.ts | 11 +++--- packages/api/src/types.d.ts | 3 +- packages/type-jsonrpc/src/chain.ts | 9 +++-- packages/type-jsonrpc/src/state.ts | 13 ++++--- packages/type-params/src/method.ts | 6 ++-- packages/type-params/src/types.d.ts | 3 +- 16 files changed, 69 insertions(+), 82 deletions(-) delete mode 100644 packages/api-provider/src/ws/types.d.ts diff --git a/packages/api-provider/src/mock/mocks.ts b/packages/api-provider/src/mock/mocks.ts index c2291ae0b2..a11b7d33c1 100644 --- a/packages/api-provider/src/mock/mocks.ts +++ b/packages/api-provider/src/mock/mocks.ts @@ -84,6 +84,6 @@ export default function mocks ({ emitter, storage, subscriptions }: MockState): setStorageBn(storage, stateTimestamp.current, Math.floor(Date.now() / 1000)); - updateSubs(subscriptions, 'chain_subscribeNewHead', headerEncode(newHead)); + updateSubs(subscriptions, 'chain_newHead', headerEncode(newHead)); }, 5000); } diff --git a/packages/api-provider/src/mock/state.spec.js b/packages/api-provider/src/mock/state.spec.js index dbc0bcc6d7..060721f587 100644 --- a/packages/api-provider/src/mock/state.spec.js +++ b/packages/api-provider/src/mock/state.spec.js @@ -24,7 +24,7 @@ describe('state', () => { expect( state.subscriptions ).toMatchObject({ - 'chain_subscribeNewHead': { + 'chain_newHead': { callbacks: {}, lastValue: null } diff --git a/packages/api-provider/src/mock/subscribe.spec.js b/packages/api-provider/src/mock/subscribe.spec.js index 6736c78a8e..9adc1a4f8a 100644 --- a/packages/api-provider/src/mock/subscribe.spec.js +++ b/packages/api-provider/src/mock/subscribe.spec.js @@ -19,7 +19,7 @@ describe('subscribe', () => { }); it('returns a subscription id', () => { - return subscribe(state, 'chain_subscribeNewHead', [() => void 0]).then((id) => { + return subscribe(state, 'chain_newHead', [() => void 0]).then((id) => { expect(id).toEqual(state.subscriptionId); }); }); @@ -27,16 +27,16 @@ describe('subscribe', () => { it('stores the mapping values', () => { const cb = () => void 0; - return subscribe(state, 'chain_subscribeNewHead', [cb]).then((id) => { - expect(state.subscriptionMap[id]).toEqual('chain_subscribeNewHead'); - expect(state.subscriptions['chain_subscribeNewHead'].callbacks[id]).toEqual(cb); + return subscribe(state, 'chain_newHead', [cb]).then((id) => { + expect(state.subscriptionMap[id]).toEqual('chain_newHead'); + expect(state.subscriptions['chain_newHead'].callbacks[id]).toEqual(cb); }); }); it('calls back with the last known value', (done) => { - state.subscriptions['chain_subscribeNewHead'].lastValue = 'testValue'; + state.subscriptions['chain_newHead'].lastValue = 'testValue'; - subscribe(state, 'chain_subscribeNewHead', [(_, value) => { + subscribe(state, 'chain_newHead', [(_, value) => { expect(value).toEqual('testValue'); done(); }]); diff --git a/packages/api-provider/src/mock/unsubscribe.spec.js b/packages/api-provider/src/mock/unsubscribe.spec.js index f63ce456c9..8d951d7f81 100644 --- a/packages/api-provider/src/mock/unsubscribe.spec.js +++ b/packages/api-provider/src/mock/unsubscribe.spec.js @@ -13,23 +13,23 @@ describe('unsubscribe', () => { beforeEach(() => { state = createState(); - return subscribe(state, 'chain_subscribeNewHead', [() => void 0]).then((_id) => { + return subscribe(state, 'chain_newHead', [() => void 0]).then((_id) => { id = _id; }); }); it('fails on unknown ids', () => { - return unsubscribe(state, 'chain_subscribeNewHead', 5).catch((error) => { + return unsubscribe(state, 'chain_newHead', 5).catch((error) => { expect(error.message).toMatch(/Unable to find/); }); }); it('unsubscribes successfully', () => { - return unsubscribe(state, 'chain_subscribeNewHead', id); + return unsubscribe(state, 'chain_newHead', id); }); it('fails on double unsubscribe', () => { - return unsubscribe(state, 'chain_subscribeNewHead', id) + return unsubscribe(state, 'chain_newHead', id) .then(() => unsubscribe(state, id)) .catch((error) => { expect(error.message).toMatch(/Unable to find/); @@ -37,9 +37,9 @@ describe('unsubscribe', () => { }); it('clears the subscriptions', () => { - return unsubscribe(state, 'chain_subscribeNewHead', id).then(() => { + return unsubscribe(state, 'chain_newHead', id).then(() => { expect(state.subscriptionMap[id]).not.toBeDefined(); - expect(state.subscriptions['chain_subscribeNewHead'].callbacks[id]).not.toBeDefined(); + expect(state.subscriptions['chain_newHead'].callbacks[id]).not.toBeDefined(); }); }); }); diff --git a/packages/api-provider/src/ws/index.ts b/packages/api-provider/src/ws/index.ts index 697223d1e8..0909510562 100644 --- a/packages/api-provider/src/ws/index.ts +++ b/packages/api-provider/src/ws/index.ts @@ -18,11 +18,15 @@ import coder from '../coder/json'; type WsState$Awaiting = { callback: ProviderInterface$Callback, + method: string, + params: Array, subscription?: ProviderInterface$Callback }; type WsState$Subscription = { - callback: ProviderInterface$Callback + callback: ProviderInterface$Callback, + method: string, + params: Array }; interface WSProviderInterface extends ProviderInterface { @@ -42,7 +46,7 @@ export default class WsProvider extends E3.EventEmitter implements WSProviderInt [index: string]: string }; private subscriptions: { - [index: number]: WsState$Subscription + [index: string]: WsState$Subscription }; private websocket: WebSocket | null; @@ -104,6 +108,8 @@ export default class WsProvider extends E3.EventEmitter implements WSProviderInt this.handlers[id] = { callback, + method, + params, subscription }; @@ -125,7 +131,7 @@ export default class WsProvider extends E3.EventEmitter implements WSProviderInt } async unsubscribe (method: string, id: number): Promise { - assert(!isUndefined(this.subscriptions[id]), `Unable to find active subscription=${id}`); + assert(!isUndefined(this.subscriptions[`${method}::${id}`]), `Unable to find active subscription=${id}`); delete this.subscriptions[id]; @@ -172,12 +178,14 @@ export default class WsProvider extends E3.EventEmitter implements WSProviderInt } try { - const { subscription } = this.handlers[response.id]; + const { method, params, subscription } = this.handlers[response.id]; const result = this.coder.decodeResponse(response); if (subscription) { - this.subscriptions[result as number] = { - callback: subscription + this.subscriptions[`${method}::${result}`] = { + callback: subscription, + method, + params }; } @@ -190,12 +198,14 @@ export default class WsProvider extends E3.EventEmitter implements WSProviderInt } private onSocketMessageSubscribe = (response: JsonRpcResponse): void => { - this.l.debug(() => ['handling: response =', response, 'subscription =', response.params.subscription]); + const subscription = `${response.method}::${response.params.subscription}`; - const handler = this.subscriptions[response.params.subscription]; + this.l.debug(() => ['handling: response =', response, 'subscription =', subscription]); + + const handler = this.subscriptions[subscription]; if (!handler) { - this.l.error(`Unable to find handler for subscription=${response.params.subscription}`); + this.l.error(`Unable to find handler for subscription=${subscription}`); return; } diff --git a/packages/api-provider/src/ws/onMessageSubscribe.spec.js b/packages/api-provider/src/ws/onMessageSubscribe.spec.js index dccc2dc06d..856130505e 100644 --- a/packages/api-provider/src/ws/onMessageSubscribe.spec.js +++ b/packages/api-provider/src/ws/onMessageSubscribe.spec.js @@ -21,13 +21,14 @@ describe('onMessageSubscribe', () => { ws.onSocketMessage({ data: '{"method":"test","params":{"subscription":2}}' }); expect(errorSpy).toHaveBeenCalledWith( - expect.anything(), expect.anything(), 'Unable to find handler for subscription=2' + expect.anything(), expect.anything(), 'Unable to find handler for subscription=test::2' ); }); it('calls the subscriber with data', (done) => { ws.handlers[11] = { callback: (_, id) => {}, + method: 'test', subscription: (_, result) => { expect(result).toEqual('test'); done(); @@ -41,6 +42,7 @@ describe('onMessageSubscribe', () => { it('calls the subscriber with error', (done) => { ws.handlers[11] = { callback: (_, id) => {}, + method: 'test', subscription: (error) => { expect(error.message).toMatch(/test/); done(); diff --git a/packages/api-provider/src/ws/types.d.ts b/packages/api-provider/src/ws/types.d.ts deleted file mode 100644 index f0c74d328a..0000000000 --- a/packages/api-provider/src/ws/types.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2017-2018 @polkadot/api-provider authors & contributors -// This software may be modified and distributed under the terms -// of the ISC license. See the LICENSE file for details. - -import E3 from 'eventemitter3'; -import { Logger } from '@polkadot/util/types'; -import { RpcCoder } from '../coder/json/types'; -import { ProviderInterface$Callback } from '../types'; - -export type WsState$Awaiting = { - callback: ProviderInterface$Callback, - subscription?: ProviderInterface$Callback -}; - -export type WsState$Subscription = { - callback: ProviderInterface$Callback -}; - -export type WsState = { - autoConnect: boolean, - coder: RpcCoder, - endpoint: string, - emitter: E3.EventEmitter, - handlers: { - [index: number]: WsState$Awaiting - }, - isConnected: boolean, - l: Logger, - queued: { - [index: string]: string - }, - subscriptions: { - [index: number]: WsState$Subscription - }, - websocket: WebSocket | null -}; diff --git a/packages/api-provider/src/ws/unsubscribe.spec.js b/packages/api-provider/src/ws/unsubscribe.spec.js index 9d97cefec2..6082cf3df0 100644 --- a/packages/api-provider/src/ws/unsubscribe.spec.js +++ b/packages/api-provider/src/ws/unsubscribe.spec.js @@ -58,7 +58,7 @@ describe('subscribe', () => { return ws .subscribe('subscribe_test', [], () => {}) .then((id) => { - return ws.unsubscribe('unsubscribe_test', id); + return ws.unsubscribe('subscribe_test', id); }); }); @@ -76,7 +76,7 @@ describe('subscribe', () => { return ws .subscribe('subscribe_test', [], () => {}) .then((id) => { - return ws.unsubscribe('unsubscribe_test', 111); + return ws.unsubscribe('subscribe_test', 111); }) .catch((error) => { expect(error.message).toMatch(/find active subscription/); diff --git a/packages/api-provider/test/e2e.test.js b/packages/api-provider/test/e2e.test.js index 4259c2bcf2..765b0c88a7 100644 --- a/packages/api-provider/test/e2e.test.js +++ b/packages/api-provider/test/e2e.test.js @@ -15,12 +15,12 @@ describe.skip('e2e', () => { api = createApi(new Ws('ws://127.0.0.1:9944')); }); - it('subscribes to chain_subscribeNewHead', (done) => { + it('subscribes to chain_newHead', (done) => { let count = 0; // tslint:disable-next-line api.chain - .subscribeNewHead((error, data) => { + .newHead((error, data) => { if (error) { return done(error); } diff --git a/packages/api/src/create/formatResult.spec.js b/packages/api/src/create/formatResult.spec.js index 58580e5e6a..f3903582b9 100644 --- a/packages/api/src/create/formatResult.spec.js +++ b/packages/api/src/create/formatResult.spec.js @@ -52,7 +52,7 @@ describe('formatResult', () => { it('encodes multiple keys, decoding multiple results', (done) => { api.state - .subscribeStorage( + .storage( [ [storage.staking.public.freeBalanceOf, ADDR_ONE], [storage.staking.public.freeBalanceOf, ADDR_TWO] diff --git a/packages/api/src/create/methodSubscribe.ts b/packages/api/src/create/methodSubscribe.ts index ef078330d1..70069c1905 100644 --- a/packages/api/src/create/methodSubscribe.ts +++ b/packages/api/src/create/methodSubscribe.ts @@ -17,8 +17,8 @@ import formatResult from './formatResult'; export default function methodSubscribe (provider: ProviderInterface, rpcName: string, method: SectionItem): ApiInterface$Section$Method { const unsubscribe = (subscriptionId: any): Promise => - provider.send(rpcName.replace('subscribe', 'unsubscribe'), [subscriptionId]); - const call = async (...values: Array): Promise => { + provider.send(method.subscribe[1], [subscriptionId]); + const _call = async (...values: Array): Promise => { try { const cb: ProviderInterface$Callback = values.pop(); @@ -29,14 +29,15 @@ export default function methodSubscribe (provider: ProviderInterface, rpcName: s cb(error, formatResult(method, params, values, result)); }; - return provider.subscribe(rpcName, params, update); + return provider.subscribe(method.subscribe[0], params, update); } catch (error) { throw new ExtError(`${signature(method)}:: ${error.message}`, (error as ExtError).code, undefined); } }; - // @ts-ignore yes, we are extending here + const call = _call as ApiInterface$Section$Method; + call.unsubscribe = unsubscribe; - return call as ApiInterface$Section$Method; + return call; } diff --git a/packages/api/src/types.d.ts b/packages/api/src/types.d.ts index 562967550f..8af3207303 100644 --- a/packages/api/src/types.d.ts +++ b/packages/api/src/types.d.ts @@ -4,9 +4,10 @@ import { Interfaces, Interface$Sections } from '@polkadot/jsonrpc/types'; -export type ApiInterface$Section$Method = { +export interface ApiInterface$Section$Method { (...params: Array): Promise; + subscription: string; unsubscribe: (id: number) => Promise; } diff --git a/packages/type-jsonrpc/src/chain.ts b/packages/type-jsonrpc/src/chain.ts index 2c645fec8a..85ab43ed04 100644 --- a/packages/type-jsonrpc/src/chain.ts +++ b/packages/type-jsonrpc/src/chain.ts @@ -30,9 +30,12 @@ const getHeader: CreateItemOptions = { type: 'Header' }; -const subscribeNewHead: CreateItemOptions = { +const newHead: CreateItemOptions = { description: 'Retrieves the best header via subscription', - isSubscription: true, + subscribe: [ + 'chain_subscribeNewHead', + 'chain_unsubscribeNewHead' + ], params: [], type: 'Header' }; @@ -40,7 +43,7 @@ const subscribeNewHead: CreateItemOptions = { const privateMethods: CreateItemOptionsMap = {}; const publicMethods: CreateItemOptionsMap = { - getBlock, getHead, getHeader, subscribeNewHead + getBlock, getHead, getHeader, newHead }; export type PublicMethods = typeof publicMethods; diff --git a/packages/type-jsonrpc/src/state.ts b/packages/type-jsonrpc/src/state.ts index 48bd215227..403b75f4f4 100644 --- a/packages/type-jsonrpc/src/state.ts +++ b/packages/type-jsonrpc/src/state.ts @@ -78,9 +78,12 @@ const getStorageSizeAt: CreateItemOptions = { type: 'u64' }; -const subscribeStorage: CreateItemOptions = { +const storage: CreateItemOptions = { description: 'Subscribes to storage changes for the provided keys', - isSubscription: true, + subscribe: [ + 'state_subscribeStorage', + 'state_unsubscribeStorage' + ], params: [ param('keys', ['StorageKey']) ], @@ -90,7 +93,7 @@ const subscribeStorage: CreateItemOptions = { const privateMethods: CreateItemOptionsMap = {}; const publicMethods: CreateItemOptionsMap = { - call, callAt, getStorage, getStorageAt, getStorageHash, getStorageHashAt, getStorageSize, getStorageSizeAt, subscribeStorage + call, callAt, getStorage, getStorageAt, getStorageHash, getStorageHashAt, getStorageSize, getStorageSizeAt, storage }; export type PrivateMethods = typeof privateMethods; @@ -119,7 +122,7 @@ export default (name: Interface$Sections): Section (section: keyof T, sectionIndex: Uint8Array): CreateItems { return (name: string, index: number = 0): CreateItem => - ({ description, key = '', params, type, isDeprecated = false, isHidden = false, isSigned = false, isSubscription = false, isUnhashed = false }: CreateItemOptions): SectionItem => ({ + ({ description, key = '', params, type, isDeprecated = false, isHidden = false, isSigned = false, isUnhashed = false, subscribe }: CreateItemOptions): SectionItem => ({ description, index: u8aConcat(sectionIndex, bnToU8a(index, 8, true)), isDeprecated, isHidden, isSigned, - isSubscription, + isSubscription: !isUndefined(subscribe), isUnhashed, key, name, params, section, + subscribe: subscribe || ['', ''], type }); } diff --git a/packages/type-params/src/types.d.ts b/packages/type-params/src/types.d.ts index eea5cd5e76..5b0f6f52ab 100644 --- a/packages/type-params/src/types.d.ts +++ b/packages/type-params/src/types.d.ts @@ -79,6 +79,7 @@ export type SectionItem = { name: string, params: Params, section: keyof T, + subscribe: [string, string], // only for jsonrpc type: Param$Types }; @@ -103,10 +104,10 @@ export type CreateItemOptions = { isDeprecated?: boolean, isHidden?: boolean, isSigned?: boolean, - isSubscription?: boolean, isUnhashed?: boolean, key?: string, params: Params, + subscribe?: [string, string], type: Param$Types };