@kne/fastify-app-manager 0.1.22 → 0.1.23
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 +96 -2
- package/index.js +4 -0
- package/libs/controllers/app.js +120 -0
- package/libs/models/appOpenApiRecord.js +46 -0
- package/libs/services/app.js +1 -0
- package/libs/services/bootstrap.js +13 -8
- package/libs/services/openApi.js +145 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -203,6 +203,8 @@ await fastify.listen({ port: 3000 });
|
|
|
203
203
|
| `systemEnvKeys` | array | 否 | `[]` | 宿主维护的系统变量键名,与内置 `DB_TABLE_PREFIX` 合并:接口不返回,create / save / saveEnv 不可新增、修改或删除 |
|
|
204
204
|
| `resolveSystemEnv` | function | 否 | `null` | `async ({ app, version, serverDir, upstreamUrl }) => env \| null`(`upstreamUrl` 为子应用进程地址 `http://{upstreamHost}:{port}`),每次启动进程(deploy / start / restart / 恢复)前调用;返回值覆盖应用变量注入子进程,值为 `null` / `undefined` 的键忽略,属于 `systemEnvKeys` 的键持久化到 `app.env` |
|
|
205
205
|
| `onAppRemoved` | function | 否 | `null` | `async ({ app }) => void`,应用删除成功后调用,`app` 为删除前快照(含 `env`);数据清理未完成而未删除时不调用,钩子报错只记 warn 日志 |
|
|
206
|
+
| `getOpenApiToken` | function | 否 | `null` | `async app => accessToken`,签发读取子应用 `/open-api.json` 的服务令牌;未配置时 `GET .../app/open-api` 返回 400。接 OIDC 时传 `appOidc.getOpenApiToken` |
|
|
207
|
+
| `issueUserAccessToken` | function | 否 | `null` | `async ({ app, userId, tenantId }) => accessToken`,以登录用户身份签发子应用令牌;未配置时 `POST .../app/open-api/token` 返回 400。接 OIDC 时传 `appOidc.issueUserAccessToken` |
|
|
206
208
|
| `resolveVersionFile` | function | 否 | `null` | `async ({ fileId, name, version, request }) => Buffer`,版本上传传 `fileId`(而非 multipart 文件)时调用,返回 zip 内容;未配置时传 `fileId` 返回 400。版本记录保存 `fileId`;这类版本只在当前部署时常驻磁盘,部署非当前版本或启动时当前版本目录缺失会再次调用以重建 |
|
|
207
209
|
| `defaultAppDb` | object | 否 | `appsRoot/_shared/apps-data.sqlite` | 托管应用默认库(须与宿主主库分离) |
|
|
208
210
|
| `dbQueryMaxRows` | number | 否 | `500` | 只读 query SQL 最大返回行数 |
|
|
@@ -346,6 +348,67 @@ await fastify.listen({ port: 3000 });
|
|
|
346
348
|
- 两者都**不含应用中心注入的变量**(见 `services.app.listInjectedEnvKeys`):`PORT`、`DB_TABLE_PREFIX`、`systemEnvKeys`、`passthroughEnvKeys`、托管库连接 `DB_DIALECT` / `DB_HOST` / `DB_PORT` / `DB_DATABASE` / `DB_USERNAME` / `DB_PASSWORD` / `DB_STORAGE` 与 `DB_DEDICATED`(自有库在数据页签配置),以及最近一次启动时 `resolveSystemEnv` 返回的键(记录在 `options.injectedEnvKeys`)。注入的变量照常参与启动前校验。
|
|
347
349
|
- 版本没有 schema 时 `hasSchema=false`、`declared=[]`,该版本无法部署。
|
|
348
350
|
|
|
351
|
+
##### GET `{prefix}/app/open-api`
|
|
352
|
+
|
|
353
|
+
运行中应用的 OpenAPI 文档:用 `getOpenApiToken` 签发的服务令牌请求子应用 `http://{upstreamHost}:{port}/open-api.json`,原样返回 JSON。
|
|
354
|
+
|
|
355
|
+
| 参数名 | 类型 | 必填 | 说明 |
|
|
356
|
+
|--------|------|------|------|
|
|
357
|
+
| name | string | 是 | 应用 slug |
|
|
358
|
+
|
|
359
|
+
应用未运行、未配置 `getOpenApiToken`、子应用未开启 `/open-api.json`(需 `@kne/fastify-app-runtime` >=0.1.1)或拒绝服务令牌(需 >=0.1.2)时返回 400,其它上游错误返回 502。
|
|
360
|
+
|
|
361
|
+
##### POST `{prefix}/app/open-api/token`
|
|
362
|
+
|
|
363
|
+
以当前登录用户(`request.userInfo.id`)身份调用 `issueUserAccessToken` 签发访问该应用接口的令牌,供管理端在线调试:前端带 `Authorization: Bearer {token}` 经网关 `{pathPrefix}/{name}` 请求子应用,子应用看到的是该用户本人。
|
|
364
|
+
|
|
365
|
+
| 参数名 | 类型 | 必填 | 说明 |
|
|
366
|
+
|--------|------|------|------|
|
|
367
|
+
| name | string | 是 | 应用 slug |
|
|
368
|
+
| tenantId | string | 否 | 接口依赖租户时传入 |
|
|
369
|
+
|
|
370
|
+
返回 `{ token, expiresAt }`,`expiresAt` 取自令牌 `exp`(非 JWT 时为 `null`)。应用未运行或未配置 `issueUserAccessToken` 时返回 400。
|
|
371
|
+
|
|
372
|
+
##### GET `{prefix}/app/open-api/records`
|
|
373
|
+
|
|
374
|
+
应用的接口调试记录或用例,按应用共享(不区分用户),不要求应用运行。
|
|
375
|
+
|
|
376
|
+
| 参数名 | 类型 | 必填 | 说明 |
|
|
377
|
+
|--------|------|------|------|
|
|
378
|
+
| name | string | 是 | 应用 slug |
|
|
379
|
+
| type | string | 是 | `history` 调用记录(按创建时间倒序)/ `case` 接口用例(按创建时间正序) |
|
|
380
|
+
| operationKey | string | 否 | 只取该接口的记录(如按接口分页加载用例) |
|
|
381
|
+
| keyword | string | 否 | 按方法、地址、标题、用例名模糊搜索,不区分大小写 |
|
|
382
|
+
| offset | integer | 否 | 跳过条数,默认 0;下拉加载时传已加载条数,新增 / 删除记录后也不会重复或漏取 |
|
|
383
|
+
| limit | integer | 否 | 每次条数(1–100),不传返回全部 |
|
|
384
|
+
|
|
385
|
+
返回 `{ pageData, totalCount }`,`pageData` 为记录原文。
|
|
386
|
+
|
|
387
|
+
##### GET `{prefix}/app/open-api/records/count`
|
|
388
|
+
|
|
389
|
+
按接口统计记录数,参数 `name`、`type`,返回 `{ [operationKey]: count }`(如接口树上的用例数量)。
|
|
390
|
+
|
|
391
|
+
##### POST `{prefix}/app/open-api/records/save`
|
|
392
|
+
|
|
393
|
+
按 `records[].id` 新增或覆盖记录,保存人记为当前登录用户;调用记录超过 1000 条时删除最旧的。
|
|
394
|
+
|
|
395
|
+
| 参数名 | 类型 | 必填 | 说明 |
|
|
396
|
+
|--------|------|------|------|
|
|
397
|
+
| name | string | 是 | 应用 slug |
|
|
398
|
+
| type | string | 是 | `history` 调用记录 / `case` 接口用例 |
|
|
399
|
+
| records | array | 是 | 记录原文,每条须带 `id`,原样保存(如 PostCat `OpenApiView` 的调用记录、用例) |
|
|
400
|
+
|
|
401
|
+
##### POST `{prefix}/app/open-api/records/remove`
|
|
402
|
+
|
|
403
|
+
| 参数名 | 类型 | 必填 | 说明 |
|
|
404
|
+
|--------|------|------|------|
|
|
405
|
+
| name | string | 是 | 应用 slug |
|
|
406
|
+
| type | string | 是 | `history` / `case` |
|
|
407
|
+
| ids | string[] | 否 | 要删除的记录 id |
|
|
408
|
+
| all | boolean | 否 | 为 `true` 时清空该应用该类型的全部记录(忽略 `ids`) |
|
|
409
|
+
|
|
410
|
+
删除应用时一并删除其调试记录与用例。
|
|
411
|
+
|
|
349
412
|
##### 数据运维与表生命周期
|
|
350
413
|
|
|
351
414
|
解析后的应用库:应用 `env` 的 `DB_*` 优先,否则注入 `defaultAppDb`。共享库(未自配 `DB_*`)仅能操作 `options.ownedTables`。
|
|
@@ -809,6 +872,17 @@ data: {"name":"demo","ts":1791456608533,...}
|
|
|
809
872
|
| `getLogHub()` | 获取 EventEmitter |
|
|
810
873
|
| `toPublicApp(app)` / `mountPrefix(name)` | 序列化辅助 |
|
|
811
874
|
|
|
875
|
+
##### services.openApi
|
|
876
|
+
|
|
877
|
+
| 方法签名 | 说明 |
|
|
878
|
+
|----------|------|
|
|
879
|
+
| `getDocument({ name })` | 同 `GET .../app/open-api` |
|
|
880
|
+
| `issueUserToken({ name, userId, tenantId? })` | 同 `POST .../app/open-api/token` |
|
|
881
|
+
| `listRecords({ name, type, operationKey?, keyword?, offset?, limit? })` | 同 `GET .../app/open-api/records` |
|
|
882
|
+
| `countRecords({ name, type })` | 同 `GET .../app/open-api/records/count` |
|
|
883
|
+
| `saveRecords({ name, type, records, userId? })` | 同 `POST .../app/open-api/records/save` |
|
|
884
|
+
| `removeRecords({ name, type, ids?, all? })` | 同 `POST .../app/open-api/records/remove` |
|
|
885
|
+
|
|
812
886
|
##### services.dbops
|
|
813
887
|
|
|
814
888
|
| 方法签名 | 说明 |
|
|
@@ -833,7 +907,7 @@ data: {"name":"demo","ts":1791456608533,...}
|
|
|
833
907
|
| 方法签名 | 说明 |
|
|
834
908
|
|----------|------|
|
|
835
909
|
| `onReady()` | `ensureSchema` 后连接 PM2、挂 log bus、启动日志切分与负载采样定时器,并 **setImmediate** 异步执行 `recoverOnStartup`,以及一次 `rotateLogs` 与一次 `sampleLoad`(不阻塞父应用 ready) |
|
|
836
|
-
| `ensureSchema()` | 宿主 `sync()` 不给已有表加列:为老库补齐后续新增的可空列(当前为 `appVersion.fileId`、`appVersion.migrationFiles`),可重复执行 |
|
|
910
|
+
| `ensureSchema()` | 宿主 `sync()` 不给已有表加列:为老库补齐后续新增的可空列(当前为 `appVersion.fileId`、`appVersion.migrationFiles`、`appVersion.envSchema`、`appOpenApiRecord.searchText`),可重复执行 |
|
|
837
911
|
| `recoverOnStartup()` | 两路并行:部署目录完好的应用立即 `reconcile`;目录缺失的应用逐个 `restoreArtifact`(需重装依赖,较慢),每补完一个即单独 `syncStatus` 并按需拉起;补不回且原为 `running`/`deploying` 的标记 `error`;两路结束后 `pruneAllVersionArtifacts`。返回 `{ reconciled, restored, pruned }` |
|
|
838
912
|
| `onClose()` | 停止切分与采样定时器并等待进行中的任务,断开 bus / PM2(由插件 `onClose` 调用) |
|
|
839
913
|
| `rotateLogs({ now? })` | 立即执行一轮切分 + 压缩 + 保留清理;返回本轮切分的 `[{ name, stream, fileName, reason }]`,`reason` 为 `size` / `daily` |
|
|
@@ -883,6 +957,23 @@ data: {"name":"demo","ts":1791456608533,...}
|
|
|
883
957
|
|
|
884
958
|
唯一约束:`(app_name, version)`。
|
|
885
959
|
|
|
960
|
+
##### appOpenApiRecord
|
|
961
|
+
|
|
962
|
+
应用接口调试记录与用例,按应用共享;删除记录为硬删除。
|
|
963
|
+
|
|
964
|
+
| 属性名 | 类型 | 说明 |
|
|
965
|
+
|--------|------|------|
|
|
966
|
+
| id | string | 雪花主键 |
|
|
967
|
+
| appName | string | 所属应用 name |
|
|
968
|
+
| type | string | `history` 调用记录 / `case` 接口用例 |
|
|
969
|
+
| recordId | string | 前端生成的记录 id |
|
|
970
|
+
| operationKey | string / null | 所属接口 key |
|
|
971
|
+
| data | json | 记录原文 |
|
|
972
|
+
| searchText | text / null | 搜索文本:小写的方法、地址、标题、用例名,保存时生成 |
|
|
973
|
+
| userId | string / null | 最后保存人 |
|
|
974
|
+
|
|
975
|
+
索引:`(app_name, type)`;唯一约束:`(app_name, type, record_id)`。
|
|
976
|
+
|
|
886
977
|
#### 机制说明
|
|
887
978
|
|
|
888
979
|
##### 网关与改写
|
|
@@ -987,7 +1078,10 @@ const appOidc = createAppOidc(fastify, { origin, issuer, serviceAudience });
|
|
|
987
1078
|
fastify.register(require('@kne/fastify-app-manager'), {
|
|
988
1079
|
systemEnvKeys: appOidc.systemEnvKeys,
|
|
989
1080
|
resolveSystemEnv: appOidc.resolveSystemEnv,
|
|
990
|
-
onAppRemoved: appOidc.onAppRemoved
|
|
1081
|
+
onAppRemoved: appOidc.onAppRemoved,
|
|
1082
|
+
// 可选:开启 GET/POST {prefix}/app/open-api(接口文档与在线调试)
|
|
1083
|
+
getOpenApiToken: appOidc.getOpenApiToken,
|
|
1084
|
+
issueUserAccessToken: appOidc.issueUserAccessToken
|
|
991
1085
|
});
|
|
992
1086
|
```
|
|
993
1087
|
|
package/index.js
CHANGED
|
@@ -50,6 +50,10 @@ module.exports = fp(
|
|
|
50
50
|
resolveSystemEnv: null,
|
|
51
51
|
/** async ({ app }) => void,应用删除成功后调用,app 为删除前快照;报错只记日志 */
|
|
52
52
|
onAppRemoved: null,
|
|
53
|
+
/** async app => accessToken,签发读取子应用 /open-api.json 的服务令牌;不传则 /app/open-api 不可用 */
|
|
54
|
+
getOpenApiToken: null,
|
|
55
|
+
/** async ({ app, userId, tenantId }) => accessToken,以登录用户身份签发子应用令牌;不传则 /app/open-api/token 不可用 */
|
|
56
|
+
issueUserAccessToken: null,
|
|
53
57
|
/** async ({ fileId, name, version, request }) => Buffer,版本上传传 fileId 时读取宿主文件 */
|
|
54
58
|
resolveVersionFile: null,
|
|
55
59
|
secretEnvKeyPattern: /(SECRET|PASSWORD|TOKEN|KEY|PRIVATE)/i,
|
package/libs/controllers/app.js
CHANGED
|
@@ -155,6 +155,126 @@ module.exports = fp(async (fastify, options) => {
|
|
|
155
155
|
async request => services.app.getEnvDeclaration(request.query)
|
|
156
156
|
);
|
|
157
157
|
|
|
158
|
+
fastify.get(
|
|
159
|
+
`${options.prefix}/app/open-api`,
|
|
160
|
+
{
|
|
161
|
+
onRequest: auth(),
|
|
162
|
+
schema: {
|
|
163
|
+
summary: '运行中应用的 OpenAPI 文档(子应用 /open-api.json 原文,需配置 getOpenApiToken)',
|
|
164
|
+
query: {
|
|
165
|
+
type: 'object',
|
|
166
|
+
required: ['name'],
|
|
167
|
+
properties: {
|
|
168
|
+
name: { type: 'string' }
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
async request => services.openApi.getDocument(request.query)
|
|
174
|
+
);
|
|
175
|
+
|
|
176
|
+
fastify.post(
|
|
177
|
+
`${options.prefix}/app/open-api/token`,
|
|
178
|
+
{
|
|
179
|
+
onRequest: auth(),
|
|
180
|
+
schema: {
|
|
181
|
+
summary: '以当前登录用户身份签发访问应用接口的令牌,供在线调试(需配置 issueUserAccessToken)',
|
|
182
|
+
body: {
|
|
183
|
+
type: 'object',
|
|
184
|
+
required: ['name'],
|
|
185
|
+
properties: {
|
|
186
|
+
name: { type: 'string' },
|
|
187
|
+
tenantId: { type: 'string' }
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
async request => services.openApi.issueUserToken(Object.assign({}, request.body, { userId: request.userInfo?.id }))
|
|
193
|
+
);
|
|
194
|
+
|
|
195
|
+
fastify.get(
|
|
196
|
+
`${options.prefix}/app/open-api/records`,
|
|
197
|
+
{
|
|
198
|
+
onRequest: auth(),
|
|
199
|
+
schema: {
|
|
200
|
+
summary: '应用接口调试记录或用例(按应用共享;调用记录倒序、最多保留 1000 条;传 limit 时按 offset 分页)',
|
|
201
|
+
query: {
|
|
202
|
+
type: 'object',
|
|
203
|
+
required: ['name', 'type'],
|
|
204
|
+
properties: {
|
|
205
|
+
name: { type: 'string' },
|
|
206
|
+
type: { type: 'string', enum: ['history', 'case'] },
|
|
207
|
+
operationKey: { type: 'string', description: '只取该接口的记录' },
|
|
208
|
+
keyword: { type: 'string', description: '按方法、地址、标题、用例名模糊搜索(不区分大小写)' },
|
|
209
|
+
offset: { type: 'integer', minimum: 0, default: 0 },
|
|
210
|
+
limit: { type: 'integer', minimum: 1, maximum: 100 }
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
},
|
|
215
|
+
async request => services.openApi.listRecords(request.query)
|
|
216
|
+
);
|
|
217
|
+
|
|
218
|
+
fastify.get(
|
|
219
|
+
`${options.prefix}/app/open-api/records/count`,
|
|
220
|
+
{
|
|
221
|
+
onRequest: auth(),
|
|
222
|
+
schema: {
|
|
223
|
+
summary: '按接口统计应用接口调试记录 / 用例数量,返回 { [operationKey]: count }',
|
|
224
|
+
query: {
|
|
225
|
+
type: 'object',
|
|
226
|
+
required: ['name', 'type'],
|
|
227
|
+
properties: {
|
|
228
|
+
name: { type: 'string' },
|
|
229
|
+
type: { type: 'string', enum: ['history', 'case'] }
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
},
|
|
234
|
+
async request => services.openApi.countRecords(request.query)
|
|
235
|
+
);
|
|
236
|
+
|
|
237
|
+
fastify.post(
|
|
238
|
+
`${options.prefix}/app/open-api/records/save`,
|
|
239
|
+
{
|
|
240
|
+
onRequest: auth(),
|
|
241
|
+
schema: {
|
|
242
|
+
summary: '新增或覆盖应用接口调试记录 / 用例(按 records[].id 覆盖)',
|
|
243
|
+
body: {
|
|
244
|
+
type: 'object',
|
|
245
|
+
required: ['name', 'type', 'records'],
|
|
246
|
+
properties: {
|
|
247
|
+
name: { type: 'string' },
|
|
248
|
+
type: { type: 'string', enum: ['history', 'case'] },
|
|
249
|
+
records: { type: 'array', items: { type: 'object', required: ['id'], additionalProperties: true } }
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
},
|
|
254
|
+
async request => services.openApi.saveRecords(Object.assign({}, request.body, { userId: request.userInfo?.id }))
|
|
255
|
+
);
|
|
256
|
+
|
|
257
|
+
fastify.post(
|
|
258
|
+
`${options.prefix}/app/open-api/records/remove`,
|
|
259
|
+
{
|
|
260
|
+
onRequest: auth(),
|
|
261
|
+
schema: {
|
|
262
|
+
summary: '删除应用接口调试记录 / 用例(all=true 时清空该类型全部记录)',
|
|
263
|
+
body: {
|
|
264
|
+
type: 'object',
|
|
265
|
+
required: ['name', 'type'],
|
|
266
|
+
properties: {
|
|
267
|
+
name: { type: 'string' },
|
|
268
|
+
type: { type: 'string', enum: ['history', 'case'] },
|
|
269
|
+
ids: { type: 'array', items: { type: 'string' } },
|
|
270
|
+
all: { type: 'boolean' }
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
},
|
|
275
|
+
async request => services.openApi.removeRecords(request.body)
|
|
276
|
+
);
|
|
277
|
+
|
|
158
278
|
fastify.post(
|
|
159
279
|
`${options.prefix}/app/version/upload`,
|
|
160
280
|
{
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
module.exports = ({ DataTypes }) => {
|
|
2
|
+
return {
|
|
3
|
+
name: 'appOpenApiRecord',
|
|
4
|
+
model: {
|
|
5
|
+
appName: {
|
|
6
|
+
type: DataTypes.STRING,
|
|
7
|
+
allowNull: false,
|
|
8
|
+
comment: '所属应用 name'
|
|
9
|
+
},
|
|
10
|
+
type: {
|
|
11
|
+
type: DataTypes.STRING,
|
|
12
|
+
allowNull: false,
|
|
13
|
+
comment: 'history 调用记录 | case 接口用例'
|
|
14
|
+
},
|
|
15
|
+
recordId: {
|
|
16
|
+
type: DataTypes.STRING,
|
|
17
|
+
allowNull: false,
|
|
18
|
+
comment: '前端生成的记录 id'
|
|
19
|
+
},
|
|
20
|
+
operationKey: {
|
|
21
|
+
type: DataTypes.STRING,
|
|
22
|
+
allowNull: true,
|
|
23
|
+
comment: '所属接口 key(method + path)'
|
|
24
|
+
},
|
|
25
|
+
data: {
|
|
26
|
+
type: DataTypes.JSON,
|
|
27
|
+
allowNull: false,
|
|
28
|
+
comment: '记录原文(请求、响应或用例)'
|
|
29
|
+
},
|
|
30
|
+
searchText: {
|
|
31
|
+
type: DataTypes.TEXT,
|
|
32
|
+
allowNull: true,
|
|
33
|
+
comment: '搜索文本(小写的方法、地址、标题、用例名)'
|
|
34
|
+
},
|
|
35
|
+
userId: {
|
|
36
|
+
type: DataTypes.STRING,
|
|
37
|
+
allowNull: true,
|
|
38
|
+
comment: '最后保存人'
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
options: {
|
|
42
|
+
comment: '应用接口调试记录与用例(按应用共享)',
|
|
43
|
+
indexes: [{ fields: ['app_name', 'type'] }, { unique: true, fields: ['app_name', 'type', 'record_id'] }]
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
};
|
package/libs/services/app.js
CHANGED
|
@@ -1339,6 +1339,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
1339
1339
|
|
|
1340
1340
|
const snapshot = app.toJSON();
|
|
1341
1341
|
await models.appVersion.destroy({ where: { appName: name } });
|
|
1342
|
+
await models.appOpenApiRecord.destroy({ where: { appName: name }, force: true });
|
|
1342
1343
|
await fs.remove(app.rootPath).catch(() => {});
|
|
1343
1344
|
deployProgress.clear(app.name);
|
|
1344
1345
|
await app.destroy();
|
|
@@ -39,14 +39,19 @@ module.exports = fp(async (fastify, options) => {
|
|
|
39
39
|
/** 宿主 sync() 不会给已有表加列:老库升级时补齐后续新增的可空列 */
|
|
40
40
|
const ensureSchema = async () => {
|
|
41
41
|
const { models } = fastify[options.name];
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
for (const
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
42
|
+
const targets = [
|
|
43
|
+
[models.appVersion, ['fileId', 'migrationFiles', 'envSchema']],
|
|
44
|
+
[models.appOpenApiRecord, ['searchText']]
|
|
45
|
+
];
|
|
46
|
+
for (const [model, names] of targets) {
|
|
47
|
+
const queryInterface = model.sequelize.getQueryInterface();
|
|
48
|
+
const table = model.getTableName();
|
|
49
|
+
const columns = await queryInterface.describeTable(table);
|
|
50
|
+
for (const name of names) {
|
|
51
|
+
const attr = model.rawAttributes[name];
|
|
52
|
+
if (!columns[attr.field]) {
|
|
53
|
+
await queryInterface.addColumn(table, attr.field, { type: attr.type, allowNull: true, comment: attr.comment });
|
|
54
|
+
}
|
|
50
55
|
}
|
|
51
56
|
}
|
|
52
57
|
};
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
const fp = require('fastify-plugin');
|
|
2
|
+
|
|
3
|
+
const HISTORY_LIMIT = 1000;
|
|
4
|
+
|
|
5
|
+
module.exports = fp(async (fastify, options) => {
|
|
6
|
+
const getAppService = () => fastify[options.name].services.app;
|
|
7
|
+
|
|
8
|
+
const httpError = (statusCode, message) => {
|
|
9
|
+
if (fastify.httpErrors) {
|
|
10
|
+
if (statusCode === 400) throw fastify.httpErrors.badRequest(message);
|
|
11
|
+
if (statusCode === 502) throw fastify.httpErrors.badGateway(message);
|
|
12
|
+
}
|
|
13
|
+
const err = new Error(message);
|
|
14
|
+
err.statusCode = statusCode;
|
|
15
|
+
throw err;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const getRunningApp = async (name, hook) => {
|
|
19
|
+
if (typeof options[hook] !== 'function') {
|
|
20
|
+
httpError(400, `未配置 ${hook},无法访问子应用接口文档(见 README「应用 OIDC 对接」)`);
|
|
21
|
+
}
|
|
22
|
+
const app = await getAppService().detail({ name });
|
|
23
|
+
if (app.status !== 'running') {
|
|
24
|
+
httpError(400, `应用 ${name} 当前状态为 ${app.status},运行中才能访问接口文档`);
|
|
25
|
+
}
|
|
26
|
+
return app;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** 以 open-api:read 服务令牌读取子应用 /open-api.json,原样返回 */
|
|
30
|
+
const getDocument = async ({ name }) => {
|
|
31
|
+
const app = await getRunningApp(name, 'getOpenApiToken');
|
|
32
|
+
const token = await options.getOpenApiToken(app);
|
|
33
|
+
const response = await fetch(`http://${options.upstreamHost}:${app.port}/open-api.json`, {
|
|
34
|
+
headers: { authorization: `Bearer ${token}` },
|
|
35
|
+
signal: AbortSignal.timeout(15000)
|
|
36
|
+
});
|
|
37
|
+
const isJson = String(response.headers.get('content-type') || '').includes('application/json');
|
|
38
|
+
if (response.status === 404 || (response.ok && !isJson)) {
|
|
39
|
+
httpError(400, `应用 ${name} 未开启 /open-api.json:需 @kne/fastify-app-runtime >=0.1.1、server 最前面注册 @fastify/swagger 且注册了 account 模块`);
|
|
40
|
+
}
|
|
41
|
+
if (response.status === 401) {
|
|
42
|
+
httpError(400, `应用 ${name} 拒绝服务令牌:需将 @kne/fastify-app-runtime 升级到 >=0.1.2 后重新部署`);
|
|
43
|
+
}
|
|
44
|
+
if (!response.ok) {
|
|
45
|
+
httpError(502, `读取应用 ${name} 文档失败:HTTP ${response.status} ${(await response.text()).slice(0, 200)}`);
|
|
46
|
+
}
|
|
47
|
+
return response.json();
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** 以登录用户身份签发访问子应用接口的令牌(在线调试用),返回 { token, expiresAt } */
|
|
51
|
+
const issueUserToken = async ({ name, userId, tenantId }) => {
|
|
52
|
+
if (!userId) {
|
|
53
|
+
httpError(400, '缺少登录用户,无法签发调试令牌');
|
|
54
|
+
}
|
|
55
|
+
const app = await getRunningApp(name, 'issueUserAccessToken');
|
|
56
|
+
const token = await options.issueUserAccessToken({ app, userId, tenantId });
|
|
57
|
+
const { exp } = JSON.parse(Buffer.from(String(token).split('.')[1] || '', 'base64url').toString('utf8') || '{}');
|
|
58
|
+
return { token, expiresAt: exp ? new Date(exp * 1000).toISOString() : null };
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const getRecordModel = () => fastify[options.name].models.appOpenApiRecord;
|
|
62
|
+
|
|
63
|
+
const toSearchText = record => [record.method, record.url || record.path, record.summary, record.name].filter(Boolean).join(' ').toLowerCase();
|
|
64
|
+
|
|
65
|
+
/** 调用记录与用例按应用共享;调用记录按时间倒序、只保留最新 HISTORY_LIMIT 条,用例按时间正序;传 limit 时按 offset 分页 */
|
|
66
|
+
const listRecords = async ({ name, type, operationKey, keyword, offset = 0, limit }) => {
|
|
67
|
+
await getAppService().detail({ name });
|
|
68
|
+
const where = { appName: name, type };
|
|
69
|
+
if (operationKey) {
|
|
70
|
+
where.operationKey = operationKey;
|
|
71
|
+
}
|
|
72
|
+
const search = String(keyword || '')
|
|
73
|
+
.trim()
|
|
74
|
+
.toLowerCase();
|
|
75
|
+
if (search) {
|
|
76
|
+
const { Op } = fastify.sequelize.Sequelize;
|
|
77
|
+
where.searchText = { [Op.like]: `%${search}%` };
|
|
78
|
+
}
|
|
79
|
+
const { rows, count } = await getRecordModel().findAndCountAll({
|
|
80
|
+
where,
|
|
81
|
+
order: [['createdAt', type === 'history' ? 'DESC' : 'ASC']],
|
|
82
|
+
offset,
|
|
83
|
+
limit
|
|
84
|
+
});
|
|
85
|
+
return { pageData: rows.map(row => row.data), totalCount: count };
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
/** 按接口统计记录数,返回 { [operationKey]: count } */
|
|
89
|
+
const countRecords = async ({ name, type }) => {
|
|
90
|
+
await getAppService().detail({ name });
|
|
91
|
+
const { fn, col } = fastify.sequelize.Sequelize;
|
|
92
|
+
const rows = await getRecordModel().findAll({
|
|
93
|
+
where: { appName: name, type },
|
|
94
|
+
attributes: ['operationKey', [fn('COUNT', col('id')), 'count']],
|
|
95
|
+
group: ['operationKey'],
|
|
96
|
+
raw: true
|
|
97
|
+
});
|
|
98
|
+
return rows.reduce((output, row) => Object.assign(output, { [row.operationKey || '']: Number(row.count) }), {});
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const saveRecords = async ({ name, type, records = [], userId }) => {
|
|
102
|
+
await getAppService().detail({ name });
|
|
103
|
+
for (const record of records) {
|
|
104
|
+
const recordId = record && record.id && String(record.id);
|
|
105
|
+
if (!recordId) {
|
|
106
|
+
httpError(400, '记录缺少 id');
|
|
107
|
+
}
|
|
108
|
+
const values = {
|
|
109
|
+
appName: name,
|
|
110
|
+
type,
|
|
111
|
+
recordId,
|
|
112
|
+
operationKey: record.operationKey || null,
|
|
113
|
+
data: record,
|
|
114
|
+
searchText: toSearchText(record),
|
|
115
|
+
userId: userId ? String(userId) : null
|
|
116
|
+
};
|
|
117
|
+
const row = await getRecordModel().findOne({ where: { appName: name, type, recordId } });
|
|
118
|
+
row ? await row.update(values) : await getRecordModel().create(values);
|
|
119
|
+
}
|
|
120
|
+
if (type === 'history') {
|
|
121
|
+
const stale = await getRecordModel().findAll({
|
|
122
|
+
where: { appName: name, type },
|
|
123
|
+
attributes: ['id'],
|
|
124
|
+
order: [['createdAt', 'DESC']],
|
|
125
|
+
offset: HISTORY_LIMIT
|
|
126
|
+
});
|
|
127
|
+
stale.length && (await getRecordModel().destroy({ where: { id: stale.map(row => row.id) }, force: true }));
|
|
128
|
+
}
|
|
129
|
+
return {};
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
/** all 为 true 时清空该应用该类型的全部记录,否则按 ids 删除 */
|
|
133
|
+
const removeRecords = async ({ name, type, ids = [], all = false }) => {
|
|
134
|
+
if (all) {
|
|
135
|
+
await getRecordModel().destroy({ where: { appName: name, type }, force: true });
|
|
136
|
+
} else if (ids.length) {
|
|
137
|
+
await getRecordModel().destroy({ where: { appName: name, type, recordId: ids.map(String) }, force: true });
|
|
138
|
+
}
|
|
139
|
+
return {};
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
Object.assign(fastify[options.name].services, {
|
|
143
|
+
openApi: { getDocument, issueUserToken, listRecords, countRecords, saveRecords, removeRecords }
|
|
144
|
+
});
|
|
145
|
+
});
|