dsh-mobile-plugin 0.5.81 → 0.5.83

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.
Files changed (67) hide show
  1. package/README.md +4 -0
  2. package/dsh-mobile-credentials/lib/credentials.js +5 -0
  3. package/lib/client.js +171 -5
  4. package/lib/frpc/provision.cjs +21 -17
  5. package/lib/frpc/runner.cjs +231 -168
  6. package/lib/impl.js +77 -107
  7. package/lib/index.js +1 -1
  8. package/lib/mirror/pusher.cjs +60 -10
  9. package/lib/mobile/approval-memory.js +2 -55
  10. package/lib/mobile/approvals.js +6 -82
  11. package/lib/mobile/events.js +2 -1
  12. package/lib/mobile/feedback.js +6 -5
  13. package/lib/mobile/file-read.js +4 -2
  14. package/lib/mobile/host-bridge.js +12 -1
  15. package/lib/mobile/mux.js +148 -21
  16. package/lib/mobile/paired-devices.js +2 -1
  17. package/lib/mobile/pairing.js +8 -7
  18. package/lib/mobile/relay-control.js +33 -38
  19. package/lib/mobile/session-changes.js +8 -2
  20. package/lib/mobile/session-delivery.js +5 -1
  21. package/lib/mobile/session-file.js +46 -25
  22. package/lib/mobile/session-head.js +7 -3
  23. package/lib/mobile/session-snapshot.js +5 -1
  24. package/lib/mobile/session-step.js +13 -7
  25. package/lib/mobile/session-stop-summary.js +6 -1
  26. package/lib/mobile/stream-registry.js +48 -53
  27. package/lib/mobile/stream.js +17 -2
  28. package/lib/mobile/uploads.js +190 -163
  29. package/lib/p2p/session.cjs +169 -70
  30. package/lib/p2p/wiring.cjs +4 -2
  31. package/lib/panel/index.html +44 -24
  32. package/lib/relay/blob-upload.cjs +103 -0
  33. package/lib/relay/config-store.js +79 -0
  34. package/lib/relay/control.js +131 -52
  35. package/lib/relay/core.js +55 -17
  36. package/lib/relay/lan-discovery.cjs +22 -14
  37. package/lib/relay/lan-port-policy.cjs +8 -2
  38. package/lib/relay/lan-proxy.js +47 -12
  39. package/lib/relay/pairing-payload.cjs +14 -5
  40. package/lib/relay/preview-webapp.cjs +150 -0
  41. package/lib/relay/preview.js +35 -8
  42. package/lib/relay/protocol.js +6 -4
  43. package/lib/relay/relay-probe.js +112 -21
  44. package/lib/relay/status.js +4 -7
  45. package/lib/relay/tunnel-forwarder.cjs +4 -2
  46. package/lib/relay/tunnel.js +39 -8
  47. package/lib/remote/controller.cjs +33 -3
  48. package/lib/remote/host-control.cjs +11 -2
  49. package/lib/remote/router.cjs +83 -33
  50. package/lib/remote/transport.cjs +32 -5
  51. package/lib/remote/tunnel-helper.cjs +51 -25
  52. package/lib/remote/tunnels.cjs +27 -3
  53. package/lib/routes/control-plane.js +41 -53
  54. package/lib/routes/mobile-api.js +21 -31
  55. package/lib/shared/fresh-request.js +32 -1
  56. package/lib/shared/route-order.cjs +118 -132
  57. package/lib/shared/sse-write.js +29 -10
  58. package/lib/shared/via-header.js +5 -12
  59. package/lib/shell/transport-host.js +9 -1
  60. package/lib/shell/updater.js +18 -6
  61. package/lib/sidecar-facade-worker.cjs +165 -118
  62. package/lib/sidecar-facade.cjs +6 -1
  63. package/lib/sidecar-lifecycle.cjs +6 -2
  64. package/lib/tailcat/host-process.cjs +32 -8
  65. package/lib/tailcat/session.cjs +27 -10
  66. package/package.json +6 -6
  67. package/lib/mobile/auto-review.js +0 -178
@@ -1,73 +1,68 @@
1
+ // 按实例与设备登记 SSE,吊销只收掉对应实例的在途流。
1
2
  'use strict';
2
3
 
3
- /**
4
- * 按设备登记的 SSE 流。
5
- *
6
- * token 换了只保证**下一次请求**被拒;一条已经开着的流不会自己断,被踢的手机还能继续收
7
- * 消息,直到它自己重连。不做这一步,「单台吊销」就只完成了一半。
8
- *
9
- * 登记表按 deviceId 分组:同一台手机可能同时开着两条流(会话流 + 设备级事件流),
10
- * 两台手机之间互不影响。收流由吊销那条路径调 `drop`,逐条 `end()` 掉。
11
- *
12
- * 这里**不做超时与配额**:宿主本来就是给自己那几台设备推东西,流的上限由它们自己的
13
- * 打开次数决定,加一层闸只会把「手机连着却收不到」变成一种新的失败形态。
14
- */
15
4
  const streams = new Map();
16
5
 
17
- /**
18
- * 登记一条流。
19
- *
20
- * @param {string} deviceId 设备 id(凭据记录上的 `deviceId`)
21
- * @param {object} res 这条流的响应对象(只需要 `end` 与 `destroy`)
22
- * @returns {() => void} 注销函数;流自己关掉时调用,避免表越攒越大
23
- */
24
- function track(deviceId, res) {
25
- const key = typeof deviceId === 'string' ? deviceId : '';
26
- if (!key || !res) return () => {};
27
- let set = streams.get(key);
28
- if (!set) {
29
- set = new Set();
30
- streams.set(key, set);
31
- }
6
+ /** 无实例参数保留旧调用口径;业务入口显式传当前实例。 */
7
+ function track(deviceId, res, instanceId = '') {
8
+ if (typeof deviceId !== 'string' || !deviceId || !res) return () => {};
9
+ const scope = String(instanceId || '');
10
+ let devices = streams.get(scope);
11
+ if (!devices) { devices = new Map(); streams.set(scope, devices); }
12
+ let set = devices.get(deviceId);
13
+ if (!set) { set = new Set(); devices.set(deviceId, set); }
32
14
  set.add(res);
33
15
  return () => {
34
- const current = streams.get(key);
35
- if (!current) return;
36
- current.delete(res);
37
- if (current.size === 0) streams.delete(key);
16
+ const current = streams.get(scope);
17
+ const active = current?.get(deviceId);
18
+ if (!active) return;
19
+ active.delete(res);
20
+ if (active.size === 0) current.delete(deviceId);
21
+ if (current.size === 0) streams.delete(scope);
38
22
  };
39
23
  }
40
24
 
41
- /**
42
- * 收掉这台设备上所有已建立的流。
43
- *
44
- * 先 `end()` 再 `destroy()`:`end` 让对端看到正常的流结束(App 会在下一次请求上收到
45
- * `device-revoked`,而不是一个「网络出错」);对已经卡住的连接 `destroy` 是兜底。
46
- *
47
- * @returns {number} 实际收掉了多少条
48
- */
49
- function drop(deviceId) {
50
- const key = typeof deviceId === 'string' ? deviceId : '';
51
- const set = streams.get(key);
52
- if (!set) return 0;
53
- streams.delete(key);
25
+ function closeSet(set, deferClose) {
26
+ const active = [...set].filter(res => !res.destroyed && !res.writableEnded);
27
+ const close = () => {
28
+ for (const res of active) {
29
+ try { res.end?.(); } catch { /* 对端已经关闭 */ }
30
+ try { res.destroy?.(); } catch { /* 同上 */ }
31
+ }
32
+ };
33
+ if (deferClose) deferClose(close);
34
+ else close();
35
+ return active.length;
36
+ }
37
+
38
+ function drop(deviceId, instanceId, deferClose) {
39
+ let closed = 0;
40
+ for (const [scope, devices] of streams) {
41
+ if (instanceId !== undefined && scope !== String(instanceId || '')) continue;
42
+ const set = devices.get(deviceId);
43
+ if (!set) continue;
44
+ devices.delete(deviceId);
45
+ if (devices.size === 0) streams.delete(scope);
46
+ closed += closeSet(set, deferClose);
47
+ }
48
+ return closed;
49
+ }
50
+
51
+ function dropAll(instanceId) {
54
52
  let closed = 0;
55
- for (const res of set) {
56
- closed += 1;
57
- try { res.end?.(); } catch { /* 对端已经走了 */ }
58
- try { res.destroy?.(); } catch { /* 同上 */ }
53
+ for (const [scope, devices] of streams) {
54
+ if (instanceId !== undefined && scope !== String(instanceId || '')) continue;
55
+ streams.delete(scope);
56
+ for (const set of devices.values()) closed += closeSet(set);
59
57
  }
60
58
  return closed;
61
59
  }
62
60
 
63
- /** 测试与自检用:当前登记了多少条流。 */
64
61
  function size() {
65
62
  let total = 0;
66
- for (const set of streams.values()) total += set.size;
63
+ for (const devices of streams.values()) for (const set of devices.values()) total += set.size;
67
64
  return total;
68
65
  }
69
-
70
- /** 测试用:清空登记表。 */
71
66
  function reset() { streams.clear(); }
72
67
 
73
- module.exports = { track, drop, size, reset };
68
+ module.exports = { track, drop, dropAll, size, reset };
@@ -1,3 +1,4 @@
1
+ // 转发会话事件并统一处理实时、合帧和回放写入的背压与取消。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -221,6 +222,7 @@ function writeSse(res, payload, frame, options = {}) {
221
222
  // 请求 ts / nonce 与帧序号(AAD 要绑这三样)。
222
223
  sealFrame: typeof options.sealFrame === 'function' ? options.sealFrame : null,
223
224
  batch: res.__dshFrameBatch === true,
225
+ onBatchResult: res.__dshBatchResult,
224
226
  });
225
227
  }
226
228
 
@@ -444,9 +446,20 @@ async function handleStream(ctx, req, res) {
444
446
  } catch (error) { logStream(sessionId, 'writeHead failed', error); return; }
445
447
  res.write(': connected\n\n');
446
448
  const ac = new AbortController();
449
+ let batchDrain = null;
450
+ res.__dshBatchResult = (sent) => {
451
+ if (!sent.ok) { ac.abort(); try { res.end(); } catch { /* 已关闭 */ } return; }
452
+ if (sent.needDrain && !batchDrain) {
453
+ batchDrain = res.__dshBatchDrain = waitForDrain(res, ac.signal).then((drained) => {
454
+ batchDrain = res.__dshBatchDrain = null;
455
+ if (!drained) { ac.abort(); try { res.end(); } catch { /* 已关闭 */ } }
456
+ return drained;
457
+ });
458
+ }
459
+ };
447
460
  // 按设备登记这条流:吊销时宿主主动断它(§3.3)。没有这一步,被踢的手机还能继续
448
461
  // 收消息,直到它自己重连 —— 「单台吊销」就只生效了一半。
449
- const untrack = streamRegistry.track(req.__dshRecord && req.__dshRecord.deviceId, res);
462
+ const untrack = streamRegistry.track(req.__dshRecord && req.__dshRecord.deviceId, res, req.__dshRecord?.instanceId);
450
463
  res.on('close', () => { untrack(); ac.abort(); });
451
464
  // 与设备级流(mobile/events.js)对齐:写坏掉的连接不该让 'error' 在 res 上无人接住
452
465
  // 而变成未捕获异常,那时 aborted 仍是 false,收尾分支会以为客户端还在、白写一帧 resync。
@@ -595,6 +608,7 @@ async function handleStream(ctx, req, res) {
595
608
  // 「需要等 drain」这一步是这次 OOM 的正解 —— 写不动就停手,等底层消化完再继续,
596
609
  // 而不是把帧继续往内存里塞。
597
610
  const push = async (payload, frameArg) => {
611
+ if ((batchDrain && !(await batchDrain)) || ac.signal.aborted) return 'closed';
598
612
  const sent = writeSse(res, payload, frameArg, { sealFrame });
599
613
  if (sent.shed) return 'shed';
600
614
  if (!sent.ok) return 'closed';
@@ -806,7 +820,8 @@ async function replaySince(ctx, sessionId, sinceSeq, res, signal, onDelivered, a
806
820
  // 工具名先从整窗吸一遍 —— 窗口里那条 `tool/call` 可能排在游标之前、不在候选里。
807
821
  if (toolNames) toolNames.absorbAll(events);
808
822
  for (const entry of candidates) {
809
- if (signal.aborted) break;
823
+ if (res.__dshBatchDrain && !(await res.__dshBatchDrain)) return { gap: true, oldestSeq };
824
+ if (signal.aborted) return { gap: true, oldestSeq };
810
825
  const e = entry?.event || entry;
811
826
  // 工作流事件在这里也走一遍折树:直播那份树只收「经过某条开着的流」的事件,手机不在
812
827
  // 那几分钟里的事件它根本没见到,不补的话开流那份快照同样是旧的。回放本来就是把这些
@@ -1,3 +1,4 @@
1
+ // 串行维护同一上传的分片、字节水位与收口,落点仍受既有允许区约束。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -30,8 +31,8 @@
30
31
  * `DSH_MOBILE_INBOX` 可覆盖,只给测试用。
31
32
  *
32
33
  * 落盘那一段(finish 里判候选名 + rename)进 `project-write-queue.js` 的项目级单写者队列,
33
- * 键与 `file-ops.js` 同一个算法(`queueKeyOf`)。分片阶段不排队:那是往暂存文件追加字节,
34
- * 不碰任何用户看得见的落点。finish 在排队与落盘期间保留身份,同一上传的重试共用结果;
34
+ * 键与 `file-ops.js` 同一个算法(`queueKeyOf`)。分片只进 uploadId 队列,不占项目写队列:
35
+ * 暂存追加不碰用户可见落点。finish 在排队与落盘期间保留身份,同一上传的重试共用结果;
35
36
  * 指定目录跨卷时只对 EXDEV 改用复制,复制完成后才清暂存。
36
37
  */
37
38
 
@@ -134,10 +135,24 @@ function resolveFinishedUpload(uploadId) {
134
135
  * 进行中的上传:uploadId → job。
135
136
  *
136
137
  * 两种 wire 共用这张表,靠 job 上的 `wire` 分流(`json` 是老行为,`bin` 是 v3):
137
- * - json:`received` 是**片数**,chunk 只吃下一片。
138
+ * - json:`received` 是**片数**,chunk 只吃下一片;`receivedBytes` 是实际连续明文字节。
138
139
  * - bin:`receivedBytes` 是**已连续落盘的字节数**,片按偏移收,乱序的先进 `window`。
139
140
  */
140
141
  const uploads = new Map();
142
+ const uploadWrites = new Map();
143
+
144
+ /** 同一 uploadId 的状态判定和磁盘追加共用队列;进入后必须重新从 uploads 取身份。 */
145
+ async function withUploadWrite(uploadId, action) {
146
+ const previous = uploadWrites.get(uploadId) || Promise.resolve();
147
+ const current = previous.then(action);
148
+ const tail = current.catch(() => {});
149
+ uploadWrites.set(uploadId, tail);
150
+ try {
151
+ return await current;
152
+ } finally {
153
+ if (uploadWrites.get(uploadId) === tail) uploadWrites.delete(uploadId);
154
+ }
155
+ }
141
156
 
142
157
  function removeUpload(uploadId, job) {
143
158
  if (uploads.get(uploadId) !== job) return false;
@@ -154,15 +169,16 @@ function removeUpload(uploadId, job) {
154
169
  }
155
170
 
156
171
  async function expireUpload(uploadId, job) {
157
- if (uploads.get(uploadId) !== job || job.finishPromise) return;
158
- const remaining = job.expiresAt - Date.now();
159
- if (remaining > 0) {
160
- job.expiryTimer = setTimeout(() => { void expireUpload(uploadId, job); }, remaining);
161
- job.expiryTimer.unref?.();
162
- return;
163
- }
164
- if (!removeUpload(uploadId, job)) return;
165
- try { await fsp.unlink(job.stagingPath); } catch { /* 暂存文件可能已由磁盘清扫移除 */ }
172
+ await withUploadWrite(uploadId, async () => {
173
+ if (uploads.get(uploadId) !== job || job.finishPromise) return;
174
+ const remaining = job.expiresAt - Date.now();
175
+ if (remaining > 0) {
176
+ scheduleUploadExpiry(uploadId, job);
177
+ return;
178
+ }
179
+ if (!removeUpload(uploadId, job)) return;
180
+ try { await fsp.unlink(job.stagingPath); } catch { /* 暂存文件可能已由磁盘清扫移除 */ }
181
+ });
166
182
  }
167
183
 
168
184
  function scheduleUploadExpiry(uploadId, job) {
@@ -173,10 +189,10 @@ function scheduleUploadExpiry(uploadId, job) {
173
189
 
174
190
  /** 清理过期上传状态及其暂存文件;传入 now 便于测试 TTL 边界。 */
175
191
  async function sweepExpiredUploads(now = Date.now()) {
176
- await Promise.all([...uploads].map(async ([uploadId, job]) => {
177
- if (job.finishPromise || job.expiresAt > now || !removeUpload(uploadId, job)) return;
192
+ await Promise.all([...uploads].map(([uploadId, job]) => withUploadWrite(uploadId, async () => {
193
+ if (uploads.get(uploadId) !== job || job.finishPromise || job.expiresAt > now || !removeUpload(uploadId, job)) return;
178
194
  try { await fsp.unlink(job.stagingPath); } catch { /* 暂存文件可能已由磁盘清扫移除 */ }
179
- }));
195
+ })));
180
196
  }
181
197
 
182
198
  /** 收件根目录。每次取用都重算,好让测试用环境变量分派。 */
@@ -245,18 +261,23 @@ async function sweepStaging(stagingDir) {
245
261
  const cutoff = Date.now() - STAGING_TTL_MS;
246
262
  const removed = await Promise.all(entries.map(async (entry) => {
247
263
  if (!entry.isFile() || !entry.name.endsWith('.part')) return null;
248
- // finish 可能被项目暂停留在队列里,不能按暂存 mtime 把它仍要落盘的片扫掉。
249
- if (uploads.get(entry.name.slice(0, -5))?.finishPromise) return null;
250
- const target = path.join(stagingDir, entry.name);
251
- try {
252
- const stat = await fsp.stat(target);
253
- if (stat.mtimeMs >= cutoff) return null;
254
- await fsp.unlink(target);
255
- return stat.size;
256
- } catch {
257
- // 已被别人清掉,或者删不掉:都不算这次腾出来的量。
258
- return null;
259
- }
264
+ const uploadId = entry.name.slice(0, -5);
265
+ return withUploadWrite(uploadId, async () => {
266
+ const job = uploads.get(uploadId);
267
+ // finish 可能被项目暂停留在队列里,不能按暂存 mtime 把它仍要落盘的片扫掉。
268
+ if (job?.finishPromise) return null;
269
+ const target = path.join(stagingDir, entry.name);
270
+ try {
271
+ const stat = await fsp.stat(target);
272
+ if (stat.mtimeMs >= cutoff) return null;
273
+ if (job) removeUpload(uploadId, job);
274
+ await fsp.unlink(target);
275
+ return stat.size;
276
+ } catch {
277
+ // 已被别人清掉,或者删不掉:都不算这次腾出来的量。
278
+ return null;
279
+ }
280
+ });
260
281
  }));
261
282
  const sizes = removed.filter((size) => typeof size === 'number');
262
283
  return { deleted: sizes.length, bytes: sizes.reduce((sum, size) => sum + size, 0) };
@@ -322,7 +343,7 @@ async function resolveDestDir(ctx, body) {
322
343
  * begin 里的能力协商(v3)。
323
344
  *
324
345
  * **只有明确说了 `caps.wire === 'bin'` 才进 v3**:老 App 一个字段都不带,`caps` 为空,
325
- * 于是它拿到的是和从前一模一样的响应,走的也是从前那条代码路径。
346
+ * 仍走按 index 收片的 v2;begin 额外的 receivedBytes:0 只声明字节 ACK 能力。
326
347
  *
327
348
  * v3 必须同时给出 `size`(总字节数):收口时要靠它证明「字节齐了」,没有它就没法区分
328
349
  * 「一次传完」和「少了一片但客户端以为传完了」。
@@ -385,12 +406,12 @@ async function handleUploadBegin(ctx, req, res) {
385
406
  // 与 `file-ops.js` 同一个口径。收件箱那条路没有落点根,留空数组。
386
407
  destRoots: destination.roots || [],
387
408
  stagingPath,
388
- // 老路径(json)的两个计数器;v3 另起 `receivedBytes`,两者语义不同,不混用同一格。
409
+ // json 的 received 数片;两种 wire 的 receivedBytes 都只数已连续落盘的明文字节。
389
410
  received: 0,
390
411
  bytes: 0,
391
412
  wire: caps.wire,
392
- // v3 才有意义:偏移收片的账、待拼窗口与它的两块封顶。
393
413
  receivedBytes: 0,
414
+ // v3 的偏移收片账、待拼窗口与它的两块封顶。
394
415
  total: caps.wire === 'bin' ? caps.total : 0,
395
416
  pipeline: caps.wire === 'bin' ? caps.pipeline : 0,
396
417
  windowBytes: caps.wire === 'bin' ? caps.windowBytes : 0,
@@ -404,8 +425,8 @@ async function handleUploadBegin(ctx, req, res) {
404
425
  scheduleUploadExpiry(uploadId, job);
405
426
  // chunkSize 是起步值、maxChunkSize 是天花板:客户端从前者开始按实测周期往上爬。
406
427
  //
407
- // 老客户端(没协商 caps)拿到的是**和从前逐字节相同**的那五个字段:多一个 `wire` 都会
408
- // 让「不带 caps 就走 v2」这条承诺落空,所以 v3 的字段只在真协商成功时追加。
428
+ // v3 的 wire 与窗口只在明确协商时追加;v2 用 receivedBytes:0 声明字节 ACK,旧 App
429
+ // 仍可只看片数。支持缩片的客户端据实收字节推进,不从本次重传的片长猜进度。
409
430
  if (caps.wire === 'bin') {
410
431
  return sendJson(res, 200, {
411
432
  ok: true,
@@ -417,7 +438,7 @@ async function handleUploadBegin(ctx, req, res) {
417
438
  windowBytes: job.windowBytes,
418
439
  });
419
440
  }
420
- sendJson(res, 200, { ok: true, uploadId, chunkSize: CHUNK_BYTES, maxChunkSize: CHUNK_MAX_BYTES });
441
+ sendJson(res, 200, { ok: true, uploadId, chunkSize: CHUNK_BYTES, maxChunkSize: CHUNK_MAX_BYTES, receivedBytes: 0 });
421
442
  }
422
443
 
423
444
  /**
@@ -462,68 +483,67 @@ async function flushWindow(job) {
462
483
  */
463
484
  async function handleBinChunk(req, res) {
464
485
  const uploadId = headerOf(req, 'x-dsh-upload-id').trim();
465
- const job = uploads.get(uploadId);
466
- if (!job || job.finishPromise) return fail(res, 404, 'unknown-upload', '上传会话不存在或已结束');
467
- // 同一 job 中途换 wire 一律拒:两种 wire 的 `received` 一个数片、一个数字节,混着收
468
- // 会拼出一个对不上账的暂存文件,而客户端还以为自己在续传。
469
- if (job.wire !== 'bin') {
470
- return fail(res, 400, 'wire-mismatch', '这个上传是按 JSON 分片协商的,不能混发二进制分片');
471
- }
486
+ return withUploadWrite(uploadId, async () => {
487
+ const job = uploads.get(uploadId);
488
+ if (!job || job.finishPromise) return fail(res, 404, 'unknown-upload', '上传会话不存在或已结束');
489
+ // 两种 wire 的 received 一个数片、一个数字节,同一 job 不能中途换 wire。
490
+ if (job.wire !== 'bin') {
491
+ return fail(res, 400, 'wire-mismatch', '这个上传是按 JSON 分片协商的,不能混发二进制分片');
492
+ }
472
493
 
473
- const offsetText = headerOf(req, 'x-dsh-upload-offset').trim();
474
- const offset = Number(offsetText);
475
- if (!/^\d+$/.test(offsetText) || !Number.isSafeInteger(offset)) {
476
- return fail(res, 400, 'bad-offset', 'X-Dsh-Upload-Offset 必须是非负整数');
477
- }
478
- const piece = await readRawBody(req, BIN_CHUNK_MAX_BYTES);
479
- if (!piece) return fail(res, 413, 'too-large', '分片过大');
480
- if (!piece.length) return fail(res, 400, 'bad-offset', '分片不能是空的');
481
-
482
- const end = offset + piece.length;
483
- if (offset < job.receivedBytes) {
484
- if (end <= job.receivedBytes) return sendJson(res, 200, { ok: true, received: job.receivedBytes });
485
- return fail(res, 400, 'bad-offset', `这一片跨过了已收边界(已收 ${job.receivedBytes} 字节)`);
486
- }
494
+ const offsetText = headerOf(req, 'x-dsh-upload-offset').trim();
495
+ const offset = Number(offsetText);
496
+ if (!/^\d+$/.test(offsetText) || !Number.isSafeInteger(offset)) {
497
+ return fail(res, 400, 'bad-offset', 'X-Dsh-Upload-Offset 必须是非负整数');
498
+ }
499
+ const piece = await readRawBody(req, BIN_CHUNK_MAX_BYTES);
500
+ if (!piece) return fail(res, 413, 'too-large', '分片过大');
501
+ if (!piece.length) return fail(res, 400, 'bad-offset', '分片不能是空的');
502
+
503
+ const end = offset + piece.length;
504
+ if (offset < job.receivedBytes) {
505
+ if (end <= job.receivedBytes) return sendJson(res, 200, { ok: true, received: job.receivedBytes });
506
+ return fail(res, 400, 'bad-offset', `这一片跨过了已收边界(已收 ${job.receivedBytes} 字节)`);
507
+ }
487
508
 
488
- if (offset === job.receivedBytes) {
489
- try {
490
- await appendPiece(job, offset, piece);
491
- await flushWindow(job);
492
- } catch (error) {
493
- removeUpload(uploadId, job);
494
- return fail(res, 500, 'inbox-unavailable', `写入暂存文件失败:${error.message}`);
509
+ if (offset === job.receivedBytes) {
510
+ try {
511
+ await appendPiece(job, offset, piece);
512
+ await flushWindow(job);
513
+ } catch (error) {
514
+ removeUpload(uploadId, job);
515
+ return fail(res, 500, 'inbox-unavailable', `写入暂存文件失败:${error.message}`);
516
+ }
517
+ job.expiresAt = Date.now() + STAGING_TTL_MS;
518
+ scheduleUploadExpiry(uploadId, job);
519
+ return sendJson(res, 200, { ok: true, received: job.receivedBytes });
520
+ }
521
+
522
+ // 乱序片暂存,原有窗口与字节 ACK 语义不变。
523
+ const existing = job.window.find((entry) => entry.offset === offset);
524
+ const added = existing ? piece.length - existing.data.length : piece.length;
525
+ if (
526
+ job.pendingWindowBytes + added > job.windowBytes
527
+ || (!existing && job.window.length >= job.windowPieces)
528
+ ) {
529
+ return fail(res, 409, 'window-exceeded', `乱序窗口已满(${job.windowPieces} 片 / ${job.windowBytes} 字节),请退避后重发这一片`);
495
530
  }
531
+ if (existing) {
532
+ existing.data = piece;
533
+ } else {
534
+ const at = job.window.findIndex((entry) => entry.offset > offset);
535
+ const entry = { offset, data: piece };
536
+ if (at < 0) job.window.push(entry);
537
+ else job.window.splice(at, 0, entry);
538
+ }
539
+ job.pendingWindowBytes += added;
496
540
  job.expiresAt = Date.now() + STAGING_TTL_MS;
497
541
  scheduleUploadExpiry(uploadId, job);
498
542
  return sendJson(res, 200, { ok: true, received: job.receivedBytes });
499
- }
500
-
501
- // 到这里就是乱序:这一片比已连续落盘的字节跑得靠后,先攒着。
502
- const existing = job.window.find((entry) => entry.offset === offset);
503
- const added = existing ? piece.length - existing.data.length : piece.length;
504
- if (
505
- job.pendingWindowBytes + added > job.windowBytes
506
- || (!existing && job.window.length >= job.windowPieces)
507
- ) {
508
- return fail(res, 409, 'window-exceeded', `乱序窗口已满(${job.windowPieces} 片 / ${job.windowBytes} 字节),请退避后重发这一片`);
509
- }
510
- if (existing) {
511
- // 同一偏移重发:以新的字节为准(客户端重传的是同一片,内容应当一样),不重复计数。
512
- existing.data = piece;
513
- } else {
514
- // 保持按偏移升序:flushWindow 只认队首,插错位置会让窗口永远不前进。
515
- const at = job.window.findIndex((entry) => entry.offset > offset);
516
- const entry = { offset, data: piece };
517
- if (at < 0) job.window.push(entry);
518
- else job.window.splice(at, 0, entry);
519
- }
520
- job.pendingWindowBytes += added;
521
- job.expiresAt = Date.now() + STAGING_TTL_MS;
522
- scheduleUploadExpiry(uploadId, job);
523
- return sendJson(res, 200, { ok: true, received: job.receivedBytes });
543
+ });
524
544
  }
525
545
 
526
- /** POST /api/mobile/v1/upload/chunk { uploadId, index, data } → { ok, received }。 */
546
+ /** POST /api/mobile/v1/upload/chunk { uploadId, index, data } → { ok, received, receivedBytes }(v2)。 */
527
547
  async function handleUploadChunk(_ctx, req, res) {
528
548
  // wire 在最前面分流:bin 的请求体是裸密文(守卫已解成 `req.rawBody`),拿它当 JSON 读
529
549
  // 只会得到一个「畸形 JSON」的 413 —— 那是假象,不是真的太大。
@@ -532,35 +552,39 @@ async function handleUploadChunk(_ctx, req, res) {
532
552
  const body = await readJsonBody(req, CHUNK_MAX_BODY);
533
553
  if (!body) return fail(res, 413, 'too-large', '分片过大或不是合法 JSON');
534
554
 
535
- const job = uploads.get(String(body.uploadId == null ? '' : body.uploadId));
536
- if (!job || job.finishPromise) return fail(res, 404, 'unknown-upload', '上传会话不存在或已结束');
537
- if (job.wire === 'bin') {
538
- return fail(res, 400, 'wire-mismatch', '这个上传是按二进制分片协商的,不能混发 JSON 分片');
539
- }
555
+ const uploadId = String(body.uploadId == null ? '' : body.uploadId);
556
+ return withUploadWrite(uploadId, async () => {
557
+ const job = uploads.get(uploadId);
558
+ if (!job || job.finishPromise) return fail(res, 404, 'unknown-upload', '上传会话不存在或已结束');
559
+ if (job.wire === 'bin') {
560
+ return fail(res, 400, 'wire-mismatch', '这个上传是按二进制分片协商的,不能混发 JSON 分片');
561
+ }
540
562
 
541
- const index = Number(body.index);
542
- if (!Number.isInteger(index) || index < 0) return fail(res, 400, 'bad-request', 'index 必须是非负整数');
543
- if (typeof body.data !== 'string') return fail(res, 400, 'bad-request', 'data 必须是 base64 字符串');
544
- if (index < job.received) return sendJson(res, 200, { ok: true, received: job.received });
545
- if (index > job.received) {
546
- return fail(res, 409, 'out-of-order', `期望分片 ${job.received},收到 ${index}`);
547
- }
563
+ const index = Number(body.index);
564
+ if (!Number.isInteger(index) || index < 0) return fail(res, 400, 'bad-request', 'index 必须是非负整数');
565
+ if (typeof body.data !== 'string') return fail(res, 400, 'bad-request', 'data 必须是 base64 字符串');
566
+ if (index < job.received) return sendJson(res, 200, { ok: true, received: job.received, receivedBytes: job.receivedBytes });
567
+ if (index > job.received) {
568
+ return fail(res, 409, 'out-of-order', `期望分片 ${job.received},收到 ${index}`);
569
+ }
548
570
 
549
- const chunk = Buffer.from(body.data, 'base64');
550
- if (!BASE64_RE.test(body.data) || body.data.length % 4 !== 0) {
551
- return fail(res, 400, 'bad-request', 'data 不是合法 base64');
552
- }
553
- try {
554
- await fsp.appendFile(job.stagingPath, chunk);
555
- } catch (error) {
556
- removeUpload(String(body.uploadId), job);
557
- return fail(res, 500, 'inbox-unavailable', `写入暂存文件失败:${error.message}`);
558
- }
559
- job.received += 1;
560
- job.bytes += chunk.length;
561
- job.expiresAt = Date.now() + STAGING_TTL_MS;
562
- scheduleUploadExpiry(String(body.uploadId), job);
563
- sendJson(res, 200, { ok: true, received: job.received });
571
+ const chunk = Buffer.from(body.data, 'base64');
572
+ if (!BASE64_RE.test(body.data) || body.data.length % 4 !== 0) {
573
+ return fail(res, 400, 'bad-request', 'data 不是合法 base64');
574
+ }
575
+ try {
576
+ await fsp.appendFile(job.stagingPath, chunk);
577
+ } catch (error) {
578
+ removeUpload(uploadId, job);
579
+ return fail(res, 500, 'inbox-unavailable', `写入暂存文件失败:${error.message}`);
580
+ }
581
+ job.received += 1;
582
+ job.bytes += chunk.length;
583
+ job.receivedBytes = job.bytes;
584
+ job.expiresAt = Date.now() + STAGING_TTL_MS;
585
+ scheduleUploadExpiry(uploadId, job);
586
+ sendJson(res, 200, { ok: true, received: job.received, receivedBytes: job.receivedBytes });
587
+ });
564
588
  }
565
589
 
566
590
  /** POST /api/mobile/v1/upload/finish { uploadId } → { ok, path, name, bytes }。
@@ -573,52 +597,53 @@ async function handleUploadChunk(_ctx, req, res) {
573
597
  async function handleUploadFinish(_ctx, req, res) {
574
598
  const body = await readJsonBody(req);
575
599
  const uploadId = String((body && body.uploadId) || '');
576
- const job = uploads.get(uploadId);
577
- if (!job) {
578
- const replay = resolveFinishedUpload(uploadId);
579
- if (replay) return sendJson(res, 200, { ok: true, ...replay, uploadId });
580
- return fail(res, 404, 'unknown-upload', '上传会话不存在或已结束');
581
- }
600
+ const pending = await withUploadWrite(uploadId, () => {
601
+ const job = uploads.get(uploadId);
602
+ if (!job) {
603
+ const replay = resolveFinishedUpload(uploadId);
604
+ if (replay) return sendJson(res, 200, { ok: true, ...replay, uploadId });
605
+ return fail(res, 404, 'unknown-upload', '上传会话不存在或已结束');
606
+ }
582
607
 
583
- // v3 的收口必须先证明字节齐了:分片可以乱序、可以重发,少一片时落盘出来的文件是残缺的,
584
- // 而文件名照样对、客户端照样以为传完了。**job 不删** —— 客户端补上缺的那几片后还能再收一次口。
585
- if (job.wire === 'bin' && job.receivedBytes !== job.total) {
586
- return sendJson(res, 400, {
587
- ok: false,
588
- error: { code: 'incomplete', message: `上传还没收齐(已收 ${job.receivedBytes} / ${job.total} 字节)`, received: job.receivedBytes },
589
- });
590
- }
591
- if (!job.finishPromise) {
592
- if (job.expiryTimer) clearTimeout(job.expiryTimer);
593
- job.expiryTimer = null;
594
- const dir = job.destDir || path.join(inboxRoot(), today());
595
- // 判重与落盘共用同一个项目独占窗口。Promise 只存结果,不捕获任何一次请求的 res:
596
- // 首个请求超时断开之后,重试仍然等同一次落盘,并向自己的连接回包。
597
- job.finishPromise = withProjectWrite(queueKeyOf(job.destRoots, dir), async () => {
598
- try {
599
- // 指定落点已在 begin 确认存在,中途被删就报错,不悄悄重建。
600
- if (!job.destDir) await fsp.mkdir(dir, { recursive: true });
601
- const target = await uniquePath(dir, job.name);
608
+ // v3 缺字节时保留上传,客户端补齐后仍可收口。
609
+ if (job.wire === 'bin' && job.receivedBytes !== job.total) {
610
+ return sendJson(res, 400, {
611
+ ok: false,
612
+ error: { code: 'incomplete', message: `上传还没收齐(已收 ${job.receivedBytes} / ${job.total} 字节)`, received: job.receivedBytes },
613
+ });
614
+ }
615
+ if (!job.finishPromise) {
616
+ if (job.expiryTimer) clearTimeout(job.expiryTimer);
617
+ job.expiryTimer = null;
618
+ const dir = job.destDir || path.join(inboxRoot(), today());
619
+ // 项目独占负责判重与落盘;Promise 不捕获 res,首个连接断开后重试仍共用结果。
620
+ job.finishPromise = withProjectWrite(queueKeyOf(job.destRoots, dir), async () => {
602
621
  try {
603
- await fsp.rename(job.stagingPath, target);
622
+ if (!job.destDir) await fsp.mkdir(dir, { recursive: true });
623
+ const target = await uniquePath(dir, job.name);
624
+ try {
625
+ await fsp.rename(job.stagingPath, target);
626
+ } catch (error) {
627
+ if (error.code !== 'EXDEV') throw error;
628
+ await fsp.copyFile(job.stagingPath, target);
629
+ try { await fsp.unlink(job.stagingPath); } catch { /* 落点已完整写好,残片留给清扫 */ }
630
+ }
631
+ const result = { path: target, name: path.basename(target), bytes: job.bytes };
632
+ rememberFinishedUpload(uploadId, result);
633
+ return { status: 200, body: { ok: true, ...result, uploadId } };
604
634
  } catch (error) {
605
- if (error.code !== 'EXDEV') throw error;
606
- await fsp.copyFile(job.stagingPath, target);
607
- try { await fsp.unlink(job.stagingPath); } catch { /* 落点已完整写好,残片留给清扫 */ }
635
+ try { await fsp.unlink(job.stagingPath); } catch { /* 已经不在了 */ }
636
+ return { status: 500, body: { ok: false, error: { code: 'inbox-unavailable', message: `落盘失败:${error.message}` } } };
637
+ } finally {
638
+ removeUpload(uploadId, job);
608
639
  }
609
- const result = { path: target, name: path.basename(target), bytes: job.bytes };
610
- rememberFinishedUpload(uploadId, result);
611
- return { status: 200, body: { ok: true, ...result, uploadId } };
612
- } catch (error) {
613
- try { await fsp.unlink(job.stagingPath); } catch { /* 已经不在了 */ }
614
- return { status: 500, body: { ok: false, error: { code: 'inbox-unavailable', message: `落盘失败:${error.message}` } } };
615
- } finally {
616
- // 成功回执已经可回放,或者这一趟明确失败,才交还上传身份与暂存的所有权。
617
- removeUpload(uploadId, job);
618
- }
619
- });
620
- }
621
- const result = await job.finishPromise;
640
+ });
641
+ }
642
+ // 只发布收口身份;在锁外等待项目写队列,让后到的 chunk/abort 能立即看到已收口。
643
+ return { finishPromise: job.finishPromise };
644
+ });
645
+ if (!pending || !pending.finishPromise) return;
646
+ const result = await pending.finishPromise;
622
647
  return sendJson(res, result.status, result.body);
623
648
  }
624
649
 
@@ -626,13 +651,15 @@ async function handleUploadFinish(_ctx, req, res) {
626
651
  async function handleUploadAbort(_ctx, req, res) {
627
652
  const body = await readJsonBody(req);
628
653
  const uploadId = String((body && body.uploadId) || '');
629
- const job = uploads.get(uploadId);
630
- // finish 一经接收就由落盘任务持有暂存,和已完成后 abort 一样只确认,不撤回收口。
631
- if (job && !job.finishPromise) {
632
- removeUpload(uploadId, job);
633
- try { await fsp.unlink(job.stagingPath); } catch { /* 已经不在了 */ }
634
- }
635
- sendJson(res, 200, { ok: true });
654
+ return withUploadWrite(uploadId, async () => {
655
+ const job = uploads.get(uploadId);
656
+ // finish 一经接收就由落盘任务持有暂存,和已完成后 abort 一样只确认,不撤回收口。
657
+ if (job && !job.finishPromise) {
658
+ removeUpload(uploadId, job);
659
+ try { await fsp.unlink(job.stagingPath); } catch { /* 已经不在了 */ }
660
+ }
661
+ sendJson(res, 200, { ok: true });
662
+ });
636
663
  }
637
664
 
638
665
  const UPLOAD_EXPIRED_MESSAGE = '这张图片的上传已过期,请重新发送';