TSRPC Framework
website·Indexed 31 days ago
https://tsrpc.cnA TypeScript-native RPC framework designed for HTTP APIs, WebSocket real-time applications, and NodeJS microservices. It features a binary serialization system for efficiency, a middleware model called Flow, and a type system that provides runtime type detection. TSRPC supports both API Services (request/response) and Message Services (publish/subscribe) and is designed to be transport-protocol agnostic.
What's inside TSRPC
- The Message Service is a publish/subscribe model allowing bidirectional communication between the server and clients. Unlike API Services, messages are asynchronous and do not have a response; once sent, the operation is considered complete regardless of whether the recipient processed it. Messages are transmitted using binary serialization and type checking. On TCP-based protocols like HTTP and WebSocket, message delivery is ordered.
Overview of TSRPC Framework
TSRPC is an RPC framework specifically designed for TypeScript. It provides a type-safe way to handle communication between clients and servers, applicable for HTTP APIs, WebSocket real-time applications, and NodeJS microservices. Key capabilities include support for advanced TypeScript types (Union, Intersection, Utility types), automatic runtime parameter validation, and the ability to transmit complex types likeArrayBuffer,Date, andObjectIdwithin JSON or via binary encoding without needing Protobuf.Overview of the TypeScript RPC framework features
This framework provides a type-safe communication layer using native TypeScript type definition protocols. Key capabilities include:
- Pure TypeScript: No decorators, annotations, or third-party languages required.
- End-to-End Type Safety: Provides full IDE code completion during development and automatic parameter validation at runtime.
- Enhanced JSON: Supports transmitting complex data types such as
ArrayBuffer,Date, andObjectIdwithin JSON. - Binary Transmission: Ability to encode TypeScript types directly into binary for smaller payloads and easier encryption, removing the need for Protobuf.
- Deployment Flexibility: Supports both Serverless cloud functions (Aliyun, Tencent Cloud, AWS) and containerized deployments.
- Documentation: One-click generation of interface documentation in Swagger/OpenAPI and Markdown formats.
- Protocol Support: Supports both HTTP and WebSocket, allowing for a transport-agnostic architecture.
- Cross-Platform: Compatible with Browsers, Mini-programs, Mobile Apps, and Node.js, while remaining compatible with Restful API calls.
- Performance: Capable of 5000+ QPS on a single core (tested on Macbook Air 2020) and verified in projects with tens of millions of DAU.
Overview of TSRPC Framework
TSRPC is an RPC framework specifically designed for TypeScript and Cocos. It addresses the limitations of standard TypeScript types (which only exist at compile-time) by providing runtime type validation and binary serialization. Key capabilities include:
- Runtime Type Safety: Automatically validates request and response types at runtime and intercepts illegal requests.
- Binary Serialization: Encodes TypeScript types into binary format with efficiency similar to Protobuf, while supporting advanced TS types (e.g.,
Pick,Omit, complex nested references). - Full-stack Type Sharing: Allows sharing of protocol definitions between frontend and backend for consistent code hints and reduced errors.
- Transport Independence: A single codebase can run over HTTP (short connections) and WebSocket (long connections), and can be extended to UDP, IPC, or Web Workers.
Deploy TSRPC client to a file server or CDN
TSRPC project templates (created viacreate-tsrpc-app) use a decoupled frontend/backend architecture. The frontend is deployed as static files.# 1. Build the frontend cd frontend npm run build # 2. Copy 'frontend/dist' to a file server or CDNImplement a real-time multiplayer synchronization architecture
A robust real-time multiplayer architecture separates logic from presentation to handle network latency. The core flow consists of three main components:
- GameSystem (Shared Logic): A cross-platform module that defines the game state and inputs. It implements the deterministic algorithm:
Old State + Input = New State. - Server (Authority): Manages game rooms, receives player inputs, periodically broadcasts those inputs to all clients, and maintains the authoritative game state using the GameSystem.
- Client (Prediction & Presentation):
- GameManager (Logic Layer): Performs client-side prediction and reconciliation. It calculates the local predicted state by applying pending local inputs to the last known authoritative state from the server.
- GameScene (Presentation Layer): Renders the state provided by the GameManager. It uses direct updates for the local player and interpolation (e.g., Tweens) for other players to ensure smooth movement.
- GameSystem (Shared Logic): A cross-platform module that defines the game state and inputs. It implements the deterministic algorithm:
Implement runtime type validation in TSRPC
TSRPC provides a runtime type system that ensures type safety for API request inputs and response outputs. It automatically intercepts requests and responses that do not match the defined TypeScript types. Validation occurs twice: first on the client side to catch errors locally, and again on the server side before the API implementation function is executed.Implement a distributed game room architecture with TSRPC
To achieve a 'global server' (全区全服) experience without a complex dedicated access layer, split the project into two types of services:
- Room Service (Stateful): A WebSocket service managing game room logic and connection aggregations. Each instance is exposed via a unique URL to maintain session persistence.
- Matchmaking Service (Stateless): An HTTP service for room creation and matchmaking. Multiple instances can be deployed behind a load balancer under a single unified URL.
This architecture simplifies the stack by removing the need for a proxy access layer; clients connect directly to services using URLs. Authentication is shared across services since they reside in the same project.
Implement a distributed game architecture with TSRPC
To achieve a 'global server' (all-region) feel without a complex access layer, split the project into two types of services:
- Room Service (Stateful): A WebSocket service managing game room logic and connection aggregation. Each instance is exposed via a unique URL to maintain session persistence.
- Matching Service (Stateless): An HTTP service for creating rooms and random matching. Multiple instances can be deployed behind a load balancer (e.g., Nginx/K8s Ingress) under a single URL.
By sharing authentication logic across services in the same project, the need for a dedicated proxy/access layer is removed, reducing latency and complexity.
postDisconnectFlow type definition
ThepostDisconnectFlowprovides context about why a WebSocket connection was closed.Flow<{ /** Reason provided by server when calling `conn.close(reason)` */ reason?: string, /** * True if disconnected via `client.disconnect()`. * False if disconnected due to network error or server-side closure. */ isManual?: boolean }>()Use extended types in TSRPC JSON API calls
TSRPC extends standard JSON transmission to support the direct use of complex types such asArrayBuffer,Date, andObjectIdwithin API calls, removing the need for manual serialization/deserialization of these specific types.Implement a distributed Room and Matching architecture
To support high concurrency and horizontal scaling in multiplayer games, split the project into two types of services:
- Room Service (Stateful): A WebSocket service managing game room logic and connection aggregations. Each instance is exposed via a unique URL to maintain session persistence.
- Matching Service (Stateless): An HTTP service handling room creation and player matchmaking. Multiple instances can be deployed behind a load balancer (e.g., Nginx or K8s Ingress) and exposed via a single unified URL.
By sharing authentication logic across services in the same project, a dedicated access layer can be omitted, reducing latency and complexity.