ssh-net 26.10.33 → 26.10.35

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,34 @@
1
+ // 文件系统小原语:原子落盘与「缺失即 null」读取。manage/state/runtime/conf
2
+ // 等所有落盘方共用这一份,不各自抄 tmp+rename+chmod。
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ /**
7
+ * 读文件;不存在返回 null(仅吞 ENOENT,其余错误照抛)。
8
+ * @param {string} file
9
+ * @param {BufferEncoding|null} [encoding] 缺省 utf8;传 null 读 Buffer
10
+ * @returns {string|Buffer|null}
11
+ */
12
+ export function readFileOrNull(file, encoding = 'utf8') {
13
+ try {
14
+ return fs.readFileSync(file, encoding === null ? undefined : encoding);
15
+ } catch (err) {
16
+ if (err && err.code === 'ENOENT') return null;
17
+ throw err;
18
+ }
19
+ }
20
+
21
+ /**
22
+ * 原子落盘:tmp 写好再 rename 落定,落定后 chmod 兜底(怪 umask/拷贝工具
23
+ * 吃位都修正到 mode)。
24
+ * @param {string} file
25
+ * @param {string|Buffer} content
26
+ * @param {{mode?: number, tmpDir?: string}} [opts] tmpDir 给 Include 片段用:
27
+ * tmp 必须写在 glob 目录之外(conf.d/* 会被 ssh 扫到)
28
+ */
29
+ export function writeFileAtomic(file, content, { mode = 0o644, tmpDir = path.dirname(file) } = {}) {
30
+ const tmp = path.join(tmpDir, `.${path.basename(file)}.tmp-${process.pid}`);
31
+ fs.writeFileSync(tmp, content, { mode });
32
+ fs.renameSync(tmp, file);
33
+ fs.chmodSync(file, mode);
34
+ }
@@ -8,20 +8,21 @@
8
8
  import net from 'node:net';
9
9
 
10
10
  /**
11
- * 取首 hextet 数值;不是「无 scope、非内嵌 v4 的合法 IPv6 字面值」返回 null。
11
+ * 分类一个候选 v6:合法(无 scope、非内嵌 v4 的 IPv6 字面值)给首 hextet
12
+ * 数值;否则给中文拒收原因。isDialableV6 与 explainV6Error 的唯一共同来源,
13
+ * 拒收规则不抄第二份。
12
14
  * @param {unknown} value
13
- * @returns {number | null}
15
+ * @returns {{g0:number}|{reason:string}}
14
16
  */
15
- function firstHextetOf(value) {
16
- if (typeof value !== 'string') return null;
17
- if (value.length === 0 || value.includes('%')) return null; // 无 scope id
18
- if (net.isIP(value) !== 6) return null;
17
+ function classifyV6(value) {
18
+ if (typeof value !== 'string' || value.length === 0) return { reason: 'v6 为空' };
19
+ if (value.includes('%')) return { reason: 'v6 带 scope id,拒绝' };
20
+ if (net.isIP(value) !== 6) return { reason: '不是合法 IPv6 字面值' };
19
21
  // 任何内嵌 v4 形态(末段含点,如 ::ffff:192.0.2.1)一律拒
20
- const tail = value.slice(value.lastIndexOf(':') + 1);
21
- if (tail.includes('.')) return null;
22
+ if (value.slice(value.lastIndexOf(':') + 1).includes('.'))
23
+ return { reason: '拒绝内嵌 v4(含 ::ffff: v4-mapped)' };
22
24
  const firstGroup = value.split(':')[0];
23
- const g0 = firstGroup === '' ? 0 : Number.parseInt(firstGroup, 16);
24
- return Number.isInteger(g0) ? g0 : null;
25
+ return { g0: firstGroup === '' ? 0 : Number.parseInt(firstGroup, 16) };
25
26
  }
26
27
 
27
28
  /**
@@ -30,23 +31,19 @@ function firstHextetOf(value) {
30
31
  * @returns {boolean}
31
32
  */
32
33
  export function isDialableV6(value) {
33
- const g0 = firstHextetOf(value);
34
- return g0 !== null
35
- && ((g0 >= 0x2000 && g0 <= 0x3fff) || (g0 >= 0xfc00 && g0 <= 0xfdff));
34
+ const c = classifyV6(value);
35
+ return 'g0' in c
36
+ && ((c.g0 >= 0x2000 && c.g0 <= 0x3fff) || (c.g0 >= 0xfc00 && c.g0 <= 0xfdff));
36
37
  }
37
38
 
38
39
  /**
39
- * 给报名 RPC 报错用的中文原因;合法返回 null。
40
+ * 给报名 RPC 报错用的中文原因;合法可拨号返回 null。
40
41
  * @param {unknown} value
41
42
  * @returns {string | null}
42
43
  */
43
44
  export function explainV6Error(value) {
44
- if (typeof value !== 'string' || value.length === 0) return 'v6 为空';
45
- if (value.includes('%')) return 'v6 带 scope id,拒绝';
46
- if (net.isIP(value) !== 6) return '不是合法 IPv6 字面值';
47
- if (value.slice(value.lastIndexOf(':') + 1).includes('.'))
48
- return '拒绝内嵌 v4(含 ::ffff: v4-mapped)';
49
- // 可拨号判定单一来源是 isDialableV6,别在这抄第二份
45
+ const c = classifyV6(value);
46
+ if ('reason' in c) return c.reason;
50
47
  if (!isDialableV6(value))
51
48
  return '不是可拨号 v6(收 2000::/3 公网单播与 fc00::/7 ULA,拒 link-local/组播/保留段)';
52
49
  return null;
@@ -5,7 +5,8 @@
5
5
  import * as launchd from './launchd.mjs';
6
6
  import { linkLabel } from './render.mjs';
7
7
 
8
- const TERM_BUDGET_MS = 40_000; // 覆盖 TERM 落在 start peer 前台报名 ssh 的最坏 ~35s
8
+ const TERM_ROUNDS = 2; // 每轮最多等 20s,两轮共覆盖最坏 ~35s 的前台报名 ssh
9
+ const ROUND_MS = 20_000;
9
10
  const POLL_MS = 500;
10
11
 
11
12
  function sleepMs(ms) {
@@ -14,7 +15,8 @@ function sleepMs(ms) {
14
15
  }
15
16
 
16
17
  function isGone(ctx, label) {
17
- const st = launchd.inspect(ctx.runner, ctx.uid, label);
18
+ // 只要 print 的注册/运行/pid:轮询每 500ms 一次,不跑全域 print-disabled
19
+ const st = launchd.printState(ctx.runner, ctx.uid, label);
18
20
  return !st.registered || (!st.running && st.pid === null);
19
21
  }
20
22
 
@@ -27,17 +29,16 @@ export function stopEdgeLink(ctx) {
27
29
  // 删两开关(peer 依赖 relay,见 design §5)。PathState:rm RELAY_ON 不杀
28
30
  // 进程,但阻止退出后重拉
29
31
  ctx.state.removeOn(['relay', 'peer']);
30
- if (!launchd.inspect(ctx.runner, ctx.uid, label).registered) return { gone: true, label };
32
+ if (!launchd.printState(ctx.runner, ctx.uid, label).registered)
33
+ return { gone: true, label };
31
34
 
32
- let remaining = TERM_BUDGET_MS;
33
- for (let attempt = 0; attempt < 2; attempt += 1) {
35
+ for (let attempt = 0; attempt < TERM_ROUNDS; attempt += 1) {
34
36
  launchd.killJob(ctx.runner, ctx.uid, label, 'TERM');
35
- const end = Date.now() + Math.min(20_000, remaining);
37
+ const end = Date.now() + ROUND_MS;
36
38
  while (Date.now() < end) {
37
39
  if (isGone(ctx, label)) return { gone: true, label };
38
40
  sleepMs(POLL_MS);
39
41
  }
40
- remaining -= 20_000;
41
42
  }
42
43
  return { gone: isGone(ctx, label), label };
43
44
  }
@@ -4,9 +4,32 @@
4
4
  // - 休眠判据只用 print-disabled 字典(print 正文无稳定字段)
5
5
  // - 任何 bootstrap 前无条件先 enable(override 残留时 bootstrap error 5)
6
6
  // - enable 本身不触发首发,唤醒必须 kickstart -k
7
+ import fs from 'node:fs';
8
+ import { edgeLabel } from './render.mjs';
9
+
7
10
  /** @param {number} uid */
8
11
  export const guiDomain = (uid) => `gui/${uid}`;
9
12
 
13
+ const EDGE_PLIST_PREFIX = edgeLabel(''); // 'local.ssh-net-uplink-edge-'
14
+
15
+ /**
16
+ * 磁盘 LaunchAgents 里 uplink-edge job plist 的别名清单(install/status/
17
+ * uninstall 共用;topology 已删的机器只能靠这个 glob 兜底发现,目录不存在
18
+ * 时空)。
19
+ * @param {string} launchAgentsDir
20
+ * @returns {string[]}
21
+ */
22
+ export function edgeAliasesOnDisk(launchAgentsDir) {
23
+ try {
24
+ return fs
25
+ .readdirSync(launchAgentsDir)
26
+ .filter((f) => f.startsWith(EDGE_PLIST_PREFIX) && f.endsWith('.plist'))
27
+ .map((f) => f.slice(EDGE_PLIST_PREFIX.length, -'.plist'.length));
28
+ } catch {
29
+ return [];
30
+ }
31
+ }
32
+
10
33
  /**
11
34
  * print 正文解析。
12
35
  * @param {{code:number|null, stderr:string, stdout:string}} result
@@ -59,22 +82,62 @@ export function parseDisabled(stdout) {
59
82
  */
60
83
 
61
84
  /**
62
- * print + print-disabled 合成四态所需的全部事实。
85
+ * 整个 gui 域的 disabled override 字典(一次 print-disabled)。同一域多个
86
+ * label 体检时循环外取一次、inspectWith 共用——全域 dump 与查哪个 label 无关。
87
+ * @param {import('./exec.mjs').Runner} runner
88
+ * @param {number} uid
89
+ * @returns {Map<string, boolean>}
90
+ */
91
+ export function disabledMap(runner, uid) {
92
+ return parseDisabled(
93
+ runner.run('launchctl', ['print-disabled', guiDomain(uid)]).stdout,
94
+ );
95
+ }
96
+
97
+ /**
98
+ * print + 预取字典合成四态(inspect 的 map 注入版;字典由调用方循环外取一次
99
+ * 共用)。print 先行:未注册不碰传入 map。
100
+ * @param {import('./exec.mjs').Runner} runner
101
+ * @param {number} uid
102
+ * @param {string} label
103
+ * @param {Map<string, boolean>} map disabledMap 的产物
104
+ * @returns {JobState}
105
+ */
106
+ export function inspectWith(runner, uid, label, map) {
107
+ const printed = printState(runner, uid, label);
108
+ if (!printed.registered) {
109
+ return { registered: false, disabled: false, running: false, pid: null, runs: null, lastExitCode: null };
110
+ }
111
+ return { ...printed, disabled: map.get(label) === true };
112
+ }
113
+
114
+ /**
115
+ * print + print-disabled 合成四态所需的全部事实(单 label 便捷封装)。
116
+ * print 在前、未注册即返回(不白跑全域 dump)。
63
117
  * @param {import('./exec.mjs').Runner} runner
64
118
  * @param {number} uid
65
119
  * @param {string} label
66
120
  * @returns {JobState}
67
121
  */
68
122
  export function inspect(runner, uid, label) {
69
- const domain = guiDomain(uid);
70
- const printed = parsePrint(runner.run('launchctl', ['print', `${domain}/${label}`]));
123
+ const printed = printState(runner, uid, label);
71
124
  if (!printed.registered) {
72
125
  return { registered: false, disabled: false, running: false, pid: null, runs: null, lastExitCode: null };
73
126
  }
74
- const disabledMap = parseDisabled(
75
- runner.run('launchctl', ['print-disabled', domain]).stdout,
127
+ return { ...printed, disabled: disabledMap(runner, uid).get(label) === true };
128
+ }
129
+
130
+ /**
131
+ * 只要注册/运行/pid 事实(stop 轮询专用):不跑全域 print-disabled。
132
+ * @param {import('./exec.mjs').Runner} runner
133
+ * @param {number} uid
134
+ * @param {string} label
135
+ * @returns {ReturnType<typeof parsePrint>}
136
+ */
137
+ export function printState(runner, uid, label) {
138
+ return parsePrint(
139
+ runner.run('launchctl', ['print', `${guiDomain(uid)}/${label}`]),
76
140
  );
77
- return { ...printed, disabled: disabledMap.get(label) === true };
78
141
  }
79
142
 
80
143
  /** 以下均返回原始 RunResult,由命令层判 code(编排顺序是冻结行为,勿在此吞错)。 */
@@ -86,6 +149,20 @@ export const bootstrap = (runner, uid, plistPath) =>
86
149
  runner.run('launchctl', ['bootstrap', guiDomain(uid), plistPath]);
87
150
  export const kickstart = (runner, uid, label) =>
88
151
  runner.run('launchctl', ['kickstart', '-k', `${guiDomain(uid)}/${label}`]);
152
+ /**
153
+ * enable + bootstrap 连发(未注册 job 的加载序列)。任一步失败抛错——
154
+ * enable 失败若吞掉,只会以 bootstrap error 5 的间接形式浮出,排障被带偏。
155
+ * @param {import('./exec.mjs').Runner} runner
156
+ * @param {number} uid
157
+ * @param {string} label
158
+ * @param {string} plistPath
159
+ */
160
+ export function enableBootstrap(runner, uid, label, plistPath) {
161
+ const en = enable(runner, uid, label);
162
+ if (en.code !== 0) throw new Error(`enable 失败(${label}):${en.stderr.trim()}`);
163
+ const b = bootstrap(runner, uid, plistPath);
164
+ if (b.code !== 0) throw new Error(`bootstrap 失败(${label}):${b.stderr.trim()}`);
165
+ }
89
166
  /** kickstart 对 disabled job 被拒(实测矩阵),kickstart 前一律幂等 enable。
90
167
  * enable 失败要报(本文件宣言「勿在此吞错」):否则以 kickstart 被拒的
91
168
  * 间接形式浮出,排障方向被带偏。 */
@@ -3,13 +3,47 @@
3
3
  // 渲染结果与现文件字节相同则不 bootout——install 幂等不断连。
4
4
  import fs from 'node:fs';
5
5
  import * as launchd from './launchd.mjs';
6
+ import { readFileOrNull } from './fsutil.mjs';
6
7
 
7
- /** 同目录 tmp + rename 原子落盘。 */
8
- export function writeFileAtomic(file, content, mode = 0o644) {
9
- const tmp = `${file}.tmp-${process.pid}`;
10
- fs.writeFileSync(tmp, content, { mode });
11
- fs.renameSync(tmp, file);
12
- fs.chmodSync(file, mode);
8
+ /**
9
+ * 确保一个在册 job 已加载可用(launchctl 四态状态机的唯一实现,实测矩阵见
10
+ * launchd.mjs 头注;syncPlist 的「文件没变」分支与 `start core` 共用)。
11
+ * @param {object} ctx
12
+ * @param {{label:string, plistPath:string}} job
13
+ * @param {object} [opts]
14
+ * @param {boolean} [opts.kickWhenStopped=false] registered+enabled 但没在跑时
15
+ * 是否踢活:install 对账不踢(不断连),start 要踢
16
+ * @param {boolean} [opts.reviveRunningDisabled=false] registered+disabled 但
17
+ * 还在跑时是否踢重启:install 要 revive,start 只清 override、不闪断
18
+ * @returns {'bootstrapped'|'kickstarted'|'enabled'|'unchanged'}
19
+ */
20
+ export function ensureLoaded(ctx, { label, plistPath }, {
21
+ kickWhenStopped = false,
22
+ reviveRunningDisabled = false,
23
+ } = {}) {
24
+ const { runner, uid } = ctx;
25
+ const st = launchd.inspect(runner, uid, label);
26
+ if (!st.registered) {
27
+ launchd.enableBootstrap(runner, uid, label, plistPath);
28
+ return 'bootstrapped';
29
+ }
30
+ if (st.disabled && (!st.running || reviveRunningDisabled)) {
31
+ const k = launchd.kickstartEnabled(runner, uid, label);
32
+ if (k.code !== 0) throw new Error(`kickstart 失败(${label}):${k.stderr.trim()}`);
33
+ return 'kickstarted';
34
+ }
35
+ if (st.disabled) {
36
+ // 在跑但 override 残留:只 enable 清掉,防退出后不重拉,不打断现连接
37
+ const en = launchd.enable(runner, uid, label);
38
+ if (en.code !== 0) throw new Error(`enable 失败(${label}):${en.stderr.trim()}`);
39
+ return 'enabled';
40
+ }
41
+ if (kickWhenStopped && !st.running) {
42
+ const k = launchd.kickstart(runner, uid, label);
43
+ if (k.code !== 0) throw new Error(`kickstart 失败(${label}):${k.stderr.trim()}`);
44
+ return 'kickstarted';
45
+ }
46
+ return 'unchanged';
13
47
  }
14
48
 
15
49
  /**
@@ -24,29 +58,16 @@ export function syncPlist(ctx, { label, plistPath, content }) {
24
58
  fs.mkdirSync(paths.launchAgentsDir, { recursive: true });
25
59
  fs.mkdirSync(paths.logsDir, { recursive: true });
26
60
 
27
- let existing = null;
28
- try {
29
- existing = fs.readFileSync(plistPath, 'utf8');
30
- } catch {
31
- existing = null;
32
- }
61
+ const existing = readFileOrNull(plistPath);
33
62
 
34
63
  if (existing === content) {
35
- const st = launchd.inspect(runner, uid, label);
36
64
  // registered+disabled(stop 中途失败/手工 disable)不是「已部署」:
37
65
  // enable 后拉起,否则 install 报 unchanged 却没在跑、start 的 kickstart 被拒
38
- if (st.registered && !st.disabled) return { unchanged: true };
39
- const en = launchd.enable(runner, uid, label);
40
- // enable 失败要报(launchd.mjs 宣言「勿在此吞错」):否则错误以
41
- // bootstrap error 5 / kickstart 被拒的间接形式浮出,排障方向被带偏
42
- if (en.code !== 0) throw new Error(`enable 失败(${label}):${en.stderr.trim()}`);
43
- if (!st.registered) {
44
- const b = launchd.bootstrap(runner, uid, plistPath);
45
- if (b.code !== 0) throw new Error(`bootstrap 失败(${label}):${b.stderr.trim()}`);
46
- return { registered: true };
47
- }
48
- const k = launchd.kickstart(runner, uid, label);
49
- if (k.code !== 0) throw new Error(`kickstart 失败(${label}):${k.stderr.trim()}`);
66
+ const action = ensureLoaded(ctx, { label, plistPath }, {
67
+ reviveRunningDisabled: true,
68
+ });
69
+ if (action === 'unchanged') return { unchanged: true };
70
+ if (action === 'bootstrapped') return { registered: true };
50
71
  return { revived: true };
51
72
  }
52
73
 
@@ -67,15 +88,11 @@ export function syncPlist(ctx, { label, plistPath, content }) {
67
88
  }
68
89
  fs.renameSync(tmp, plistPath);
69
90
  fs.chmodSync(plistPath, 0o644);
70
- // enable 失败要报(launchd.mjs 宣言「勿在此吞错」):否则错误以 bootstrap
71
- // error 5 的间接形式浮出,排障方向被带偏。取舍:此处 job 已 bootout、
72
- // enable 失败即不 bootstrap(停机态)——launchctl enable 对已 enable 的
73
- // job 幂等返回 0,真失败(override 数据库损坏)下 bootstrap 也过不去
74
- // (error 5),可见性优先于「也许 bootstrap 能侥幸成功」
75
- const en = launchd.enable(runner, uid, label); // 无条件先 enable(override 残留时 bootstrap error 5)
76
- if (en.code !== 0) throw new Error(`enable 失败(${label}):${en.stderr.trim()}`);
77
- const b = launchd.bootstrap(runner, uid, plistPath);
78
- if (b.code !== 0) throw new Error(`bootstrap 失败(${label}):${b.stderr.trim()}`);
91
+ // 无条件先 enable(override 残留时 bootstrap error 5;launchd.mjs 宣言
92
+ // 「勿在此吞错」)。取舍:此处 job 已 bootout、enable 失败即不 bootstrap
93
+ //(停机态)——真失败(override 数据库损坏)下 bootstrap 也过不去(error 5),
94
+ // 可见性优先于「也许 bootstrap 能侥幸成功」
95
+ launchd.enableBootstrap(runner, uid, label, plistPath);
79
96
  return { deployed: true };
80
97
  }
81
98
 
@@ -0,0 +1,41 @@
1
+ // 运行时实体/服务软链清单的单一来源(install 对账与 status 体检共用,
2
+ // design §2.3)。清单即契约:新增包脚本只改这里,漏装与假报「组件异常」
3
+ // 不会再分叉。
4
+ //
5
+ // entities:[bin 名, 包脚本名]——原名实体;links:[带机器名软链, 实体名]。
6
+ // core 安装时按磁盘在册 edge 追加 uplink-edge(见 installCore),单台 edge
7
+ // 报名时的一对固定对账直接写在 register.mjs——都只有一个消费方,不进这里。
8
+ import { linkLinkName, relayLinkName } from './render.mjs';
9
+
10
+ /**
11
+ * edge 形态:基础三件套恒装;装了 link 附加件才加第 4 实体与带机器名软链。
12
+ * @param {import('./config.mjs').Topology} topo
13
+ * @param {boolean} linkInstalled
14
+ */
15
+ export function edgeRuntimePlan(topo, linkInstalled) {
16
+ /** @type {[string,string][]} */
17
+ const entities = [
18
+ ['sn-probe', 'sn-probe'],
19
+ ['sn-route', 'sn-route'], // Match exec 按需选路 + 成功后本地通知/秒切(design §2.2)
20
+ ['sn-ipv6', 'sn-ipv6'],
21
+ ];
22
+ /** @type {[string,string][]} */
23
+ const links = [];
24
+ if (linkInstalled) {
25
+ entities.push(['ssh-net-link-core', 'ssh-net-link-core']);
26
+ links.push([linkLinkName(topo.core.alias), 'ssh-net-link-core']);
27
+ }
28
+ return { entities, links };
29
+ }
30
+
31
+ /**
32
+ * relay 一件套:core/node 常驻服务的基础形态(installCore 在其上追加在册
33
+ * edge 的回拨组件)。
34
+ * @param {import('./config.mjs').Topology} topo
35
+ */
36
+ export function relayRuntimePlan(topo) {
37
+ return {
38
+ entities: [['ssh-net-uplink-relay', 'ssh-net-uplink-relay']],
39
+ links: [[relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay']],
40
+ };
41
+ }
@@ -11,8 +11,7 @@
11
11
  // state/ 易变状态(两开关、edges v6、PROBE_FAIL、ENSURE)
12
12
  // link.enabled link 附加件的持久安装意图(树根,不放 state/)
13
13
  // conf.d/ 渲染给 ssh Include 的配置片段(生成物,不进 dotfiles):
14
- // routes edge:Match 选路块(install 渲染)
15
- // vscode-mark edge:VS Code 连接打标块(install 渲染常量)
14
+ // routes edge:Match 选路块 + 尾部 VS Code 打标块(install 渲染)
16
15
  // edge-<别名> core:edge 在线入口(_register 写/休眠删)
17
16
  // ~/.ssh/config dotfiles 托管,顶部 Include conf.d/* + 静态主机块(IP 唯一来源)
18
17
  import path from 'node:path';
@@ -45,7 +44,6 @@ export function machinePaths(env = process.env) {
45
44
  const sshNetDir = path.join(home, '.ssh', 'ssh-net');
46
45
  const stateDir = path.join(sshNetDir, 'state');
47
46
  return Object.freeze({
48
- home,
49
47
  sshDir: path.join(home, '.ssh'),
50
48
  sshConfigFile: path.join(home, '.ssh', 'config'),
51
49
  sshNetDir,
@@ -53,9 +51,9 @@ export function machinePaths(env = process.env) {
53
51
  binDir: path.join(sshNetDir, 'bin'),
54
52
  runtimeVersionFile: path.join(sshNetDir, 'runtime-version'),
55
53
  stateDir,
56
- // ssh Include 片段目录(design §4.2,2026-10-01):routes、vscode-mark
57
- // 仅 edge install 写;edge-<别名> 仅 core _register/休眠写删;node 不建。
58
- // Include glob 零匹配静默,主 config 五台可同份
54
+ // ssh Include 片段目录(design §4.2,2026-10-01):routes 仅 edge install
55
+ // 写(含尾部 VS Code 打标块);edge-<别名> 仅 core _register/休眠写删;
56
+ // node 不建。Include glob 零匹配静默,主 config 五台可同份
59
57
  confDir: path.join(sshNetDir, 'conf.d'),
60
58
  routesFile: path.join(sshNetDir, 'conf.d', 'routes'),
61
59
  /** @param {string} alias edge 别名 */
@@ -110,13 +110,15 @@ export function descendantsOf(tree, root) {
110
110
  * @param {import('./exec.mjs').Runner} runner
111
111
  * @param {number} port
112
112
  * @param {number|null} jobPid link job 的 pid(未注册给 null)
113
+ * @param {Map<number,number>} [tree] 预检全程进程树不变:多端口预检时调用方
114
+ * 建一次传入复用,缺省本函数自取
113
115
  * @returns {{kind:'free'|'ours'|'foreign', pids:number[]}}
114
116
  */
115
- export function classifyLocalPort(runner, port, jobPid) {
117
+ export function classifyLocalPort(runner, port, jobPid, tree) {
116
118
  const pids = listListeners(runner, port);
117
119
  if (pids.length === 0) return { kind: 'free', pids: [] };
118
120
  if (jobPid === null) return { kind: 'foreign', pids };
119
- const ok = new Set([jobPid, ...descendantsOf(processTree(runner), jobPid)]);
121
+ const ok = new Set([jobPid, ...descendantsOf(tree ?? processTree(runner), jobPid)]);
120
122
  return pids.every((p) => ok.has(p))
121
123
  ? { kind: 'ours', pids }
122
124
  : { kind: 'foreign', pids };
@@ -0,0 +1,47 @@
1
+ // core 侧 edge 登记的不变式(install reconcile、status 体检、报名 _register
2
+ // 三处共同遵守):
3
+ // conf.d/edge-<别名> 存在 ⟺ 回拨 job 在册且未休眠 ⋀ state/edges/<别名> 有 v6
4
+ // 片段内容恒为 edge 行 + 该 v6 的渲染。state 与片段永远两处同写/同删——
5
+ // 没有 job 兜底的片段是指向陈旧 v6 的假入口。
6
+ import { syncConfFile, removeConfFile } from './conf.mjs';
7
+ import { renderEdgeHost } from './render.mjs';
8
+
9
+ /**
10
+ * edge 在线入口片段的期望内容。
11
+ * @param {{alias:string, aliases:string[], user:string}} edge topology edge 行
12
+ * @param {string} v6
13
+ * @returns {string}
14
+ */
15
+ export function edgeFragmentContent(edge, v6) {
16
+ return renderEdgeHost({
17
+ alias: edge.alias, aliases: edge.aliases, user: edge.user, v6,
18
+ });
19
+ }
20
+
21
+ /**
22
+ * 片段此刻是否应当存在:job 在册、未休眠(enabled)、state 有 v6 三者齐备。
23
+ * @param {{registered:boolean, disabled:boolean}} jobState launchd.inspect 的结果
24
+ * @param {string|null} v6
25
+ * @returns {boolean}
26
+ */
27
+ export function edgeFragmentShouldExist(jobState, v6) {
28
+ return jobState.registered && !jobState.disabled && v6 !== null;
29
+ }
30
+
31
+ /**
32
+ * 两处同写(唯一写者 _register;install reconcile 用 syncConfFile 只补片段):
33
+ * state/edges/<别名> 给 uplink-edge 脚本机读,conf.d/edge-<别名> 给人当入口。
34
+ * @param {object} ctx
35
+ * @param {{alias:string, aliases:string[], user:string}} edge
36
+ * @param {string} v6
37
+ */
38
+ export function writeEdgeRegistration(ctx, edge, v6) {
39
+ ctx.state.writeEdgeV6(edge.alias, v6);
40
+ syncConfFile(ctx.paths.edgeHostFile(edge.alias), edgeFragmentContent(edge, v6));
41
+ }
42
+
43
+ /** 两处同删(未报名过的失败路径、休眠收尸)。 */
44
+ export function removeEdgeRegistration(ctx, alias) {
45
+ ctx.state.removeEdgeV6(alias);
46
+ removeConfFile(ctx.paths.edgeHostFile(alias));
47
+ }