@kne/fastify-app-manager 0.1.23 → 0.1.25

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
@@ -50,7 +50,7 @@ Client / Admin UI
50
50
  | Domain gateway | Host 精确匹配且状态为 `running` 时透明反代,不改写路径 |
51
51
  | Path gateway | `/app/{name}` 剥前缀;改写绝对路径 Location、Cookie Path、文本类 body |
52
52
  | 未运行兜底 | 应用存在但未 `running` 时,网关返回 503 状态页(已停止 / 启动中 / 异常 / 未部署),接口请求返回 JSON,不再落到宿主 404;`/app/{name}` 下应用不存在时返回 404「应用不存在」页 |
53
- | PM2 | 每应用一进程,名 `app-manager__{name}`;stdout/stderr 由 PM2 落 `appsRoot/{name}/logs`,插件按大小/按天切分归档 |
53
+ | PM2 | 每应用一进程,名 `app-manager__{hostName}__{name}`(`hostName` 默认取宿主项目根 `package.json` 的 `name`);stdout/stderr 由 PM2 落 `appsRoot/{name}/logs`,插件按大小/按天切分归档 |
54
54
  | Bootstrap | `onReady` 连接 PM2、挂 log bus(只推 SSE)、启动日志切分与负载采样定时器;**异步**并行:目录完好的托管应用立即 `syncAllStatuses`,缺当前版本目录的应用按版本 `fileId` 逐个补回后再单独拉起,最后清理非当前版本目录(均不阻塞父应用 ready) |
55
55
 
56
56
  ##### 部署时序
@@ -194,6 +194,7 @@ await fastify.listen({ port: 3000 });
194
194
  | `prefix` | string | 否 | `'/api/v1/app-manager'` | 管理 API 前缀 |
195
195
  | `dbTableNamePrefix` | string | 否 | `'t_app_manager_'` | Sequelize 表名前缀 |
196
196
  | `appsRoot` | string | 否 | `cwd/managed-apps` | 应用落盘根目录 |
197
+ | `hostName` | string | 否 | 项目根 `package.json` 的 `name` | 宿主名,拼进 PM2 进程名 `app-manager__{hostName}__{name}`,多个宿主共用 PM2 时避免同名应用互相覆盖。不传时从 `cwd` 向上找到含 `.git` 的目录(找不到则到文件系统根),取沿途最外层 `package.json` 的 `name`;`@` 去掉、`/` 等字符换成 `-`。启动时库里旧规则的进程名会改成新名,旧进程仅在其工作目录位于该应用目录下时删除 |
197
198
  | `portMin` | number | 否 | `4000` | 端口池下限(含) |
198
199
  | `portMax` | number | 否 | `7999` | 端口池上限(含) |
199
200
  | `pathPrefix` | string | 否 | `'/app'` | 路径访问前缀(无尾斜杠亦可) |
@@ -211,6 +212,9 @@ await fastify.listen({ port: 3000 });
211
212
  | `pm2Defaults` | object | 否 | 见下表 | 全局 PM2 默认;可被应用 `pm2Config` 覆盖 |
212
213
  | `createAuthenticate` | function | 否 | 见说明 | 返回 `onRequest` 钩子数组;默认 `fastify.account.authenticate.user` + `admin` |
213
214
  | `createUserAuthenticate` | function | 否 | 见说明 | 应用中心等普通用户接口的 `onRequest` 钩子数组;默认尝试 `fastify.account.authenticate.user` |
215
+ | `enableGroup` | boolean | 否 | `true` | 是否在插件内部注册 `@kne/fastify-group` 提供应用分类接口;宿主已有分组服务时可设为 `false` |
216
+ | `groupName` | string | 否 | `'appManagerGroup'` | 内部分组插件的命名空间(`fastify[groupName]`),与宿主自己注册的 `group` 区分 |
217
+ | `groupDbTableNamePrefix` | string | 否 | `'t_'` | 分组表前缀,表名为前缀 + `snakeCase(groupName + 'Tag')`,默认 `t_app_manager_group_tag` |
214
218
  | `upstreamHost` | string | 否 | `'127.0.0.1'` | 子应用进程监听地址:网关转发、WebSocket、就绪探测、端口探测与 `resolveSystemEnv` 的 `upstreamUrl` 共用 |
215
219
  | `healthCheckPath` | string | 否 | `'/'` | 部署后就绪探测路径 |
216
220
  | `healthCheckTimeoutMs` | number | 否 | `30000` | 探测总超时(毫秒) |
@@ -276,7 +280,7 @@ await fastify.listen({ port: 3000 });
276
280
  | description | string | 否 | - | 描述 |
277
281
  | category | object / string | 否 | - | 应用分类(应用中心分组用),写入 `options.category`;推荐传 fastify-group 分组对象,对象只保留 `{ code, name }`,字符串原样保存 |
278
282
  | isPublic | boolean | 否 | `true` | 是否在公开应用中心展示,写入 `options.isPublic`;未设置视为公开 |
279
- | entries | array | 否 | `[]` | 应用入口 `[{ label, path }]`,写入 `options.entries`;`path` 相对应用根(缺前导 `/` 自动补),缺 `label` 或 `path` 的项丢弃,同 `path` 只保留第一项 |
283
+ | entries | array | 否 | `[]` | 应用入口 `[{ label, path, showInCenter }]`,写入 `options.entries`;`path` 相对应用根(缺前导 `/` 自动补),缺 `label` 或 `path` 的项丢弃,同 `path` 只保留第一项;`showInCenter` 为是否开放给前台(默认 `true`),为 `false` 时应用中心列表与 PWA 不返回该入口,管理端仍可见 |
280
284
  | env | object | 否 | `{}` | 应用自有环境变量 |
281
285
  | pm2Config | object | 否 | `{}` | PM2 覆盖项 |
282
286
  | options | object | 否 | `{}` | 扩展字段;可含 `secretEnvKeys: string[]` 显式密钥键名 |
@@ -606,6 +610,13 @@ data: {"progressId":"p-1","step":"ready","status":"done","detail":null,"message"
606
610
 
607
611
  返回 `{ pageData, totalCount }`,元素均为脱敏后的应用对象。
608
612
 
613
+ ##### 应用分类 `{prefix}/group/*`
614
+
615
+ `enableGroup` 不为 `false` 时,插件内部注册 `@kne/fastify-group`,接口与其一致:`GET group/list`、`GET group/group-list`、`GET group/detail`、`POST group/save`、`POST group/remove`。应用分类使用 `type: 'app'`。
616
+
617
+ - 读接口(`list` / `group-list` / `detail`)**无需登录**,未登录的公开应用中心也能显示分类名称
618
+ - 写接口(`save` / `remove`)使用 `createAuthenticate` 鉴权
619
+
609
620
  ##### GET `{prefix}/app/center/list`
610
621
 
611
622
  应用中心列表,使用 `createUserAuthenticate` 鉴权(普通登录用户可访问)。仅返回 `status: 'running'` 的应用,且只含公开字段(不含 env、端口、路径等)。
@@ -622,8 +633,8 @@ data: {"progressId":"p-1","step":"ready","status":"done","detail":null,"message"
622
633
  "isPublic": true,
623
634
  "pathUrl": "/app/demo/",
624
635
  "entries": [
625
- { "label": "PC", "path": "/", "url": "/app/demo/" },
626
- { "label": "移动端", "path": "/mobile", "url": "/app/demo/mobile" }
636
+ { "label": "PC", "path": "/", "showInCenter": true, "url": "/app/demo/" },
637
+ { "label": "移动端", "path": "/mobile", "showInCenter": true, "url": "/app/demo/mobile" }
627
638
  ],
628
639
  "deployment": null
629
640
  }
@@ -632,6 +643,8 @@ data: {"progressId":"p-1","step":"ready","status":"done","detail":null,"message"
632
643
  }
633
644
  ```
634
645
 
646
+ `entries` 只含 `showInCenter` 不为 `false` 的入口。
647
+
635
648
  `deployment`:部署或启动补回部署目录进行中时为 `{ source: 'deploy' | 'restore' }`,此时应用暂不可访问;否则为 `null`。
636
649
 
637
650
  ##### GET `{prefix}/app/center/public-list`
@@ -930,12 +943,12 @@ data: {"name":"demo","ts":1791456608533,...}
930
943
  | description | string / null | 描述 |
931
944
  | env | object | 自有环境变量 |
932
945
  | pm2Config | object | PM2 覆盖 |
933
- | options | object | 扩展字段;`secretEnvKeys` 为显式密钥键名列表,`category` 为应用分类,`isPublic` 为是否公开(未设置视为公开),`entries` 为应用入口 `[{ label, path }]` |
946
+ | options | object | 扩展字段;`secretEnvKeys` 为显式密钥键名列表,`category` 为应用分类,`isPublic` 为是否公开(未设置视为公开),`entries` 为应用入口 `[{ label, path, showInCenter }]` |
934
947
  | port | number | 分配端口 |
935
948
  | status | string | `idle` / `deploying` / `running` / `stopped` / `error` |
936
949
  | currentVersionId | string / null | 当前部署版本 id |
937
950
  | rootPath | string | 落盘根路径 |
938
- | pm2Name | string | PM2 进程名,唯一 |
951
+ | pm2Name | string | PM2 进程名 `app-manager__{hostName}__{name}`,唯一 |
939
952
  | message | string / null | 最近状态说明(如健康检查失败原因) |
940
953
 
941
954
  索引:`status`、`domain`;`name` / `pm2Name` / `domain` 唯一。
package/index.js CHANGED
@@ -3,6 +3,7 @@ const path = require('node:path');
3
3
  const fs = require('fs-extra');
4
4
  const { assertDefaultAppDbSeparated } = require('./libs/utils/dbIdentity');
5
5
  const { parseTimezone } = require('./libs/utils/logTime');
6
+ const { normalizeHostName, resolveHostName } = require('./libs/utils/hostName');
6
7
 
7
8
  module.exports = fp(
8
9
  async (fastify, options) => {
@@ -87,6 +88,11 @@ module.exports = fp(
87
88
  }
88
89
  return [];
89
90
  },
91
+ /** 应用分类:插件内部注册 @kne/fastify-group,宿主已有分组服务时可关闭 */
92
+ enableGroup: true,
93
+ groupName: 'appManagerGroup',
94
+ /** 表名 = 前缀 + snakeCase(groupName + Tag),默认 t_app_manager_group_tag */
95
+ groupDbTableNamePrefix: 't_',
90
96
  /** 普通登录用户可访问的接口(应用中心列表) */
91
97
  createUserAuthenticate: () => {
92
98
  if (fastify.account?.authenticate?.user) {
@@ -98,6 +104,9 @@ module.exports = fp(
98
104
  options
99
105
  );
100
106
 
107
+ // 多个宿主共用一个 PM2 守护进程时,进程名带宿主名才不会互相覆盖
108
+ options.hostName = options.hostName ? normalizeHostName(options.hostName) : resolveHostName();
109
+
101
110
  parseTimezone(options.logTimezone);
102
111
 
103
112
  if (!options.defaultAppDb) {
@@ -129,6 +138,16 @@ module.exports = fp(
129
138
  options.createAuthenticate = withQueryToken(options.createAuthenticate);
130
139
  options.createUserAuthenticate = withQueryToken(options.createUserAuthenticate);
131
140
 
141
+ // 分类读取需对未登录的公开应用中心开放,增删改沿用管理端鉴权
142
+ if (options.enableGroup !== false) {
143
+ await fastify.register(require('@kne/fastify-group'), {
144
+ name: options.groupName,
145
+ prefix: `${options.prefix}/group`,
146
+ dbTableNamePrefix: options.groupDbTableNamePrefix,
147
+ getAuthenticate: type => (type === 'read' ? [] : options.createAuthenticate())
148
+ });
149
+ }
150
+
132
151
  // 宿主可能已注册(如 fastify-file-manager),重复注册会报错
133
152
  if (!fastify.hasDecorator('multipartErrors')) {
134
153
  await fastify.register(require('@fastify/multipart'), {
@@ -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' },
@@ -3,6 +3,7 @@ const path = require('node:path');
3
3
  const crypto = require('node:crypto');
4
4
  const fs = require('fs-extra');
5
5
  const portPool = require('../utils/portPool');
6
+ const { createPm2Name } = require('../utils/hostName');
6
7
  const {
7
8
  mergeEnv,
8
9
  maskEnvForResponse,
@@ -62,7 +63,7 @@ module.exports = fp(async (fastify, options) => {
62
63
  }
63
64
  return category.code ? { code: category.code, name: category.name || category.code } : null;
64
65
  };
65
- // 应用入口:label + 相对应用根的 path;去空、补前导 /、按 path 去重
66
+ // 应用入口:label + 相对应用根的 path;去空、补前导 /、按 path 去重;showInCenter 未设置视为开放给前台
66
67
  const normalizeEntries = entries => {
67
68
  const seen = new Set();
68
69
  return (Array.isArray(entries) ? entries : []).reduce((result, item) => {
@@ -74,7 +75,7 @@ module.exports = fp(async (fastify, options) => {
74
75
  const entryPath = rawPath.startsWith('/') ? rawPath : `/${rawPath}`;
75
76
  if (!seen.has(entryPath)) {
76
77
  seen.add(entryPath);
77
- result.push({ label, path: entryPath });
78
+ result.push({ label, path: entryPath, showInCenter: item?.showInCenter !== false });
78
79
  }
79
80
  return result;
80
81
  }, []);
@@ -167,7 +168,7 @@ module.exports = fp(async (fastify, options) => {
167
168
  port,
168
169
  status: 'idle',
169
170
  rootPath,
170
- pm2Name: `app-manager__${name}`,
171
+ pm2Name: createPm2Name(options.hostName, name),
171
172
  message: null
172
173
  });
173
174
  return toPublicApp(app);
@@ -266,7 +267,7 @@ module.exports = fp(async (fastify, options) => {
266
267
  category: app.options?.category || null,
267
268
  isPublic: isAppPublic(app),
268
269
  pathUrl: `${mountPrefix(app.name)}/`,
269
- entries: resolveEntries(app),
270
+ entries: resolveEntries(app).filter(entry => entry.showInCenter),
270
271
  deployment: active ? { source: active.source } : null
271
272
  };
272
273
  });
@@ -8,6 +8,7 @@ const { LOG_STREAMS, rotateIfNeeded, compressArchive, applyRetention } = require
8
8
  const { summarizeProcesses, createLoadStore } = require('../utils/loadMonitor');
9
9
  const { createRequestMetrics } = require('../utils/requestMetrics');
10
10
  const { toIsoInTz } = require('../utils/logTime');
11
+ const { createPm2Name } = require('../utils/hostName');
11
12
 
12
13
  const OFFLINE_LOAD = { status: 'offline', cpu: 0, memory: 0, instances: 0, pids: [], uptime: 0, restarts: 0 };
13
14
 
@@ -181,8 +182,37 @@ module.exports = fp(async (fastify, options) => {
181
182
  return results;
182
183
  };
183
184
 
185
+ /**
186
+ * 进程名规则变化(如加上宿主名)后,把库里的旧名改成新名;随后的 reconcile 会按新名拉起应在运行的应用。
187
+ * 旧名进程只在其工作目录位于本应用目录下时才删除:共用 PM2 时同名旧进程可能属于其它宿主。
188
+ */
189
+ const migratePm2Names = async () => {
190
+ const { models } = fastify[options.name];
191
+ const apps = await models.app.findAll();
192
+ const migrated = [];
193
+ for (const app of apps) {
194
+ const pm2Name = createPm2Name(options.hostName, app.name);
195
+ if (app.pm2Name === pm2Name) {
196
+ continue;
197
+ }
198
+ try {
199
+ const rootPath = path.resolve(app.rootPath) + path.sep;
200
+ const owned = (await pm2Util.describe(app.pm2Name)).some(item => path.resolve(item.pm2_env?.pm_cwd || '').startsWith(rootPath));
201
+ if (owned) {
202
+ await pm2Util.deleteProcess(app.pm2Name);
203
+ }
204
+ await app.update({ pm2Name });
205
+ migrated.push({ name: app.name, from: app.pm2Name, to: pm2Name });
206
+ } catch (e) {
207
+ fastify.log.warn({ err: e, app: app.name }, 'migrate pm2 name failed');
208
+ }
209
+ }
210
+ return migrated;
211
+ };
212
+
184
213
  const recoverOnStartup = async () => {
185
214
  const { services } = fastify[options.name];
215
+ await migratePm2Names().catch(err => fastify.log.warn({ err }, 'migrate pm2 names failed'));
186
216
  await services.app.markInterruptedDeploys().catch(err => fastify.log.warn({ err }, 'mark interrupted deploys failed'));
187
217
  const missing = await services.app.listMissingArtifacts();
188
218
  // 两路并行:部署目录完好的应用不必等其它应用重装依赖
@@ -337,6 +367,6 @@ module.exports = fp(async (fastify, options) => {
337
367
  };
338
368
 
339
369
  Object.assign(fastify[options.name].services, {
340
- bootstrap: { onReady, onClose, ensureSchema, recoverOnStartup, reconcile, rotateLogs, sampleLoad }
370
+ bootstrap: { onReady, onClose, ensureSchema, migratePm2Names, recoverOnStartup, reconcile, rotateLogs, sampleLoad }
341
371
  });
342
372
  });
@@ -0,0 +1,42 @@
1
+ const path = require('node:path');
2
+ const fs = require('fs-extra');
3
+
4
+ const PM2_NAME_PREFIX = 'app-manager__';
5
+
6
+ /** 包名转进程名片段:@kne/ai-talent-saas → kne-ai-talent-saas */
7
+ const normalizeHostName = name =>
8
+ String(name || '')
9
+ .trim()
10
+ .replace(/^@/, '')
11
+ .replace(/[^A-Za-z0-9._-]+/g, '-')
12
+ .replace(/^-+|-+$/g, '');
13
+
14
+ const readPackageName = dir => {
15
+ try {
16
+ return fs.readJsonSync(path.join(dir, 'package.json')).name || null;
17
+ } catch (e) {
18
+ return null;
19
+ }
20
+ };
21
+
22
+ /**
23
+ * 从 cwd 向上找到项目根(含 .git 的目录,找不到则到文件系统根)沿途最外层 package.json 的 name。
24
+ * 宿主 server 目录的 package.json 常叫 server,区分不了宿主,所以取项目根。
25
+ */
26
+ const resolveHostName = (cwd = process.cwd()) => {
27
+ let dir = path.resolve(cwd);
28
+ let name = null;
29
+ while (true) {
30
+ name = readPackageName(dir) || name;
31
+ const parent = path.dirname(dir);
32
+ if (fs.existsSync(path.join(dir, '.git')) || parent === dir) {
33
+ break;
34
+ }
35
+ dir = parent;
36
+ }
37
+ return normalizeHostName(name);
38
+ };
39
+
40
+ const createPm2Name = (hostName, name) => (hostName ? `${PM2_NAME_PREFIX}${hostName}__${name}` : `${PM2_NAME_PREFIX}${name}`);
41
+
42
+ module.exports = { normalizeHostName, resolveHostName, createPm2Name };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-app-manager",
3
- "version": "0.1.23",
3
+ "version": "0.1.25",
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",