[add] first

This commit is contained in:
2022-04-29 15:25:10 +08:00
commit da8024fc30
87 changed files with 16892 additions and 0 deletions

22
test/try/client/http.ts Normal file
View File

@@ -0,0 +1,22 @@
import { HttpClient } from '../../src/client/http/HttpClient';
import { serviceProto, ServiceType } from '../proto/serviceProto';
let client = new HttpClient<ServiceType>({
server: 'http://localhost:3000',
proto: serviceProto
});
async function main() {
const P = 50, N = 1000;
let max = 0;
console.time(`test ${P}/${N}`);
for (let i = 0, len = N / P; i < len; ++i) {
let res = await Promise.all(Array.from({ length: P }, () => {
let start = Date.now();
return client.callApi('a/b/c/Test', { name: '123' }).then(() => Date.now() - start);
}));
max = Math.max(res.max(), max)
}
console.timeEnd(`test ${P}/${N}`);
console.log('max', max)
}
main();

82
test/try/client/ws.ts Normal file
View File

@@ -0,0 +1,82 @@
import { serviceProto, ServiceType } from '../proto/serviceProto';
import { WsClient } from '../../src/client/ws/WsClient';
import SuperPromise from 'k8w-super-promise';
import { Func } from 'mocha';
async function main() {
let client = new WsClient({
server: 'ws://127.0.0.1:3000',
proto: serviceProto,
onStatusChange: v => {
console.log('StatusChange', v);
},
// onLostConnection: () => {
// console.log('连接断开2秒后重连');
// setTimeout(() => {
// client.connect().catch(() => { });
// }, 2000)
// }
});
await client.connect();
let cancel = client.callApi('Test', { name: 'XXXXXXXXXXXXX' }).catch(e => e);
cancel.cancel();
let res = await client.callApi('Test', { name: '小明同学' }).catch(e => e);
console.log('Test Res', res);
res = await client.callApi('a/b/c/Test', { name: '小明同学' }).catch(e => e);
console.log('Test1 Res', res);
// setInterval(async () => {
// try {
// let res = await client.callApi('Test', { name: '小明同学' });
// console.log('收到回复', res);
// }
// catch (e) {
// if (e.info === 'NETWORK_ERR') {
// return;
// }
// console.log('API错误', e)
// }
// }, 1000);
// client.listenMsg('Chat', msg => {
// console.log('收到MSG', msg);
// });
// setInterval(() => {
// try {
// client.sendMsg('Chat', {
// channel: 123,
// userName: '王小明',
// content: '你好',
// time: Date.now()
// }).catch(e => {
// console.log('SendMsg Failed', e.message)
// })
// }
// catch{ }
// }, 1000)
// #region Benchmark
// let maxTime = 0;
// let done = 0;
// let startTime = Date.now();
// setTimeout(() => {
// console.log('done', maxTime, done);
// process.exit();
// }, 3000);
// for (let i = 0; i < 10000; ++i) {
// client.callApi('Test', { name: '小明同学' }).then(() => {
// ++done;
// maxTime = Math.max(maxTime, Date.now() - startTime)
// })
// }
// #endregion
}
main();

27
test/try/massive.ts Normal file
View File

@@ -0,0 +1,27 @@
import { TSRPCClient } from "..";
import { serviceProto, ServiceType } from './proto/serviceProto';
async function main() {
setInterval(() => {
for (let i = 0; i < 100; ++i) {
let client = new TSRPCClient<ServiceType>({
server: 'ws://127.0.0.1:3000',
proto: serviceProto
});
client.connect().then(() => {
client.callApi('a/b/c/Test1', { name: '小明同学' }).then(v => {
// console.log('成功', v)
}).catch(e => {
console.error('错误', e.message)
}).then(() => {
client.disconnect();
});
}).catch(e => {
console.error('连接错误', e)
})
}
}, 1000)
}
main();

View File

@@ -0,0 +1,12 @@
import { TsrpcClient } from "../../..";
import { serviceProto } from '../server/protocols/proto';
let client = new TsrpcClient({
proto: serviceProto
});
client.callApi('Test', { name: 'ssss' }).then(v => {
console.log('then', v)
}).catch(e => {
console.log('catch', e)
})

View File

@@ -0,0 +1,10 @@
import { TsrpcServer } from '../../../index';
import { serviceProto } from './protocols/proto';
let server = new TsrpcServer({
proto: serviceProto,
});
server.autoImplementApi('src/api');
server.start();

View File

@@ -0,0 +1,7 @@
export interface ReqTest {
name: string
}
export interface ResTest {
reply: string
}

View File

@@ -0,0 +1,52 @@
import { ServiceProto } from 'tsrpc-proto';
import { ReqTest, ResTest } from './PtlTest'
export interface ServiceType {
req: {
"Test": ReqTest
},
res: {
"Test": ResTest
},
msg: {
}
}
export const serviceProto: ServiceProto<ServiceType> = {
"services": [
{
"id": 0,
"name": "Test",
"type": "api",
"req": "PtlTest/ReqTest",
"res": "PtlTest/ResTest"
}
],
"types": {
"PtlTest/ReqTest": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "name",
"type": {
"type": "String"
}
}
]
},
"PtlTest/ResTest": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "reply",
"type": {
"type": "String"
}
}
]
}
}
};

View File

@@ -0,0 +1,18 @@
import { ReqTest, ResTest } from "../../protocols/PtlTest";
import { ApiCall } from "../../../../..";
export async function ApiTest(call: ApiCall<ReqTest, ResTest>) {
await new Promise(rs => {
let i = 5;
call.logger.log(i);
let interval = setInterval(() => {
call.logger.log(--i);
if (i === 0) {
clearInterval(interval);
rs();
}
}, 1000);
});
call.error('asdfasdf', { a: 1, b: 2 })
}

12
test/try/package-lock.json generated Normal file
View File

@@ -0,0 +1,12 @@
{
"name": "try",
"version": "1.0.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"version": "1.0.0",
"license": "ISC"
}
}
}

11
test/try/package.json Normal file
View File

@@ -0,0 +1,11 @@
{
"name": "try",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}

View File

@@ -0,0 +1,6 @@
export interface MsgChat {
channel: number,
userName: string,
content: string,
time: number
}

View File

@@ -0,0 +1,7 @@
export interface ReqTest {
name: string
};
export type ResTest = {
reply: string
};

View File

@@ -0,0 +1,10 @@
import { MsgChat } from '../../../MsgChat';
export interface ReqTest {
name: string
};
export type ResTest = {
reply: string,
chat?: MsgChat
};

View File

@@ -0,0 +1,135 @@
import { ServiceProto } from 'tsrpc-proto';
import { ReqTest, ResTest } from './a/b/c/PtlTest'
import { MsgChat } from './MsgChat'
import { ReqTest as ReqTest_1, ResTest as ResTest_1 } from './PtlTest'
export interface ServiceType {
req: {
"a/b/c/Test": ReqTest,
"Test": ReqTest_1
},
res: {
"a/b/c/Test": ResTest,
"Test": ResTest_1
},
msg: {
"Chat": MsgChat
}
}
export const serviceProto: ServiceProto<ServiceType> = {
"services": [
{
"id": 0,
"name": "a/b/c/Test",
"type": "api",
"req": "a/b/c/PtlTest/ReqTest",
"res": "a/b/c/PtlTest/ResTest"
},
{
"id": 1,
"name": "Chat",
"type": "msg",
"msg": "MsgChat/MsgChat"
},
{
"id": 2,
"name": "Test",
"type": "api",
"req": "PtlTest/ReqTest",
"res": "PtlTest/ResTest"
}
],
"types": {
"a/b/c/PtlTest/ReqTest": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "name",
"type": {
"type": "String"
}
}
]
},
"a/b/c/PtlTest/ResTest": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "reply",
"type": {
"type": "String"
}
},
{
"id": 1,
"name": "chat",
"type": {
"type": "Reference",
"target": "MsgChat/MsgChat"
},
"optional": true
}
]
},
"MsgChat/MsgChat": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "channel",
"type": {
"type": "Number"
}
},
{
"id": 1,
"name": "userName",
"type": {
"type": "String"
}
},
{
"id": 2,
"name": "content",
"type": {
"type": "String"
}
},
{
"id": 3,
"name": "time",
"type": {
"type": "Number"
}
}
]
},
"PtlTest/ReqTest": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "name",
"type": {
"type": "String"
}
}
]
},
"PtlTest/ResTest": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "reply",
"type": {
"type": "String"
}
}
]
}
}
};

View File

@@ -0,0 +1,59 @@
{
"MsgChat/MsgChat": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "channel",
"type": {
"type": "String"
}
},
{
"id": 1,
"name": "userName",
"type": {
"type": "String"
}
},
{
"id": 2,
"name": "content",
"type": {
"type": "String"
}
},
{
"id": 3,
"name": "time",
"type": {
"type": "Number"
}
}
]
},
"PtlTest/ReqTest": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "name",
"type": {
"type": "String"
}
}
]
},
"PtlTest/ResTest": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "reply",
"type": {
"type": "String"
}
}
]
}
}

View File

@@ -0,0 +1,21 @@
import { TsrpcError } from "tsrpc-proto";
import { ApiCallHttp } from '../../../src/server/http/HttpCall';
import { ReqTest } from "../../proto/PtlTest";
import { ResTest } from '../../proto/a/b/c/PtlTest';
export async function ApiTest(call: ApiCallHttp<ReqTest, ResTest>) {
if (Math.random() > 0.75) {
call.succ({
reply: 'Hello, ' + call.req.name
})
}
else if (Math.random() > 0.5) {
call.error('What the fuck??', { msg: '哈哈哈哈' })
}
else if (Math.random() > 0.25) {
throw new Error('这应该是InternalERROR')
}
else {
throw new TsrpcError('返回到前台的错误', 'ErrInfo');
}
}

View File

@@ -0,0 +1,5 @@
export async function ApiTest(call: any) {
call.succ({
reply: 'Api Test1 Succ'
})
}

22
test/try/server/http.ts Normal file
View File

@@ -0,0 +1,22 @@
import { serviceProto } from '../proto/serviceProto';
import * as path from "path";
import { TsrpcServer } from '../../index';
let server = new TsrpcServer({
proto: serviceProto
});
server.dataFlow.push((data, conn) => {
let httpReq = conn.options.httpReq;
if (httpReq.method === 'GET') {
conn.logger.log('url', httpReq.url);
conn.logger.log('host', httpReq.headers.host);
conn.options.httpRes.end('Hello~~~');
return false;
}
return true;
})
server.autoImplementApi(path.resolve(__dirname, 'api'));
server.start();

18
test/try/server/ws.ts Normal file
View File

@@ -0,0 +1,18 @@
import { serviceProto, ServiceType } from '../proto/serviceProto';
import * as path from "path";
import { TsrpcServerWs } from '../../index';
let server = new TsrpcServerWs<ServiceType>({
proto: serviceProto
});
server.start();
server.autoImplementApi(path.resolve(__dirname, 'api'));
server.listenMsg('Chat', v => {
v.conn.sendMsg('Chat', {
channel: v.msg.channel,
userName: 'SYSTEM',
content: '收到',
time: Date.now()
})
})

59
test/try/tsconfig.json Normal file
View File

@@ -0,0 +1,59 @@
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
"useUnknownInCatchVariables": false
}
}