oox 0.3.6 → 0.3.7

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/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  graceful microservice framework.
6
6
 
7
7
  ### Features
8
- - [x] HTTP & socket.io support (native SSL supported)
8
+ - [x] HTTP & WebSocket support (native SSL supported)
9
9
  - [x] Zero configure startup
10
10
  - [x] Non-invasive coding style
11
11
  - [x] Intuitive route style
package/bin/cli.js CHANGED
@@ -63,11 +63,6 @@ if (execFilename.endsWith('oox') || fileURLToPath(import.meta.url) === execFilen
63
63
  ['http.ssl.cert', 'file', 'set HTTPS certificate path'],
64
64
  ['http.ssl.key', 'file', 'set HTTPS private key path'],
65
65
  ['http.ssl.ca', 'file', 'set HTTPS CA path'],
66
- ['socketio', 'json/bool', 'SocketIO server options, support flat name, or set no to disable SocketIO server'],
67
- ['socketio.port', 'int server port'],
68
- ['socketio.path', 'string', 'set SocketIO server path'],
69
- ['socketio.origin', 'urls', 'set SocketIO server origin, support string | array<string>'],
70
- ['socketio.ssl', 'json', 'like http.ssl'],
71
66
  ];
72
67
  console.log(mergeCommandParams(params_base));
73
68
  console.log(chalk.bold('Registry:'));
package/bin/starter.js CHANGED
@@ -57,13 +57,16 @@ export async function startup() {
57
57
  // 服务启动
58
58
  await oox.serve();
59
59
  oox.emit('app:served');
60
- const { http, socketio } = oox.modules.builtins;
60
+ const { http } = oox.modules.builtins;
61
61
  console.log();
62
62
  console.log('Service', chalk.bold(`${oox.config.name}`), 'running.');
63
- if (http.config.enabled)
64
- console.log(' at', chalk.underline.green(http.getURL()));
65
- if (socketio.config.enabled)
66
- console.log(' at', chalk.underline.green(socketio.getURL()));
63
+ // 打包服务地址
64
+ const maxNameLength = Math.max(...oox.modules.queue.map(module => module.name.length));
65
+ for (const module of oox.modules.queue) {
66
+ const spaces = ' '.repeat(Math.max(0, maxNameLength - module.name.length));
67
+ if (module.config.enabled && module.serviceURL)
68
+ console.log(` ${spaces}${chalk.bold(module.name)} at`, chalk.underline.green(module.serviceURL.toString()));
69
+ }
67
70
  console.log();
68
71
  // 服务注册
69
72
  if (config.registry)
@@ -30,13 +30,13 @@ export class KeepAliveConnection extends EventEmitter {
30
30
  set enabled(enabled) {
31
31
  if (enabled !== this.#enabled) {
32
32
  this.#enabled = enabled;
33
- this.emit(enabled ? 'enabled' : 'disabled');
34
33
  if (enabled) {
35
34
  enabledKeepAliveConnections.add(this);
36
35
  }
37
36
  else {
38
37
  enabledKeepAliveConnections.remove(this);
39
38
  }
39
+ this.emit(enabled ? 'enabled' : 'disabled');
40
40
  }
41
41
  }
42
42
  get enabled() {
@@ -120,15 +120,15 @@ export function addKeepAliveConnection(connection) {
120
120
  export function removeKeepAliveConnection(arg1, arg2) {
121
121
  if (typeof arg1 === 'string') {
122
122
  const connection = keepAliveConnections.get(arg1, arg2);
123
- if (connection)
124
- connection.disconnect();
125
123
  keepAliveConnections.remove(arg1, arg2);
126
124
  enabledKeepAliveConnections.remove(arg1, arg2);
125
+ if (connection)
126
+ connection.disconnect();
127
127
  }
128
128
  else {
129
- arg1.disconnect();
130
129
  keepAliveConnections.remove(arg1);
131
130
  enabledKeepAliveConnections.remove(arg1);
131
+ arg1.disconnect();
132
132
  }
133
133
  }
134
134
  /**
@@ -72,6 +72,9 @@ export default class HTTPModule extends Module {
72
72
  getConfig() {
73
73
  return this.config;
74
74
  }
75
+ get serviceURL() {
76
+ return this.getURL();
77
+ }
75
78
  /**
76
79
  * start http service
77
80
  */
package/modules/index.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import HTTP from './http/index.js';
2
- import SocketIO from './socketio/index.js';
3
2
  /**
4
3
  * FIFO queue for modules starting
5
4
  */
@@ -84,7 +83,5 @@ export async function stop() {
84
83
  */
85
84
  export const builtins = {
86
85
  http: new HTTP,
87
- socketio: new SocketIO,
88
86
  };
89
87
  add(builtins.http);
90
- add(builtins.socketio);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oox",
3
- "version": "0.3.6",
3
+ "version": "0.3.7",
4
4
  "description": "OOX Service Engine",
5
5
  "keywords": [
6
6
  "http",
@@ -40,9 +40,7 @@
40
40
  "homepage": "https://gitee.com/lipingruan/oox",
41
41
  "license": "MIT",
42
42
  "dependencies": {
43
- "chalk": "^5.6.2",
44
- "socket.io": "^4.8.3",
45
- "socket.io-client": "^4.8.3"
43
+ "chalk": "^5.6.2"
46
44
  },
47
45
  "engines": {
48
46
  "node": ">=18.0.0"
@@ -47,16 +47,16 @@ export class SampleKeepAliveConnectionAdapter {
47
47
  connection.enabled = false;
48
48
  });
49
49
  socket.on(this.OOXEvent.DISCONNECT, () => {
50
- removeKeepAliveConnection(connection);
51
50
  socket.removeAllListeners();
51
+ removeKeepAliveConnection(connection);
52
52
  connection.emit('disconnect');
53
53
  });
54
54
  socket.on(this.OOXEvent.CONNECT, () => {
55
55
  connection.emit('connect');
56
56
  });
57
57
  socket.on(this.OOXEvent.ERROR, (error) => {
58
- removeKeepAliveConnection(connection);
59
58
  socket.removeAllListeners();
59
+ removeKeepAliveConnection(connection);
60
60
  connection.emit('error', new KeepAliveConnectionError(error.message, connection));
61
61
  });
62
62
  }
@@ -64,17 +64,24 @@ export class SampleKeepAliveConnectionAdapter {
64
64
  const connection = this.newConnection(identify);
65
65
  addKeepAliveConnection(connection);
66
66
  this.bindConnectionEvents(connection);
67
- this.bindCall(connection);
68
- await new Promise((resolve, reject) => {
69
- connection.once('enabled', resolve);
70
- connection.once('error', reject);
71
- connection.once('disconnect', () => {
72
- reject(new Error('disconnect'));
67
+ try {
68
+ await new Promise((resolve, reject) => {
69
+ connection.once('enabled', resolve);
70
+ connection.once('error', reject);
71
+ connection.once('disconnect', () => {
72
+ reject(new Error('disconnect'));
73
+ });
74
+ if (connection.nativeConnection.connect) {
75
+ connection.nativeConnection.connect();
76
+ }
73
77
  });
74
- if (connection.nativeConnection.connect) {
75
- connection.nativeConnection.connect();
76
- }
77
- });
78
+ }
79
+ catch (error) {
80
+ connection.removeAllListeners();
81
+ removeKeepAliveConnection(connection);
82
+ throw error;
83
+ }
84
+ this.bindCall(connection);
78
85
  return connection;
79
86
  }
80
87
  async close(connection) {
@@ -126,6 +133,8 @@ export class SampleKeepAliveConnectionAdapter {
126
133
  * @param connection
127
134
  */
128
135
  bindCall(connection) {
136
+ if (!connection.enabled)
137
+ throw new Error('Connection not enabled');
129
138
  const { id, name, ip } = connection.data;
130
139
  connection.nativeConnection.on(this.OOXEvent.CALL, async (action, params, context, callback) => {
131
140
  const validContext = genContext({
@@ -27,6 +27,7 @@ export default class HTTPModule extends Module {
27
27
  use(middleware: Middleware): this;
28
28
  setConfig(config: HTTPConfig): void;
29
29
  getConfig(): HTTPConfig;
30
+ get serviceURL(): URL;
30
31
  /**
31
32
  * start http service
32
33
  */
@@ -1,6 +1,5 @@
1
1
  import { Module } from './module.js';
2
2
  import HTTP from './http/index.js';
3
- import SocketIO from './socketio/index.js';
4
3
  /**
5
4
  * FIFO queue for modules starting
6
5
  */
@@ -35,5 +34,4 @@ export declare function stop(): Promise<void>;
35
34
  */
36
35
  export declare const builtins: {
37
36
  http: HTTP;
38
- socketio: SocketIO;
39
37
  };
@@ -4,6 +4,7 @@ export interface ModuleConfig {
4
4
  export declare abstract class Module {
5
5
  abstract config: ModuleConfig;
6
6
  abstract name: string;
7
+ abstract serviceURL?: URL;
7
8
  abstract setConfig(config: any): void;
8
9
  abstract getConfig(): ModuleConfig;
9
10
  abstract serve(): Promise<void>;
@@ -1,48 +0,0 @@
1
- import * as SocketIOClient from 'socket.io-client';
2
- import * as oox from '../../index.js';
3
- import { OOXEvent, genWebSocketURL } from './utils.js';
4
- import { randomUUID } from 'node:crypto';
5
- import { SampleKeepAliveConnectionAdapter } from '../../samples/index.js';
6
- export default class SocketIOAdapter extends SampleKeepAliveConnectionAdapter {
7
- name = 'socketio';
8
- OOXEvent = OOXEvent;
9
- newConnection(identify) {
10
- const { id, name } = oox.config;
11
- const headers = {
12
- 'x-caller': name,
13
- 'x-caller-id': id,
14
- };
15
- let mURL;
16
- const connectionData = {
17
- name: 'anonymous',
18
- id: randomUUID(),
19
- adapter: this.name,
20
- ip: '',
21
- token: ''
22
- };
23
- if ('string' === typeof identify) {
24
- mURL = genWebSocketURL(identify);
25
- }
26
- else if (identify instanceof URL) {
27
- mURL = identify;
28
- }
29
- else if (identify.url) {
30
- // KeepAliveConnectionData
31
- Object.assign(connectionData, identify);
32
- mURL = new URL(identify.url);
33
- if (identify.token) {
34
- headers['x-token'] = identify.token;
35
- }
36
- }
37
- else {
38
- throw new Error('identify must be string, URL, or KeepAliveConnectionData');
39
- }
40
- const socket = SocketIOClient.io(mURL.origin, {
41
- extraHeaders: headers,
42
- path: mURL.pathname,
43
- autoConnect: false,
44
- });
45
- const connection = new oox.KeepAliveConnection(this, socket, connectionData);
46
- return connection;
47
- }
48
- }
@@ -1,23 +0,0 @@
1
- import * as PATH from 'node:path';
2
- import * as oox from '../../index.js';
3
- import SocketINServer from './server.js';
4
- export default class SocketIOModule extends SocketINServer {
5
- async serve() {
6
- await this.stop();
7
- const _http = oox.modules.builtins.http;
8
- const httpConfig = _http.getConfig(), config = this.getConfig();
9
- let isShareServer = false;
10
- // 都没设置端口
11
- isShareServer = !httpConfig.port && !config.port;
12
- // 都设置相同端口
13
- isShareServer ||= httpConfig.port === config.port;
14
- // http 模块未被禁用
15
- isShareServer &&= httpConfig.enabled;
16
- if (isShareServer) {
17
- config.path = PATH.posix.join(httpConfig.path, config.path);
18
- this.server = _http.server;
19
- this.config.ssl = _http.config.ssl;
20
- }
21
- await super.serve();
22
- }
23
- }
@@ -1,203 +0,0 @@
1
- import * as http from 'node:http';
2
- import * as https from 'node:https';
3
- import { Server } from 'socket.io';
4
- import * as oox from '../../index.js';
5
- import { Module } from '../module.js';
6
- import SocketIOAdapter from './adapter.js';
7
- import { OOXEvent } from './utils.js';
8
- import { randomUUID } from 'node:crypto';
9
- export class SocketIOConfig {
10
- enabled = true;
11
- // listen port
12
- port = 0;
13
- // service path
14
- path = '/socket.io';
15
- // browser cross origin
16
- origin = '';
17
- // https options
18
- ssl = {
19
- // enable https
20
- enabled: false,
21
- // ssl certificate path
22
- cert: '',
23
- // ssl private key path
24
- key: '',
25
- // ssl ca path
26
- ca: ''
27
- };
28
- }
29
- export default class SocketIOServer extends Module {
30
- name = 'socketio';
31
- config = new SocketIOConfig;
32
- /**
33
- * means this.server created by myself<SocketIOServer>
34
- */
35
- #isSelfServer = false;
36
- server = null;
37
- socketServer = null;
38
- adapter = new SocketIOAdapter();
39
- constructor() {
40
- super();
41
- oox.keepAliveConnectionAdapters.set(this.name, this.adapter);
42
- }
43
- getURL() {
44
- const { host } = oox.config;
45
- const { port, path } = this.config;
46
- const protocol = this.config.ssl.enabled ? 'wss:' : 'ws:';
47
- return new URL(`${protocol}//${host}:${port}${path}`);
48
- }
49
- setConfig(config) {
50
- Object.assign(this.config, config);
51
- if (!config.hasOwnProperty('port')) {
52
- this.config.port = oox.config.port;
53
- }
54
- if (!config.hasOwnProperty('origin')) {
55
- this.config.origin = oox.config.origin;
56
- }
57
- }
58
- getConfig() {
59
- return this.config;
60
- }
61
- async serve() {
62
- await this.stop();
63
- const { port, ssl } = this.config;
64
- const isSelfServer = this.#isSelfServer = this.server ? true : false;
65
- let server = null;
66
- if (isSelfServer) {
67
- if (!this.server)
68
- throw new Error('HTTP Server is not created');
69
- server = this.server;
70
- }
71
- else {
72
- if (ssl.enabled) {
73
- const fs = await import('node:fs');
74
- const options = {
75
- key: ssl.key ? fs.readFileSync(ssl.key) : undefined,
76
- cert: ssl.cert ? fs.readFileSync(ssl.cert) : undefined,
77
- ca: ssl.ca ? fs.readFileSync(ssl.ca) : undefined
78
- };
79
- if (!options.key || !options.cert) {
80
- throw new Error('HTTPS enabled but missing key or cert');
81
- }
82
- server = https.createServer(options, (_request, response) => response.end('No HTTP Gateway'));
83
- }
84
- else {
85
- server = http.createServer((_request, response) => response.end('No HTTP Gateway'));
86
- }
87
- }
88
- this.server = server;
89
- if (!server.listening)
90
- server.listen(port);
91
- const address = server.address();
92
- if (!address || 'object' !== typeof address)
93
- throw new Error('Cannot read socket.io server port');
94
- this.config.port = address.port;
95
- this.createSocketIOServer();
96
- }
97
- async stop() {
98
- const { server, socketServer } = this;
99
- if (socketServer)
100
- await new Promise((resolve, reject) => socketServer.close(error => error ? reject(error) : resolve()));
101
- if (this.#isSelfServer)
102
- await new Promise((resolve, reject) => server?.close(error => error ? reject(error) : resolve()));
103
- }
104
- genSocketIOServerOptions() {
105
- const options = {
106
- /**
107
- * name of the path to capture
108
- * @default "/socket.io"
109
- */
110
- path: this.config.path,
111
- /**
112
- * how many ms before a client without namespace is closed
113
- * @default 45000
114
- */
115
- connectTimeout: 5000,
116
- /**
117
- * how many ms without a pong packet to consider the connection closed
118
- * @default 5000
119
- */
120
- pingTimeout: 2000,
121
- /**
122
- * how many ms before sending a new ping packet
123
- * @default 25000
124
- */
125
- pingInterval: 10000,
126
- /**
127
- * how many bytes or characters a message can be, before closing the session (to avoid DoS).
128
- * @default 1e5 (100 KB)
129
- */
130
- maxHttpBufferSize: 1e5
131
- };
132
- const { origin } = this.config;
133
- if (origin)
134
- options.cors = { origin };
135
- return options;
136
- }
137
- createSocketIOServer() {
138
- const { server } = this;
139
- if (!server)
140
- throw new Error('HTTP Server is not created');
141
- const socketServer = this.socketServer = new Server(server, {
142
- ...this.genSocketIOServerOptions(),
143
- });
144
- socketServer.on('connection', async (socket) => {
145
- try {
146
- this.serverOnSocketConnection(socket);
147
- }
148
- catch (error) {
149
- console.error(error);
150
- socket.send(error.message).disconnect(true);
151
- }
152
- });
153
- }
154
- /**
155
- * 服务端Socket连接事件
156
- */
157
- serverOnSocketConnection(socket) {
158
- const headers = socket.handshake.headers;
159
- const callerId = String(headers['x-caller-id'] || randomUUID());
160
- // client ip or caller service ip
161
- const ip = String(headers['x-real-ip'] || socket.handshake.address);
162
- // service name
163
- const caller = String(headers['x-caller'] || 'anonymous');
164
- const token = String(headers['x-token'] || '');
165
- // check token
166
- const { allow, reason } = oox.checkAllow(ip, caller, token);
167
- if (!allow) {
168
- socket.send(reason).disconnect(true);
169
- return;
170
- }
171
- const connection = new oox.KeepAliveConnection(this.adapter, socket, {
172
- ip,
173
- name: caller,
174
- id: callerId,
175
- token,
176
- });
177
- oox.addKeepAliveConnection(connection);
178
- this.bindServerConnectionEvents(connection);
179
- this.adapter.bindCall(connection);
180
- socket.emit(OOXEvent.READY, {
181
- id: oox.config.id,
182
- name: oox.config.name
183
- });
184
- connection.enabled = true;
185
- }
186
- /**
187
- * 绑定服务器连接事件
188
- * @param connection
189
- */
190
- bindServerConnectionEvents(connection) {
191
- const socket = connection.nativeConnection;
192
- socket.on(OOXEvent.REGISTRY_SYNC_CONNECTIONS, async (fn) => {
193
- if ('function' !== typeof fn)
194
- return;
195
- oox.registry.onSyncConnections(connection, {}, fn);
196
- });
197
- socket.on('disconnecting', (reason) => {
198
- oox.removeKeepAliveConnection(connection);
199
- socket.removeAllListeners();
200
- connection.emit('disconnect');
201
- });
202
- }
203
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,44 +0,0 @@
1
- export const OOXEvent = {
2
- CONNECT: 'connect',
3
- DISCONNECT: 'disconnect',
4
- ERROR: 'error',
5
- CALL: 'call',
6
- READY: 'oox:ready',
7
- ENABLED: 'oox:enabled',
8
- DISABLED: 'oox:disabled',
9
- REGISTRY_SYNC_CONNECTIONS: 'oox:registry:sync_connections',
10
- REGISTRY_SUBSCRIBE: 'oox:registry:subscribe',
11
- REGISTRY_NOTIFY: 'oox:registry:notify',
12
- };
13
- export function isWebSocketURL(url) {
14
- if ('string' === typeof url) {
15
- return /^wss?:\/\/.+$/.test(url);
16
- }
17
- else {
18
- return url.protocol === 'ws:' || url.protocol === 'wss:';
19
- }
20
- }
21
- export function genWebSocketURL(url) {
22
- // :6000
23
- if (url.startsWith(':'))
24
- url = 'ws://localhost' + url;
25
- // 127.0.0.1:6000
26
- if (!/^\w+?:\/.+$/.test(url))
27
- url = 'ws://' + url;
28
- const urlObject = new URL(url);
29
- // :8000 => :8000/socket.io
30
- const notSetPath = !urlObject.pathname || (urlObject.pathname === '/'
31
- && !url.endsWith('/')
32
- && !urlObject.search
33
- && !urlObject.hash);
34
- if (notSetPath) {
35
- urlObject.pathname = '/socket.io';
36
- }
37
- if (urlObject.protocol !== 'wss:') {
38
- if (urlObject.port === '443')
39
- urlObject.protocol = 'wss:';
40
- else
41
- urlObject.protocol = 'ws:';
42
- }
43
- return urlObject;
44
- }
@@ -1,19 +0,0 @@
1
- import * as oox from '../../index.js';
2
- import { Socket } from './socket.js';
3
- import { SampleKeepAliveConnectionAdapter } from '../../samples/index.js';
4
- export default class SocketIOAdapter extends SampleKeepAliveConnectionAdapter<Socket> {
5
- name: string;
6
- OOXEvent: {
7
- CONNECT: string;
8
- DISCONNECT: string;
9
- ERROR: string;
10
- CALL: string;
11
- READY: string;
12
- ENABLED: string;
13
- DISABLED: string;
14
- REGISTRY_SYNC_CONNECTIONS: string;
15
- REGISTRY_SUBSCRIBE: string;
16
- REGISTRY_NOTIFY: string;
17
- };
18
- newConnection(identify: string | URL | oox.KeepAliveConnectionData): oox.KeepAliveConnection<Socket>;
19
- }
@@ -1,4 +0,0 @@
1
- import SocketINServer from './server.js';
2
- export default class SocketIOModule extends SocketINServer {
3
- serve(): Promise<void>;
4
- }
@@ -1,44 +0,0 @@
1
- import * as http from 'node:http';
2
- import * as https from 'node:https';
3
- import { Server, ServerOptions } from 'socket.io';
4
- import * as oox from '../../index.js';
5
- import { Module, ModuleConfig } from '../module.js';
6
- import { Socket } from './socket.js';
7
- import SocketIOAdapter from './adapter.js';
8
- export declare class SocketIOConfig implements ModuleConfig {
9
- enabled: boolean;
10
- port: number;
11
- path: string;
12
- origin: string | string[];
13
- ssl: {
14
- enabled: boolean;
15
- cert: string;
16
- key: string;
17
- ca: string;
18
- };
19
- }
20
- export default class SocketIOServer extends Module {
21
- #private;
22
- name: string;
23
- config: SocketIOConfig;
24
- server: http.Server | https.Server | null;
25
- socketServer: Server | null;
26
- adapter: SocketIOAdapter;
27
- constructor();
28
- getURL(): URL;
29
- setConfig(config: SocketIOConfig): void;
30
- getConfig(): SocketIOConfig;
31
- serve(): Promise<void>;
32
- stop(): Promise<void>;
33
- genSocketIOServerOptions(): Partial<ServerOptions>;
34
- createSocketIOServer(): void;
35
- /**
36
- * 服务端Socket连接事件
37
- */
38
- serverOnSocketConnection(socket: Socket<'server'>): void;
39
- /**
40
- * 绑定服务器连接事件
41
- * @param connection
42
- */
43
- bindServerConnectionEvents(connection: oox.KeepAliveConnection<Socket<'server'>>): void;
44
- }
@@ -1,8 +0,0 @@
1
- import { Socket as ServerSocket } from 'socket.io';
2
- import { Socket as ClientSocket } from 'socket.io-client';
3
- export type SocketMap = {
4
- [key: string]: ServerSocket | ClientSocket;
5
- server: ServerSocket;
6
- client: ClientSocket;
7
- };
8
- export type Socket<T extends keyof SocketMap = keyof SocketMap> = SocketMap[T];
@@ -1,14 +0,0 @@
1
- export declare const OOXEvent: {
2
- CONNECT: string;
3
- DISCONNECT: string;
4
- ERROR: string;
5
- CALL: string;
6
- READY: string;
7
- ENABLED: string;
8
- DISABLED: string;
9
- REGISTRY_SYNC_CONNECTIONS: string;
10
- REGISTRY_SUBSCRIBE: string;
11
- REGISTRY_NOTIFY: string;
12
- };
13
- export declare function isWebSocketURL(url: string | URL): boolean;
14
- export declare function genWebSocketURL(url: string): URL;