@kne/fastify-app-manager 0.1.22 → 0.1.24
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 +112 -6
- package/index.js +19 -0
- package/libs/controllers/app.js +122 -2
- package/libs/models/appOpenApiRecord.js +46 -0
- package/libs/services/app.js +4 -3
- package/libs/services/bootstrap.js +13 -8
- package/libs/services/openApi.js +145 -0
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -203,12 +203,17 @@ 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 最大返回行数 |
|
|
209
211
|
| `pm2Defaults` | object | 否 | 见下表 | 全局 PM2 默认;可被应用 `pm2Config` 覆盖 |
|
|
210
212
|
| `createAuthenticate` | function | 否 | 见说明 | 返回 `onRequest` 钩子数组;默认 `fastify.account.authenticate.user` + `admin` |
|
|
211
213
|
| `createUserAuthenticate` | function | 否 | 见说明 | 应用中心等普通用户接口的 `onRequest` 钩子数组;默认尝试 `fastify.account.authenticate.user` |
|
|
214
|
+
| `enableGroup` | boolean | 否 | `true` | 是否在插件内部注册 `@kne/fastify-group` 提供应用分类接口;宿主已有分组服务时可设为 `false` |
|
|
215
|
+
| `groupName` | string | 否 | `'appManagerGroup'` | 内部分组插件的命名空间(`fastify[groupName]`),与宿主自己注册的 `group` 区分 |
|
|
216
|
+
| `groupDbTableNamePrefix` | string | 否 | `'t_'` | 分组表前缀,表名为前缀 + `snakeCase(groupName + 'Tag')`,默认 `t_app_manager_group_tag` |
|
|
212
217
|
| `upstreamHost` | string | 否 | `'127.0.0.1'` | 子应用进程监听地址:网关转发、WebSocket、就绪探测、端口探测与 `resolveSystemEnv` 的 `upstreamUrl` 共用 |
|
|
213
218
|
| `healthCheckPath` | string | 否 | `'/'` | 部署后就绪探测路径 |
|
|
214
219
|
| `healthCheckTimeoutMs` | number | 否 | `30000` | 探测总超时(毫秒) |
|
|
@@ -274,7 +279,7 @@ await fastify.listen({ port: 3000 });
|
|
|
274
279
|
| description | string | 否 | - | 描述 |
|
|
275
280
|
| category | object / string | 否 | - | 应用分类(应用中心分组用),写入 `options.category`;推荐传 fastify-group 分组对象,对象只保留 `{ code, name }`,字符串原样保存 |
|
|
276
281
|
| isPublic | boolean | 否 | `true` | 是否在公开应用中心展示,写入 `options.isPublic`;未设置视为公开 |
|
|
277
|
-
| entries | array | 否 | `[]` | 应用入口 `[{ label, path }]`,写入 `options.entries`;`path` 相对应用根(缺前导 `/` 自动补),缺 `label` 或 `path` 的项丢弃,同 `path`
|
|
282
|
+
| entries | array | 否 | `[]` | 应用入口 `[{ label, path, showInCenter }]`,写入 `options.entries`;`path` 相对应用根(缺前导 `/` 自动补),缺 `label` 或 `path` 的项丢弃,同 `path` 只保留第一项;`showInCenter` 为是否开放给前台(默认 `true`),为 `false` 时应用中心列表与 PWA 不返回该入口,管理端仍可见 |
|
|
278
283
|
| env | object | 否 | `{}` | 应用自有环境变量 |
|
|
279
284
|
| pm2Config | object | 否 | `{}` | PM2 覆盖项 |
|
|
280
285
|
| options | object | 否 | `{}` | 扩展字段;可含 `secretEnvKeys: string[]` 显式密钥键名 |
|
|
@@ -346,6 +351,67 @@ await fastify.listen({ port: 3000 });
|
|
|
346
351
|
- 两者都**不含应用中心注入的变量**(见 `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
352
|
- 版本没有 schema 时 `hasSchema=false`、`declared=[]`,该版本无法部署。
|
|
348
353
|
|
|
354
|
+
##### GET `{prefix}/app/open-api`
|
|
355
|
+
|
|
356
|
+
运行中应用的 OpenAPI 文档:用 `getOpenApiToken` 签发的服务令牌请求子应用 `http://{upstreamHost}:{port}/open-api.json`,原样返回 JSON。
|
|
357
|
+
|
|
358
|
+
| 参数名 | 类型 | 必填 | 说明 |
|
|
359
|
+
|--------|------|------|------|
|
|
360
|
+
| name | string | 是 | 应用 slug |
|
|
361
|
+
|
|
362
|
+
应用未运行、未配置 `getOpenApiToken`、子应用未开启 `/open-api.json`(需 `@kne/fastify-app-runtime` >=0.1.1)或拒绝服务令牌(需 >=0.1.2)时返回 400,其它上游错误返回 502。
|
|
363
|
+
|
|
364
|
+
##### POST `{prefix}/app/open-api/token`
|
|
365
|
+
|
|
366
|
+
以当前登录用户(`request.userInfo.id`)身份调用 `issueUserAccessToken` 签发访问该应用接口的令牌,供管理端在线调试:前端带 `Authorization: Bearer {token}` 经网关 `{pathPrefix}/{name}` 请求子应用,子应用看到的是该用户本人。
|
|
367
|
+
|
|
368
|
+
| 参数名 | 类型 | 必填 | 说明 |
|
|
369
|
+
|--------|------|------|------|
|
|
370
|
+
| name | string | 是 | 应用 slug |
|
|
371
|
+
| tenantId | string | 否 | 接口依赖租户时传入 |
|
|
372
|
+
|
|
373
|
+
返回 `{ token, expiresAt }`,`expiresAt` 取自令牌 `exp`(非 JWT 时为 `null`)。应用未运行或未配置 `issueUserAccessToken` 时返回 400。
|
|
374
|
+
|
|
375
|
+
##### GET `{prefix}/app/open-api/records`
|
|
376
|
+
|
|
377
|
+
应用的接口调试记录或用例,按应用共享(不区分用户),不要求应用运行。
|
|
378
|
+
|
|
379
|
+
| 参数名 | 类型 | 必填 | 说明 |
|
|
380
|
+
|--------|------|------|------|
|
|
381
|
+
| name | string | 是 | 应用 slug |
|
|
382
|
+
| type | string | 是 | `history` 调用记录(按创建时间倒序)/ `case` 接口用例(按创建时间正序) |
|
|
383
|
+
| operationKey | string | 否 | 只取该接口的记录(如按接口分页加载用例) |
|
|
384
|
+
| keyword | string | 否 | 按方法、地址、标题、用例名模糊搜索,不区分大小写 |
|
|
385
|
+
| offset | integer | 否 | 跳过条数,默认 0;下拉加载时传已加载条数,新增 / 删除记录后也不会重复或漏取 |
|
|
386
|
+
| limit | integer | 否 | 每次条数(1–100),不传返回全部 |
|
|
387
|
+
|
|
388
|
+
返回 `{ pageData, totalCount }`,`pageData` 为记录原文。
|
|
389
|
+
|
|
390
|
+
##### GET `{prefix}/app/open-api/records/count`
|
|
391
|
+
|
|
392
|
+
按接口统计记录数,参数 `name`、`type`,返回 `{ [operationKey]: count }`(如接口树上的用例数量)。
|
|
393
|
+
|
|
394
|
+
##### POST `{prefix}/app/open-api/records/save`
|
|
395
|
+
|
|
396
|
+
按 `records[].id` 新增或覆盖记录,保存人记为当前登录用户;调用记录超过 1000 条时删除最旧的。
|
|
397
|
+
|
|
398
|
+
| 参数名 | 类型 | 必填 | 说明 |
|
|
399
|
+
|--------|------|------|------|
|
|
400
|
+
| name | string | 是 | 应用 slug |
|
|
401
|
+
| type | string | 是 | `history` 调用记录 / `case` 接口用例 |
|
|
402
|
+
| records | array | 是 | 记录原文,每条须带 `id`,原样保存(如 PostCat `OpenApiView` 的调用记录、用例) |
|
|
403
|
+
|
|
404
|
+
##### POST `{prefix}/app/open-api/records/remove`
|
|
405
|
+
|
|
406
|
+
| 参数名 | 类型 | 必填 | 说明 |
|
|
407
|
+
|--------|------|------|------|
|
|
408
|
+
| name | string | 是 | 应用 slug |
|
|
409
|
+
| type | string | 是 | `history` / `case` |
|
|
410
|
+
| ids | string[] | 否 | 要删除的记录 id |
|
|
411
|
+
| all | boolean | 否 | 为 `true` 时清空该应用该类型的全部记录(忽略 `ids`) |
|
|
412
|
+
|
|
413
|
+
删除应用时一并删除其调试记录与用例。
|
|
414
|
+
|
|
349
415
|
##### 数据运维与表生命周期
|
|
350
416
|
|
|
351
417
|
解析后的应用库:应用 `env` 的 `DB_*` 优先,否则注入 `defaultAppDb`。共享库(未自配 `DB_*`)仅能操作 `options.ownedTables`。
|
|
@@ -543,6 +609,13 @@ data: {"progressId":"p-1","step":"ready","status":"done","detail":null,"message"
|
|
|
543
609
|
|
|
544
610
|
返回 `{ pageData, totalCount }`,元素均为脱敏后的应用对象。
|
|
545
611
|
|
|
612
|
+
##### 应用分类 `{prefix}/group/*`
|
|
613
|
+
|
|
614
|
+
`enableGroup` 不为 `false` 时,插件内部注册 `@kne/fastify-group`,接口与其一致:`GET group/list`、`GET group/group-list`、`GET group/detail`、`POST group/save`、`POST group/remove`。应用分类使用 `type: 'app'`。
|
|
615
|
+
|
|
616
|
+
- 读接口(`list` / `group-list` / `detail`)**无需登录**,未登录的公开应用中心也能显示分类名称
|
|
617
|
+
- 写接口(`save` / `remove`)使用 `createAuthenticate` 鉴权
|
|
618
|
+
|
|
546
619
|
##### GET `{prefix}/app/center/list`
|
|
547
620
|
|
|
548
621
|
应用中心列表,使用 `createUserAuthenticate` 鉴权(普通登录用户可访问)。仅返回 `status: 'running'` 的应用,且只含公开字段(不含 env、端口、路径等)。
|
|
@@ -559,8 +632,8 @@ data: {"progressId":"p-1","step":"ready","status":"done","detail":null,"message"
|
|
|
559
632
|
"isPublic": true,
|
|
560
633
|
"pathUrl": "/app/demo/",
|
|
561
634
|
"entries": [
|
|
562
|
-
{ "label": "PC", "path": "/", "url": "/app/demo/" },
|
|
563
|
-
{ "label": "移动端", "path": "/mobile", "url": "/app/demo/mobile" }
|
|
635
|
+
{ "label": "PC", "path": "/", "showInCenter": true, "url": "/app/demo/" },
|
|
636
|
+
{ "label": "移动端", "path": "/mobile", "showInCenter": true, "url": "/app/demo/mobile" }
|
|
564
637
|
],
|
|
565
638
|
"deployment": null
|
|
566
639
|
}
|
|
@@ -569,6 +642,8 @@ data: {"progressId":"p-1","step":"ready","status":"done","detail":null,"message"
|
|
|
569
642
|
}
|
|
570
643
|
```
|
|
571
644
|
|
|
645
|
+
`entries` 只含 `showInCenter` 不为 `false` 的入口。
|
|
646
|
+
|
|
572
647
|
`deployment`:部署或启动补回部署目录进行中时为 `{ source: 'deploy' | 'restore' }`,此时应用暂不可访问;否则为 `null`。
|
|
573
648
|
|
|
574
649
|
##### GET `{prefix}/app/center/public-list`
|
|
@@ -809,6 +884,17 @@ data: {"name":"demo","ts":1791456608533,...}
|
|
|
809
884
|
| `getLogHub()` | 获取 EventEmitter |
|
|
810
885
|
| `toPublicApp(app)` / `mountPrefix(name)` | 序列化辅助 |
|
|
811
886
|
|
|
887
|
+
##### services.openApi
|
|
888
|
+
|
|
889
|
+
| 方法签名 | 说明 |
|
|
890
|
+
|----------|------|
|
|
891
|
+
| `getDocument({ name })` | 同 `GET .../app/open-api` |
|
|
892
|
+
| `issueUserToken({ name, userId, tenantId? })` | 同 `POST .../app/open-api/token` |
|
|
893
|
+
| `listRecords({ name, type, operationKey?, keyword?, offset?, limit? })` | 同 `GET .../app/open-api/records` |
|
|
894
|
+
| `countRecords({ name, type })` | 同 `GET .../app/open-api/records/count` |
|
|
895
|
+
| `saveRecords({ name, type, records, userId? })` | 同 `POST .../app/open-api/records/save` |
|
|
896
|
+
| `removeRecords({ name, type, ids?, all? })` | 同 `POST .../app/open-api/records/remove` |
|
|
897
|
+
|
|
812
898
|
##### services.dbops
|
|
813
899
|
|
|
814
900
|
| 方法签名 | 说明 |
|
|
@@ -833,7 +919,7 @@ data: {"name":"demo","ts":1791456608533,...}
|
|
|
833
919
|
| 方法签名 | 说明 |
|
|
834
920
|
|----------|------|
|
|
835
921
|
| `onReady()` | `ensureSchema` 后连接 PM2、挂 log bus、启动日志切分与负载采样定时器,并 **setImmediate** 异步执行 `recoverOnStartup`,以及一次 `rotateLogs` 与一次 `sampleLoad`(不阻塞父应用 ready) |
|
|
836
|
-
| `ensureSchema()` | 宿主 `sync()` 不给已有表加列:为老库补齐后续新增的可空列(当前为 `appVersion.fileId`、`appVersion.migrationFiles`),可重复执行 |
|
|
922
|
+
| `ensureSchema()` | 宿主 `sync()` 不给已有表加列:为老库补齐后续新增的可空列(当前为 `appVersion.fileId`、`appVersion.migrationFiles`、`appVersion.envSchema`、`appOpenApiRecord.searchText`),可重复执行 |
|
|
837
923
|
| `recoverOnStartup()` | 两路并行:部署目录完好的应用立即 `reconcile`;目录缺失的应用逐个 `restoreArtifact`(需重装依赖,较慢),每补完一个即单独 `syncStatus` 并按需拉起;补不回且原为 `running`/`deploying` 的标记 `error`;两路结束后 `pruneAllVersionArtifacts`。返回 `{ reconciled, restored, pruned }` |
|
|
838
924
|
| `onClose()` | 停止切分与采样定时器并等待进行中的任务,断开 bus / PM2(由插件 `onClose` 调用) |
|
|
839
925
|
| `rotateLogs({ now? })` | 立即执行一轮切分 + 压缩 + 保留清理;返回本轮切分的 `[{ name, stream, fileName, reason }]`,`reason` 为 `size` / `daily` |
|
|
@@ -856,7 +942,7 @@ data: {"name":"demo","ts":1791456608533,...}
|
|
|
856
942
|
| description | string / null | 描述 |
|
|
857
943
|
| env | object | 自有环境变量 |
|
|
858
944
|
| pm2Config | object | PM2 覆盖 |
|
|
859
|
-
| options | object | 扩展字段;`secretEnvKeys` 为显式密钥键名列表,`category` 为应用分类,`isPublic` 为是否公开(未设置视为公开),`entries` 为应用入口 `[{ label, path }]` |
|
|
945
|
+
| options | object | 扩展字段;`secretEnvKeys` 为显式密钥键名列表,`category` 为应用分类,`isPublic` 为是否公开(未设置视为公开),`entries` 为应用入口 `[{ label, path, showInCenter }]` |
|
|
860
946
|
| port | number | 分配端口 |
|
|
861
947
|
| status | string | `idle` / `deploying` / `running` / `stopped` / `error` |
|
|
862
948
|
| currentVersionId | string / null | 当前部署版本 id |
|
|
@@ -883,6 +969,23 @@ data: {"name":"demo","ts":1791456608533,...}
|
|
|
883
969
|
|
|
884
970
|
唯一约束:`(app_name, version)`。
|
|
885
971
|
|
|
972
|
+
##### appOpenApiRecord
|
|
973
|
+
|
|
974
|
+
应用接口调试记录与用例,按应用共享;删除记录为硬删除。
|
|
975
|
+
|
|
976
|
+
| 属性名 | 类型 | 说明 |
|
|
977
|
+
|--------|------|------|
|
|
978
|
+
| id | string | 雪花主键 |
|
|
979
|
+
| appName | string | 所属应用 name |
|
|
980
|
+
| type | string | `history` 调用记录 / `case` 接口用例 |
|
|
981
|
+
| recordId | string | 前端生成的记录 id |
|
|
982
|
+
| operationKey | string / null | 所属接口 key |
|
|
983
|
+
| data | json | 记录原文 |
|
|
984
|
+
| searchText | text / null | 搜索文本:小写的方法、地址、标题、用例名,保存时生成 |
|
|
985
|
+
| userId | string / null | 最后保存人 |
|
|
986
|
+
|
|
987
|
+
索引:`(app_name, type)`;唯一约束:`(app_name, type, record_id)`。
|
|
988
|
+
|
|
886
989
|
#### 机制说明
|
|
887
990
|
|
|
888
991
|
##### 网关与改写
|
|
@@ -987,7 +1090,10 @@ const appOidc = createAppOidc(fastify, { origin, issuer, serviceAudience });
|
|
|
987
1090
|
fastify.register(require('@kne/fastify-app-manager'), {
|
|
988
1091
|
systemEnvKeys: appOidc.systemEnvKeys,
|
|
989
1092
|
resolveSystemEnv: appOidc.resolveSystemEnv,
|
|
990
|
-
onAppRemoved: appOidc.onAppRemoved
|
|
1093
|
+
onAppRemoved: appOidc.onAppRemoved,
|
|
1094
|
+
// 可选:开启 GET/POST {prefix}/app/open-api(接口文档与在线调试)
|
|
1095
|
+
getOpenApiToken: appOidc.getOpenApiToken,
|
|
1096
|
+
issueUserAccessToken: appOidc.issueUserAccessToken
|
|
991
1097
|
});
|
|
992
1098
|
```
|
|
993
1099
|
|
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,
|
|
@@ -83,6 +87,11 @@ module.exports = fp(
|
|
|
83
87
|
}
|
|
84
88
|
return [];
|
|
85
89
|
},
|
|
90
|
+
/** 应用分类:插件内部注册 @kne/fastify-group,宿主已有分组服务时可关闭 */
|
|
91
|
+
enableGroup: true,
|
|
92
|
+
groupName: 'appManagerGroup',
|
|
93
|
+
/** 表名 = 前缀 + snakeCase(groupName + Tag),默认 t_app_manager_group_tag */
|
|
94
|
+
groupDbTableNamePrefix: 't_',
|
|
86
95
|
/** 普通登录用户可访问的接口(应用中心列表) */
|
|
87
96
|
createUserAuthenticate: () => {
|
|
88
97
|
if (fastify.account?.authenticate?.user) {
|
|
@@ -125,6 +134,16 @@ module.exports = fp(
|
|
|
125
134
|
options.createAuthenticate = withQueryToken(options.createAuthenticate);
|
|
126
135
|
options.createUserAuthenticate = withQueryToken(options.createUserAuthenticate);
|
|
127
136
|
|
|
137
|
+
// 分类读取需对未登录的公开应用中心开放,增删改沿用管理端鉴权
|
|
138
|
+
if (options.enableGroup !== false) {
|
|
139
|
+
await fastify.register(require('@kne/fastify-group'), {
|
|
140
|
+
name: options.groupName,
|
|
141
|
+
prefix: `${options.prefix}/group`,
|
|
142
|
+
dbTableNamePrefix: options.groupDbTableNamePrefix,
|
|
143
|
+
getAuthenticate: type => (type === 'read' ? [] : options.createAuthenticate())
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
128
147
|
// 宿主可能已注册(如 fastify-file-manager),重复注册会报错
|
|
129
148
|
if (!fastify.hasDecorator('multipartErrors')) {
|
|
130
149
|
await fastify.register(require('@fastify/multipart'), {
|
package/libs/controllers/app.js
CHANGED
|
@@ -30,7 +30,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
30
30
|
isPublic: { type: 'boolean' },
|
|
31
31
|
entries: {
|
|
32
32
|
type: ['array', 'null'],
|
|
33
|
-
items: { type: 'object', properties: { label: { type: 'string' }, path: { type: 'string' } } }
|
|
33
|
+
items: { type: 'object', properties: { label: { type: 'string' }, path: { type: 'string' }, showInCenter: { type: 'boolean' } } }
|
|
34
34
|
},
|
|
35
35
|
env: { type: 'object' },
|
|
36
36
|
pm2Config: { type: 'object' },
|
|
@@ -61,7 +61,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
61
61
|
isPublic: { type: 'boolean' },
|
|
62
62
|
entries: {
|
|
63
63
|
type: ['array', 'null'],
|
|
64
|
-
items: { type: 'object', properties: { label: { type: 'string' }, path: { type: 'string' } } }
|
|
64
|
+
items: { type: 'object', properties: { label: { type: 'string' }, path: { type: 'string' }, showInCenter: { type: 'boolean' } } }
|
|
65
65
|
},
|
|
66
66
|
env: { type: 'object' },
|
|
67
67
|
pm2Config: { type: 'object' },
|
|
@@ -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
|
@@ -62,7 +62,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
62
62
|
}
|
|
63
63
|
return category.code ? { code: category.code, name: category.name || category.code } : null;
|
|
64
64
|
};
|
|
65
|
-
// 应用入口:label + 相对应用根的 path;去空、补前导 /、按 path
|
|
65
|
+
// 应用入口:label + 相对应用根的 path;去空、补前导 /、按 path 去重;showInCenter 未设置视为开放给前台
|
|
66
66
|
const normalizeEntries = entries => {
|
|
67
67
|
const seen = new Set();
|
|
68
68
|
return (Array.isArray(entries) ? entries : []).reduce((result, item) => {
|
|
@@ -74,7 +74,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
74
74
|
const entryPath = rawPath.startsWith('/') ? rawPath : `/${rawPath}`;
|
|
75
75
|
if (!seen.has(entryPath)) {
|
|
76
76
|
seen.add(entryPath);
|
|
77
|
-
result.push({ label, path: entryPath });
|
|
77
|
+
result.push({ label, path: entryPath, showInCenter: item?.showInCenter !== false });
|
|
78
78
|
}
|
|
79
79
|
return result;
|
|
80
80
|
}, []);
|
|
@@ -266,7 +266,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
266
266
|
category: app.options?.category || null,
|
|
267
267
|
isPublic: isAppPublic(app),
|
|
268
268
|
pathUrl: `${mountPrefix(app.name)}/`,
|
|
269
|
-
entries: resolveEntries(app),
|
|
269
|
+
entries: resolveEntries(app).filter(entry => entry.showInCenter),
|
|
270
270
|
deployment: active ? { source: active.source } : null
|
|
271
271
|
};
|
|
272
272
|
});
|
|
@@ -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
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kne/fastify-app-manager",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.24",
|
|
4
4
|
"description": "Fastify 单机应用市场插件:版本上传、PM2 托管、路径/域名反代与日志 SSE",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|
|
@@ -75,6 +75,7 @@
|
|
|
75
75
|
"@fastify/multipart": "^10.1.1",
|
|
76
76
|
"@fastify/reply-from": "^12.6.5",
|
|
77
77
|
"@kne/ensure-slash": "^0.1.0",
|
|
78
|
+
"@kne/fastify-group": "^0.2.6",
|
|
78
79
|
"@kne/pwa-document": "^0.1.0",
|
|
79
80
|
"adm-zip": "^0.6.0",
|
|
80
81
|
"ajv": "^8.17.1",
|