oox 0.3.0-beta11 → 0.3.0-beta13

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.
@@ -1,168 +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;
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;
@@ -1,136 +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.listening && 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;
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.listening && 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;
@@ -1,4 +1,4 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.sockets = void 0;
4
- exports.sockets = new Map();
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sockets = void 0;
4
+ exports.sockets = new Map();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oox",
3
- "version": "0.3.0-beta11",
3
+ "version": "0.3.0-beta13",
4
4
  "description": "Graceful NodeJS distributed application solution",
5
5
  "keywords": [
6
6
  "http",