dsh-mobile-ios 0.2.6 → 0.2.8
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/LICENSE +21 -21
- package/README.md +284 -284
- package/cordis.patch.yml +20 -20
- package/entries/plugin.mjs +246 -246
- package/entries/sidecar.mjs +111 -111
- package/lib/client.js +1294 -1193
- package/lib/vendor/qrcode-generator.cjs +2297 -2297
- package/lib/vendor/qrcode-utf8.cjs +26 -26
- package/package.json +53 -53
- package/src/adapter/artifacts.mjs +235 -235
- package/src/adapter/cordis-host.mjs +1225 -1225
- package/src/adapter/mock-host.mjs +437 -437
- package/src/adapter/mux-host.mjs +99 -99
- package/src/adapter/session-history.mjs +241 -241
- package/src/cloudflare.mjs +628 -628
- package/src/cloudflared-install.mjs +139 -0
- package/src/dns-label.mjs +32 -32
- package/src/dns-probe.mjs +90 -90
- package/src/file-log.mjs +68 -68
- package/src/gateway.mjs +285 -285
- package/src/pairing.mjs +300 -300
- package/src/protocol.mjs +59 -59
- package/src/provision-local.mjs +309 -309
- package/src/rest.mjs +812 -786
- package/src/ring.mjs +148 -148
- package/src/server.mjs +219 -219
- package/src/tunnel.mjs +523 -504
- package/src/version.mjs +24 -24
- package/src/ws.mjs +332 -332
package/src/gateway.mjs
CHANGED
|
@@ -1,285 +1,285 @@
|
|
|
1
|
-
// gateway.mjs — 传输无关的网关核心(ADR-12)
|
|
2
|
-
// 这一层只认识三样东西:host 适配器、配对服务、会话集合。
|
|
3
|
-
// 不含任何宿主 API 调用、不含任何 HTTP/WS 细节 —— 插件与 sidecar 共用它。
|
|
4
|
-
|
|
5
|
-
import crypto from 'node:crypto';
|
|
6
|
-
import { EventLog } from './ring.mjs';
|
|
7
|
-
import { fail, isSupportedProtocol, PROTOCOL_VERSION, newId } from './protocol.mjs';
|
|
8
|
-
|
|
9
|
-
const IDEMPOTENCY_TTL_MS = 10 * 60 * 1000;
|
|
10
|
-
|
|
11
|
-
export class GatewayCore {
|
|
12
|
-
constructor({ host, pairing, log = () => {}, now = () => Date.now(), eventLog } = {}) {
|
|
13
|
-
if (!host) throw new Error('GatewayCore 需要 host 适配器');
|
|
14
|
-
if (!pairing) throw new Error('GatewayCore 需要 pairing 服务');
|
|
15
|
-
this.host = host;
|
|
16
|
-
this.pairing = pairing;
|
|
17
|
-
this.log = log;
|
|
18
|
-
this.now = now;
|
|
19
|
-
this.events = eventLog || new EventLog();
|
|
20
|
-
this.sessions = new Map();
|
|
21
|
-
this.idempotency = new Map();
|
|
22
|
-
this.gen = `gen_${crypto.randomBytes(3).toString('hex')}`;
|
|
23
|
-
this.unsubscribe = null;
|
|
24
|
-
this.startedAt = null;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
start() {
|
|
28
|
-
if (this.startedAt) return;
|
|
29
|
-
this.startedAt = this.now();
|
|
30
|
-
this.unsubscribe = this.host.subscribe((evt) => this.publish(evt));
|
|
31
|
-
this.log(`core start gen=${this.gen} host=${this.host.info().hostName}`);
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
stop() {
|
|
35
|
-
this.unsubscribe?.();
|
|
36
|
-
this.unsubscribe = null;
|
|
37
|
-
for (const s of this.sessions.values()) {
|
|
38
|
-
try {
|
|
39
|
-
s.close(1001, 'gateway stopping');
|
|
40
|
-
} catch {
|
|
41
|
-
/* 关闭失败不影响退出 */
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
this.sessions.clear();
|
|
45
|
-
this.startedAt = null;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* 宿主重启:seq 空间作废,旧游标不再指向同一串事实。
|
|
50
|
-
*
|
|
51
|
-
* 契约只写了「gen 变化 ⇒ 客户端全量重建」,但客户端要等 ready 才知道 gen 变了;
|
|
52
|
-
* 若不额外告知,它会把「补不到增量」读成「没有新事件」——静默丢数据。
|
|
53
|
-
* 所以这里做三件事:换 gen、清空环缓冲、给在线会话推 gateway 事件并以 1012 关闭。
|
|
54
|
-
*/
|
|
55
|
-
restartHost(reason = 'host_restart') {
|
|
56
|
-
const prevGen = this.gen;
|
|
57
|
-
this.gen = `gen_${crypto.randomBytes(3).toString('hex')}`;
|
|
58
|
-
this.notifyGateway({ event: 'host.restarted', reason, gen: this.gen, prevGen });
|
|
59
|
-
// 真实宿主重启后,在跑的任务不会自己复活:宿主会把它们标成「已中断」。
|
|
60
|
-
// 之前 mock 不建模这一点,列表快照仍报 running,客户端刚降级的状态会被覆盖回去,
|
|
61
|
-
// 端到端就永远验不出 FR-TASK-06(「已中断 · 可续」而不是一直转圈)。
|
|
62
|
-
try {
|
|
63
|
-
this.host.onHostRestart?.(reason);
|
|
64
|
-
} catch (err) {
|
|
65
|
-
this.log(`core host.onHostRestart 失败:${err.message}`);
|
|
66
|
-
}
|
|
67
|
-
this.events.clear();
|
|
68
|
-
for (const s of [...this.sessions.values()]) {
|
|
69
|
-
try {
|
|
70
|
-
s.close(1012, 'host restarted');
|
|
71
|
-
} catch {
|
|
72
|
-
/* 关闭失败不影响重启 */
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
this.sessions.clear();
|
|
76
|
-
this.log(`core restart gen=${prevGen} -> ${this.gen}`);
|
|
77
|
-
return { gen: this.gen, prevGen, reason };
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* 网关级事件(不属于某个任务):不分配 seq,不进环缓冲。
|
|
82
|
-
*
|
|
83
|
-
* 这类事件描述的是「连接环境」本身变了(宿主重启、隧道地址漂移),
|
|
84
|
-
* 与之关联的不是某个任务的时间线,因此不带 seq 也不该被续传。
|
|
85
|
-
*/
|
|
86
|
-
notifyGateway(data) {
|
|
87
|
-
const notice = {
|
|
88
|
-
t: 'ev',
|
|
89
|
-
seq: 0,
|
|
90
|
-
taskId: null,
|
|
91
|
-
kind: 'gateway',
|
|
92
|
-
at: new Date(this.now()).toISOString(),
|
|
93
|
-
data,
|
|
94
|
-
};
|
|
95
|
-
for (const s of this.sessions.values()) {
|
|
96
|
-
if (!s.ready) continue;
|
|
97
|
-
try {
|
|
98
|
-
s.send(notice);
|
|
99
|
-
} catch {
|
|
100
|
-
/* 对端已断,忽略 */
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
return notice;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/** 故障注入:裁掉某任务已缓冲的旧帧,制造「游标早于下界」的缺口场景 */
|
|
107
|
-
injectGap(taskId, keep = 0) {
|
|
108
|
-
const dropped = this.events.trim(taskId, keep);
|
|
109
|
-
return { taskId, dropped, lowerBound: this.events.lowerBound(taskId), maxSeq: this.events.maxSeq(taskId) };
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/** 宿主事件 → 分配 seq → 扇出。网关不改写 data,只加封套。 */
|
|
113
|
-
publish({ taskId, kind, data, at }) {
|
|
114
|
-
const frame = this.events.append({ taskId, kind, data, at });
|
|
115
|
-
for (const s of this.sessions.values()) {
|
|
116
|
-
if (s.ready) s.send(frame);
|
|
117
|
-
}
|
|
118
|
-
return frame;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
addSession({ device, send, close, remote = '' }) {
|
|
122
|
-
const session = {
|
|
123
|
-
id: newId('sess'),
|
|
124
|
-
deviceId: device?.deviceId || null,
|
|
125
|
-
installId: device?.installId || null,
|
|
126
|
-
device,
|
|
127
|
-
send,
|
|
128
|
-
close,
|
|
129
|
-
remote,
|
|
130
|
-
ready: false,
|
|
131
|
-
cursors: {},
|
|
132
|
-
createdAt: this.now(),
|
|
133
|
-
lastFrameAt: this.now(),
|
|
134
|
-
sent: 0,
|
|
135
|
-
};
|
|
136
|
-
this.sessions.set(session.id, session);
|
|
137
|
-
return session;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
removeSession(session) {
|
|
141
|
-
if (session) this.sessions.delete(session.id);
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
/** 握手:任何一步失败都抛 GatewayError,由传输层转 reject + close(1008) */
|
|
145
|
-
handleHello(session, hello = {}) {
|
|
146
|
-
if (!session.device) throw fail(4001);
|
|
147
|
-
if (!isSupportedProtocol(hello.protocolVersion)) {
|
|
148
|
-
throw fail(4004, undefined, { supported: PROTOCOL_VERSION });
|
|
149
|
-
}
|
|
150
|
-
if (hello.deviceId && hello.deviceId !== session.device.deviceId) {
|
|
151
|
-
throw fail(4001, '设备标识与凭证不匹配');
|
|
152
|
-
}
|
|
153
|
-
if (hello.installId && hello.installId !== session.device.installId) {
|
|
154
|
-
// 安装标识变化 = 凭证被搬到另一台设备,宁可让用户重新配对
|
|
155
|
-
throw fail(4009, '设备标识已变化,请重新配对');
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
const host = this.host.info();
|
|
159
|
-
// 客户端回带上次见过的 gen:不一致说明跨了一次宿主重启,旧游标无意义。
|
|
160
|
-
// 此时必须把 gap 置真并丢弃游标,否则客户端会把「补不到」误读成「没有新事件」。
|
|
161
|
-
const genChanged = typeof hello.gen === 'string' && hello.gen !== '' && hello.gen !== this.gen;
|
|
162
|
-
const { frames, resumeFrom, gap } = genChanged
|
|
163
|
-
? { frames: [], resumeFrom: 1, gap: true }
|
|
164
|
-
: this.events.replay({
|
|
165
|
-
lastSeq: Number(hello.lastSeq) || 0,
|
|
166
|
-
cursors: hello.cursors,
|
|
167
|
-
});
|
|
168
|
-
|
|
169
|
-
session.ready = true;
|
|
170
|
-
session.cursors = { ...(hello.cursors || {}) };
|
|
171
|
-
const ready = {
|
|
172
|
-
t: 'ready',
|
|
173
|
-
hostId: host.hostId,
|
|
174
|
-
hostName: host.hostName,
|
|
175
|
-
hostVersion: host.hostVersion,
|
|
176
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
177
|
-
caps: host.caps,
|
|
178
|
-
gen: this.gen,
|
|
179
|
-
resumeFrom,
|
|
180
|
-
resumed: frames.length,
|
|
181
|
-
gap,
|
|
182
|
-
...(genChanged ? { genChanged: true } : {}),
|
|
183
|
-
...(host.degraded ? { degraded: true, reason: host.reason } : {}),
|
|
184
|
-
};
|
|
185
|
-
session.send(ready);
|
|
186
|
-
for (const f of frames) session.send(f);
|
|
187
|
-
this.log(
|
|
188
|
-
`ws ready device=${session.device.deviceId} resumeFrom=${resumeFrom} frames=${frames.length}${gap ? ' GAP' : ''}${genChanged ? ' GEN-CHANGED' : ''}`
|
|
189
|
-
);
|
|
190
|
-
return { ready, replayed: frames.length };
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
/** WS 上的控制调用。方法表只放"必须走同一连接"的,业务读写一律走 REST。 */
|
|
194
|
-
async handleReq(session, msg = {}) {
|
|
195
|
-
if (!session.ready) throw fail(4004, '未握手');
|
|
196
|
-
const { id, method, params = {} } = msg;
|
|
197
|
-
switch (method) {
|
|
198
|
-
case 'ping':
|
|
199
|
-
return { id, data: { serverTime: new Date(this.now()).toISOString(), gen: this.gen } };
|
|
200
|
-
case 'diag.snapshot':
|
|
201
|
-
return { id, data: this.stats() };
|
|
202
|
-
default:
|
|
203
|
-
throw fail(4021, undefined, { method });
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
/**
|
|
208
|
-
* 写操作幂等(FR-CMD-03):同键 10 分钟内返回首次结果,不重复下发。
|
|
209
|
-
* 注意:缓存的是"结果",不是"意图"——宿主成功了才写缓存。
|
|
210
|
-
*
|
|
211
|
-
* 命中缓存时必须把 duplicate 置真:契约(openapi §createTask / schemas)规定
|
|
212
|
-
* "重复请求返回首次结果并置 duplicate: true",客户端靠这个字段决定要不要提示
|
|
213
|
-
* "已经提交过了"。此前只回 replayed(契约外字段),实现与契约不符。
|
|
214
|
-
*/
|
|
215
|
-
async idempotent(key, fn) {
|
|
216
|
-
if (!key) return fn();
|
|
217
|
-
const hit = this.idempotency.get(key);
|
|
218
|
-
if (hit && this.now() - hit.at < IDEMPOTENCY_TTL_MS) {
|
|
219
|
-
if (hit.pending) return hit.pending;
|
|
220
|
-
this.log(`idem hit ${key.slice(0, 12)}…`);
|
|
221
|
-
return { ...hit.result, duplicate: true, replayed: true };
|
|
222
|
-
}
|
|
223
|
-
const pending = (async () => {
|
|
224
|
-
const result = await fn();
|
|
225
|
-
this.idempotency.set(key, { at: this.now(), result });
|
|
226
|
-
return result;
|
|
227
|
-
})();
|
|
228
|
-
this.idempotency.set(key, { at: this.now(), pending });
|
|
229
|
-
try {
|
|
230
|
-
return await pending;
|
|
231
|
-
} catch (err) {
|
|
232
|
-
this.idempotency.delete(key); // 失败不占位,允许原键重试
|
|
233
|
-
throw err;
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
#gcIdempotency() {
|
|
238
|
-
for (const [k, v] of this.idempotency) {
|
|
239
|
-
if (this.now() - v.at > IDEMPOTENCY_TTL_MS) this.idempotency.delete(k);
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
/** 当前完成握手的设备 ID——面板「已配对 N 台」右边标真实在线数用。 */
|
|
244
|
-
connectedDeviceIds() {
|
|
245
|
-
return [...new Set(
|
|
246
|
-
[...this.sessions.values()]
|
|
247
|
-
.filter((s) => s.ready && s.deviceId)
|
|
248
|
-
.map((s) => s.deviceId)
|
|
249
|
-
)];
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
/** 单设备下线时立刻掐断它的 WS:撤销只改注册表,不关会话的话旧连接还能继续读任务。 */
|
|
253
|
-
dropSessionsByDevice(deviceId) {
|
|
254
|
-
let n = 0;
|
|
255
|
-
for (const s of [...this.sessions.values()]) {
|
|
256
|
-
if (s.deviceId !== deviceId) continue;
|
|
257
|
-
try { s.close(4009, 'device revoked'); } catch { /* 已断开的会话忽略 */ }
|
|
258
|
-
this.removeSession(s);
|
|
259
|
-
n += 1;
|
|
260
|
-
}
|
|
261
|
-
return n;
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
stats() {
|
|
265
|
-
this.#gcIdempotency();
|
|
266
|
-
const host = this.host.info();
|
|
267
|
-
return {
|
|
268
|
-
gen: this.gen,
|
|
269
|
-
uptimeSec: this.startedAt ? Math.floor((this.now() - this.startedAt) / 1000) : 0,
|
|
270
|
-
host: {
|
|
271
|
-
hostId: host.hostId,
|
|
272
|
-
hostName: host.hostName,
|
|
273
|
-
hostVersion: host.hostVersion,
|
|
274
|
-
platform: host.platform,
|
|
275
|
-
caps: host.caps,
|
|
276
|
-
},
|
|
277
|
-
sessions: this.sessions.size,
|
|
278
|
-
readySessions: [...this.sessions.values()].filter((s) => s.ready).length,
|
|
279
|
-
events: this.events.stats(),
|
|
280
|
-
pairing: this.pairing.stats(),
|
|
281
|
-
idempotencyKeys: this.idempotency.size,
|
|
282
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
283
|
-
};
|
|
284
|
-
}
|
|
285
|
-
}
|
|
1
|
+
// gateway.mjs — 传输无关的网关核心(ADR-12)
|
|
2
|
+
// 这一层只认识三样东西:host 适配器、配对服务、会话集合。
|
|
3
|
+
// 不含任何宿主 API 调用、不含任何 HTTP/WS 细节 —— 插件与 sidecar 共用它。
|
|
4
|
+
|
|
5
|
+
import crypto from 'node:crypto';
|
|
6
|
+
import { EventLog } from './ring.mjs';
|
|
7
|
+
import { fail, isSupportedProtocol, PROTOCOL_VERSION, newId } from './protocol.mjs';
|
|
8
|
+
|
|
9
|
+
const IDEMPOTENCY_TTL_MS = 10 * 60 * 1000;
|
|
10
|
+
|
|
11
|
+
export class GatewayCore {
|
|
12
|
+
constructor({ host, pairing, log = () => {}, now = () => Date.now(), eventLog } = {}) {
|
|
13
|
+
if (!host) throw new Error('GatewayCore 需要 host 适配器');
|
|
14
|
+
if (!pairing) throw new Error('GatewayCore 需要 pairing 服务');
|
|
15
|
+
this.host = host;
|
|
16
|
+
this.pairing = pairing;
|
|
17
|
+
this.log = log;
|
|
18
|
+
this.now = now;
|
|
19
|
+
this.events = eventLog || new EventLog();
|
|
20
|
+
this.sessions = new Map();
|
|
21
|
+
this.idempotency = new Map();
|
|
22
|
+
this.gen = `gen_${crypto.randomBytes(3).toString('hex')}`;
|
|
23
|
+
this.unsubscribe = null;
|
|
24
|
+
this.startedAt = null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
start() {
|
|
28
|
+
if (this.startedAt) return;
|
|
29
|
+
this.startedAt = this.now();
|
|
30
|
+
this.unsubscribe = this.host.subscribe((evt) => this.publish(evt));
|
|
31
|
+
this.log(`core start gen=${this.gen} host=${this.host.info().hostName}`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
stop() {
|
|
35
|
+
this.unsubscribe?.();
|
|
36
|
+
this.unsubscribe = null;
|
|
37
|
+
for (const s of this.sessions.values()) {
|
|
38
|
+
try {
|
|
39
|
+
s.close(1001, 'gateway stopping');
|
|
40
|
+
} catch {
|
|
41
|
+
/* 关闭失败不影响退出 */
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
this.sessions.clear();
|
|
45
|
+
this.startedAt = null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 宿主重启:seq 空间作废,旧游标不再指向同一串事实。
|
|
50
|
+
*
|
|
51
|
+
* 契约只写了「gen 变化 ⇒ 客户端全量重建」,但客户端要等 ready 才知道 gen 变了;
|
|
52
|
+
* 若不额外告知,它会把「补不到增量」读成「没有新事件」——静默丢数据。
|
|
53
|
+
* 所以这里做三件事:换 gen、清空环缓冲、给在线会话推 gateway 事件并以 1012 关闭。
|
|
54
|
+
*/
|
|
55
|
+
restartHost(reason = 'host_restart') {
|
|
56
|
+
const prevGen = this.gen;
|
|
57
|
+
this.gen = `gen_${crypto.randomBytes(3).toString('hex')}`;
|
|
58
|
+
this.notifyGateway({ event: 'host.restarted', reason, gen: this.gen, prevGen });
|
|
59
|
+
// 真实宿主重启后,在跑的任务不会自己复活:宿主会把它们标成「已中断」。
|
|
60
|
+
// 之前 mock 不建模这一点,列表快照仍报 running,客户端刚降级的状态会被覆盖回去,
|
|
61
|
+
// 端到端就永远验不出 FR-TASK-06(「已中断 · 可续」而不是一直转圈)。
|
|
62
|
+
try {
|
|
63
|
+
this.host.onHostRestart?.(reason);
|
|
64
|
+
} catch (err) {
|
|
65
|
+
this.log(`core host.onHostRestart 失败:${err.message}`);
|
|
66
|
+
}
|
|
67
|
+
this.events.clear();
|
|
68
|
+
for (const s of [...this.sessions.values()]) {
|
|
69
|
+
try {
|
|
70
|
+
s.close(1012, 'host restarted');
|
|
71
|
+
} catch {
|
|
72
|
+
/* 关闭失败不影响重启 */
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
this.sessions.clear();
|
|
76
|
+
this.log(`core restart gen=${prevGen} -> ${this.gen}`);
|
|
77
|
+
return { gen: this.gen, prevGen, reason };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 网关级事件(不属于某个任务):不分配 seq,不进环缓冲。
|
|
82
|
+
*
|
|
83
|
+
* 这类事件描述的是「连接环境」本身变了(宿主重启、隧道地址漂移),
|
|
84
|
+
* 与之关联的不是某个任务的时间线,因此不带 seq 也不该被续传。
|
|
85
|
+
*/
|
|
86
|
+
notifyGateway(data) {
|
|
87
|
+
const notice = {
|
|
88
|
+
t: 'ev',
|
|
89
|
+
seq: 0,
|
|
90
|
+
taskId: null,
|
|
91
|
+
kind: 'gateway',
|
|
92
|
+
at: new Date(this.now()).toISOString(),
|
|
93
|
+
data,
|
|
94
|
+
};
|
|
95
|
+
for (const s of this.sessions.values()) {
|
|
96
|
+
if (!s.ready) continue;
|
|
97
|
+
try {
|
|
98
|
+
s.send(notice);
|
|
99
|
+
} catch {
|
|
100
|
+
/* 对端已断,忽略 */
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return notice;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 故障注入:裁掉某任务已缓冲的旧帧,制造「游标早于下界」的缺口场景 */
|
|
107
|
+
injectGap(taskId, keep = 0) {
|
|
108
|
+
const dropped = this.events.trim(taskId, keep);
|
|
109
|
+
return { taskId, dropped, lowerBound: this.events.lowerBound(taskId), maxSeq: this.events.maxSeq(taskId) };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 宿主事件 → 分配 seq → 扇出。网关不改写 data,只加封套。 */
|
|
113
|
+
publish({ taskId, kind, data, at }) {
|
|
114
|
+
const frame = this.events.append({ taskId, kind, data, at });
|
|
115
|
+
for (const s of this.sessions.values()) {
|
|
116
|
+
if (s.ready) s.send(frame);
|
|
117
|
+
}
|
|
118
|
+
return frame;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
addSession({ device, send, close, remote = '' }) {
|
|
122
|
+
const session = {
|
|
123
|
+
id: newId('sess'),
|
|
124
|
+
deviceId: device?.deviceId || null,
|
|
125
|
+
installId: device?.installId || null,
|
|
126
|
+
device,
|
|
127
|
+
send,
|
|
128
|
+
close,
|
|
129
|
+
remote,
|
|
130
|
+
ready: false,
|
|
131
|
+
cursors: {},
|
|
132
|
+
createdAt: this.now(),
|
|
133
|
+
lastFrameAt: this.now(),
|
|
134
|
+
sent: 0,
|
|
135
|
+
};
|
|
136
|
+
this.sessions.set(session.id, session);
|
|
137
|
+
return session;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
removeSession(session) {
|
|
141
|
+
if (session) this.sessions.delete(session.id);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 握手:任何一步失败都抛 GatewayError,由传输层转 reject + close(1008) */
|
|
145
|
+
handleHello(session, hello = {}) {
|
|
146
|
+
if (!session.device) throw fail(4001);
|
|
147
|
+
if (!isSupportedProtocol(hello.protocolVersion)) {
|
|
148
|
+
throw fail(4004, undefined, { supported: PROTOCOL_VERSION });
|
|
149
|
+
}
|
|
150
|
+
if (hello.deviceId && hello.deviceId !== session.device.deviceId) {
|
|
151
|
+
throw fail(4001, '设备标识与凭证不匹配');
|
|
152
|
+
}
|
|
153
|
+
if (hello.installId && hello.installId !== session.device.installId) {
|
|
154
|
+
// 安装标识变化 = 凭证被搬到另一台设备,宁可让用户重新配对
|
|
155
|
+
throw fail(4009, '设备标识已变化,请重新配对');
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const host = this.host.info();
|
|
159
|
+
// 客户端回带上次见过的 gen:不一致说明跨了一次宿主重启,旧游标无意义。
|
|
160
|
+
// 此时必须把 gap 置真并丢弃游标,否则客户端会把「补不到」误读成「没有新事件」。
|
|
161
|
+
const genChanged = typeof hello.gen === 'string' && hello.gen !== '' && hello.gen !== this.gen;
|
|
162
|
+
const { frames, resumeFrom, gap } = genChanged
|
|
163
|
+
? { frames: [], resumeFrom: 1, gap: true }
|
|
164
|
+
: this.events.replay({
|
|
165
|
+
lastSeq: Number(hello.lastSeq) || 0,
|
|
166
|
+
cursors: hello.cursors,
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
session.ready = true;
|
|
170
|
+
session.cursors = { ...(hello.cursors || {}) };
|
|
171
|
+
const ready = {
|
|
172
|
+
t: 'ready',
|
|
173
|
+
hostId: host.hostId,
|
|
174
|
+
hostName: host.hostName,
|
|
175
|
+
hostVersion: host.hostVersion,
|
|
176
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
177
|
+
caps: host.caps,
|
|
178
|
+
gen: this.gen,
|
|
179
|
+
resumeFrom,
|
|
180
|
+
resumed: frames.length,
|
|
181
|
+
gap,
|
|
182
|
+
...(genChanged ? { genChanged: true } : {}),
|
|
183
|
+
...(host.degraded ? { degraded: true, reason: host.reason } : {}),
|
|
184
|
+
};
|
|
185
|
+
session.send(ready);
|
|
186
|
+
for (const f of frames) session.send(f);
|
|
187
|
+
this.log(
|
|
188
|
+
`ws ready device=${session.device.deviceId} resumeFrom=${resumeFrom} frames=${frames.length}${gap ? ' GAP' : ''}${genChanged ? ' GEN-CHANGED' : ''}`
|
|
189
|
+
);
|
|
190
|
+
return { ready, replayed: frames.length };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** WS 上的控制调用。方法表只放"必须走同一连接"的,业务读写一律走 REST。 */
|
|
194
|
+
async handleReq(session, msg = {}) {
|
|
195
|
+
if (!session.ready) throw fail(4004, '未握手');
|
|
196
|
+
const { id, method, params = {} } = msg;
|
|
197
|
+
switch (method) {
|
|
198
|
+
case 'ping':
|
|
199
|
+
return { id, data: { serverTime: new Date(this.now()).toISOString(), gen: this.gen } };
|
|
200
|
+
case 'diag.snapshot':
|
|
201
|
+
return { id, data: this.stats() };
|
|
202
|
+
default:
|
|
203
|
+
throw fail(4021, undefined, { method });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* 写操作幂等(FR-CMD-03):同键 10 分钟内返回首次结果,不重复下发。
|
|
209
|
+
* 注意:缓存的是"结果",不是"意图"——宿主成功了才写缓存。
|
|
210
|
+
*
|
|
211
|
+
* 命中缓存时必须把 duplicate 置真:契约(openapi §createTask / schemas)规定
|
|
212
|
+
* "重复请求返回首次结果并置 duplicate: true",客户端靠这个字段决定要不要提示
|
|
213
|
+
* "已经提交过了"。此前只回 replayed(契约外字段),实现与契约不符。
|
|
214
|
+
*/
|
|
215
|
+
async idempotent(key, fn) {
|
|
216
|
+
if (!key) return fn();
|
|
217
|
+
const hit = this.idempotency.get(key);
|
|
218
|
+
if (hit && this.now() - hit.at < IDEMPOTENCY_TTL_MS) {
|
|
219
|
+
if (hit.pending) return hit.pending;
|
|
220
|
+
this.log(`idem hit ${key.slice(0, 12)}…`);
|
|
221
|
+
return { ...hit.result, duplicate: true, replayed: true };
|
|
222
|
+
}
|
|
223
|
+
const pending = (async () => {
|
|
224
|
+
const result = await fn();
|
|
225
|
+
this.idempotency.set(key, { at: this.now(), result });
|
|
226
|
+
return result;
|
|
227
|
+
})();
|
|
228
|
+
this.idempotency.set(key, { at: this.now(), pending });
|
|
229
|
+
try {
|
|
230
|
+
return await pending;
|
|
231
|
+
} catch (err) {
|
|
232
|
+
this.idempotency.delete(key); // 失败不占位,允许原键重试
|
|
233
|
+
throw err;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
#gcIdempotency() {
|
|
238
|
+
for (const [k, v] of this.idempotency) {
|
|
239
|
+
if (this.now() - v.at > IDEMPOTENCY_TTL_MS) this.idempotency.delete(k);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** 当前完成握手的设备 ID——面板「已配对 N 台」右边标真实在线数用。 */
|
|
244
|
+
connectedDeviceIds() {
|
|
245
|
+
return [...new Set(
|
|
246
|
+
[...this.sessions.values()]
|
|
247
|
+
.filter((s) => s.ready && s.deviceId)
|
|
248
|
+
.map((s) => s.deviceId)
|
|
249
|
+
)];
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** 单设备下线时立刻掐断它的 WS:撤销只改注册表,不关会话的话旧连接还能继续读任务。 */
|
|
253
|
+
dropSessionsByDevice(deviceId) {
|
|
254
|
+
let n = 0;
|
|
255
|
+
for (const s of [...this.sessions.values()]) {
|
|
256
|
+
if (s.deviceId !== deviceId) continue;
|
|
257
|
+
try { s.close(4009, 'device revoked'); } catch { /* 已断开的会话忽略 */ }
|
|
258
|
+
this.removeSession(s);
|
|
259
|
+
n += 1;
|
|
260
|
+
}
|
|
261
|
+
return n;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
stats() {
|
|
265
|
+
this.#gcIdempotency();
|
|
266
|
+
const host = this.host.info();
|
|
267
|
+
return {
|
|
268
|
+
gen: this.gen,
|
|
269
|
+
uptimeSec: this.startedAt ? Math.floor((this.now() - this.startedAt) / 1000) : 0,
|
|
270
|
+
host: {
|
|
271
|
+
hostId: host.hostId,
|
|
272
|
+
hostName: host.hostName,
|
|
273
|
+
hostVersion: host.hostVersion,
|
|
274
|
+
platform: host.platform,
|
|
275
|
+
caps: host.caps,
|
|
276
|
+
},
|
|
277
|
+
sessions: this.sessions.size,
|
|
278
|
+
readySessions: [...this.sessions.values()].filter((s) => s.ready).length,
|
|
279
|
+
events: this.events.stats(),
|
|
280
|
+
pairing: this.pairing.stats(),
|
|
281
|
+
idempotencyKeys: this.idempotency.size,
|
|
282
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
}
|