mm_os 5.0.0 → 5.0.2

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/lib/os.js CHANGED
@@ -1,369 +1,572 @@
1
- const { Mod, Store } = require('mm_corejs');
2
- const { getLogger } = require('mm_logger');
3
- const Loader = require('./loader');
4
-
5
- /**
6
- * OS类
7
- */
8
- class OS extends Mod {
9
- static config = {
10
- name: 'os',
11
- in_adapters: ['web', 'mqtt', 'socket', 'websocket'],
12
- out_adapters: ['redis', 'mongodb', 'mysql', 'sqlite', 'jsondb', 'file'],
13
- tools: ['lang', 'tpl', 'ret'],
14
- admins: ['handle', 'event', 'api', 'param', 'service', 'template', 'pendant', 'timer', 'statics'],
15
- cache: {
16
- type: 'redis'
17
- },
18
- db: {
19
- type: 'mysql'
20
- },
21
- web: {
22
- port: 8080
23
- },
24
- mqtt: {
25
- port: 1883
26
- },
27
- socket: {
28
- port: 9000
29
- },
30
- websocket: {
31
- port: 9001
32
- },
33
- jsondb: {
34
- dir: './data'
35
- },
36
- mysql: {
37
- host: '127.0.0.1',
38
- port: 3306,
39
- user: 'root',
40
- password: 'Asd159357',
41
- database: 'mm'
42
- },
43
- redis: {
44
- host: '127.0.0.1',
45
- password: 'asd159357',
46
- port: 6379,
47
- db: 0
48
- },
49
- mongodb: {
50
- host: '127.0.0.1',
51
- port: 27017,
52
- user: 'root',
53
- password: 'asd123',
54
- database: 'mm'
55
- },
56
- sqlite: {
57
- dir: './db',
58
- database: 'mm',
59
- user: 'root',
60
- password: 'asd123'
61
- },
62
- ret: {
63
- type: 'json-rpc'
64
- },
65
- lang: {
66
- type: 'zh_cn'
67
- },
68
- tpl: {
69
- dir: './static/template',
70
- ext: '.html'
71
- }
72
- }
73
-
74
- /**
75
- * OS类构造函数
76
- * @param {object} config 配置对象
77
- */
78
- constructor(config) {
79
- super(config);
80
- /**
81
- * 管理列表
82
- * @type {Store}
83
- */
84
- this.admins = new Store();
85
- /**
86
- * 输入适配器列表
87
- * @type {Store}
88
- */
89
- this.in_adapters = new Store();
90
- /**
91
- * 输出适配器列表
92
- * @type {Store}
93
- */
94
- this.out_adapters = new Store();
95
- }
96
-
97
- /**
98
- * 生命周期初始化钩子
99
- * @returns {void} 无返回值
100
- */
101
- async onInit() {
102
- this.initLogger();
103
- // 初始化事件总线
104
- this.initEventBus();
105
- await this.initAdmins();
106
- await this.initAdapter();
107
- await this.initpStorage();
108
- await this.initLoader();
109
- }
110
- }
111
-
112
- /**
113
- * 初始化日志记录器
114
- */
115
- OS.prototype.initLogger = function () {
116
- this.logger = getLogger(this.config.log || { level: 'info' });
117
- };
118
-
119
- /**
120
- * 记录日志
121
- * @param {string} type 日志类型
122
- * @param {string} msg 日志消息
123
- * @param {...*} args 日志参数
124
- */
125
- OS.prototype.log = function (type, msg, ...args) {
126
- this.logger[type](msg, ...args);
127
- };
128
-
129
- /**
130
- * 注册管理
131
- * @param {string} name 管理名称
132
- * @param {object} admin 管理对象
133
- */
134
- OS.prototype.reg = function (name, admin) {
135
- this.admins.add({ id: name, name: name, admin });
136
- };
137
-
138
- /**
139
- * 加载模块
140
- * @param {string} mod_name 模块名称
141
- * @returns {object} 模块对象
142
- */
143
- OS.prototype.require = function (mod_name) {
144
- return require(mod_name);
145
- };
146
-
147
- /**
148
- * 初始化适配器
149
- * @returns {void} 无返回值
150
- */
151
- OS.prototype.initAdapter = async function () {
152
- // 入站适配器
153
- let adapters = this.config.in_adapters || [];
154
- for (let name of adapters) {
155
- try {
156
- let admin = this.require(`mm_${name}_server`).admin;
157
- admin.setServer(this);
158
- let manager = admin.get('os', this.config[name]);
159
- this._useMiddleware(name, manager);
160
- if (typeof manager.init === 'function') {
161
- await manager.init();
162
- }
163
- this.in_adapters.add({ id: name, name: name, admin: manager });
164
- } catch (error) {
165
- this.log('error', `初始化适配器 ${name} 失败: ${error}`);
166
- }
167
- }
168
-
169
- // 出站适配器
170
- let out_adapters = this.config.out_adapters || [];
171
- for (let name of out_adapters) {
172
- try {
173
- let admin = this.require(`mm_${name}`).admin;
174
- admin.setServer(this);
175
- let manager = admin.get('os', this.config[name]);
176
- if (typeof manager.init === 'function') {
177
- await manager.init();
178
- }
179
- this.out_adapters.add({ id: name, name: name, admin: manager });
180
- } catch (error) {
181
- this.log('error', `初始化适配器 ${name} 失败: ${error}`);
182
- }
183
- }
184
- };
185
-
186
- /**
187
- * 装配中间件:web 适配器挂载页面渲染中间件与静态资源插件,
188
- * 使 HTML 页面以正确内容类型输出,并让注册到 mm_statics 的静态文件可被直接访问
189
- * @param {string} name 适配器名称(web / socket / mqtt / websocket)
190
- * @param {object} manager 适配器管理器实例
191
- * @returns {void} 无返回值
192
- * @private
193
- */
194
- OS.prototype._useMiddleware = function (name, manager) {
195
- if (name !== 'web' || !manager || typeof manager.use !== 'function') return;
196
- try {
197
- const { Render } = this.require('mm_render');
198
- manager.use(new Render());
199
- const statics_mod = this.require('mm_statics');
200
- manager.use(new statics_mod.StaticsPlugin({ admin: statics_mod.admin }));
201
- } catch (error) {
202
- this.log('error', `装配渲染中间件失败: ${error.message}`);
203
- }
204
- };
205
-
206
- /**
207
- * 初始化工具
208
- * @returns {void} 无返回值
209
- */
210
- OS.prototype.initTools = async function () {
211
- let tools = this.config.tools || [];
212
- for (let name of tools) {
213
- try {
214
- let admin = this.require(`mm_${name}`).admin;
215
- admin.setServer(this);
216
- let manager = admin.get('os', this.config[name]);
217
- if (typeof manager.init === 'function') {
218
- await manager.init();
219
- }
220
- this.reg(name, manager);
221
- } catch (error) {
222
- this.log('error', `初始化工具 ${name} 失败: ${error}`);
223
- }
224
- }
225
- };
226
-
227
- /**
228
- * 初始化管理
229
- * @returns {void} 无返回值
230
- */
231
- OS.prototype.initAdmins = async function () {
232
- let admins = this.config.admins || [];
233
- for (let name of admins) {
234
- try {
235
- let admin = this.require(`mm_${name}`).admin;
236
- admin.setServer(this);
237
- let manager = admin.get('os', this.config[name]);
238
- if (typeof manager.init === 'function') {
239
- await manager.init();
240
- }
241
- this.reg(name, manager);
242
- } catch (error) {
243
- this.log('error', `初始化管理 ${name} 失败: ${error}`);
244
- }
245
- }
246
- };
247
-
248
- /**
249
- * 初始化存储
250
- * @returns {void} 无返回值
251
- */
252
- OS.prototype.initpStorage = async function () {
253
- // 初始化缓存存储
254
- let cacheAdmin = this.require('mm_cache').admin;
255
- this._setAdminServer(cacheAdmin);
256
- let cache = cacheAdmin.get('os', Object.assign({}, this.config.cache, { redis: this.config.redis, mongodb: this.config.mongodb, cachebase: this.config.cachebase }));
257
- if (typeof cache.init === 'function') {
258
- await cache.init();
259
- }
260
- this.cache = cache;
261
-
262
- // 初始化数据库
263
- let sqlAdmin = this.require('mm_sql').admin;
264
- this._setAdminServer(sqlAdmin);
265
- let sql = sqlAdmin.get('os', Object.assign({}, this.config.sql, { mysql: this.config.mysql, sqlite: this.config.sqlite, jsondb: this.config.jsondb }));
266
- if (typeof sql.init === 'function') {
267
- await sql.init();
268
- }
269
- this.sql = sql;
270
- };
271
-
272
- /**
273
- * 设置管理器服务器:已设置时跳过,避免同一 Admin 实例重复绑定
274
- * @param {object} admin 管理器工厂实例
275
- */
276
- OS.prototype._setAdminServer = function (admin) {
277
- if (!admin.getServer()) {
278
- admin.setServer(this);
279
- }
280
- };
281
-
282
- /**
283
- * 初始化应用加载器
284
- * @returns {void} 无返回值
285
- */
286
- OS.prototype.initLoader = async function () {
287
- let loader = new Loader(this.config.loader || {}, this);
288
- loader.setLogger(this.logger);
289
- await loader.init();
290
- this.loader = loader;
291
- };
292
-
293
- /**
294
- * 初始化事件总线
295
- * @returns {void} 无返回值
296
- */
297
- OS.prototype.initEventBus = function () {
298
- let admin = this.require('mm_eventer').admin;
299
- admin.setServer(this);
300
- this.eventer = admin.get('os');
301
- };
302
-
303
- /**
304
- * 启动入站适配器
305
- * @returns {void} 无返回值
306
- */
307
- OS.prototype._startInAdapters = async function () {
308
- let in_adapters = this.in_adapters.list();
309
- for (let item of in_adapters) {
310
- try {
311
- await item.admin.start();
312
- this._printAddress(item);
313
- } catch (error) {
314
- this.log('error', `启动适配器 ${item.name} 失败: ${error}`);
315
- }
316
- }
317
- };
318
-
319
- /**
320
- * 启动出站适配器
321
- * @returns {void} 无返回值
322
- */
323
- OS.prototype._startOutAdapters = async function () {
324
- let out_adapters = this.out_adapters.list();
325
- for (let item of out_adapters) {
326
- try {
327
- await item.admin.start();
328
- this._printAddress(item);
329
- } catch (error) {
330
- this.log('error', `启动适配器 ${item.name} 失败: ${error}`);
331
- }
332
- }
333
- };
334
-
335
- /**
336
- * 启动适配器
337
- * @returns {void} 无返回值
338
- */
339
- OS.prototype.start = async function () {
340
- // 启动入站适配器
341
- await this._startInAdapters();
342
- // 启动出站适配器
343
- await this._startOutAdapters();
344
-
345
- // 启动缓存存储
346
- await this.cache.start();
347
- // 启动数据库
348
- await this.sql.start();
349
-
350
- // 启动应用
351
- if (this.loader) {
352
- await this.loader.start();
353
- }
354
- };
355
-
356
- /**
357
- * 打印适配器监听地址
358
- * @param {object} item 适配器存储项,含 name 与 admin
359
- */
360
- OS.prototype._printAddress = function (item) {
361
- let { host, port } = item.admin.config || {};
362
- if (!host || host === '0.0.0.0' || host === '::') {
363
- host = 'localhost';
364
- }
365
- let protocol = { web: 'http', websocket: 'ws', socket: 'tcp', mqtt: 'mqtt' }[item.name] || item.name;
366
- this.log('info', `适配器 ${item.name} 已启动: ${protocol}://${host}:${port}`);
367
- };
368
-
1
+ const path = require('path');
2
+ const { Mod } = require('mm_mod');
3
+ const { containerAdmin } = require('mm_container');
4
+ const { getLogger } = require('mm_logger');
5
+ const { Loader } = require('mm_loader');
6
+ const { appAdmin } = require('mm_apps');
7
+ const { eventAdmin } = require('mm_event');
8
+ const { Response } = require('mm_response');
9
+
10
+ /**
11
+ * OS类
12
+ */
13
+ class OS extends Mod {
14
+ static config = {
15
+ name: 'os',
16
+ in_adapters: [{
17
+ name: 'web',
18
+ module: 'mm_web_server'
19
+ }, {
20
+ name: 'mqtt',
21
+ module: 'mm_mqtt_server'
22
+ }, {
23
+ name: 'socket',
24
+ module: 'mm_socket_server'
25
+ }, {
26
+ name: 'websocket',
27
+ module: 'mm_websocket_server'
28
+ }],
29
+ // 输出适配器
30
+ out_adapters: [{
31
+ name: 'redis',
32
+ module: 'mm_redis'
33
+ }, {
34
+ name: 'mongodb',
35
+ module: 'mm_mongodb'
36
+ }, {
37
+ name: 'mysql',
38
+ module: 'mm_mysql'
39
+ }, {
40
+ name: 'sqlite',
41
+ module: 'mm_sqlite'
42
+ }, {
43
+ name: 'jsondb',
44
+ module: 'mm_jsondb'
45
+ }, {
46
+ name: 'file',
47
+ module: 'mm_files'
48
+ }],
49
+ tools: [{
50
+ name: 'lang',
51
+ module: 'mm_lang'
52
+ }, {
53
+ name: 'tpl',
54
+ module: 'mm_tpl'
55
+ }, {
56
+ name: 'ret',
57
+ module: 'mm_ret'
58
+ }],
59
+ admins: [{
60
+ name: 'event',
61
+ module: 'mm_event'
62
+ }, {
63
+ name: 'api',
64
+ module: 'mm_api'
65
+ }, {
66
+ name: 'param',
67
+ module: 'mm_param'
68
+ }, {
69
+ name: 'dao',
70
+ module: 'mm_dao'
71
+ }, {
72
+ name: 'service',
73
+ module: 'mm_service'
74
+ }, {
75
+ name: 'template',
76
+ module: 'mm_template'
77
+ }, {
78
+ name: 'pendant',
79
+ module: 'mm_pendant'
80
+ }, {
81
+ name: 'timer',
82
+ module: 'mm_timer'
83
+ }, {
84
+ name: 'static',
85
+ module: 'mm_statics'
86
+ }],
87
+ cache: {
88
+ type: 'redis'
89
+ },
90
+ sql: {
91
+ type: 'mysql'
92
+ },
93
+ web: {
94
+ port: 8000
95
+ },
96
+ mqtt: {
97
+ port: 1883
98
+ },
99
+ socket: {
100
+ port: 9000
101
+ },
102
+ websocket: {
103
+ port: 9001
104
+ },
105
+ jsondb: {
106
+ dir: './data'
107
+ },
108
+ mysql: {
109
+ host: '127.0.0.1',
110
+ port: 3306,
111
+ user: 'root',
112
+ password: 'Asd159357',
113
+ database: 'mm'
114
+ },
115
+ redis: {
116
+ host: '127.0.0.1',
117
+ password: 'asd159357',
118
+ port: 6379,
119
+ db: 0
120
+ },
121
+ mongodb: {
122
+ host: '127.0.0.1',
123
+ port: 27017,
124
+ user: 'root',
125
+ password: 'asd123',
126
+ database: 'mm'
127
+ },
128
+ sqlite: {
129
+ dir: './db',
130
+ database: 'mm',
131
+ user: 'root',
132
+ password: 'asd123'
133
+ },
134
+ ret: {
135
+ type: 'json-rpc'
136
+ },
137
+ lang: {
138
+ type: 'zh_cn'
139
+ },
140
+ tpl: {
141
+ dir: './static/template',
142
+ ext: '.html'
143
+ },
144
+ loader: {
145
+ dir: ''
146
+ }
147
+ }
148
+
149
+ /**
150
+ * OS类构造函数
151
+ * @param {object} config 配置对象
152
+ */
153
+ constructor(config) {
154
+ super(config);
155
+ /**
156
+ * 实例容器(按作用域共享)
157
+ * @type {object}
158
+ */
159
+ this.container = containerAdmin('os', { name: 'os' });
160
+ this.container.server = this;
161
+ /**
162
+ * 初始化阶段创建的全局管理器列表
163
+ * @type {Array<object>}
164
+ */
165
+ this._admin_managers = [];
166
+ /**
167
+ * 已启动的全局管理器集合,避免重复启动
168
+ * @type {Set<object>}
169
+ */
170
+ this._started_admins = new Set();
171
+ }
172
+
173
+ /**
174
+ * 生命周期初始化钩子
175
+ * @returns {void} 无返回值
176
+ */
177
+ async onInit() {
178
+ this.initConfig();
179
+ this.initLogger();
180
+ // 初始化事件总线
181
+ this.initEventBus();
182
+ // 存储需先于管理器初始化:mm_dao 等管理器会通过 mm_sql 的 getSql() 复用同名 SQL 实例,
183
+ // 若管理器先创建,则会以默认(空库名)配置占用实例,导致后续 SQL 报 No database selected
184
+ await this.initpStorage();
185
+ await this.initAdmins();
186
+ await this.initAdapter();
187
+ await this.initLoader();
188
+ }
189
+ }
190
+
191
+ /**
192
+ * 初始化配置管理器
193
+ */
194
+ OS.prototype.initConfig = function () {
195
+ const { admin } = require('mm_config');
196
+ admin.setServer(this);
197
+ admin.get('os', this.config);
198
+ admin.get('cache', { ...this.config.cache, redis: this.config.redis, mongodb: this.config.mongodb });
199
+ admin.get('sql', { ...this.config.sql, mysql: this.config.mysql, sqlite: this.config.sqlite, jsondb: this.config.jsondb });
200
+ admin.get('web', this.config.web);
201
+ admin.get('mqtt', this.config.mqtt);
202
+ admin.get('socket', this.config.socket);
203
+ admin.get('websocket', this.config.websocket);
204
+ admin.get('jsondb', this.config.jsondb);
205
+ admin.get('redis', this.config.redis);
206
+ admin.get('mongodb', this.config.mongodb);
207
+ admin.get('sqlite', this.config.sqlite);
208
+ admin.get('mysql', this.config.mysql);
209
+ admin.get('ret', this.config.ret);
210
+ admin.get('lang', this.config.lang);
211
+ admin.get('tpl', this.config.tpl);
212
+ admin.get('loader', this.config.loader);
213
+ this.reg('config', admin);
214
+ };
215
+
216
+ /**
217
+ * 初始化日志记录器
218
+ */
219
+ OS.prototype.initLogger = function () {
220
+ this.reg('logger', getLogger(this.config.log || { level: 'info' }));
221
+ };
222
+
223
+ /**
224
+ * 记录日志
225
+ * @param {string} type 日志类型
226
+ * @param {string} msg 日志消息
227
+ * @param {...*} args 日志参数
228
+ */
229
+ OS.prototype.log = function (type, msg, ...args) {
230
+ this.container.get('logger')[type](msg, ...args);
231
+ };
232
+
233
+ /**
234
+ * 注册管理
235
+ * @param {string} name 管理名称
236
+ * @param {object} admin 管理对象
237
+ */
238
+ OS.prototype.reg = function (name, admin) {
239
+ this.container.set(name, admin);
240
+ };
241
+
242
+ /**
243
+ * 加载模块
244
+ * @param {string} mod_name 模块名称
245
+ * @returns {object} 模块对象
246
+ */
247
+ OS.prototype.require = function (mod_name) {
248
+ return require(mod_name);
249
+ };
250
+
251
+ /**
252
+ * 初始化适配器
253
+ * @returns {void} 无返回值
254
+ */
255
+ OS.prototype.initAdapter = async function () {
256
+ // 入站适配器
257
+ let adapters = this.config.in_adapters || [];
258
+ for (let mod of adapters) {
259
+ try {
260
+ let admin = this.require(mod.module).admin;
261
+ admin.setServer(this);
262
+ let manager = admin.get('os', this.config[mod.name]);
263
+ if (typeof manager.init === 'function') {
264
+ await manager.init();
265
+ }
266
+ this.reg(mod.name, manager);
267
+ } catch (error) {
268
+ this.log('error', `初始化适配器 ${mod.name} 失败: ${error}`);
269
+ }
270
+ }
271
+
272
+ // 出站适配器
273
+ let out_adapters = this.config.out_adapters || [];
274
+ for (let mod of out_adapters) {
275
+ try {
276
+ let admin = this.require(mod.module).admin;
277
+ admin.setServer(this);
278
+ let manager = admin.get('os', this.config[mod.name]);
279
+ if (typeof manager.init === 'function') {
280
+ await manager.init();
281
+ }
282
+ this.reg(mod.name, manager);
283
+ } catch (error) {
284
+ this.log('error', `初始化适配器 ${mod.name} 失败: ${error}`);
285
+ }
286
+ }
287
+ };
288
+
289
+ /**
290
+ * 初始化工具
291
+ * @returns {void} 无返回值
292
+ */
293
+ OS.prototype.initTools = async function () {
294
+ let tools = this.config.tools || [];
295
+ for (let mod of tools) {
296
+ try {
297
+ let admin = this.require(mod.module).admin;
298
+ admin.setServer(this);
299
+ let manager = admin.get('os', this.config[mod.name]);
300
+ if (typeof manager.init === 'function') {
301
+ await manager.init();
302
+ }
303
+ this.reg(mod.name, manager);
304
+ } catch (error) {
305
+ this.log('error', `初始化工具 ${mod.name} 失败: ${error}`);
306
+ }
307
+ }
308
+ };
309
+
310
+ /**
311
+ * 初始化管理
312
+ * @returns {void} 无返回值
313
+ */
314
+ OS.prototype.initAdmins = async function () {
315
+ let admins = this.config.admins || [];
316
+ for (let mod of admins) {
317
+ try {
318
+ let admin = this.require(mod.module).admin;
319
+ admin.setServer(this);
320
+ let manager = admin.get('os', this.config[mod.name]);
321
+ if (typeof manager.init === 'function') {
322
+ await manager.init();
323
+ }
324
+ this.reg(mod.name, manager);
325
+ this._admin_managers.push(manager);
326
+ } catch (error) {
327
+ this.log('error', `初始化管理 ${mod.name} 失败: ${error}`);
328
+ }
329
+ }
330
+ };
331
+
332
+ /**
333
+ * 初始化存储
334
+ * @returns {void} 无返回值
335
+ */
336
+ OS.prototype.initpStorage = async function () {
337
+ // 初始化缓存存储
338
+ let cacheAdmin = this.require('mm_cache').admin;
339
+ this._setAdminServer(cacheAdmin);
340
+ let cache = cacheAdmin.get('os', Object.assign({}, this.config.cache, { redis: this.config.redis, mongodb: this.config.mongodb, cachebase: this.config.cachebase }));
341
+ if (typeof cache.init === 'function') {
342
+ await cache.init();
343
+ }
344
+ this.reg('cache', cache);
345
+
346
+ // 初始化数据库
347
+ let sqlAdmin = this.require('mm_sql').admin;
348
+ this._setAdminServer(sqlAdmin);
349
+ let sql = sqlAdmin.get('os', Object.assign({}, this.config.sql, { mysql: this.config.mysql, sqlite: this.config.sqlite, jsondb: this.config.jsondb }));
350
+ if (typeof sql.init === 'function') {
351
+ await sql.init();
352
+ }
353
+ this.reg('sql', sql);
354
+ };
355
+
356
+ /**
357
+ * 设置管理器服务器:已设置时跳过,避免同一 Admin 实例重复绑定
358
+ * @param {object} admin 管理器工厂实例
359
+ */
360
+ OS.prototype._setAdminServer = function (admin) {
361
+ if (!admin.getServer()) {
362
+ admin.setServer(this);
363
+ }
364
+ };
365
+
366
+ /**
367
+ * 初始化应用加载器(协调层:只创建加载器与应用管理器,装配逻辑在 mm_apps/mm_plugins)
368
+ * @returns {void} 无返回值
369
+ */
370
+ OS.prototype.initLoader = async function () {
371
+ // 配置加载器:注入 socket/mqtt 类型,其余类型由 mm_loader 默认提供
372
+ const loader = new Loader(this.config.loader || {});
373
+ loader.addType('socket', 'socket.json');
374
+ loader.addType('mqtt', 'mqtt.json');
375
+ this.reg('loader', loader);
376
+
377
+ // 应用管理器:装配应用由 AppManager.load 负责,插件随 App.onInit 引入
378
+ const app = appAdmin('os');
379
+ app.setServer(this);
380
+ app.setLogger(this.container.get('logger'));
381
+ this.reg('app', app);
382
+
383
+ const dir = this.config.loader.dir || path.join(__dirname, '..', 'example', 'app');
384
+ await app.load(dir, loader);
385
+ await app.init();
386
+
387
+ // 注入 Web 请求路由
388
+ this._initWeb();
389
+ };
390
+
391
+ /**
392
+ * 初始化 Web 适配器:注入跨作用域事件路由与响应写出器
393
+ * @returns {void} 无返回值
394
+ */
395
+ OS.prototype._initWeb = function () {
396
+ const web = this.container.get('web');
397
+ if (!web) return;
398
+ web.setEventManager(this._createEventRouter());
399
+ new Response().bind(web);
400
+ };
401
+
402
+ /**
403
+ * 创建跨作用域事件路由:Web 适配器只持有 web 作用域,需转发到各应用作用域
404
+ * @returns {object} 含 run 方法的事件管理器
405
+ */
406
+ OS.prototype._createEventRouter = function () {
407
+ return {
408
+ run: (target, params, ctx, options) => this._routeRequest(target, params, ctx, options)
409
+ };
410
+ };
411
+
412
+ /**
413
+ * 路由请求:先尝试静态资源,未命中再按应用顺序执行事件
414
+ * @param {string} target 请求路径
415
+ * @param {object} params 请求参数
416
+ * @param {object} ctx 请求上下文
417
+ * @param {object} options 事件运行选项
418
+ * @returns {Promise<*>} 事件执行结果
419
+ */
420
+ OS.prototype._routeRequest = async function (target, params, ctx, options = {}) {
421
+ const statics = this.container.get('static');
422
+ if (statics && typeof statics.run === 'function') {
423
+ // 静态模块为服务式调用:命中即返回 true 并已写出响应,未命中返回 false 继续后续事件
424
+ const served = await statics.run(params, ctx, options);
425
+ if (served) {
426
+ return undefined;
427
+ }
428
+ }
429
+ return await this._runAppEvents(target, params, ctx, options);
430
+ };
431
+
432
+ /**
433
+ * 按应用排序依次执行事件:命中结果、响应已写出或发生错误时中止
434
+ * @param {string} target 请求路径
435
+ * @param {object} params 请求参数
436
+ * @param {object} ctx 请求上下文
437
+ * @param {object} options 事件运行选项
438
+ * @returns {Promise<*>} 事件执行结果
439
+ */
440
+ OS.prototype._runAppEvents = async function (target, params, ctx, options = {}) {
441
+ const app = this.container.get('app');
442
+ if (!app || typeof app.list !== 'function') return undefined;
443
+
444
+ const apps = app.list().slice().sort((a, b) => this._getSort(a) - this._getSort(b));
445
+ for (const item of apps) {
446
+ if (this._isRequestHandled(ctx) || ctx.error) return undefined;
447
+ const name = item.config && item.config.name;
448
+ if (!name) continue;
449
+ const app_options = {};
450
+ const result = await eventAdmin(name).run(target, params, ctx, app_options);
451
+ if (app_options.error) {
452
+ ctx.error = ctx.error || app_options.error;
453
+ options.error = options.error || app_options.error;
454
+ return undefined;
455
+ }
456
+ if (result !== undefined && result !== null) return result;
457
+ }
458
+ return undefined;
459
+ };
460
+
461
+ /**
462
+ * 判断请求是否已处理完毕:事件或中间件已写出响应
463
+ * @param {object} ctx 请求上下文
464
+ * @returns {boolean} 响应是否已写出
465
+ */
466
+ OS.prototype._isRequestHandled = function (ctx) {
467
+ if (!ctx) return false;
468
+ if (ctx.handled === true) return true;
469
+ const res = ctx.res;
470
+ return !!(res && (res.writableEnded || res.headersSent));
471
+ };
472
+
473
+ /**
474
+ * 获取应用执行顺序
475
+ * @param {object} app 应用驱动实例
476
+ * @returns {number} 排序值,缺省 100
477
+ */
478
+ OS.prototype._getSort = function (app) {
479
+ const sort = app && app.config ? app.config.sort : undefined;
480
+ return typeof sort === 'number' ? sort : 100;
481
+ };
482
+
483
+ /**
484
+ * 初始化事件总线
485
+ * @returns {void} 无返回值
486
+ */
487
+ OS.prototype.initEventBus = function () {
488
+ let admin = this.require('mm_eventer').admin;
489
+ admin.setServer(this);
490
+ this.reg('eventer', admin.get('os'));
491
+ };
492
+
493
+ /**
494
+ * 启动适配器:按配置中的入站、出站适配器名称从容器取出管理器并启动
495
+ * @returns {void} 无返回值
496
+ */
497
+ OS.prototype._startAdapters = async function () {
498
+ let mods = this.config.in_adapters;
499
+ for (let mod of mods) {
500
+ let manager = this.container.get(mod.name);
501
+ if (!manager || typeof manager.start !== 'function') continue;
502
+ try {
503
+ await manager.start();
504
+ this._printAddress(mod.name, manager);
505
+ } catch (error) {
506
+ this.log('error', `启动适配器 ${mod.name} 失败: ${error}`);
507
+ }
508
+ }
509
+ };
510
+
511
+ /**
512
+ * 启动初始化阶段创建的全局管理器
513
+ * 仅启动一次,避免重复执行管理器生命周期
514
+ * @returns {void} 无返回值
515
+ */
516
+ OS.prototype._startAdmins = async function () {
517
+ let managers = this._admin_managers || [];
518
+ for (let manager of managers) {
519
+ if (!manager || typeof manager.start !== 'function') continue;
520
+ if (this._started_admins.has(manager)) continue;
521
+ try {
522
+ await manager.start();
523
+ this._started_admins.add(manager);
524
+ } catch (error) {
525
+ let name = manager.config && manager.config.name;
526
+ this.log('error', `启动管理 ${name} 失败: ${error}`);
527
+ }
528
+ }
529
+ };
530
+
531
+ /**
532
+ * 启动
533
+ * @returns {void} 无返回值
534
+ */
535
+ OS.prototype.start = async function () {
536
+ // 启动适配器
537
+ await this._startAdapters();
538
+
539
+ // 启动缓存存储
540
+ await this.container.get('cache').start();
541
+ // 启动数据库
542
+ await this.container.get('sql').start();
543
+
544
+ // 启动应用
545
+ const app = this.container.get('app');
546
+ if (app) {
547
+ await app.start();
548
+ }
549
+
550
+ // 启动初始化阶段创建的全局管理器(含 os 作用域静态资源)
551
+ await this._startAdmins();
552
+ };
553
+
554
+ /**
555
+ * 打印适配器监听地址
556
+ * @param {string} name 适配器名称
557
+ * @param {object} manager 适配器管理器实例
558
+ */
559
+ OS.prototype._printAddress = function (name, manager) {
560
+ let { host, port } = manager.config || {};
561
+ if (!host || host === '0.0.0.0' || host === '::') {
562
+ host = 'localhost';
563
+ }
564
+ let protocol = { web: 'http', websocket: 'ws', socket: 'tcp', mqtt: 'mqtt' }[name] || name;
565
+ let address = `${protocol}://${host}`;
566
+ if (port) {
567
+ address += `:${port}`;
568
+ }
569
+ this.log('info', `适配器 ${name} 已启动: ${address}`);
570
+ };
571
+
369
572
  module.exports = OS;