This repository was archived by the owner on Oct 16, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 82
Suggestion to simplify prevention of dangling Promise on destroy #286
Merged
mikesposito
merged 2 commits into
fix/internal-listeners
from
fix/internal-listeners-suggestion
Nov 26, 2024
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,10 @@ | ||
| import type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider'; | ||
| import SafeEventEmitter from '@metamask/safe-event-emitter'; | ||
| import { getErrorMessage, type JsonRpcRequest } from '@metamask/utils'; | ||
| import { | ||
| createDeferredPromise, | ||
| getErrorMessage, | ||
| type JsonRpcRequest, | ||
| } from '@metamask/utils'; | ||
| import getCreateRandomId from 'json-rpc-random-id'; | ||
|
|
||
| import type { BlockTracker } from './BlockTracker'; | ||
|
|
@@ -26,7 +30,7 @@ interface ExtendedJsonRpcRequest extends JsonRpcRequest<[]> { | |
| skipCache?: boolean; | ||
| } | ||
|
|
||
| type InternalListener = (value: string | PromiseLike<string>) => void; | ||
| type InternalListener = (value: string) => void; | ||
|
|
||
| export class PollingBlockTracker | ||
| extends SafeEventEmitter | ||
|
|
@@ -56,6 +60,10 @@ export class PollingBlockTracker | |
|
|
||
| readonly #internalEventListeners: InternalListener[] = []; | ||
|
|
||
| #pendingLatestBlock: | ||
| | { promise: Promise<string>; reject: (error: unknown) => void } | ||
| | undefined; | ||
|
|
||
| constructor(opts: PollingBlockTrackerOptions = {}) { | ||
| // parse + validate args | ||
| if (!opts.provider) { | ||
|
|
@@ -91,19 +99,10 @@ export class PollingBlockTracker | |
| async destroy() { | ||
| this._cancelBlockResetTimeout(); | ||
| this._maybeEnd(); | ||
| this.eventNames().forEach((eventName) => | ||
| this.listeners(eventName).forEach((listener) => { | ||
| if ( | ||
| this.#internalEventListeners.every( | ||
| (internalListener) => !Object.is(internalListener, listener), | ||
| ) | ||
| ) { | ||
| // @ts-expect-error this listener comes from SafeEventEmitter itself, though | ||
| // its type differs between `.listeners()` and `.removeListener()` | ||
| this.removeListener(eventName, listener); | ||
| } | ||
| }), | ||
| ); | ||
| this.removeAllListeners(); | ||
| if (this.#pendingLatestBlock) { | ||
| this.#pendingLatestBlock.reject(new Error('Block tracker destroeyd')); | ||
| } | ||
| } | ||
|
|
||
| isRunning(): boolean { | ||
|
|
@@ -118,37 +117,24 @@ export class PollingBlockTracker | |
| // return if available | ||
| if (this._currentBlock) { | ||
| return this._currentBlock; | ||
| } else if (this.#pendingLatestBlock) { | ||
| return await this.#pendingLatestBlock.promise; | ||
| } | ||
| // wait for a new latest block | ||
| const latestBlock: string = await new Promise((resolve, reject) => { | ||
| // eslint-disable-next-line prefer-const | ||
| let onLatestBlockUnavailable: InternalListener; | ||
| const onLatestBlockAvailable = (value: string | PromiseLike<string>) => { | ||
| this.#removeInternalListener(onLatestBlockAvailable); | ||
| this.#removeInternalListener(onLatestBlockUnavailable); | ||
| this.removeListener('error', onLatestBlockUnavailable); | ||
| resolve(value); | ||
| }; | ||
| onLatestBlockUnavailable = () => { | ||
| // if the block tracker is no longer running, reject | ||
| // and remove the listeners | ||
| if (!this._isRunning) { | ||
| this.#removeInternalListener(onLatestBlockAvailable); | ||
| this.#removeInternalListener(onLatestBlockUnavailable); | ||
| this.removeListener('latest', onLatestBlockAvailable); | ||
| this.removeListener('error', onLatestBlockUnavailable); | ||
| reject( | ||
| new Error('Block tracker ended before latest block was available'), | ||
| ); | ||
| } | ||
| }; | ||
| this.#addInternalListener(onLatestBlockAvailable); | ||
| this.#addInternalListener(onLatestBlockUnavailable); | ||
| this.once('latest', onLatestBlockAvailable); | ||
| this.on('error', onLatestBlockUnavailable); | ||
|
|
||
| const { promise, resolve, reject } = createDeferredPromise<string>({ | ||
| suppressUnhandledRejection: true, | ||
| }); | ||
| // return newly set current block | ||
| return latestBlock; | ||
| this.#pendingLatestBlock = { promise, reject }; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm wondering, if we are making this promise available to the rest of the class, would it make sense to also resolve it through this class variable and get rid of the internal listener altogether?
This comment was marked as resolved.
Sorry, something went wrong.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. True, yeah maybe so, good idea |
||
|
|
||
| // wait for a new latest block | ||
| const onLatestBlock = (value: string) => { | ||
| this.#removeInternalListener(onLatestBlock); | ||
| resolve(value); | ||
|
Gudahtt marked this conversation as resolved.
|
||
| delete this.#pendingLatestBlock; | ||
| }; | ||
| this.#addInternalListener(onLatestBlock); | ||
| this.once('latest', onLatestBlock); | ||
|
Gudahtt marked this conversation as resolved.
|
||
| return await promise; | ||
| } | ||
|
|
||
| // dont allow module consumer to remove our internal event listeners | ||
|
|
@@ -345,15 +331,6 @@ export class PollingBlockTracker | |
|
|
||
| try { | ||
| this.emit('error', newErr); | ||
| if ( | ||
| this.listeners('error').filter((listener) => | ||
| this.#internalEventListeners.every( | ||
| (internalListener) => !Object.is(listener, internalListener), | ||
| ), | ||
| ).length === 0 | ||
| ) { | ||
| console.error(newErr); | ||
| } | ||
| } catch (emitErr) { | ||
| console.error(newErr); | ||
| } | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah, good catch here. I was thinking of also using a deferred promise and keeping it in a private field, but it seemed that calling
getLatestBlockmultiple times without waiting would overwrite that field. This is a good solution.