Track subscriptions per method (#134)
* Track subscriptions per method * Update subscription tests * Correct newHead un/subscribe methods
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ describe('state', () => {
|
||||
expect(
|
||||
state.subscriptions
|
||||
).toMatchObject({
|
||||
'chain_subscribeNewHead': {
|
||||
'chain_newHead': {
|
||||
callbacks: {},
|
||||
lastValue: null
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}]);
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,11 +18,15 @@ import coder from '../coder/json';
|
||||
|
||||
type WsState$Awaiting = {
|
||||
callback: ProviderInterface$Callback,
|
||||
method: string,
|
||||
params: Array<any>,
|
||||
subscription?: ProviderInterface$Callback
|
||||
};
|
||||
|
||||
type WsState$Subscription = {
|
||||
callback: ProviderInterface$Callback
|
||||
callback: ProviderInterface$Callback,
|
||||
method: string,
|
||||
params: Array<any>
|
||||
};
|
||||
|
||||
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<boolean> {
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
-36
@@ -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
|
||||
};
|
||||
@@ -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/);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -17,8 +17,8 @@ import formatResult from './formatResult';
|
||||
|
||||
export default function methodSubscribe (provider: ProviderInterface, rpcName: string, method: SectionItem<Interfaces>): ApiInterface$Section$Method {
|
||||
const unsubscribe = (subscriptionId: any): Promise<any> =>
|
||||
provider.send(rpcName.replace('subscribe', 'unsubscribe'), [subscriptionId]);
|
||||
const call = async (...values: Array<any>): Promise<any> => {
|
||||
provider.send(method.subscribe[1], [subscriptionId]);
|
||||
const _call = async (...values: Array<any>): Promise<any> => {
|
||||
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;
|
||||
}
|
||||
|
||||
Vendored
+2
-1
@@ -4,9 +4,10 @@
|
||||
|
||||
import { Interfaces, Interface$Sections } from '@polkadot/jsonrpc/types';
|
||||
|
||||
export type ApiInterface$Section$Method = {
|
||||
export interface ApiInterface$Section$Method {
|
||||
(...params: Array<any>): Promise<any>;
|
||||
|
||||
subscription: string;
|
||||
unsubscribe: (id: number) => Promise<any>;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<Interfaces, PrivateMethods, P
|
||||
createMethod('getStorageSize')(getStorageSize),
|
||||
getStorageSizeAt:
|
||||
createMethod('getStorageSizeAt')(getStorageSizeAt),
|
||||
subscribeStorage:
|
||||
createMethod('subscribeStorage')(subscribeStorage)
|
||||
storage:
|
||||
createMethod('storage')(storage)
|
||||
}
|
||||
}));
|
||||
|
||||
@@ -6,21 +6,23 @@ import { SectionItem, CreateItem, CreateItems, CreateItemOptions } from './types
|
||||
|
||||
import bnToU8a from '@polkadot/util/bn/toU8a';
|
||||
import u8aConcat from '@polkadot/util/u8a/concat';
|
||||
import isUndefined from '@polkadot/util/is/undefined';
|
||||
|
||||
export default function createMethod<T> (section: keyof T, sectionIndex: Uint8Array): CreateItems<T> {
|
||||
return (name: string, index: number = 0): CreateItem<T> =>
|
||||
({ description, key = '', params, type, isDeprecated = false, isHidden = false, isSigned = false, isSubscription = false, isUnhashed = false }: CreateItemOptions): SectionItem<T> => ({
|
||||
({ description, key = '', params, type, isDeprecated = false, isHidden = false, isSigned = false, isUnhashed = false, subscribe }: CreateItemOptions): SectionItem<T> => ({
|
||||
description,
|
||||
index: u8aConcat(sectionIndex, bnToU8a(index, 8, true)),
|
||||
isDeprecated,
|
||||
isHidden,
|
||||
isSigned,
|
||||
isSubscription,
|
||||
isSubscription: !isUndefined(subscribe),
|
||||
isUnhashed,
|
||||
key,
|
||||
name,
|
||||
params,
|
||||
section,
|
||||
subscribe: subscribe || ['', ''],
|
||||
type
|
||||
});
|
||||
}
|
||||
|
||||
Vendored
+2
-1
@@ -79,6 +79,7 @@ export type SectionItem<T> = {
|
||||
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
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user