@yourstandby/fabric 0.0.0-stage → 0.1.0
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 +24 -2
- package/dist/daemon.js +3797 -0
- package/dist/index.js +3916 -0
- package/package.json +30 -4
- package/src/artifacts.test.ts +148 -0
- package/src/artifacts.ts +247 -0
- package/src/daemon-runner.ts +218 -0
- package/src/daemon.ts +524 -0
- package/src/discovery.ts +332 -0
- package/src/dispatch.test.ts +154 -0
- package/src/dispatch.ts +459 -0
- package/src/dispatcher.test.ts +321 -0
- package/src/dispatcher.ts +794 -0
- package/src/fabric-apply.test.ts +115 -0
- package/src/fabric-apply.ts +137 -0
- package/src/fabric-avatar.test.ts +51 -0
- package/src/fabric-discovery.test.ts +100 -0
- package/src/fabric-history.test.ts +68 -0
- package/src/fabric-keepalive.test.ts +112 -0
- package/src/fabric-notify.test.ts +269 -0
- package/src/fabric-pairing.test.ts +164 -0
- package/src/fabric-runner.test.ts +113 -0
- package/src/fabric-runner.ts +167 -0
- package/src/fabric-score.test.ts +74 -0
- package/src/fabric-server.ts +101 -0
- package/src/fabric-service.test.ts +279 -0
- package/src/fabric-service.ts +745 -0
- package/src/fabric-view.test.ts +118 -0
- package/src/fabric-view.ts +182 -0
- package/src/fabric-worktree.test.ts +139 -0
- package/src/fabric-worktree.ts +232 -0
- package/src/history.ts +127 -0
- package/src/host-load.ts +18 -0
- package/src/index.ts +27 -0
- package/src/pairing.test.ts +212 -0
- package/src/pairing.ts +342 -0
- package/src/peer-store.test.ts +212 -0
- package/src/peer-store.ts +243 -0
- package/src/transport.test.ts +247 -0
- package/src/transport.ts +709 -0
|
@@ -0,0 +1,745 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fabric 的组装根:身份 + peer 表 + 监听 + 发现 + 调度 + 清理。
|
|
3
|
+
*
|
|
4
|
+
* server.ts 只需要 「start() / stop() / snapshot() / dispatch() / pair()」五个入口,
|
|
5
|
+
* 不必知道内部有几种模块——这样接线只有一处,回归面积最小。
|
|
6
|
+
*/
|
|
7
|
+
import {
|
|
8
|
+
FABRIC_DEFAULT_PORT,
|
|
9
|
+
FABRIC_FEATURES,
|
|
10
|
+
type FabricGrant,
|
|
11
|
+
type FabricPeer,
|
|
12
|
+
} from "../../../contract/domains/fabric.ts";
|
|
13
|
+
import {
|
|
14
|
+
ArtifactStore,
|
|
15
|
+
ARTIFACT_REFERENCED_TTL_MS,
|
|
16
|
+
} from "./artifacts.ts";
|
|
17
|
+
import { FabricDispatcher, sanitizeLabels, type FabricRemoteRunner, type SubmitInput } from "./dispatcher.ts";
|
|
18
|
+
import { TaskLedger, isTerminalState } from "./dispatch.ts";
|
|
19
|
+
import {
|
|
20
|
+
discoverPeer,
|
|
21
|
+
scanLan,
|
|
22
|
+
startAnnouncer,
|
|
23
|
+
startResponder,
|
|
24
|
+
type Announcer,
|
|
25
|
+
type DiscoveryResponder,
|
|
26
|
+
type NearbyDevice,
|
|
27
|
+
} from "./discovery.ts";
|
|
28
|
+
import { dialFabricLink, requestPairing as requestPairingTransport } from "./transport.ts";
|
|
29
|
+
import { applyPatchToRepo, type ApplyPatchResult } from "./fabric-apply.ts";
|
|
30
|
+
import { startFabricListener, type FabricListener } from "./fabric-server.ts";
|
|
31
|
+
import {
|
|
32
|
+
PAIRING_WINDOW_MS,
|
|
33
|
+
PairingGuard,
|
|
34
|
+
PairingSession,
|
|
35
|
+
loadOrCreateIdentity,
|
|
36
|
+
nodeIdOf,
|
|
37
|
+
type FabricIdentity,
|
|
38
|
+
} from "./pairing.ts";
|
|
39
|
+
import { deletePeer, getPeer, listPeers, savePeer } from "./peer-store.ts";
|
|
40
|
+
|
|
41
|
+
/** 终态任务记录留一天:够事后追查,又不至于把 tasks 目录堆成垃圾场。 */
|
|
42
|
+
export const FABRIC_TASK_RETENTION_MS = 24 * 60 * 60 * 1000;
|
|
43
|
+
|
|
44
|
+
export interface FabricServiceOptions {
|
|
45
|
+
agentDir: string;
|
|
46
|
+
appVersion?: string;
|
|
47
|
+
runner?: FabricRemoteRunner;
|
|
48
|
+
/** 本机对外宣告的能力标签(例如 gpu / build)。 */
|
|
49
|
+
labels?: () => string[];
|
|
50
|
+
host?: string;
|
|
51
|
+
port?: number;
|
|
52
|
+
/** 共享上下文名:发现包里带它,防止同网不同团队互相认领。 */
|
|
53
|
+
ctx?: string;
|
|
54
|
+
log?: (message: string) => void;
|
|
55
|
+
now?: () => number;
|
|
56
|
+
/** 有配对请求进来时通知本机 UI:面板从「4 秒轮询」变成「有人敲门立刻弹出来」。 */
|
|
57
|
+
onPairRequestNotice?: (request: InboundPairRequest) => void;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** 未配对对端发来的配对请求(等本机用户点允许)。 */
|
|
61
|
+
export interface InboundPairRequest {
|
|
62
|
+
nodeId: string;
|
|
63
|
+
publicKey: string;
|
|
64
|
+
name: string;
|
|
65
|
+
address: string;
|
|
66
|
+
port: number;
|
|
67
|
+
/** 两端显示同一个 6 位对照码,用户核对一致再点允许。 */
|
|
68
|
+
sas: string;
|
|
69
|
+
at: number;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 本机发起、等对方点允许的配对请求。 */
|
|
73
|
+
export interface OutboundPairRequest {
|
|
74
|
+
nodeId: string;
|
|
75
|
+
publicKey: string;
|
|
76
|
+
name: string;
|
|
77
|
+
address: string;
|
|
78
|
+
port: number;
|
|
79
|
+
sas: string;
|
|
80
|
+
at: number;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** diff 预览上限:再大也只给这么多,够看改动、不够撑爆 WebView。 */
|
|
84
|
+
export const FABRIC_DIFF_PREVIEW_BYTES = 256 * 1024;
|
|
85
|
+
|
|
86
|
+
/** 配对请求的保鲜期:过期就丢,避免面板里躺着一周前的请求。 */
|
|
87
|
+
export const FABRIC_PAIR_REQUEST_TTL_MS = 10 * 60 * 1000;
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 扫描结果缓存:面板 2 秒扫一次,而「点某台配对」必须用同一份结果里的地址。
|
|
91
|
+
* 缓存也顺带挡住「前端自己编一个地址让宿主去连」——地址只能来自本机广播。
|
|
92
|
+
*/
|
|
93
|
+
export const FABRIC_SCAN_CACHE_MS = 5_000;
|
|
94
|
+
|
|
95
|
+
export interface PairInput {
|
|
96
|
+
nodeId: string;
|
|
97
|
+
publicKey: string;
|
|
98
|
+
name: string;
|
|
99
|
+
address: string;
|
|
100
|
+
port: number;
|
|
101
|
+
grants: FabricGrant;
|
|
102
|
+
/** 用户在弹窗上比对的 6 位码;不给就视为「只点确认、不比码」。 */
|
|
103
|
+
sas?: string;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export type PairResult =
|
|
107
|
+
| { ok: true; peer: FabricPeer; sas: string }
|
|
108
|
+
| { ok: false; code: string; reason: string };
|
|
109
|
+
|
|
110
|
+
export class FabricService {
|
|
111
|
+
readonly identity: FabricIdentity;
|
|
112
|
+
readonly dispatcher: FabricDispatcher;
|
|
113
|
+
readonly artifacts: ArtifactStore;
|
|
114
|
+
readonly outbound: TaskLedger;
|
|
115
|
+
readonly inbound: TaskLedger;
|
|
116
|
+
private readonly options: FabricServiceOptions;
|
|
117
|
+
private readonly guard = new PairingGuard();
|
|
118
|
+
private listener: FabricListener | null = null;
|
|
119
|
+
private responder: DiscoveryResponder | null = null;
|
|
120
|
+
private pendingPair: PairingSession | null = null;
|
|
121
|
+
/** 入站配对请求:等本机用户点「允许」。 */
|
|
122
|
+
private readonly inboundRequests = new Map<string, InboundPairRequest>();
|
|
123
|
+
/** 出站配对请求:等对端用户点「允许」,之后本机自动补上 peer 记录。 */
|
|
124
|
+
private readonly outboundRequests = new Map<string, OutboundPairRequest>();
|
|
125
|
+
/** 被明确拒绝过的对端(带时间):发起方下一次探测就能立刻知道,不用等 TTL。 */
|
|
126
|
+
private readonly deniedRequests = new Map<string, number>();
|
|
127
|
+
private started = false;
|
|
128
|
+
private announcer: Announcer | null = null;
|
|
129
|
+
/** 默认开:自家两台机器要能被零输入发现;公司/公共网可以在面板里关掉。 */
|
|
130
|
+
private discoverable = true;
|
|
131
|
+
private lastScan: { at: number; devices: NearbyDevice[] } | null = null;
|
|
132
|
+
|
|
133
|
+
constructor(options: FabricServiceOptions) {
|
|
134
|
+
this.options = options;
|
|
135
|
+
this.identity = loadOrCreateIdentity(options.agentDir, this.now());
|
|
136
|
+
this.artifacts = new ArtifactStore(options.agentDir);
|
|
137
|
+
this.outbound = new TaskLedger(options.agentDir, "outbound");
|
|
138
|
+
this.inbound = new TaskLedger(options.agentDir, "inbound");
|
|
139
|
+
this.dispatcher = new FabricDispatcher({
|
|
140
|
+
agentDir: options.agentDir,
|
|
141
|
+
identity: this.identity,
|
|
142
|
+
runner: options.runner,
|
|
143
|
+
artifacts: this.artifacts,
|
|
144
|
+
outbound: this.outbound,
|
|
145
|
+
inbound: this.inbound,
|
|
146
|
+
appVersion: options.appVersion,
|
|
147
|
+
log: options.log,
|
|
148
|
+
now: options.now,
|
|
149
|
+
// 任务结束时主动推给发起方;没连上就返回 false(对方下次对账再收尾)。
|
|
150
|
+
notify: (nodeId, frame) => this.listener?.publish(nodeId, frame) ?? false,
|
|
151
|
+
});
|
|
152
|
+
if (options.labels) this.dispatcher.labels = options.labels;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
private now(): number {
|
|
156
|
+
return this.options.now?.() ?? Date.now();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
get nodeId(): string {
|
|
160
|
+
return this.identity.nodeId;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
get port(): number {
|
|
164
|
+
return this.listener?.port ?? 0;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 启动:监听 + 应答发现。任何一个失败都不阻断另一个(跨网用不到广播,
|
|
169
|
+
* 端口占用也不该死掉整个 Host)——只记日志。
|
|
170
|
+
*/
|
|
171
|
+
async start(): Promise<{ port: number; discPort: number | null }> {
|
|
172
|
+
if (this.started) return { port: this.port, discPort: this.responder?.port ?? null };
|
|
173
|
+
this.started = true;
|
|
174
|
+
const listen = (port?: number) =>
|
|
175
|
+
startFabricListener({
|
|
176
|
+
identity: this.identity,
|
|
177
|
+
host: this.options.host ?? "0.0.0.0",
|
|
178
|
+
port,
|
|
179
|
+
appVersion: this.options.appVersion,
|
|
180
|
+
log: this.options.log,
|
|
181
|
+
isPaired: (nodeId) => Boolean(getPeer(this.options.agentDir, nodeId)),
|
|
182
|
+
onPairRequest: (info) => this.acceptPairRequest(info),
|
|
183
|
+
onRestrictedCall: async (method, _params, caller) => {
|
|
184
|
+
if (method !== "peer.status") {
|
|
185
|
+
throw new Error("E_UNAUTHORIZED");
|
|
186
|
+
}
|
|
187
|
+
// 受限会话上的 peer.status:只回答「敲门状态」,不暴露任何负载信息。
|
|
188
|
+
return {
|
|
189
|
+
restricted: true,
|
|
190
|
+
pending: this.inboundRequests.has(caller.nodeId),
|
|
191
|
+
denied: this.deniedRequests.has(caller.nodeId),
|
|
192
|
+
online: false,
|
|
193
|
+
queueDepth: 0,
|
|
194
|
+
hbAgeMs: null,
|
|
195
|
+
labels: [],
|
|
196
|
+
};
|
|
197
|
+
},
|
|
198
|
+
onCall: (method, params, caller) => {
|
|
199
|
+
// 档位来自配对记录,不来自对端自报:自报的一律不可信。
|
|
200
|
+
const peer = getPeer(this.options.agentDir, caller.nodeId);
|
|
201
|
+
if (!peer) throw new Error("E_PEER_UNKNOWN");
|
|
202
|
+
return this.dispatcher.handleInbound(method, params, {
|
|
203
|
+
nodeId: caller.nodeId,
|
|
204
|
+
grants: peer.grants,
|
|
205
|
+
});
|
|
206
|
+
},
|
|
207
|
+
});
|
|
208
|
+
try {
|
|
209
|
+
this.listener = await listen(this.options.port);
|
|
210
|
+
} catch (error) {
|
|
211
|
+
// 端口被占(同机多实例 / 别的程序)不该让整台机器的 Fabric 起不来:
|
|
212
|
+
// 退到系统分配的临时端口——跨网场景本来就由人填地址。
|
|
213
|
+
this.options.log?.(
|
|
214
|
+
`fabric listen on ${this.options.port ?? "default"} failed, falling back to ephemeral: ${
|
|
215
|
+
error instanceof Error ? error.message : String(error)
|
|
216
|
+
}`,
|
|
217
|
+
);
|
|
218
|
+
this.listener = await listen(0);
|
|
219
|
+
}
|
|
220
|
+
try {
|
|
221
|
+
this.responder = await startResponder({
|
|
222
|
+
nodeName: this.displayName(),
|
|
223
|
+
tcpPort: this.listener.port,
|
|
224
|
+
ctx: this.options.ctx ?? "piforge",
|
|
225
|
+
log: this.options.log,
|
|
226
|
+
});
|
|
227
|
+
} catch (error) {
|
|
228
|
+
this.options.log?.(
|
|
229
|
+
`fabric discovery disabled: ${error instanceof Error ? error.message : String(error)}`,
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
try {
|
|
233
|
+
this.announcer = await startAnnouncer({
|
|
234
|
+
nodeId: this.identity.nodeId,
|
|
235
|
+
tcpPort: this.listener.port,
|
|
236
|
+
...(this.options.appVersion ? { appVersion: this.options.appVersion } : {}),
|
|
237
|
+
enabled: () => this.discoverable,
|
|
238
|
+
log: this.options.log,
|
|
239
|
+
});
|
|
240
|
+
} catch (error) {
|
|
241
|
+
// 7799 被占用不该让 Fabric 起不来:退化成「只能手动填地址」,日志写清楚。
|
|
242
|
+
this.options.log?.(
|
|
243
|
+
`fabric announce disabled: ${error instanceof Error ? error.message : String(error)}`,
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
// 已配对机器各开一条常驻连接:配对即连,不手动取消就一直连着。
|
|
247
|
+
const keep = this.dispatcher.keepAlive();
|
|
248
|
+
if (keep.started.length > 0) {
|
|
249
|
+
this.options.log?.(`fabric keep-alive started for ${keep.started.length} peer(s)`);
|
|
250
|
+
}
|
|
251
|
+
return { port: this.listener.port, discPort: this.responder?.port ?? null };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async stop(): Promise<void> {
|
|
255
|
+
this.started = false;
|
|
256
|
+
this.dispatcher.close();
|
|
257
|
+
await this.announcer?.close();
|
|
258
|
+
this.announcer = null;
|
|
259
|
+
await this.responder?.close();
|
|
260
|
+
this.responder = null;
|
|
261
|
+
await this.listener?.close();
|
|
262
|
+
this.listener = null;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** 本机在发现包里的名字:主机名 + nodeId 前缀,两台机器重名也能区分。 */
|
|
266
|
+
displayName(): string {
|
|
267
|
+
return `${process.env.COMPUTERNAME ?? process.env.HOSTNAME ?? "piforge"}-${this.identity.nodeId.slice(0, 6)}`;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* 配对:算 SAS + ECDH,并(可选)核对用户看到的 6 位码;确认后才写 peer 记录。
|
|
272
|
+
* 失败不写任何持久化状态——「点了拒绝」等价于什么都没发生。
|
|
273
|
+
*/
|
|
274
|
+
pair(input: PairInput): PairResult {
|
|
275
|
+
const locked = this.guard.lockedUntil(input.nodeId);
|
|
276
|
+
if (locked > this.now()) {
|
|
277
|
+
return { ok: false, code: "E_PAIR_LOCKED", reason: `配对被锁定直到 ${new Date(locked).toISOString()}` };
|
|
278
|
+
}
|
|
279
|
+
let session: PairingSession;
|
|
280
|
+
try {
|
|
281
|
+
session = new PairingSession(this.identity, input.nodeId, input.publicKey, this.now(), {
|
|
282
|
+
windowMs: PAIRING_WINDOW_MS,
|
|
283
|
+
});
|
|
284
|
+
} catch (error) {
|
|
285
|
+
return { ok: false, code: "E_INVALID_PARAMS", reason: error instanceof Error ? error.message : "bad key" };
|
|
286
|
+
}
|
|
287
|
+
this.pendingPair = session;
|
|
288
|
+
const confirmed = session.confirm({ sas: input.sas }, this.now());
|
|
289
|
+
if (confirmed.ok === false) {
|
|
290
|
+
if (confirmed.code === "E_PAIR_LOCKED") this.guard.recordFailure(input.nodeId, this.now());
|
|
291
|
+
else if (confirmed.code === "E_PAIR_SAS_MISMATCH") this.guard.recordFailure(input.nodeId, this.now());
|
|
292
|
+
this.pendingPair = null;
|
|
293
|
+
return { ok: false, code: confirmed.code, reason: "配对未通过" };
|
|
294
|
+
}
|
|
295
|
+
this.guard.reset(input.nodeId);
|
|
296
|
+
const peer = savePeer(this.options.agentDir, {
|
|
297
|
+
nodeId: input.nodeId,
|
|
298
|
+
name: input.name,
|
|
299
|
+
address: input.address,
|
|
300
|
+
port: input.port,
|
|
301
|
+
grants: input.grants,
|
|
302
|
+
features: [...FABRIC_FEATURES],
|
|
303
|
+
appVersion: this.options.appVersion ?? "",
|
|
304
|
+
lastSeenAt: this.now(),
|
|
305
|
+
});
|
|
306
|
+
this.pendingPair = null;
|
|
307
|
+
// 配对前可能已有一条受限连接(只放行 pair.request),必须重建才派得出活。
|
|
308
|
+
this.dispatcher.resetConnection(peer.nodeId);
|
|
309
|
+
return { ok: true, peer, sas: session.sas };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** 当前待确认的配对:UI 拿 sas 显示给用户比对。 */
|
|
313
|
+
pendingSas(): string | null {
|
|
314
|
+
return this.pendingPair?.sas ?? null;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* 未配对对端敲门的处理:算出 SAS、排队等用户点允许,并回「收到了」。
|
|
319
|
+
* 注意这里不写任何 peer 记录——只有用户的点击会写。
|
|
320
|
+
*/
|
|
321
|
+
private async acceptPairRequest(info: {
|
|
322
|
+
nodeId: string;
|
|
323
|
+
publicKey: string;
|
|
324
|
+
name: string;
|
|
325
|
+
address: string;
|
|
326
|
+
port: number;
|
|
327
|
+
claimedPort: number;
|
|
328
|
+
}): Promise<{ pending: boolean; sas: string; publicKey: string }> {
|
|
329
|
+
this.prunePairRequests();
|
|
330
|
+
const session = new PairingSession(this.identity, info.nodeId, info.publicKey, this.now(), {
|
|
331
|
+
windowMs: FABRIC_PAIR_REQUEST_TTL_MS,
|
|
332
|
+
});
|
|
333
|
+
this.inboundRequests.set(info.nodeId, {
|
|
334
|
+
nodeId: info.nodeId,
|
|
335
|
+
publicKey: info.publicKey,
|
|
336
|
+
name: info.name || info.nodeId.slice(0, 6),
|
|
337
|
+
address: info.address,
|
|
338
|
+
port: info.claimedPort || info.port,
|
|
339
|
+
sas: session.sas,
|
|
340
|
+
at: this.now(),
|
|
341
|
+
});
|
|
342
|
+
this.options.log?.(`fabric pair request from ${info.nodeId} at ${info.address} (sas=${session.sas})`);
|
|
343
|
+
const stored = this.inboundRequests.get(info.nodeId);
|
|
344
|
+
if (stored) this.options.onPairRequestNotice?.(stored);
|
|
345
|
+
return { pending: true, sas: session.sas, publicKey: this.identity.publicKey };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** 面板轮询用:两边待确认的请求,都带 6 位对照码。 */
|
|
349
|
+
pendingRequests(): {
|
|
350
|
+
inbound: InboundPairRequest[];
|
|
351
|
+
outbound: OutboundPairRequest[];
|
|
352
|
+
denied: string[];
|
|
353
|
+
} {
|
|
354
|
+
this.prunePairRequests();
|
|
355
|
+
return {
|
|
356
|
+
inbound: [...this.inboundRequests.values()],
|
|
357
|
+
outbound: [...this.outboundRequests.values()],
|
|
358
|
+
denied: [...this.deniedRequests.keys()],
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
private prunePairRequests(now = this.now()): void {
|
|
363
|
+
for (const [nodeId, request] of this.inboundRequests) {
|
|
364
|
+
if (now - request.at > FABRIC_PAIR_REQUEST_TTL_MS) this.inboundRequests.delete(nodeId);
|
|
365
|
+
}
|
|
366
|
+
for (const [nodeId, request] of this.outboundRequests) {
|
|
367
|
+
if (now - request.at > FABRIC_PAIR_REQUEST_TTL_MS) this.outboundRequests.delete(nodeId);
|
|
368
|
+
}
|
|
369
|
+
for (const [nodeId, at] of this.deniedRequests) {
|
|
370
|
+
if (now - at > FABRIC_PAIR_REQUEST_TTL_MS) this.deniedRequests.delete(nodeId);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* 本机发起配对(「让对方点一下确认」的一半):
|
|
376
|
+
* 连过去只调 pair.request,然后等对方在它自己的面板上点允许。
|
|
377
|
+
*/
|
|
378
|
+
async requestPairing(input: {
|
|
379
|
+
address: string;
|
|
380
|
+
port: number;
|
|
381
|
+
name?: string;
|
|
382
|
+
}): Promise<{ ok: true; nodeId: string; sas: string } | { ok: false; code: string; reason: string }> {
|
|
383
|
+
try {
|
|
384
|
+
const reply = await requestPairingTransport({
|
|
385
|
+
identity: this.identity,
|
|
386
|
+
address: input.address,
|
|
387
|
+
port: input.port,
|
|
388
|
+
name: input.name ?? this.displayName(),
|
|
389
|
+
listenPort: this.port,
|
|
390
|
+
log: this.options.log,
|
|
391
|
+
});
|
|
392
|
+
const session = new PairingSession(this.identity, reply.nodeId, reply.publicKey, this.now(), {
|
|
393
|
+
windowMs: FABRIC_PAIR_REQUEST_TTL_MS,
|
|
394
|
+
});
|
|
395
|
+
this.outboundRequests.set(reply.nodeId, {
|
|
396
|
+
nodeId: reply.nodeId,
|
|
397
|
+
publicKey: reply.publicKey,
|
|
398
|
+
name: input.name ?? input.address,
|
|
399
|
+
address: input.address,
|
|
400
|
+
port: input.port,
|
|
401
|
+
sas: session.sas,
|
|
402
|
+
at: this.now(),
|
|
403
|
+
});
|
|
404
|
+
this.options.log?.(`fabric pair request sent to ${reply.nodeId} (sas=${session.sas})`);
|
|
405
|
+
return { ok: true, nodeId: reply.nodeId, sas: session.sas };
|
|
406
|
+
} catch (error) {
|
|
407
|
+
return {
|
|
408
|
+
ok: false,
|
|
409
|
+
code: error instanceof Error && "code" in error ? String((error as { code: unknown }).code) : "E_PEER_OFFLINE",
|
|
410
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* 本机用户点「允许 / 拒绝」(另一半)。
|
|
417
|
+
* 允许才会写 peer 记录——档位就是这一刻定的,之后不再悄悄提升。
|
|
418
|
+
*/
|
|
419
|
+
confirmPairRequest(
|
|
420
|
+
nodeId: string,
|
|
421
|
+
accept: boolean,
|
|
422
|
+
// 一键连默认只读:要给写权限必须重新配对一次,不能顺着「方便」悄悄升级。
|
|
423
|
+
grants: FabricGrant = "read-only",
|
|
424
|
+
name?: string,
|
|
425
|
+
): { ok: boolean; peer?: FabricPeer; code?: string } {
|
|
426
|
+
const request = this.inboundRequests.get(nodeId);
|
|
427
|
+
if (!request) return { ok: false, code: "E_PAIR_UNKNOWN" };
|
|
428
|
+
// 头像与短 ID 都从 nodeId 派生,而 nodeId 必须与公钥对得上——这里再校一次,
|
|
429
|
+
// 免得中间人拿别人的公钥配一个自己编的 nodeId,让两端「比头像」比了个假的。
|
|
430
|
+
if (nodeIdOf(request.publicKey) !== request.nodeId) {
|
|
431
|
+
this.inboundRequests.delete(nodeId);
|
|
432
|
+
this.guard.recordFailure(nodeId, this.now());
|
|
433
|
+
this.options.log?.(`fabric pair rejected: nodeId does not match public key (${nodeId})`);
|
|
434
|
+
return { ok: false, code: "E_PAIR_SAS_MISMATCH" };
|
|
435
|
+
}
|
|
436
|
+
this.inboundRequests.delete(nodeId);
|
|
437
|
+
if (!accept) {
|
|
438
|
+
// 记下拒绝:发起方下一次探测(peer.status)会收到 denied,立刻停等并提示用户。
|
|
439
|
+
this.deniedRequests.set(nodeId, this.now());
|
|
440
|
+
this.options.log?.(`fabric pair request from ${nodeId} rejected`);
|
|
441
|
+
return { ok: true };
|
|
442
|
+
}
|
|
443
|
+
const peer = savePeer(this.options.agentDir, {
|
|
444
|
+
nodeId: request.nodeId,
|
|
445
|
+
name: name?.trim() || request.name,
|
|
446
|
+
address: request.address,
|
|
447
|
+
// 记的是对端握手时的源端口:同机双实例、临时端口场景下猜 7788 会连错。
|
|
448
|
+
port: request.port || FABRIC_DEFAULT_PORT,
|
|
449
|
+
grants,
|
|
450
|
+
features: [...FABRIC_FEATURES],
|
|
451
|
+
appVersion: this.options.appVersion ?? "",
|
|
452
|
+
lastSeenAt: this.now(),
|
|
453
|
+
});
|
|
454
|
+
this.dispatcher.resetConnection(peer.nodeId);
|
|
455
|
+
return { ok: true, peer };
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* 出站请求的收尾:对端点允许后会开始接受正常握手,这里探一次成功就落盘。
|
|
460
|
+
* 用「探一次」而不是等推送,是因为未配对连接上没有可信的事件通道。
|
|
461
|
+
*/
|
|
462
|
+
async resolveOutboundPairings(): Promise<{ resolved: string[]; denied: string[] }> {
|
|
463
|
+
this.prunePairRequests();
|
|
464
|
+
const resolved: string[] = [];
|
|
465
|
+
const denied: string[] = [];
|
|
466
|
+
for (const [nodeId, request] of this.outboundRequests) {
|
|
467
|
+
// 「能握手」不等于「已被允许」:未配对连接本来就允许握手(只放行 pair.request)。
|
|
468
|
+
// 所以必须再调一个仅配对后可用的方法,用它来区分「已接受」和「还挂着」。
|
|
469
|
+
const link = await dialFabricLink({
|
|
470
|
+
identity: this.identity,
|
|
471
|
+
peer: { nodeId, address: request.address, port: request.port },
|
|
472
|
+
timeoutMs: 1_500,
|
|
473
|
+
log: this.options.log,
|
|
474
|
+
}).catch(() => null);
|
|
475
|
+
if (!link) continue;
|
|
476
|
+
let status: Record<string, unknown>;
|
|
477
|
+
try {
|
|
478
|
+
status = (await link.call("peer.status", {})) as Record<string, unknown>;
|
|
479
|
+
} catch {
|
|
480
|
+
link.close();
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
link.close();
|
|
484
|
+
if (status.restricted === true) {
|
|
485
|
+
// 还没被允许(或者已经被明确拒绝):拒绝就立刻收摊,别让用户等 10 分钟 TTL。
|
|
486
|
+
if (status.denied === true) {
|
|
487
|
+
this.outboundRequests.delete(nodeId);
|
|
488
|
+
this.deniedRequests.set(nodeId, this.now());
|
|
489
|
+
denied.push(nodeId);
|
|
490
|
+
}
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
// 本机记录的是「本机给对方的档位」:默认只读,提升要重新配对一次。
|
|
494
|
+
savePeer(this.options.agentDir, {
|
|
495
|
+
nodeId,
|
|
496
|
+
name: request.name,
|
|
497
|
+
address: request.address,
|
|
498
|
+
port: request.port,
|
|
499
|
+
grants: "read-only",
|
|
500
|
+
features: [...FABRIC_FEATURES],
|
|
501
|
+
appVersion: this.options.appVersion ?? "",
|
|
502
|
+
lastSeenAt: this.now(),
|
|
503
|
+
});
|
|
504
|
+
this.outboundRequests.delete(nodeId);
|
|
505
|
+
resolved.push(nodeId);
|
|
506
|
+
this.dispatcher.keepAlive();
|
|
507
|
+
}
|
|
508
|
+
return { resolved, denied };
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
unpair(nodeId: string): boolean {
|
|
512
|
+
const removed = deletePeer(this.options.agentDir, nodeId);
|
|
513
|
+
// 取消配对立刻断开常驻连接(这是唯一会主动断开的路径)。
|
|
514
|
+
if (removed) this.dispatcher.keepAlive();
|
|
515
|
+
return removed;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** 一键检索匹配:局域网广播找对端,返回 host:port。 */
|
|
519
|
+
async discover(wantNode: string, timeoutMs?: number): Promise<string | null> {
|
|
520
|
+
return discoverPeer({
|
|
521
|
+
wantNode,
|
|
522
|
+
ctx: this.options.ctx ?? "piforge",
|
|
523
|
+
timeoutMs,
|
|
524
|
+
log: this.options.log,
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* 取对端任务的 patch:本机没有就去对端拉一次再落库。
|
|
530
|
+
*
|
|
531
|
+
* diffFor() 只读本机 ArtifactStore,而 patch 是在**对端**生成的产物,
|
|
532
|
+
* 帧里只有引用。少了这一步拉取,「对端明明改了」在本机看起来就是空 diff。
|
|
533
|
+
*/
|
|
534
|
+
async fetchDiff(taskId: string): Promise<ReturnType<FabricService["diffFor"]>> {
|
|
535
|
+
const local = this.diffFor(taskId);
|
|
536
|
+
if (local) return local;
|
|
537
|
+
const record = this.outbound.get(taskId);
|
|
538
|
+
if (!record?.diffRef) return null;
|
|
539
|
+
await this.dispatcher.fetchArtifact(record.peerId, record.diffRef);
|
|
540
|
+
return this.diffFor(taskId);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* 急停:不再应答发现、断开全部连接、把每台已配对机器的档位降回 read-only。
|
|
545
|
+
*
|
|
546
|
+
* 这是「远程机器能在本机跑 bash」这条授权的唯一逃生门,必须一条命令生效:
|
|
547
|
+
* 只关 discoverable 不够(已配对连接还在),只断连接也不够(下次派活会自己重连)。
|
|
548
|
+
*/
|
|
549
|
+
panic(): { peers: number; revoked: number } {
|
|
550
|
+
this.discoverable = false;
|
|
551
|
+
const peers = listPeers(this.options.agentDir);
|
|
552
|
+
for (const peer of peers) {
|
|
553
|
+
savePeer(this.options.agentDir, { ...peer, grants: "read-only" });
|
|
554
|
+
}
|
|
555
|
+
this.dispatcher.close();
|
|
556
|
+
this.inboundRequests.clear();
|
|
557
|
+
this.options.log?.(
|
|
558
|
+
`fabric panic: 已断开全部连接,${peers.length} 台机器的档位降回 read-only`,
|
|
559
|
+
);
|
|
560
|
+
return { peers: peers.length, revoked: peers.length };
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* 「允许局域网发现」开关:关掉只是不应答匿名扫描(SBF3),
|
|
565
|
+
* 已配对的点名探测(SBF1)照常工作——否则关开关会把已经连着的机器一起弄丢。
|
|
566
|
+
*/
|
|
567
|
+
setDiscoverable(enabled: boolean): boolean {
|
|
568
|
+
this.discoverable = enabled;
|
|
569
|
+
this.options.log?.(`fabric announce ${enabled ? "enabled" : "disabled"}`);
|
|
570
|
+
return this.discoverable;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
isDiscoverable(): boolean {
|
|
574
|
+
return this.discoverable;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/** 扫一圈局域网;结果缓存几秒,配对时复用同一份(地址只能来自本机广播)。 */
|
|
578
|
+
async nearby(force = false): Promise<NearbyDevice[]> {
|
|
579
|
+
if (!force && this.lastScan && this.now() - this.lastScan.at < FABRIC_SCAN_CACHE_MS) {
|
|
580
|
+
return this.lastScan.devices;
|
|
581
|
+
}
|
|
582
|
+
const devices = await scanLan({ log: this.options.log });
|
|
583
|
+
// 把自己滤掉:同一台机器上的另一个实例也该出现,但本进程自己不该出现在列表里。
|
|
584
|
+
const others = devices.filter((device) => device.nodeId !== this.identity.nodeId);
|
|
585
|
+
this.lastScan = { at: this.now(), devices: others };
|
|
586
|
+
return others;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* 从扫描列表里挑一台配对:地址/端口取自本机扫描结果,不接受 UI 传进来的地址
|
|
591
|
+
* (UI 传来的地址等于让前端决定连到哪台机器)。
|
|
592
|
+
*/
|
|
593
|
+
async requestPairNearby(
|
|
594
|
+
nodeId: string,
|
|
595
|
+
name?: string,
|
|
596
|
+
): Promise<{ ok: true; nodeId: string; sas: string } | { ok: false; code: string; reason: string }> {
|
|
597
|
+
const devices = await this.nearby();
|
|
598
|
+
const device = devices.find((item) => item.nodeId === nodeId);
|
|
599
|
+
if (!device) {
|
|
600
|
+
return { ok: false, code: "E_PEER_OFFLINE", reason: "扫描列表里没有这台机器,可能刚断线" };
|
|
601
|
+
}
|
|
602
|
+
return this.requestPairing({
|
|
603
|
+
address: device.address,
|
|
604
|
+
port: device.tcpPort,
|
|
605
|
+
...(name ? { name } : {}),
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
snapshot(): {
|
|
610
|
+
nodeId: string;
|
|
611
|
+
/** 本机公钥:配对时对方要抄的就是它(公钥本来就不是秘密)。 */
|
|
612
|
+
publicKey: string;
|
|
613
|
+
displayName: string;
|
|
614
|
+
port: number;
|
|
615
|
+
/** 本机是否在应答局域网扫描。 */
|
|
616
|
+
discoverable: boolean;
|
|
617
|
+
peers: FabricPeer[];
|
|
618
|
+
loads: ReturnType<FabricDispatcher["snapshot"]>["loads"];
|
|
619
|
+
tasks: ReturnType<FabricDispatcher["snapshot"]>["tasks"];
|
|
620
|
+
} {
|
|
621
|
+
const snap = this.dispatcher.snapshot();
|
|
622
|
+
return {
|
|
623
|
+
nodeId: this.identity.nodeId,
|
|
624
|
+
publicKey: this.identity.publicKey,
|
|
625
|
+
displayName: this.displayName(),
|
|
626
|
+
port: this.port,
|
|
627
|
+
discoverable: this.discoverable,
|
|
628
|
+
...snap,
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
async dispatch(input: SubmitInput): Promise<Awaited<ReturnType<FabricDispatcher["submit"]>>> {
|
|
633
|
+
return this.dispatcher.submit(input);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** 断线对账:重连后第一件事,先问对端干完没有,再谈重派。 */
|
|
637
|
+
async reconcile(): Promise<{ lost: string[]; done: string[] }> {
|
|
638
|
+
return this.dispatcher.reconcile();
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/** 磁盘清理:无主产物 24h、有主 7 天、终态任务记录 24h。 */
|
|
642
|
+
sweep(now = this.now()): { artifacts: number; tasks: number } {
|
|
643
|
+
const referenced = new Set<string>();
|
|
644
|
+
for (const ledger of [this.outbound, this.inbound]) {
|
|
645
|
+
for (const sha of ledger.references()) referenced.add(sha);
|
|
646
|
+
}
|
|
647
|
+
const artifacts = this.artifacts.sweep(referenced, now).removed;
|
|
648
|
+
const tasks =
|
|
649
|
+
this.outbound.prune(FABRIC_TASK_RETENTION_MS, now) +
|
|
650
|
+
this.inbound.prune(FABRIC_TASK_RETENTION_MS, now);
|
|
651
|
+
void ARTIFACT_REFERENCED_TTL_MS;
|
|
652
|
+
return { artifacts, tasks };
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/** 供 UI 的「已配对机器」列表:负载是上一轮探测的快照,未探测则为空。 */
|
|
656
|
+
/** 每台机器的连接状态(online / reconnecting / manual-off),面板直接显示。 */
|
|
657
|
+
connectionStates(): Record<string, string> {
|
|
658
|
+
return this.dispatcher.connectionStates();
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
peerRows(): { peer: FabricPeer; online: boolean; queueDepth: number | null; labels: string[] }[] {
|
|
662
|
+
const loads = new Map(this.dispatcher.snapshot().loads.map((load) => [load.nodeId, load]));
|
|
663
|
+
return listPeers(this.options.agentDir).map((peer) => {
|
|
664
|
+
const load = loads.get(peer.nodeId);
|
|
665
|
+
return {
|
|
666
|
+
peer,
|
|
667
|
+
online: load?.online ?? false,
|
|
668
|
+
queueDepth: load?.queueDepth ?? null,
|
|
669
|
+
labels: sanitizeLabels(load?.labels ?? []),
|
|
670
|
+
};
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* 取回某个任务的 diff 文本(面板展示 / 导出用)。
|
|
676
|
+
* 有上限:diff 再大也不该把 WebView 撑死,超了就截断并标记。
|
|
677
|
+
*/
|
|
678
|
+
diffFor(taskId: string, limit = FABRIC_DIFF_PREVIEW_BYTES): {
|
|
679
|
+
taskId: string;
|
|
680
|
+
text: string;
|
|
681
|
+
bytes: number;
|
|
682
|
+
truncated: boolean;
|
|
683
|
+
files: string[];
|
|
684
|
+
} | null {
|
|
685
|
+
const record = this.outbound.get(taskId);
|
|
686
|
+
if (!record?.diffRef) return null;
|
|
687
|
+
try {
|
|
688
|
+
const data = this.artifacts.read(record.diffRef);
|
|
689
|
+
const truncated = data.length > limit;
|
|
690
|
+
return {
|
|
691
|
+
taskId,
|
|
692
|
+
text: data.subarray(0, limit).toString("utf8"),
|
|
693
|
+
bytes: data.length,
|
|
694
|
+
truncated,
|
|
695
|
+
files: [...record.files],
|
|
696
|
+
};
|
|
697
|
+
} catch {
|
|
698
|
+
return null;
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* 把某个任务的远端改动应用到本机仓库。默认只做 dry-run —— 写别人仓库这件事,
|
|
704
|
+
* 必须由用户点第二次确认,不能因为「反正能干净应用」就自动落。
|
|
705
|
+
*/
|
|
706
|
+
async applyDiff(input: {
|
|
707
|
+
taskId: string;
|
|
708
|
+
repo?: string;
|
|
709
|
+
dryRun?: boolean;
|
|
710
|
+
}): Promise<ApplyPatchResult> {
|
|
711
|
+
const record = this.outbound.get(input.taskId);
|
|
712
|
+
if (!record) {
|
|
713
|
+
return { ok: false, code: "E_TASK_UNKNOWN", message: "没有这个任务" };
|
|
714
|
+
}
|
|
715
|
+
if (!record.diffRef) {
|
|
716
|
+
return { ok: false, code: "E_PATCH_EMPTY", message: "这个任务没有改动可应用" };
|
|
717
|
+
}
|
|
718
|
+
const repo = input.repo?.trim() || record.workspaceHint;
|
|
719
|
+
if (!repo) {
|
|
720
|
+
return { ok: false, code: "E_NOT_A_REPO", message: "不知道该应用到哪个仓库(任务没有记录工作区)" };
|
|
721
|
+
}
|
|
722
|
+
let patch: Buffer;
|
|
723
|
+
try {
|
|
724
|
+
patch = this.artifacts.read(record.diffRef);
|
|
725
|
+
} catch {
|
|
726
|
+
return { ok: false, code: "E_PATCH_EMPTY", message: "diff 产物已被清理,无法应用" };
|
|
727
|
+
}
|
|
728
|
+
const result = await applyPatchToRepo({
|
|
729
|
+
repo,
|
|
730
|
+
patch,
|
|
731
|
+
dryRun: input.dryRun !== false,
|
|
732
|
+
log: this.options.log,
|
|
733
|
+
});
|
|
734
|
+
this.options.log?.(
|
|
735
|
+
`fabric apply ${input.taskId} -> ${repo}: ${result.ok ? "ok" : result.code}`,
|
|
736
|
+
);
|
|
737
|
+
return result;
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
isTerminal(taskId: string): boolean {
|
|
741
|
+
const record = this.outbound.get(taskId);
|
|
742
|
+
return record ? isTerminalState(record.state) : false;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|