oox 0.3.2 → 0.3.3
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/bin/argv.js +10 -1
- package/bin/configurer.js +3 -1
- package/bin/register.js +9 -23
- package/bin/starter.js +2 -2
- package/index.js +22 -43
- package/modules/http/index.js +2 -2
- package/modules/socketio/adapter.js +158 -0
- package/modules/socketio/index.js +4 -152
- package/modules/socketio/server.js +53 -40
- package/modules/socketio/socket.js +1 -1
- package/modules/socketio/utils.js +38 -0
- package/package.json +1 -1
- package/rpc-keepalive-connection.js +89 -0
- package/types/app.d.ts +1 -1
- package/types/index.d.ts +11 -36
- package/types/modules/http/index.d.ts +2 -2
- package/types/modules/socketio/adapter.d.ts +28 -0
- package/types/modules/socketio/index.d.ts +2 -35
- package/types/modules/socketio/server.d.ts +16 -12
- package/types/modules/socketio/socket.d.ts +8 -11
- package/types/modules/socketio/utils.d.ts +7 -0
- package/types/rpc-keepalive-connection.d.ts +57 -0
- package/modules/socketio/client.js +0 -97
- package/types/modules/socketio/client.d.ts +0 -23
package/bin/argv.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import * as FS from 'node:fs';
|
|
2
|
+
import * as PATH from 'node:path';
|
|
1
3
|
export function getAllEnvArgs() {
|
|
2
4
|
const args = process.argv.slice(2);
|
|
3
5
|
const env = {};
|
|
@@ -9,7 +11,14 @@ export function getAllEnvArgs() {
|
|
|
9
11
|
env[arg.slice(1)] = true;
|
|
10
12
|
}
|
|
11
13
|
else if (!arg.includes('=')) {
|
|
12
|
-
|
|
14
|
+
// index.js
|
|
15
|
+
const path = PATH.resolve(process.cwd(), arg);
|
|
16
|
+
if (FS.existsSync(path)) {
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
env[arg] = true;
|
|
21
|
+
}
|
|
13
22
|
}
|
|
14
23
|
else {
|
|
15
24
|
const index = arg.indexOf('=');
|
package/bin/configurer.js
CHANGED
|
@@ -19,6 +19,7 @@ function mergeFlatEnv(env) {
|
|
|
19
19
|
tmpEnv = tmpEnv[subKey];
|
|
20
20
|
}
|
|
21
21
|
tmpEnv[valueKey] = env[key];
|
|
22
|
+
delete env[key];
|
|
22
23
|
}
|
|
23
24
|
}
|
|
24
25
|
}
|
|
@@ -32,12 +33,13 @@ async function readEnvFile(filePath) {
|
|
|
32
33
|
else {
|
|
33
34
|
const finalPath = path.resolve(filePath).replace(/\\/g, '/');
|
|
34
35
|
env = await import(`file://${finalPath}`);
|
|
36
|
+
env = env.default || env;
|
|
35
37
|
}
|
|
36
38
|
}
|
|
37
39
|
else {
|
|
38
40
|
throw new Error('Env file not found: ' + filePath);
|
|
39
41
|
}
|
|
40
|
-
return env
|
|
42
|
+
return env;
|
|
41
43
|
}
|
|
42
44
|
export async function buildConfig(mergeEnv) {
|
|
43
45
|
const env = Object.create(null);
|
package/bin/register.js
CHANGED
|
@@ -1,25 +1,11 @@
|
|
|
1
1
|
import chalk from 'chalk';
|
|
2
2
|
import * as oox from '../index.js';
|
|
3
|
-
import { default as SocketIOModule } from '../modules/socketio/index.js';
|
|
4
3
|
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
|
5
|
-
function urlFormatter(url) {
|
|
6
|
-
let _url = SocketIOModule.genWebSocketUrl(url);
|
|
7
|
-
const urlObject = new URL(_url);
|
|
8
|
-
if (urlObject.pathname === '/' && !url.endsWith('/'))
|
|
9
|
-
_url += '/socket.io';
|
|
10
|
-
return _url;
|
|
11
|
-
}
|
|
12
4
|
async function connect(url, prevError = null) {
|
|
13
|
-
const
|
|
14
|
-
const { host } = oox.config;
|
|
15
|
-
const { port, path } = socketio.config;
|
|
16
|
-
const urlObject = new URL(url);
|
|
17
|
-
// check if url is self
|
|
18
|
-
if (urlObject.host === host && urlObject.port === String(port))
|
|
19
|
-
return;
|
|
5
|
+
const adapter = oox.rpcKeepAliveConnectionAdapters.get(oox.config.registryAdapter);
|
|
20
6
|
try {
|
|
21
|
-
const
|
|
22
|
-
onConnection(
|
|
7
|
+
const connection = await adapter.open(url);
|
|
8
|
+
onConnection(connection, url);
|
|
23
9
|
}
|
|
24
10
|
catch (error) {
|
|
25
11
|
if (!prevError)
|
|
@@ -28,19 +14,19 @@ async function connect(url, prevError = null) {
|
|
|
28
14
|
connect(url, error);
|
|
29
15
|
}
|
|
30
16
|
}
|
|
31
|
-
async function onConnection(
|
|
32
|
-
const { name } =
|
|
33
|
-
|
|
34
|
-
console.log(chalk.red('[Registry]'), `Service<${name}>`, chalk.underline.red(`${url}`), 'disconnected.');
|
|
17
|
+
async function onConnection(connection, url) {
|
|
18
|
+
const { name } = connection.data;
|
|
19
|
+
connection.once('disconnect', async () => {
|
|
20
|
+
console.log(chalk.red('[Registry]'), `Service<${name}>`, chalk.underline.red(`${connection.data.url || url}`), 'disconnected.');
|
|
35
21
|
await delay(1000);
|
|
36
22
|
connect(url);
|
|
37
23
|
});
|
|
38
|
-
console.log(chalk.green('[Registry]'), `Service<${name}>`, chalk.underline.green(`${url}`), 'connected.');
|
|
24
|
+
console.log(chalk.green('[Registry]'), `Service<${name}>`, chalk.underline.green(`${connection.data.url || url}`), 'connected.');
|
|
39
25
|
}
|
|
40
26
|
export async function registry(urls) {
|
|
41
27
|
if ('string' === typeof urls)
|
|
42
28
|
urls = [urls];
|
|
43
29
|
for (const url of urls) {
|
|
44
|
-
connect(
|
|
30
|
+
connect(url);
|
|
45
31
|
}
|
|
46
32
|
}
|
package/bin/starter.js
CHANGED
|
@@ -53,9 +53,9 @@ export async function startup() {
|
|
|
53
53
|
console.log();
|
|
54
54
|
console.log('Service', chalk.bold(`${oox.config.name}`), 'running.');
|
|
55
55
|
if (http.config.enabled)
|
|
56
|
-
console.log(' at', chalk.underline.green(http.
|
|
56
|
+
console.log(' at', chalk.underline.green(http.getURL()));
|
|
57
57
|
if (socketio.config.enabled)
|
|
58
|
-
console.log(' at', chalk.underline.green(socketio.
|
|
58
|
+
console.log(' at', chalk.underline.green(socketio.getURL()));
|
|
59
59
|
console.log();
|
|
60
60
|
// 服务注册
|
|
61
61
|
if (config.registry)
|
package/index.js
CHANGED
|
@@ -3,6 +3,8 @@ import * as app from './app.js';
|
|
|
3
3
|
import { getIPAddress } from './utils.js';
|
|
4
4
|
import Module, { ModuleConfig } from './modules/module.js';
|
|
5
5
|
import Modules from './modules/index.js';
|
|
6
|
+
import { RPCKeepAliveConnection, rpcKeepAliveConnectionAdapters, keepAliveConnections, enabledKeepAliveConnections } from './rpc-keepalive-connection.js';
|
|
7
|
+
export { RPCKeepAliveConnection, rpcKeepAliveConnectionAdapters, keepAliveConnections, enabledKeepAliveConnections };
|
|
6
8
|
export { Module, ModuleConfig };
|
|
7
9
|
export const modules = new Modules;
|
|
8
10
|
export const { asyncStore, setMethods, getMethods, kvMethods, sourceKVMethods, call, execute, logger, on, once, off, emit, } = app;
|
|
@@ -24,6 +26,8 @@ export class Context extends app.Context {
|
|
|
24
26
|
}
|
|
25
27
|
}
|
|
26
28
|
export class Config {
|
|
29
|
+
// 服务ID
|
|
30
|
+
id = randomUUID();
|
|
27
31
|
// 服务名称
|
|
28
32
|
name = 'local';
|
|
29
33
|
// 服务列表路径
|
|
@@ -45,6 +49,10 @@ export class Config {
|
|
|
45
49
|
origin = '';
|
|
46
50
|
// 默认返回错误调用栈信息信息
|
|
47
51
|
errorStack = true;
|
|
52
|
+
// 服务注册列表
|
|
53
|
+
registry = [];
|
|
54
|
+
// 服务注册适配器
|
|
55
|
+
registryAdapter = 'socketio';
|
|
48
56
|
}
|
|
49
57
|
export const config = new Config();
|
|
50
58
|
let genTraceIdFunction = () => randomUUID();
|
|
@@ -78,55 +86,26 @@ export async function serve() {
|
|
|
78
86
|
export async function stop() {
|
|
79
87
|
await modules.stop();
|
|
80
88
|
}
|
|
81
|
-
export class RPCKeepAliveConnection {
|
|
82
|
-
data;
|
|
83
|
-
nativeConnection = null;
|
|
84
|
-
adapter = null;
|
|
85
|
-
constructor(adapter, nativeConnection, data) {
|
|
86
|
-
this.adapter = adapter;
|
|
87
|
-
this.nativeConnection = nativeConnection;
|
|
88
|
-
if (data)
|
|
89
|
-
this.data = data;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
export const keepAliveConnections = new Map();
|
|
93
|
-
export function getKeepAliveConnections(name) {
|
|
94
|
-
return keepAliveConnections.get(name) || new Map();
|
|
95
|
-
}
|
|
96
|
-
export function getKeepAliveConnection(name, id) {
|
|
97
|
-
const connections = keepAliveConnections.get(name);
|
|
98
|
-
if (!connections)
|
|
99
|
-
return null;
|
|
100
|
-
return connections.get(id);
|
|
101
|
-
}
|
|
102
89
|
export function addKeepAliveConnection(connection) {
|
|
103
|
-
|
|
104
|
-
if (keepAliveConnections.has(name)) {
|
|
105
|
-
keepAliveConnections.get(name).set(id, connection);
|
|
106
|
-
}
|
|
107
|
-
else {
|
|
108
|
-
keepAliveConnections.set(name, new Map([[id, connection]]));
|
|
109
|
-
}
|
|
90
|
+
keepAliveConnections.add(connection);
|
|
110
91
|
}
|
|
111
|
-
export function removeKeepAliveConnection(
|
|
112
|
-
if (
|
|
113
|
-
|
|
114
|
-
|
|
92
|
+
export function removeKeepAliveConnection(arg1, arg2) {
|
|
93
|
+
if (typeof arg1 === 'string') {
|
|
94
|
+
keepAliveConnections.remove(arg1, arg2);
|
|
95
|
+
enabledKeepAliveConnections.remove(arg1, arg2);
|
|
115
96
|
}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
if (!group.size)
|
|
120
|
-
keepAliveConnections.delete(name);
|
|
97
|
+
else {
|
|
98
|
+
keepAliveConnections.remove(arg1);
|
|
99
|
+
enabledKeepAliveConnections.remove(arg1);
|
|
121
100
|
}
|
|
122
101
|
}
|
|
123
102
|
/**
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
103
|
+
* random connection select for default load balance policy
|
|
104
|
+
* @param name service name
|
|
105
|
+
* @returns selected connection
|
|
106
|
+
*/
|
|
128
107
|
let loadBalancePolicy = (name) => {
|
|
129
|
-
const connections =
|
|
108
|
+
const connections = enabledKeepAliveConnections.getConnectionsOfService(name);
|
|
130
109
|
if (!connections || !connections.size)
|
|
131
110
|
return null;
|
|
132
111
|
const arrayConnections = Array.from(connections.values());
|
|
@@ -151,5 +130,5 @@ export async function rpc(arg1, action, params, context) {
|
|
|
151
130
|
}
|
|
152
131
|
else
|
|
153
132
|
throw new Error(`Unknown rpc arg1<${arg1}>`);
|
|
154
|
-
return connection.adapter.rpc(connection
|
|
133
|
+
return connection.adapter.rpc(connection, action, params, context);
|
|
155
134
|
}
|
package/modules/http/index.js
CHANGED
|
@@ -28,11 +28,11 @@ export default class HTTPModule extends Module {
|
|
|
28
28
|
config = new HTTPConfig;
|
|
29
29
|
server = null;
|
|
30
30
|
router = new Router();
|
|
31
|
-
|
|
31
|
+
getURL() {
|
|
32
32
|
const { host } = oox.config;
|
|
33
33
|
const { port, path } = this.config;
|
|
34
34
|
const protocol = this.config.ssl.enabled ? `https:` : `http:`;
|
|
35
|
-
return `${protocol}//${host}:${port}${path}
|
|
35
|
+
return new URL(`${protocol}//${host}:${port}${path}`);
|
|
36
36
|
}
|
|
37
37
|
// 注册GET路由
|
|
38
38
|
get(path, ...args) {
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import * as SocketIOClient from 'socket.io-client';
|
|
2
|
+
import * as oox from '../../index.js';
|
|
3
|
+
import { OOXEvent, genWebSocketURL, isWebSocketURL } from './utils.js';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
export default class SocketIOAdapter {
|
|
6
|
+
/**
|
|
7
|
+
* 客户端发送连接列表
|
|
8
|
+
* @param datas
|
|
9
|
+
*/
|
|
10
|
+
[OOXEvent.SYNC_CONNECTIONS](datas) {
|
|
11
|
+
for (const data of datas) {
|
|
12
|
+
if (data.name === oox.config.name)
|
|
13
|
+
continue;
|
|
14
|
+
if (!data.url || !isWebSocketURL(data.url))
|
|
15
|
+
continue;
|
|
16
|
+
const has = oox.keepAliveConnections.has(data.name, data.id);
|
|
17
|
+
if (has)
|
|
18
|
+
continue;
|
|
19
|
+
this.open(data.url).catch((error) => console.error(error));
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
bindClientConnectionEvents(connection) {
|
|
23
|
+
const socket = connection.nativeConnection;
|
|
24
|
+
socket.on(OOXEvent.CONNECTED, ({ id, name }) => {
|
|
25
|
+
connection.updateIdAndName(id, name);
|
|
26
|
+
connection.enabled = true;
|
|
27
|
+
socket.emit(OOXEvent.SYNC_CONNECTIONS, this[OOXEvent.SYNC_CONNECTIONS].bind(this));
|
|
28
|
+
});
|
|
29
|
+
socket.on(OOXEvent.DISABLED, () => {
|
|
30
|
+
connection.enabled = false;
|
|
31
|
+
});
|
|
32
|
+
socket.on('disconnect', (reason) => {
|
|
33
|
+
connection.emit('disconnect');
|
|
34
|
+
oox.removeKeepAliveConnection(connection);
|
|
35
|
+
socket.removeAllListeners();
|
|
36
|
+
socket.disconnect();
|
|
37
|
+
});
|
|
38
|
+
socket.on('connect', () => {
|
|
39
|
+
connection.emit('connect');
|
|
40
|
+
});
|
|
41
|
+
socket.on('connect_error', (error) => {
|
|
42
|
+
connection.emit('error', error);
|
|
43
|
+
oox.removeKeepAliveConnection(connection);
|
|
44
|
+
socket.removeAllListeners();
|
|
45
|
+
socket.disconnect();
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
newConnection(url) {
|
|
49
|
+
const { id, host, name } = oox.config;
|
|
50
|
+
const headers = {
|
|
51
|
+
'x-ip': host,
|
|
52
|
+
'x-caller': name,
|
|
53
|
+
'x-caller-id': id,
|
|
54
|
+
};
|
|
55
|
+
let mURL;
|
|
56
|
+
if ('string' === typeof url) {
|
|
57
|
+
mURL = genWebSocketURL(url);
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
mURL = url;
|
|
61
|
+
}
|
|
62
|
+
const socket = SocketIOClient.io(mURL.origin, {
|
|
63
|
+
extraHeaders: headers,
|
|
64
|
+
path: mURL.pathname,
|
|
65
|
+
autoConnect: false,
|
|
66
|
+
});
|
|
67
|
+
const data = {
|
|
68
|
+
name: 'anonymous',
|
|
69
|
+
id: randomUUID(),
|
|
70
|
+
host: mURL.host,
|
|
71
|
+
url: mURL
|
|
72
|
+
};
|
|
73
|
+
const connection = new oox.RPCKeepAliveConnection(this, socket, data);
|
|
74
|
+
return connection;
|
|
75
|
+
}
|
|
76
|
+
async open(url) {
|
|
77
|
+
const connection = this.newConnection(url);
|
|
78
|
+
oox.addKeepAliveConnection(connection);
|
|
79
|
+
this.bindClientConnectionEvents(connection);
|
|
80
|
+
this.bindCall(connection);
|
|
81
|
+
await new Promise((resolve, reject) => {
|
|
82
|
+
connection.once('enabled', resolve);
|
|
83
|
+
connection.once('error', reject);
|
|
84
|
+
connection.once('disconnect', () => {
|
|
85
|
+
reject(new Error('disconnect'));
|
|
86
|
+
});
|
|
87
|
+
connection.nativeConnection.connect();
|
|
88
|
+
});
|
|
89
|
+
return connection;
|
|
90
|
+
}
|
|
91
|
+
async close(connection) {
|
|
92
|
+
connection.nativeConnection.disconnect();
|
|
93
|
+
return Promise.resolve();
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* socketio emit
|
|
97
|
+
*/
|
|
98
|
+
async emit(socket, event, params) {
|
|
99
|
+
if (!socket.connected)
|
|
100
|
+
throw new Error('Socket not connected');
|
|
101
|
+
return await new Promise((resolve, reject) => {
|
|
102
|
+
const onError = (reason) => {
|
|
103
|
+
const message = 'string' === typeof reason ? reason : reason instanceof Error ? reason.message : 'connect error';
|
|
104
|
+
reject(new Error(message));
|
|
105
|
+
};
|
|
106
|
+
// RPC 执行时中断连接
|
|
107
|
+
socket.once('disconnect', onError);
|
|
108
|
+
socket.emit(event, ...params, (returns) => {
|
|
109
|
+
socket.offAny(onError);
|
|
110
|
+
resolve(returns);
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* RPC
|
|
116
|
+
*/
|
|
117
|
+
async rpc(connection, action, params, context) {
|
|
118
|
+
if (!context)
|
|
119
|
+
context = oox.getContext();
|
|
120
|
+
const { success, error, body } = await this.emit(connection.nativeConnection, 'call', [action, params, context]);
|
|
121
|
+
if (success)
|
|
122
|
+
return body;
|
|
123
|
+
else if (error)
|
|
124
|
+
throw new Error(error.message);
|
|
125
|
+
else
|
|
126
|
+
throw new Error('[RPC] Unknown Error');
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* 绑定 call 事件
|
|
130
|
+
* @param connection
|
|
131
|
+
*/
|
|
132
|
+
bindCall(connection) {
|
|
133
|
+
const { id, name, host } = connection.data;
|
|
134
|
+
const connectionContext = {
|
|
135
|
+
sourceIP: '',
|
|
136
|
+
ip: host,
|
|
137
|
+
caller: name,
|
|
138
|
+
callerId: id,
|
|
139
|
+
connection
|
|
140
|
+
};
|
|
141
|
+
connection.nativeConnection.on('call', async (action, params, context, callback) => {
|
|
142
|
+
if ('object' !== typeof context)
|
|
143
|
+
context = oox.genContext(connectionContext);
|
|
144
|
+
else
|
|
145
|
+
context = oox.genContext(Object.assign(context, connectionContext));
|
|
146
|
+
this.call(action, params, context, callback);
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
async call(action, params, context, callback) {
|
|
150
|
+
const returns = await oox.call(action, params, context);
|
|
151
|
+
if (returns.error && !oox.config.errorStack) {
|
|
152
|
+
// 不返回错误调用栈信息
|
|
153
|
+
delete returns.error.stack;
|
|
154
|
+
}
|
|
155
|
+
'function' === typeof callback && callback(returns);
|
|
156
|
+
return returns;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
@@ -1,11 +1,7 @@
|
|
|
1
|
-
import * as
|
|
2
|
-
import SocketIOClient from './client.js';
|
|
1
|
+
import * as PATH from 'node:path';
|
|
3
2
|
import * as oox from '../../index.js';
|
|
4
|
-
import
|
|
5
|
-
|
|
6
|
-
export { sockets };
|
|
7
|
-
export default class SocketIOModule extends SocketIOClient {
|
|
8
|
-
sockets = sockets;
|
|
3
|
+
import SocketINServer from './server.js';
|
|
4
|
+
export default class SocketIOModule extends SocketINServer {
|
|
9
5
|
async serve() {
|
|
10
6
|
await this.stop();
|
|
11
7
|
const _http = oox.modules.builtins.http;
|
|
@@ -18,154 +14,10 @@ export default class SocketIOModule extends SocketIOClient {
|
|
|
18
14
|
// http 模块未被禁用
|
|
19
15
|
isShareServer &&= httpConfig.enabled;
|
|
20
16
|
if (isShareServer) {
|
|
21
|
-
config.path =
|
|
17
|
+
config.path = PATH.posix.join(httpConfig.path, config.path);
|
|
22
18
|
this.server = _http.server;
|
|
23
19
|
this.config.ssl = _http.config.ssl;
|
|
24
20
|
}
|
|
25
21
|
await super.serve();
|
|
26
22
|
}
|
|
27
|
-
onSyncConnection(socket) {
|
|
28
|
-
const mSockets = Array.from(sockets.values())
|
|
29
|
-
.filter(s => s !== socket &&
|
|
30
|
-
s.data.name !== socket.data.name &&
|
|
31
|
-
/^wss?:\/\/.+$/.test(s.data.id));
|
|
32
|
-
return mSockets.map(s => s.data);
|
|
33
|
-
}
|
|
34
|
-
serverOnDisconnect(socket, reason) {
|
|
35
|
-
super.serverOnDisconnect(socket, reason);
|
|
36
|
-
removeKeepAliveConnection(socket.data.name, socket.data.id);
|
|
37
|
-
}
|
|
38
|
-
clientOnDisconnect(socket, reason) {
|
|
39
|
-
super.clientOnDisconnect(socket, reason);
|
|
40
|
-
removeKeepAliveConnection(socket.data.name, socket.data.id);
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
*
|
|
44
|
-
* @param socket 是由哪个通道发送过来的
|
|
45
|
-
* @param connectionDatas
|
|
46
|
-
*/
|
|
47
|
-
clientOnSyncConnection(socket, connectionDatas) {
|
|
48
|
-
for (const data of connectionDatas)
|
|
49
|
-
if (!sockets.has(data.id))
|
|
50
|
-
this.connect(data.id).catch((error) => console.error(error));
|
|
51
|
-
}
|
|
52
|
-
onFetchActions(socket, search) {
|
|
53
|
-
const data = [];
|
|
54
|
-
for (const key of oox.kvMethods.keys())
|
|
55
|
-
if (!key.endsWith('_proxy') && key.includes(search))
|
|
56
|
-
data.push(key);
|
|
57
|
-
return data;
|
|
58
|
-
}
|
|
59
|
-
fetchActions(id, search = '') {
|
|
60
|
-
let socket = sockets.get(id);
|
|
61
|
-
if (!socket) {
|
|
62
|
-
const connections = getKeepAliveConnections(id);
|
|
63
|
-
if (!connections || !connections.size)
|
|
64
|
-
throw new Error(`Unknown service identify<${id}>`);
|
|
65
|
-
id = connections.keys().next().value;
|
|
66
|
-
socket = sockets.get(id);
|
|
67
|
-
}
|
|
68
|
-
if (!socket)
|
|
69
|
-
throw new Error(`Unknown service identify<${id}>`);
|
|
70
|
-
return this.emit(socket.data.id, 'fetchActions', [search]);
|
|
71
|
-
}
|
|
72
|
-
onConnection(socket) {
|
|
73
|
-
const { id, name, host } = socket.data;
|
|
74
|
-
const connection = new RPCKeepAliveConnection(this, id, socket.data);
|
|
75
|
-
addKeepAliveConnection(connection);
|
|
76
|
-
const connectionContext = {
|
|
77
|
-
sourceIP: '',
|
|
78
|
-
ip: host,
|
|
79
|
-
caller: name,
|
|
80
|
-
callerId: id,
|
|
81
|
-
connection
|
|
82
|
-
};
|
|
83
|
-
socket.on('fetchActions', async (search, fn) => {
|
|
84
|
-
if ('function' !== typeof fn)
|
|
85
|
-
return;
|
|
86
|
-
const data = await this.onFetchActions(socket, search);
|
|
87
|
-
fn(data);
|
|
88
|
-
});
|
|
89
|
-
socket.on('call', async (action, params, context, callback) => {
|
|
90
|
-
if ('object' !== typeof context)
|
|
91
|
-
context = oox.genContext(connectionContext);
|
|
92
|
-
else
|
|
93
|
-
context = oox.genContext(Object.assign(context, connectionContext));
|
|
94
|
-
this.call(action, params, context, callback);
|
|
95
|
-
});
|
|
96
|
-
}
|
|
97
|
-
/**
|
|
98
|
-
*
|
|
99
|
-
* @param {Socket} socket
|
|
100
|
-
*/
|
|
101
|
-
serverOnConnection(socket) {
|
|
102
|
-
super.serverOnConnection(socket);
|
|
103
|
-
socket.setMaxListeners(0);
|
|
104
|
-
socket.on('syncConnection', async (fn) => {
|
|
105
|
-
if ('function' !== typeof fn)
|
|
106
|
-
return;
|
|
107
|
-
const data = this.onSyncConnection(socket);
|
|
108
|
-
fn(data);
|
|
109
|
-
});
|
|
110
|
-
this.onConnection(socket);
|
|
111
|
-
}
|
|
112
|
-
async call(action, params, context, callback) {
|
|
113
|
-
const returns = await oox.call(action, params, context);
|
|
114
|
-
if (!oox.config.errorStack && returns.error) {
|
|
115
|
-
// 不返回错误调用栈信息
|
|
116
|
-
delete returns.error.stack;
|
|
117
|
-
}
|
|
118
|
-
'function' === typeof callback && callback(returns);
|
|
119
|
-
return returns;
|
|
120
|
-
}
|
|
121
|
-
clientOnConnection(socket) {
|
|
122
|
-
super.clientOnConnection(socket);
|
|
123
|
-
socket.emit('syncConnection', (socketDatas) => this.clientOnSyncConnection(socket, socketDatas));
|
|
124
|
-
this.onConnection(socket);
|
|
125
|
-
}
|
|
126
|
-
/**
|
|
127
|
-
* socketio emit
|
|
128
|
-
*/
|
|
129
|
-
async emit(url, event, params) {
|
|
130
|
-
let socket = null;
|
|
131
|
-
try {
|
|
132
|
-
socket = await this.connect(url);
|
|
133
|
-
}
|
|
134
|
-
catch (error) {
|
|
135
|
-
// try again
|
|
136
|
-
socket = await this.connect(url);
|
|
137
|
-
}
|
|
138
|
-
try {
|
|
139
|
-
return await new Promise((resolve, reject) => {
|
|
140
|
-
const onError = (reason) => {
|
|
141
|
-
const message = 'string' === typeof reason ? reason : reason instanceof Error ? reason.message : 'connect error';
|
|
142
|
-
reject(new Error(message));
|
|
143
|
-
};
|
|
144
|
-
// RPC 执行时中断连接
|
|
145
|
-
socket.once('disconnect', onError);
|
|
146
|
-
socket.emit(event, ...params, (returns) => {
|
|
147
|
-
socket.off('disconnect', onError);
|
|
148
|
-
resolve(returns);
|
|
149
|
-
});
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
catch (error) {
|
|
153
|
-
throw new Error(error.message);
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
/**
|
|
157
|
-
* RPC
|
|
158
|
-
*/
|
|
159
|
-
async rpc(url, action, params, context) {
|
|
160
|
-
if (!context || !context.traceId) {
|
|
161
|
-
context = oox.getContext();
|
|
162
|
-
}
|
|
163
|
-
const { success, error, body } = await this.emit(url, 'call', [action, params, context]);
|
|
164
|
-
if (success)
|
|
165
|
-
return body;
|
|
166
|
-
else if (error)
|
|
167
|
-
throw new Error(error.message);
|
|
168
|
-
else
|
|
169
|
-
throw new Error('[RPC] Unknown Error');
|
|
170
|
-
}
|
|
171
23
|
}
|
|
@@ -3,7 +3,8 @@ import * as https from 'node:https';
|
|
|
3
3
|
import { Server } from 'socket.io';
|
|
4
4
|
import * as oox from '../../index.js';
|
|
5
5
|
import { Module, ModuleConfig } from '../../index.js';
|
|
6
|
-
import
|
|
6
|
+
import SocketIOAdapter from './adapter.js';
|
|
7
|
+
import { isWebSocketURL, OOXEvent } from './utils.js';
|
|
7
8
|
export class SocketIOConfig extends ModuleConfig {
|
|
8
9
|
// listen port
|
|
9
10
|
port = 0;
|
|
@@ -32,30 +33,12 @@ export default class SocketIOServer extends Module {
|
|
|
32
33
|
#isSelfServer = false;
|
|
33
34
|
server = null;
|
|
34
35
|
socketServer = null;
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}
|
|
38
|
-
static genWebSocketUrl(url) {
|
|
39
|
-
// :6000
|
|
40
|
-
if (url.startsWith(':'))
|
|
41
|
-
url = oox.config.host + url;
|
|
42
|
-
// 127.0.0.1:6000
|
|
43
|
-
if (!/^\w+?:\/.+$/.test(url))
|
|
44
|
-
url = 'ws://' + url;
|
|
45
|
-
const urlObject = new URL(url);
|
|
46
|
-
if (urlObject.protocol !== 'wss:') {
|
|
47
|
-
if (urlObject.port === '443')
|
|
48
|
-
urlObject.protocol = 'wss:';
|
|
49
|
-
else
|
|
50
|
-
urlObject.protocol = 'ws:';
|
|
51
|
-
}
|
|
52
|
-
return urlObject.toString();
|
|
53
|
-
}
|
|
54
|
-
getUrl() {
|
|
36
|
+
adapter = new SocketIOAdapter();
|
|
37
|
+
getURL() {
|
|
55
38
|
const { host } = oox.config;
|
|
56
39
|
const { port, path } = this.config;
|
|
57
40
|
const protocol = this.config.ssl.enabled ? 'wss:' : 'ws:';
|
|
58
|
-
return `${protocol}//${host}:${port}${path}
|
|
41
|
+
return new URL(`${protocol}//${host}:${port}${path}`);
|
|
59
42
|
}
|
|
60
43
|
setConfig(config) {
|
|
61
44
|
Object.assign(this.config, config);
|
|
@@ -70,6 +53,7 @@ export default class SocketIOServer extends Module {
|
|
|
70
53
|
return this.config;
|
|
71
54
|
}
|
|
72
55
|
async serve() {
|
|
56
|
+
oox.rpcKeepAliveConnectionAdapters.set(this.name, this.adapter);
|
|
73
57
|
await this.stop();
|
|
74
58
|
const { port, ssl } = this.config;
|
|
75
59
|
const isSelfServer = this.#isSelfServer = this.server ? true : false;
|
|
@@ -149,6 +133,7 @@ export default class SocketIOServer extends Module {
|
|
|
149
133
|
this.serverOnSocketConnection(socket);
|
|
150
134
|
}
|
|
151
135
|
catch (error) {
|
|
136
|
+
console.error(error);
|
|
152
137
|
socket.send(error.message).disconnect(true);
|
|
153
138
|
}
|
|
154
139
|
});
|
|
@@ -159,30 +144,58 @@ export default class SocketIOServer extends Module {
|
|
|
159
144
|
serverOnSocketConnection(socket) {
|
|
160
145
|
const headers = socket.handshake.headers;
|
|
161
146
|
const callerId = String(headers['x-caller-id'] || '') || socket.id;
|
|
162
|
-
// 已经存在相同的连接
|
|
163
|
-
if (sockets.has(callerId))
|
|
164
|
-
throw new Error('Connection Exists');
|
|
165
147
|
// client ip or caller service ip
|
|
166
148
|
const ip = String(headers['x-real-ip'] || headers['x-ip'] || socket.handshake.address);
|
|
167
149
|
// service name
|
|
168
150
|
const caller = String(headers['x-caller'] || 'anonymous');
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
151
|
+
const connection = new oox.RPCKeepAliveConnection(this.adapter, socket, {
|
|
152
|
+
host: ip,
|
|
153
|
+
name: caller,
|
|
154
|
+
id: callerId,
|
|
155
|
+
});
|
|
156
|
+
oox.addKeepAliveConnection(connection);
|
|
157
|
+
this.bindServerConnectionEvents(connection);
|
|
158
|
+
this.adapter.bindCall(connection);
|
|
159
|
+
connection.enabled = true;
|
|
160
|
+
socket.emit(OOXEvent.CONNECTED, {
|
|
161
|
+
id: oox.config.id,
|
|
162
|
+
name: oox.config.name
|
|
163
|
+
});
|
|
175
164
|
}
|
|
176
|
-
serverOnConnection(socket) { }
|
|
177
165
|
/**
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
166
|
+
* 服务器发送连接列表
|
|
167
|
+
* @param connection
|
|
168
|
+
*/
|
|
169
|
+
[OOXEvent.SYNC_CONNECTIONS](connection) {
|
|
170
|
+
const socket = connection.nativeConnection;
|
|
171
|
+
const datas = [];
|
|
172
|
+
for (const [name, connections] of oox.enabledKeepAliveConnections.entries()) {
|
|
173
|
+
if (name === connection.data.name)
|
|
174
|
+
continue;
|
|
175
|
+
for (const conn of Array.from(connections.values())) {
|
|
176
|
+
if (!conn.data.url || !isWebSocketURL(conn.data.url))
|
|
177
|
+
continue;
|
|
178
|
+
datas.push(conn.data);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return datas;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* 绑定服务器连接事件
|
|
185
|
+
* @param connection
|
|
181
186
|
*/
|
|
182
|
-
|
|
183
|
-
socket
|
|
184
|
-
|
|
185
|
-
|
|
187
|
+
bindServerConnectionEvents(connection) {
|
|
188
|
+
const socket = connection.nativeConnection;
|
|
189
|
+
socket.on(OOXEvent.SYNC_CONNECTIONS, async (fn) => {
|
|
190
|
+
if ('function' !== typeof fn)
|
|
191
|
+
return;
|
|
192
|
+
const datas = this[OOXEvent.SYNC_CONNECTIONS](connection);
|
|
193
|
+
fn(datas);
|
|
194
|
+
});
|
|
195
|
+
socket.on('disconnecting', (reason) => {
|
|
196
|
+
oox.removeKeepAliveConnection(connection);
|
|
197
|
+
socket.removeAllListeners();
|
|
198
|
+
connection.emit('disconnect');
|
|
199
|
+
});
|
|
186
200
|
}
|
|
187
|
-
serverOnDisconnect(socket, reason) { }
|
|
188
201
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export var OOXEvent;
|
|
2
|
+
(function (OOXEvent) {
|
|
3
|
+
OOXEvent["CONNECTED"] = "oox:connected";
|
|
4
|
+
OOXEvent["DISABLED"] = "oox:disabled";
|
|
5
|
+
OOXEvent["SYNC_CONNECTIONS"] = "oox:sync_connections";
|
|
6
|
+
})(OOXEvent || (OOXEvent = {}));
|
|
7
|
+
export function isWebSocketURL(url) {
|
|
8
|
+
if ('string' === typeof url) {
|
|
9
|
+
return /^wss?:\/\/.+$/.test(url);
|
|
10
|
+
}
|
|
11
|
+
else {
|
|
12
|
+
return url.protocol === 'ws:' || url.protocol === 'wss:';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export function genWebSocketURL(url) {
|
|
16
|
+
// :6000
|
|
17
|
+
if (url.startsWith(':'))
|
|
18
|
+
url = 'ws://localhost' + url;
|
|
19
|
+
// 127.0.0.1:6000
|
|
20
|
+
if (!/^\w+?:\/.+$/.test(url))
|
|
21
|
+
url = 'ws://' + url;
|
|
22
|
+
const urlObject = new URL(url);
|
|
23
|
+
// :8000 => :8000/socket.io
|
|
24
|
+
const notSetPath = !urlObject.pathname || (urlObject.pathname === '/'
|
|
25
|
+
&& !url.endsWith('/')
|
|
26
|
+
&& !urlObject.search
|
|
27
|
+
&& !urlObject.hash);
|
|
28
|
+
if (notSetPath) {
|
|
29
|
+
urlObject.pathname = '/socket.io';
|
|
30
|
+
}
|
|
31
|
+
if (urlObject.protocol !== 'wss:') {
|
|
32
|
+
if (urlObject.port === '443')
|
|
33
|
+
urlObject.protocol = 'wss:';
|
|
34
|
+
else
|
|
35
|
+
urlObject.protocol = 'ws:';
|
|
36
|
+
}
|
|
37
|
+
return urlObject;
|
|
38
|
+
}
|
package/package.json
CHANGED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import EventEmitter from 'node:events';
|
|
2
|
+
export class RPCKeepAliveConnection extends EventEmitter {
|
|
3
|
+
// 连接是否可用
|
|
4
|
+
#enabled = false;
|
|
5
|
+
data;
|
|
6
|
+
nativeConnection;
|
|
7
|
+
adapter;
|
|
8
|
+
constructor(adapter, nativeConnection, data) {
|
|
9
|
+
super();
|
|
10
|
+
this.adapter = adapter;
|
|
11
|
+
this.nativeConnection = nativeConnection;
|
|
12
|
+
this.data = data;
|
|
13
|
+
}
|
|
14
|
+
set enabled(enabled) {
|
|
15
|
+
if (enabled !== this.#enabled) {
|
|
16
|
+
this.#enabled = enabled;
|
|
17
|
+
this.emit(enabled ? 'enabled' : 'disabled');
|
|
18
|
+
if (enabled) {
|
|
19
|
+
enabledKeepAliveConnections.add(this);
|
|
20
|
+
}
|
|
21
|
+
else {
|
|
22
|
+
enabledKeepAliveConnections.remove(this);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
get enabled() {
|
|
27
|
+
return this.#enabled;
|
|
28
|
+
}
|
|
29
|
+
updateId(newId) {
|
|
30
|
+
keepAliveConnections.remove(this);
|
|
31
|
+
this.data.id = newId;
|
|
32
|
+
keepAliveConnections.add(this);
|
|
33
|
+
}
|
|
34
|
+
updateName(newName) {
|
|
35
|
+
keepAliveConnections.remove(this);
|
|
36
|
+
this.data.name = newName;
|
|
37
|
+
keepAliveConnections.add(this);
|
|
38
|
+
}
|
|
39
|
+
updateIdAndName(newId, newName) {
|
|
40
|
+
keepAliveConnections.remove(this);
|
|
41
|
+
this.data.id = newId;
|
|
42
|
+
this.data.name = newName;
|
|
43
|
+
keepAliveConnections.add(this);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export class KeepAliveConnectionStore {
|
|
47
|
+
#map = new Map();
|
|
48
|
+
entries() {
|
|
49
|
+
return this.#map.entries();
|
|
50
|
+
}
|
|
51
|
+
getConnectionsOfService(name) {
|
|
52
|
+
return this.#map.get(name) || new Map();
|
|
53
|
+
}
|
|
54
|
+
has(name, id) {
|
|
55
|
+
const connections = this.#map.get(name);
|
|
56
|
+
if (!connections)
|
|
57
|
+
return false;
|
|
58
|
+
return connections.has(id);
|
|
59
|
+
}
|
|
60
|
+
get(name, id) {
|
|
61
|
+
const connections = this.#map.get(name);
|
|
62
|
+
if (!connections)
|
|
63
|
+
return null;
|
|
64
|
+
return connections.get(id) || null;
|
|
65
|
+
}
|
|
66
|
+
add(connection) {
|
|
67
|
+
const { name, id } = connection.data;
|
|
68
|
+
const connections = this.#map.get(name);
|
|
69
|
+
if (connections) {
|
|
70
|
+
connections.set(id, connection);
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
this.#map.set(name, new Map([[id, connection]]));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
remove(name, id) {
|
|
77
|
+
if (name instanceof RPCKeepAliveConnection) {
|
|
78
|
+
id = name.data.id;
|
|
79
|
+
name = name.data.name;
|
|
80
|
+
}
|
|
81
|
+
const connections = this.#map.get(name);
|
|
82
|
+
if (connections && id !== undefined) {
|
|
83
|
+
connections.delete(id);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
export const rpcKeepAliveConnectionAdapters = new Map();
|
|
88
|
+
export const keepAliveConnections = new KeepAliveConnectionStore();
|
|
89
|
+
export const enabledKeepAliveConnections = new KeepAliveConnectionStore();
|
package/types/app.d.ts
CHANGED
package/types/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import * as app from './app.js';
|
|
2
2
|
import Module, { ModuleConfig } from './modules/module.js';
|
|
3
3
|
import Modules from './modules/index.js';
|
|
4
|
+
import { RPCKeepAliveConnectionAdapter, RPCKeepAliveConnection, RPCKeepAliveConnectionData, rpcKeepAliveConnectionAdapters, keepAliveConnections, enabledKeepAliveConnections } from './rpc-keepalive-connection.js';
|
|
5
|
+
export { RPCKeepAliveConnectionAdapter, RPCKeepAliveConnection, RPCKeepAliveConnectionData, rpcKeepAliveConnectionAdapters, keepAliveConnections, enabledKeepAliveConnections };
|
|
4
6
|
export { ReturnsBody } from './app.js';
|
|
5
7
|
export { Module, ModuleConfig };
|
|
6
8
|
export declare const modules: Modules;
|
|
@@ -10,11 +12,12 @@ export declare class Context extends app.Context {
|
|
|
10
12
|
ip: string;
|
|
11
13
|
caller: string;
|
|
12
14
|
callerId: string;
|
|
13
|
-
connection?: RPCKeepAliveConnection
|
|
15
|
+
connection?: RPCKeepAliveConnection<any>;
|
|
14
16
|
toJSON?(): {} & this;
|
|
15
17
|
}
|
|
16
18
|
export declare class Config {
|
|
17
19
|
[x: string]: any;
|
|
20
|
+
id: `${string}-${string}-${string}-${string}-${string}`;
|
|
18
21
|
name: string;
|
|
19
22
|
group: string;
|
|
20
23
|
ignore: string[];
|
|
@@ -24,8 +27,10 @@ export declare class Config {
|
|
|
24
27
|
};
|
|
25
28
|
host: string;
|
|
26
29
|
port: number;
|
|
27
|
-
origin: string;
|
|
30
|
+
origin: string | string[];
|
|
28
31
|
errorStack: boolean;
|
|
32
|
+
registry: string[];
|
|
33
|
+
registryAdapter: string;
|
|
29
34
|
}
|
|
30
35
|
export declare const config: Config;
|
|
31
36
|
export declare function setGenTraceIdFunction(fn: () => string): void;
|
|
@@ -40,39 +45,9 @@ export declare function genContext(context?: Context): Context;
|
|
|
40
45
|
export declare function getContext(): Context;
|
|
41
46
|
export declare function serve(): Promise<void>;
|
|
42
47
|
export declare function stop(): Promise<void>;
|
|
43
|
-
export
|
|
44
|
-
|
|
45
|
-
}
|
|
46
|
-
export interface RPCKeepAliveConnectionData {
|
|
47
|
-
/**
|
|
48
|
-
* 是否连接成功
|
|
49
|
-
*/
|
|
50
|
-
connected: boolean;
|
|
51
|
-
/**
|
|
52
|
-
* 连接主机地址
|
|
53
|
-
*/
|
|
54
|
-
host: string;
|
|
55
|
-
/**
|
|
56
|
-
* 连接服务名称
|
|
57
|
-
*/
|
|
58
|
-
name: string;
|
|
59
|
-
/**
|
|
60
|
-
* 目标服务网络唯一ID
|
|
61
|
-
*/
|
|
62
|
-
id: string;
|
|
63
|
-
}
|
|
64
|
-
export declare class RPCKeepAliveConnection {
|
|
65
|
-
data: RPCKeepAliveConnectionData;
|
|
66
|
-
nativeConnection: any;
|
|
67
|
-
adapter: RPCConnectionAdapter;
|
|
68
|
-
constructor(adapter: RPCConnectionAdapter, nativeConnection: any, data?: RPCKeepAliveConnectionData);
|
|
69
|
-
}
|
|
70
|
-
export declare const keepAliveConnections: Map<string, Map<string, RPCKeepAliveConnection>>;
|
|
71
|
-
export declare function getKeepAliveConnections(name: string): Map<string, RPCKeepAliveConnection>;
|
|
72
|
-
export declare function getKeepAliveConnection(name: string, id: string): RPCKeepAliveConnection | null;
|
|
73
|
-
export declare function addKeepAliveConnection(connection: RPCKeepAliveConnection): void;
|
|
74
|
-
export declare function removeKeepAliveConnection(connection: RPCKeepAliveConnection): void;
|
|
48
|
+
export declare function addKeepAliveConnection(connection: RPCKeepAliveConnection<any>): void;
|
|
49
|
+
export declare function removeKeepAliveConnection(connection: RPCKeepAliveConnection<any>): void;
|
|
75
50
|
export declare function removeKeepAliveConnection(name: string, id: string): void;
|
|
76
|
-
export declare function setLoadBalancePolicy(policy: (name: string) => RPCKeepAliveConnection): void;
|
|
51
|
+
export declare function setLoadBalancePolicy(policy: (name: string) => RPCKeepAliveConnection<any>): void;
|
|
77
52
|
export declare function rpc(appName: string, action: string, params: any[], context?: Context): Promise<any>;
|
|
78
|
-
export declare function rpc(connection: RPCKeepAliveConnection
|
|
53
|
+
export declare function rpc(connection: RPCKeepAliveConnection<any>, action: string, params: any[], context?: Context): Promise<any>;
|
|
@@ -5,7 +5,7 @@ import Module, { ModuleConfig } from '../module.js';
|
|
|
5
5
|
export declare class HTTPConfig extends ModuleConfig {
|
|
6
6
|
port: number;
|
|
7
7
|
path: string;
|
|
8
|
-
origin: string;
|
|
8
|
+
origin: string | string[];
|
|
9
9
|
ssl: {
|
|
10
10
|
enabled: boolean;
|
|
11
11
|
cert: string;
|
|
@@ -18,7 +18,7 @@ export default class HTTPModule extends Module {
|
|
|
18
18
|
config: HTTPConfig;
|
|
19
19
|
server: http.Server;
|
|
20
20
|
router: Router;
|
|
21
|
-
|
|
21
|
+
getURL(): URL;
|
|
22
22
|
get(path: string, ...args: any[]): this;
|
|
23
23
|
post(path: string, ...args: any[]): this;
|
|
24
24
|
put(path: string, ...args: any[]): this;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import * as oox from '../../index.js';
|
|
2
|
+
import { Socket } from './socket.js';
|
|
3
|
+
import { OOXEvent } from './utils.js';
|
|
4
|
+
export default class SocketIOAdapter implements oox.RPCKeepAliveConnectionAdapter<Socket> {
|
|
5
|
+
/**
|
|
6
|
+
* 客户端发送连接列表
|
|
7
|
+
* @param datas
|
|
8
|
+
*/
|
|
9
|
+
[OOXEvent.SYNC_CONNECTIONS](datas: oox.RPCKeepAliveConnectionData[]): void;
|
|
10
|
+
bindClientConnectionEvents(connection: oox.RPCKeepAliveConnection<Socket<'client'>>): void;
|
|
11
|
+
newConnection(url: string | URL): oox.RPCKeepAliveConnection<Socket>;
|
|
12
|
+
open(url: string | URL): Promise<oox.RPCKeepAliveConnection<Socket>>;
|
|
13
|
+
close(connection: oox.RPCKeepAliveConnection<Socket>): Promise<void>;
|
|
14
|
+
/**
|
|
15
|
+
* socketio emit
|
|
16
|
+
*/
|
|
17
|
+
emit(socket: Socket, event: string, params: any[]): Promise<unknown>;
|
|
18
|
+
/**
|
|
19
|
+
* RPC
|
|
20
|
+
*/
|
|
21
|
+
rpc(connection: oox.RPCKeepAliveConnection<Socket>, action: string, params: [], context?: oox.Context): Promise<any>;
|
|
22
|
+
/**
|
|
23
|
+
* 绑定 call 事件
|
|
24
|
+
* @param connection
|
|
25
|
+
*/
|
|
26
|
+
bindCall(connection: oox.RPCKeepAliveConnection<Socket>): void;
|
|
27
|
+
call(action: string, params: any[], context: oox.Context, callback?: (returns: any) => void): Promise<oox.ReturnsBody>;
|
|
28
|
+
}
|
|
@@ -1,37 +1,4 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
import { RPCKeepAliveConnectionData, RPCConnectionAdapter } from '../../index.js';
|
|
4
|
-
import { Socket, sockets, ServerSocket, ClientSocket } from './socket.js';
|
|
5
|
-
export { Socket, sockets };
|
|
6
|
-
export default class SocketIOModule extends SocketIOClient implements RPCConnectionAdapter {
|
|
7
|
-
sockets: Map<string, Socket>;
|
|
1
|
+
import SocketINServer from './server.js';
|
|
2
|
+
export default class SocketIOModule extends SocketINServer {
|
|
8
3
|
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, event: string, params: any[]): Promise<unknown>;
|
|
33
|
-
/**
|
|
34
|
-
* RPC
|
|
35
|
-
*/
|
|
36
|
-
rpc(url: string, action: string, params: [], context?: oox.Context): Promise<any>;
|
|
37
4
|
}
|
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import * as http from 'node:http';
|
|
2
2
|
import * as https from 'node:https';
|
|
3
3
|
import { Server, ServerOptions } from 'socket.io';
|
|
4
|
+
import * as oox from '../../index.js';
|
|
4
5
|
import { Module, ModuleConfig } from '../../index.js';
|
|
5
|
-
import {
|
|
6
|
+
import { Socket } from './socket.js';
|
|
7
|
+
import SocketIOAdapter from './adapter.js';
|
|
8
|
+
import { OOXEvent } from './utils.js';
|
|
6
9
|
export declare class SocketIOConfig extends ModuleConfig {
|
|
7
10
|
port: number;
|
|
8
11
|
path: string;
|
|
9
|
-
origin: string;
|
|
12
|
+
origin: string | string[];
|
|
10
13
|
ssl: {
|
|
11
14
|
enabled: boolean;
|
|
12
15
|
cert: string;
|
|
@@ -20,9 +23,8 @@ export default class SocketIOServer extends Module {
|
|
|
20
23
|
config: SocketIOConfig;
|
|
21
24
|
server: http.Server | https.Server;
|
|
22
25
|
socketServer: Server;
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
getUrl(): string;
|
|
26
|
+
adapter: SocketIOAdapter;
|
|
27
|
+
getURL(): URL;
|
|
26
28
|
setConfig(config: SocketIOConfig): void;
|
|
27
29
|
getConfig(): SocketIOConfig;
|
|
28
30
|
serve(): Promise<void>;
|
|
@@ -32,13 +34,15 @@ export default class SocketIOServer extends Module {
|
|
|
32
34
|
/**
|
|
33
35
|
* 服务端Socket连接事件
|
|
34
36
|
*/
|
|
35
|
-
serverOnSocketConnection(socket: Socket): void;
|
|
36
|
-
serverOnConnection(socket: Socket): void;
|
|
37
|
+
serverOnSocketConnection(socket: Socket<'server'>): void;
|
|
37
38
|
/**
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
* 服务器发送连接列表
|
|
40
|
+
* @param connection
|
|
41
|
+
*/
|
|
42
|
+
[OOXEvent.SYNC_CONNECTIONS](connection: oox.RPCKeepAliveConnection<Socket<'server'>>): oox.RPCKeepAliveConnectionData[];
|
|
43
|
+
/**
|
|
44
|
+
* 绑定服务器连接事件
|
|
45
|
+
* @param connection
|
|
41
46
|
*/
|
|
42
|
-
|
|
43
|
-
serverOnDisconnect(socket: Socket, reason: string): void;
|
|
47
|
+
bindServerConnectionEvents(connection: oox.RPCKeepAliveConnection<Socket<'server'>>): void;
|
|
44
48
|
}
|
|
@@ -1,11 +1,8 @@
|
|
|
1
|
-
import { Socket as
|
|
2
|
-
import { Socket as
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
}
|
|
10
|
-
export type Socket = ServerSocket | ClientSocket;
|
|
11
|
-
export declare const sockets: Map<string, Socket>;
|
|
1
|
+
import { Socket as ServerSocket } from 'socket.io';
|
|
2
|
+
import { Socket as ClientSocket } from 'socket.io-client';
|
|
3
|
+
export type SocketMap = {
|
|
4
|
+
[key: string]: ServerSocket | ClientSocket;
|
|
5
|
+
server: ServerSocket;
|
|
6
|
+
client: ClientSocket;
|
|
7
|
+
};
|
|
8
|
+
export type Socket<T extends keyof SocketMap = keyof SocketMap> = SocketMap[T];
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare enum OOXEvent {
|
|
2
|
+
CONNECTED = "oox:connected",
|
|
3
|
+
DISABLED = "oox:disabled",
|
|
4
|
+
SYNC_CONNECTIONS = "oox:sync_connections"
|
|
5
|
+
}
|
|
6
|
+
export declare function isWebSocketURL(url: string | URL): boolean;
|
|
7
|
+
export declare function genWebSocketURL(url: string): URL;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import EventEmitter from 'node:events';
|
|
2
|
+
import { Context } from './index.js';
|
|
3
|
+
export interface RPCKeepAliveConnectionAdapter<T> {
|
|
4
|
+
open(url: string | URL): Promise<RPCKeepAliveConnection<T>>;
|
|
5
|
+
close(connection: RPCKeepAliveConnection<T>): Promise<void>;
|
|
6
|
+
rpc(connection: RPCKeepAliveConnection<T>, action: string, params: any[], context: Context): Promise<any>;
|
|
7
|
+
}
|
|
8
|
+
export interface RPCKeepAliveConnectionData {
|
|
9
|
+
/**
|
|
10
|
+
* 连接主机地址
|
|
11
|
+
*/
|
|
12
|
+
host: string;
|
|
13
|
+
/**
|
|
14
|
+
* 连接服务名称
|
|
15
|
+
*/
|
|
16
|
+
name: string;
|
|
17
|
+
/**
|
|
18
|
+
* 连接URL
|
|
19
|
+
*/
|
|
20
|
+
url?: string | URL;
|
|
21
|
+
/**
|
|
22
|
+
* 目标服务网络唯一ID
|
|
23
|
+
*/
|
|
24
|
+
id: string;
|
|
25
|
+
}
|
|
26
|
+
export type RPCKeepAliveConnectionEventMap = Record<keyof {
|
|
27
|
+
"enabled": any;
|
|
28
|
+
"disabled": any;
|
|
29
|
+
"connect": any;
|
|
30
|
+
"disconnect": any;
|
|
31
|
+
'error': any;
|
|
32
|
+
}, any[]>;
|
|
33
|
+
export declare class RPCKeepAliveConnection<T> extends EventEmitter<RPCKeepAliveConnectionEventMap> {
|
|
34
|
+
#private;
|
|
35
|
+
data: RPCKeepAliveConnectionData;
|
|
36
|
+
nativeConnection: T;
|
|
37
|
+
adapter: RPCKeepAliveConnectionAdapter<T>;
|
|
38
|
+
constructor(adapter: RPCKeepAliveConnectionAdapter<T>, nativeConnection: T, data: RPCKeepAliveConnectionData);
|
|
39
|
+
set enabled(enabled: boolean);
|
|
40
|
+
get enabled(): boolean;
|
|
41
|
+
updateId(newId: string): void;
|
|
42
|
+
updateName(newName: string): void;
|
|
43
|
+
updateIdAndName(newId: string, newName: string): void;
|
|
44
|
+
}
|
|
45
|
+
export declare class KeepAliveConnectionStore<T> {
|
|
46
|
+
#private;
|
|
47
|
+
entries(): MapIterator<[string, Map<string, RPCKeepAliveConnection<T>>]>;
|
|
48
|
+
getConnectionsOfService(name: string): Map<string, RPCKeepAliveConnection<T>>;
|
|
49
|
+
has(name: string, id: string): boolean;
|
|
50
|
+
get(name: string, id: string): RPCKeepAliveConnection<T> | null;
|
|
51
|
+
add(connection: RPCKeepAliveConnection<T>): void;
|
|
52
|
+
remove(connection: RPCKeepAliveConnection<T>): void;
|
|
53
|
+
remove(name: string, id: string): void;
|
|
54
|
+
}
|
|
55
|
+
export declare const rpcKeepAliveConnectionAdapters: Map<string, RPCKeepAliveConnectionAdapter<any>>;
|
|
56
|
+
export declare const keepAliveConnections: KeepAliveConnectionStore<any>;
|
|
57
|
+
export declare const enabledKeepAliveConnections: KeepAliveConnectionStore<any>;
|
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
import * as SocketIOClient from 'socket.io-client';
|
|
2
|
-
import { sockets } from './socket.js';
|
|
3
|
-
import SocketIOServer from './server.js';
|
|
4
|
-
import * as oox from '../../index.js';
|
|
5
|
-
export default class SocketIOCore extends SocketIOServer {
|
|
6
|
-
/**
|
|
7
|
-
* connect to <SocketIO RPC> service
|
|
8
|
-
*/
|
|
9
|
-
async connect(url) {
|
|
10
|
-
let socket = sockets.get(url);
|
|
11
|
-
// 已经连接的直接返回
|
|
12
|
-
if (socket) {
|
|
13
|
-
try {
|
|
14
|
-
await this.clientWaitConnection(socket);
|
|
15
|
-
}
|
|
16
|
-
catch (error) {
|
|
17
|
-
this.clientOnSocketDisconnect(socket, error.message);
|
|
18
|
-
throw error;
|
|
19
|
-
}
|
|
20
|
-
return socket;
|
|
21
|
-
}
|
|
22
|
-
const headers = {
|
|
23
|
-
'x-caller': oox.config.name
|
|
24
|
-
};
|
|
25
|
-
const { host } = oox.config;
|
|
26
|
-
headers['x-ip'] = host;
|
|
27
|
-
headers['x-caller-id'] = this.getUrl();
|
|
28
|
-
// create socket handler
|
|
29
|
-
const mURL = new URL(url);
|
|
30
|
-
socket = SocketIOClient.io(mURL.origin, {
|
|
31
|
-
extraHeaders: headers,
|
|
32
|
-
path: mURL.pathname
|
|
33
|
-
});
|
|
34
|
-
socket.data = { name: 'anonymous', connected: false, id: url, host: mURL.host };
|
|
35
|
-
sockets.set(url, socket);
|
|
36
|
-
try {
|
|
37
|
-
await this.clientWaitConnection(socket);
|
|
38
|
-
}
|
|
39
|
-
catch (error) {
|
|
40
|
-
this.clientOnSocketDisconnect(socket, error);
|
|
41
|
-
throw error;
|
|
42
|
-
}
|
|
43
|
-
return socket;
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* 客户端Socket连接事件
|
|
47
|
-
*/
|
|
48
|
-
clientOnSocketConnection(socket) {
|
|
49
|
-
socket.data.connected = true;
|
|
50
|
-
socket.once('disconnect', reason => this.clientOnSocketDisconnect(socket, reason));
|
|
51
|
-
this.clientOnConnection(socket);
|
|
52
|
-
}
|
|
53
|
-
clientOnDisconnect(socket, reason) { }
|
|
54
|
-
clientOnConnection(socket) { }
|
|
55
|
-
/**
|
|
56
|
-
* 客户端Socket断开事件
|
|
57
|
-
* @param {Socket} socket
|
|
58
|
-
*/
|
|
59
|
-
clientOnSocketDisconnect(socket, reason) {
|
|
60
|
-
socket.data.connected = false;
|
|
61
|
-
socket.disconnect();
|
|
62
|
-
sockets.delete(socket.data.id);
|
|
63
|
-
this.clientOnDisconnect(socket, reason);
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* 等待socket连接
|
|
67
|
-
*/
|
|
68
|
-
async clientWaitConnection(socket) {
|
|
69
|
-
if (socket.data.connected)
|
|
70
|
-
return;
|
|
71
|
-
if (socket.connect)
|
|
72
|
-
socket.connect();
|
|
73
|
-
try {
|
|
74
|
-
await new Promise((resolve, reject) => {
|
|
75
|
-
const onError = (reason) => {
|
|
76
|
-
socket.offAny(onError);
|
|
77
|
-
const message = 'string' === typeof reason ? reason : reason instanceof Error ? reason.message : 'connect error';
|
|
78
|
-
reject(new Error(message));
|
|
79
|
-
};
|
|
80
|
-
socket.once('disconnect', onError);
|
|
81
|
-
socket.once('connect_error', onError);
|
|
82
|
-
socket.once('connect_timeout', onError);
|
|
83
|
-
socket.once('reconnect_error', onError);
|
|
84
|
-
socket.once('reconnect_failed', onError);
|
|
85
|
-
socket.once('oox_connected', ({ name }) => {
|
|
86
|
-
socket.offAny(onError);
|
|
87
|
-
socket.data.name = name;
|
|
88
|
-
resolve();
|
|
89
|
-
});
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
catch (error) {
|
|
93
|
-
throw new Error(error.message);
|
|
94
|
-
}
|
|
95
|
-
this.clientOnSocketConnection(socket);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { ClientSocket as Socket } from './socket.js';
|
|
2
|
-
import SocketIOServer from './server.js';
|
|
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
|
-
}
|