Skip to content

Phase 3: Typed packet wrapper classes for compile-time safety #2803

@drazisil

Description

@drazisil

Summary

Replace runtime setSerializeOrder() pattern with compile-time typed packet classes for better type safety, IDE autocomplete, and reduced boilerplate.

Background

Current pattern in handlers:

const request = new BytableMessage();
request.setSerializeOrder([
    { name: 'commId', field: 'Dword' },
    { name: 'riffName', field: 'String' },
]);
request.deserialize(buffer);
const commId = (request.getFieldValueByName('commId') as Buffer).readInt32BE();

Problems:

  • No compile-time type checking
  • Field name typos fail at runtime
  • Verbose field access with manual casting
  • Same structure redefined in multiple handlers

Proposed Solution

Create typed wrapper classes:

// packages/lobby/src/packets/OpenCommChannelRequest.ts
import { NPS_MESSAGE_IDS } from 'rusty-motors-shared';

export class OpenCommChannelRequest {
    static readonly MESSAGE_ID = NPS_MESSAGE_IDS.OPEN_COMM_CHANNEL;

    readonly commId: number;
    readonly riffName: string;
    readonly slotNumber: number;
    readonly slotFlags: number;

    private constructor(data: {...}) {
        this.commId = data.commId;
        // ...
    }

    static fromBuffer(buffer: Buffer): OpenCommChannelRequest {
        // Internal BytableMessage usage hidden
    }

    toBuffer(): Buffer {
        // Serialization logic
    }
}

Usage becomes:

const request = OpenCommChannelRequest.fromBuffer(buffer);
const commId = request.commId;  // Already typed as number

Tasks

  • Create 2-3 typed packet classes as proof of concept:
    • OpenCommChannelRequest
    • OpenCommChannelResponse
    • UserLoginRequest
  • Update corresponding handlers to use typed packets
  • Add unit tests for typed packets
  • Document the pattern for future packets
  • Evaluate results before broader adoption

Dependencies

Future Consideration

If this pattern proves successful, consider:

  • Decorator-based packet definitions
  • Code generation from protocol schemas

Related

Part of the packet architecture improvement initiative. See PR #2801 for context.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions