oox 0.3.0-beta6 → 0.3.0-beta9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app.js +14 -15
- package/bin/configurer.js +22 -9
- package/bin/starter.js +4 -6
- package/index.js +22 -6
- package/logger.js +30 -10
- package/modules/http/index.js +8 -2
- package/modules/index.js +3 -0
- package/modules/socketio/client.js +101 -0
- package/modules/socketio/index.js +168 -0
- package/modules/socketio/server.js +136 -0
- package/modules/socketio/socket.js +4 -0
- package/package.json +4 -3
- package/types/app.d.ts +12 -1
- package/types/bin/configurer.d.ts +1 -1
- package/types/index.d.ts +3 -2
- package/types/logger.d.ts +2 -1
- package/types/modules/http/utils.d.ts +2 -2
- package/types/modules/index.d.ts +2 -0
- package/types/modules/socketio/client.d.ts +23 -0
- package/types/modules/socketio/index.d.ts +37 -0
- package/types/modules/socketio/server.d.ts +35 -0
- package/types/modules/socketio/socket.d.ts +11 -0
package/app.js
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.execute = exports.call = exports.on = exports.getMethods = exports.setMethods = exports.sourceKVMethods = exports.kvMethods = exports.eventHub = exports.asyncStore = exports.Context = exports.logger = void 0;
|
|
3
|
+
exports.execute = exports.call = exports.emit = exports.off = exports.once = exports.on = exports.getMethods = exports.setMethods = exports.sourceKVMethods = exports.kvMethods = exports.eventHub = exports.asyncStore = exports.Context = exports.logger = void 0;
|
|
4
4
|
const node_events_1 = require("node:events");
|
|
5
5
|
const node_async_hooks_1 = require("node:async_hooks");
|
|
6
6
|
const utils_1 = require("./utils");
|
|
7
|
-
// import { wrappedActions, actionMiddlewares, middlewares } from './middleware'
|
|
8
7
|
exports.logger = require("./logger");
|
|
9
8
|
class Context {
|
|
10
9
|
// 请求溯源ID
|
|
@@ -34,9 +33,21 @@ function getMethods() {
|
|
|
34
33
|
}
|
|
35
34
|
exports.getMethods = getMethods;
|
|
36
35
|
function on(event, listener) {
|
|
37
|
-
|
|
36
|
+
exports.eventHub.on(event, listener);
|
|
38
37
|
}
|
|
39
38
|
exports.on = on;
|
|
39
|
+
function once(event, listener) {
|
|
40
|
+
exports.eventHub.once(event, listener);
|
|
41
|
+
}
|
|
42
|
+
exports.once = once;
|
|
43
|
+
function off(event, listener) {
|
|
44
|
+
exports.eventHub.off(event, listener);
|
|
45
|
+
}
|
|
46
|
+
exports.off = off;
|
|
47
|
+
function emit(event, ...args) {
|
|
48
|
+
return exports.eventHub.emit(event, ...args);
|
|
49
|
+
}
|
|
50
|
+
exports.emit = emit;
|
|
40
51
|
/**
|
|
41
52
|
* Call an Function on RPC server
|
|
42
53
|
* @param action
|
|
@@ -126,18 +137,6 @@ async function execute(action, params, context) {
|
|
|
126
137
|
// ============================= PROXY END =============================
|
|
127
138
|
// make sure target action execute after all proxies
|
|
128
139
|
if (target) {
|
|
129
|
-
/*
|
|
130
|
-
const sourceMethod = wrappedActions.get ( action )
|
|
131
|
-
|
|
132
|
-
const middlewareNames = actionMiddlewares.get ( sourceMethod )
|
|
133
|
-
|
|
134
|
-
if ( middlewareNames && middlewareNames.length ) for ( const name of middlewareNames ) {
|
|
135
|
-
|
|
136
|
-
const middleware = middlewares.get ( name )
|
|
137
|
-
|
|
138
|
-
await middleware ( action, params, context )
|
|
139
|
-
}
|
|
140
|
-
*/
|
|
141
140
|
return await target(...params);
|
|
142
141
|
}
|
|
143
142
|
}
|
package/bin/configurer.js
CHANGED
|
@@ -25,17 +25,30 @@ function mergeFlatEnv(env) {
|
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
-
function
|
|
29
|
-
let env =
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
28
|
+
async function readEnvFile(filePath) {
|
|
29
|
+
let env = {};
|
|
30
|
+
if (filePath && fs.existsSync(filePath)) {
|
|
31
|
+
if (filePath.endsWith('.json')) {
|
|
32
|
+
const raw = fs.readFileSync(filePath, 'utf-8');
|
|
33
|
+
env = JSON.parse(raw);
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
const finalPath = path.resolve(filePath).replace(/\\/g, '/');
|
|
37
|
+
env = await eval(`import('file://${finalPath}')`);
|
|
38
|
+
}
|
|
33
39
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
Object.assign(env, require(path.resolve(envPath)));
|
|
40
|
+
else {
|
|
41
|
+
throw new Error('Env file not found: ' + filePath);
|
|
37
42
|
}
|
|
38
|
-
|
|
43
|
+
return env.default || env;
|
|
44
|
+
}
|
|
45
|
+
async function configure() {
|
|
46
|
+
const env = Object.create(null);
|
|
47
|
+
const defaultEnvPath = argv.getEnvArg('default-env');
|
|
48
|
+
const targetEnvPath = argv.getEnvArg('env');
|
|
49
|
+
const defaultEnv = defaultEnvPath ? await readEnvFile(defaultEnvPath) : {};
|
|
50
|
+
const targetEnv = targetEnvPath ? await readEnvFile(targetEnvPath) : {};
|
|
51
|
+
Object.assign(env, defaultEnv, targetEnv, argv.getAllEnvArgs());
|
|
39
52
|
mergeFlatEnv(env);
|
|
40
53
|
if ('string' === typeof env.ignore)
|
|
41
54
|
env.ignore = env.ignore.split(',');
|
package/bin/starter.js
CHANGED
|
@@ -7,10 +7,6 @@ const oox = require("../index");
|
|
|
7
7
|
const proxyer_1 = require("./proxyer");
|
|
8
8
|
const configurer_1 = require("./configurer");
|
|
9
9
|
const register_1 = require("./register");
|
|
10
|
-
const module_socketio_1 = require("@oox/module-socketio");
|
|
11
|
-
// preload modules
|
|
12
|
-
const socketio = new module_socketio_1.default();
|
|
13
|
-
oox.modules.add(socketio);
|
|
14
10
|
function getEntryFile(env) {
|
|
15
11
|
const args = process.argv.slice(2);
|
|
16
12
|
var [entryFilename] = args.filter(arg => !arg.includes('=') && arg.endsWith('.js'));
|
|
@@ -32,7 +28,7 @@ async function loadEntry(name, entryPath) {
|
|
|
32
28
|
}
|
|
33
29
|
async function startup() {
|
|
34
30
|
// 加载环境变量
|
|
35
|
-
const env = (0, configurer_1.configure)();
|
|
31
|
+
const env = await (0, configurer_1.configure)();
|
|
36
32
|
Object.assign(oox.config, env);
|
|
37
33
|
// 获取服务入口地址
|
|
38
34
|
const entryFile = getEntryFile(env);
|
|
@@ -51,9 +47,11 @@ async function startup() {
|
|
|
51
47
|
await loadEntry(entryFile.name, entryFile.path);
|
|
52
48
|
// 模块配置
|
|
53
49
|
oox.modules.setConfig(oox.config);
|
|
54
|
-
|
|
50
|
+
oox.emit('app:configured');
|
|
51
|
+
const { http: { config: httpConfig }, socketio: { config: socketioConfig } } = oox.modules.builtins;
|
|
55
52
|
// 服务启动
|
|
56
53
|
await oox.serve();
|
|
54
|
+
oox.emit('app:served');
|
|
57
55
|
console.log();
|
|
58
56
|
console.log('Service', (0, chalk_1.bold) `${oox.config.name}`, 'running.');
|
|
59
57
|
if (!httpConfig.disabled)
|
package/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.rpc = exports.removeKeepAliveConnection = exports.addKeepAliveConnection = exports.getKeepAliveConnection = exports.getKeepAliveConnections = exports.keepAliveConnections = exports.RPCKeepAliveConnection = exports.stop = exports.serve = exports.getContext = exports.genContext = exports.genTraceId = exports.setGenTraceIdFunction = exports.config = exports.Config = exports.Context = exports.on = exports.execute = exports.call = exports.sourceKVMethods = exports.kvMethods = exports.getMethods = exports.setMethods = exports.asyncStore = exports.modules = exports.ModuleConfig = exports.Module = void 0;
|
|
3
|
+
exports.rpc = exports.setLoadBalancePolicy = exports.removeKeepAliveConnection = exports.addKeepAliveConnection = exports.getKeepAliveConnection = exports.getKeepAliveConnections = exports.keepAliveConnections = exports.RPCKeepAliveConnection = exports.stop = exports.serve = exports.getContext = exports.genContext = exports.genTraceId = exports.setGenTraceIdFunction = exports.config = exports.Config = exports.Context = exports.emit = exports.off = exports.once = exports.on = exports.logger = exports.execute = exports.call = exports.sourceKVMethods = exports.kvMethods = exports.getMethods = exports.setMethods = exports.asyncStore = exports.modules = exports.ModuleConfig = exports.Module = void 0;
|
|
4
4
|
const node_crypto_1 = require("node:crypto");
|
|
5
5
|
const app = require("./app");
|
|
6
6
|
const utils_1 = require("./utils");
|
|
@@ -9,7 +9,7 @@ exports.Module = module_1.default;
|
|
|
9
9
|
Object.defineProperty(exports, "ModuleConfig", { enumerable: true, get: function () { return module_1.ModuleConfig; } });
|
|
10
10
|
const modules_1 = require("./modules");
|
|
11
11
|
exports.modules = new modules_1.default;
|
|
12
|
-
exports.asyncStore = app.asyncStore, exports.setMethods = app.setMethods, exports.getMethods = app.getMethods, exports.kvMethods = app.kvMethods, exports.sourceKVMethods = app.sourceKVMethods, exports.call = app.call, exports.execute = app.execute, exports.on = app.on;
|
|
12
|
+
exports.asyncStore = app.asyncStore, exports.setMethods = app.setMethods, exports.getMethods = app.getMethods, exports.kvMethods = app.kvMethods, exports.sourceKVMethods = app.sourceKVMethods, exports.call = app.call, exports.execute = app.execute, exports.logger = app.logger, exports.on = app.on, exports.once = app.once, exports.off = app.off, exports.emit = app.emit;
|
|
13
13
|
class Context extends app.Context {
|
|
14
14
|
// 请求溯源IP
|
|
15
15
|
sourceIP = '';
|
|
@@ -24,7 +24,7 @@ class Context extends app.Context {
|
|
|
24
24
|
toJSON() {
|
|
25
25
|
const context = Object.assign({}, this);
|
|
26
26
|
delete context.connection;
|
|
27
|
-
return
|
|
27
|
+
return context;
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
30
|
exports.Context = Context;
|
|
@@ -131,6 +131,23 @@ function removeKeepAliveConnection(name, id) {
|
|
|
131
131
|
}
|
|
132
132
|
}
|
|
133
133
|
exports.removeKeepAliveConnection = removeKeepAliveConnection;
|
|
134
|
+
/**
|
|
135
|
+
* random connection select for default load balance policy
|
|
136
|
+
* @param name service name
|
|
137
|
+
* @returns selected connection
|
|
138
|
+
*/
|
|
139
|
+
let loadBalancePolicy = (name) => {
|
|
140
|
+
const connections = exports.keepAliveConnections.get(name);
|
|
141
|
+
if (!connections || !connections.size)
|
|
142
|
+
return null;
|
|
143
|
+
const arrayConnections = Array.from(connections.values());
|
|
144
|
+
const index = Math.floor(Math.random() * arrayConnections.length);
|
|
145
|
+
return arrayConnections[index];
|
|
146
|
+
};
|
|
147
|
+
function setLoadBalancePolicy(policy) {
|
|
148
|
+
loadBalancePolicy = policy;
|
|
149
|
+
}
|
|
150
|
+
exports.setLoadBalancePolicy = setLoadBalancePolicy;
|
|
134
151
|
async function rpc(arg1, action, params, context) {
|
|
135
152
|
if (!context || !context.traceId) {
|
|
136
153
|
context = getContext();
|
|
@@ -140,10 +157,9 @@ async function rpc(arg1, action, params, context) {
|
|
|
140
157
|
connection = arg1;
|
|
141
158
|
}
|
|
142
159
|
else if ('string' === typeof arg1) {
|
|
143
|
-
|
|
144
|
-
if (!
|
|
160
|
+
connection = loadBalancePolicy(arg1);
|
|
161
|
+
if (!connection)
|
|
145
162
|
throw new Error(`Connection<${arg1}> not found`);
|
|
146
|
-
connection = connections.values().next().value;
|
|
147
163
|
}
|
|
148
164
|
else
|
|
149
165
|
throw new Error(`Unknown rpc arg1<${arg1}>`);
|
package/logger.js
CHANGED
|
@@ -1,20 +1,40 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.error = exports.
|
|
3
|
+
exports.trace = exports.error = exports.warn = exports.info = void 0;
|
|
4
4
|
const app_1 = require("./app");
|
|
5
|
-
function log(tag, ...msgs) {
|
|
6
|
-
const context = app_1.asyncStore.getStore();
|
|
7
|
-
app_1.eventHub.emit('log', context, { tag, msgs });
|
|
8
|
-
}
|
|
9
5
|
function info(...msgs) {
|
|
10
|
-
|
|
6
|
+
const context = app_1.asyncStore.getStore();
|
|
7
|
+
if (context)
|
|
8
|
+
app_1.eventHub.emit('log', context, 'info', msgs);
|
|
9
|
+
else
|
|
10
|
+
console.info('[INFO]', ...msgs);
|
|
11
11
|
}
|
|
12
12
|
exports.info = info;
|
|
13
|
-
function
|
|
14
|
-
|
|
13
|
+
function warn(...msgs) {
|
|
14
|
+
const context = app_1.asyncStore.getStore();
|
|
15
|
+
if (context)
|
|
16
|
+
app_1.eventHub.emit('log', context, 'warn', msgs);
|
|
17
|
+
else
|
|
18
|
+
console.warn('[WARN]', ...msgs);
|
|
15
19
|
}
|
|
16
|
-
exports.
|
|
20
|
+
exports.warn = warn;
|
|
17
21
|
function error(...msgs) {
|
|
18
|
-
|
|
22
|
+
const context = app_1.asyncStore.getStore();
|
|
23
|
+
if (context)
|
|
24
|
+
app_1.eventHub.emit('log', context, 'error', msgs);
|
|
25
|
+
else
|
|
26
|
+
console.error('[ERROR]', ...msgs);
|
|
19
27
|
}
|
|
20
28
|
exports.error = error;
|
|
29
|
+
function trace(name) {
|
|
30
|
+
const context = app_1.asyncStore.getStore();
|
|
31
|
+
const trace = { stack: '' };
|
|
32
|
+
Error.captureStackTrace(trace);
|
|
33
|
+
const stack = trace.stack
|
|
34
|
+
.replace(/.*\n.*logger.js.*\n/, name || 'Untitle\n');
|
|
35
|
+
if (context)
|
|
36
|
+
app_1.eventHub.emit('log', context, 'trace', stack);
|
|
37
|
+
else
|
|
38
|
+
console.log('[TRACE]', stack);
|
|
39
|
+
}
|
|
40
|
+
exports.trace = trace;
|
package/modules/http/index.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.HTTPConfig = void 0;
|
|
4
4
|
const http = require("node:http");
|
|
5
|
+
const node_querystring_1 = require("node:querystring");
|
|
5
6
|
const utils_1 = require("./utils");
|
|
6
7
|
const oox = require("../../index");
|
|
7
8
|
const module_1 = require("../module");
|
|
@@ -104,7 +105,12 @@ class HTTPModule extends module_1.default {
|
|
|
104
105
|
return;
|
|
105
106
|
let body = Object.create(null);
|
|
106
107
|
try {
|
|
107
|
-
|
|
108
|
+
if ('GET' === request.method) {
|
|
109
|
+
body = (0, node_querystring_1.parse)(request.url.split('?').pop());
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
body = await (0, utils_1.parseHTTPBody)(request);
|
|
113
|
+
}
|
|
108
114
|
if (!body || 'object' !== typeof body)
|
|
109
115
|
throw new Error('Content Invalid');
|
|
110
116
|
}
|
|
@@ -125,7 +131,7 @@ class HTTPModule extends module_1.default {
|
|
|
125
131
|
const ip = String(request.headers['x-ip'] || request.socket.remoteAddress || '');
|
|
126
132
|
// startup client ip
|
|
127
133
|
const sourceIP = String(request.headers['x-real-ip'] || '');
|
|
128
|
-
const { action, params = [] } = body;
|
|
134
|
+
const { action = 'index', params = [] } = body;
|
|
129
135
|
const context = oox.genContext({ traceId, caller, sourceIP, ip, callerId: '' });
|
|
130
136
|
const format = await oox.call(action, params, context);
|
|
131
137
|
this.respond(request, response, format);
|
package/modules/index.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
const module_1 = require("./module");
|
|
4
4
|
const http_1 = require("./http");
|
|
5
|
+
const socketio_1 = require("./socketio");
|
|
5
6
|
class Modules extends module_1.default {
|
|
6
7
|
/**
|
|
7
8
|
* the module unique name
|
|
@@ -20,10 +21,12 @@ class Modules extends module_1.default {
|
|
|
20
21
|
*/
|
|
21
22
|
builtins = {
|
|
22
23
|
http: new http_1.default,
|
|
24
|
+
socketio: new socketio_1.default,
|
|
23
25
|
};
|
|
24
26
|
constructor() {
|
|
25
27
|
super();
|
|
26
28
|
this.add(this.builtins.http);
|
|
29
|
+
this.add(this.builtins.socketio);
|
|
27
30
|
}
|
|
28
31
|
add(module) {
|
|
29
32
|
if (!module.name || 'string' !== typeof module.name)
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const SocketIOClient = require("socket.io-client");
|
|
4
|
+
const socket_1 = require("./socket");
|
|
5
|
+
const server_1 = require("./server");
|
|
6
|
+
const oox = require("../../index");
|
|
7
|
+
class SocketIOCore extends server_1.default {
|
|
8
|
+
/**
|
|
9
|
+
* connect to <SocketIO RPC> service
|
|
10
|
+
*/
|
|
11
|
+
async connect(url) {
|
|
12
|
+
let socket = socket_1.sockets.get(url);
|
|
13
|
+
// 已经连接的直接返回
|
|
14
|
+
if (socket) {
|
|
15
|
+
try {
|
|
16
|
+
await this.clientWaitConnection(socket);
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
this.clientOnSocketDisconnect(socket, error.message);
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
return socket;
|
|
23
|
+
}
|
|
24
|
+
const headers = {
|
|
25
|
+
'x-caller': oox.config.name
|
|
26
|
+
};
|
|
27
|
+
const { host } = oox.config;
|
|
28
|
+
const { port, path } = this.config;
|
|
29
|
+
headers['x-ip'] = host;
|
|
30
|
+
headers['x-caller-id'] = `ws://${host}:${port}${path}`;
|
|
31
|
+
// create socket handler
|
|
32
|
+
const mURL = new URL(url);
|
|
33
|
+
socket = SocketIOClient.io(mURL.origin, {
|
|
34
|
+
extraHeaders: headers,
|
|
35
|
+
path: mURL.pathname
|
|
36
|
+
});
|
|
37
|
+
socket.data = { name: 'anonymous', connected: false, id: url, host: mURL.host };
|
|
38
|
+
socket_1.sockets.set(url, socket);
|
|
39
|
+
try {
|
|
40
|
+
await this.clientWaitConnection(socket);
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
this.clientOnSocketDisconnect(socket, error);
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
return socket;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* 客户端Socket连接事件
|
|
50
|
+
*/
|
|
51
|
+
clientOnSocketConnection(socket) {
|
|
52
|
+
socket.data.connected = true;
|
|
53
|
+
socket.once('disconnect', reason => this.clientOnSocketDisconnect(socket, reason));
|
|
54
|
+
this.clientOnConnection(socket);
|
|
55
|
+
}
|
|
56
|
+
clientOnDisconnect(socket, reason) { }
|
|
57
|
+
clientOnConnection(socket) { }
|
|
58
|
+
/**
|
|
59
|
+
* 客户端Socket断开事件
|
|
60
|
+
* @param {Socket} socket
|
|
61
|
+
*/
|
|
62
|
+
clientOnSocketDisconnect(socket, reason) {
|
|
63
|
+
socket.data.connected = false;
|
|
64
|
+
socket.disconnect();
|
|
65
|
+
socket_1.sockets.delete(socket.data.id);
|
|
66
|
+
this.clientOnDisconnect(socket, reason);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* 等待socket连接
|
|
70
|
+
*/
|
|
71
|
+
async clientWaitConnection(socket) {
|
|
72
|
+
if (socket.data.connected)
|
|
73
|
+
return;
|
|
74
|
+
if (socket.connect)
|
|
75
|
+
socket.connect();
|
|
76
|
+
try {
|
|
77
|
+
await new Promise((resolve, reject) => {
|
|
78
|
+
const onError = (reason) => {
|
|
79
|
+
socket.offAny(onError);
|
|
80
|
+
const message = 'string' === typeof reason ? reason : reason instanceof Error ? reason.message : 'connect error';
|
|
81
|
+
reject(new Error(message));
|
|
82
|
+
};
|
|
83
|
+
socket.once('disconnect', onError);
|
|
84
|
+
socket.once('connect_error', onError);
|
|
85
|
+
socket.once('connect_timeout', onError);
|
|
86
|
+
socket.once('reconnect_error', onError);
|
|
87
|
+
socket.once('reconnect_failed', onError);
|
|
88
|
+
socket.once('oox_connected', ({ name }) => {
|
|
89
|
+
socket.offAny(onError);
|
|
90
|
+
socket.data.name = name;
|
|
91
|
+
resolve();
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
throw new Error(error.message);
|
|
97
|
+
}
|
|
98
|
+
this.clientOnSocketConnection(socket);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
exports.default = SocketIOCore;
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.sockets = void 0;
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
const client_1 = require("./client");
|
|
6
|
+
const oox = require("../../index");
|
|
7
|
+
const index_1 = require("../../index");
|
|
8
|
+
const socket_1 = require("./socket");
|
|
9
|
+
Object.defineProperty(exports, "sockets", { enumerable: true, get: function () { return socket_1.sockets; } });
|
|
10
|
+
class SocketIOModule extends client_1.default {
|
|
11
|
+
sockets = socket_1.sockets;
|
|
12
|
+
async serve() {
|
|
13
|
+
await this.stop();
|
|
14
|
+
const _http = oox.modules.builtins.http;
|
|
15
|
+
const httpConfig = _http.getConfig(), config = this.getConfig();
|
|
16
|
+
let isShareServer = false;
|
|
17
|
+
// 都没设置端口
|
|
18
|
+
isShareServer = !httpConfig.port && !config.port;
|
|
19
|
+
// 都设置相同端口
|
|
20
|
+
isShareServer = isShareServer || httpConfig.port === config.port;
|
|
21
|
+
// http 模块未被禁用
|
|
22
|
+
isShareServer = isShareServer && !httpConfig.disabled;
|
|
23
|
+
if (isShareServer) {
|
|
24
|
+
config.path = path.posix.join(httpConfig.path, config.path);
|
|
25
|
+
this.server = _http.server;
|
|
26
|
+
}
|
|
27
|
+
await super.serve();
|
|
28
|
+
}
|
|
29
|
+
onSyncConnection(socket) {
|
|
30
|
+
const mSockets = Array.from(socket_1.sockets.values())
|
|
31
|
+
.filter(s => s !== socket &&
|
|
32
|
+
s.data.name !== socket.data.name &&
|
|
33
|
+
s.data.id.startsWith('ws://'));
|
|
34
|
+
return mSockets.map(s => s.data);
|
|
35
|
+
}
|
|
36
|
+
serverOnDisconnect(socket, reason) {
|
|
37
|
+
super.serverOnDisconnect(socket, reason);
|
|
38
|
+
(0, index_1.removeKeepAliveConnection)(socket.data.name, socket.data.id);
|
|
39
|
+
}
|
|
40
|
+
clientOnDisconnect(socket, reason) {
|
|
41
|
+
super.clientOnDisconnect(socket, reason);
|
|
42
|
+
(0, index_1.removeKeepAliveConnection)(socket.data.name, socket.data.id);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
*
|
|
46
|
+
* @param socket 是由哪个通道发送过来的
|
|
47
|
+
* @param connectionDatas
|
|
48
|
+
*/
|
|
49
|
+
clientOnSyncConnection(socket, connectionDatas) {
|
|
50
|
+
for (const data of connectionDatas)
|
|
51
|
+
if (!socket_1.sockets.has(data.id))
|
|
52
|
+
this.connect(data.id).catch((error) => console.error(error));
|
|
53
|
+
}
|
|
54
|
+
onFetchActions(socket, search) {
|
|
55
|
+
const data = [];
|
|
56
|
+
for (const key of oox.kvMethods.keys())
|
|
57
|
+
if (!key.endsWith('_proxy') && key.includes(search))
|
|
58
|
+
data.push(key);
|
|
59
|
+
return data;
|
|
60
|
+
}
|
|
61
|
+
fetchActions(id, search = '') {
|
|
62
|
+
let socket = socket_1.sockets.get(id);
|
|
63
|
+
if (!socket) {
|
|
64
|
+
const connections = (0, index_1.getKeepAliveConnections)(id);
|
|
65
|
+
if (!connections || !connections.size)
|
|
66
|
+
throw new Error(`Unknown service identify<${id}>`);
|
|
67
|
+
id = connections.keys().next().value;
|
|
68
|
+
socket = socket_1.sockets.get(id);
|
|
69
|
+
}
|
|
70
|
+
if (!socket)
|
|
71
|
+
throw new Error(`Unknown service identify<${id}>`);
|
|
72
|
+
return this.emit(socket.data.id, 'fetchActions', [search]);
|
|
73
|
+
}
|
|
74
|
+
onConnection(socket) {
|
|
75
|
+
const { id, name, host } = socket.data;
|
|
76
|
+
const connection = new index_1.RPCKeepAliveConnection(this, id, socket.data);
|
|
77
|
+
(0, index_1.addKeepAliveConnection)(connection);
|
|
78
|
+
const connectionContext = {
|
|
79
|
+
sourceIP: '',
|
|
80
|
+
ip: host,
|
|
81
|
+
caller: name,
|
|
82
|
+
callerId: id,
|
|
83
|
+
connection
|
|
84
|
+
};
|
|
85
|
+
socket.on('fetchActions', async (search, fn) => {
|
|
86
|
+
if ('function' !== typeof fn)
|
|
87
|
+
return;
|
|
88
|
+
const data = await this.onFetchActions(socket, search);
|
|
89
|
+
fn(data);
|
|
90
|
+
});
|
|
91
|
+
socket.on('call', async (action, params, context, callback) => {
|
|
92
|
+
if ('object' !== typeof context)
|
|
93
|
+
context = oox.genContext(connectionContext);
|
|
94
|
+
else
|
|
95
|
+
context = oox.genContext(Object.assign(context, connectionContext));
|
|
96
|
+
this.call(action, params, context, callback);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
*
|
|
101
|
+
* @param {Socket} socket
|
|
102
|
+
*/
|
|
103
|
+
serverOnConnection(socket) {
|
|
104
|
+
super.serverOnConnection(socket);
|
|
105
|
+
socket.setMaxListeners(0);
|
|
106
|
+
socket.on('syncConnection', async (fn) => {
|
|
107
|
+
if ('function' !== typeof fn)
|
|
108
|
+
return;
|
|
109
|
+
const data = this.onSyncConnection(socket);
|
|
110
|
+
fn(data);
|
|
111
|
+
});
|
|
112
|
+
this.onConnection(socket);
|
|
113
|
+
}
|
|
114
|
+
async call(action, params, context, callback) {
|
|
115
|
+
const returns = await oox.call(action, params, context);
|
|
116
|
+
'function' === typeof callback && callback(returns);
|
|
117
|
+
return returns;
|
|
118
|
+
}
|
|
119
|
+
clientOnConnection(socket) {
|
|
120
|
+
super.clientOnConnection(socket);
|
|
121
|
+
socket.emit('syncConnection', (socketDatas) => this.clientOnSyncConnection(socket, socketDatas));
|
|
122
|
+
this.onConnection(socket);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* socketio emit
|
|
126
|
+
*/
|
|
127
|
+
async emit(url, action, params) {
|
|
128
|
+
let socket = null;
|
|
129
|
+
try {
|
|
130
|
+
socket = await this.connect(url);
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
// try again
|
|
134
|
+
socket = await this.connect(url);
|
|
135
|
+
}
|
|
136
|
+
try {
|
|
137
|
+
return await new Promise((resolve, reject) => {
|
|
138
|
+
const onError = (reason) => {
|
|
139
|
+
const message = 'string' === typeof reason ? reason : reason instanceof Error ? reason.message : 'connect error';
|
|
140
|
+
reject(new Error(message));
|
|
141
|
+
};
|
|
142
|
+
// RPC 执行时中断连接
|
|
143
|
+
socket.once('disconnect', onError);
|
|
144
|
+
socket.emit(action, ...params, (returns) => {
|
|
145
|
+
socket.off('disconnect', onError);
|
|
146
|
+
resolve(returns);
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
throw new Error(error.message);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* RPC
|
|
156
|
+
*/
|
|
157
|
+
async rpc(url, action, params, context) {
|
|
158
|
+
if (!context || !context.traceId) {
|
|
159
|
+
context = oox.getContext();
|
|
160
|
+
}
|
|
161
|
+
const { error, body } = await this.emit(url, 'call', [action, params, context]);
|
|
162
|
+
if (error)
|
|
163
|
+
throw new Error(error.message);
|
|
164
|
+
else
|
|
165
|
+
return body;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
exports.default = SocketIOModule;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SocketIOConfig = void 0;
|
|
4
|
+
const http = require("node:http");
|
|
5
|
+
const socket_io_1 = require("socket.io");
|
|
6
|
+
const oox = require("../../index");
|
|
7
|
+
const index_1 = require("../../index");
|
|
8
|
+
const socket_1 = require("./socket");
|
|
9
|
+
class SocketIOConfig extends index_1.ModuleConfig {
|
|
10
|
+
// listen port
|
|
11
|
+
port = 0;
|
|
12
|
+
// service path
|
|
13
|
+
path = '/socket.io';
|
|
14
|
+
// browser cross origin
|
|
15
|
+
origin = '';
|
|
16
|
+
}
|
|
17
|
+
exports.SocketIOConfig = SocketIOConfig;
|
|
18
|
+
class SocketIOServer extends index_1.Module {
|
|
19
|
+
name = 'socketio';
|
|
20
|
+
config = new SocketIOConfig;
|
|
21
|
+
/**
|
|
22
|
+
* means this.server created by myself<SocketIOServer>
|
|
23
|
+
*/
|
|
24
|
+
#isSelfServer = false;
|
|
25
|
+
server = null;
|
|
26
|
+
socketServer = null;
|
|
27
|
+
setConfig(config) {
|
|
28
|
+
Object.assign(this.config, config);
|
|
29
|
+
if (!config.hasOwnProperty('port')) {
|
|
30
|
+
this.config.port = oox.config.port;
|
|
31
|
+
}
|
|
32
|
+
if (!config.hasOwnProperty('origin')) {
|
|
33
|
+
this.config.origin = oox.config.origin;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
getConfig() {
|
|
37
|
+
return this.config;
|
|
38
|
+
}
|
|
39
|
+
async serve() {
|
|
40
|
+
await this.stop();
|
|
41
|
+
const port = this.config.port;
|
|
42
|
+
const isSelfServer = this.#isSelfServer = this.server ? true : false;
|
|
43
|
+
const server = this.server = isSelfServer ? this.server :
|
|
44
|
+
http.createServer((request, response) => response.end('No HTTP Gateway'));
|
|
45
|
+
if (!server.listening)
|
|
46
|
+
server.listen(port);
|
|
47
|
+
const address = server.address();
|
|
48
|
+
if (!address || 'object' !== typeof address)
|
|
49
|
+
throw new Error('Cannot read socket.io server port');
|
|
50
|
+
this.config.port = address.port;
|
|
51
|
+
this.createSocketIOServer();
|
|
52
|
+
}
|
|
53
|
+
async stop() {
|
|
54
|
+
if (this.socketServer)
|
|
55
|
+
await new Promise((resolve, reject) => this.socketServer.close(error => error ? reject(error) : resolve()));
|
|
56
|
+
if (this.#isSelfServer)
|
|
57
|
+
await new Promise((resolve, reject) => this.server.close(error => error ? reject(error) : resolve()));
|
|
58
|
+
}
|
|
59
|
+
genSocketIOServerOptions() {
|
|
60
|
+
const options = {
|
|
61
|
+
/**
|
|
62
|
+
* name of the path to capture
|
|
63
|
+
* @default "/socket.io"
|
|
64
|
+
*/
|
|
65
|
+
path: this.config.path,
|
|
66
|
+
/**
|
|
67
|
+
* how many ms before a client without namespace is closed
|
|
68
|
+
* @default 45000
|
|
69
|
+
*/
|
|
70
|
+
connectTimeout: 5000,
|
|
71
|
+
/**
|
|
72
|
+
* how many ms without a pong packet to consider the connection closed
|
|
73
|
+
* @default 5000
|
|
74
|
+
*/
|
|
75
|
+
pingTimeout: 2000,
|
|
76
|
+
/**
|
|
77
|
+
* how many ms before sending a new ping packet
|
|
78
|
+
* @default 25000
|
|
79
|
+
*/
|
|
80
|
+
pingInterval: 10000,
|
|
81
|
+
/**
|
|
82
|
+
* how many bytes or characters a message can be, before closing the session (to avoid DoS).
|
|
83
|
+
* @default 1e5 (100 KB)
|
|
84
|
+
*/
|
|
85
|
+
maxHttpBufferSize: 1e5
|
|
86
|
+
};
|
|
87
|
+
const { origin } = this.config;
|
|
88
|
+
if (origin)
|
|
89
|
+
options.cors = { origin };
|
|
90
|
+
return options;
|
|
91
|
+
}
|
|
92
|
+
createSocketIOServer() {
|
|
93
|
+
const socketServer = this.socketServer = new socket_io_1.Server(this.server, this.genSocketIOServerOptions());
|
|
94
|
+
socketServer.on('connection', async (socket) => {
|
|
95
|
+
try {
|
|
96
|
+
this.serverOnSocketConnection(socket);
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
socket.send(error.message).disconnect(true);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* 服务端Socket连接事件
|
|
105
|
+
*/
|
|
106
|
+
serverOnSocketConnection(socket) {
|
|
107
|
+
const headers = socket.handshake.headers;
|
|
108
|
+
const callerId = String(headers['x-caller-id'] || '') || socket.id;
|
|
109
|
+
// 已经存在相同的连接
|
|
110
|
+
if (socket_1.sockets.has(callerId))
|
|
111
|
+
throw new Error('Connection Exists');
|
|
112
|
+
// client ip or caller service ip
|
|
113
|
+
const ip = String(headers['x-real-ip'] || headers['x-ip'] || socket.handshake.address);
|
|
114
|
+
// service name
|
|
115
|
+
const caller = String(headers['x-caller'] || 'anonymous');
|
|
116
|
+
socket.data = { connected: true, host: ip, name: caller, id: callerId };
|
|
117
|
+
// 保存 callerId 与 socket 对应关系
|
|
118
|
+
socket_1.sockets.set(callerId, socket);
|
|
119
|
+
socket.on('disconnect', reason => this.serverOnSocketDisconnect(socket, reason));
|
|
120
|
+
socket.emit('oox_connected', { name: oox.config.name });
|
|
121
|
+
this.serverOnConnection(socket);
|
|
122
|
+
}
|
|
123
|
+
serverOnConnection(socket) { }
|
|
124
|
+
/**
|
|
125
|
+
* 服务端Socket断开事件
|
|
126
|
+
* @param {Socket} socket
|
|
127
|
+
* @param {Error} reason
|
|
128
|
+
*/
|
|
129
|
+
serverOnSocketDisconnect(socket, reason) {
|
|
130
|
+
socket.data.connected = false;
|
|
131
|
+
socket_1.sockets.delete(socket.data.id);
|
|
132
|
+
this.serverOnDisconnect(socket, reason);
|
|
133
|
+
}
|
|
134
|
+
serverOnDisconnect(socket, reason) { }
|
|
135
|
+
}
|
|
136
|
+
exports.default = SocketIOServer;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "oox",
|
|
3
|
-
"version": "0.3.0-
|
|
3
|
+
"version": "0.3.0-beta9",
|
|
4
4
|
"description": "Graceful NodeJS distributed application solution",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"http",
|
|
@@ -29,8 +29,9 @@
|
|
|
29
29
|
"homepage": "https://github.com/lipingruan/oox",
|
|
30
30
|
"license": "MIT",
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"
|
|
33
|
-
"
|
|
32
|
+
"chalk": "^4.1.0",
|
|
33
|
+
"socket.io": "^4.4.0",
|
|
34
|
+
"socket.io-client": "^4.4.0"
|
|
34
35
|
},
|
|
35
36
|
"engines": {
|
|
36
37
|
"node": ">=12.0.0"
|
package/types/app.d.ts
CHANGED
|
@@ -25,10 +25,21 @@ export declare const kvMethods: Map<string, Function>;
|
|
|
25
25
|
export declare const sourceKVMethods: Map<string, Function>;
|
|
26
26
|
export declare function setMethods(methods: any): void;
|
|
27
27
|
export declare function getMethods(): any;
|
|
28
|
+
export declare function on(event: 'app:configured' | 'app:served' | 'app:stopped', listener: () => void): void;
|
|
28
29
|
export declare function on(event: 'request', listener: (action: string, params: any[], context: Context) => void): void;
|
|
29
30
|
export declare function on(event: 'success', listener: (action: string, params: any[], context: Context, result: ReturnsBody) => void): void;
|
|
30
31
|
export declare function on(event: 'fail', listener: (action: string, params: any[], context: Context, error: Error) => void): void;
|
|
31
|
-
export declare function on(event: 'log', listener: (context: Context,
|
|
32
|
+
export declare function on(event: 'log', listener: (context: Context, tag: string, msgs: any[]) => void): void;
|
|
33
|
+
export declare function on(event: string, listener: (...args: any[]) => void): void;
|
|
34
|
+
export declare function once(event: 'app:configured' | 'app:served' | 'app:stopped', listener: (...args: any[]) => void): void;
|
|
35
|
+
export declare function once(event: 'request', listener: (action: string, params: any[], context: Context) => void): void;
|
|
36
|
+
export declare function once(event: 'success', listener: (action: string, params: any[], context: Context, result: ReturnsBody) => void): void;
|
|
37
|
+
export declare function once(event: 'fail', listener: (action: string, params: any[], context: Context, error: Error) => void): void;
|
|
38
|
+
export declare function once(event: 'log', listener: (context: Context, tag: string, msgs: any[]) => void): void;
|
|
39
|
+
export declare function once(event: string, listener: (...args: any[]) => void): void;
|
|
40
|
+
export declare function off(event: 'app:configured' | 'app:served' | 'app:stopped' | 'request' | 'success' | 'fail' | 'log', listener: (...args: any[]) => void): void;
|
|
41
|
+
export declare function off(event: string, listener: (...args: any[]) => void): void;
|
|
42
|
+
export declare function emit(event: string, ...args: any[]): boolean;
|
|
32
43
|
/**
|
|
33
44
|
* Call an Function on RPC server
|
|
34
45
|
* @param action
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare function configure(): any
|
|
1
|
+
export declare function configure(): Promise<any>;
|
package/types/index.d.ts
CHANGED
|
@@ -5,14 +5,14 @@ import Modules from './modules';
|
|
|
5
5
|
export { ReturnsBody } from './app';
|
|
6
6
|
export { Module, ModuleConfig };
|
|
7
7
|
export declare const modules: Modules;
|
|
8
|
-
export declare const asyncStore: import("async_hooks").AsyncLocalStorage<app.Context>, setMethods: typeof app.setMethods, getMethods: typeof app.getMethods, kvMethods: Map<string, Function>, sourceKVMethods: Map<string, Function>, call: typeof app.call, execute: typeof app.execute, on: typeof app.on;
|
|
8
|
+
export declare const asyncStore: import("async_hooks").AsyncLocalStorage<app.Context>, setMethods: typeof app.setMethods, getMethods: typeof app.getMethods, kvMethods: Map<string, Function>, sourceKVMethods: Map<string, Function>, call: typeof app.call, execute: typeof app.execute, logger: typeof app.logger, on: typeof app.on, once: typeof app.once, off: typeof app.off, emit: typeof app.emit;
|
|
9
9
|
export declare class Context extends app.Context {
|
|
10
10
|
sourceIP: string;
|
|
11
11
|
ip: string;
|
|
12
12
|
caller: string;
|
|
13
13
|
callerId: string;
|
|
14
14
|
connection?: RPCKeepAliveConnection;
|
|
15
|
-
toJSON?():
|
|
15
|
+
toJSON?(): {} & this;
|
|
16
16
|
}
|
|
17
17
|
export declare class Config {
|
|
18
18
|
[x: string]: any;
|
|
@@ -71,5 +71,6 @@ export declare function getKeepAliveConnection(name: string, id: string): RPCKee
|
|
|
71
71
|
export declare function addKeepAliveConnection(connection: RPCKeepAliveConnection): void;
|
|
72
72
|
export declare function removeKeepAliveConnection(connection: RPCKeepAliveConnection): void;
|
|
73
73
|
export declare function removeKeepAliveConnection(name: string, id: string): void;
|
|
74
|
+
export declare function setLoadBalancePolicy(policy: (name: string) => RPCKeepAliveConnection): void;
|
|
74
75
|
export declare function rpc(appName: string, action: string, params: any[], context?: Context): Promise<any>;
|
|
75
76
|
export declare function rpc(connection: RPCKeepAliveConnection, action: string, params: any[], context?: Context): Promise<any>;
|
package/types/logger.d.ts
CHANGED
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
/// <reference types="node" />
|
|
3
3
|
/// <reference types="node" />
|
|
4
4
|
import * as http from 'node:http';
|
|
5
|
-
import
|
|
5
|
+
import { Readable } from 'node:stream';
|
|
6
6
|
/**
|
|
7
7
|
* Stream => Buffer
|
|
8
8
|
*/
|
|
9
|
-
export declare function stream2buffer(stream:
|
|
9
|
+
export declare function stream2buffer(stream: Readable, totalLength?: number): Promise<Buffer>;
|
|
10
10
|
/**
|
|
11
11
|
* Request => JSONObject
|
|
12
12
|
*/
|
package/types/modules/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import Module from './module';
|
|
2
2
|
import HTTP from './http';
|
|
3
|
+
import SocketIO from './socketio';
|
|
3
4
|
export default class Modules extends Module {
|
|
4
5
|
#private;
|
|
5
6
|
/**
|
|
@@ -11,6 +12,7 @@ export default class Modules extends Module {
|
|
|
11
12
|
*/
|
|
12
13
|
builtins: {
|
|
13
14
|
http: HTTP;
|
|
15
|
+
socketio: SocketIO;
|
|
14
16
|
};
|
|
15
17
|
constructor();
|
|
16
18
|
add(module: Module): this;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ClientSocket as Socket } from './socket';
|
|
2
|
+
import SocketIOServer from './server';
|
|
3
|
+
export default class SocketIOCore extends SocketIOServer {
|
|
4
|
+
/**
|
|
5
|
+
* connect to <SocketIO RPC> service
|
|
6
|
+
*/
|
|
7
|
+
connect(url: string): Promise<Socket>;
|
|
8
|
+
/**
|
|
9
|
+
* 客户端Socket连接事件
|
|
10
|
+
*/
|
|
11
|
+
clientOnSocketConnection(socket: Socket): void;
|
|
12
|
+
clientOnDisconnect(socket: Socket, reason: any): void;
|
|
13
|
+
clientOnConnection(socket: Socket): void;
|
|
14
|
+
/**
|
|
15
|
+
* 客户端Socket断开事件
|
|
16
|
+
* @param {Socket} socket
|
|
17
|
+
*/
|
|
18
|
+
clientOnSocketDisconnect(socket: Socket, reason: any): void;
|
|
19
|
+
/**
|
|
20
|
+
* 等待socket连接
|
|
21
|
+
*/
|
|
22
|
+
clientWaitConnection(socket: Socket): Promise<void>;
|
|
23
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import SocketIOClient from './client';
|
|
2
|
+
import * as oox from '../../index';
|
|
3
|
+
import { RPCKeepAliveConnectionData, RPCConnectionAdapter } from '../../index';
|
|
4
|
+
import { Socket, sockets, ServerSocket, ClientSocket } from './socket';
|
|
5
|
+
export { Socket, sockets };
|
|
6
|
+
export default class SocketIOModule extends SocketIOClient implements RPCConnectionAdapter {
|
|
7
|
+
sockets: Map<string, Socket>;
|
|
8
|
+
serve(): Promise<void>;
|
|
9
|
+
onSyncConnection(socket: Socket): oox.RPCKeepAliveConnectionData[];
|
|
10
|
+
serverOnDisconnect(socket: ServerSocket, reason: string): void;
|
|
11
|
+
clientOnDisconnect(socket: ClientSocket, reason: any): void;
|
|
12
|
+
/**
|
|
13
|
+
*
|
|
14
|
+
* @param socket 是由哪个通道发送过来的
|
|
15
|
+
* @param connectionDatas
|
|
16
|
+
*/
|
|
17
|
+
clientOnSyncConnection(socket: Socket, connectionDatas: RPCKeepAliveConnectionData[]): void;
|
|
18
|
+
onFetchActions(socket: Socket, search: string): string[];
|
|
19
|
+
fetchActions(url: string, search?: string): Promise<RPCKeepAliveConnectionData[]>;
|
|
20
|
+
fetchActions(name: string, search?: string): Promise<RPCKeepAliveConnectionData[]>;
|
|
21
|
+
onConnection(socket: Socket): void;
|
|
22
|
+
/**
|
|
23
|
+
*
|
|
24
|
+
* @param {Socket} socket
|
|
25
|
+
*/
|
|
26
|
+
serverOnConnection(socket: ServerSocket): void;
|
|
27
|
+
call(action: string, params: any[], context: oox.Context, callback?: (returns: any) => void): Promise<oox.ReturnsBody>;
|
|
28
|
+
clientOnConnection(socket: ClientSocket): void;
|
|
29
|
+
/**
|
|
30
|
+
* socketio emit
|
|
31
|
+
*/
|
|
32
|
+
emit(url: string, action: string, params: any[]): Promise<unknown>;
|
|
33
|
+
/**
|
|
34
|
+
* RPC
|
|
35
|
+
*/
|
|
36
|
+
rpc(url: string, action: string, params: [], context?: oox.Context): Promise<any>;
|
|
37
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import * as http from 'node:http';
|
|
3
|
+
import { Server, ServerOptions } from 'socket.io';
|
|
4
|
+
import { Module, ModuleConfig } from '../../index';
|
|
5
|
+
import { ServerSocket as Socket } from './socket';
|
|
6
|
+
export declare class SocketIOConfig extends ModuleConfig {
|
|
7
|
+
port: number;
|
|
8
|
+
path: string;
|
|
9
|
+
origin: string;
|
|
10
|
+
}
|
|
11
|
+
export default class SocketIOServer extends Module {
|
|
12
|
+
#private;
|
|
13
|
+
name: string;
|
|
14
|
+
config: SocketIOConfig;
|
|
15
|
+
server: http.Server;
|
|
16
|
+
socketServer: Server;
|
|
17
|
+
setConfig(config: SocketIOConfig): void;
|
|
18
|
+
getConfig(): SocketIOConfig;
|
|
19
|
+
serve(): Promise<void>;
|
|
20
|
+
stop(): Promise<void>;
|
|
21
|
+
genSocketIOServerOptions(): Partial<ServerOptions>;
|
|
22
|
+
createSocketIOServer(): void;
|
|
23
|
+
/**
|
|
24
|
+
* 服务端Socket连接事件
|
|
25
|
+
*/
|
|
26
|
+
serverOnSocketConnection(socket: Socket): void;
|
|
27
|
+
serverOnConnection(socket: Socket): void;
|
|
28
|
+
/**
|
|
29
|
+
* 服务端Socket断开事件
|
|
30
|
+
* @param {Socket} socket
|
|
31
|
+
* @param {Error} reason
|
|
32
|
+
*/
|
|
33
|
+
serverOnSocketDisconnect(socket: Socket, reason: string): void;
|
|
34
|
+
serverOnDisconnect(socket: Socket, reason: string): void;
|
|
35
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Socket as _ServerSocket } from 'socket.io';
|
|
2
|
+
import { Socket as _ClientSocket } from 'socket.io-client';
|
|
3
|
+
import { RPCKeepAliveConnectionData } from '../../index';
|
|
4
|
+
export interface ServerSocket extends _ServerSocket {
|
|
5
|
+
data: RPCKeepAliveConnectionData;
|
|
6
|
+
}
|
|
7
|
+
export interface ClientSocket extends _ClientSocket {
|
|
8
|
+
data: RPCKeepAliveConnectionData;
|
|
9
|
+
}
|
|
10
|
+
export declare type Socket = ServerSocket | ClientSocket;
|
|
11
|
+
export declare const sockets: Map<string, Socket>;
|