Skip to content

Commit

Permalink
fix: optimization for multiple connections
Browse files Browse the repository at this point in the history
  • Loading branch information
cyperdark committed Feb 19, 2024
1 parent f0d37a1 commit fb06ca6
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 31 deletions.
102 changes: 73 additions & 29 deletions packages/server/socket/index.ts
Original file line number Diff line number Diff line change
@@ -1,55 +1,97 @@
import { config, sleep, wLogger } from '@tosu/common';
import WebSocket from 'ws';

const socketsHandler = ({
interface ModifiedWebsocket extends WebSocket {
id: string;
}

interface ModifiedSocket extends WebSocket.Server {
getUniqueID: () => string;
}

const connectedClients = {
v1: new Map<string, ModifiedWebsocket>(),
v2: new Map<string, ModifiedWebsocket>(),
keyOvelay: new Map<string, ModifiedWebsocket>()
};

const socketsHandler = async ({
socketType,
instancesManager,
pollRate,
socket,
state
}: {
socket: WebSocket.Server;
socketType: 'v1' | 'v2' | 'keyOvelay';
socket: ModifiedSocket;
instancesManager: any;
pollRate: number;
state: string;
}) => {
socket.on('connection', async (ws) => {
wLogger.debug('>>> ws: CONNECTED');
let isSocketConnected = true;
socket.getUniqueID = function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4();
};

socket.on('connection', (ws: ModifiedWebsocket) => {
ws.id = socket.getUniqueID();

wLogger.debug(
`[${ws.id}](${connectedClients[socketType].size}) >>> ws: CONNECTED`
);

ws.on('close', function (reasonCode, description) {
isSocketConnected = false;
wLogger.debug('>>> ws: CLOSED');
connectedClients[socketType].delete(ws.id);

wLogger.debug(
`[${ws.id}](${connectedClients[socketType].size}) >>> ws: CLOSED`
);
});

ws.on('error', function (reasonCode, description) {
isSocketConnected = false;
wLogger.debug(`>>> ws: error: ${reasonCode} [${description}]`);
});
connectedClients[socketType].delete(ws.id);

while (isSocketConnected) {
const osuInstances: any = Object.values(
instancesManager.osuInstances || {}
wLogger.debug(
`[${ws.id}](${connectedClients[socketType].size}) >>> ws: error: ${reasonCode} [${description}]`
);
if (osuInstances.length < 1) {
await sleep(500);
continue;
}

try {
ws.send(
JSON.stringify(osuInstances[0][state](instancesManager))
);
} catch (error) {}

await sleep(pollRate);
}
});

connectedClients[socketType].set(ws.id, ws);
});

while (true) {
const osuInstances: any = Object.values(
instancesManager.osuInstances || {}
);
if (osuInstances.length < 1) {
await sleep(500);
continue;
}

const clients = connectedClients[socketType];
if (clients.size > 0) {
clients.forEach((value, key) => {
try {
value.send(
JSON.stringify(osuInstances[0][state](instancesManager))
);
} catch (error) {}
});
}

await sleep(pollRate);
}
};

export const WebSocketV1 = (instancesManager: any) => {
const wss = new WebSocket.Server({ noServer: true });
const wss = new WebSocket.Server({ noServer: true }) as ModifiedSocket;

socketsHandler({
socketType: 'v1',
socket: wss,
instancesManager,
pollRate: config.pollRate,
Expand All @@ -60,9 +102,10 @@ export const WebSocketV1 = (instancesManager: any) => {
};

export const WebSocketV2 = (instancesManager: any) => {
const wss = new WebSocket.Server({ noServer: true });
const wss = new WebSocket.Server({ noServer: true }) as ModifiedSocket;

socketsHandler({
socketType: 'v2',
socket: wss,
instancesManager,
pollRate: config.pollRate,
Expand All @@ -73,9 +116,10 @@ export const WebSocketV2 = (instancesManager: any) => {
};

export const WebSocketKeys = (instancesManager: any) => {
const wss = new WebSocket.Server({ noServer: true });
const wss = new WebSocket.Server({ noServer: true }) as ModifiedSocket;

socketsHandler({
socketType: 'keyOvelay',
socket: wss,
instancesManager,
pollRate: config.keyOverlayPollRate,
Expand Down
4 changes: 4 additions & 0 deletions packages/tosu/src/api/types/v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -435,3 +435,7 @@ export interface TourneyClients {
};
};
}

export interface ApiKeypressAnswer extends KeyOverlay {
bpm: Bpm;
}
13 changes: 11 additions & 2 deletions packages/tosu/src/api/utils/buildResultV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { fixDecimals } from '@/utils/fixDecimals';
import { getOsuModsString } from '@/utils/osuMods';

import {
ApiKeypressAnswer,
ApiV2Answer,
BeatmapStatuses,
KeyOverlay,
Expand Down Expand Up @@ -395,10 +396,18 @@ export const buildResult = (
};
};

export const buildKeyOverlay = (service: DataRepo): KeyOverlay => {
const { gamePlayData } = service.getServices(['gamePlayData']);
export const buildKeyOverlay = (service: DataRepo): ApiKeypressAnswer => {
const { gamePlayData, beatmapPpData } = service.getServices([
'gamePlayData',
'beatmapPpData'
]);

return {
bpm: {
common: beatmapPpData.commonBPM,
min: beatmapPpData.minBPM,
max: beatmapPpData.maxBPM
},
k1: {
isPressed: gamePlayData.KeyOverlay.K1Pressed,
count: gamePlayData.KeyOverlay.K1Count
Expand Down

0 comments on commit fb06ca6

Please sign in to comment.