First stage renames, rpc-{core,provider,rx} (#220)
* Docs renames (& removal for re-gen) * Rename api, api-provider & api-rx * Apoi -> Rpc, RxApi -> RpcRx (classes) * Add .nodoc * Bump version * Link updates (summary) * Cleanup deleted (master version) * Deleted re-instated * More... ;) * Types... * Revert .nodoc
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
|
||||
import mocks from './mocks';
|
||||
import on from './on';
|
||||
import send from './send';
|
||||
import state from './state';
|
||||
import subscribe from './subscribe';
|
||||
import unsubscribe from './unsubscribe';
|
||||
|
||||
/**
|
||||
* A moock provider mainly used for testing.
|
||||
* @return {ProviderInterface} The mock provider
|
||||
*/
|
||||
export default function mockProvider (): ProviderInterface {
|
||||
const self = state();
|
||||
|
||||
mocks(self);
|
||||
|
||||
return {
|
||||
isConnected: (): boolean =>
|
||||
true,
|
||||
on: (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void =>
|
||||
on(self, type, sub),
|
||||
send: (method: string, params: Array<any>): Promise<any> =>
|
||||
send(self, method, params),
|
||||
subscribe: (type: string, method: string, ...params: Array<any>): Promise<number> =>
|
||||
subscribe(self, type, method, params),
|
||||
unsubscribe: (type: string, method: string, id: number): Promise<boolean> =>
|
||||
unsubscribe(self, type, method, id)
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
// FIXME: This file is way too long and way too messy
|
||||
|
||||
import { StorageFunction } from '@polkadot/types/StorageKey';
|
||||
import { KeyringPair } from '@polkadot/util-keyring/types';
|
||||
import { ProviderInterface$Emitted } from '../types';
|
||||
import { MockState, MockState$Db, MockState$Subscriptions } from './types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import storage from '@polkadot/storage/static';
|
||||
import Header from '@polkadot/types/Header';
|
||||
import bnToU8a from '@polkadot/util/bn/toU8a';
|
||||
import u8aToHex from '@polkadot/util/u8a/toHex';
|
||||
import randomAsU8a from '@polkadot/util-crypto/random/asU8a';
|
||||
import testKeyring from '@polkadot/util-keyring/testing';
|
||||
|
||||
const keyring = testKeyring();
|
||||
|
||||
const emitEvents: Array<ProviderInterface$Emitted> = ['connected', 'disconnected'];
|
||||
let emitIndex = 0;
|
||||
|
||||
function makeBlockHeader (prevNumber: BN) {
|
||||
const blockNumber = prevNumber.addn(1);
|
||||
|
||||
return {
|
||||
digest: {
|
||||
logs: []
|
||||
},
|
||||
extrinsicsRoot: randomAsU8a(),
|
||||
number: blockNumber,
|
||||
parentHash: prevNumber.eqn(-1)
|
||||
? new Uint8Array(32)
|
||||
: bnToU8a(prevNumber, 256, false),
|
||||
stateRoot: bnToU8a(blockNumber, 256, false)
|
||||
};
|
||||
}
|
||||
|
||||
function updateSubs (subscriptions: MockState$Subscriptions, method: string, value: any) {
|
||||
subscriptions[method].lastValue = value;
|
||||
|
||||
Object
|
||||
.values(subscriptions[method].callbacks)
|
||||
.forEach((cb) => {
|
||||
try {
|
||||
cb(null, value);
|
||||
} catch (error) {
|
||||
console.error(`Error on '${method}' subscription`, error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function setStorageBn (db: MockState$Db, createKey: StorageFunction, value: BN | number, ...keyParams: Array<Uint8Array>): void {
|
||||
const keyValue = u8aToHex(
|
||||
createKey(...keyParams)
|
||||
);
|
||||
|
||||
db[keyValue] = bnToU8a(value, 64, true);
|
||||
}
|
||||
|
||||
export default function mocks ({ emitter, db, subscriptions }: MockState): void {
|
||||
let newHead = makeBlockHeader(new BN(-1));
|
||||
|
||||
setInterval(() => {
|
||||
if (++emitIndex === emitEvents.length) {
|
||||
emitIndex = 0;
|
||||
}
|
||||
|
||||
emitter.emit(emitEvents[emitIndex]);
|
||||
|
||||
newHead = makeBlockHeader(newHead.number);
|
||||
|
||||
keyring.getPairs().forEach(({ publicKey }: KeyringPair, index: number) => {
|
||||
setStorageBn(db, storage.balances.freeBalance, newHead.number.muln(3).iaddn(index), publicKey());
|
||||
setStorageBn(db, storage.system.accountNonce, newHead.number.addn(index), publicKey());
|
||||
});
|
||||
|
||||
setStorageBn(db, storage.timestamp.now, Math.floor(Date.now() / 1000));
|
||||
|
||||
updateSubs(subscriptions, 'chain_newHead', new Header(newHead).toJSON());
|
||||
}, 5000);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
import { MockState } from './types';
|
||||
|
||||
export default function on (self: MockState, type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
|
||||
self.emitter.on(type, sub);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { MockState } from './types';
|
||||
|
||||
export default async function send ({ requests, db }: MockState, method: string, params: Array<any>): Promise<any> {
|
||||
if (!requests[method]) {
|
||||
throw new Error(`provider.send: Invalid method '${method}'`);
|
||||
}
|
||||
|
||||
return requests[method](db, params);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import createState from './state';
|
||||
|
||||
describe('state', () => {
|
||||
let state;
|
||||
|
||||
beforeEach(() => {
|
||||
state = createState();
|
||||
});
|
||||
|
||||
it('generates a sane initial state', () => {
|
||||
expect(
|
||||
state
|
||||
).toMatchObject({
|
||||
subscriptionId: 0,
|
||||
subscriptionMap: {}
|
||||
});
|
||||
});
|
||||
|
||||
it('generates a proper section_method map', () => {
|
||||
expect(
|
||||
state.subscriptions
|
||||
).toMatchObject({
|
||||
'chain_newHead': {
|
||||
callbacks: {},
|
||||
lastValue: null
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { MockState, MockState$Db, MockState$Subscriptions } from './types';
|
||||
|
||||
import E3 from 'eventemitter3';
|
||||
import interfaces from '@polkadot/jsonrpc/index';
|
||||
import u8aToHex from '@polkadot/util/u8a/toHex';
|
||||
import logger from '@polkadot/util/logger';
|
||||
|
||||
const l = logger('api-mock');
|
||||
|
||||
const SUBSCRIPTIONS: string[] = Array.prototype.concat.apply(
|
||||
[], Object.values(interfaces).map((area) =>
|
||||
Object
|
||||
.values(area.methods)
|
||||
.filter((method) =>
|
||||
method.isSubscription
|
||||
)
|
||||
.map(({ method, section }) =>
|
||||
`${section}_${method}`
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
const REQUESTS = {
|
||||
'state_getStorage': (storage: MockState$Db, params: Array<any>): string => {
|
||||
return u8aToHex(
|
||||
storage[(params[0] as string)]
|
||||
);
|
||||
},
|
||||
'system_chain': (): string => 'mockChain',
|
||||
'system_name': (): string => 'mockClient',
|
||||
'system_version': (): string => '9.8.7'
|
||||
};
|
||||
|
||||
export default function state (): MockState {
|
||||
const db = {};
|
||||
const subscriptions: MockState$Subscriptions = SUBSCRIPTIONS.reduce((subs, name) => {
|
||||
subs[name] = {
|
||||
callbacks: {},
|
||||
lastValue: null
|
||||
};
|
||||
|
||||
return subs;
|
||||
}, ({} as MockState$Subscriptions));
|
||||
|
||||
return {
|
||||
emitter: new E3.EventEmitter(),
|
||||
l,
|
||||
requests: Object.assign({}, REQUESTS),
|
||||
db,
|
||||
subscriptionId: 0,
|
||||
subscriptionMap: {},
|
||||
subscriptions
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import createState from './state';
|
||||
import subscribe from './subscribe';
|
||||
|
||||
describe('subscribe', () => {
|
||||
let state;
|
||||
|
||||
beforeEach(() => {
|
||||
state = createState();
|
||||
});
|
||||
|
||||
it('fails on unknown methods', () => {
|
||||
return subscribe(state, 'test', 'test_notFound').catch((error) => {
|
||||
expect(error.message).toMatch(/Invalid method 'test_notFound'/);
|
||||
});
|
||||
});
|
||||
|
||||
it('returns a subscription id', () => {
|
||||
return subscribe(state, 'chain_newHead', 'chain_newHead', [() => void 0]).then((id) => {
|
||||
expect(id).toEqual(state.subscriptionId);
|
||||
});
|
||||
});
|
||||
|
||||
it('stores the mapping values', () => {
|
||||
const cb = () => void 0;
|
||||
|
||||
return subscribe(state, 'chain_newHead', '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_newHead'].lastValue = 'testValue';
|
||||
|
||||
subscribe(state, 'chain_newHead', 'chain_newHead', [(_, value) => {
|
||||
expect(value).toEqual('testValue');
|
||||
done();
|
||||
}]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { MockState, MockState$Subscription$Callback } from './types';
|
||||
|
||||
export default async function subscribe (self: MockState, type: string, method: string, params: Array<any>): Promise<number> {
|
||||
self.l.debug(() => ['subscribe', method, params]);
|
||||
|
||||
if (self.subscriptions[method]) {
|
||||
const callback: MockState$Subscription$Callback = params.pop();
|
||||
const id = ++self.subscriptionId;
|
||||
|
||||
self.subscriptions[method].callbacks[id] = callback;
|
||||
self.subscriptionMap[id] = method;
|
||||
|
||||
callback(null, self.subscriptions[method].lastValue);
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
throw new Error(`provider.subscribe: Invalid method '${method}'`);
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import EventEmitter from 'eventemitter3';
|
||||
import { Logger } from '@polkadot/util/types';
|
||||
|
||||
export type MockState$Subscription$Callback = (error: Error | null, value: any) => void;
|
||||
|
||||
export type MockState$Subscriptions = {
|
||||
[index: string]: {
|
||||
callbacks: {
|
||||
[index: number]: MockState$Subscription$Callback
|
||||
},
|
||||
lastValue: any
|
||||
}
|
||||
};
|
||||
|
||||
export type MockState$Db = {
|
||||
[index: string]: Uint8Array
|
||||
};
|
||||
|
||||
export type MockState$Requests = {
|
||||
[index: string]: (db: MockState$Db, params: Array<any>) => string
|
||||
};
|
||||
|
||||
export type MockState = {
|
||||
emitter: EventEmitter,
|
||||
l: Logger,
|
||||
requests: MockState$Requests,
|
||||
db: MockState$Db,
|
||||
subscriptionId: number,
|
||||
subscriptionMap: {
|
||||
[index: number]: string
|
||||
},
|
||||
subscriptions: MockState$Subscriptions
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import createState from './state';
|
||||
import subscribe from './subscribe';
|
||||
import unsubscribe from './unsubscribe';
|
||||
|
||||
describe('unsubscribe', () => {
|
||||
let state;
|
||||
let id;
|
||||
|
||||
beforeEach(() => {
|
||||
state = createState();
|
||||
|
||||
return subscribe(state, 'chain_newHead', 'chain_newHead', [() => void 0]).then((_id) => {
|
||||
id = _id;
|
||||
});
|
||||
});
|
||||
|
||||
it('fails on unknown ids', () => {
|
||||
return unsubscribe(state, 'chain_newHead', 'chain_newHead', 5).catch((error) => {
|
||||
expect(error.message).toMatch(/Unable to find/);
|
||||
});
|
||||
});
|
||||
|
||||
it('unsubscribes successfully', () => {
|
||||
return unsubscribe(state, 'chain_newHead', 'chain_newHead', id);
|
||||
});
|
||||
|
||||
it('fails on double unsubscribe', () => {
|
||||
return unsubscribe(state, 'chain_newHead', 'chain_newHead', id)
|
||||
.then(() => unsubscribe(state, id))
|
||||
.catch((error) => {
|
||||
expect(error.message).toMatch(/Unable to find/);
|
||||
});
|
||||
});
|
||||
|
||||
it('clears the subscriptions', () => {
|
||||
return unsubscribe(state, 'chain_newHead', 'chain_newHead', id).then(() => {
|
||||
expect(state.subscriptionMap[id]).not.toBeDefined();
|
||||
expect(state.subscriptions['chain_newHead'].callbacks[id]).not.toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { MockState } from './types';
|
||||
|
||||
export default async function unsubscribe (self: MockState, type: string, name: string, id: number): Promise<boolean> {
|
||||
const method = self.subscriptionMap[id];
|
||||
|
||||
self.l.debug(() => ['unsubscribe', id, method]);
|
||||
|
||||
if (!method) {
|
||||
throw new Error(`Unable to find subscription for ${id}`);
|
||||
}
|
||||
|
||||
delete self.subscriptionMap[id];
|
||||
delete self.subscriptions[method].callbacks[id];
|
||||
|
||||
return true;
|
||||
}
|
||||
Reference in New Issue
Block a user