Skip to content
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

🐛 Fix sdk-utils websocket constructor hanging #1057

Merged
merged 1 commit into from
Sep 7, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions packages/sdk-utils/src/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,25 +51,31 @@ const log = logger.log = (ns, lvl, msg, meta) => {
};

// Create a new WebSocket and resolve with it once connected
async function createWebSocket(address, timeout = 1000) {
// attempt to import `ws` in node environments
let WebSocket = process.env.__PERCY_BROWSERIFIED__
/* eslint-disable-next-line import/no-extraneous-dependencies */
? window.WebSocket : (await import('ws')).default;
let ws = new WebSocket(address.replace(/^http/, 'ws'));

function createWebSocket(address, timeout = 1000) {
return new Promise((resolve, reject) => {
let done = ws.onopen = ws.onerror = e => {
ws._socket?.unref();
let ws;

let done = e => {
ws?._socket?.unref();
clearTimeout(timeoutid);
ws.onopen = ws.onerror = null;
/* istanbul ignore else: edge case */
if (ws) ws.onopen = ws.onerror = null;
if (!e.error && e.type !== 'error') return resolve(ws);
else reject(e.error || 'Error: Socket connection failed');
};

let timeoutid = setTimeout(done, timeout, {
error: 'Error: Socket connection timed out'
});

Promise.resolve(
process.env.__PERCY_BROWSERIFIED__
/* eslint-disable-next-line import/no-extraneous-dependencies */
? { default: window.WebSocket } : import('ws')
).then(({ default: WS }) => {
ws = new WS(address.replace(/^http/, 'ws'));
ws.onopen = ws.onerror = done;
}, reject);
});
}

Expand Down