@kne/fastify-app-manager 0.1.21 → 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 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`。
@@ -501,7 +564,7 @@ data: {"progressId":"p-1","step":"ready","status":"done","detail":null,"message"
501
564
 
502
565
  ##### 部署记录
503
566
 
504
- 每次部署(含父应用启动时补回部署目录,`source: 'restore'`)都会落库,每个应用保留最近 `deployRecordKeep` 条。父应用重启时,未结束的记录标为 `failed`(`message: deploy interrupted: app manager restarted`)。应用详情返回 `deployment`(进行中的部署,无则 `null`)与 `lastDeployment`(最近一次部署记录摘要)。
567
+ 每次部署(含父应用启动时补回部署目录,`source: 'restore'`;需补回的应用启动时即全部登记,排队中的也带 `deployment`)都会落库,每个应用保留最近 `deployRecordKeep` 条。父应用重启时,未结束的记录标为 `failed`(`message: deploy interrupted: app manager restarted`)。应用详情返回 `deployment`(进行中的部署,无则 `null`)与 `lastDeployment`(最近一次部署记录摘要)。
505
568
 
506
569
  | 方法 | 路径 | 参数 | 说明 |
507
570
  |------|------|------|------|
@@ -561,13 +624,16 @@ data: {"progressId":"p-1","step":"ready","status":"done","detail":null,"message"
561
624
  "entries": [
562
625
  { "label": "PC", "path": "/", "url": "/app/demo/" },
563
626
  { "label": "移动端", "path": "/mobile", "url": "/app/demo/mobile" }
564
- ]
627
+ ],
628
+ "deployment": null
565
629
  }
566
630
  ],
567
631
  "totalCount": 1
568
632
  }
569
633
  ```
570
634
 
635
+ `deployment`:部署或启动补回部署目录进行中时为 `{ source: 'deploy' | 'restore' }`,此时应用暂不可访问;否则为 `null`。
636
+
571
637
  ##### GET `{prefix}/app/center/public-list`
572
638
 
573
639
  公开应用中心列表,**无需登录**。返回结构同 `app/center/list`,仅包含运行中且 `isPublic` 不为 `false` 的应用。
@@ -587,7 +653,7 @@ data: {"progressId":"p-1","step":"ready","status":"done","detail":null,"message"
587
653
  |--------|------|------|------|
588
654
  | name | string | 是 | 应用 slug |
589
655
 
590
- 返回脱敏后的应用对象,另带 `deployment`:最近一次部署尚未结束(未出错、就绪阶段未完成)时为 `{ progressId, versionId, version, startedAt, step, detail }`,否则为 `null`。准备部署包阶段应用仍是旧的 `status` 与 `currentVersionId`,用它判断哪个版本正在部署。`app/list` 的每个元素同样带该字段。
656
+ 返回脱敏后的应用对象,另带 `deployment`:最近一次部署尚未结束(未出错、就绪阶段未完成)时为 `{ progressId, versionId, version, source, startedAt, step, detail }`(`source`:`deploy` 手动部署 / `restore` 启动补回,补回排队中 `step` 为 `null`),否则为 `null`。准备部署包阶段应用仍是旧的 `status` 与 `currentVersionId`,用它判断哪个版本正在部署。`app/list` 的每个元素同样带该字段。
591
657
 
592
658
  详情另带 `pm2Defaults`:宿主生效的全局 PM2 默认(即插件选项 `pm2Defaults`),供管理端展示应用 `pm2Config` 未覆盖项的实际取值。
593
659
 
@@ -806,6 +872,17 @@ data: {"name":"demo","ts":1791456608533,...}
806
872
  | `getLogHub()` | 获取 EventEmitter |
807
873
  | `toPublicApp(app)` / `mountPrefix(name)` | 序列化辅助 |
808
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
+
809
886
  ##### services.dbops
810
887
 
811
888
  | 方法签名 | 说明 |
@@ -830,7 +907,7 @@ data: {"name":"demo","ts":1791456608533,...}
830
907
  | 方法签名 | 说明 |
831
908
  |----------|------|
832
909
  | `onReady()` | `ensureSchema` 后连接 PM2、挂 log bus、启动日志切分与负载采样定时器,并 **setImmediate** 异步执行 `recoverOnStartup`,以及一次 `rotateLogs` 与一次 `sampleLoad`(不阻塞父应用 ready) |
833
- | `ensureSchema()` | 宿主 `sync()` 不给已有表加列:为老库补齐后续新增的可空列(当前为 `appVersion.fileId`、`appVersion.migrationFiles`),可重复执行 |
910
+ | `ensureSchema()` | 宿主 `sync()` 不给已有表加列:为老库补齐后续新增的可空列(当前为 `appVersion.fileId`、`appVersion.migrationFiles`、`appVersion.envSchema`、`appOpenApiRecord.searchText`),可重复执行 |
834
911
  | `recoverOnStartup()` | 两路并行:部署目录完好的应用立即 `reconcile`;目录缺失的应用逐个 `restoreArtifact`(需重装依赖,较慢),每补完一个即单独 `syncStatus` 并按需拉起;补不回且原为 `running`/`deploying` 的标记 `error`;两路结束后 `pruneAllVersionArtifacts`。返回 `{ reconciled, restored, pruned }` |
835
912
  | `onClose()` | 停止切分与采样定时器并等待进行中的任务,断开 bus / PM2(由插件 `onClose` 调用) |
836
913
  | `rotateLogs({ now? })` | 立即执行一轮切分 + 压缩 + 保留清理;返回本轮切分的 `[{ name, stream, fileName, reason }]`,`reason` 为 `size` / `daily` |
@@ -880,6 +957,23 @@ data: {"name":"demo","ts":1791456608533,...}
880
957
 
881
958
  唯一约束:`(app_name, version)`。
882
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
+
883
977
  #### 机制说明
884
978
 
885
979
  ##### 网关与改写
@@ -984,7 +1078,10 @@ const appOidc = createAppOidc(fastify, { origin, issuer, serviceAudience });
984
1078
  fastify.register(require('@kne/fastify-app-manager'), {
985
1079
  systemEnvKeys: appOidc.systemEnvKeys,
986
1080
  resolveSystemEnv: appOidc.resolveSystemEnv,
987
- onAppRemoved: appOidc.onAppRemoved
1081
+ onAppRemoved: appOidc.onAppRemoved,
1082
+ // 可选:开启 GET/POST {prefix}/app/open-api(接口文档与在线调试)
1083
+ getOpenApiToken: appOidc.getOpenApiToken,
1084
+ issueUserAccessToken: appOidc.issueUserAccessToken
988
1085
  });
989
1086
  ```
990
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,
@@ -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
+ };
@@ -256,16 +256,20 @@ module.exports = fp(async (fastify, options) => {
256
256
  const rows = await models.app.findAll({ where: { status: 'running' }, order: [['createdAt', 'DESC']] });
257
257
  const pageData = rows
258
258
  .filter(app => !publicOnly || isAppPublic(app))
259
- .map(app => ({
260
- name: app.name,
261
- label: app.label,
262
- icon: app.icon,
263
- description: app.description,
264
- category: app.options?.category || null,
265
- isPublic: isAppPublic(app),
266
- pathUrl: `${mountPrefix(app.name)}/`,
267
- entries: resolveEntries(app)
268
- }));
259
+ .map(app => {
260
+ const active = deployProgress.active(app.name);
261
+ return {
262
+ name: app.name,
263
+ label: app.label,
264
+ icon: app.icon,
265
+ description: app.description,
266
+ category: app.options?.category || null,
267
+ isPublic: isAppPublic(app),
268
+ pathUrl: `${mountPrefix(app.name)}/`,
269
+ entries: resolveEntries(app),
270
+ deployment: active ? { source: active.source } : null
271
+ };
272
+ });
269
273
  return { pageData, totalCount: pageData.length };
270
274
  };
271
275
 
@@ -1335,6 +1339,7 @@ module.exports = fp(async (fastify, options) => {
1335
1339
 
1336
1340
  const snapshot = app.toJSON();
1337
1341
  await models.appVersion.destroy({ where: { appName: name } });
1342
+ await models.appOpenApiRecord.destroy({ where: { appName: name }, force: true });
1338
1343
  await fs.remove(app.rootPath).catch(() => {});
1339
1344
  deployProgress.clear(app.name);
1340
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 model = models.appVersion;
43
- const queryInterface = model.sequelize.getQueryInterface();
44
- const table = model.getTableName();
45
- const columns = await queryInterface.describeTable(table);
46
- for (const name of ['fileId', 'migrationFiles', 'envSchema']) {
47
- const attr = model.rawAttributes[name];
48
- if (!columns[attr.field]) {
49
- await queryInterface.addColumn(table, attr.field, { type: attr.type, allowNull: true, comment: attr.comment });
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
  };
@@ -132,14 +137,26 @@ module.exports = fp(async (fastify, options) => {
132
137
  return [];
133
138
  };
134
139
 
135
- /** 逐个补回缺失的部署目录(npm install 耗时),每补完一个就单独对齐状态并按需拉起 */
140
+ /** 逐个补回缺失的部署目录(npm install 耗时),每补完一个就单独对齐状态并按需拉起;排队中的应用也先登记进度,列表/详情据此显示恢复中 */
136
141
  const restoreArtifacts = async missing => {
137
142
  const { services } = fastify[options.name];
143
+ const queue = missing.map(item => ({
144
+ item,
145
+ progress: services.app.getDeployProgress().begin(item.app.name, crypto.randomUUID(), { versionId: String(item.ver.id), version: item.ver.version, source: 'restore' })
146
+ }));
138
147
  const results = [];
139
- for (const item of missing) {
140
- const { app, ver } = item;
141
- const progress = services.app.getDeployProgress().begin(app.name, crypto.randomUUID(), { versionId: String(ver.id), version: ver.version, source: 'restore' });
142
- const result = await services.app.restoreArtifact(Object.assign({}, item, { progress }));
148
+ for (const { item, progress } of queue) {
149
+ const { app } = item;
150
+ let result;
151
+ try {
152
+ result = await services.app.restoreArtifact(Object.assign({}, item, { progress }));
153
+ } catch (e) {
154
+ fastify.log.warn({ err: e, app: app.name }, 'restore artifact failed');
155
+ if (!progress.finished()) {
156
+ progress.report('package', 'error', { message: e.message });
157
+ }
158
+ continue;
159
+ }
143
160
  results.push(result);
144
161
  const wasActive = app.status === 'running' || app.status === 'deploying';
145
162
  try {
@@ -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.21",
3
+ "version": "0.1.23",
4
4
  "description": "Fastify 单机应用市场插件:版本上传、PM2 托管、路径/域名反代与日志 SSE",
5
5
  "main": "index.js",
6
6
  "scripts": {