refactor: Remove rpc-rx (#1037)

* Remove rpc-rx

* Make some stuff work

* Fix tests

* Update Base

* Change some stuff

* Remove rpc-rx mentions

* Add correct tests

* Make cache work

* Fix little bugs

* Rename to spec

* Fix lint

* Fix little bugs

* Add comment

* Add correct test

* Update header

* Add test

* Add comments

* Indentation
This commit is contained in:
Amaury Martiny
2019-06-20 11:06:13 +02:00
committed by GitHub
parent 49d7668534
commit fe16c09f01
35 changed files with 549 additions and 1193 deletions
+78
View File
@@ -0,0 +1,78 @@
// Copyright 2017-2019 @polkadot/rpc-core authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import testingPairs from '@polkadot/keyring/testingPairs';
import MockProvider from '@polkadot/rpc-provider/mock';
import { AccountId } from '@polkadot/types';
import Rpc from '.';
describe('Cached Observables', () => {
let rpc: Rpc;
const keyring = testingPairs();
beforeEach(() => {
rpc = new Rpc(new MockProvider());
});
it('creates a single observable for subscriptions (multiple calls)', () => {
const observable1 = rpc.chain.subscribeNewHead(123);
const observable2 = rpc.chain.subscribeNewHead(123);
expect(observable2).toBe(observable1);
});
it('creates a single observable for subscriptions (multiple calls, no arguments)', () => {
const observable1 = rpc.chain.subscribeNewHead();
const observable2 = rpc.chain.subscribeNewHead();
expect(observable2).toBe(observable1);
});
it('creates a single observable (multiple calls, different arguments that should be cached together)', () => {
const observable1 = rpc.chain.subscribeNewHead(keyring.alice.address);
const observable2 = rpc.chain.subscribeNewHead(new AccountId(keyring.alice.address));
expect(observable2).toBe(observable1);
});
it('creates multiple observables for different values', () => {
const observable1 = rpc.chain.subscribeNewHead(123);
const observable2 = rpc.chain.subscribeNewHead(456);
expect(observable2).not.toBe(observable1);
});
it('clears cache if there are no more subscribers', () => {
const observable1 = rpc.chain.subscribeNewHead();
const observable2 = rpc.chain.subscribeNewHead();
expect(observable1).toBe(observable2);
const sub1 = observable1.subscribe();
const sub2 = observable2.subscribe();
sub1.unsubscribe();
sub2.unsubscribe();
// No more subscribers, now create a new observable
const observable3 = rpc.chain.subscribeNewHead();
expect(observable3).not.toBe(observable1);
});
it('creates different observables for different methods but same arguments', () => {
const observable1 = rpc.chain.subscribeNewHead(123);
const observable2 = rpc.state.subscribeStorage(123);
expect(observable2).not.toBe(observable1);
});
it('creates multiple observables for one-shots', () => {
const observable1 = rpc.system.chain(123);
const observable2 = rpc.system.chain(123);
expect(observable2).not.toBe(observable1);
});
});
+32 -30
View File
@@ -16,11 +16,11 @@ import Api from '.';
const ADDR_ONE = '5DkQbYAExs3M2sZgT1Ec3mKfZnAQCL4Dt9beTCknkCUn5jzo';
const ADDR_TWO = '5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF';
const BALANCE_KEYS = [
/* v3- */ '0x4af2c53fce3ec33c6ccccf22e926f1a7',
/* v4+ */ '0xec8f96437274a883afcac82d01a9defeb68209cd4f2c084632813692aa5e65ad'
/* v3-, using xxHash */ '0x4af2c53fce3ec33c6ccccf22e926f1a7',
/* v4+, using blake2_256 */ '0xec8f96437274a883afcac82d01a9defeb68209cd4f2c084632813692aa5e65ad'
];
function formattingTests (version: string, storage: Storage, encodedValues: [String, String]) {
function formattingTests (version: string, storage: Storage, encodedValues: [string, string]) {
const [ENC_ONE, ENC_TWO] = encodedValues;
describe(`formatting with Metadata ${version}`, () => {
@@ -36,8 +36,8 @@ function formattingTests (version: string, storage: Storage, encodedValues: [Str
: null
)
),
subscribe: jest.fn((type, method, params, subscription) =>
subscription(null, {
subscribe: jest.fn((type, method, params, cb) =>
cb(null, {
block: '0x1234',
changes: [
[ENC_ONE, '0x01020000000000000000000000000000'],
@@ -49,10 +49,10 @@ function formattingTests (version: string, storage: Storage, encodedValues: [Str
api = new Api(provider);
});
it('encodes key (with params), decoding response', () => {
return api.state
it('encodes key (with params), decoding response', (done) => {
api.state
.getStorage([storage.balances.freeBalance, ADDR_ONE])
.then((value) => {
.subscribe((value) => {
expect(
provider.send
).toHaveBeenCalledWith(
@@ -60,42 +60,44 @@ function formattingTests (version: string, storage: Storage, encodedValues: [Str
[ENC_ONE]
);
expect(value.toNumber()).toEqual(513);
done();
});
});
it('returns the fallback result on not-found values', () => {
return api.state
it('returns the fallback result on not-found values', (done) => {
api.state
.getStorage([storage.system.accountNonce, ADDR_ONE])
.then((value) => {
.subscribe((value) => {
expect(value.toHex()).toEqual('0x0000000000000000');
done();
});
});
it('encodes multiple keys, decoding multiple results', (done) => {
return api.state.subscribeStorage(
api.state.subscribeStorage(
[
[storage.balances.freeBalance, ADDR_ONE],
[storage.balances.freeBalance, ADDR_TWO]
],
(value: any) => {
console.error(value);
]
).subscribe((value: any) => {
console.error(value);
expect(
provider.subscribe
).toHaveBeenCalledWith(
'state_storage',
'state_subscribeStorage',
[[ENC_ONE, ENC_TWO]],
expect.anything()
);
expect(
value.map((balance: BN) =>
balance.toNumber()
)
).toEqual([513, 258]);
expect(
provider.subscribe
).toHaveBeenCalledWith(
'state_storage',
'state_subscribeStorage',
[[ENC_ONE, ENC_TWO]],
expect.anything()
);
expect(
value.map((balance: BN) =>
balance.toNumber()
)
).toEqual([513, 258]);
done();
});
done();
});
});
});
}
+12 -25
View File
@@ -2,38 +2,25 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import Api from '.';
import MockProvider from '@polkadot/rpc-provider/mock';
import Rpc from '.';
describe('Api', () => {
let api: Api;
let provider: any;
let sendSpy: any;
beforeEach(() => {
provider = {
send: (method: any, params: Array<any>) => {
return Promise.resolve(params[0]);
}
};
sendSpy = jest.spyOn(provider, 'send');
api = new Api(provider);
});
afterEach(() => {
sendSpy.mockRestore();
});
it('requires a provider with a send method', () => {
expect(
() => new Api({} as any)
() => new Rpc({} as any)
).toThrow(/Expected Provider/);
});
it('sets up the chain interface', () => {
expect(api.chain).toBeDefined();
});
it('creates an instance with all sections', () => {
const rpc = new Rpc(new MockProvider());
it('sets up the state interface', () => {
expect(api.state).toBeDefined();
expect(
Object.keys(rpc)
).toEqual([
'provider',
'author', 'chain', 'state', 'system'
]);
});
});
+100 -49
View File
@@ -2,12 +2,14 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ProviderInterface, ProviderInterface$Callback } from '@polkadot/rpc-provider/types';
import { ProviderInterface } from '@polkadot/rpc-provider/types';
import { RpcSection, RpcMethod } from '@polkadot/jsonrpc/types';
import { RpcInterface, RpcInterface$Method, RpcInterface$Section } from './types';
import memoize from 'memoizee';
import { combineLatest, from, Observable, Observer, of, throwError } from 'rxjs';
import { catchError, map, publishReplay, refCount, switchMap } from 'rxjs/operators';
import interfaces from '@polkadot/jsonrpc';
import { WsProvider } from '@polkadot/rpc-provider';
import { Codec } from '@polkadot/types/types';
import { Option, StorageChangeSet, StorageKey, Vector, createClass, createType } from '@polkadot/types';
import { ExtError, assert, isFunction, isNull, logger } from '@polkadot/util';
@@ -39,15 +41,15 @@ const EMPTY_META = {
* <BR>
*
* ```javascript
* import Api from '@polkadot/rpc-core';
* import Rpc from '@polkadot/rpc-core';
* import WsProvider from '@polkadot/rpc-provider/ws';
*
* const provider = new WsProvider('ws://127.0.0.1:9944');
* const api = new Api(provider);
* const rpc = new Rpc(provider);
* ```
*/
export default class Rpc implements RpcInterface {
readonly _provider: ProviderInterface;
readonly provider: ProviderInterface;
readonly author: RpcInterface$Section;
readonly chain: RpcInterface$Section;
readonly state: RpcInterface$Section;
@@ -58,10 +60,10 @@ export default class Rpc implements RpcInterface {
* Default constructor for the Api Object
* @param {ProviderInterface} provider An API provider using HTTP or WebSocket
*/
constructor (provider: ProviderInterface = new WsProvider()) {
constructor (provider: ProviderInterface) {
assert(provider && isFunction(provider.send), 'Expected Provider to API create');
this._provider = provider;
this.provider = provider;
this.author = this.createInterface(interfaces.author);
this.chain = this.createInterface(interfaces.chain);
@@ -96,17 +98,21 @@ export default class Rpc implements RpcInterface {
* @description Manually disconnect from the attached provider
*/
disconnect (): void {
this._provider.disconnect();
this.provider.disconnect();
}
private createErrorMessage (method: RpcMethod, error: Error) {
return `${Rpc.signature(method)}:: ${error.message}`;
}
private createInterface ({ methods }: RpcSection): RpcInterface$Section {
return Object
.keys(methods)
.reduce((exposed, method) => {
.reduce((exposed, methodName) => {
const def = methods[method];
const def = methods[methodName];
exposed[method] = def.isSubscription
exposed[methodName] = def.isSubscription
? this.createMethodSubscribe(def)
: this.createMethodSend(def);
@@ -117,23 +123,40 @@ export default class Rpc implements RpcInterface {
private createMethodSend (method: RpcMethod): RpcInterface$Method {
const rpcName = `${method.section}_${method.method}`;
const call = async (...values: Array<any>): Promise<any> => {
const call = (...values: Array<any>): Observable<any> => {
// TODO Warn on deprecated methods
try {
const params = this.formatInputs(method, values);
const paramsJson = params.map((param) => param.toJSON());
const result = await this._provider.send(rpcName, paramsJson);
return this.formatOutput(method, params, result);
} catch (error) {
const message = `${Rpc.signature(method)}:: ${error.message}`;
// Here, logically, it should be `of(this.formatInputs(method, values))`.
// However, formatInputs can throw, and when it does, the above way
// doesn't throw in the "Observable loop" (which is internally wrapped in
// a try/catch block). So we:
// - first do `of(1)` - won't throw
// - then do `map(()=>this.formatInputs)` - might throw, but inside Observable.
return of(1)
.pipe(
map(() => this.formatInputs(method, values)),
switchMap((params) =>
combineLatest([
of(params),
from(this.provider.send(rpcName, params.map((param) => param.toJSON())))
])
),
map(([params, result]) => this.formatOutput(method, params, result)),
catchError((error) => {
const message = this.createErrorMessage(method, error);
l.error(message);
l.error(message);
throw new ExtError(message, (error as ExtError).code, undefined);
}
return throwError(new ExtError(message, (error as ExtError).code, undefined));
}),
publishReplay(1), // create a Replay(1)
refCount() // Unsubcribe WS when there are no more subscribers
);
};
// We voluntarily don't cache the "one-shot" RPC calls. For example,
// `getStorage('123')` returns the current value, but this value can change
// over time, so we wouldn't want to cache the Observable.
return call as RpcInterface$Method;
}
@@ -143,40 +166,68 @@ export default class Rpc implements RpcInterface {
const unsubName = `${method.section}_${unsubMethod}`;
const subType = `${method.section}_${updateType}`;
const unsubscribe = (subscriptionId: any): Promise<any> =>
this._provider.unsubscribe(subType, unsubName, subscriptionId);
const _call = async (...values: Array<any>): Promise<any> => {
try {
const cb: ProviderInterface$Callback = values.pop();
const call = (...values: Array<any>): Observable<any> => {
return new Observable((observer: Observer<any>) => {
let subscriptionPromise: Promise<number>;
assert(isFunction(cb), `Expected callback in last position of params`);
try {
const params = this.formatInputs(method, values);
const paramsJson = params.map((param) => param.toJSON());
const update = (error?: Error, result?: any) => {
if (error) {
l.error(this.createErrorMessage(method, error));
return;
}
const params = this.formatInputs(method, values);
const paramsJson = params.map((param) => param.toJSON());
const update = (error: Error | null, result?: any) => {
if (error) {
l.error(`${Rpc.signature(method)}:: ${error.message}`);
return;
}
observer.next(this.formatOutput(method, params, result));
};
cb(this.formatOutput(method, params, result));
subscriptionPromise = this.provider.subscribe(subType, subName, paramsJson, update);
} catch (error) {
const message = this.createErrorMessage(method, error);
l.error(message);
observer.error(new ExtError(message, (error as ExtError).code, undefined));
}
// Teardown logic
return () => {
// Delete from cache
// Reason:
// ```
// const s = api.query.system.accountNonce(addr1).subscribe(); // let's say it's 6
// s.unsubscribe();
// // wait a bit, for the nonce to increase to 7
// api.query.system.accountNonce(addr1).subscribe(); // will output 6 instead of 7 if we don't clear cache
// // that's because all our observables are replay(1)
// ```
memoized.delete(...values);
// Unsubscribe from provider
subscriptionPromise
.then((subscriptionId) => this.provider.unsubscribe(subType, unsubName, subscriptionId))
.catch((error: Error) => {
const message = this.createErrorMessage(method, error);
l.error(message);
});
};
return this._provider.subscribe(subType, subName, paramsJson, update);
} catch (error) {
const message = `${Rpc.signature(method)}:: ${error.message}`;
l.error(message);
throw new ExtError(message, (error as ExtError).code, undefined);
}
}).pipe(
publishReplay(1),
refCount()
);
};
const call = _call as RpcInterface$Method;
const memoized = memoize(call, {
// Dynamic length for argument
length: false,
// Normalize args so that different args that should be cached
// together are cached together.
// E.g.: `query.my.method('abc') === query.my.method(new AccountId('abc'));`
normalizer: JSON.stringify
});
call.unsubscribe = unsubscribe;
return call;
return memoized;
}
private formatInputs (method: RpcMethod, inputs: Array<any>): Array<Codec> {
+24 -16
View File
@@ -2,10 +2,10 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import Api from '.';
import Rpc from '.';
describe('methodSend', () => {
let api: Api;
let rpc: Rpc;
let methods: any;
let provider: any;
@@ -33,34 +33,42 @@ describe('methodSend', () => {
})
};
api = new Api(provider);
rpc = new Rpc(provider);
});
it('wraps errors with the call signature', () => {
it('wraps errors with the call signature', (done) => {
// @ts-ignore private method
const method = api.createMethodSend(methods.blah);
const method = rpc.createMethodSend(methods.blah);
return method().catch((error) => {
expect(error.message).toMatch(/blah \(foo: Bytes\): Bytes/);
});
method().subscribe(
() => { /* noop */ },
(error) => {
expect(error.message).toMatch(/blah \(foo: Bytes\): Bytes/);
done();
}
);
});
it('checks for mismatched parameters', () => {
it('checks for mismatched parameters', (done) => {
// @ts-ignore private method
const method = api.createMethodSend(methods.bleh);
const method = rpc.createMethodSend(methods.bleh);
return method(1).catch((error) => {
expect(error.message).toMatch(/parameters, 1 found instead/);
});
method(1).subscribe(
() => { /* noop */ },
(error) => {
expect(error.message).toMatch(/parameters, 1 found instead/);
done();
});
});
it('calls the provider with the correct parameters', () => {
it('calls the provider with the correct parameters', (done) => {
// @ts-ignore private method
const method = api.createMethodSend(methods.blah);
const method = rpc.createMethodSend(methods.blah);
// Args are length-prefixed, because it's a Bytes
return method(new Uint8Array([2 << 2, 0x12, 0x34])).then(() => {
method(new Uint8Array([2 << 2, 0x12, 0x34])).subscribe(() => {
expect(provider.send).toHaveBeenCalledWith('test_blah', ['0x1234']);
done();
});
});
});
+64
View File
@@ -0,0 +1,64 @@
// Copyright 2017-2019 @polkadot/rpc-core authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { of } from 'rxjs';
import MockProvider from '@polkadot/rpc-provider/mock';
import Rpc from '.';
describe('replay', () => {
let rpc: Rpc;
beforeEach(() => {
rpc = new Rpc(new MockProvider());
});
it('subscribes via the rpc section', (done) => {
rpc.chain.getBlockHash = jest.fn(() => of(1));
rpc.chain.getBlockHash(123, false).subscribe(() => {
expect(
rpc.chain.getBlockHash
).toHaveBeenCalledWith(123, false);
done();
});
});
it('returns the observable value', (done) => {
rpc.system.chain().subscribe((value) => {
if (value) {
expect(value).toEqual('mockChain'); // Defined in MockProvider
done();
}
});
});
it('replay(1) works as expected', (done) => {
const observable = rpc.system.chain();
let a: string | undefined;
observable.subscribe((value) => { a = value; });
setTimeout(() => {
// Subscribe again to the same observable, it should fire value immediately
observable.subscribe((value) => {
expect(value).toEqual(a);
done();
});
}, 1000);
});
it('unsubscribes as required', (done) => {
rpc.provider.unsubscribe = jest.fn();
const subscription = rpc.chain.subscribeNewHead().subscribe(() => {
subscription.unsubscribe();
// There's a promise inside .unsubscribe(), wait a bit
setTimeout(() => {
expect(rpc.provider.unsubscribe).toHaveBeenCalled();
done();
}, 200);
});
});
});
+3 -4
View File
@@ -2,11 +2,10 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export interface RpcInterface$Method {
(...params: Array<any>): Promise<any>;
import { Observable } from 'rxjs';
subscription: string;
unsubscribe: (id: number) => Promise<any>;
export interface RpcInterface$Method {
(...params: Array<any>): Observable<any>;
}
export type RpcInterface$Section = {