Giter Site home page Giter Site logo

k8w / tsrpc Goto Github PK

View Code? Open in Web Editor NEW
1.7K 55.0 185.0 2.43 MB

A TypeScript RPC framework, with runtime type checking and serialization, support both HTTP and WebSocket. It is very suitable for website / APP / games, and absolutely comfortable to full-stack TypeScript developers.

License: MIT License

TypeScript 99.31% JavaScript 0.69%
typescript rpc framework nodejs ajax axios full-stack node runtime-type-checking typescript-serialization

tsrpc's Introduction

TSRPC

EN / 中文

A TypeScript RPC framework with runtime type checking and binary serialization.

Official site: https://tsrpc.cn (English version is on the way)

Features

  • Runtime type checking
  • Binary serialization
  • Pure TypeScript, without any decorater or other language
  • HTTP / WebSocket / and more protocols...
  • Optional backward-compatibility to JSON
  • High performance and reliable, verified by services over 100,000,000 users

Create Full-stack Project

npx create-tsrpc-app@latest

Usage

Define Protocol (Shared)

export interface ReqHello {
  name: string;
}

export interface ResHello {
  reply: string;
}

Implement API (Server)

import { ApiCall } from "tsrpc";

export async function ApiHello(call: ApiCall<ReqHello, ResHello>) {
  call.succ({
    reply: 'Hello, ' + call.req.name
  });
}

Call API (Client)

let ret = await client.callApi('Hello', {
    name: 'World'
});

Examples

https://github.com/k8w/tsrpc-examples

Serialization Algorithm

The best TypeScript serialization algorithm ever. Without any 3rd-party IDL language (like protobuf), it is fully based on TypeScript source file. Define the protocols directly by your code.

This is powered by TSBuffer, which is going to be open-source.

TypeScript has the best type system, with some unique advanced features like union type, intersection type, mapped type, etc.

TSBuffer may be the only serialization algorithm that support them all.

API Reference

See API Reference.

tsrpc's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tsrpc's Issues

bigint不能解析的问题

return { isSucc: true, output: type === 'json' ? json : JSON.stringify(json) };

能否改为

return { isSucc: true, output: type === 'json' ? json : JSON.stringify(
    json,
    (key, value) => (typeof value === 'bigint' ? value.toString() : value) 
  )  }; 

不知道这样解决合不合理

tsrpc.config.ts 配置, 接口创建异常.

问题描述

  1. tsrpc.config.ts配置多个[proto].
  2. 在 「protocolsA」下新建一个PtlTest.ts 协议
  3. 在「src/api/A」成功创建了API
  4. [异常] 在「src/api/」 下 增加了一个「protocolsA」 的API文件

image

类型定义问题

我在创建接口时如下定义

export interface ReqUpdate extends BaseRequest {
  id: number;
  info: {
    projectName?: string;
    projectOwner?: string;
    isDel?: boolean;
  };
}

或是

export type T_project_item = {
  id: number
  projectName: string
  projectOwner: string
  createTime: string
  updateTime: string
  isDel: boolean
}


export interface ReqUpdate extends BaseRequest {
  id: number;
  info: Pick<T_project_item,'id'>
}

可以正常编译通过,

但是我的自定义工具类型则报错

export type Nullable<T> = {
  [Key in keyof T]?: T[Key];
};

export interface ReqUpdate extends BaseRequest {
  id: number;
  info: Nullable<Pick<T_project_item,'isDel'| 'projectOwner'>>;
}
⨯ Cannot resolve type: {
  [Key in keyof T]?: T[Key];
}
    at ../../plugins/typeTool
⨯ ServiceProto 生成失败,请检查 TypeScript 代码是否编译报错: src/shared/protocols/serviceProto.ts

项目打包时报错:no such file or directory, open 'dist/package.json'

tsrpc.config

{
proto: [
{
ptlDir: "src/procedures/protocols",
output: "src/procedures/protocols/service-proto.ts",
apiDir: "src/procedures/api",
docDir: "src/procedures/docs",
ptlTemplate: { baseFile: "src/procedures/protocols/base.ts" },
},
],
sync: [],
dev: {
autoProto: true,
autoSync: true,
autoApi: true,
watch: "src",
entry: "src/procedures/backend.ts",
},
build: {
autoProto: true,
autoSync: true,
autoApi: true,
outDir: ".procedures",
},
};

issues in readme

  • tsrpc has no exported member 'RpcServer', so does tsrpc-browser

  • ApiHelloWorld.ts import wrong relative path

npm run sync错误

PS F:\Project\Pests\Server> npm run sync

[email protected] sync
tsrpc-cli sync

错误 fs__default$1.default.rm is not a function
npm ERR! code 4294967295
npm ERR! path F:\Project\Pests\Server
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c tsrpc-cli sync

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\35730\AppData\Local\npm-cache_logs\2022-09-07T08_30_48_643Z-debug.log

0 verbose cli [
0 verbose cli 'D:\nodejs\node.exe',
0 verbose cli 'C:\Users\35730\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js',
0 verbose cli 'run',
0 verbose cli 'sync'
0 verbose cli ]
1 info using [email protected]
2 info using [email protected]
3 timing config:load:defaults Completed in 3ms
4 timing config:load:file:C:\Users\35730\AppData\Roaming\npm\node_modules\npm\npmrc Completed in 2ms
5 timing config:load:builtin Completed in 2ms
6 timing config:load:cli Completed in 2ms
7 timing config:load:env Completed in 0ms
8 timing config:load:file:F:\Project\Pests\Server.npmrc Completed in 0ms
9 timing config:load:project Completed in 1ms
10 timing config:load:file:C:\Users\35730.npmrc Completed in 0ms
11 timing config:load:user Completed in 0ms
12 timing config:load:file:C:\Users\35730\AppData\Roaming\npm\etc\npmrc Completed in 1ms
13 timing config:load:global Completed in 1ms
14 timing config:load:cafile Completed in 0ms
15 timing config:load:validate Completed in 0ms
16 timing config:load:setUserAgent Completed in 0ms
17 timing config:load:setEnvs Completed in 1ms
18 timing config:load Completed in 10ms
19 verbose npm-session 74022eb5a037d18f
20 timing npm:load Completed in 20ms
21 timing command:run-script Completed in 1989ms
22 verbose stack Error: command failed
22 verbose stack at ChildProcess. (C:\Users\35730\AppData\Roaming\npm\node_modules\npm\node_modules@npmcli\promise-spawn\index.js:64:27)
22 verbose stack at ChildProcess.emit (events.js:311:20)
22 verbose stack at maybeClose (internal/child_process.js:1021:16)
22 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
23 verbose pkgid [email protected]
24 verbose cwd F:\Project\Pests\Server
25 verbose Windows_NT 10.0.19044
26 verbose argv "D:\nodejs\node.exe" "C:\Users\35730\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js" "run" "sync"
27 verbose node v12.16.1
28 verbose npm v7.5.4
29 error code 4294967295
30 error path F:\Project\Pests\Server
31 error command failed
32 error command C:\WINDOWS\system32\cmd.exe /d /s /c tsrpc-cli sync
33 verbose exit 4294967295

我本地实际用的包管理器是pnpm,但是自动检测认为是yarn,提示是npm

我本地实际用的包管理器是pnpm,但是自动检测认为是yarn,提示是npm

=== 欢迎使用 create-tsrpc-app 版本 1.1.8 ===

创建 TSRPC 应用: trpc
? 请选择要创建的项目类型: Vue 3 + 后端
? 请选择传输协议: HTTP 短连接
 √ 1/9 检测 NPM 环境: Command: yarn, Registry: https://registry.npm.taobao.org
 √ 2/9 复制文件到 "backend"
 √ 3/9 生成 "backend/package.json"
 √ 4/9 npm-check-update
 √ 5/9 复制文件到 "frontend"
 √ 6/9 生成 "frontend/package.json"
 √ 7/9 npm-check-update
 √ 8/9 Initialize symlink
 √ 9/9 安装 NPM 依赖

========================================

✅ TSRPC APP 创建成功。

运行本地开发服务器:

= 后端 =

    cd backend
    npm run dev

= 前端 =

    cd frontend
    npm run dev

联机游戏的后端如何使用cocos的物理引擎

如题想请教下,用cocos写单机游戏的时候可以使用其自带的物理引擎,各个物体的位置都是由物理引擎计算的,而联机游戏需要前后端共用一套逻辑,这时后端如何使用cocos的物理引擎呢

[feature request] 服务端在其它语言中的实现

看了文档,感觉和thrift协议很像,特色在于使用了前端友好、有类型检查的typescript进行接口定义,既然这么想所以我在想有没有可能出个其它语言(大火的go)的服务端实现彻底干翻thrift这种自定义dsl的协议

about version.

Why the latest tag is v2.3.2?Why the Official website latest version is v3.2.3? And we need releases version.

项目发展方向建议

  1. 提供 nodejs 流行框架如 express koa nestjs 等的中间件,方便嵌入已有的项目中
  2. 丰富完善 tsrpc-cli 文档和 api ,方便 express koa 等框架的项目接入
  3. tsrpc 可以往全栈框架发展, 不止步于 rpc 框架

ws和http如何共存

就是期待端口复用,之所以有这个疑问是因为我用WsServer上传的附件无法给前端访问

协议支持大消息分片传输吗

作者你好:
我想了解一下使用这个框架websocket协议,里面自己处理了粘包(我也不知道websocket有粘包的问题不,第一次用)吗?,还有发送大消息的时候会自动分片发送保证对端收到吗?
谢谢

ws服务端,在Api方法中,调用conn.close()方法如果这时候客户端已经关闭,会强制覆盖并返回一个错误结果

我的业务逻辑是: ApiLogin
我希望在登录验证失败后,服务端确保连接要关闭掉
客户端发现失败的结果也做一层主动关闭

伪代码:
server.ts

if(认证失败){
 call.error("失败");
 call.conn.close();//如果客户端立即关闭,这里会强制覆盖和返回一个错误(类似调用call.error),并且这里即使判断了conn的状态也是没用
}

client.ts

let ret = await ...
if(!ret.succ){
  client.disconnect();
}

服务端打印的日志如下:

<21632> 2022-02-14 15:20:02 [ERROR] 127.0.0.1 Conn#3 [Api:Send] SN=1 [SendReturnErr] WebSocket is not open: readyState 2 (CLOSING) {  isSucc: false,
  err: TsrpcError {
    message: 'Content is empty',
    type: 'ApiError',
    code: 400
  }
}
<21632> 2022-02-14 15:20:02 [ERROR] 127.0.0.1 Conn#3 [Api:Send] SN=1 {
  message: 'WebSocket is not open: readyState 2 (CLOSING)',
  name: 'SendReturnErr'
}
<21632> 2022-02-14 15:20:02 [ERROR] 127.0.0.1 Conn#3 [Api:Send] SN=1 [SendReturnErr] WebSocket is not opened {
  isSucc: false,
  err: TsrpcError {
    message: 'Internal Server Error',
    type: 'ServerError',
    code: 'INTERNAL_ERR',
    innerErr: 'WebSocket is not open: readyState 2 (CLOSING)'
  }
}
<21632> 2022-02-14 15:20:02 [INFO] 127.0.0.1 Conn#3 [Disconnected] Code=1000 ActiveConn=1

客户端打印日志如下:

[ApiReq] #1 Send {content: 'err'}
Lost connection to ws://127.0.0.1:3000 code=1000 reason=
[ApiErr] #1 Send TsrpcError {message: 'Lost connection to server', type: 'NetworkError', code: 'LOST_CONN'}

附带一个能重现问题的demo
testConnClose.zip

优雅停机tsrpc

怎么做到在停机前,先发送close(reason?: string),告知客户端关闭的原因,然后再进行关闭。

gRPC compatibility

Hey,

I want to use Unity as frontend and TSRPC as backend, is that possible?

看了您TSRPC + Cocos,多人实时对战 So Easy!的文章,请教俩个问题。

文章写的真好,受益良多。但有两个问题还望请教。
1,关于判定该听谁的问题,大佬你举的例子是个射击游戏,这还好,要是moba游戏,放一个技能,这技能也不带晕,就是简单的子弹飞行,命中,掉血,这么一个技能。由于没有晕、位移等效果,也不存在被击中者被强制拉回去的问题,就是中了掉血。这种判定是听攻击者客户端运算的,还是听服务端运算的呢?听谁的好像另外一边都不会同意,影响游戏体验,那现有的moba游戏是如何实现这里的同步策略的呢?
2,关于作弊问题,大佬你文章最后提到:你担心客户端可能发给你作弊的计算结果,其实客户端一样可能发给你作弊的输入,所以客户端算和服务端算,对于作弊来说都是一样的。我这里觉得还是不一样,因为服务端可以比较容易校验客户端传过来的输入是否合法,而不太容易校验客户端传上来的结果是否合法。

server的实现是基于什么语言/框架?

非常厉害的框架!不过我对实现细节有一些疑问,考虑到介绍页面有比较强的性能指标,所以很好奇server端的底层实现是依赖于什么语言或者框架?

在TSRPC中使用export default interface导出接口后,npm run doc会报错

错误信息

ERROR ⨯ Debug Failure. False expression: Node must have a real position for this operation

问题原因

在目录src/tsrpc/types/文件下定义的接口文件(tsrpc协议中会用到), 如果使用export default interface导出这个接口, build和dev命令都是可以正常运行的,但是doc命令会报这个错误.

解决办法

去掉default,使用export interface导出接口,这个问题可以解决.

协议接口增加新属性兼容问题

原先协议接口属性:
export interface ReqLogin{
username: string
}

后因为需求变更,需要增加字段:客户端类型
export interface ReqLogin{
username: string,
clientType:number
}

旧客户端未更新协议之前,访问新的服务器,会提示fail:Missing required property clientType
怎么做到兼容的处理呢?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.