-
Notifications
You must be signed in to change notification settings - Fork 306
feat(lazer): Improve JS SDK reliability via redundant parallel websocket cxns #2236
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
05f85b9
feat: improve js sdk reliability via redundant parallel websocket cxns
tejasbadadare 79b685a
doc: update comment
tejasbadadare 1e1c2ea
feat: add error handler, bump ver
tejasbadadare 5aec239
feat: improve promise handling, fix eslint
tejasbadadare 9f1da48
fix: eslint
tejasbadadare dc8a145
doc: fix comment
tejasbadadare 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
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
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 |
|---|---|---|
|
|
@@ -9,6 +9,8 @@ | |
| type Response, | ||
| SOLANA_FORMAT_MAGIC_BE, | ||
| } from "./protocol.js"; | ||
| import { WebSocketPool } from "./socket/WebSocketPool.js"; | ||
| import { dummyLogger, type Logger } from "ts-log"; | ||
|
|
||
| export type BinaryResponse = { | ||
| subscriptionId: number; | ||
|
|
@@ -28,52 +30,58 @@ | |
| const UINT64_NUM_BYTES = 8; | ||
|
|
||
| export class PythLazerClient { | ||
| ws: WebSocket; | ||
| wsp: WebSocketPool; | ||
|
|
||
| constructor(url: string, token: string) { | ||
| const finalUrl = new URL(url); | ||
| finalUrl.searchParams.append("ACCESS_TOKEN", token); | ||
| this.ws = new WebSocket(finalUrl); | ||
| /** | ||
| * Creates a new PythLazerClient instance. | ||
| * @param urls List of WebSocket URLs of the Pyth Lazer service | ||
|
Check failure on line 37 in lazer/sdk/js/src/client.ts
|
||
| * @param token The access token for authentication | ||
| * @param numConnections The number of parallel WebSocket connections to establish (default: 3). A higher number gives a more reliable stream. | ||
| * @param logger Optional logger to get socket level logs. Compatible with most loggers such as the built-in console and `bunyan`. | ||
| */ | ||
| constructor( | ||
| urls: string[], | ||
| token: string, | ||
| numConnections: number = 3, | ||
| logger: Logger = dummyLogger | ||
| ) { | ||
| this.wsp = new WebSocketPool(urls, token, numConnections, logger); | ||
| } | ||
|
|
||
| addMessageListener(handler: (event: JsonOrBinaryResponse) => void) { | ||
| this.ws.addEventListener("message", (event: WebSocket.MessageEvent) => { | ||
| if (typeof event.data == "string") { | ||
| this.wsp.addMessageListener((data: WebSocket.Data) => { | ||
| if (typeof data == "string") { | ||
| handler({ | ||
| type: "json", | ||
| value: JSON.parse(event.data) as Response, | ||
| value: JSON.parse(data) as Response, | ||
| }); | ||
| } else if (Buffer.isBuffer(event.data)) { | ||
| } else if (Buffer.isBuffer(data)) { | ||
| let pos = 0; | ||
| const magic = event.data | ||
| .subarray(pos, pos + UINT32_NUM_BYTES) | ||
| .readUint32BE(); | ||
| const magic = data.subarray(pos, pos + UINT32_NUM_BYTES).readUint32BE(); | ||
| pos += UINT32_NUM_BYTES; | ||
| if (magic != BINARY_UPDATE_FORMAT_MAGIC) { | ||
| throw new Error("binary update format magic mismatch"); | ||
| } | ||
| // TODO: some uint64 values may not be representable as Number. | ||
| const subscriptionId = Number( | ||
| event.data.subarray(pos, pos + UINT64_NUM_BYTES).readBigInt64BE() | ||
| data.subarray(pos, pos + UINT64_NUM_BYTES).readBigInt64BE() | ||
| ); | ||
| pos += UINT64_NUM_BYTES; | ||
|
|
||
| const value: BinaryResponse = { subscriptionId }; | ||
| while (pos < event.data.length) { | ||
| const len = event.data | ||
| .subarray(pos, pos + UINT16_NUM_BYTES) | ||
| .readUint16BE(); | ||
| while (pos < data.length) { | ||
| const len = data.subarray(pos, pos + UINT16_NUM_BYTES).readUint16BE(); | ||
| pos += UINT16_NUM_BYTES; | ||
| const magic = event.data | ||
| const magic = data | ||
| .subarray(pos, pos + UINT32_NUM_BYTES) | ||
| .readUint32BE(); | ||
| if (magic == EVM_FORMAT_MAGIC) { | ||
| value.evm = event.data.subarray(pos, pos + len); | ||
| value.evm = data.subarray(pos, pos + len); | ||
| } else if (magic == SOLANA_FORMAT_MAGIC_BE) { | ||
| value.solana = event.data.subarray(pos, pos + len); | ||
| value.solana = data.subarray(pos, pos + len); | ||
| } else if (magic == PARSED_FORMAT_MAGIC) { | ||
| value.parsed = JSON.parse( | ||
| event.data.subarray(pos + UINT32_NUM_BYTES, pos + len).toString() | ||
| data.subarray(pos + UINT32_NUM_BYTES, pos + len).toString() | ||
| ) as ParsedPayload; | ||
| } else { | ||
| throw new Error("unknown magic: " + magic.toString()); | ||
|
|
@@ -87,7 +95,22 @@ | |
| }); | ||
| } | ||
|
|
||
| subscribe(request: Request) { | ||
| if (request.type !== "subscribe") { | ||
| throw new Error("Request must be a subscribe request"); | ||
| } | ||
| this.wsp.addSubscription(request); | ||
| } | ||
|
|
||
| unsubscribe(subscriptionId: number) { | ||
| this.wsp.removeSubscription(subscriptionId); | ||
| } | ||
|
|
||
| send(request: Request) { | ||
| this.ws.send(JSON.stringify(request)); | ||
| this.wsp.sendRequest(request); | ||
| } | ||
|
|
||
| shutdown(): void { | ||
| this.wsp.shutdown(); | ||
| } | ||
| } | ||
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 |
|---|---|---|
| @@ -0,0 +1,183 @@ | ||
| import WebSocket, { type ClientOptions } from "isomorphic-ws"; | ||
| import type { ClientRequestArgs } from "node:http"; | ||
| import type { Logger } from "ts-log"; | ||
|
|
||
| // Reconnect with expo backoff if we don't get a message or ping for 10 seconds | ||
| const HEARTBEAT_TIMEOUT_DURATION = 10000; | ||
|
|
||
| /** | ||
| * This class wraps websocket to provide a resilient web socket client. | ||
| * | ||
| * It will reconnect if connection fails with exponential backoff. Also, it will reconnect | ||
| * if it receives no ping request or regular message from server within a while as indication | ||
| * of timeout (assuming the server sends either regularly). | ||
| * | ||
| * This class also logs events if logger is given and by replacing onError method you can handle | ||
| * connection errors yourself (e.g: do not retry and close the connection). | ||
| */ | ||
| export class ResilientWebSocket { | ||
tejasbadadare marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| endpoint: string; | ||
| wsClient: undefined | WebSocket; | ||
| wsUserClosed: boolean; | ||
| private wsOptions: ClientOptions | ClientRequestArgs | undefined; | ||
| private wsFailedAttempts: number; | ||
| private heartbeatTimeout: undefined | NodeJS.Timeout; | ||
| private logger: undefined | Logger; | ||
|
|
||
| onError: (error: Error) => void; | ||
| onMessage: (data: WebSocket.Data) => void; | ||
| onReconnect: () => void; | ||
| constructor( | ||
| endpoint: string, | ||
| wsOptions?: ClientOptions | ClientRequestArgs, | ||
| logger?: Logger | ||
| ) { | ||
| this.endpoint = endpoint; | ||
| this.wsOptions = wsOptions; | ||
| this.logger = logger; | ||
|
|
||
| this.wsFailedAttempts = 0; | ||
| this.onError = (error: Error) => { | ||
| this.logger?.error(error); | ||
| }; | ||
| this.wsUserClosed = true; | ||
| this.onMessage = () => {}; | ||
| this.onReconnect = () => {}; | ||
| } | ||
|
|
||
| async send(data: any) { | ||
| this.logger?.info(`Sending ${data}`); | ||
|
|
||
| await this.waitForMaybeReadyWebSocket(); | ||
|
|
||
| if (this.wsClient === undefined) { | ||
| this.logger?.error( | ||
| "Couldn't connect to the websocket server. Error callback is called." | ||
| ); | ||
| } else { | ||
| this.wsClient?.send(data); | ||
| } | ||
| } | ||
|
|
||
| async startWebSocket() { | ||
| if (this.wsClient !== undefined) { | ||
| return; | ||
| } | ||
|
|
||
| this.logger?.info(`Creating Web Socket client`); | ||
|
|
||
| this.wsClient = new WebSocket(this.endpoint, this.wsOptions); | ||
| this.wsUserClosed = false; | ||
|
|
||
| this.wsClient.onopen = () => { | ||
| this.wsFailedAttempts = 0; | ||
| this.resetHeartbeat(); | ||
| }; | ||
|
|
||
| this.wsClient.onerror = (event) => { | ||
| this.onError(event.error); | ||
| }; | ||
|
|
||
| this.wsClient.onmessage = (event) => { | ||
| this.resetHeartbeat(); | ||
| this.onMessage(event.data); | ||
| }; | ||
|
|
||
| this.wsClient.onclose = async () => { | ||
| if (this.heartbeatTimeout !== undefined) { | ||
| clearTimeout(this.heartbeatTimeout); | ||
| } | ||
|
|
||
| if (this.wsUserClosed === false) { | ||
| this.wsFailedAttempts += 1; | ||
| this.wsClient = undefined; | ||
| const waitTime = expoBackoff(this.wsFailedAttempts); | ||
|
|
||
| this.logger?.error( | ||
| `Connection closed unexpectedly or because of timeout. Reconnecting after ${waitTime}ms.` | ||
| ); | ||
|
|
||
| await sleep(waitTime); | ||
| this.restartUnexpectedClosedWebsocket(); | ||
| } else { | ||
| this.logger?.info("The connection has been closed successfully."); | ||
| } | ||
| }; | ||
|
|
||
| if (this.wsClient.on !== undefined) { | ||
| // Ping handler is undefined in browser side | ||
| this.wsClient.on("ping", () => { | ||
| this.logger?.info("Ping received"); | ||
| this.resetHeartbeat(); | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Reset the heartbeat timeout. This is called when we receive any message (ping or regular) | ||
| * from the server. If we don't receive any message within HEARTBEAT_TIMEOUT_DURATION, | ||
| * we assume the connection is dead and reconnect. | ||
| */ | ||
| private resetHeartbeat() { | ||
| if (this.heartbeatTimeout !== undefined) { | ||
| clearTimeout(this.heartbeatTimeout); | ||
| } | ||
|
|
||
| this.heartbeatTimeout = setTimeout(() => { | ||
| this.logger?.warn(`Connection timed out. Reconnecting...`); | ||
| this.wsClient?.terminate(); | ||
| this.restartUnexpectedClosedWebsocket(); | ||
| }, HEARTBEAT_TIMEOUT_DURATION); | ||
| } | ||
|
|
||
| private async waitForMaybeReadyWebSocket() { | ||
| let waitedTime = 0; | ||
| while ( | ||
| this.wsClient !== undefined && | ||
| this.wsClient.readyState !== this.wsClient.OPEN | ||
| ) { | ||
| if (waitedTime > 5000) { | ||
| this.wsClient.close(); | ||
| return; | ||
| } else { | ||
| waitedTime += 10; | ||
| await sleep(10); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private async restartUnexpectedClosedWebsocket() { | ||
| if (this.wsUserClosed === true) { | ||
| return; | ||
| } | ||
|
|
||
| await this.startWebSocket(); | ||
| await this.waitForMaybeReadyWebSocket(); | ||
|
|
||
| if (this.wsClient === undefined) { | ||
| this.logger?.error( | ||
| "Couldn't reconnect to websocket. Error callback is called." | ||
| ); | ||
| return; | ||
| } | ||
|
|
||
| this.onReconnect(); | ||
| } | ||
|
|
||
| closeWebSocket() { | ||
| if (this.wsClient !== undefined) { | ||
| const client = this.wsClient; | ||
| this.wsClient = undefined; | ||
| client.close(); | ||
| } | ||
| this.wsUserClosed = true; | ||
| } | ||
| } | ||
|
|
||
| async function sleep(ms: number) { | ||
| return new Promise((resolve) => setTimeout(resolve, ms)); | ||
| } | ||
|
|
||
| function expoBackoff(attempts: number): number { | ||
| return 2 ** attempts * 100; | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.