@kne/fastify-app-manager 0.1.35 → 0.1.36

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
@@ -921,7 +921,7 @@ data: {"name":"demo","ts":1791456608533,...}
921
921
  | 方法签名 | 说明 |
922
922
  |----------|------|
923
923
  | `onReady()` | `ensureSchema` 后连接 PM2、挂 log bus、启动日志切分与负载采样定时器,并 **setImmediate** 异步执行 `recoverOnStartup`,以及一次 `rotateLogs` 与一次 `sampleLoad`(不阻塞父应用 ready) |
924
- | `ensureSchema()` | 宿主 `sync()` 不给已有表加列:为老库补齐后续新增列/可空约束(含 `app.kind`、`appVersion.fileId|migrationFiles|envSchema`、`appOpenApiRecord.searchText`,并把 `port/rootPath/pm2Name` 改为可空),可重复执行;插件 `after` 与 `onReady` 都会调用。离线补齐见包内 `sql/host-upgrade-linked-kind.sql` |
924
+ | `ensureSchema()` | 宿主 `sync()` 不给已有表加列:为老库补齐后续新增列/可空约束(含 `app.kind`、`appVersion.fileId|migrationFiles|envSchema`、`appOpenApiRecord.searchText`,并把 `port/rootPath/pm2Name` 改为可空);postgres 下将 `name/domain/pm2_name` 唯一约束改为 `WHERE deleted_at IS NULL` 部分唯一索引(软删后可同名重建),可重复执行;插件 `after` 与 `onReady` 都会调用。离线补齐见包内 `sql/host-upgrade-linked-kind.sql`、`sql/host-upgrade-app-soft-delete-unique.sql` |
925
925
  | `recoverOnStartup()` | 两路并行:部署目录完好的应用立即 `reconcile`;目录缺失的应用逐个 `restoreArtifact`(需重装依赖,较慢),每补完一个即单独 `syncStatus` 并按需拉起;补不回且原为 `running`/`deploying` 的标记 `error`;两路结束后 `pruneAllVersionArtifacts`。返回 `{ reconciled, restored, pruned }` |
926
926
  | `onClose()` | 停止切分与采样定时器并等待进行中的任务,断开 bus / PM2(由插件 `onClose` 调用) |
927
927
  | `rotateLogs({ now? })` | 立即执行一轮切分 + 压缩 + 保留清理;返回本轮切分的 `[{ name, stream, fileName, reason }]`,`reason` 为 `size` / `daily` |
@@ -5,7 +5,6 @@ module.exports = ({ DataTypes }) => {
5
5
  name: {
6
6
  type: DataTypes.STRING,
7
7
  allowNull: false,
8
- unique: true,
9
8
  comment: '应用 slug / appId'
10
9
  },
11
10
  label: {
@@ -22,7 +21,6 @@ module.exports = ({ DataTypes }) => {
22
21
  domain: {
23
22
  type: DataTypes.STRING,
24
23
  allowNull: true,
25
- unique: true,
26
24
  comment: '绑定域名 Host;linked 必须为空'
27
25
  },
28
26
  icon: {
@@ -77,7 +75,6 @@ module.exports = ({ DataTypes }) => {
77
75
  pm2Name: {
78
76
  type: DataTypes.STRING,
79
77
  allowNull: true,
80
- unique: true,
81
78
  comment: 'PM2 进程名;linked 可空'
82
79
  },
83
80
  message: {
@@ -88,7 +85,14 @@ module.exports = ({ DataTypes }) => {
88
85
  },
89
86
  options: {
90
87
  comment: '托管应用',
91
- indexes: [{ fields: ['status'] }, { fields: ['domain'] }, { fields: ['kind'] }]
88
+ indexes: [
89
+ { fields: ['status'] },
90
+ { fields: ['kind'] },
91
+ // 软删行不占唯一键:删除后可同名重建(须配合 ensureSchema / 迁移丢掉旧的 *_key)
92
+ { name: 'app_name_active_uk', unique: true, fields: ['name'], where: { deleted_at: null } },
93
+ { name: 'app_domain_active_uk', unique: true, fields: ['domain'], where: { deleted_at: null } },
94
+ { name: 'app_pm2_name_active_uk', unique: true, fields: ['pm2_name'], where: { deleted_at: null } }
95
+ ]
92
96
  }
93
97
  };
94
98
  };
@@ -64,16 +64,46 @@ module.exports = fp(async (fastify, options) => {
64
64
  }
65
65
  return category.code ? { code: category.code, name: category.name || category.code } : null;
66
66
  };
67
+ /**
68
+ * 入口 path 一律相对应用根入库。
69
+ * 详情/中心列表若曾把绝对 url 写回 options.entries,或出现 /http://… 脏数据,这里剥成 pathname,避免与 baseUrl 重复拼接。
70
+ */
71
+ const toRelativeEntryPath = raw => {
72
+ let path = String(raw || '').trim();
73
+ if (!path) {
74
+ return '';
75
+ }
76
+ for (let i = 0; i < 8; i += 1) {
77
+ if (/^https?:\/\//i.test(path)) {
78
+ try {
79
+ const u = new URL(path);
80
+ path = `${u.pathname || '/'}${u.search || ''}${u.hash || ''}` || '/';
81
+ continue;
82
+ } catch (e) {
83
+ return '';
84
+ }
85
+ }
86
+ if (/^\/https?:\/\//i.test(path)) {
87
+ path = path.slice(1);
88
+ continue;
89
+ }
90
+ break;
91
+ }
92
+ if (!path.startsWith('/')) {
93
+ path = `/${path}`;
94
+ }
95
+ return path;
96
+ };
97
+
67
98
  // 应用入口:label + 相对应用根的 path;去空、补前导 /、按 path 去重;showInCenter 未设置视为开放给前台
68
99
  const normalizeEntries = entries => {
69
100
  const seen = new Set();
70
101
  return (Array.isArray(entries) ? entries : []).reduce((result, item) => {
71
102
  const label = String(item?.label || '').trim();
72
- const rawPath = String(item?.path || '').trim();
73
- if (!label || !rawPath) {
103
+ const entryPath = toRelativeEntryPath(item?.path);
104
+ if (!label || !entryPath) {
74
105
  return result;
75
106
  }
76
- const entryPath = rawPath.startsWith('/') ? rawPath : `/${rawPath}`;
77
107
  if (!seen.has(entryPath)) {
78
108
  seen.add(entryPath);
79
109
  result.push({ label, path: entryPath, showInCenter: item?.showInCenter !== false });
@@ -98,9 +128,10 @@ module.exports = fp(async (fastify, options) => {
98
128
  const remote = linked ? linkedBaseUrl(appLike) : null;
99
129
  const base = remote || mountPrefix(appLike.name);
100
130
  return normalizeEntries(appLike.options?.entries).map(entry => {
101
- const pathPart = entry.path.startsWith('/') ? entry.path : `/${entry.path}`;
102
- const url = remote ? `${remote}${pathPart}` : `${base}${pathPart}`;
103
- return Object.assign({}, entry, { path: remote ? url : entry.path, url });
131
+ // path 始终相对,仅 url 拼绝对;linked 若把 path 改成绝对再经 save 回写会与 baseUrl 叠成 http://host/http://host/...
132
+ const pathPart = entry.path;
133
+ const url = `${String(base).replace(/\/+$/, '')}${pathPart}`;
134
+ return Object.assign({}, entry, { path: pathPart, url });
104
135
  });
105
136
  };
106
137
 
@@ -185,22 +216,30 @@ module.exports = fp(async (fastify, options) => {
185
216
  normalizedOptions.homePath = '/';
186
217
  }
187
218
 
188
- const app = await models.app.create({
189
- name,
190
- label,
191
- kind: KIND_MANAGED,
192
- domain: domain || null,
193
- icon: icon || null,
194
- description: description || null,
195
- env: omitSystemEnv(env, options.systemEnvKeys),
196
- pm2Config: pm2Config || {},
197
- options: normalizedOptions,
198
- port,
199
- status: 'idle',
200
- rootPath,
201
- pm2Name: createPm2Name(options.hostName, name),
202
- message: null
203
- });
219
+ let app;
220
+ try {
221
+ app = await models.app.create({
222
+ name,
223
+ label,
224
+ kind: KIND_MANAGED,
225
+ domain: domain || null,
226
+ icon: icon || null,
227
+ description: description || null,
228
+ env: omitSystemEnv(env, options.systemEnvKeys),
229
+ pm2Config: pm2Config || {},
230
+ options: normalizedOptions,
231
+ port,
232
+ status: 'idle',
233
+ rootPath,
234
+ pm2Name: createPm2Name(options.hostName, name),
235
+ message: null
236
+ });
237
+ } catch (e) {
238
+ if (e.name === 'SequelizeUniqueConstraintError') {
239
+ httpError(409, `app ${name} already exists`);
240
+ }
241
+ throw e;
242
+ }
204
243
  return toPublicApp(app);
205
244
  };
206
245
 
@@ -298,15 +337,7 @@ module.exports = fp(async (fastify, options) => {
298
337
  const linked = isLinked(app);
299
338
  const base = linked ? linkedBaseUrl(app) : null;
300
339
  const pathUrl = linked && base ? `${base}/` : `${mountPrefix(app.name)}/`;
301
- const entries = resolveEntries(app)
302
- .filter(entry => entry.showInCenter)
303
- .map(entry =>
304
- linked && base
305
- ? Object.assign({}, entry, {
306
- path: entry.path.startsWith('http') ? entry.path : `${base}${entry.path.startsWith('/') ? '' : '/'}${entry.path}`
307
- })
308
- : entry
309
- );
340
+ const entries = resolveEntries(app).filter(entry => entry.showInCenter);
310
341
  return {
311
342
  name: app.name,
312
343
  label: app.label,
@@ -1068,7 +1099,14 @@ module.exports = fp(async (fastify, options) => {
1068
1099
  /** 只做 fs 检查:返回当前版本目录(artifactPath/server)缺失的应用 */
1069
1100
  const listMissingArtifacts = async () => {
1070
1101
  const { Op } = fastify.sequelize.Sequelize;
1071
- const apps = await models.app.findAll({ where: { currentVersionId: { [Op.ne]: null } } });
1102
+ // 恢复按创建顺序排队:不指定 order 时顺序取决于库的查询计划/索引,改索引后会变
1103
+ const apps = await models.app.findAll({
1104
+ where: { currentVersionId: { [Op.ne]: null } },
1105
+ order: [
1106
+ ['createdAt', 'ASC'],
1107
+ ['id', 'ASC']
1108
+ ]
1109
+ });
1072
1110
  const missing = [];
1073
1111
  for (const app of apps) {
1074
1112
  if (isLinked(app)) {
@@ -87,6 +87,37 @@ module.exports = fp(async (fastify, options) => {
87
87
  await queryInterface.addIndex(table, [kindAttr.field], { name: indexName });
88
88
  }
89
89
  }
90
+
91
+ // 软删不占唯一键:去掉字段级 UNIQUE 约束,改为 WHERE deleted_at IS NULL 的部分唯一索引。
92
+ // sequelize sync 不会 DROP 旧 *_key;须在此幂等迁移(仅 postgres;MySQL 不支持部分索引)。
93
+ const dialect = models.app.sequelize.getDialect();
94
+ if (dialect === 'postgres') {
95
+ const qi = models.app.sequelize.getQueryInterface();
96
+ const quoted = `"${String(tableName).replace(/"/g, '""')}"`;
97
+ for (const col of ['name', 'domain', 'pm2_name']) {
98
+ await models.app.sequelize.query(`ALTER TABLE ${quoted} DROP CONSTRAINT IF EXISTS "${tableName}_${col}_key"`);
99
+ }
100
+ // 顺带去掉旧的非唯一 domain 索引(若仍存在)
101
+ await models.app.sequelize.query(`DROP INDEX IF EXISTS "${tableName}_domain"`);
102
+
103
+ const activeIndexes = [
104
+ { name: `${tableName}_name_active_uk`, fields: ['name'] },
105
+ { name: `${tableName}_domain_active_uk`, fields: ['domain'] },
106
+ { name: `${tableName}_pm2_name_active_uk`, fields: ['pm2_name'] }
107
+ ];
108
+ const indexes = await qi.showIndex(table);
109
+ for (const item of activeIndexes) {
110
+ const exists = (indexes || []).some(row => row.name === item.name);
111
+ if (exists) {
112
+ continue;
113
+ }
114
+ await qi.addIndex(table, item.fields, {
115
+ name: item.name,
116
+ unique: true,
117
+ where: { deleted_at: null }
118
+ });
119
+ }
120
+ }
90
121
  };
91
122
 
92
123
  const onReady = async () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-app-manager",
3
- "version": "0.1.35",
3
+ "version": "0.1.36",
4
4
  "description": "Fastify 单机应用市场插件:版本上传、PM2 托管、路径/域名反代与日志 SSE",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -0,0 +1,41 @@
1
+ -- 宿主库升级脚本(可选):软删行不再占用 name/domain/pm2_name 唯一键。
2
+ -- 默认表前缀 t_app_manager_;若宿主传了 dbTableNamePrefix / DB_TABLE_PREFIX,请改表名。
3
+ -- 幂等。仅 PostgreSQL(部分唯一索引)。对应 @kne/fastify-app-manager libs/models/app.js
4
+ -- 也可由 bootstrap.ensureSchema 在启动时自动执行。
5
+
6
+ DO $$
7
+ BEGIN
8
+ IF EXISTS (
9
+ SELECT 1 FROM information_schema.tables
10
+ WHERE table_schema = 'public' AND table_name = 't_app_manager_app'
11
+ ) THEN
12
+ ALTER TABLE t_app_manager_app DROP CONSTRAINT IF EXISTS t_app_manager_app_name_key;
13
+ ALTER TABLE t_app_manager_app DROP CONSTRAINT IF EXISTS t_app_manager_app_domain_key;
14
+ ALTER TABLE t_app_manager_app DROP CONSTRAINT IF EXISTS t_app_manager_app_pm2_name_key;
15
+ DROP INDEX IF EXISTS t_app_manager_app_domain;
16
+
17
+ IF NOT EXISTS (
18
+ SELECT 1 FROM pg_indexes
19
+ WHERE schemaname = 'public' AND indexname = 't_app_manager_app_name_active_uk'
20
+ ) THEN
21
+ CREATE UNIQUE INDEX t_app_manager_app_name_active_uk
22
+ ON t_app_manager_app (name) WHERE deleted_at IS NULL;
23
+ END IF;
24
+
25
+ IF NOT EXISTS (
26
+ SELECT 1 FROM pg_indexes
27
+ WHERE schemaname = 'public' AND indexname = 't_app_manager_app_domain_active_uk'
28
+ ) THEN
29
+ CREATE UNIQUE INDEX t_app_manager_app_domain_active_uk
30
+ ON t_app_manager_app (domain) WHERE deleted_at IS NULL;
31
+ END IF;
32
+
33
+ IF NOT EXISTS (
34
+ SELECT 1 FROM pg_indexes
35
+ WHERE schemaname = 'public' AND indexname = 't_app_manager_app_pm2_name_active_uk'
36
+ ) THEN
37
+ CREATE UNIQUE INDEX t_app_manager_app_pm2_name_active_uk
38
+ ON t_app_manager_app (pm2_name) WHERE deleted_at IS NULL;
39
+ END IF;
40
+ END IF;
41
+ END $$;