Skip to content

Commit

Permalink
Use better socket implementation, update deps
Browse files Browse the repository at this point in the history
  • Loading branch information
Linux123123 committed Aug 23, 2022
1 parent f03ea6f commit 2d4ea8a
Show file tree
Hide file tree
Showing 5 changed files with 170 additions and 97 deletions.
19 changes: 10 additions & 9 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,32 @@ const prettierOptions = JSON.parse(
fs.readFileSync(path.resolve(__dirname, '.prettierrc'), 'utf8')
);

/** @type {import("@types/eslint").Linter.Config} */
module.exports = {
env: {
es2021: true,
node: true,
es2022: true,
node: true
},
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
'plugin:prettier/recommended'
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
ecmaVersion: 'latest',
sourceType: 'module'
},
plugins: ['@typescript-eslint', 'prettier', 'eslint-plugin-tsdoc'],
ignorePatterns: ['dist', '.eslintrc.js'],
rules: {
'prettier/prettier': ['error', prettierOptions],
'tsdoc/syntax': 'warn',
'tsdoc/syntax': 'warn'
},
overrides: [
{
files: ['**/*.ts'],
rules: { 'prettier/prettier': ['error', prettierOptions] },
},
],
rules: { 'prettier/prettier': ['error', prettierOptions] }
}
]
};
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@
},
"homepage": "https://jspteroapi.linux123123.com",
"dependencies": {
"sockette": "^2.0.6",
"undici": "^5.9.1",
"ws": "^8.8.1"
},
"devDependencies": {
"@microsoft/tsdoc-config": "^0.16.1",
"@types/node": "^18.7.8",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
"@types/node": "^18.7.11",
"@types/ws": "^8.5.3",
"@typescript-eslint/eslint-plugin": "^5.34.0",
"@typescript-eslint/parser": "^5.34.0",
"eslint": "^8.22.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
Expand Down
21 changes: 10 additions & 11 deletions src/client/Websocket.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
/** @module ClientWebsocket */

import Sockette from 'sockette';
import { EventEmitter } from 'events';
import { WebsocketAuthData } from './interfaces/WebsocketAuthData';
import { JSPteroAPIError } from '../modules/Error';
import { Socket } from '../modules/Socket';

const reconnectErrors = [
'jwt: exp claim is invalid',
'jwt: created too far in past (denylist)'
];

global.WebSocket = require('ws');

// Code mostly from pterodactyl websocket implementation

export class WebsocketClient extends EventEmitter {
constructor(
errorHandler: (error: JSPteroAPIError) => void,
Expand Down Expand Up @@ -59,7 +55,7 @@ export class WebsocketClient extends EventEmitter {
private backoff = 5000;

// The socket instance being tracked.
private socket: Sockette | null = null;
private socket: Socket | null = null;

// The URL being connected to for the socket.
private url: string | null = null;
Expand All @@ -75,10 +71,10 @@ export class WebsocketClient extends EventEmitter {
private connect(url: string): this {
this.url = url;

this.socket = new Sockette(this.url, {
this.socket = new Socket(this.url, {
onmessage: (e) => {
try {
const { event, args } = JSON.parse(e.data);
const { event, args } = JSON.parse(e.data.toString());
args ? this.emit(event, ...args) : this.emit(event);
} catch (ex) {
console.warn('Failed to parse incoming websocket message.', ex);
Expand All @@ -97,13 +93,16 @@ export class WebsocketClient extends EventEmitter {
this.authenticate();
},
onclose: () => this.emit('SOCKET_CLOSE'),
onerror: (event: Event) => {
onerror: (event) => {
if (
(event as ErrorEvent).message ===
event.message ===
'WebSocket was closed before the connection was established'
)
return;
throw new Error((event as ErrorEvent).message);
throw new Error(event.message);
},
onmaximum: () => {
return;
}
});

Expand Down
76 changes: 76 additions & 0 deletions src/modules/Socket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { WebSocket, Event, MessageEvent, CloseEvent, ErrorEvent } from 'ws';

export class Socket {
constructor(
private readonly url: string,
private readonly options: {
onopen: (this: Socket, ev: Event) => void;
onmessage: (this: Socket, ev: MessageEvent) => void;
onreconnect: (this: Socket, ev: Event | CloseEvent | ErrorEvent) => void;
onmaximum: (this: Socket, ev: CloseEvent | ErrorEvent) => void;
onclose: (this: Socket, ev: CloseEvent) => void;
onerror: (this: Socket, ev: ErrorEvent) => void;
}
) {
this.open();
}

declare ws: WebSocket;
declare timer: NodeJS.Timeout;
private reconnectNum = 0;

public open = () => {
const options = this.options;
const reconnect = this.reconnect;
this.ws = new WebSocket(this.url);

this.ws.onmessage = options.onmessage;

const onOpen = options.onopen.bind(this);
this.ws.onopen = (e) => {
onOpen(e);
this.reconnectNum = 0;
};

const onClose = options.onclose.bind(this);
this.ws.onclose = function (e) {
e.code === 1e3 || e.code === 1001 || e.code === 1005 || reconnect(e);
onClose(e);
};

const onError = options.onerror.bind(this);
this.ws.onerror = function (e) {
e && (e as unknown as Record<string, string>).code === 'ECONNREFUSED'
? reconnect(e)
: onError(e);
};
};

private reconnect = (e: CloseEvent | ErrorEvent) => {
const onReconnect = this.options.onreconnect.bind(this);
const onMaximum = this.options.onmaximum.bind(this);

const open = this.open;
if (this.timer && this.reconnectNum++ < Infinity) {
this.timer = setTimeout(function () {
onReconnect(e);
open();
}, 1e3);
} else {
onMaximum(e);
}
};

public json = (x: unknown) => {
this.ws.send(JSON.stringify(x));
};

public send = (x: unknown) => {
this.ws.send(x);
};

public close = (x?: number, y?: string | Buffer) => {
clearTimeout(this.timer);
this.ws.close(x || 1e3, y);
};
}
Loading

0 comments on commit 2d4ea8a

Please sign in to comment.