oox 0.3.1 → 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 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
- env[arg] = true;
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.default || 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 socketio = oox.modules.get('socketio');
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 socket = await socketio.connect(url);
22
- onConnection(socket, url);
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(socket, url) {
32
- const { name } = socket.data;
33
- socket.once('disconnect', async () => {
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(urlFormatter(url));
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.getUrl()));
56
+ console.log(' at', chalk.underline.green(http.getURL()));
57
57
  if (socketio.config.enabled)
58
- console.log(' at', chalk.underline.green(socketio.getUrl()));
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
- const { name, id } = connection.data;
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(name, id) {
112
- if (name instanceof RPCKeepAliveConnection) {
113
- id = name.data.id;
114
- name = name.data.name;
92
+ export function removeKeepAliveConnection(arg1, arg2) {
93
+ if (typeof arg1 === 'string') {
94
+ keepAliveConnections.remove(arg1, arg2);
95
+ enabledKeepAliveConnections.remove(arg1, arg2);
115
96
  }
116
- if (keepAliveConnections.has(name)) {
117
- const group = keepAliveConnections.get(name);
118
- group.delete(id);
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
- * random connection select for default load balance policy
125
- * @param name service name
126
- * @returns selected connection
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 = keepAliveConnections.get(name);
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.nativeConnection, action, params, context);
133
+ return connection.adapter.rpc(connection, action, params, context);
155
134
  }
@@ -1,6 +1,7 @@
1
1
  import * as http from 'node:http';
2
2
  import * as https from 'node:https';
3
3
  import { httpRequest, parseHTTPBody } from './utils.js';
4
+ import Router from './router.js';
4
5
  import * as oox from '../../index.js';
5
6
  import Module, { ModuleConfig } from '../module.js';
6
7
  export class HTTPConfig extends ModuleConfig {
@@ -26,11 +27,37 @@ export default class HTTPModule extends Module {
26
27
  name = 'http';
27
28
  config = new HTTPConfig;
28
29
  server = null;
29
- getUrl() {
30
+ router = new Router();
31
+ getURL() {
30
32
  const { host } = oox.config;
31
33
  const { port, path } = this.config;
32
34
  const protocol = this.config.ssl.enabled ? `https:` : `http:`;
33
- return `${protocol}//${host}:${port}${path}`;
35
+ return new URL(`${protocol}//${host}:${port}${path}`);
36
+ }
37
+ // 注册GET路由
38
+ get(path, ...args) {
39
+ this.router.get(path, ...args);
40
+ return this;
41
+ }
42
+ // 注册POST路由
43
+ post(path, ...args) {
44
+ this.router.post(path, ...args);
45
+ return this;
46
+ }
47
+ // 注册PUT路由
48
+ put(path, ...args) {
49
+ this.router.put(path, ...args);
50
+ return this;
51
+ }
52
+ // 注册DELETE路由
53
+ delete(path, ...args) {
54
+ this.router.delete(path, ...args);
55
+ return this;
56
+ }
57
+ // 注册全局中间件
58
+ use(middleware) {
59
+ this.router.use(middleware);
60
+ return this;
34
61
  }
35
62
  setConfig(config) {
36
63
  Object.assign(this.config, config);
@@ -118,7 +145,32 @@ export default class HTTPModule extends Module {
118
145
  async requestHandler(request, response) {
119
146
  if (!this.cors(request, response))
120
147
  return;
121
- const url = new URL(request.url, request.headers.origin || 'http://localhost');
148
+ const url = new URL(request.url, `http://${request.headers.host || 'localhost'}`);
149
+ const method = request.method || 'GET';
150
+ // 尝试匹配路由
151
+ const matched = this.router.match(method, url.pathname);
152
+ if (matched) {
153
+ const req = this.router.createRequestObject(request, url);
154
+ const res = this.router.createResponseObject(response);
155
+ // 解析请求体
156
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
157
+ try {
158
+ req.body = await parseHTTPBody(request);
159
+ }
160
+ catch (error) {
161
+ return this.respond(request, response, {
162
+ success: false,
163
+ error: {
164
+ message: error.message,
165
+ stack: error.stack
166
+ }
167
+ });
168
+ }
169
+ }
170
+ await this.router.handleRoute(matched.route, matched.params, req, res);
171
+ return;
172
+ }
173
+ // 回退到RPC调用
122
174
  if (url.pathname === this.config.path) {
123
175
  await this.call(request, response);
124
176
  }
@@ -0,0 +1,205 @@
1
+ export default class Router {
2
+ routes = new Map();
3
+ globalMiddleware = [];
4
+ // 注册GET路由
5
+ get(path, ...args) {
6
+ const { handler, middleware } = this.parseRouteArgs(args);
7
+ this.addRoute('GET', path, handler, middleware);
8
+ }
9
+ // 注册POST路由
10
+ post(path, ...args) {
11
+ const { handler, middleware } = this.parseRouteArgs(args);
12
+ this.addRoute('POST', path, handler, middleware);
13
+ }
14
+ // 注册PUT路由
15
+ put(path, ...args) {
16
+ const { handler, middleware } = this.parseRouteArgs(args);
17
+ this.addRoute('PUT', path, handler, middleware);
18
+ }
19
+ // 注册DELETE路由
20
+ delete(path, ...args) {
21
+ const { handler, middleware } = this.parseRouteArgs(args);
22
+ this.addRoute('DELETE', path, handler, middleware);
23
+ }
24
+ // 解析路由参数,支持多种传入方式
25
+ parseRouteArgs(args) {
26
+ let handler;
27
+ let middleware = [];
28
+ if (args.length === 0) {
29
+ throw new Error('No handler provided for route');
30
+ }
31
+ // 方式1: [handler] 或 [middlewareArray, handler]
32
+ if (args.length === 1) {
33
+ if (typeof args[0] === 'function') {
34
+ handler = args[0];
35
+ }
36
+ else {
37
+ throw new Error('Invalid route handler');
38
+ }
39
+ }
40
+ // 方式2: [handler, middlewareArray] 或 [middleware1, middleware2, handler] 或 [middlewareArray, handler]
41
+ else {
42
+ // 检查最后一个参数是否是函数(处理器)
43
+ if (typeof args[args.length - 1] === 'function') {
44
+ handler = args[args.length - 1];
45
+ // 前面的所有都是中间件
46
+ const middleArgs = args.slice(0, -1);
47
+ // 展平中间件数组
48
+ for (const arg of middleArgs) {
49
+ if (Array.isArray(arg)) {
50
+ middleware.push(...arg);
51
+ }
52
+ else if (typeof arg === 'function') {
53
+ middleware.push(arg);
54
+ }
55
+ }
56
+ }
57
+ // 检查第一个参数是否是函数
58
+ else if (typeof args[0] === 'function') {
59
+ handler = args[0];
60
+ // 后面的是中间件
61
+ const middleArgs = args.slice(1);
62
+ for (const arg of middleArgs) {
63
+ if (Array.isArray(arg)) {
64
+ middleware.push(...arg);
65
+ }
66
+ else if (typeof arg === 'function') {
67
+ middleware.push(arg);
68
+ }
69
+ }
70
+ }
71
+ else {
72
+ throw new Error('Invalid route arguments');
73
+ }
74
+ }
75
+ return { handler, middleware };
76
+ }
77
+ // 注册全局中间件
78
+ use(middleware) {
79
+ this.globalMiddleware.push(middleware);
80
+ }
81
+ // 注册特定路径的中间件
82
+ usePath(path, middleware) {
83
+ // 实现路径级中间件
84
+ }
85
+ // 添加路由
86
+ addRoute(method, path, handler, middleware = []) {
87
+ if (!this.routes.has(method)) {
88
+ this.routes.set(method, []);
89
+ }
90
+ // 编译路径为正则表达式,支持路径参数
91
+ const { regex, paramNames } = this.compilePath(path);
92
+ this.routes.get(method).push({
93
+ path,
94
+ method,
95
+ handler,
96
+ middleware,
97
+ regex,
98
+ paramNames
99
+ });
100
+ }
101
+ // 编译路径为正则表达式
102
+ compilePath(path) {
103
+ const paramNames = [];
104
+ const regexPattern = path
105
+ .replace(/:([^/]+)/g, (_, paramName) => {
106
+ paramNames.push(paramName);
107
+ return '([^/]+)';
108
+ })
109
+ .replace(/\//g, '\\/')
110
+ .replace(/\*/g, '.*');
111
+ return {
112
+ regex: new RegExp(`^${regexPattern}$`),
113
+ paramNames
114
+ };
115
+ }
116
+ // 匹配路由
117
+ match(method, path) {
118
+ const routes = this.routes.get(method) || [];
119
+ for (const route of routes) {
120
+ const match = path.match(route.regex);
121
+ if (match) {
122
+ const params = {};
123
+ route.paramNames.forEach((paramName, index) => {
124
+ params[paramName] = match[index + 1];
125
+ });
126
+ return { route, params };
127
+ }
128
+ }
129
+ return null;
130
+ }
131
+ // 创建请求对象
132
+ createRequestObject(originalRequest, url) {
133
+ return {
134
+ originalRequest,
135
+ url,
136
+ method: originalRequest.method || 'GET',
137
+ path: url.pathname,
138
+ query: Object.fromEntries(url.searchParams),
139
+ params: {},
140
+ headers: originalRequest.headers,
141
+ body: null
142
+ };
143
+ }
144
+ // 创建响应对象
145
+ createResponseObject(originalResponse) {
146
+ let statusCode = 200;
147
+ return {
148
+ originalResponse,
149
+ status(code) {
150
+ statusCode = code;
151
+ return this;
152
+ },
153
+ json(data) {
154
+ const jsonString = JSON.stringify(data);
155
+ this.originalResponse.statusCode = statusCode;
156
+ this.originalResponse.setHeader('Content-Type', 'application/json');
157
+ this.originalResponse.setHeader('Content-Length', Buffer.byteLength(jsonString));
158
+ this.originalResponse.end(jsonString);
159
+ },
160
+ send(data) {
161
+ const dataString = typeof data === 'string' ? data : JSON.stringify(data);
162
+ this.originalResponse.statusCode = statusCode;
163
+ this.originalResponse.setHeader('Content-Type', 'text/plain');
164
+ this.originalResponse.setHeader('Content-Length', Buffer.byteLength(dataString));
165
+ this.originalResponse.end(dataString);
166
+ },
167
+ end(data) {
168
+ this.originalResponse.statusCode = statusCode;
169
+ this.originalResponse.end(data);
170
+ }
171
+ };
172
+ }
173
+ // 执行中间件
174
+ async executeMiddleware(middleware, req, res) {
175
+ for (const fn of middleware) {
176
+ let nextCalled = false;
177
+ const next = () => { nextCalled = true; };
178
+ const result = fn(req, res, next);
179
+ if (result instanceof Promise) {
180
+ await result;
181
+ }
182
+ if (!nextCalled) {
183
+ return false; // 中间件已结束响应
184
+ }
185
+ }
186
+ return true; // 所有中间件都已执行
187
+ }
188
+ // 处理路由请求
189
+ async handleRoute(route, params, req, res) {
190
+ req.params = params;
191
+ // 执行全局中间件
192
+ const globalMiddlewareContinue = await this.executeMiddleware(this.globalMiddleware, req, res);
193
+ if (!globalMiddlewareContinue)
194
+ return;
195
+ // 执行路由中间件
196
+ const routeMiddlewareContinue = await this.executeMiddleware(route.middleware, req, res);
197
+ if (!routeMiddlewareContinue)
198
+ return;
199
+ // 执行路由处理函数
200
+ const result = route.handler(req, res);
201
+ if (result instanceof Promise) {
202
+ await result;
203
+ }
204
+ }
205
+ }
@@ -29,11 +29,12 @@ export async function parseHTTPBody(request) {
29
29
  // application/json; charset=utf-8
30
30
  if (contentType)
31
31
  contentType = contentType.split(';')[0].trim();
32
- const contentSize = request.headers['content-length'];
33
- if (!contentSize)
32
+ const contentLength = request.headers['content-length'];
33
+ if (!contentLength || contentLength === '0')
34
34
  return null;
35
- const buffer = await stream2buffer(request, +contentSize || 0);
36
- if (contentSize && buffer.length !== +contentSize)
35
+ const contentSize = +contentLength;
36
+ const buffer = await stream2buffer(request, contentSize);
37
+ if (buffer.length !== contentSize)
37
38
  throw new Error('Content-Length Incorrect');
38
39
  switch (contentType) {
39
40
  case 'application/json':
@@ -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
+ }