diff --git a/CHANGELOG.md b/CHANGELOG.md index b5f8cd5061..43dc9ed95c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Changes: +- Add internal merge of single storage queries - Expose provider stats on API intrerface via `.stats` - Adjust flag extraction for latest phragmen types - Add Kusama 9220 upgrade block diff --git a/packages/api/src/base/Decorate.ts b/packages/api/src/base/Decorate.ts index 62c907e542..c7a3dc6199 100644 --- a/packages/api/src/base/Decorate.ts +++ b/packages/api/src/base/Decorate.ts @@ -44,6 +44,7 @@ interface FullDecoration { // the max amount of keys/values that we will retrieve at once const PAGE_SIZE_K = 1000; // limit aligned with the 1k on the node (trie lookups are heavy) const PAGE_SIZE_V = 250; // limited since the data may be very large (e.g. misfiring elections) +const PAGE_SIZE_Q = 10; // queue of storage entry queries, mapped together const l = logger('api/init'); @@ -58,6 +59,10 @@ export abstract class Decorate extends Events { #registry: Registry; + #storageGetQ: [[StorageEntry, ...unknown[]][], Observable][] = []; + + #storageSubQ: [[StorageEntry, ...unknown[]][], Observable][] = []; + // HACK Use BN import so decorateDerive works... yes, wtf. protected __phantom = new BN(0); @@ -401,18 +406,33 @@ export abstract class Decorate extends Events { // only be called if supportMulti is true protected _decorateMulti (decorateMethod: DecorateMethod): QueryableStorageMulti { // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return decorateMethod((calls: QueryableStorageMultiArg[]): Observable => - (this.hasSubscriptions + return decorateMethod((keys: QueryableStorageMultiArg[]): Observable => { + const query = this.hasSubscriptions ? this._rpcCore.state.subscribeStorage - : this._rpcCore.state.queryStorageAt)( - calls.map((args: QueryableStorageMultiArg) => - Array.isArray(args) - ? args[0].creator.meta.type.isPlain - ? [args[0].creator] - : args[0].creator.meta.type.asMap.hashers.length === 1 - ? [args[0].creator, args.slice(1)] - : [args[0].creator, ...args.slice(1)] - : [args.creator]))); + : this._rpcCore.state.queryStorageAt; + + const calls = keys.map((args: QueryableStorageMultiArg): [StorageEntry, ...unknown[]] => + Array.isArray(args) + ? args[0].creator.meta.type.isPlain + ? [args[0].creator] + : args[0].creator.meta.type.asMap.hashers.length === 1 + ? [args[0].creator, args.slice(1)] + : [args[0].creator, ...args.slice(1)] + : [args.creator] + ); + + // with a smaller number of keys we combine this into a queue + // along with other ongoing queries + if (calls.length <= PAGE_SIZE_Q) { + const queue = this.hasSubscriptions + ? this.#storageSubQ + : this.#storageGetQ; + + return this._queuedStorage(calls, queue, query); + } + + return query(calls); + }); } protected _decorateMultiAt (atApi: ApiDecoration, decorateMethod: DecorateMethod, blockHash: Uint8Array | string): QueryableStorageMulti { @@ -633,18 +653,79 @@ export abstract class Decorate extends Events { return this._decorateFunctionMeta(creator as unknown as MetaDecoration, decorated) as unknown as QueryableStorageEntry; } + private _queuedStorage (calls: [StorageEntry, ...unknown[]][], queue: [[StorageEntry, ...unknown[]][], Observable][], query: (calls: unknown[]) => Observable): Observable { + const count = calls.length; + let queueIdx = queue.length - 1; + + if (queueIdx === -1 || !queue[queueIdx] || queue[queueIdx][0].length === PAGE_SIZE_Q || count >= PAGE_SIZE_Q) { + queueIdx++; + + queue.push([[], from( + // slightly faster than setTimeout(..., 0) + Promise + .resolve() + .then((): [StorageEntry, ...unknown[]][] => { + const [calls] = queue[queueIdx]; + + delete queue[queueIdx]; + + return calls; + }) + .catch(() => []) + ).pipe( + switchMap((calls) => + query(calls) + ) + )]); + } + + const valueIdx = queue[queueIdx][0].length; + const valueObs = queue[queueIdx][1]; + + for (let i = 0; i < count; i++) { + queue[queueIdx][0].push(calls[i]); + } + + return valueObs.pipe( + map((values): Codec[] => { + if (valueIdx === 0 && values.length === count) { + return values; + } else if (count === 1) { + return [values[valueIdx]]; + } + + const result = new Array(count); + + for (let i = 0; i < count; i++) { + result[i] = values[valueIdx + i]; + } + + return result; + }) + ); + } + + private _queuedStorageSingle (call: [StorageEntry, ...unknown[]], queue: [[StorageEntry, ...unknown[]][], Observable][], query: (calls: unknown[]) => Observable): Observable { + return this._queuedStorage([call], queue, query).pipe( + map(([first]) => first) + ); + } + // Decorate the base storage call. In the case or rxjs or promise-without-callback (await) // we make a subscription, alternatively we push this through a single-shot query private _decorateStorageCall (creator: StorageEntry, decorateMethod: DecorateMethod): ReturnType> { return decorateMethod((...args: unknown[]): Observable => { - return this.hasSubscriptions - ? this._rpcCore.state.subscribeStorage<[Codec]>([extractStorageArgs(this.#registry, creator, args)]).pipe( - map(([data]) => data) // extract first/only result from list - ) - : this._rpcCore.state.getStorage(extractStorageArgs(this.#registry, creator, args)); + const call = extractStorageArgs(this.#registry, creator, args); + + if (!this.hasSubscriptions) { + return this._rpcCore.state.getStorage(call); + } + + return this._queuedStorageSingle(call, this.#storageSubQ, this._rpcCore.state.subscribeStorage); }, { methodName: creator.method, - overrideNoSub: (...args: unknown[]) => this._rpcCore.state.getStorage(extractStorageArgs(this.#registry, creator, args)) + overrideNoSub: (...args: unknown[]) => + this._queuedStorageSingle(extractStorageArgs(this.#registry, creator, args), this.#storageGetQ, this._rpcCore.state.queryStorageAt) }); } @@ -667,15 +748,25 @@ export abstract class Decorate extends Events { return of([]); } - const queryCall = this.hasSubscriptions && !blockHash + const query = this.hasSubscriptions && !blockHash ? this._rpcCore.state.subscribeStorage : this._rpcCore.state.queryStorageAt; + // Where we have a limited number of multi keys, we combine + // this query with others that precedes it (same tick) + if (!blockHash && keys.length <= PAGE_SIZE_Q) { + const queue = this.hasSubscriptions + ? this.#storageSubQ + : this.#storageGetQ; + + return this._queuedStorage(keys, queue, query); + } + return combineLatest( arrayChunk(keys, PAGE_SIZE_V).map((k) => blockHash - ? queryCall(k, blockHash) - : queryCall(k) + ? query(k, blockHash) + : query(k) ) ).pipe( map(arrayFlatten) @@ -696,11 +787,15 @@ export abstract class Decorate extends Events { switchMap(getKeysPaged), map((keys) => keys.map(setMeta)), tap((keys): void => { - setTimeout((): void => { - keys.length === PAGE_SIZE_K - ? startSubject.next(keys[PAGE_SIZE_K - 1].toHex()) - : startSubject.complete(); - }, 0); + // slightly faster than setTimeout(..., 0) + Promise + .resolve() + .then((): void => { + keys.length === PAGE_SIZE_K + ? startSubject.next(keys[PAGE_SIZE_K - 1].toHex()) + : startSubject.complete(); + }) + .catch(console.error); }), toArray(), // toArray since we want to startSubject to be completed map(arrayFlatten) diff --git a/packages/api/src/promise/decorateMethod.ts b/packages/api/src/promise/decorateMethod.ts index 66c0b4083e..9e5ad37840 100644 --- a/packages/api/src/promise/decorateMethod.ts +++ b/packages/api/src/promise/decorateMethod.ts @@ -75,7 +75,12 @@ function decorateCall>> (method: M, args ) .subscribe((result): void => { tracker.resolve(result); - setTimeout(() => subscription.unsubscribe(), 0); + + // slightly faster than setTimeout(..., 0) + Promise + .resolve() + .then(() => subscription.unsubscribe()) + .catch(console.error); }); }); } @@ -94,7 +99,11 @@ function decorateSubscribe>> (method: M, ) .subscribe((result): void => { // queue result (back of queue to clear current) - setTimeout(() => resultCb(result) as void, 0); + // slightly faster than setTimeout(..., 0) + Promise + .resolve() + .then(() => resultCb(result)) + .catch(console.error); }); }); }