oox 0.3.0-beta5 → 0.3.0-beta8
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 +2 -13
- package/bin/configurer.js +22 -9
- package/bin/loader.mjs +279 -0
- package/bin/starter.js +13 -30
- package/index.js +33 -9
- package/index.mjs +1 -0
- package/logger.js +40 -0
- package/modules/http/index.js +6 -0
- package/modules/index.js +7 -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 +10 -6
- package/types/app.d.ts +3 -0
- package/types/bin/configurer.d.ts +1 -1
- package/types/index.d.ts +9 -3
- package/types/logger.d.ts +4 -0
- 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,9 +1,10 @@
|
|
|
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 = void 0;
|
|
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;
|
|
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
|
+
exports.logger = require("./logger");
|
|
7
8
|
class Context {
|
|
8
9
|
// 请求溯源ID
|
|
9
10
|
traceId = '';
|
|
@@ -124,18 +125,6 @@ async function execute(action, params, context) {
|
|
|
124
125
|
// ============================= PROXY END =============================
|
|
125
126
|
// make sure target action execute after all proxies
|
|
126
127
|
if (target) {
|
|
127
|
-
/*
|
|
128
|
-
const sourceMethod = wrappedActions.get ( action )
|
|
129
|
-
|
|
130
|
-
const middlewareNames = actionMiddlewares.get ( sourceMethod )
|
|
131
|
-
|
|
132
|
-
if ( middlewareNames && middlewareNames.length ) for ( const name of middlewareNames ) {
|
|
133
|
-
|
|
134
|
-
const middleware = middlewares.get ( name )
|
|
135
|
-
|
|
136
|
-
await middleware ( action, params, context )
|
|
137
|
-
}
|
|
138
|
-
*/
|
|
139
128
|
return await target(...params);
|
|
140
129
|
}
|
|
141
130
|
}
|
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/loader.mjs
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
|
|
4
|
+
import os from 'node:os'
|
|
5
|
+
|
|
6
|
+
import fs from 'node:fs'
|
|
7
|
+
|
|
8
|
+
import { get as httpGet } from 'node:http'
|
|
9
|
+
|
|
10
|
+
import { get as httpsGet } from 'node:https'
|
|
11
|
+
|
|
12
|
+
import oox from '../index.mjs'
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
function generateRPCProxyScript ( name, attributes = [ ] ) {
|
|
17
|
+
|
|
18
|
+
let attrExports = ''
|
|
19
|
+
|
|
20
|
+
for ( const attr of attributes ) {
|
|
21
|
+
|
|
22
|
+
attrExports += `\nexport const ${attr} = proxyer.${attr}\n`
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const script = `
|
|
26
|
+
import oox from 'oox'
|
|
27
|
+
function RPC_${name} ( ) { }
|
|
28
|
+
function dotCall ( name, action ) {
|
|
29
|
+
|
|
30
|
+
return new Proxy ( RPC_${name}, {
|
|
31
|
+
|
|
32
|
+
get ( target, key ) {
|
|
33
|
+
|
|
34
|
+
return dotCall ( name, action ? action + '.' + key : key )
|
|
35
|
+
},
|
|
36
|
+
|
|
37
|
+
has ( target, key ) { return true },
|
|
38
|
+
|
|
39
|
+
apply ( target, thisArg, args ) {
|
|
40
|
+
|
|
41
|
+
return oox.rpc ( name, action, args )
|
|
42
|
+
}
|
|
43
|
+
} )
|
|
44
|
+
}
|
|
45
|
+
const proxyer = dotCall ( '${name}', '' )
|
|
46
|
+
export default proxyer
|
|
47
|
+
${attrExports}
|
|
48
|
+
`
|
|
49
|
+
|
|
50
|
+
return script
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
function generateRPCProxyURL ( name, attributes ) {
|
|
56
|
+
|
|
57
|
+
let searchText = ''
|
|
58
|
+
|
|
59
|
+
if ( attributes.length ) {
|
|
60
|
+
|
|
61
|
+
const search = new URLSearchParams ( )
|
|
62
|
+
|
|
63
|
+
for ( const attr of attributes ) {
|
|
64
|
+
|
|
65
|
+
search.append ( 'attr', attr )
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
searchText = '?' + search.toString ( )
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return `oox://rpc/${name}.mjs${searchText}`
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
function isWebURL ( url ) {
|
|
77
|
+
|
|
78
|
+
return url && ( url.startsWith ( 'https://' ) || url.startsWith ( 'http://' ) )
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
function isOOXURL ( url ) {
|
|
84
|
+
|
|
85
|
+
return url && url.startsWith ( 'oox://' )
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* make ESModule support dynamic <export *> attributes import
|
|
92
|
+
* @param {string} importerSpecifier the import url
|
|
93
|
+
* @param {string} specifier parentURL
|
|
94
|
+
* @returns {string[]}
|
|
95
|
+
*/
|
|
96
|
+
function getImportAttributes ( importerSpecifier, specifier ) {
|
|
97
|
+
|
|
98
|
+
const attributes = [ ]
|
|
99
|
+
|
|
100
|
+
const contents = fs.readFileSync ( importerSpecifier, 'utf-8' )
|
|
101
|
+
|
|
102
|
+
// import * as xxx from "xxx"
|
|
103
|
+
const mergeImport = contents.match ( new RegExp ( `import.+\\*\\s*as\\s+(\\w+)\\s+from\\s*["']${specifier}["']` ) )
|
|
104
|
+
|
|
105
|
+
if ( mergeImport ) {
|
|
106
|
+
|
|
107
|
+
const mergeName = mergeImport [ 1 ]
|
|
108
|
+
|
|
109
|
+
const attributesIterator = contents.matchAll ( new RegExp ( `${mergeName}\\s*\\.\\s*(\\w+)`, 'g' ) )
|
|
110
|
+
|
|
111
|
+
for ( const caseItem of attributesIterator ) {
|
|
112
|
+
|
|
113
|
+
attributes.push ( caseItem [ 1 ] )
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// import { a, b, c } from 'xxx'
|
|
118
|
+
const attributeImport = contents.match ( new RegExp ( `import.+{(.+)}\\s*from\\s*["']${specifier}["']` ) )
|
|
119
|
+
|
|
120
|
+
if ( attributeImport ) {
|
|
121
|
+
|
|
122
|
+
const definedAttributes = attributeImport [ 1 ].split ( ',' ).map ( v => v.trim ( ) ).filter ( v => !v.startsWith ( 'default' ) )
|
|
123
|
+
|
|
124
|
+
attributes.push ( ...definedAttributes )
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return Array.from ( new Set ( attributes ) )
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* @param {string} specifier
|
|
134
|
+
* @param {{
|
|
135
|
+
* conditions: string[],
|
|
136
|
+
* parentURL: string | undefined,
|
|
137
|
+
* }} context
|
|
138
|
+
* @param {Function} defaultResolve
|
|
139
|
+
* @returns {Promise<{ url: string }>}
|
|
140
|
+
*/
|
|
141
|
+
export async function resolve ( specifier, context, defaultResolve ) {
|
|
142
|
+
|
|
143
|
+
const defaultSpecifer = specifier
|
|
144
|
+
|
|
145
|
+
const { parentURL } = context
|
|
146
|
+
|
|
147
|
+
// HTTP & HTTPS
|
|
148
|
+
if ( isWebURL ( specifier ) ) {
|
|
149
|
+
|
|
150
|
+
return { url: specifier }
|
|
151
|
+
} else if ( isWebURL ( parentURL ) && ( specifier.startsWith ( '.' ) || specifier.startsWith ( '/' ) ) ) {
|
|
152
|
+
|
|
153
|
+
return { url: new URL ( specifier, parentURL ).href }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// OOX special alias for web package
|
|
157
|
+
if ( specifier === 'oox' ) {
|
|
158
|
+
|
|
159
|
+
return {
|
|
160
|
+
url: 'file://' + path.resolve ( './node_modules/oox/index.mjs' )
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const { entryFile } = oox.config
|
|
165
|
+
|
|
166
|
+
// Relative specifier concat to absolute path
|
|
167
|
+
if ( specifier.startsWith ( '.' ) && parentURL ) {
|
|
168
|
+
|
|
169
|
+
specifier = path.posix.join ( path.dirname ( parentURL.replace ( 'file://', '' ) ), specifier )
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Windows pathname remove root sep
|
|
173
|
+
if ( os.platform ( ) === 'win32' && specifier.startsWith ( '/' ) ) {
|
|
174
|
+
|
|
175
|
+
specifier = specifier.replace ( '/', '' )
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// OOX RPC Proxy URL generation
|
|
179
|
+
if ( !specifier.endsWith ( entryFile.path ) && entryFile.group && specifier.startsWith ( entryFile.group ) ) {
|
|
180
|
+
|
|
181
|
+
const subSpecifier = specifier.slice ( entryFile.group.length )
|
|
182
|
+
|
|
183
|
+
const matchResult = subSpecifier.match ( /^\/?([\w-]+)(\/index)?(\.m?js)?$/ )
|
|
184
|
+
|
|
185
|
+
if ( matchResult ) {
|
|
186
|
+
|
|
187
|
+
const importerSpecifier = parentURL.replace ( os.platform ( ) === 'win32' ? /file:\/+/ : 'file://', '' )
|
|
188
|
+
|
|
189
|
+
const attributes = getImportAttributes ( importerSpecifier, defaultSpecifer )
|
|
190
|
+
|
|
191
|
+
return { url: generateRPCProxyURL ( matchResult [ 1 ], attributes ) }
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// restore Windows specifier protocol
|
|
196
|
+
if ( os.platform ( ) === 'win32' && specifier.includes ( '/' ) && !specifier.startsWith ( 'file://' ) ) {
|
|
197
|
+
|
|
198
|
+
specifier = 'file://' + specifier
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return defaultResolve ( specifier, context, defaultResolve )
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* @param {string} url
|
|
208
|
+
* @param {{
|
|
209
|
+
* format: string,
|
|
210
|
+
* }} context If resolve settled with a `format`, that value is included here.
|
|
211
|
+
* @param {Function} defaultLoad
|
|
212
|
+
* @returns {Promise<{
|
|
213
|
+
* format: string,
|
|
214
|
+
* source: string | ArrayBuffer | SharedArrayBuffer | Uint8Array,
|
|
215
|
+
* }>}
|
|
216
|
+
*/
|
|
217
|
+
export async function load ( url, context, defaultLoad ) {
|
|
218
|
+
|
|
219
|
+
if ( isWebURL ( url ) || isOOXURL ( url ) ) {
|
|
220
|
+
|
|
221
|
+
return getSource ( url, context, defaultLoad )
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return defaultLoad ( url, context, defaultLoad )
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
export function getFormat ( url, context, defaultGetFormat ) {
|
|
230
|
+
|
|
231
|
+
if ( isWebURL ( url ) || isOOXURL ( url ) ) {
|
|
232
|
+
|
|
233
|
+
return {
|
|
234
|
+
format: 'module'
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
return defaultGetFormat ( url, context, defaultGetFormat )
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
export function getSource ( url, context, defaultGetSource ) {
|
|
244
|
+
|
|
245
|
+
if ( isWebURL ( url ) ) {
|
|
246
|
+
|
|
247
|
+
const getMethod = url.startsWith ( 'https://' ) ? httpsGet : httpGet
|
|
248
|
+
|
|
249
|
+
return new Promise ( ( resolve, reject ) => getMethod ( url, res => {
|
|
250
|
+
let source = ''
|
|
251
|
+
res
|
|
252
|
+
.on ( 'data', chunk => source += chunk )
|
|
253
|
+
.on ( 'end', () => resolve ( { format: 'module', source } ) )
|
|
254
|
+
} ).on ( 'error', reject ) )
|
|
255
|
+
} else if ( isOOXURL ( url ) ) {
|
|
256
|
+
|
|
257
|
+
const mURL = new URL ( url )
|
|
258
|
+
|
|
259
|
+
if ( mURL.host === 'rpc' ) {
|
|
260
|
+
|
|
261
|
+
const regexp = /\/([\w-]+)\.mjs$/
|
|
262
|
+
|
|
263
|
+
const matchResult = mURL.pathname.match ( regexp )
|
|
264
|
+
|
|
265
|
+
// read all import attributes
|
|
266
|
+
const attributes = mURL.searchParams.getAll ( 'attr' )
|
|
267
|
+
|
|
268
|
+
const source = generateRPCProxyScript ( matchResult [ 1 ], attributes )
|
|
269
|
+
|
|
270
|
+
return { format: 'module', source }
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
return defaultGetSource ( url, context, defaultGetSource )
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
process.on ( 'unhandledRejection', console.error )
|
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'));
|
|
@@ -24,17 +20,22 @@ function getEntryFile(env) {
|
|
|
24
20
|
var name = filename === 'index.js' && groupFullDirectory !== fullDirectory ? directory : filename.split('.js')[0];
|
|
25
21
|
return { name, path: fullPath, group: groupFullDirectory };
|
|
26
22
|
}
|
|
27
|
-
function loadEntry(name, entryPath) {
|
|
23
|
+
async function loadEntry(name, entryPath) {
|
|
28
24
|
oox.config.name = name;
|
|
29
|
-
|
|
30
|
-
|
|
25
|
+
// Typescript 4.7.3, not supported import() expression
|
|
26
|
+
const methods = await eval(`import('file://${entryPath.replace(/\\/g, '/')}')`);
|
|
27
|
+
oox.setMethods(methods.default || methods);
|
|
31
28
|
}
|
|
32
29
|
async function startup() {
|
|
33
30
|
// 加载环境变量
|
|
34
|
-
const env = (0, configurer_1.configure)();
|
|
31
|
+
const env = await (0, configurer_1.configure)();
|
|
35
32
|
Object.assign(oox.config, env);
|
|
36
33
|
// 获取服务入口地址
|
|
37
34
|
const entryFile = getEntryFile(env);
|
|
35
|
+
oox.config.entryFile = {
|
|
36
|
+
path: entryFile.path.replace(/\\/g, '/'),
|
|
37
|
+
group: entryFile.group.replace(/\\/g, '/'),
|
|
38
|
+
};
|
|
38
39
|
// 代理<服务间调用>
|
|
39
40
|
if (env.group) {
|
|
40
41
|
const excludes = [entryFile.name];
|
|
@@ -43,28 +44,10 @@ async function startup() {
|
|
|
43
44
|
(0, proxyer_1.proxyGroup)(entryFile.group, excludes);
|
|
44
45
|
}
|
|
45
46
|
// 加载服务
|
|
46
|
-
loadEntry(entryFile.name, entryFile.path);
|
|
47
|
-
//
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
const httpConfig = oox.modules.builtins.http.config, socketioConfig = socketio.config;
|
|
51
|
-
if ('number' === typeof env.port) {
|
|
52
|
-
httpConfig.port = socketioConfig.port = env.port;
|
|
53
|
-
}
|
|
54
|
-
if (env.origin)
|
|
55
|
-
httpConfig.origin = env.origin;
|
|
56
|
-
if ('http' in env) {
|
|
57
|
-
if (env.http)
|
|
58
|
-
Object.assign(httpConfig, env.http);
|
|
59
|
-
else
|
|
60
|
-
httpConfig.disabled = true;
|
|
61
|
-
}
|
|
62
|
-
if ('socketio' in env) {
|
|
63
|
-
if (env.socketio)
|
|
64
|
-
Object.assign(socketioConfig, env.socketio);
|
|
65
|
-
else
|
|
66
|
-
socketioConfig.disabled = true;
|
|
67
|
-
}
|
|
47
|
+
await loadEntry(entryFile.name, entryFile.path);
|
|
48
|
+
// 模块配置
|
|
49
|
+
oox.modules.setConfig(oox.config);
|
|
50
|
+
const { http: { config: httpConfig }, socketio: { config: socketioConfig } } = oox.modules.builtins;
|
|
68
51
|
// 服务启动
|
|
69
52
|
await oox.serve();
|
|
70
53
|
console.log();
|
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.
|
|
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.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;
|
|
13
13
|
class Context extends app.Context {
|
|
14
14
|
// 请求溯源IP
|
|
15
15
|
sourceIP = '';
|
|
@@ -24,21 +24,29 @@ 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;
|
|
31
31
|
class Config {
|
|
32
32
|
// 服务名称
|
|
33
33
|
name = 'local';
|
|
34
|
+
// 启动文件
|
|
35
|
+
entryFile = {
|
|
36
|
+
// 启动文件路径
|
|
37
|
+
path: '',
|
|
38
|
+
// 服务列表路径
|
|
39
|
+
group: '',
|
|
40
|
+
};
|
|
34
41
|
// 主机地址
|
|
35
42
|
host = (0, utils_1.getIPAddress)(4)[0];
|
|
43
|
+
// 默认监听端口
|
|
44
|
+
port = 0;
|
|
45
|
+
// 默认跨域设置
|
|
46
|
+
origin = '';
|
|
36
47
|
}
|
|
37
48
|
exports.Config = Config;
|
|
38
49
|
exports.config = new Config();
|
|
39
|
-
function getConfig() {
|
|
40
|
-
}
|
|
41
|
-
exports.getConfig = getConfig;
|
|
42
50
|
let genTraceIdFunction = () => (0, node_crypto_1.randomUUID)();
|
|
43
51
|
function setGenTraceIdFunction(fn) {
|
|
44
52
|
genTraceIdFunction = fn;
|
|
@@ -123,6 +131,23 @@ function removeKeepAliveConnection(name, id) {
|
|
|
123
131
|
}
|
|
124
132
|
}
|
|
125
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;
|
|
126
151
|
async function rpc(arg1, action, params, context) {
|
|
127
152
|
if (!context || !context.traceId) {
|
|
128
153
|
context = getContext();
|
|
@@ -132,10 +157,9 @@ async function rpc(arg1, action, params, context) {
|
|
|
132
157
|
connection = arg1;
|
|
133
158
|
}
|
|
134
159
|
else if ('string' === typeof arg1) {
|
|
135
|
-
|
|
136
|
-
if (!
|
|
160
|
+
connection = loadBalancePolicy(arg1);
|
|
161
|
+
if (!connection)
|
|
137
162
|
throw new Error(`Connection<${arg1}> not found`);
|
|
138
|
-
connection = connections.values().next().value;
|
|
139
163
|
}
|
|
140
164
|
else
|
|
141
165
|
throw new Error(`Unknown rpc arg1<${arg1}>`);
|
package/index.mjs
CHANGED
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;
|
package/modules/http/index.js
CHANGED
|
@@ -20,6 +20,12 @@ class HTTPModule extends module_1.default {
|
|
|
20
20
|
server = null;
|
|
21
21
|
setConfig(config) {
|
|
22
22
|
Object.assign(this.config, config);
|
|
23
|
+
if (!config.hasOwnProperty('port')) {
|
|
24
|
+
this.config.port = oox.config.port;
|
|
25
|
+
}
|
|
26
|
+
if (!config.hasOwnProperty('origin')) {
|
|
27
|
+
this.config.origin = oox.config.origin;
|
|
28
|
+
}
|
|
23
29
|
}
|
|
24
30
|
getConfig() {
|
|
25
31
|
return this.config;
|
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)
|
|
@@ -57,6 +60,10 @@ class Modules extends module_1.default {
|
|
|
57
60
|
module.setConfig({ disabled: true });
|
|
58
61
|
}
|
|
59
62
|
}
|
|
63
|
+
else {
|
|
64
|
+
module.setConfig({});
|
|
65
|
+
}
|
|
66
|
+
config[module.name] = module.getConfig();
|
|
60
67
|
}
|
|
61
68
|
}
|
|
62
69
|
async serve() {
|
|
@@ -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,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "oox",
|
|
3
|
-
"version": "0.3.0-
|
|
3
|
+
"version": "0.3.0-beta8",
|
|
4
4
|
"description": "Graceful NodeJS distributed application solution",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"http",
|
|
7
7
|
"websocket",
|
|
8
8
|
"socket.io",
|
|
9
9
|
"rpc",
|
|
10
|
+
"framework",
|
|
10
11
|
"microservice",
|
|
11
12
|
"distributed",
|
|
12
13
|
"tracing"
|
|
@@ -15,9 +16,11 @@
|
|
|
15
16
|
"main": "index.js",
|
|
16
17
|
"types": "types/index.d.ts",
|
|
17
18
|
"exports": {
|
|
18
|
-
"
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
".": {
|
|
20
|
+
"import": "./index.mjs",
|
|
21
|
+
"require": "./index.js"
|
|
22
|
+
},
|
|
23
|
+
"./loader": "./bin/loader.mjs"
|
|
21
24
|
},
|
|
22
25
|
"bin": {
|
|
23
26
|
"oox": "bin/cli.js"
|
|
@@ -26,8 +29,9 @@
|
|
|
26
29
|
"homepage": "https://github.com/lipingruan/oox",
|
|
27
30
|
"license": "MIT",
|
|
28
31
|
"dependencies": {
|
|
29
|
-
"
|
|
30
|
-
"
|
|
32
|
+
"chalk": "^4.1.0",
|
|
33
|
+
"socket.io": "^4.4.0",
|
|
34
|
+
"socket.io-client": "^4.4.0"
|
|
31
35
|
},
|
|
32
36
|
"engines": {
|
|
33
37
|
"node": ">=12.0.0"
|
package/types/app.d.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
/// <reference types="node" />
|
|
3
3
|
import { EventEmitter } from 'node:events';
|
|
4
4
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
5
|
+
export * as logger from './logger';
|
|
5
6
|
export interface ReturnsBody {
|
|
6
7
|
traceId: string;
|
|
7
8
|
success: boolean;
|
|
@@ -12,6 +13,7 @@ export interface ReturnsBody {
|
|
|
12
13
|
};
|
|
13
14
|
}
|
|
14
15
|
export declare class Context {
|
|
16
|
+
[x: string]: any;
|
|
15
17
|
traceId?: string;
|
|
16
18
|
}
|
|
17
19
|
export declare const asyncStore: AsyncLocalStorage<Context>;
|
|
@@ -26,6 +28,7 @@ export declare function getMethods(): any;
|
|
|
26
28
|
export declare function on(event: 'request', listener: (action: string, params: any[], context: Context) => void): void;
|
|
27
29
|
export declare function on(event: 'success', listener: (action: string, params: any[], context: Context, result: ReturnsBody) => void): void;
|
|
28
30
|
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, tag: string, msgs: any[]) => void): void;
|
|
29
32
|
/**
|
|
30
33
|
* Call an Function on RPC server
|
|
31
34
|
* @param action
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare function configure(): any
|
|
1
|
+
export declare function configure(): Promise<any>;
|
package/types/index.d.ts
CHANGED
|
@@ -5,22 +5,27 @@ 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;
|
|
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;
|
|
19
19
|
name: string;
|
|
20
|
+
entryFile: {
|
|
21
|
+
path: string;
|
|
22
|
+
group: string;
|
|
23
|
+
};
|
|
20
24
|
host: string;
|
|
25
|
+
port: number;
|
|
26
|
+
origin: string;
|
|
21
27
|
}
|
|
22
28
|
export declare const config: Config;
|
|
23
|
-
export declare function getConfig(): void;
|
|
24
29
|
export declare function setGenTraceIdFunction(fn: () => string): void;
|
|
25
30
|
/**
|
|
26
31
|
* 生成随机不重复id
|
|
@@ -66,5 +71,6 @@ export declare function getKeepAliveConnection(name: string, id: string): RPCKee
|
|
|
66
71
|
export declare function addKeepAliveConnection(connection: RPCKeepAliveConnection): void;
|
|
67
72
|
export declare function removeKeepAliveConnection(connection: RPCKeepAliveConnection): void;
|
|
68
73
|
export declare function removeKeepAliveConnection(name: string, id: string): void;
|
|
74
|
+
export declare function setLoadBalancePolicy(policy: (name: string) => RPCKeepAliveConnection): void;
|
|
69
75
|
export declare function rpc(appName: string, action: string, params: any[], context?: Context): Promise<any>;
|
|
70
76
|
export declare function rpc(connection: RPCKeepAliveConnection, action: string, params: any[], context?: Context): Promise<any>;
|
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>;
|