oox 0.3.6 → 0.3.8

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
@@ -56,14 +56,17 @@ export async function startup() {
56
56
  await loadEntry(config.name, config.entryInfo.path);
57
57
  // 服务启动
58
58
  await oox.serve();
59
+ // 服务启动完成
59
60
  oox.emit('app:served');
60
- const { http, socketio } = 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
  /**
package/modules/index.js CHANGED
@@ -1,5 +1,4 @@
1
- import HTTP from './http/index.js';
2
- import SocketIO from './socketio/index.js';
1
+ import HTTP from '@oox/http';
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.8",
4
4
  "description": "OOX Service Engine",
5
5
  "keywords": [
6
6
  "http",
@@ -40,9 +40,8 @@
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
+ "@oox/http": "^1.0.0",
44
+ "chalk": "^5.6.2"
46
45
  },
47
46
  "engines": {
48
47
  "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({
@@ -1,6 +1,5 @@
1
1
  import { Module } from './module.js';
2
- import HTTP from './http/index.js';
3
- import SocketIO from './socketio/index.js';
2
+ import HTTP from '@oox/http';
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,275 +0,0 @@
1
- import * as http from 'node:http';
2
- import * as https from 'node:https';
3
- import { parseHTTPBody } from './utils.js';
4
- import Router from './router.js';
5
- import * as oox from '../../index.js';
6
- import { Module } from '../module.js';
7
- export class HTTPConfig {
8
- enabled = true;
9
- // listen port
10
- port = 0;
11
- // service path
12
- path = '/';
13
- // browser cross origin
14
- origin = '';
15
- // https options
16
- ssl = {
17
- // enable https
18
- enabled: false,
19
- // ssl certificate path
20
- cert: '',
21
- // ssl private key path
22
- key: '',
23
- // ssl ca path
24
- ca: ''
25
- };
26
- }
27
- export default class HTTPModule extends Module {
28
- name = 'http';
29
- config = new HTTPConfig;
30
- server = null;
31
- router = new Router();
32
- getURL() {
33
- const { host } = oox.config;
34
- const { port, path } = this.config;
35
- const protocol = this.config.ssl.enabled ? `https:` : `http:`;
36
- return new URL(`${protocol}//${host}:${port}${path}`);
37
- }
38
- // 注册GET路由
39
- get(path, ...args) {
40
- this.router.get(path, ...args);
41
- return this;
42
- }
43
- // 注册POST路由
44
- post(path, ...args) {
45
- this.router.post(path, ...args);
46
- return this;
47
- }
48
- // 注册PUT路由
49
- put(path, ...args) {
50
- this.router.put(path, ...args);
51
- return this;
52
- }
53
- // 注册DELETE路由
54
- delete(path, ...args) {
55
- this.router.delete(path, ...args);
56
- return this;
57
- }
58
- // 注册全局中间件
59
- use(middleware) {
60
- this.router.use(middleware);
61
- return this;
62
- }
63
- setConfig(config) {
64
- Object.assign(this.config, config);
65
- if (!config.hasOwnProperty('port')) {
66
- this.config.port = oox.config.port;
67
- }
68
- if (!config.hasOwnProperty('origin')) {
69
- this.config.origin = oox.config.origin;
70
- }
71
- }
72
- getConfig() {
73
- return this.config;
74
- }
75
- /**
76
- * start http service
77
- */
78
- async serve() {
79
- await this.stop();
80
- const { port, ssl } = this.config;
81
- if (ssl.enabled) {
82
- const fs = await import('node:fs');
83
- const options = {
84
- key: ssl.key ? fs.readFileSync(ssl.key) : undefined,
85
- cert: ssl.cert ? fs.readFileSync(ssl.cert) : undefined,
86
- ca: ssl.ca ? fs.readFileSync(ssl.ca) : undefined
87
- };
88
- if (!options.key || !options.cert) {
89
- throw new Error('HTTPS enabled but missing key or cert');
90
- }
91
- this.server = https.createServer(options, this.requestHandler.bind(this));
92
- }
93
- else {
94
- this.server = http.createServer(this.requestHandler.bind(this));
95
- }
96
- this.server.listen(port);
97
- const address = this.server.address();
98
- if (!address || 'object' !== typeof address)
99
- throw new Error('Cannot read http server port');
100
- this.config.port = address.port;
101
- }
102
- /**
103
- * stop http service
104
- */
105
- async stop() {
106
- const { server } = this;
107
- if (!server || !server.listening)
108
- return Promise.resolve();
109
- return new Promise((resolve, reject) => {
110
- server.close(function (error) {
111
- if (error)
112
- reject(error);
113
- else
114
- resolve();
115
- });
116
- });
117
- }
118
- /**
119
- * browser cross origin
120
- */
121
- cors(request, response) {
122
- // origin checking
123
- const origin = this.config.origin;
124
- const requestOrigin = request.headers.origin;
125
- if (origin && requestOrigin) {
126
- let allow = false;
127
- if ('string' === typeof origin) {
128
- allow = origin === '*' || new RegExp(origin).test(requestOrigin);
129
- }
130
- else if (Array.isArray(origin)) {
131
- allow = origin.some(item => item === '*' || new RegExp(item).test(requestOrigin));
132
- }
133
- if (allow) {
134
- response.setHeader('Access-Control-Allow-Origin', requestOrigin);
135
- response.setHeader('Vary', 'Origin');
136
- }
137
- else {
138
- response.statusCode = 403;
139
- response.end();
140
- return false;
141
- }
142
- response.setHeader('Access-Control-Max-Age', 3600);
143
- response.setHeader('Access-Control-Allow-Headers', 'x-caller,x-token,content-type');
144
- response.setHeader('Access-Control-Allow-Methods', '*');
145
- }
146
- if (request.method === 'OPTIONS') {
147
- response.statusCode = 204;
148
- response.end();
149
- return false;
150
- }
151
- return true;
152
- }
153
- async requestHandler(request, response) {
154
- const url = new URL(request.url || '', `http://${request.headers.host || 'localhost'}`);
155
- const method = request.method || 'GET';
156
- // 尝试匹配路由
157
- const matched = this.router.match(method, url.pathname);
158
- if (matched) {
159
- const req = this.router.createRequestObject(request, url);
160
- const res = this.router.createResponseObject(response);
161
- // 解析请求体
162
- if (request.method !== 'GET' && request.method !== 'HEAD') {
163
- try {
164
- req.body = await parseHTTPBody(request);
165
- }
166
- catch (error) {
167
- return this.respond(request, response, {
168
- success: false,
169
- error: {
170
- message: error.message,
171
- stack: error.stack
172
- }
173
- });
174
- }
175
- }
176
- await this.router.handleRoute(matched.route, matched.params, req, res);
177
- return;
178
- }
179
- // 内置cors仅处理RPC请求
180
- if (!this.cors(request, response))
181
- return;
182
- // 回退到RPC调用
183
- if (url.pathname === this.config.path) {
184
- await this.call(request, response);
185
- }
186
- else {
187
- const error = new Error('Invalid URL');
188
- return this.respond(request, response, {
189
- success: false,
190
- error: {
191
- message: error.message,
192
- stack: error.stack
193
- }
194
- });
195
- }
196
- }
197
- /**
198
- * 从请求里获取调用的接口和参数
199
- */
200
- async getCallArgsFromRequest(request) {
201
- const args = await parseHTTPBody(request);
202
- if (!args || 'object' !== typeof args || !args.action)
203
- throw new Error('Content Invalid');
204
- else
205
- return args;
206
- }
207
- /**
208
- * HTTP-RPC服务器请求监听方法
209
- */
210
- async call(request, response) {
211
- // global unique id
212
- const traceId = String(request.headers['x-trace-id'] || '');
213
- // service name, required
214
- const caller = String(request.headers['x-caller'] || 'anonymous');
215
- // client ip or caller service ip
216
- const ip = String(request.headers['x-real-ip'] || request.socket.remoteAddress || '');
217
- // startup client ip
218
- const sourceIP = String(request.headers['x-source-ip'] || request.socket.remoteAddress || '');
219
- // check token
220
- const token = String(request.headers['x-token'] || '');
221
- const { allow, reason } = oox.checkAllow(ip, caller, token);
222
- if (!allow)
223
- return this.respond(request, response, {
224
- success: false,
225
- error: {
226
- message: reason
227
- }
228
- });
229
- let callArgs = Object.create(null);
230
- try {
231
- callArgs = await this.getCallArgsFromRequest(request);
232
- }
233
- catch (error) {
234
- return this.respond(request, response, {
235
- success: false,
236
- error: {
237
- message: error.message,
238
- stack: error.stack
239
- }
240
- });
241
- }
242
- const { action, params = [] } = callArgs;
243
- const context = oox.genContext({ traceId, caller, sourceIP, ip, callerId: '' });
244
- const format = await oox.call(action, params, context);
245
- this.respond(request, response, format);
246
- }
247
- /**
248
- * HTTP Response Catch
249
- */
250
- respond(_request, response, returns) {
251
- let returnsString = '';
252
- if (!oox.config.errorStack && returns.error) {
253
- // 不返回错误调用栈信息
254
- delete returns.error.stack;
255
- }
256
- try {
257
- returnsString = JSON.stringify(returns);
258
- }
259
- catch (error) {
260
- delete returns.body;
261
- returns.success = false;
262
- returns.error = {
263
- message: error.message
264
- };
265
- if (oox.config.errorStack) {
266
- // 返回错误调用栈信息
267
- returns.error.stack = error.stack;
268
- }
269
- returnsString = JSON.stringify(returns);
270
- }
271
- response.setHeader('Content-Type', 'application/json');
272
- response.setHeader('Content-Length', Buffer.byteLength(returnsString));
273
- response.end(returnsString);
274
- }
275
- }
@@ -1,210 +0,0 @@
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
- // 编译路径为正则表达式,支持路径参数
88
- const { regex, paramNames } = this.compilePath(path);
89
- let routes = [];
90
- if (this.routes.has(method)) {
91
- routes = this.routes.get(method) || [];
92
- }
93
- else {
94
- routes = [];
95
- this.routes.set(method, routes);
96
- }
97
- routes.push({
98
- path,
99
- method,
100
- handler,
101
- middleware,
102
- regex,
103
- paramNames
104
- });
105
- }
106
- // 编译路径为正则表达式
107
- compilePath(path) {
108
- const paramNames = [];
109
- const regexPattern = path
110
- .replace(/:([^/]+)/g, (_, paramName) => {
111
- paramNames.push(paramName);
112
- return '([^/]+)';
113
- })
114
- .replace(/\//g, '\\/')
115
- .replace(/\*/g, '.*');
116
- return {
117
- regex: new RegExp(`^${regexPattern}$`),
118
- paramNames
119
- };
120
- }
121
- // 匹配路由
122
- match(method, path) {
123
- const routes = this.routes.get(method) || [];
124
- for (const route of routes) {
125
- const match = path.match(route.regex);
126
- if (match) {
127
- const params = {};
128
- route.paramNames.forEach((paramName, index) => {
129
- params[paramName] = match[index + 1];
130
- });
131
- return { route, params };
132
- }
133
- }
134
- return null;
135
- }
136
- // 创建请求对象
137
- createRequestObject(originalRequest, url) {
138
- return {
139
- originalRequest,
140
- url,
141
- method: originalRequest.method || 'GET',
142
- path: url.pathname,
143
- query: Object.fromEntries(url.searchParams),
144
- params: {},
145
- headers: originalRequest.headers,
146
- body: null
147
- };
148
- }
149
- // 创建响应对象
150
- createResponseObject(originalResponse) {
151
- let statusCode = 200;
152
- return {
153
- originalResponse,
154
- status(code) {
155
- statusCode = code;
156
- return this;
157
- },
158
- json(data) {
159
- const jsonString = JSON.stringify(data);
160
- this.originalResponse.statusCode = statusCode;
161
- this.originalResponse.setHeader('Content-Type', 'application/json');
162
- this.originalResponse.setHeader('Content-Length', Buffer.byteLength(jsonString));
163
- this.originalResponse.end(jsonString);
164
- },
165
- send(data) {
166
- const dataString = typeof data === 'string' ? data : JSON.stringify(data);
167
- this.originalResponse.statusCode = statusCode;
168
- this.originalResponse.setHeader('Content-Type', 'text/plain');
169
- this.originalResponse.setHeader('Content-Length', Buffer.byteLength(dataString));
170
- this.originalResponse.end(dataString);
171
- },
172
- end(data) {
173
- this.originalResponse.statusCode = statusCode;
174
- this.originalResponse.end(data);
175
- }
176
- };
177
- }
178
- // 执行中间件
179
- async executeMiddleware(middleware, req, res) {
180
- for (const fn of middleware) {
181
- let nextCalled = false;
182
- const next = () => { nextCalled = true; };
183
- const result = fn(req, res, next);
184
- if (result instanceof Promise) {
185
- await result;
186
- }
187
- if (!nextCalled) {
188
- return false; // 中间件已结束响应
189
- }
190
- }
191
- return true; // 所有中间件都已执行
192
- }
193
- // 处理路由请求
194
- async handleRoute(route, params, req, res) {
195
- req.params = params;
196
- // 执行全局中间件
197
- const globalMiddlewareContinue = await this.executeMiddleware(this.globalMiddleware, req, res);
198
- if (!globalMiddlewareContinue)
199
- return;
200
- // 执行路由中间件
201
- const routeMiddlewareContinue = await this.executeMiddleware(route.middleware, req, res);
202
- if (!routeMiddlewareContinue)
203
- return;
204
- // 执行路由处理函数
205
- const result = route.handler(req, res);
206
- if (result instanceof Promise) {
207
- await result;
208
- }
209
- }
210
- }
@@ -1,75 +0,0 @@
1
- import * as http from 'node:http';
2
- import * as https from 'node:https';
3
- /**
4
- * Stream => Buffer
5
- */
6
- export function stream2buffer(stream, totalLength = 0) {
7
- return new Promise(function (resolve, reject) {
8
- let buffers = [];
9
- stream.on('error', reject);
10
- if (totalLength) {
11
- stream.on('data', function (data) { buffers.push(data); });
12
- }
13
- else {
14
- stream.on('data', function (data) {
15
- buffers.push(data);
16
- totalLength += data.length;
17
- });
18
- }
19
- stream.on('end', function () { resolve(Buffer.concat(buffers, totalLength)); });
20
- });
21
- }
22
- /**
23
- * Request => JSONObject
24
- */
25
- export async function parseHTTPBody(request) {
26
- if (request.method === 'GET')
27
- return null;
28
- let contentType = request.headers['content-type'];
29
- // application/json; charset=utf-8
30
- if (contentType)
31
- contentType = contentType.split(';')[0].trim();
32
- const contentLength = request.headers['content-length'];
33
- if (!contentLength || contentLength === '0')
34
- return null;
35
- const contentSize = +contentLength;
36
- const buffer = await stream2buffer(request, contentSize);
37
- if (buffer.length !== contentSize)
38
- throw new Error('Content-Length Incorrect');
39
- switch (contentType) {
40
- case 'application/json':
41
- return JSON.parse(buffer.toString());
42
- case 'text/plain':
43
- return buffer.toString();
44
- default:
45
- return buffer;
46
- }
47
- }
48
- /**
49
- * http request
50
- */
51
- export function httpRequest(url, options, body) {
52
- return new Promise(function (resolve, reject) {
53
- const urlObj = typeof url === 'string' ? new URL(url) : url;
54
- const protocol = urlObj.protocol;
55
- const client = protocol === 'https:' ? https : http;
56
- const request = client.request(url, options, async function (response) {
57
- try {
58
- const result = await parseHTTPBody(response);
59
- resolve(result);
60
- }
61
- catch (error) {
62
- const decoration = new Error(`${response.statusCode} - ${error.message}`);
63
- reject(decoration);
64
- }
65
- });
66
- request.on('error', reject);
67
- if (body) {
68
- request.method = 'POST';
69
- request.setHeader('Content-Type', 'application/json');
70
- request.setHeader('Content-Length', Buffer.byteLength(body));
71
- request.write(body);
72
- }
73
- request.end();
74
- });
75
- }
@@ -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,62 +0,0 @@
1
- import * as http from 'node:http';
2
- import * as https from 'node:https';
3
- import Router, { Middleware } from './router.js';
4
- import { Module, ModuleConfig } from '../module.js';
5
- export declare class HTTPConfig implements ModuleConfig {
6
- enabled: boolean;
7
- port: number;
8
- path: string;
9
- origin: string | string[];
10
- ssl: {
11
- enabled: boolean;
12
- cert: string;
13
- key: string;
14
- ca: string;
15
- };
16
- }
17
- export default class HTTPModule extends Module {
18
- name: string;
19
- config: HTTPConfig;
20
- server: http.Server | https.Server | null;
21
- router: Router;
22
- getURL(): URL;
23
- get(path: string, ...args: any[]): this;
24
- post(path: string, ...args: any[]): this;
25
- put(path: string, ...args: any[]): this;
26
- delete(path: string, ...args: any[]): this;
27
- use(middleware: Middleware): this;
28
- setConfig(config: HTTPConfig): void;
29
- getConfig(): HTTPConfig;
30
- /**
31
- * start http service
32
- */
33
- serve(): Promise<void>;
34
- /**
35
- * stop http service
36
- */
37
- stop(): Promise<void>;
38
- /**
39
- * browser cross origin
40
- */
41
- cors(request: http.IncomingMessage, response: http.ServerResponse): boolean;
42
- requestHandler(request: http.IncomingMessage, response: http.ServerResponse): Promise<void>;
43
- /**
44
- * 从请求里获取调用的接口和参数
45
- */
46
- getCallArgsFromRequest(request: http.IncomingMessage): Promise<any>;
47
- /**
48
- * HTTP-RPC服务器请求监听方法
49
- */
50
- call(request: http.IncomingMessage, response: http.ServerResponse): Promise<void>;
51
- /**
52
- * HTTP Response Catch
53
- */
54
- respond(_request: http.IncomingMessage, response: http.ServerResponse, returns: {
55
- body?: any;
56
- success: boolean;
57
- error?: {
58
- message: any;
59
- stack?: any;
60
- };
61
- }): void;
62
- }
@@ -1,49 +0,0 @@
1
- import * as http from 'node:http';
2
- export type RouteHandler = (req: Request, res: Response) => Promise<any> | any;
3
- export type Middleware = (req: Request, res: Response, next: () => void) => Promise<any> | any;
4
- export interface Route {
5
- path: string;
6
- method: string;
7
- handler: RouteHandler;
8
- middleware: Middleware[];
9
- regex: RegExp;
10
- paramNames: string[];
11
- }
12
- export interface Request {
13
- originalRequest: http.IncomingMessage;
14
- url: URL;
15
- method: string;
16
- path: string;
17
- query: Record<string, string>;
18
- params: Record<string, string>;
19
- headers: Record<string, string>;
20
- body: any;
21
- }
22
- export interface Response {
23
- originalResponse: http.ServerResponse;
24
- status(code: number): Response;
25
- json(data: any): void;
26
- send(data: any): void;
27
- end(data?: any): void;
28
- }
29
- export default class Router {
30
- private routes;
31
- private globalMiddleware;
32
- get(path: string, ...args: any[]): void;
33
- post(path: string, ...args: any[]): void;
34
- put(path: string, ...args: any[]): void;
35
- delete(path: string, ...args: any[]): void;
36
- private parseRouteArgs;
37
- use(middleware: Middleware): void;
38
- usePath(path: string, middleware: Middleware): void;
39
- private addRoute;
40
- private compilePath;
41
- match(method: string, path: string): {
42
- route: Route;
43
- params: Record<string, string>;
44
- } | null;
45
- createRequestObject(originalRequest: http.IncomingMessage, url: URL): Request;
46
- createResponseObject(originalResponse: http.ServerResponse): Response;
47
- private executeMiddleware;
48
- handleRoute(route: Route, params: Record<string, string>, req: Request, res: Response): Promise<void>;
49
- }
@@ -1,14 +0,0 @@
1
- import * as http from 'node:http';
2
- import { Readable } from 'node:stream';
3
- /**
4
- * Stream => Buffer
5
- */
6
- export declare function stream2buffer(stream: Readable, totalLength?: number): Promise<Buffer>;
7
- /**
8
- * Request => JSONObject
9
- */
10
- export declare function parseHTTPBody(request: http.IncomingMessage): Promise<any>;
11
- /**
12
- * http request
13
- */
14
- export declare function httpRequest(url: URL | string, options: http.RequestOptions, body: string): Promise<any>;
@@ -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;