Skip to content

Commit

Permalink
feat(): optional promisified subscribe requests
Browse files Browse the repository at this point in the history
  • Loading branch information
tiagosiebler committed Feb 17, 2025
1 parent 6d69380 commit 9120932
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 6 deletions.
9 changes: 9 additions & 0 deletions src/types/websockets/ws-general.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,15 @@ export interface WSClientConfigurableOptions {

wsUrl?: string;

/**
* Default: false.
*
* When enabled, any calls to the subscribe method will return a promise.
* Note: internally, subscription requests are sent in batches. This may not behave as expected when
* subscribing to a large number of topics, especially if you are not yet connected when subscribing.
*/
promiseSubscribeRequests?: boolean;

/**
* Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method
*
Expand Down
32 changes: 26 additions & 6 deletions src/util/BaseWSClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,15 @@ export abstract class BaseWebsocketClient<
reconnectTimeout: 500,
recvWindow: 5000,

// Calls to subscribeV5() are wrapped in a promise, allowing you to await a subscription request.
// Note: due to internal complexity, it's only recommended if you connect before subscribing.
promiseSubscribeRequests: false,

// Automatically send an authentication op/request after a connection opens, for private connections.
authPrivateConnectionsOnConnect: true,
// Individual requests do not require a signature, so this is disabled.
authPrivateRequests: false,

...options,
};
}
Expand Down Expand Up @@ -305,6 +310,9 @@ export abstract class BaseWebsocketClient<

for (const requestKey in pendingSubReqs) {
const request = pendingSubReqs[requestKey];
this.logger.trace(
`clearTopicsPendingSubscriptions(${wsKey}, ${rejectAll}, ${rejectReason}, ${requestKey}): rejecting promise for: ${JSON.stringify(request?.requestData || {})}`,
);
request?.rejector(request.requestData, rejectReason);
}
}
Expand Down Expand Up @@ -854,9 +862,11 @@ export abstract class BaseWebsocketClient<
for (const midflightRequest of subscribeWsMessages) {
const wsMessage = midflightRequest.requestEvent;

promises.push(
this.upsertPendingTopicSubscribeRequests(wsKey, midflightRequest),
);
if (this.options.promiseSubscribeRequests) {
promises.push(
this.upsertPendingTopicSubscribeRequests(wsKey, midflightRequest),
);
}

this.logger.trace(
`Sending batch via message: "${JSON.stringify(wsMessage)}"`,
Expand Down Expand Up @@ -899,9 +909,11 @@ export abstract class BaseWebsocketClient<
for (const midflightRequest of subscribeWsMessages) {
const wsMessage = midflightRequest.requestEvent;

promises.push(
this.upsertPendingTopicSubscribeRequests(wsKey, midflightRequest),
);
if (this.options.promiseSubscribeRequests) {
promises.push(
this.upsertPendingTopicSubscribeRequests(wsKey, midflightRequest),
);
}

this.logger.trace(`Sending batch via message: "${wsMessage}"`);
this.tryWsSend(wsKey, JSON.stringify(wsMessage));
Expand Down Expand Up @@ -1004,6 +1016,7 @@ export abstract class BaseWebsocketClient<
} catch (e) {
this.logger.error(
'Exception trying to resolve "connectionInProgress" promise',
e,
);
}

Expand Down Expand Up @@ -1073,6 +1086,7 @@ export abstract class BaseWebsocketClient<
} catch (e) {
this.logger.error(
'Exception trying to resolve "connectionInProgress" promise',
e,
);
}

Expand Down Expand Up @@ -1216,6 +1230,9 @@ export abstract class BaseWebsocketClient<
if (
this.wsStore.getConnectionState(wsKey) !== WsConnectionStateEnum.CLOSING
) {
this.logger.trace(
`onWsClose(${wsKey}): rejecting all deferred promises...`,
);
// clean up any pending promises for this connection
this.getWsStore().rejectAllDeferredPromises(
wsKey,
Expand All @@ -1230,6 +1247,9 @@ export abstract class BaseWebsocketClient<
this.emit('reconnect', { wsKey, event });
} else {
// clean up any pending promises for this connection
this.logger.trace(
`onWsClose(${wsKey}): rejecting all deferred promises...`,
);
this.getWsStore().rejectAllDeferredPromises(wsKey, 'disconnected');
this.setWsState(wsKey, WsConnectionStateEnum.INITIAL);
this.emit('close', { wsKey, event });
Expand Down
3 changes: 3 additions & 0 deletions src/util/websockets/WsStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,9 @@ export class WsStore<
const promise = this.getDeferredPromise(wsKey, promiseRef);

if (promise?.reject) {
this.logger.trace(
`rejectDeferredPromise(): rejecting ${wsKey}/${promiseRef}/${value}`,
);
promise.reject(value);
}

Expand Down

0 comments on commit 9120932

Please sign in to comment.