@kne/fastify-app-manager 0.1.28 → 0.1.30

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.
@@ -0,0 +1,234 @@
1
+ // 响应 schema 会参与 fast-json-stringify 序列化:对象一律 additionalProperties: true 以免裁掉未声明字段;
2
+ // 用 nullable 而非类型数组(类型数组遇到不匹配的值会直接 500),类型不确定的字段(如 id、日期、JSON 列)只写说明不声明类型
3
+ const str = description => ({ type: 'string', nullable: true, description });
4
+ const num = description => ({ type: 'number', nullable: true, description });
5
+ const bool = description => ({ type: 'boolean', nullable: true, description });
6
+ const any = description => ({ description });
7
+ const strArray = description => ({ type: 'array', nullable: true, description, items: { type: 'string' } });
8
+ const list = (description, items) => ({ type: 'array', nullable: true, description, items: items || {} });
9
+ const obj = (description, properties = {}) => ({ type: 'object', nullable: true, description, additionalProperties: true, properties });
10
+
11
+ const success = (description, schema) => ({
12
+ 200: Object.assign({ type: 'object', additionalProperties: true }, schema, { description })
13
+ });
14
+
15
+ const empty = (description = '操作成功,返回空对象') => success(description);
16
+
17
+ // 文件流、SSE 等非 JSON 响应:只写说明不声明结构,不参与序列化
18
+ const raw = description => ({ 200: { description } });
19
+
20
+ const pageResult = (description, item) => ({
21
+ properties: {
22
+ pageData: list(`${description}列表`, item),
23
+ totalCount: num('总条数')
24
+ }
25
+ });
26
+
27
+ const APP_STATUS = '应用状态:idle 未部署,deploying 部署/启动中,running 运行中,stopped 已停止,error 异常';
28
+
29
+ const entry = obj('应用入口', {
30
+ label: str('入口名称'),
31
+ path: str('相对应用根的路径,以 / 开头'),
32
+ showInCenter: bool('是否在应用中心前台展示'),
33
+ url: str('入口完整访问地址(挂载前缀 + path)')
34
+ });
35
+
36
+ const deployment = obj('进行中的部署,没有为 null', {
37
+ progressId: str('部署进度标识'),
38
+ versionId: any('部署的版本 ID'),
39
+ version: str('部署的版本号'),
40
+ source: str('来源:deploy 手动部署,restore 启动时补回部署目录'),
41
+ startedAt: any('开始时间'),
42
+ step: str('当前阶段:package / env / migrate / start / ready'),
43
+ detail: any('当前阶段的附加说明')
44
+ });
45
+
46
+ const deployEvent = obj('部署进度事件', {
47
+ progressId: str('部署进度标识'),
48
+ step: str('阶段:package 准备部署包,env 校验环境变量,migrate SQL 迁移,start 启动进程,ready 等待就绪'),
49
+ status: str('阶段状态:running / done / skipped / error'),
50
+ detail: any('附加说明'),
51
+ message: str('失败原因'),
52
+ at: any('事件时间')
53
+ });
54
+
55
+ const deployRecordProps = {
56
+ name: str('应用 name'),
57
+ progressId: str('部署进度标识'),
58
+ versionId: any('部署的版本 ID'),
59
+ version: str('部署的版本号'),
60
+ source: str('来源:deploy 手动部署,restore 启动时补回部署目录'),
61
+ status: str('部署结果:running 进行中,success 成功,failed 失败'),
62
+ step: str('最后到达的阶段'),
63
+ message: str('失败原因'),
64
+ startedAt: any('开始时间'),
65
+ finishedAt: any('结束时间,进行中为 null')
66
+ };
67
+
68
+ const deployRecord = obj('部署记录(不含日志)', deployRecordProps);
69
+
70
+ const appProps = {
71
+ id: any('应用 ID'),
72
+ name: str('应用 name(小写 slug,同时作为访问路径 /app/{name})'),
73
+ label: str('应用显示名称'),
74
+ domain: str('绑定的域名,未绑定为 null'),
75
+ icon: str('应用图标(文件 ID 或地址)'),
76
+ description: str('应用描述'),
77
+ env: obj('应用环境变量;密钥类变量值被掩码为 ********,宿主维护的系统变量不返回'),
78
+ pm2Config: obj('PM2 覆盖配置'),
79
+ options: obj('扩展配置(分类、是否公开、入口、密钥变量名、所属表等)'),
80
+ port: num('分配给子应用进程的端口'),
81
+ status: str(APP_STATUS),
82
+ currentVersionId: any('当前部署的版本 ID,未部署为 null'),
83
+ rootPath: str('应用在服务器上的根目录'),
84
+ pm2Name: str('PM2 进程名'),
85
+ message: str('最近一次状态说明(如失败原因)'),
86
+ passthroughEnvKeys: strArray('宿主透传给子应用的环境变量名'),
87
+ secretEnvKeys: strArray('按密钥处理(值被掩码)的环境变量名'),
88
+ pathUrl: str('按路径访问的地址,如 /app/{name}/'),
89
+ category: any('应用分类:{ code, name } 或分类编码字符串,未设置为 null'),
90
+ isPublic: bool('是否公开(未登录可在应用中心看到),未设置视为公开'),
91
+ entries: list('应用入口', entry),
92
+ createdAt: any('创建时间'),
93
+ updatedAt: any('更新时间'),
94
+ deletedAt: any('删除时间')
95
+ };
96
+
97
+ const app = description => obj(description || '应用', appProps);
98
+
99
+ const appDetail = obj(
100
+ '应用详情',
101
+ Object.assign({}, appProps, {
102
+ pm2Defaults: obj('插件级 PM2 默认配置'),
103
+ deployment,
104
+ lastDeployment: obj('最近一次部署记录(不含日志),没有为 null', deployRecordProps)
105
+ })
106
+ );
107
+
108
+ const appListItem = obj('应用', Object.assign({}, appProps, { deployment }));
109
+
110
+ const centerApp = obj('应用中心中的应用', {
111
+ name: str('应用 name'),
112
+ label: str('应用显示名称'),
113
+ icon: str('应用图标'),
114
+ description: str('应用描述'),
115
+ category: any('应用分类:{ code, name } 或分类编码字符串,未设置为 null'),
116
+ isPublic: bool('是否公开'),
117
+ pathUrl: str('访问地址,如 /app/{name}/'),
118
+ entries: list('开放给前台的应用入口', entry),
119
+ deployment: obj('正在部署时为 { source },否则为 null', { source: str('部署来源') })
120
+ });
121
+
122
+ const version = obj('应用版本', {
123
+ id: any('版本 ID'),
124
+ appName: str('所属应用 name'),
125
+ version: str('版本号'),
126
+ label: str('版本说明'),
127
+ artifactPath: str('版本解压目录'),
128
+ hasMigration: bool('是否包含 SQL 迁移脚本'),
129
+ migrationPath: str('相对 server 的 SQL 目录'),
130
+ fileId: str('宿主文件 ID;版本目录缺失时据此重建'),
131
+ sqlFiles: strArray('SQL 迁移文件名,没有迁移脚本时不返回'),
132
+ hasEnvSchema: bool('是否包含 server/env.schema.json'),
133
+ createdAt: any('上传时间'),
134
+ updatedAt: any('更新时间')
135
+ });
136
+
137
+ const logLine = obj('日志行', {
138
+ line: num('行号(从 1 开始)'),
139
+ content: str('日志内容,行首时间已转换到配置的时区')
140
+ });
141
+
142
+ const logFile = obj('日志文件', {
143
+ fileName: str('文件名,如 out.log、out-20260101-000000.log.gz'),
144
+ stream: str('输出流:out 标准输出,err 错误输出'),
145
+ size: num('文件大小(字节)'),
146
+ compressed: bool('是否为 gzip 压缩的归档'),
147
+ current: bool('是否为正在写入的当前日志'),
148
+ mtime: any('修改时间')
149
+ });
150
+
151
+ const loadSample = obj('负载采样', {
152
+ name: str('应用 name'),
153
+ ts: num('采样时间戳(毫秒)'),
154
+ sampledAt: str('采样时间'),
155
+ status: str('进程状态,offline 表示不在运行'),
156
+ cpu: num('CPU 使用率(%)'),
157
+ memory: num('内存占用(字节)'),
158
+ instances: num('进程实例数'),
159
+ pids: list('进程 ID'),
160
+ uptime: num('运行时长(毫秒)'),
161
+ restarts: num('重启次数'),
162
+ requests: obj('网关请求指标(QPS、耗时、错误率等)')
163
+ });
164
+
165
+ const column = obj('列信息', {
166
+ name: str('列名'),
167
+ type: any('列类型'),
168
+ primaryKey: bool('是否主键'),
169
+ allowNull: bool('是否允许为空'),
170
+ defaultValue: any('默认值')
171
+ });
172
+
173
+ const tableInfo = obj('数据表', {
174
+ table: str('表名'),
175
+ columns: list('列信息', column),
176
+ primaryKey: strArray('主键列名'),
177
+ error: str('读取表结构失败时的错误信息')
178
+ });
179
+
180
+ const DB_SCOPE = '数据库归属:shared 共享托管库(按表前缀区分应用),dedicated 应用独享库';
181
+
182
+ const cleanupResult = obj('清理结果', {
183
+ dropped: strArray('已删除的表(删除 sqlite 文件时为 file:{路径})'),
184
+ skipped: list('跳过的项', obj('跳过原因', { reason: str('原因') })),
185
+ failed: list('删除失败的表', obj('失败项', { table: str('表名'), error: str('错误信息') })),
186
+ sql: strArray('需要手工执行的 SQL(dryRun 时为将要执行的 SQL)'),
187
+ manualRequired: bool('是否需要手工处理'),
188
+ dbScope: str(DB_SCOPE)
189
+ });
190
+
191
+ const exportResult = obj('导出结果', {
192
+ mode: str('导出方式:json 按表导出为 zip,file 复制 sqlite 文件'),
193
+ path: str('导出文件在服务器上的路径'),
194
+ tables: strArray('导出的表'),
195
+ rowCounts: obj('每张表导出的行数 { [表名]: 行数 }')
196
+ });
197
+
198
+ const migrationResult = obj('迁移脚本操作结果', {
199
+ name: str('脚本文件名'),
200
+ executed: bool('操作后是否为已执行')
201
+ });
202
+
203
+ module.exports = {
204
+ str,
205
+ num,
206
+ bool,
207
+ any,
208
+ strArray,
209
+ list,
210
+ obj,
211
+ success,
212
+ empty,
213
+ raw,
214
+ pageResult,
215
+ APP_STATUS,
216
+ DB_SCOPE,
217
+ entry,
218
+ deployEvent,
219
+ deployRecordProps,
220
+ deployRecord,
221
+ app,
222
+ appDetail,
223
+ appListItem,
224
+ centerApp,
225
+ version,
226
+ logLine,
227
+ logFile,
228
+ loadSample,
229
+ column,
230
+ tableInfo,
231
+ cleanupResult,
232
+ exportResult,
233
+ migrationResult
234
+ };
@@ -30,6 +30,7 @@ const { readSqlDir, writeSqlDir } = require('../utils/versionSql');
30
30
  const { createDeployProgress } = require('../utils/deployProgress');
31
31
  const pwaDocument = require('@kne/pwa-document');
32
32
  const pm2Util = require('../utils/pm2');
33
+ const { KIND_MANAGED, KIND_LINKED, isLinked, linkedBaseUrl, assertNotLinked } = require('../utils/appKind');
33
34
 
34
35
  const NAME_RE = /^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/;
35
36
 
@@ -81,8 +82,14 @@ module.exports = fp(async (fastify, options) => {
81
82
  }, []);
82
83
  };
83
84
  const resolveEntries = appLike => {
84
- const base = mountPrefix(appLike.name);
85
- return normalizeEntries(appLike.options?.entries).map(entry => Object.assign({}, entry, { url: `${base}${entry.path}` }));
85
+ const linked = isLinked(appLike);
86
+ const remote = linked ? linkedBaseUrl(appLike) : null;
87
+ const base = remote || mountPrefix(appLike.name);
88
+ return normalizeEntries(appLike.options?.entries).map(entry => {
89
+ const pathPart = entry.path.startsWith('/') ? entry.path : `/${entry.path}`;
90
+ const url = remote ? `${remote}${pathPart}` : `${base}${pathPart}`;
91
+ return Object.assign({}, entry, { path: remote ? url : entry.path, url });
92
+ });
86
93
  };
87
94
 
88
95
  const toPublicApp = app => {
@@ -95,7 +102,11 @@ module.exports = fp(async (fastify, options) => {
95
102
  json.env = maskEnvForResponse(json.env || {}, envOpts);
96
103
  json.passthroughEnvKeys = options.passthroughEnvKeys || [];
97
104
  json.secretEnvKeys = collectSecretKeys(json.env || {}, envOpts);
98
- json.pathUrl = `${mountPrefix(json.name)}/`;
105
+ const linked = isLinked(json);
106
+ const remote = linked ? linkedBaseUrl(json) : null;
107
+ json.pathUrl = remote ? `${remote}/` : `${mountPrefix(json.name)}/`;
108
+ json.openUrl = json.pathUrl;
109
+ json.kind = linked ? KIND_LINKED : KIND_MANAGED;
99
110
  json.category = json.options?.category || null;
100
111
  json.isPublic = isAppPublic(json);
101
112
  json.entries = resolveEntries(json);
@@ -159,6 +170,7 @@ module.exports = fp(async (fastify, options) => {
159
170
  const app = await models.app.create({
160
171
  name,
161
172
  label,
173
+ kind: KIND_MANAGED,
162
174
  domain: domain || null,
163
175
  icon: icon || null,
164
176
  description: description || null,
@@ -218,6 +230,9 @@ module.exports = fp(async (fastify, options) => {
218
230
 
219
231
  const saveEnv = async ({ name, env, secretEnvKeys: nextSecretKeys } = {}) => {
220
232
  const app = await getByName(name);
233
+ if (isLinked(app)) {
234
+ httpError(400, '外部应用环境变量只读,请在远程部署侧修改后重启');
235
+ }
221
236
  // 密钥类型不可撤销,只随变量删除而移除
222
237
  const secretEnvKeys = normalizeSecretKeys([...resolveSecretEnvKeys(app), ...(nextSecretKeys || [])]);
223
238
  // PORT 由端口池分配,启动时总会覆盖,不接受外部写入
@@ -259,15 +274,29 @@ module.exports = fp(async (fastify, options) => {
259
274
  .filter(app => !publicOnly || isAppPublic(app))
260
275
  .map(app => {
261
276
  const active = deployProgress.active(app.name);
277
+ const linked = isLinked(app);
278
+ const base = linked ? linkedBaseUrl(app) : null;
279
+ const pathUrl = linked && base ? `${base}/` : `${mountPrefix(app.name)}/`;
280
+ const entries = resolveEntries(app)
281
+ .filter(entry => entry.showInCenter)
282
+ .map(entry =>
283
+ linked && base
284
+ ? Object.assign({}, entry, {
285
+ path: entry.path.startsWith('http') ? entry.path : `${base}${entry.path.startsWith('/') ? '' : '/'}${entry.path}`
286
+ })
287
+ : entry
288
+ );
262
289
  return {
263
290
  name: app.name,
264
291
  label: app.label,
292
+ kind: linked ? KIND_LINKED : KIND_MANAGED,
265
293
  icon: app.icon,
266
294
  description: app.description,
267
295
  category: app.options?.category || null,
268
296
  isPublic: isAppPublic(app),
269
- pathUrl: `${mountPrefix(app.name)}/`,
270
- entries: resolveEntries(app).filter(entry => entry.showInCenter),
297
+ pathUrl,
298
+ openUrl: pathUrl,
299
+ entries,
271
300
  deployment: active ? { source: active.source } : null
272
301
  };
273
302
  });
@@ -369,6 +398,7 @@ module.exports = fp(async (fastify, options) => {
369
398
  if (!app) {
370
399
  httpError(404, `app ${name} not found; create it first`);
371
400
  }
401
+ assertNotLinked(app, '版本上传');
372
402
  // The (app_name, version) unique index also covers soft-deleted rows, so they must be purged before reuse.
373
403
  const dup = await models.appVersion.findOne({ where: { appName: name, version }, paranoid: false });
374
404
  if (dup && !dup.isSoftDeleted()) {
@@ -789,7 +819,7 @@ module.exports = fp(async (fastify, options) => {
789
819
  const excluded = new Set(excludeIds.map(String));
790
820
  const results = [];
791
821
  for (const app of apps) {
792
- if (excluded.has(String(app.id))) {
822
+ if (excluded.has(String(app.id)) || isLinked(app)) {
793
823
  continue;
794
824
  }
795
825
  const shouldRecover = recoverIfMissing && (app.status === 'running' || app.status === 'deploying');
@@ -905,6 +935,9 @@ module.exports = fp(async (fastify, options) => {
905
935
  */
906
936
  const getEnvDeclaration = async ({ name, versionId } = {}) => {
907
937
  const app = await getByName(name);
938
+ if (isLinked(app)) {
939
+ return fastify[options.name].services.link.proxy.env(app);
940
+ }
908
941
  const ver = await resolveDeclarationVersion(app, versionId);
909
942
  const schema = ver ? await getVersionEnvSchema(ver) : null;
910
943
  const injected = listInjectedEnvKeys(app);
@@ -1012,6 +1045,9 @@ module.exports = fp(async (fastify, options) => {
1012
1045
  const apps = await models.app.findAll({ where: { currentVersionId: { [Op.ne]: null } } });
1013
1046
  const missing = [];
1014
1047
  for (const app of apps) {
1048
+ if (isLinked(app)) {
1049
+ continue;
1050
+ }
1015
1051
  const ver = await models.appVersion.findByPk(app.currentVersionId);
1016
1052
  if (ver && !(await fs.pathExists(path.join(ver.artifactPath, 'server')))) {
1017
1053
  missing.push({ app, ver });
@@ -1119,6 +1155,7 @@ module.exports = fp(async (fastify, options) => {
1119
1155
 
1120
1156
  const deploy = async ({ name, versionId, version, runMigration = true, migrations, progressId }) => {
1121
1157
  const app = await getByName(name);
1158
+ assertNotLinked(app, '部署');
1122
1159
  let ver = null;
1123
1160
  if (versionId) {
1124
1161
  ver = await models.appVersion.findByPk(versionId);
@@ -1250,6 +1287,7 @@ module.exports = fp(async (fastify, options) => {
1250
1287
 
1251
1288
  const stop = async ({ name }) => {
1252
1289
  const app = await getByName(name);
1290
+ assertNotLinked(app, '停止');
1253
1291
  try {
1254
1292
  await pm2Util.stopApp(app.pm2Name);
1255
1293
  } catch (e) {
@@ -1276,6 +1314,7 @@ module.exports = fp(async (fastify, options) => {
1276
1314
 
1277
1315
  const start = async ({ name }) => {
1278
1316
  const app = await getByName(name);
1317
+ assertNotLinked(app, '启动');
1279
1318
  const env = await prepareStartEnv(app);
1280
1319
  await app.update({ status: 'deploying', message: null });
1281
1320
  try {
@@ -1291,6 +1330,7 @@ module.exports = fp(async (fastify, options) => {
1291
1330
 
1292
1331
  const restart = async ({ name }) => {
1293
1332
  const app = await getByName(name);
1333
+ assertNotLinked(app, '重启');
1294
1334
  const env = await prepareStartEnv(app);
1295
1335
  await app.update({ status: 'deploying', message: null });
1296
1336
  try {
@@ -1312,21 +1352,24 @@ module.exports = fp(async (fastify, options) => {
1312
1352
 
1313
1353
  const remove = async ({ name, exportBeforeRemove = true, cleanupData = true, allowRemoveIfCleanupIncomplete = false, force = false, removeSqliteFile = false } = {}) => {
1314
1354
  const app = await getByName(name);
1315
- try {
1316
- await pm2Util.deleteProcess(app.pm2Name);
1317
- } catch (e) {
1318
- // ignore
1355
+ const linked = isLinked(app);
1356
+ if (!linked && app.pm2Name) {
1357
+ try {
1358
+ await pm2Util.deleteProcess(app.pm2Name);
1359
+ } catch (e) {
1360
+ // ignore
1361
+ }
1319
1362
  }
1320
1363
 
1321
1364
  const dbops = fastify[options.name].services.dbops;
1322
1365
  let exportResult = null;
1323
1366
  let cleanupResult = null;
1324
1367
 
1325
- if (exportBeforeRemove && !force) {
1368
+ if (!linked && exportBeforeRemove && !force) {
1326
1369
  exportResult = await dbops.exportData({ name });
1327
1370
  }
1328
1371
 
1329
- if (cleanupData) {
1372
+ if (!linked && cleanupData) {
1330
1373
  cleanupResult = await dbops.cleanup({ name, removeSqliteFile });
1331
1374
  if (cleanupResult.manualRequired && !allowRemoveIfCleanupIncomplete) {
1332
1375
  return {
@@ -1341,7 +1384,9 @@ module.exports = fp(async (fastify, options) => {
1341
1384
  const snapshot = app.toJSON();
1342
1385
  await models.appVersion.destroy({ where: { appName: name } });
1343
1386
  await models.appOpenApiRecord.destroy({ where: { appName: name }, force: true });
1344
- await fs.remove(app.rootPath).catch(() => {});
1387
+ if (!linked && app.rootPath) {
1388
+ await fs.remove(app.rootPath).catch(() => {});
1389
+ }
1345
1390
  deployProgress.clear(app.name);
1346
1391
  await app.destroy();
1347
1392
  if (typeof options.onAppRemoved === 'function') {
@@ -1376,12 +1421,18 @@ module.exports = fp(async (fastify, options) => {
1376
1421
 
1377
1422
  const logs = async ({ name, stream = 'out', file, perPage = 100, currentPage = 1, beforeLine } = {}) => {
1378
1423
  const app = await getByName(name);
1424
+ if (isLinked(app)) {
1425
+ return fastify[options.name].services.link.proxy.logs(app, { stream, file, perPage, currentPage, beforeLine });
1426
+ }
1379
1427
  const filePath = file ? await resolveExistingLogFile(app, file) : currentLogFile(app, stream);
1380
1428
  return readLogTail(filePath, { perPage, currentPage, beforeLine, timezone: options.logTimezone });
1381
1429
  };
1382
1430
 
1383
1431
  const logFiles = async ({ name }) => {
1384
1432
  const app = await getByName(name);
1433
+ if (isLinked(app)) {
1434
+ return fastify[options.name].services.link.proxy.logFiles(app);
1435
+ }
1385
1436
  const pageData = (await listLogFiles(logsDirOf(app))).map(item => Object.assign({}, item, { mtime: toIsoInTz(item.mtime, options.logTimezone) }));
1386
1437
  return { pageData, totalCount: pageData.length };
1387
1438
  };
@@ -42,7 +42,8 @@ module.exports = fp(async (fastify, options) => {
42
42
  const { models } = fastify[options.name];
43
43
  const targets = [
44
44
  [models.appVersion, ['fileId', 'migrationFiles', 'envSchema']],
45
- [models.appOpenApiRecord, ['searchText']]
45
+ [models.appOpenApiRecord, ['searchText']],
46
+ [models.app, ['kind']]
46
47
  ];
47
48
  for (const [model, names] of targets) {
48
49
  const queryInterface = model.sequelize.getQueryInterface();
@@ -51,10 +52,30 @@ module.exports = fp(async (fastify, options) => {
51
52
  for (const name of names) {
52
53
  const attr = model.rawAttributes[name];
53
54
  if (!columns[attr.field]) {
54
- await queryInterface.addColumn(table, attr.field, { type: attr.type, allowNull: true, comment: attr.comment });
55
+ await queryInterface.addColumn(table, attr.field, {
56
+ type: attr.type,
57
+ allowNull: attr.allowNull !== false,
58
+ defaultValue: attr.defaultValue,
59
+ comment: attr.comment
60
+ });
55
61
  }
56
62
  }
57
63
  }
64
+ // linked 应用不占本机端口/目录/PM2:将既有非空列改为可空(幂等)
65
+ const queryInterface = models.app.sequelize.getQueryInterface();
66
+ const table = models.app.getTableName();
67
+ const columns = await queryInterface.describeTable(table);
68
+ for (const name of ['port', 'rootPath', 'pm2Name']) {
69
+ const attr = models.app.rawAttributes[name];
70
+ const col = columns[attr.field];
71
+ if (col && col.allowNull === false) {
72
+ await queryInterface.changeColumn(table, attr.field, {
73
+ type: attr.type,
74
+ allowNull: true,
75
+ comment: attr.comment
76
+ });
77
+ }
78
+ }
58
79
  };
59
80
 
60
81
  const onReady = async () => {
@@ -123,7 +144,24 @@ module.exports = fp(async (fastify, options) => {
123
144
  if (options.loadSampleIntervalMs > 0) {
124
145
  sampleLoad().catch(err => fastify.log.debug({ err }, 'load sampling failed'));
125
146
  }
147
+ const link = fastify[options.name].services.link;
148
+ if (link?.syncAllLinked) {
149
+ link.syncAllLinked().catch(err => fastify.log.warn({ err }, 'linked apps sync failed'));
150
+ }
126
151
  });
152
+
153
+ const linkSyncMs = options.linkSyncIntervalMs || 0;
154
+ if (linkSyncMs > 0) {
155
+ const linkTimer = setInterval(() => {
156
+ const link = fastify[options.name].services.link;
157
+ if (link?.syncAllLinked) {
158
+ link.syncAllLinked().catch(err => fastify.log.warn({ err }, 'linked apps sync failed'));
159
+ }
160
+ }, linkSyncMs);
161
+ linkTimer.unref?.();
162
+ // 挂到实例上,onClose 时可清理;无专门字段时依赖进程退出
163
+ fastify[options.name]._linkSyncTimer = linkTimer;
164
+ }
127
165
  };
128
166
 
129
167
  const fsEnsureAppsRoot = async () => {
@@ -188,9 +226,13 @@ module.exports = fp(async (fastify, options) => {
188
226
  */
189
227
  const migratePm2Names = async () => {
190
228
  const { models } = fastify[options.name];
229
+ const { isLinked } = require('../utils/appKind');
191
230
  const apps = await models.app.findAll();
192
231
  const migrated = [];
193
232
  for (const app of apps) {
233
+ if (isLinked(app) || !app.pm2Name || !app.rootPath) {
234
+ continue;
235
+ }
194
236
  const pm2Name = createPm2Name(options.hostName, app.name);
195
237
  if (app.pm2Name === pm2Name) {
196
238
  continue;
@@ -236,9 +278,13 @@ module.exports = fp(async (fastify, options) => {
236
278
 
237
279
  const runRotation = async ({ now = new Date() } = {}) => {
238
280
  const { models } = fastify[options.name];
239
- const apps = await models.app.findAll({ attributes: ['name', 'rootPath'] });
281
+ const { isLinked } = require('../utils/appKind');
282
+ const apps = await models.app.findAll({ attributes: ['name', 'rootPath', 'kind', 'options'] });
240
283
  const targets = [];
241
284
  for (const app of apps) {
285
+ if (isLinked(app) || !app.rootPath) {
286
+ continue;
287
+ }
242
288
  const logsDir = path.join(app.rootPath, 'logs');
243
289
  if (await fs.pathExists(logsDir)) {
244
290
  targets.push({ name: app.name, logsDir });
@@ -314,16 +360,18 @@ module.exports = fp(async (fastify, options) => {
314
360
  }
315
361
  const { models } = fastify[options.name];
316
362
  const summary = summarizeProcesses(await pm2Util.list(), { now: now.getTime() });
317
- const apps = await models.app.findAll({ attributes: ['name', 'pm2Name'] });
363
+ const { isLinked } = require('../utils/appKind');
364
+ const apps = await models.app.findAll({ attributes: ['name', 'pm2Name', 'kind', 'options'] });
365
+ const managed = apps.filter(app => !isLinked(app) && app.pm2Name);
318
366
  const base = { ts: now.getTime(), sampledAt: toIsoInTz(now, options.logTimezone) };
319
- const samples = apps.map(app => {
367
+ const samples = managed.map(app => {
320
368
  const sample = Object.assign({ name: app.name }, base, summary.get(app.pm2Name) || OFFLINE_LOAD, {
321
369
  requests: requestMetrics.snapshot(app.name, { now: base.ts })
322
370
  });
323
371
  loadStore.push(app.name, sample);
324
372
  return sample;
325
373
  });
326
- const names = apps.map(app => app.name);
374
+ const names = managed.map(app => app.name);
327
375
  loadStore.retain(names);
328
376
  requestMetrics.retain(names);
329
377
  return samples;
@@ -24,6 +24,8 @@ module.exports = fp(async (fastify, options) => {
24
24
  throw err;
25
25
  };
26
26
 
27
+ const { isLinked } = require('../utils/appKind');
28
+
27
29
  const getByName = async name => {
28
30
  const app = await models.app.findOne({ where: { name } });
29
31
  if (!app) {
@@ -32,6 +34,8 @@ module.exports = fp(async (fastify, options) => {
32
34
  return app;
33
35
  };
34
36
 
37
+ const linkedProxy = () => fastify[options.name].services.link.proxy;
38
+
35
39
  const resolveEnvForApp = app =>
36
40
  resolveAppDbEnv({
37
41
  passthroughEnvKeys: options.passthroughEnvKeys,
@@ -116,6 +120,9 @@ module.exports = fp(async (fastify, options) => {
116
120
 
117
121
  const listTables = async ({ name, scope } = {}) => {
118
122
  const app = await getByName(name);
123
+ if (isLinked(app)) {
124
+ return linkedProxy().dbTables(app);
125
+ }
119
126
  return withSequelize(app, async (sequelize, env) => {
120
127
  const all = await listAllTables(sequelize);
121
128
  const dbScope = resolveDbScope(app.env || {}, app.options || {});
@@ -288,6 +295,9 @@ module.exports = fp(async (fastify, options) => {
288
295
 
289
296
  const listRows = async ({ name, table, currentPage = 1, perPage = 20, filter, includeDeleted, sort, keyword } = {}) => {
290
297
  const app = await getByName(name);
298
+ if (isLinked(app)) {
299
+ return linkedProxy().dbRows(app, { table, currentPage, perPage, filter, includeDeleted, sort, keyword });
300
+ }
291
301
  const showDeleted = includeDeleted === true || includeDeleted === 'true' || includeDeleted === 1;
292
302
  return withSequelize(app, async sequelize => {
293
303
  const all = await listAllTables(sequelize);
@@ -368,6 +378,9 @@ module.exports = fp(async (fastify, options) => {
368
378
 
369
379
  const saveRow = async ({ name, table, data = {}, autoGenerate } = {}) => {
370
380
  const app = await getByName(name);
381
+ if (isLinked(app)) {
382
+ return linkedProxy().dbSaveRow(app, { table, data, autoGenerate });
383
+ }
371
384
  return withSequelize(app, async sequelize => {
372
385
  const all = await listAllTables(sequelize);
373
386
  assertTableOwned(app, all, table);
@@ -457,6 +470,9 @@ module.exports = fp(async (fastify, options) => {
457
470
 
458
471
  const removeRow = async ({ name, table, id, pk, hard = false } = {}) => {
459
472
  const app = await getByName(name);
473
+ if (isLinked(app)) {
474
+ return linkedProxy().dbRemoveRow(app, { table, id, pk, hard });
475
+ }
460
476
  return withSequelize(app, async sequelize => {
461
477
  const all = await listAllTables(sequelize);
462
478
  assertTableOwned(app, all, table);
@@ -508,6 +524,9 @@ module.exports = fp(async (fastify, options) => {
508
524
 
509
525
  const runQuery = async ({ name, sql, replacements = {}, maxRows } = {}) => {
510
526
  const app = await getByName(name);
527
+ if (isLinked(app)) {
528
+ return linkedProxy().dbQuery(app, { sql, replacements, maxRows });
529
+ }
511
530
  const limit = Math.min(Math.max(1, Number(maxRows) || options.dbQueryMaxRows || 500), options.dbQueryMaxRows || 500);
512
531
  const checked = assertReadOnlyQuerySql(sql);
513
532
  return withSequelize(app, async sequelize => {