@solayao/koa-server-kit 0.1.0 → 0.1.1
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 +4 -1
- package/package.json +5 -2
- package/src/routes/RouteLoader.js +54 -40
- package/src/routes/builtin-routes.js +173 -0
- package/src/routes/index.js +1 -0
- package/src/server/createApiServer.js +80 -67
package/README.md
CHANGED
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
Koa2 服务通用骨架包,内置插件加载、全局中间件、动态路由、Swagger、鉴权、HTTP/HTTPS/TCP 代理、请求中断、自签证书、进程收尾、默认配置与常用工具。
|
|
4
4
|
|
|
5
|
-
一次 `createApiServer`
|
|
5
|
+
一次 `createApiServer` 调用即可启动完整服务骨架,宿主只需提供业务配置与业务文件。启动失败由内核统一记录日志并退出(可用 `options.exitOnFatalError = false` 改为抛出异常交由宿主处理)。
|
|
6
|
+
|
|
7
|
+
包内已注册通用路由:`/public/internal/token`(平台 token 换取)、`/public/mock/test`、`/public/api/abort`,以及开发环境下的 `/public/mock/login`。宿主在自己的 `routesDir` 中声明同方法同路径的路由即可覆盖。
|
|
6
8
|
|
|
7
9
|
宿主项目仍需提供:
|
|
8
10
|
|
|
@@ -144,6 +146,7 @@ export default {
|
|
|
144
146
|
| `jsonLimit` / `formLimit` / `textLimit` | `10mb` | `koa-body` 各类型请求体大小上限 |
|
|
145
147
|
| `uploadTmpDir` | `cwd/assets/uploads/tmp` | multipart 上传临时目录,启动时自动创建 |
|
|
146
148
|
| `jwtUnless` | 内置规则 | `(ctx) => boolean`,覆盖 JWT 免鉴权判断;默认放行 OPTIONS、`/swagger`、`/public`(`/public/mock` 仅开发环境) |
|
|
149
|
+
| `exitOnFatalError` | `true` | 启动失败时由内核记录并 `process.exit(1)`;设为 `false` 则抛出给宿主 |
|
|
147
150
|
| `lclCtx` | `{}` | 额外注入到 `ctx` 的宿主全局对象(如 `$webdav`、`$isDev`) |
|
|
148
151
|
|
|
149
152
|
`currentIps` 无需配置:包内自适应生成为 `[getIPAddress(), '127.0.0.1', 'localhost']`(Docker 环境可用 `APP_DOCKER_IP` 指定),同时用于 `ctx.$ips`、自签证书 SAN 和启动日志。
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@solayao/koa-server-kit",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Koa2 服务通用内核:配置解析、启动代理、路由装配、鉴权、中间件、日志与通用工具",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
@@ -22,7 +22,10 @@
|
|
|
22
22
|
],
|
|
23
23
|
"scripts": {
|
|
24
24
|
"lint": "eslint src --ext .js",
|
|
25
|
-
"check": "node --check index.js"
|
|
25
|
+
"check": "node --check index.js",
|
|
26
|
+
"release": "npm version patch --no-git-tag-version && npm publish --access public",
|
|
27
|
+
"release:minor": "npm version minor --no-git-tag-version && npm publish --access public",
|
|
28
|
+
"release:major": "npm version major --no-git-tag-version && npm publish --access public"
|
|
26
29
|
},
|
|
27
30
|
"dependencies": {
|
|
28
31
|
"got": "^11.8.6",
|
|
@@ -8,6 +8,7 @@ import { AbortController } from 'node-abort-controller'
|
|
|
8
8
|
import swaggerJSDoc from 'swagger-jsdoc'
|
|
9
9
|
import swaggerDefinitions from '../swagger-definitions.js'
|
|
10
10
|
import { createAuth } from '../auth/auth.js'
|
|
11
|
+
import { createBuiltinRoutes } from './builtin-routes.js'
|
|
11
12
|
import { defaultLogger } from '../tools/LogColor.js'
|
|
12
13
|
import funcHandler from '../tools/FuncHandler.js'
|
|
13
14
|
|
|
@@ -283,6 +284,8 @@ export const createRouteLoader = ({ app, options = {}, adapters = {} } = {}) =>
|
|
|
283
284
|
apiBaseUrl: options.apiBaseUrl || '',
|
|
284
285
|
useRouteCache: !!options.useRouteCache,
|
|
285
286
|
logger: options.logger || defaultLogger,
|
|
287
|
+
isDev: !!options.isDev,
|
|
288
|
+
internalTokenPath: options.internalTokenPath || '/public/internal/token',
|
|
286
289
|
getAuthData: createAuth().getAuthData,
|
|
287
290
|
cacheGet: adapters.cacheGet || (async () => null),
|
|
288
291
|
cacheSet: adapters.cacheSet || (async () => {})
|
|
@@ -302,54 +305,65 @@ export const createRouteLoader = ({ app, options = {}, adapters = {} } = {}) =>
|
|
|
302
305
|
|
|
303
306
|
const swaggerPaths = {}
|
|
304
307
|
|
|
305
|
-
//
|
|
308
|
+
// 所有路由注册到同一个Router, 避免跨文件同路径不同方法被误拦405
|
|
306
309
|
const mainRouter = new KoaRouter()
|
|
310
|
+
const registeredKeys = new Set()
|
|
311
|
+
|
|
312
|
+
const addRoute = (item) => {
|
|
313
|
+
if (!item || !item.url || (!item.cb && !item.handler)) return
|
|
314
|
+
|
|
315
|
+
const method = (item.method || 'get').toLowerCase()
|
|
316
|
+
const fullUrl = buildRouteUrl(config.apiBaseUrl, item.url, !!item.useAuth)
|
|
317
|
+
const routeKey = `${method}:${fullUrl}`
|
|
318
|
+
|
|
319
|
+
// 宿主显式声明的同路径同方法优先, 内置路由不重复注册
|
|
320
|
+
if (typeof mainRouter[method] !== 'function' || registeredKeys.has(routeKey)) return
|
|
321
|
+
registeredKeys.add(routeKey)
|
|
322
|
+
|
|
323
|
+
mainRouter[method](fullUrl, routerHandler({
|
|
324
|
+
cb: item.cb || item.handler,
|
|
325
|
+
useAuth: !!item.useAuth,
|
|
326
|
+
useRequestCache: !!item.useRequestCache,
|
|
327
|
+
minuteRequestCache: item.minuteRequestCache || 0,
|
|
328
|
+
ignoreHeaderRk: !!item.ignoreHeaderRk,
|
|
329
|
+
getAuthData: config.getAuthData,
|
|
330
|
+
cacheEnabled: config.useRouteCache,
|
|
331
|
+
cacheGet: config.cacheGet,
|
|
332
|
+
cacheSet: config.cacheSet,
|
|
333
|
+
logger: config.logger,
|
|
334
|
+
privilegedPrefix
|
|
335
|
+
}))
|
|
336
|
+
|
|
337
|
+
// 生成动态Swagger路径
|
|
338
|
+
if (item.swaggerDoc) {
|
|
339
|
+
const swaggerItem = buildSwaggerPath(
|
|
340
|
+
fullUrl,
|
|
341
|
+
method,
|
|
342
|
+
!!item.useAuth,
|
|
343
|
+
{ ...item.swaggerDoc, ignoreHeaderRk: item.ignoreHeaderRk }
|
|
344
|
+
)
|
|
345
|
+
swaggerPaths[swaggerItem.path] = {
|
|
346
|
+
...(swaggerPaths[swaggerItem.path] || {}),
|
|
347
|
+
[swaggerItem.method]: swaggerItem.doc
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
307
351
|
|
|
308
352
|
for (const name of files) {
|
|
309
353
|
const filePath = path.join(config.routesDir, name)
|
|
310
354
|
const module = await import(pathToFileURL(filePath).href)
|
|
311
355
|
const exported = Array.isArray(module.default) ? module.default : [module.default]
|
|
312
356
|
|
|
313
|
-
for (const item of exported)
|
|
314
|
-
if (!item || !item.url || (!item.cb && !item.handler)) continue
|
|
315
|
-
|
|
316
|
-
const method = (item.method || 'get').toLowerCase()
|
|
317
|
-
const fullUrl = buildRouteUrl(config.apiBaseUrl, item.url, !!item.useAuth)
|
|
318
|
-
|
|
319
|
-
if (typeof mainRouter[method] !== 'function') continue
|
|
320
|
-
|
|
321
|
-
// 注册路由handler
|
|
322
|
-
mainRouter[method](fullUrl, routerHandler({
|
|
323
|
-
cb: item.cb || item.handler,
|
|
324
|
-
useAuth: !!item.useAuth,
|
|
325
|
-
useRequestCache: !!item.useRequestCache,
|
|
326
|
-
minuteRequestCache: item.minuteRequestCache || 0,
|
|
327
|
-
ignoreHeaderRk: !!item.ignoreHeaderRk,
|
|
328
|
-
getAuthData: config.getAuthData,
|
|
329
|
-
cacheEnabled: config.useRouteCache,
|
|
330
|
-
cacheGet: config.cacheGet,
|
|
331
|
-
cacheSet: config.cacheSet,
|
|
332
|
-
logger: config.logger,
|
|
333
|
-
privilegedPrefix
|
|
334
|
-
}))
|
|
335
|
-
|
|
336
|
-
// 生成动态Swagger路径
|
|
337
|
-
if (item.swaggerDoc) {
|
|
338
|
-
const swaggerItem = buildSwaggerPath(
|
|
339
|
-
fullUrl,
|
|
340
|
-
method,
|
|
341
|
-
!!item.useAuth,
|
|
342
|
-
{ ...item.swaggerDoc, ignoreHeaderRk: item.ignoreHeaderRk }
|
|
343
|
-
)
|
|
344
|
-
swaggerPaths[swaggerItem.path] = {
|
|
345
|
-
...(swaggerPaths[swaggerItem.path] || {}),
|
|
346
|
-
[swaggerItem.method]: swaggerItem.doc
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
}
|
|
357
|
+
for (const item of exported) addRoute(item)
|
|
351
358
|
}
|
|
352
359
|
|
|
360
|
+
// 包内通用路由: 内部token、测试、中断与开发环境模拟登录
|
|
361
|
+
const builtinRoutes = createBuiltinRoutes({
|
|
362
|
+
isDev: config.isDev,
|
|
363
|
+
internalTokenPath: config.internalTokenPath
|
|
364
|
+
})
|
|
365
|
+
for (const item of builtinRoutes) addRoute(item)
|
|
366
|
+
|
|
353
367
|
app.use(mainRouter.routes(), mainRouter.allowedMethods())
|
|
354
368
|
|
|
355
369
|
// SwaggerRoutes: 原始项目用/swagger.json输出swagger-jsdoc结果, /swagger展示UI
|
|
@@ -393,7 +407,7 @@ export const createRouteLoader = ({ app, options = {}, adapters = {} } = {}) =>
|
|
|
393
407
|
}))
|
|
394
408
|
}
|
|
395
409
|
|
|
396
|
-
log.info(`[routeLoader] registered ${files.length} route files`)
|
|
410
|
+
log.info(`[routeLoader] registered ${files.length} route files + ${builtinRoutes.length} builtin routes`)
|
|
397
411
|
return mainRouter
|
|
398
412
|
}
|
|
399
413
|
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import crypto from 'crypto'
|
|
2
|
+
import { createAuth } from '../auth/auth.js'
|
|
3
|
+
|
|
4
|
+
/** 恒定时间字符串比较(先做sha256归一化长度, 防时序攻击), 用于密钥核验 */
|
|
5
|
+
const solSafeEqual = (a = '', b = '') => {
|
|
6
|
+
const tempHashA = crypto.createHash('sha256').update(`${a}`).digest()
|
|
7
|
+
const tempHashB = crypto.createHash('sha256').update(`${b}`).digest()
|
|
8
|
+
|
|
9
|
+
return crypto.timingSafeEqual(tempHashA, tempHashB)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** 归一化IPv4映射与IPv6环回地址(::ffff:127.0.0.1 / ::1 -> 127.0.0.1) */
|
|
13
|
+
const solNormalizeIp = (ip = '') => {
|
|
14
|
+
const tempIp = `${ip}`.replace(/^::ffff:/i, '')
|
|
15
|
+
return tempIp === '::1' ? '127.0.0.1' : tempIp
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 获取可信客户端IP: 直接连接的socket必须属于信任列表(本机TCP代理), 并取XFF最后一段(由代理写入);
|
|
20
|
+
* HTTPS内部端口流量加密、代理无法注入XFF, 因此该接口在HTTPS直连上直接拒绝
|
|
21
|
+
*/
|
|
22
|
+
const solGetTrustedClientIp = (ctx) => {
|
|
23
|
+
const tempSocketIp = solNormalizeIp((ctx.request.socket && ctx.request.socket.remoteAddress) || '')
|
|
24
|
+
const tempTrustedIps = (ctx.$ips || []).map(solNormalizeIp)
|
|
25
|
+
|
|
26
|
+
if (!tempSocketIp || !tempTrustedIps.includes(tempSocketIp)) return null
|
|
27
|
+
|
|
28
|
+
const tempForwarded = `${ctx.request.headers['x-forwarded-for'] || ''}`
|
|
29
|
+
.split(',')
|
|
30
|
+
.map(it => solNormalizeIp(it.trim()))
|
|
31
|
+
.filter(Boolean)
|
|
32
|
+
|
|
33
|
+
return tempForwarded.length ? tempForwarded[tempForwarded.length - 1] : null
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 是否内网来源IP(私网段/环回), APP_Internal_Allow_Ips中配置的IP额外放行 */
|
|
37
|
+
const solIsIntranetIp = (ip = '') => {
|
|
38
|
+
const tempIp = solNormalizeIp(ip)
|
|
39
|
+
const tempIntranetRegex = /^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|::1|f[cd][0-9a-f]{2}:|fe80:)/i
|
|
40
|
+
const tempExtraIps = (process.env.APP_Internal_Allow_Ips || '').split(/\s+/).filter(Boolean)
|
|
41
|
+
|
|
42
|
+
return tempIntranetRegex.test(tempIp) || tempExtraIps.includes(tempIp)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 包内通用路由: 内部token换取、可用性测试、请求中断与开发环境模拟登录。
|
|
47
|
+
* 业务项目仍可在自己的routesDir覆盖同路径路由。
|
|
48
|
+
* @param {Object} options
|
|
49
|
+
* @param {Boolean} options.isDev 开发环境才注册模拟登录
|
|
50
|
+
* @param {String} options.internalTokenPath 内部token接口完整路径, 默认/public/internal/token
|
|
51
|
+
*/
|
|
52
|
+
export const createBuiltinRoutes = ({
|
|
53
|
+
isDev = false,
|
|
54
|
+
internalTokenPath = '/public/internal/token'
|
|
55
|
+
} = {}) => {
|
|
56
|
+
const auth = createAuth()
|
|
57
|
+
const tokenUrl = `${internalTokenPath || '/public/internal/token'}`.replace(/^\/public/, '') || '/internal/token'
|
|
58
|
+
const expiresIn = '10m'
|
|
59
|
+
|
|
60
|
+
const internalTokenRoute = {
|
|
61
|
+
url: tokenUrl,
|
|
62
|
+
method: 'post',
|
|
63
|
+
useAuth: false,
|
|
64
|
+
useRequestCache: false,
|
|
65
|
+
cb: async (ctx) => {
|
|
66
|
+
// 1. 仅接受本机代理注入的XFF末段, 拒绝客户端伪造头与无法确认来源的HTTPS直连
|
|
67
|
+
const clientIp = solGetTrustedClientIp(ctx)
|
|
68
|
+
if (!clientIp) {
|
|
69
|
+
ctx.throw(403, '无法确认可信来源IP, 请通过本机HTTP代理访问')
|
|
70
|
+
}
|
|
71
|
+
if (!solIsIntranetIp(clientIp)) {
|
|
72
|
+
ctx.throw(403, `非内网来源禁止访问: ${clientIp}`)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 2. 密钥核验(恒定时间比较), 密钥仅通过环境变量注入
|
|
76
|
+
const configuredKey = process.env.APP_Platform_Auth_Pass_Key || ''
|
|
77
|
+
if (!configuredKey) {
|
|
78
|
+
ctx.throw(500, '平台服务鉴权口令未配置, 请设置环境变量APP_Platform_Auth_Pass_Key')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const requestKey = ctx.get('X-Platform-Key') || (ctx.get('authorization') || '').replace(/^Bearer\s+/i, '')
|
|
82
|
+
if (!requestKey || !solSafeEqual(requestKey, configuredKey)) {
|
|
83
|
+
ctx.throw(401, '平台服务鉴权口令错误')
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// 3. 颁发短时效低权限token(自带Bearer前缀)
|
|
87
|
+
return { token: auth.getPlatformToken(expiresIn), expiresIn }
|
|
88
|
+
},
|
|
89
|
+
swaggerDoc: {
|
|
90
|
+
summary: '服务间平台token获取',
|
|
91
|
+
description: '内网服务携带平台密钥(X-Platform-Key头)换取短时效JWT token',
|
|
92
|
+
tags: ['内部'],
|
|
93
|
+
body: {},
|
|
94
|
+
query: {},
|
|
95
|
+
header: {
|
|
96
|
+
'X-Platform-Key': {
|
|
97
|
+
type: 'string',
|
|
98
|
+
description: '平台服务鉴权口令, 与服务端环境变量APP_Platform_Auth_Pass_Key一致',
|
|
99
|
+
required: true
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const mockTestRoute = {
|
|
106
|
+
url: '/mock/test',
|
|
107
|
+
method: 'get',
|
|
108
|
+
useAuth: false,
|
|
109
|
+
useRequestCache: false,
|
|
110
|
+
cb: async () => {
|
|
111
|
+
// 模拟长时间操作请求, 供连通性检查与请求中断验证使用
|
|
112
|
+
await new Promise(resolve => setTimeout(resolve, 1000 * 60 * 5))
|
|
113
|
+
return 'Hello world!'
|
|
114
|
+
},
|
|
115
|
+
swaggerDoc: {
|
|
116
|
+
summary: '测试接口',
|
|
117
|
+
description: '',
|
|
118
|
+
tags: ['测试'],
|
|
119
|
+
body: {},
|
|
120
|
+
query: {},
|
|
121
|
+
header: {}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const abortRoute = {
|
|
126
|
+
url: '/api/abort',
|
|
127
|
+
method: 'get',
|
|
128
|
+
useAuth: false,
|
|
129
|
+
useRequestCache: false,
|
|
130
|
+
cb: (ctx) => {
|
|
131
|
+
ctx.app.emit('route_abort', ctx.request.headers.trk || '/')
|
|
132
|
+
return '取消的请求key:' + (ctx.request.headers.trk || '/')
|
|
133
|
+
},
|
|
134
|
+
swaggerDoc: {
|
|
135
|
+
summary: '暂停请求',
|
|
136
|
+
description: '',
|
|
137
|
+
tags: ['测试'],
|
|
138
|
+
body: {},
|
|
139
|
+
query: {},
|
|
140
|
+
header: {
|
|
141
|
+
trk: {
|
|
142
|
+
type: 'string',
|
|
143
|
+
description: '对应上待终止请求的接口header内设置的rk',
|
|
144
|
+
required: true
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
},
|
|
148
|
+
ignoreHeaderRk: true
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const mockLoginRoute = {
|
|
152
|
+
url: '/mock/login',
|
|
153
|
+
method: 'post',
|
|
154
|
+
useAuth: false,
|
|
155
|
+
useRequestCache: false,
|
|
156
|
+
cb: () => auth.getMockUserToken({
|
|
157
|
+
isMock: true,
|
|
158
|
+
id: 'mock-id',
|
|
159
|
+
username: 'mock-username',
|
|
160
|
+
password: 'mock-password'
|
|
161
|
+
}, '1d'),
|
|
162
|
+
swaggerDoc: {
|
|
163
|
+
summary: '模拟登录',
|
|
164
|
+
description: '',
|
|
165
|
+
tags: ['测试'],
|
|
166
|
+
body: { $ref: '#/definitions/loginparam' },
|
|
167
|
+
query: {},
|
|
168
|
+
header: {}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return [internalTokenRoute, mockTestRoute, abortRoute, ...(isDev ? [mockLoginRoute] : [])]
|
|
173
|
+
}
|
package/src/routes/index.js
CHANGED
|
@@ -18,83 +18,96 @@ export const createApiServer = async ({
|
|
|
18
18
|
adapters = {},
|
|
19
19
|
config: configOverrides = {}
|
|
20
20
|
} = {}) => {
|
|
21
|
-
|
|
22
|
-
// 保持同一实例引用, 业务代码任意位置import config都取到最终值且运行期不可改
|
|
23
|
-
applyConfigOnce(configOverrides)
|
|
21
|
+
const fatalLogger = options.logger || defaultLogger
|
|
24
22
|
|
|
25
|
-
|
|
26
|
-
|
|
23
|
+
try {
|
|
24
|
+
// 配置特色化只在启动时注入一次, 注入后冻结:
|
|
25
|
+
// 保持同一实例引用, 业务代码任意位置import config都取到最终值且运行期不可改
|
|
26
|
+
applyConfigOnce(configOverrides)
|
|
27
27
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const System = config.solGetConfig('System')
|
|
31
|
-
const logger = options.logger && typeof options.logger.error === 'function'
|
|
32
|
-
? options.logger
|
|
33
|
-
: defaultLogger
|
|
34
|
-
const runtimeOptions = {
|
|
35
|
-
...options,
|
|
36
|
-
logger,
|
|
37
|
-
port: System.API_server_port,
|
|
38
|
-
apiBaseUrl: System.API_base_url
|
|
39
|
-
}
|
|
28
|
+
// 信任代理头, 使 ctx.ip / ctx.ips 取到真实客户端IP而非内部代理地址(127.0.0.1)
|
|
29
|
+
app.proxy = true
|
|
40
30
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
31
|
+
// 运行时参数统一从config.System读取:
|
|
32
|
+
// API_server_port / API_base_url 只在config.System声明一次, options不再重复
|
|
33
|
+
const System = config.solGetConfig('System')
|
|
34
|
+
const logger = options.logger && typeof options.logger.error === 'function'
|
|
35
|
+
? options.logger
|
|
36
|
+
: defaultLogger
|
|
37
|
+
const runtimeOptions = {
|
|
38
|
+
...options,
|
|
39
|
+
logger,
|
|
40
|
+
port: System.API_server_port,
|
|
41
|
+
apiBaseUrl: System.API_base_url
|
|
42
|
+
}
|
|
44
43
|
|
|
45
|
-
|
|
46
|
-
|
|
44
|
+
// 当前服务器IP自适应获取:
|
|
45
|
+
// currentIps同时供ctx.$ips(CORS/业务)与自签证书SAN/启动日志使用, 不需要宿主配置
|
|
46
|
+
const currentIps = getCurrentIps()
|
|
47
47
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
app,
|
|
51
|
-
options: { ...runtimeOptions, currentIps },
|
|
52
|
-
adapters: {
|
|
53
|
-
...adapters,
|
|
54
|
-
pluginContext
|
|
55
|
-
}
|
|
56
|
-
})
|
|
57
|
-
middleware.register()
|
|
48
|
+
// 1. 插件初始化必须早于中间件, 否则ctx拿不到$mysql/$redis等注入对象
|
|
49
|
+
const pluginContext = adapters.pluginLoader ? await adapters.pluginLoader() : {}
|
|
58
50
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
51
|
+
// 2. 注册全局中间件
|
|
52
|
+
const middleware = createMiddlewareLoader({
|
|
53
|
+
app,
|
|
54
|
+
options: { ...runtimeOptions, currentIps },
|
|
55
|
+
adapters: {
|
|
56
|
+
...adapters,
|
|
57
|
+
pluginContext
|
|
58
|
+
}
|
|
59
|
+
})
|
|
60
|
+
middleware.register()
|
|
62
61
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
62
|
+
// 3. 注册动态路由与Swagger(含包内内置的通用路由)
|
|
63
|
+
const routes = createRouteLoader({ app, options: runtimeOptions, adapters })
|
|
64
|
+
await routes.register()
|
|
66
65
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
app,
|
|
70
|
-
port: runtimeOptions.port,
|
|
71
|
-
currentIps,
|
|
72
|
-
logger,
|
|
73
|
-
packageMeta: options.packageMeta,
|
|
74
|
-
certProvider: adapters.certProvider,
|
|
75
|
-
certOptions: options.certOptions,
|
|
76
|
-
onStart: adapters.onServerStart || (async () => {})
|
|
77
|
-
})
|
|
66
|
+
// 4. 注册请求中断(rk -> AbortController):
|
|
67
|
+
// 监听route_login/route_abort/route_logout, 否则/public/api/abort无法中断请求
|
|
68
|
+
const routeAbortHandler = createRouteAbortHandler({ app, logger })
|
|
78
69
|
|
|
79
|
-
|
|
70
|
+
// 5. 启动HTTP/HTTPS/TCP代理
|
|
71
|
+
const serverLoader = createServerLoader({
|
|
72
|
+
app,
|
|
73
|
+
port: runtimeOptions.port,
|
|
74
|
+
currentIps,
|
|
75
|
+
logger,
|
|
76
|
+
packageMeta: options.packageMeta,
|
|
77
|
+
certProvider: adapters.certProvider,
|
|
78
|
+
certOptions: options.certOptions,
|
|
79
|
+
onStart: adapters.onServerStart || (async () => {})
|
|
80
|
+
})
|
|
80
81
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
82
|
+
const server = await serverLoader.start()
|
|
83
|
+
|
|
84
|
+
// 6. 注册退出收尾; cleanup放宿主资源, 服务/socket/日志由包内统一处理
|
|
85
|
+
const signalHandler = createProcessSignalHandler({
|
|
86
|
+
servers: [server.proxyServer, server.httpServer, server.httpsServer],
|
|
87
|
+
sockets: [...server.sockets],
|
|
88
|
+
cleanup: adapters.cleanup || [],
|
|
89
|
+
logger
|
|
90
|
+
})
|
|
91
|
+
signalHandler.register()
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
app,
|
|
95
|
+
server,
|
|
96
|
+
serverLoader,
|
|
97
|
+
middleware,
|
|
98
|
+
routes,
|
|
99
|
+
routeAbortHandler,
|
|
100
|
+
signalHandler,
|
|
101
|
+
pluginContext
|
|
102
|
+
}
|
|
103
|
+
} catch (err) {
|
|
104
|
+
// 启动失败由内核统一记录并退出, 宿主无需再包一层catch
|
|
105
|
+
const logError = fatalLogger.error
|
|
106
|
+
? fatalLogger.error.bind(fatalLogger)
|
|
107
|
+
: (...args) => fatalLogger.log(...args)
|
|
108
|
+
logError(`[createApiServer] 服务启动失败: ${err.stack || err.message}`)
|
|
89
109
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
server,
|
|
93
|
-
serverLoader,
|
|
94
|
-
middleware,
|
|
95
|
-
routes,
|
|
96
|
-
routeAbortHandler,
|
|
97
|
-
signalHandler,
|
|
98
|
-
pluginContext
|
|
110
|
+
if (options.exitOnFatalError === false) throw err
|
|
111
|
+
process.exit(1)
|
|
99
112
|
}
|
|
100
113
|
}
|