Skip to content

Commit

Permalink
refactor: 🎨 migrate to socket module, phase 1 (#2181)
Browse files Browse the repository at this point in the history
  • Loading branch information
drazisil authored Sep 28, 2024
1 parent f076c91 commit 8ca7ba2
Show file tree
Hide file tree
Showing 39 changed files with 774 additions and 218 deletions.
7 changes: 6 additions & 1 deletion packages/gateway/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,12 @@ export function onSocketConnection({
);

// Deserialize the raw message
const rawMessage = new BasePacket();
const rawMessage = new BasePacket({
connectionId: socket.id,
messageId: 0,
messageSequence: 0,
messageSource: "",
});
rawMessage.deserialize(incomingDataAsBuffer);

// Log the raw message
Expand Down
8 changes: 7 additions & 1 deletion packages/lobby/src/NPS_LOBBYCLIENT_COMMANDS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@
* @type {TNPS_COMMAND_MAP[]}
*/

import { GameMessageOpCode } from "../../interfaces/index.js";
/**
* Commands from the game client to the game server
* @export
* @readonly
* @type {TNPS_COMMAND_MAP[]}
*/
import type { GameMessageOpCode } from "rusty-motors-shared";

export const NPS_LOBBYCLIENT_COMMANDS: GameMessageOpCode[] = [
{ name: "NPS_LOGIN", value: 256, module: "Lobby" },
Expand Down
2 changes: 1 addition & 1 deletion packages/lobby/src/NPS_LOBBYSERVER_COMMANDS.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { GameMessageOpCode } from "../../interfaces/index.js";
import type { GameMessageOpCode } from "rusty-motors-shared";

/**
* Commands from the game server to the game client
Expand Down
2 changes: 1 addition & 1 deletion packages/lobby/src/NPS_LOBBY_COMMANDS.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { GameMessageOpCode } from "../../interfaces/index.js";
import type { GameMessageOpCode } from "rusty-motors-shared";
import { NPS_LOBBYCLIENT_COMMANDS } from "./NPS_LOBBYCLIENT_COMMANDS.js";
import { NPS_LOBBYSERVER_COMMANDS } from "./NPS_LOBBYSERVER_COMMANDS.js";

Expand Down
14 changes: 7 additions & 7 deletions packages/lobby/src/handlers/encryptedCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ export type NpsCommandHandler = {
log: ServerLogger;
}) => Promise<{
connectionId: string;
message: LegacyMessage;
message: LegacyMessage | null;
}>;
};

Expand Down Expand Up @@ -196,7 +196,7 @@ async function handleCommand({
log?: ServerLogger;
}): Promise<{
connectionId: string;
message: MessageBufferOld | LegacyMessage;
message: MessageBufferOld | LegacyMessage | null;
}> {
const incommingRequest = message;

Expand Down Expand Up @@ -253,19 +253,19 @@ export async function handleEncryptedNPSCommand({
inboundMessage._doDeserialize(message.data);

// Decipher
const decipheredMessage = decryptCmd({
const decipheredMessage = await decryptCmd({
connectionId,
message: inboundMessage,
log,
});

const response = handleCommand({
const response = await handleCommand({
connectionId,
message: (await decipheredMessage).message,
message: decipheredMessage.message,
log,
});

if ((await response).message === null) {
if (response.message === null) {
log.debug("No response to send");
return {
connectionId,
Expand All @@ -276,7 +276,7 @@ export async function handleEncryptedNPSCommand({
// Encipher
const encryptedResponse = encryptCmd({
connectionId,
message: (await response).message,
message: response.message,
log,
});

Expand Down
16 changes: 3 additions & 13 deletions packages/lobby/src/handlers/heartbeat.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,10 @@
import { getServerLogger } from "rusty-motors-shared";
import { NPSMessage, SerializedBuffer } from "rusty-motors-shared";

/**
* @param {object} args
* @param {string} args.connectionId
* @param {SerializedBuffer} args.message
* @param {import("pino").Logger} [args.log=getServerLogger({ name: "Lobby" })]
* @returns {Promise<{
* connectionId: string
* messages: SerializedBuffer[],
* }>}
*/
export async function _npsHeartbeat({
connectionId,
// @ts-ignore
message, // eslint-disable-line no-unused-vars
// biome-ignore lint/correctness/noUnusedVariables: <explanation>
message,
log = getServerLogger({
name: "_npsHeartbeat",
}),
Expand All @@ -28,7 +18,7 @@ export async function _npsHeartbeat({
log.debug(packetResult.toString());

const outboundMessage = new SerializedBuffer();
outboundMessage._doDeserialize(packetResult.serialize());
outboundMessage.deserialize(packetResult.serialize());

return {
connectionId,
Expand Down
22 changes: 0 additions & 22 deletions packages/lobby/src/handlers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,6 @@ import { handleEncryptedNPSCommand } from "./encryptedCommand.js";
import { _npsHeartbeat } from "./heartbeat.js";
import { _npsRequestGameConnectServer } from "./requestConnectGameServer.js";

/**
* @typedef {object} ServiceArgs
* @property {string} connectionId
* @property {SerializedBufferOld} message
* @property {import("pino").Logger} log
*/

/**
* @typedef {object} ServiceResponse
* @property {string} connectionId
* @property {SerializedBufferOld[] } messages
*/

/**
* @exports
* @typedef {object} GameMessageHandler
* @property {number} opCode
* @property {string} name
* @property {function(ServiceArgs): Promise<ServiceResponse>} handler
*/

/** @type {GameMessageHandler[]} */
export const handlerMap = [
{
opCode: 100,
Expand Down
4 changes: 2 additions & 2 deletions packages/lobby/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { LegacyMessage } from "rusty-motors-shared";
import { handleEncryptedNPSCommand } from "./handlers/encryptedCommand.js";
import { handleTrackingPing } from "./handlers/handleTrackingPing.js";
import { _npsRequestGameConnectServer } from "./handlers/requestConnectGameServer.js";
import type { Serializable } from "rusty-motors-shared-packets";
import type { BufferSerializer } from "rusty-motors-shared-packets";

/**
* Array of supported message handlers
Expand Down Expand Up @@ -87,7 +87,7 @@ export async function receiveLobbyData({
}),
}: {
connectionId: string;
message: Serializable;
message: BufferSerializer;
log?: ServerLogger;
}): Promise<{
connectionId: string;
Expand Down
4 changes: 2 additions & 2 deletions packages/login/src/receiveLoginData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
type ServiceResponse,
} from "rusty-motors-shared";
import { handleLoginData } from "./internal.js";
import type { Serializable } from "rusty-motors-shared-packets";
import type { BufferSerializer } from "rusty-motors-shared-packets";

/**
* Receives login data and handles the login process.
Expand All @@ -42,7 +42,7 @@ export async function receiveLoginData({
}),
}: {
connectionId: string;
message: Serializable;
message: BufferSerializer;
log?: import("pino").Logger;
}): Promise<ServiceResponse> {
try {
Expand Down
6 changes: 3 additions & 3 deletions packages/mcots/src/messageProcessors/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import type { ServerMessage } from "rusty-motors-shared-packets";
import type { ServerPacket } from "rusty-motors-shared-packets";
import { processClientConnect } from "./processClientConnect.js";
import { processClientTracking } from "./processClientTracking.js";
import { processServerLogin } from "./processServerLogin.js";
import { processSetOptions } from "./processSetOptions.js";
import { processStockCarInfo } from "./processStockCarInfo.js";

export type ServerSocketCallback = (messages: ServerMessage[]) => void;
export type ServerSocketCallback = (messages: ServerPacket[]) => void;

export type ServerMessageProcessor = (
connectionId: string,
message: ServerMessage,
message: ServerPacket,
socketCallback: ServerSocketCallback,
) => Promise<void>;

Expand Down
9 changes: 5 additions & 4 deletions packages/mcots/src/messageProcessors/processClientConnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@ import {
} from "rusty-motors-mcots";
import { UserStatusManager } from "rusty-motors-nps";
import { getServerLogger } from "rusty-motors-shared";
import { ServerMessage } from "rusty-motors-shared-packets";
import { ServerPacket } from "rusty-motors-shared-packets";
import { sendSuccess } from "./sendSuccess.js";

const log = getServerLogger({});
const log = getServerLogger({
name: "processClientConnect",
});

export async function processClientConnect(
connectionId: string,
message: ServerMessage,
message: ServerPacket,
socketCallback: ServerSocketCallback,
): Promise<void> {
log.debug(`Processing client connect request: ${message.toString()}`);
Expand Down Expand Up @@ -63,7 +65,6 @@ export async function processClientConnect(

sendSuccess(message, socketCallback);

log.resetName();
return Promise.resolve();
} catch (error) {
if (error instanceof ErrorNoKey) {
Expand Down
12 changes: 6 additions & 6 deletions packages/mcots/src/messageProcessors/processClientTracking.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { ClientTrackingMessage } from "rusty-motors-mcots";
import { getServerLogger } from "rusty-motors-shared";
import type { ServerMessage } from "rusty-motors-shared-packets";
import type { ServerPacket } from "rusty-motors-shared-packets";
import type { ServerSocketCallback } from "./index.js";

const log = getServerLogger();
const log = getServerLogger({
name: "processClientTracking",
});

export async function processClientTracking(
connectionId: string,
message: ServerMessage,
_connectionId: string,
message: ServerPacket,
socketCallback: ServerSocketCallback,
) {
log.setName("processClientTracking");

log.debug(`Processing client tracking message`);

Expand All @@ -24,7 +25,6 @@ export async function processClientTracking(

// Do something with the tracking data

log.resetName();
void socketCallback([]);

return Promise.resolve();
Expand Down
18 changes: 9 additions & 9 deletions packages/mcots/src/messageProcessors/processServerLogin.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { LoginCompleteMessage, LoginMessage } from "rusty-motors-mcots";
import { getServerLogger } from "rusty-motors-shared";
import { ServerMessage } from "rusty-motors-shared-packets";
import { ServerPacket } from "rusty-motors-shared-packets";
import type { ServerSocketCallback } from "./index.js";

const log = getServerLogger();
const log = getServerLogger({
name: "processServerLogin",
});

export async function processServerLogin(
connectionId: string,
message: ServerMessage,
_connectionId: string,
message: ServerPacket,
socketCallback: ServerSocketCallback,
): Promise<void> {
log.setName("processServerLogin");
// Read the inbound packet
const loginMessage = new LoginMessage(message.getDataBuffer().length);
loginMessage.deserialize(message.getDataBuffer());
Expand All @@ -25,11 +26,10 @@ export async function processServerLogin(
log.debug(`Sending LoginCompleteMessage: ${response.toString()}`);

// Send response packet
const responsePacket = new ServerMessage(response.getMessageId());
responsePacket.setData(response);
responsePacket.populateHeader(message.getSequence());
const responsePacket = new ServerPacket(response.getMessageId());
responsePacket.setDataBuffer(response.serialize());
responsePacket.setSequence(message.messageSequence);

socketCallback([responsePacket]);
log.resetName();
return Promise.resolve();
}
12 changes: 6 additions & 6 deletions packages/mcots/src/messageProcessors/processSetOptions.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { SetOptionsMessage } from "rusty-motors-mcots";
import { getServerLogger } from "rusty-motors-shared";
import { ServerMessage } from "rusty-motors-shared-packets";
import { ServerPacket } from "rusty-motors-shared-packets";
import type { ServerSocketCallback } from "./index.js";
import { sendSuccess } from "./sendSuccess.js";

const log = getServerLogger();
const log = getServerLogger({
name: "processSetOptions",
});

export async function processSetOptions(
connectionId: string,
message: ServerMessage,
_connectionId: string,
message: ServerPacket,
socketCallback: ServerSocketCallback,
) {
log.setName("processSetOptions");
log.info(`Processing SetOptionsMessage`);
const setOptionsMessage = new SetOptionsMessage().deserialize(
message.getDataBuffer(),
Expand All @@ -22,6 +23,5 @@ export async function processSetOptions(

sendSuccess(message, socketCallback);

log.resetName();
return Promise.resolve();
}
26 changes: 13 additions & 13 deletions packages/mcots/src/messageProcessors/processStockCarInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,32 +5,33 @@ import {
import { StockCarInfo, StockCar } from "rusty-motors-mcots";
import { getServerLogger } from "rusty-motors-shared";
import {
ServerGenericRequest,
ServerMessage,
GenericRequestPayload,
ServerPacket,
} from "rusty-motors-shared-packets";
import type { ServerSocketCallback } from "./index.js";

const log = getServerLogger();
const log = getServerLogger({
name: "processStockCarInfo",
});

// 1300 544f4d43 01 00000000 8d00 [08000000 00000000]

export async function processStockCarInfo(
connectionId: string,
message: ServerMessage,
_connectionId: string,
message: ServerPacket,
socketCallback: ServerSocketCallback,
): Promise<void> {
log.setName("processStockCarInfo");
try {
log.debug(`Processing stock car info message`);

const request = new ServerGenericRequest().deserialize(
const request = new GenericRequestPayload().deserialize(
message.data.serialize(),
);

log.debug(`Received stock car info request: ${request.toString()}`);

const lotOwnerId = request.getData().readUInt32LE();
const brandId = request.getData2().readUInt32LE();
const lotOwnerId = request.data;
const brandId = request.data2;

log.debug(`Lot owner ID: ${lotOwnerId} Brand ID: ${brandId}`);

Expand All @@ -50,7 +51,7 @@ export async function processStockCarInfo(
responsePacket.setDealerId(lotOwnerId);
responsePacket.setBrandId(brandId);

const response = new ServerMessage(141);
const response = new ServerPacket(141);

if (inventoryCars.inventory.length > StockCarInfo.MAX_CARS_PER_MESSAGE) {
log.error(
Expand Down Expand Up @@ -90,9 +91,8 @@ export async function processStockCarInfo(

responsePacket.setMoreCars(false);

response.setData(responsePacket);
response.populateHeader(message.header.getSequence());
log.resetName();
response.setDataBuffer(responsePacket.serialize());
response.setSequence(message.messageSequence);
return socketCallback([response]);
} catch (error) {
log.error(`Error processing stock car info: ${error as string}`);
Expand Down
Loading

0 comments on commit 8ca7ba2

Please sign in to comment.