oox 0.3.0-beta1 → 0.3.0-beta2

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/utils.js CHANGED
@@ -1,63 +1,63 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.genKVMethods = exports.getAllCallablePropertyNames = exports.getIPAddress = void 0;
4
- const os_1 = require("os");
5
- function getIPAddress(version = 4) {
6
- const interfaces = (0, os_1.networkInterfaces)();
7
- const ip = [];
8
- for (const name of Object.keys(interfaces))
9
- for (const intf of interfaces[name])
10
- if (intf.mac !== '00:00:00:00:00:00')
11
- if ((version !== 4 && version !== 6) || 'IPv' + version === intf.family)
12
- ip.push(intf.address);
13
- if (!ip.length) {
14
- if (version !== 6)
15
- ip.push('127.0.0.1');
16
- if (version !== 4)
17
- ip.push('::1');
18
- }
19
- return ip;
20
- }
21
- exports.getIPAddress = getIPAddress;
22
- function getAllCallablePropertyNames(obj) {
23
- if (!obj)
24
- return [];
25
- let props = [], tmpProps = [], index = 0, size = 0, tmpProp = '';
26
- const bans = ["constructor", "__defineGetter__", "__defineSetter__",
27
- "hasOwnProperty", "__lookupGetter__", "__lookupSetter__",
28
- "isPrototypeOf", "propertyIsEnumerable", "toString",
29
- "valueOf", "__proto__", "toLocaleString"];
30
- do {
31
- tmpProps = Object.getOwnPropertyNames(obj);
32
- index = -1, size = tmpProps.length;
33
- while (++index < size) {
34
- tmpProp = tmpProps[index];
35
- if (!props.includes(tmpProp) && !bans.includes(tmpProp)) {
36
- props.push(tmpProp);
37
- }
38
- }
39
- } while (obj = Object.getPrototypeOf(obj));
40
- return props;
41
- }
42
- exports.getAllCallablePropertyNames = getAllCallablePropertyNames;
43
- function genKVMethods(methods, kvMethods = new Map(), sourceKVMethods = new Map(), nameStack = []) {
44
- let keys = getAllCallablePropertyNames(methods);
45
- for (const key of keys) {
46
- /**
47
- * @type {Function}
48
- */
49
- let val = methods[key];
50
- if ('function' === typeof val) {
51
- const action = nameStack.concat(key).join('.');
52
- // 原函数绑定
53
- sourceKVMethods.set(action, val);
54
- // 壳函数绑定
55
- kvMethods.set(action, val.bind(methods));
56
- }
57
- else {
58
- genKVMethods(val, kvMethods, sourceKVMethods, nameStack.concat(key));
59
- }
60
- }
61
- return { kvMethods, sourceKVMethods };
62
- }
63
- exports.genKVMethods = genKVMethods;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.genKVMethods = exports.getAllCallablePropertyNames = exports.getIPAddress = void 0;
4
+ const os_1 = require("os");
5
+ function getIPAddress(version = 4) {
6
+ const interfaces = (0, os_1.networkInterfaces)();
7
+ const ip = [];
8
+ for (const name of Object.keys(interfaces))
9
+ for (const intf of interfaces[name])
10
+ if (intf.mac !== '00:00:00:00:00:00')
11
+ if ((version !== 4 && version !== 6) || 'IPv' + version === intf.family)
12
+ ip.push(intf.address);
13
+ if (!ip.length) {
14
+ if (version !== 6)
15
+ ip.push('127.0.0.1');
16
+ if (version !== 4)
17
+ ip.push('::1');
18
+ }
19
+ return ip;
20
+ }
21
+ exports.getIPAddress = getIPAddress;
22
+ function getAllCallablePropertyNames(obj) {
23
+ if (!obj)
24
+ return [];
25
+ let props = [], tmpProps = [], index = 0, size = 0, tmpProp = '';
26
+ const bans = ["constructor", "__defineGetter__", "__defineSetter__",
27
+ "hasOwnProperty", "__lookupGetter__", "__lookupSetter__",
28
+ "isPrototypeOf", "propertyIsEnumerable", "toString",
29
+ "valueOf", "__proto__", "toLocaleString"];
30
+ do {
31
+ tmpProps = Object.getOwnPropertyNames(obj);
32
+ index = -1, size = tmpProps.length;
33
+ while (++index < size) {
34
+ tmpProp = tmpProps[index];
35
+ if (!props.includes(tmpProp) && !bans.includes(tmpProp)) {
36
+ props.push(tmpProp);
37
+ }
38
+ }
39
+ } while (obj = Object.getPrototypeOf(obj));
40
+ return props;
41
+ }
42
+ exports.getAllCallablePropertyNames = getAllCallablePropertyNames;
43
+ function genKVMethods(methods, kvMethods = new Map(), sourceKVMethods = new Map(), nameStack = []) {
44
+ let keys = getAllCallablePropertyNames(methods);
45
+ for (const key of keys) {
46
+ /**
47
+ * @type {Function}
48
+ */
49
+ let val = methods[key];
50
+ if ('function' === typeof val) {
51
+ const action = nameStack.concat(key).join('.');
52
+ // 原函数绑定
53
+ sourceKVMethods.set(action, val);
54
+ // 壳函数绑定
55
+ kvMethods.set(action, val.bind(methods));
56
+ }
57
+ else {
58
+ genKVMethods(val, kvMethods, sourceKVMethods, nameStack.concat(key));
59
+ }
60
+ }
61
+ return { kvMethods, sourceKVMethods };
62
+ }
63
+ exports.genKVMethods = genKVMethods;
@@ -1,101 +0,0 @@
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;
@@ -1,148 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const client_1 = require("./client");
4
- const oox = require("../../index");
5
- const index_1 = require("../../index");
6
- const socket_1 = require("./socket");
7
- class SocketIOModule extends client_1.default {
8
- sockets = socket_1.sockets;
9
- onSyncConnection(socket) {
10
- const mSockets = Array.from(socket_1.sockets.values())
11
- .filter(s => s !== socket &&
12
- s.data.name !== socket.data.name &&
13
- s.data.id.startsWith('ws://'));
14
- return mSockets.map(s => s.data);
15
- }
16
- serverOnDisconnect(socket, reason) {
17
- super.serverOnDisconnect(socket, reason);
18
- (0, index_1.removeKeepAliveConnection)(socket.data.name, socket.data.id);
19
- }
20
- clientOnDisconnect(socket, reason) {
21
- super.clientOnDisconnect(socket, reason);
22
- (0, index_1.removeKeepAliveConnection)(socket.data.name, socket.data.id);
23
- }
24
- /**
25
- *
26
- * @param socket 是由哪个通道发送过来的
27
- * @param connectionDatas
28
- */
29
- clientOnSyncConnection(socket, connectionDatas) {
30
- for (const data of connectionDatas)
31
- if (!socket_1.sockets.has(data.id))
32
- this.connect(data.id).catch((error) => console.error(error));
33
- }
34
- onFetchActions(socket, search) {
35
- const data = [];
36
- for (const key of oox.kvMethods.keys())
37
- if (!key.endsWith('_proxy') && key.includes(search))
38
- data.push(key);
39
- return data;
40
- }
41
- fetchActions(id, search = '') {
42
- let socket = socket_1.sockets.get(id);
43
- if (!socket) {
44
- const connections = (0, index_1.getKeepAliveConnections)(id);
45
- if (!connections || !connections.size)
46
- throw new Error(`Unknown service identify<${id}>`);
47
- id = connections.keys().next().value;
48
- socket = socket_1.sockets.get(id);
49
- }
50
- if (!socket)
51
- throw new Error(`Unknown service identify<${id}>`);
52
- return this.emit(socket.data.id, 'fetchActions', [search]);
53
- }
54
- onConnection(socket) {
55
- const { id, name, host } = socket.data;
56
- const connection = new index_1.RPCKeepAliveConnection(this, id, socket.data);
57
- (0, index_1.addKeepAliveConnection)(connection);
58
- const connectionContext = {
59
- sourceIP: '',
60
- ip: host,
61
- caller: name,
62
- callerId: id,
63
- connection
64
- };
65
- socket.on('fetchActions', async (search, fn) => {
66
- if ('function' !== typeof fn)
67
- return;
68
- const data = await this.onFetchActions(socket, search);
69
- fn(data);
70
- });
71
- socket.on('call', async (action, params, context, callback) => {
72
- if ('object' !== typeof context)
73
- context = oox.genContext(connectionContext);
74
- else
75
- context = oox.genContext(Object.assign(context, connectionContext));
76
- this.call(action, params, context, callback);
77
- });
78
- }
79
- /**
80
- *
81
- * @param {Socket} socket
82
- */
83
- serverOnConnection(socket) {
84
- super.serverOnConnection(socket);
85
- socket.setMaxListeners(0);
86
- socket.on('syncConnection', async (fn) => {
87
- if ('function' !== typeof fn)
88
- return;
89
- const data = this.onSyncConnection(socket);
90
- fn(data);
91
- });
92
- this.onConnection(socket);
93
- }
94
- async call(action, params, context, callback) {
95
- const returns = await oox.call(action, params, context);
96
- 'function' === typeof callback && callback(returns);
97
- return returns;
98
- }
99
- clientOnConnection(socket) {
100
- super.clientOnConnection(socket);
101
- socket.emit('syncConnection', (socketDatas) => this.clientOnSyncConnection(socket, socketDatas));
102
- this.onConnection(socket);
103
- }
104
- /**
105
- * socketio emit
106
- */
107
- async emit(url, action, params) {
108
- let socket = null;
109
- try {
110
- socket = await this.connect(url);
111
- }
112
- catch (error) {
113
- // try again
114
- socket = await this.connect(url);
115
- }
116
- try {
117
- return await new Promise((resolve, reject) => {
118
- const onError = (reason) => {
119
- const message = 'string' === typeof reason ? reason : reason instanceof Error ? reason.message : 'connect error';
120
- reject(new Error(message));
121
- };
122
- // RPC 执行时中断连接
123
- socket.once('disconnect', onError);
124
- socket.emit(action, ...params, (returns) => {
125
- socket.off('disconnect', onError);
126
- resolve(returns);
127
- });
128
- });
129
- }
130
- catch (error) {
131
- throw new Error(error.message);
132
- }
133
- }
134
- /**
135
- * RPC
136
- */
137
- async rpc(url, action, params, context) {
138
- if (!context || !context.traceId) {
139
- context = oox.getContext();
140
- }
141
- const { error, body } = await this.emit(url, 'call', [action, params, context]);
142
- if (error)
143
- throw new Error(error.message);
144
- else
145
- return body;
146
- }
147
- }
148
- exports.default = SocketIOModule;
@@ -1,130 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SocketIOConfig = void 0;
4
- const http = require("http");
5
- const socket_io_1 = require("socket.io");
6
- const module_1 = require("../module");
7
- const socket_1 = require("./socket");
8
- const oox = require("../../index");
9
- class SocketIOConfig extends module_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 module_1.default {
19
- name = 'oox: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
- }
30
- getConfig() {
31
- return this.config;
32
- }
33
- async serve() {
34
- await this.stop();
35
- const port = this.config.port;
36
- const isSelfServer = this.#isSelfServer = this.server ? true : false;
37
- const server = this.server = isSelfServer ? this.server :
38
- http.createServer((request, response) => response.end('No HTTP Gateway'));
39
- if (!server.listening)
40
- server.listen(port);
41
- const address = server.address();
42
- if (!address || 'object' !== typeof address)
43
- throw new Error('Cannot read socket.io server port');
44
- this.config.port = address.port;
45
- this.createSocketIOServer();
46
- }
47
- async stop() {
48
- if (this.socketServer)
49
- await new Promise((resolve, reject) => this.socketServer.close(error => error ? reject(error) : resolve()));
50
- if (this.#isSelfServer)
51
- await new Promise((resolve, reject) => this.server.close(error => error ? reject(error) : resolve()));
52
- }
53
- genSocketIOServerOptions() {
54
- const options = {
55
- /**
56
- * name of the path to capture
57
- * @default "/socket.io"
58
- */
59
- path: this.config.path,
60
- /**
61
- * how many ms before a client without namespace is closed
62
- * @default 45000
63
- */
64
- connectTimeout: 5000,
65
- /**
66
- * how many ms without a pong packet to consider the connection closed
67
- * @default 5000
68
- */
69
- pingTimeout: 2000,
70
- /**
71
- * how many ms before sending a new ping packet
72
- * @default 25000
73
- */
74
- pingInterval: 10000,
75
- /**
76
- * how many bytes or characters a message can be, before closing the session (to avoid DoS).
77
- * @default 1e5 (100 KB)
78
- */
79
- maxHttpBufferSize: 1e5
80
- };
81
- const { origin } = this.config;
82
- if (origin)
83
- options.cors = { origin };
84
- return options;
85
- }
86
- createSocketIOServer() {
87
- const socketServer = this.socketServer = new socket_io_1.Server(this.server, this.genSocketIOServerOptions());
88
- socketServer.on('connection', async (socket) => {
89
- try {
90
- this.serverOnSocketConnection(socket);
91
- }
92
- catch (error) {
93
- socket.send(error.message).disconnect(true);
94
- }
95
- });
96
- }
97
- /**
98
- * 服务端Socket连接事件
99
- */
100
- serverOnSocketConnection(socket) {
101
- const headers = socket.handshake.headers;
102
- const callerId = String(headers['x-caller-id'] || '') || socket.id;
103
- // 已经存在相同的连接
104
- if (socket_1.sockets.has(callerId))
105
- throw new Error('Connection Exists');
106
- // client ip or caller service ip
107
- const ip = String(headers['x-real-ip'] || headers['x-ip'] || socket.handshake.address);
108
- // service name
109
- const caller = String(headers['x-caller'] || 'anonymous');
110
- socket.data = { connected: true, host: ip, name: caller, id: callerId };
111
- // 保存 callerId 与 socket 对应关系
112
- socket_1.sockets.set(callerId, socket);
113
- socket.on('disconnect', reason => this.serverOnSocketDisconnect(socket, reason));
114
- socket.emit('oox_connected', { name: oox.config.name });
115
- this.serverOnConnection(socket);
116
- }
117
- serverOnConnection(socket) { }
118
- /**
119
- * 服务端Socket断开事件
120
- * @param {Socket} socket
121
- * @param {Error} reason
122
- */
123
- serverOnSocketDisconnect(socket, reason) {
124
- socket.data.connected = false;
125
- socket_1.sockets.delete(socket.data.id);
126
- this.serverOnDisconnect(socket, reason);
127
- }
128
- serverOnDisconnect(socket, reason) { }
129
- }
130
- exports.default = SocketIOServer;
@@ -1,4 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.sockets = void 0;
4
- exports.sockets = new Map();
@@ -1,23 +0,0 @@
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
- }
@@ -1,35 +0,0 @@
1
- import SocketIOClient from './client';
2
- import * as oox from '../../index';
3
- import { RPCKeepAliveConnectionData, RPCConnectionAdapter } from '../../index';
4
- import { Socket, ServerSocket, ClientSocket } from './socket';
5
- export default class SocketIOModule extends SocketIOClient implements RPCConnectionAdapter {
6
- sockets: Map<string, Socket>;
7
- onSyncConnection(socket: Socket): oox.RPCKeepAliveConnectionData[];
8
- serverOnDisconnect(socket: ServerSocket, reason: string): void;
9
- clientOnDisconnect(socket: ClientSocket, reason: any): void;
10
- /**
11
- *
12
- * @param socket 是由哪个通道发送过来的
13
- * @param connectionDatas
14
- */
15
- clientOnSyncConnection(socket: Socket, connectionDatas: RPCKeepAliveConnectionData[]): void;
16
- onFetchActions(socket: Socket, search: string): string[];
17
- fetchActions(url: string, search?: string): Promise<RPCKeepAliveConnectionData[]>;
18
- fetchActions(name: string, search?: string): Promise<RPCKeepAliveConnectionData[]>;
19
- onConnection(socket: Socket): void;
20
- /**
21
- *
22
- * @param {Socket} socket
23
- */
24
- serverOnConnection(socket: ServerSocket): void;
25
- call(action: string, params: any[], context: oox.Context, callback?: (returns: any) => void): Promise<oox.ReturnsBody>;
26
- clientOnConnection(socket: ClientSocket): void;
27
- /**
28
- * socketio emit
29
- */
30
- emit(url: string, action: string, params: any[]): Promise<unknown>;
31
- /**
32
- * RPC
33
- */
34
- rpc(url: string, action: string, params: [], context?: oox.Context): Promise<any>;
35
- }
@@ -1,35 +0,0 @@
1
- /// <reference types="node" />
2
- import * as http from 'http';
3
- import { Server, ServerOptions } from 'socket.io';
4
- import Module, { ModuleConfig } from '../module';
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
- }
@@ -1,11 +0,0 @@
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>;