oox 0.2.0 → 0.3.0-beta10
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/LICENSE +21 -21
- package/README.md +32 -29
- package/app.js +143 -0
- package/bin/argv.js +70 -95
- package/bin/cli.js +49 -58
- package/bin/configurer.js +64 -78
- package/bin/loader.mjs +449 -0
- package/bin/proxyer.js +66 -95
- package/bin/register.js +55 -105
- package/bin/starter.js +71 -144
- package/index.js +168 -6
- package/index.mjs +5 -0
- package/logger.js +40 -0
- package/modules/http/index.js +192 -0
- package/modules/http/utils.js +73 -0
- package/modules/index.js +88 -0
- package/modules/module.js +16 -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 +39 -16
- package/types/app.d.ts +51 -0
- package/types/bin/argv.d.ts +8 -0
- package/types/bin/cli.d.ts +4 -0
- package/types/bin/configurer.d.ts +3 -0
- package/types/bin/proxyer.d.ts +1 -0
- package/types/bin/register.d.ts +1 -0
- package/types/bin/starter.d.ts +3 -0
- package/types/index.d.ts +76 -0
- package/types/logger.d.ts +4 -0
- package/types/modules/http/index.d.ts +47 -0
- package/types/modules/http/utils.d.ts +17 -0
- package/types/modules/index.d.ts +24 -0
- package/types/modules/module.d.ts +13 -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/types/utils.d.ts +6 -0
- package/utils.js +63 -0
- package/.gitattributes +0 -2
- package/global.js +0 -118
- package/middleware.js +0 -167
- package/rpc/config.class.js +0 -48
- package/rpc/context.class.js +0 -15
- package/rpc/http.class.js +0 -312
- package/rpc/rpc.class.js +0 -231
- package/rpc/rpc.interface.class.js +0 -119
- package/rpc/socketio.class.js +0 -223
- package/service/service.class.js +0 -74
- package/service/socketio.class.js +0 -145
- package/setMap.class.js +0 -67
- package/socketio/client.class.js +0 -190
- package/socketio/server.class.js +0 -222
- package/socketio/socket.class.js +0 -23
- package/util.js +0 -224
package/index.js
CHANGED
|
@@ -1,6 +1,168 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
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
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const app = require("./app");
|
|
6
|
+
const utils_1 = require("./utils");
|
|
7
|
+
const module_1 = require("./modules/module");
|
|
8
|
+
exports.Module = module_1.default;
|
|
9
|
+
Object.defineProperty(exports, "ModuleConfig", { enumerable: true, get: function () { return module_1.ModuleConfig; } });
|
|
10
|
+
const modules_1 = require("./modules");
|
|
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.logger = app.logger, exports.on = app.on, exports.once = app.once, exports.off = app.off, exports.emit = app.emit;
|
|
13
|
+
class Context extends app.Context {
|
|
14
|
+
// 请求溯源IP
|
|
15
|
+
sourceIP = '';
|
|
16
|
+
// 请求者IP
|
|
17
|
+
ip = '';
|
|
18
|
+
// 请求者名称
|
|
19
|
+
caller = 'anonymous';
|
|
20
|
+
// 请求者ID (长连接专用)
|
|
21
|
+
callerId = '';
|
|
22
|
+
// 请求者连接把柄
|
|
23
|
+
connection;
|
|
24
|
+
toJSON() {
|
|
25
|
+
const context = Object.assign({}, this);
|
|
26
|
+
delete context.connection;
|
|
27
|
+
return context;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
exports.Context = Context;
|
|
31
|
+
class Config {
|
|
32
|
+
// 服务名称
|
|
33
|
+
name = 'local';
|
|
34
|
+
// 启动文件
|
|
35
|
+
entryFile = {
|
|
36
|
+
// 启动文件路径
|
|
37
|
+
path: '',
|
|
38
|
+
// 服务列表路径
|
|
39
|
+
group: '',
|
|
40
|
+
};
|
|
41
|
+
// 主机地址
|
|
42
|
+
host = (0, utils_1.getIPAddress)(4)[0];
|
|
43
|
+
// 默认监听端口
|
|
44
|
+
port = 0;
|
|
45
|
+
// 默认跨域设置
|
|
46
|
+
origin = '';
|
|
47
|
+
}
|
|
48
|
+
exports.Config = Config;
|
|
49
|
+
exports.config = new Config();
|
|
50
|
+
let genTraceIdFunction = () => (0, node_crypto_1.randomUUID)();
|
|
51
|
+
function setGenTraceIdFunction(fn) {
|
|
52
|
+
genTraceIdFunction = fn;
|
|
53
|
+
}
|
|
54
|
+
exports.setGenTraceIdFunction = setGenTraceIdFunction;
|
|
55
|
+
/**
|
|
56
|
+
* 生成随机不重复id
|
|
57
|
+
*/
|
|
58
|
+
function genTraceId() {
|
|
59
|
+
return genTraceIdFunction();
|
|
60
|
+
}
|
|
61
|
+
exports.genTraceId = genTraceId;
|
|
62
|
+
/**
|
|
63
|
+
* 获取链路跟踪上下文
|
|
64
|
+
*/
|
|
65
|
+
function genContext(context) {
|
|
66
|
+
const newContext = Object.assign(new Context(), context);
|
|
67
|
+
if (!newContext.traceId)
|
|
68
|
+
newContext.traceId = genTraceId();
|
|
69
|
+
if (!newContext.sourceIP)
|
|
70
|
+
newContext.sourceIP = newContext.ip;
|
|
71
|
+
return newContext;
|
|
72
|
+
}
|
|
73
|
+
exports.genContext = genContext;
|
|
74
|
+
function getContext() {
|
|
75
|
+
const context = exports.asyncStore.getStore();
|
|
76
|
+
return context || genContext();
|
|
77
|
+
}
|
|
78
|
+
exports.getContext = getContext;
|
|
79
|
+
async function serve() {
|
|
80
|
+
await exports.modules.serve();
|
|
81
|
+
}
|
|
82
|
+
exports.serve = serve;
|
|
83
|
+
async function stop() {
|
|
84
|
+
await exports.modules.stop();
|
|
85
|
+
}
|
|
86
|
+
exports.stop = stop;
|
|
87
|
+
class RPCKeepAliveConnection {
|
|
88
|
+
data;
|
|
89
|
+
nativeConnection = null;
|
|
90
|
+
adapter = null;
|
|
91
|
+
constructor(adapter, nativeConnection, data) {
|
|
92
|
+
this.adapter = adapter;
|
|
93
|
+
this.nativeConnection = nativeConnection;
|
|
94
|
+
if (data)
|
|
95
|
+
this.data = data;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
exports.RPCKeepAliveConnection = RPCKeepAliveConnection;
|
|
99
|
+
exports.keepAliveConnections = new Map();
|
|
100
|
+
function getKeepAliveConnections(name) {
|
|
101
|
+
return exports.keepAliveConnections.get(name) || new Map();
|
|
102
|
+
}
|
|
103
|
+
exports.getKeepAliveConnections = getKeepAliveConnections;
|
|
104
|
+
function getKeepAliveConnection(name, id) {
|
|
105
|
+
const connections = exports.keepAliveConnections.get(name);
|
|
106
|
+
if (!connections)
|
|
107
|
+
return null;
|
|
108
|
+
return connections.get(id);
|
|
109
|
+
}
|
|
110
|
+
exports.getKeepAliveConnection = getKeepAliveConnection;
|
|
111
|
+
function addKeepAliveConnection(connection) {
|
|
112
|
+
const { name, id } = connection.data;
|
|
113
|
+
if (exports.keepAliveConnections.has(name)) {
|
|
114
|
+
exports.keepAliveConnections.get(name).set(id, connection);
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
exports.keepAliveConnections.set(name, new Map([[id, connection]]));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
exports.addKeepAliveConnection = addKeepAliveConnection;
|
|
121
|
+
function removeKeepAliveConnection(name, id) {
|
|
122
|
+
if (name instanceof RPCKeepAliveConnection) {
|
|
123
|
+
id = name.data.id;
|
|
124
|
+
name = name.data.name;
|
|
125
|
+
}
|
|
126
|
+
if (exports.keepAliveConnections.has(name)) {
|
|
127
|
+
const group = exports.keepAliveConnections.get(name);
|
|
128
|
+
group.delete(id);
|
|
129
|
+
if (!group.size)
|
|
130
|
+
exports.keepAliveConnections.delete(name);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
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;
|
|
151
|
+
async function rpc(arg1, action, params, context) {
|
|
152
|
+
if (!context || !context.traceId) {
|
|
153
|
+
context = getContext();
|
|
154
|
+
}
|
|
155
|
+
let connection;
|
|
156
|
+
if (arg1 instanceof RPCKeepAliveConnection) {
|
|
157
|
+
connection = arg1;
|
|
158
|
+
}
|
|
159
|
+
else if ('string' === typeof arg1) {
|
|
160
|
+
connection = loadBalancePolicy(arg1);
|
|
161
|
+
if (!connection)
|
|
162
|
+
throw new Error(`Connection<${arg1}> not found`);
|
|
163
|
+
}
|
|
164
|
+
else
|
|
165
|
+
throw new Error(`Unknown rpc arg1<${arg1}>`);
|
|
166
|
+
return connection.adapter.rpc(connection.nativeConnection, action, params, context);
|
|
167
|
+
}
|
|
168
|
+
exports.rpc = rpc;
|
package/index.mjs
ADDED
package/logger.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.trace = exports.error = exports.warn = exports.info = void 0;
|
|
4
|
+
const app_1 = require("./app");
|
|
5
|
+
function info(...msgs) {
|
|
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
|
+
}
|
|
12
|
+
exports.info = info;
|
|
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);
|
|
19
|
+
}
|
|
20
|
+
exports.warn = warn;
|
|
21
|
+
function error(...msgs) {
|
|
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);
|
|
27
|
+
}
|
|
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;
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.HTTPConfig = void 0;
|
|
4
|
+
const http = require("node:http");
|
|
5
|
+
const node_querystring_1 = require("node:querystring");
|
|
6
|
+
const utils_1 = require("./utils");
|
|
7
|
+
const oox = require("../../index");
|
|
8
|
+
const module_1 = require("../module");
|
|
9
|
+
class HTTPConfig extends module_1.ModuleConfig {
|
|
10
|
+
// listen port
|
|
11
|
+
port = 0;
|
|
12
|
+
// service path
|
|
13
|
+
path = '/';
|
|
14
|
+
// browser cross origin
|
|
15
|
+
origin = '';
|
|
16
|
+
}
|
|
17
|
+
exports.HTTPConfig = HTTPConfig;
|
|
18
|
+
class HTTPModule extends module_1.default {
|
|
19
|
+
name = 'http';
|
|
20
|
+
config = new HTTPConfig;
|
|
21
|
+
server = null;
|
|
22
|
+
setConfig(config) {
|
|
23
|
+
Object.assign(this.config, config);
|
|
24
|
+
if (!config.hasOwnProperty('port')) {
|
|
25
|
+
this.config.port = oox.config.port;
|
|
26
|
+
}
|
|
27
|
+
if (!config.hasOwnProperty('origin')) {
|
|
28
|
+
this.config.origin = oox.config.origin;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
getConfig() {
|
|
32
|
+
return this.config;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* start http service
|
|
36
|
+
*/
|
|
37
|
+
async serve() {
|
|
38
|
+
await this.stop();
|
|
39
|
+
const { port } = this.config;
|
|
40
|
+
this.server = http.createServer(this.call.bind(this));
|
|
41
|
+
this.server.listen(port);
|
|
42
|
+
const address = this.server.address();
|
|
43
|
+
if (!address || 'object' !== typeof address)
|
|
44
|
+
throw new Error('Cannot read http server port');
|
|
45
|
+
this.config.port = address.port;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* stop http service
|
|
49
|
+
*/
|
|
50
|
+
stop() {
|
|
51
|
+
if (this.server && this.server.listening)
|
|
52
|
+
return new Promise((resolve, reject) => {
|
|
53
|
+
this.server.close(function (error) {
|
|
54
|
+
if (error)
|
|
55
|
+
reject(error);
|
|
56
|
+
else
|
|
57
|
+
resolve();
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* browser cross origin
|
|
63
|
+
*/
|
|
64
|
+
cors(request, response) {
|
|
65
|
+
// origin checking
|
|
66
|
+
const origin = this.config.origin;
|
|
67
|
+
const requestOrigin = request.headers.origin;
|
|
68
|
+
if (origin && requestOrigin) {
|
|
69
|
+
if (origin === '*' || origin === requestOrigin || Array.isArray(origin) && origin.includes(requestOrigin)) {
|
|
70
|
+
response.setHeader('Access-Control-Allow-Origin', requestOrigin);
|
|
71
|
+
response.setHeader('Vary', 'Origin');
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
response.statusCode = 403;
|
|
75
|
+
response.end();
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
response.setHeader('Access-Control-Max-Age', 3600);
|
|
79
|
+
response.setHeader('Access-Control-Allow-Headers', 'x-caller,content-type');
|
|
80
|
+
response.setHeader('Access-Control-Allow-Methods', '*');
|
|
81
|
+
}
|
|
82
|
+
if (request.method === 'OPTIONS') {
|
|
83
|
+
response.statusCode = 204;
|
|
84
|
+
response.end();
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* HTTP-RPC服务器请求监听方法
|
|
91
|
+
*/
|
|
92
|
+
async call(request, response) {
|
|
93
|
+
if (request.url !== this.config.path) {
|
|
94
|
+
const error = {
|
|
95
|
+
message: 'Invalid URL',
|
|
96
|
+
stack: ''
|
|
97
|
+
};
|
|
98
|
+
Error.captureStackTrace(error);
|
|
99
|
+
return this.respond(request, response, {
|
|
100
|
+
success: false,
|
|
101
|
+
error
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
if (!this.cors(request, response))
|
|
105
|
+
return;
|
|
106
|
+
let body = Object.create(null);
|
|
107
|
+
try {
|
|
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
|
+
}
|
|
114
|
+
if (!body || 'object' !== typeof body)
|
|
115
|
+
throw new Error('Content Invalid');
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
return this.respond(request, response, {
|
|
119
|
+
success: false,
|
|
120
|
+
error: {
|
|
121
|
+
message: error.message,
|
|
122
|
+
stack: error.stack
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
// global unique id
|
|
127
|
+
const traceId = String(request.headers['x-trace-id'] || '');
|
|
128
|
+
// service name, required
|
|
129
|
+
const caller = String(request.headers['x-caller'] || 'anonymous');
|
|
130
|
+
// client ip or caller service ip
|
|
131
|
+
const ip = String(request.headers['x-ip'] || request.socket.remoteAddress || '');
|
|
132
|
+
// startup client ip
|
|
133
|
+
const sourceIP = String(request.headers['x-real-ip'] || '');
|
|
134
|
+
const { action = 'index', params = [] } = body;
|
|
135
|
+
const context = oox.genContext({ traceId, caller, sourceIP, ip, callerId: '' });
|
|
136
|
+
const format = await oox.call(action, params, context);
|
|
137
|
+
this.respond(request, response, format);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* HTTP Response Catch
|
|
141
|
+
*/
|
|
142
|
+
respond(request, response, format) {
|
|
143
|
+
let formatString = '';
|
|
144
|
+
try {
|
|
145
|
+
formatString = JSON.stringify(format);
|
|
146
|
+
}
|
|
147
|
+
catch ({ message, stack }) {
|
|
148
|
+
delete format.body;
|
|
149
|
+
format.success = false;
|
|
150
|
+
format.error = {
|
|
151
|
+
message,
|
|
152
|
+
stack
|
|
153
|
+
};
|
|
154
|
+
formatString = JSON.stringify(format);
|
|
155
|
+
}
|
|
156
|
+
response.setHeader('Content-Type', 'application/json');
|
|
157
|
+
response.setHeader('Content-Length', Buffer.byteLength(formatString));
|
|
158
|
+
response.end(formatString);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* HTTP RPC
|
|
162
|
+
*/
|
|
163
|
+
async rpc(url, action, params, context) {
|
|
164
|
+
if (!context || !context.traceId) {
|
|
165
|
+
context = oox.getContext();
|
|
166
|
+
}
|
|
167
|
+
const { traceId, caller, sourceIP } = context;
|
|
168
|
+
const headers = {
|
|
169
|
+
'Content-Type': 'application/json',
|
|
170
|
+
'x-trace-id': String(traceId),
|
|
171
|
+
};
|
|
172
|
+
if (caller)
|
|
173
|
+
headers['x-caller'] = String(caller);
|
|
174
|
+
if (sourceIP)
|
|
175
|
+
headers['x-real-ip'] = sourceIP;
|
|
176
|
+
// headers [ 'x-ip' ] = getIPAddress ( 4 ) [ 0 ]
|
|
177
|
+
const format = await (0, utils_1.httpRequest)(url, {
|
|
178
|
+
headers
|
|
179
|
+
}, JSON.stringify({ action, params }));
|
|
180
|
+
if ('string' === typeof format)
|
|
181
|
+
throw new Error(format);
|
|
182
|
+
const { error, body } = format;
|
|
183
|
+
if (error) {
|
|
184
|
+
const asyncError = new Error(error.message);
|
|
185
|
+
throw asyncError;
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
return body;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
exports.default = HTTPModule;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.httpRequest = exports.parseHTTPBody = exports.stream2buffer = void 0;
|
|
4
|
+
const http = require("node:http");
|
|
5
|
+
/**
|
|
6
|
+
* Stream => Buffer
|
|
7
|
+
*/
|
|
8
|
+
function stream2buffer(stream, totalLength = 0) {
|
|
9
|
+
return new Promise(function (resolve, reject) {
|
|
10
|
+
let buffers = [];
|
|
11
|
+
stream.on('error', reject);
|
|
12
|
+
if (totalLength) {
|
|
13
|
+
stream.on('data', function (data) { buffers.push(data); });
|
|
14
|
+
}
|
|
15
|
+
else {
|
|
16
|
+
stream.on('data', function (data) {
|
|
17
|
+
buffers.push(data);
|
|
18
|
+
totalLength += data.length;
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
stream.on('end', function () { resolve(Buffer.concat(buffers, totalLength)); });
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
exports.stream2buffer = stream2buffer;
|
|
25
|
+
/**
|
|
26
|
+
* Request => JSONObject
|
|
27
|
+
*/
|
|
28
|
+
async function parseHTTPBody(request) {
|
|
29
|
+
if (request.method === 'GET')
|
|
30
|
+
return null;
|
|
31
|
+
let contentType = request.headers['content-type'];
|
|
32
|
+
// application/json; charset=utf-8
|
|
33
|
+
if (contentType)
|
|
34
|
+
contentType = contentType.split(';')[0].trim();
|
|
35
|
+
const contentSize = request.headers['content-length'];
|
|
36
|
+
const buffer = await stream2buffer(request, +contentSize || 0);
|
|
37
|
+
if (contentSize && buffer.length !== +contentSize)
|
|
38
|
+
throw new Error('Content-Length Incorrect');
|
|
39
|
+
const bodyString = buffer.toString();
|
|
40
|
+
if ('application/json' === contentType) {
|
|
41
|
+
return JSON.parse(bodyString);
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
return bodyString;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
exports.parseHTTPBody = parseHTTPBody;
|
|
48
|
+
/**
|
|
49
|
+
* http request
|
|
50
|
+
*/
|
|
51
|
+
function httpRequest(url, options, body) {
|
|
52
|
+
return new Promise(function (resolve, reject) {
|
|
53
|
+
const request = http.request(url, options, async function (response) {
|
|
54
|
+
try {
|
|
55
|
+
const result = await parseHTTPBody(response);
|
|
56
|
+
resolve(result);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
const decoration = new Error(`${response.statusCode} - ${error.message}`);
|
|
60
|
+
reject(decoration);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
request.on('error', reject);
|
|
64
|
+
if (body) {
|
|
65
|
+
request.method = 'POST';
|
|
66
|
+
request.setHeader('Content-Type', 'application/json');
|
|
67
|
+
request.setHeader('Content-Length', Buffer.byteLength(body));
|
|
68
|
+
request.write(body);
|
|
69
|
+
}
|
|
70
|
+
request.end();
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
exports.httpRequest = httpRequest;
|
package/modules/index.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const module_1 = require("./module");
|
|
4
|
+
const http_1 = require("./http");
|
|
5
|
+
const socketio_1 = require("./socketio");
|
|
6
|
+
class Modules extends module_1.default {
|
|
7
|
+
/**
|
|
8
|
+
* the module unique name
|
|
9
|
+
*/
|
|
10
|
+
name = 'oox:modules';
|
|
11
|
+
/**
|
|
12
|
+
* FIFO queue for modules starting
|
|
13
|
+
*/
|
|
14
|
+
#queue = [];
|
|
15
|
+
/**
|
|
16
|
+
* all modules map
|
|
17
|
+
*/
|
|
18
|
+
#map = new Map();
|
|
19
|
+
/**
|
|
20
|
+
* all builtin modules
|
|
21
|
+
*/
|
|
22
|
+
builtins = {
|
|
23
|
+
http: new http_1.default,
|
|
24
|
+
socketio: new socketio_1.default,
|
|
25
|
+
};
|
|
26
|
+
constructor() {
|
|
27
|
+
super();
|
|
28
|
+
this.add(this.builtins.http);
|
|
29
|
+
this.add(this.builtins.socketio);
|
|
30
|
+
}
|
|
31
|
+
add(module) {
|
|
32
|
+
if (!module.name || 'string' !== typeof module.name)
|
|
33
|
+
throw new Error(`Module<${module.name}> has noname`);
|
|
34
|
+
if (this.#map.has(module.name))
|
|
35
|
+
throw new Error(`Module<${module.name}> has exists`);
|
|
36
|
+
this.#map.set(module.name, module);
|
|
37
|
+
this.#queue.push(module);
|
|
38
|
+
return this;
|
|
39
|
+
}
|
|
40
|
+
get(name) {
|
|
41
|
+
return this.#map.get(name);
|
|
42
|
+
}
|
|
43
|
+
async remove(name) {
|
|
44
|
+
const module = this.get(name);
|
|
45
|
+
if (!module)
|
|
46
|
+
return;
|
|
47
|
+
await module.stop();
|
|
48
|
+
const index = this.#queue.indexOf(module);
|
|
49
|
+
this.#queue.splice(index, 1);
|
|
50
|
+
this.#map.delete(name);
|
|
51
|
+
}
|
|
52
|
+
setConfig(config) {
|
|
53
|
+
for (const module of this.#queue) {
|
|
54
|
+
if (module.name in config) {
|
|
55
|
+
const moduleConfig = config[module.name];
|
|
56
|
+
if (moduleConfig) {
|
|
57
|
+
module.setConfig(moduleConfig);
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
module.setConfig({ disabled: true });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
module.setConfig({});
|
|
65
|
+
}
|
|
66
|
+
config[module.name] = module.getConfig();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async serve() {
|
|
70
|
+
try {
|
|
71
|
+
for (const module of this.#queue) {
|
|
72
|
+
if (!module.getConfig().disabled) {
|
|
73
|
+
await module.serve();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
await this.stop();
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async stop() {
|
|
83
|
+
for (const module of this.#queue) {
|
|
84
|
+
await module.stop();
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
exports.default = Modules;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ModuleConfig = void 0;
|
|
4
|
+
class ModuleConfig {
|
|
5
|
+
disabled = false;
|
|
6
|
+
}
|
|
7
|
+
exports.ModuleConfig = ModuleConfig;
|
|
8
|
+
class Module {
|
|
9
|
+
config;
|
|
10
|
+
name;
|
|
11
|
+
setConfig(config) { }
|
|
12
|
+
getConfig() { return this.config; }
|
|
13
|
+
async serve() { }
|
|
14
|
+
async stop() { }
|
|
15
|
+
}
|
|
16
|
+
exports.default = Module;
|
|
@@ -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;
|