grpc-libp2p-client 0.0.39 → 0.0.41

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/dist/index.cjs.js CHANGED
@@ -241,7 +241,6 @@ class HPACK {
241
241
  this.dynamicTable.unshift([name, value]);
242
242
  this.dynamicTableSize += size;
243
243
  }
244
- this.dynamicTable.push([name, value]);
245
244
  }
246
245
  // 获取索引的头部
247
246
  getIndexedHeader(index) {
@@ -358,22 +357,29 @@ class HPACK {
358
357
  // Huffman编码实现
359
358
  huffmanEncode(bytes) {
360
359
  const result = [];
360
+ // 使用高精度浮点数累积位,避免 JS 32-bit 有符号整数在位数 >31 时溢出。
361
+ // Huffman 码最长 30 bits,加上未输出的最多 7 bits = 37 bits,超过 32-bit 安全范围。
362
+ // Number 可精确表示 2^53 以内的整数,足够累积多个码字。
361
363
  let current = 0;
362
364
  let bits = 0;
363
365
  for (let i = 0; i < bytes.length; i++) {
364
366
  const b = bytes[i];
365
367
  const code = this.huffmanTable.codes[b];
366
368
  const length = this.huffmanTable.lengths[b];
369
+ // 用乘法左移替代 <<,避免 32-bit 截断
370
+ current = current * (1 << length) + code;
367
371
  bits += length;
368
- current = (current << length) | code;
369
372
  while (bits >= 8) {
370
373
  bits -= 8;
371
- result.push((current >> bits) & 0xFF);
374
+ result.push(Math.floor(current / (1 << bits)) & 0xFF);
375
+ // 保留低 bits 位
376
+ current = current % (1 << bits);
372
377
  }
373
378
  }
374
- // 处理剩余的位
379
+ // 处理剩余的位(用 EOS 填充 1)
375
380
  if (bits > 0) {
376
- current = (current << (8 - bits)) | ((1 << (8 - bits)) - 1);
381
+ const pad = 8 - bits;
382
+ current = current * (1 << pad) + ((1 << pad) - 1);
377
383
  result.push(current & 0xFF);
378
384
  }
379
385
  return new Uint8Array(result);
@@ -396,8 +402,16 @@ class HPACK {
396
402
  headers.set(name, value);
397
403
  index = newIndex;
398
404
  }
399
- else if ((firstByte & 0x20) !== 0) { // 001xxxxx - Dynamic Table Size Update
400
- index++; // 简单跳过,实际应该更新动态表大小
405
+ else if ((firstByte & 0x20) !== 0) { // 001xxxxx - Dynamic Table Size Update (RFC 7541 §6.3)
406
+ const [newSize, newIndex] = this.decodeInteger(buffer, index, 5);
407
+ this.maxDynamicTableSize = newSize;
408
+ // evict entries that exceed the new limit
409
+ while (this.dynamicTableSize > this.maxDynamicTableSize && this.dynamicTable.length > 0) {
410
+ const entry = this.dynamicTable.pop();
411
+ if (entry)
412
+ this.dynamicTableSize -= entry[0].length + entry[1].length + 32;
413
+ }
414
+ index = newIndex;
401
415
  }
402
416
  else if ((firstByte & 0x10) !== 0) { // 0001xxxx - Literal Header Field Never Indexed
403
417
  const [name, value, newIndex] = this.decodeLiteralHeaderWithoutIndexing(buffer, index);
@@ -469,18 +483,18 @@ class HPACK {
469
483
  if (staticIndex <= 0) {
470
484
  return ['', '', newIndex];
471
485
  }
472
- const headerField = this.staticTable[staticIndex];
486
+ const headerField = this.getIndexedHeader(staticIndex);
473
487
  if (!headerField) {
474
488
  return ['', '', newIndex];
475
489
  }
476
490
  return [headerField[0], headerField[1], newIndex];
477
491
  }
478
492
  decodeLiteralHeaderWithIndexing(buffer, index) {
479
- const [staticIndex, nameIndex] = this.decodeInteger(buffer, index, 6);
480
- index = nameIndex;
493
+ const [nameIndex, nextIndex] = this.decodeInteger(buffer, index, 6);
494
+ index = nextIndex;
481
495
  let name;
482
- if (staticIndex > 0) {
483
- const headerField = this.staticTable[staticIndex];
496
+ if (nameIndex > 0) {
497
+ const headerField = this.getIndexedHeader(nameIndex);
484
498
  name = headerField ? headerField[0] : '';
485
499
  }
486
500
  else {
@@ -489,10 +503,26 @@ class HPACK {
489
503
  index = newIndex;
490
504
  }
491
505
  const [value, finalIndex] = this.decodeLiteralString(buffer, index);
506
+ // RFC 7541 §6.2.1: Literal Header Field with Incremental Indexing must add to dynamic table
507
+ this.addToDynamicTable(name, value);
492
508
  return [name, value, finalIndex];
493
509
  }
494
510
  decodeLiteralHeaderWithoutIndexing(buffer, index) {
495
- return this.decodeLiteralHeaderWithIndexing(buffer, index);
511
+ // RFC 7541 §6.2.2 / §6.2.3: 4-bit prefix, do NOT add to dynamic table
512
+ const [nameIndex, nextIndex] = this.decodeInteger(buffer, index, 4);
513
+ index = nextIndex;
514
+ let name;
515
+ if (nameIndex > 0) {
516
+ const headerField = this.getIndexedHeader(nameIndex);
517
+ name = headerField ? headerField[0] : '';
518
+ }
519
+ else {
520
+ const [decodedName, newIndex] = this.decodeLiteralString(buffer, index);
521
+ name = decodedName;
522
+ index = newIndex;
523
+ }
524
+ const [value, finalIndex] = this.decodeLiteralString(buffer, index);
525
+ return [name, value, finalIndex];
496
526
  }
497
527
  // 直接转换为字符串的方法
498
528
  huffmanDecodeToString(bytes) {
@@ -580,9 +610,11 @@ const SETTINGS_PARAMETERS = {
580
610
  };
581
611
  const defaultSettings = {
582
612
  [SETTINGS_PARAMETERS.HEADER_TABLE_SIZE]: 4096,
583
- [SETTINGS_PARAMETERS.ENABLE_PUSH]: 1,
613
+ // gRPC 客户端不使用 Server Push,禁用以避免无效的 PUSH_PROMISE 处理
614
+ [SETTINGS_PARAMETERS.ENABLE_PUSH]: 0,
584
615
  [SETTINGS_PARAMETERS.MAX_CONCURRENT_STREAMS]: 100,
585
- [SETTINGS_PARAMETERS.INITIAL_WINDOW_SIZE]: 16 << 10, // 16k
616
+ // 匹配 parser 的实际接收缓冲区大小(4MB),避免服务端在单流上过早被限速
617
+ [SETTINGS_PARAMETERS.INITIAL_WINDOW_SIZE]: 4 << 20, // 4MB
586
618
  [SETTINGS_PARAMETERS.MAX_FRAME_SIZE]: 16 << 10, // 16k
587
619
  [SETTINGS_PARAMETERS.MAX_HEADER_LIST_SIZE]: 8192
588
620
  };
@@ -643,8 +675,8 @@ class Http2Frame {
643
675
  // Message-Data
644
676
  grpcMessage.set(data, 5);
645
677
  // 然后将完整的 gRPC 消息分割成多个 HTTP/2 DATA 帧
646
- // HTTP/2 帧头为 9 字节
647
- const maxDataPerFrame = maxFrameSize - 9;
678
+ // maxFrameSize 是 payload 上限(RFC 7540 §6.5.2 MAX_FRAME_SIZE),不含 9 字节帧头
679
+ const maxDataPerFrame = maxFrameSize;
648
680
  for (let offset = 0; offset < grpcMessage.length; offset += maxDataPerFrame) {
649
681
  const remaining = grpcMessage.length - offset;
650
682
  const chunkSize = Math.min(maxDataPerFrame, remaining);
@@ -676,13 +708,13 @@ class Http2Frame {
676
708
  const flags = endStream ? 0x01 : 0x0; // END_STREAM flag
677
709
  return Http2Frame.createFrame(0x0, flags, streamId, framedData);
678
710
  }
679
- static createHeadersFrame(streamId, path, endHeaders = true, token) {
711
+ static createHeadersFrame(streamId, path, endHeaders = true, token, authority = 'localhost') {
680
712
  // gRPC-Web 需要的标准 headers
681
713
  const headersList = {
682
714
  ':path': path,
683
715
  ':method': 'POST',
684
716
  ':scheme': 'http',
685
- ':authority': 'localhost',
717
+ ':authority': authority,
686
718
  'content-type': 'application/grpc+proto',
687
719
  'user-agent': 'grpc-web-client/0.1',
688
720
  'accept': 'application/grpc+proto',
@@ -809,8 +841,15 @@ function _createPayload(settings) {
809
841
 
810
842
  const HTTP2_PREFACE = new TextEncoder().encode("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
811
843
  class HTTP2Parser {
844
+ /** 兼容旧代码读取 buffer —— 仅在必须全量访问时调用 _flattenBuffer() */
845
+ get buffer() { return this._flattenBuffer(); }
846
+ set buffer(v) { this.bufferChunks = v.length ? [v] : []; this.bufferTotalLength = v.length; }
812
847
  constructor(writer, options) {
813
- this.buffer = new Uint8Array(0);
848
+ /** 分段缓冲:避免每次 chunk 到达时 O(n) 全量拷贝 */
849
+ this.bufferChunks = [];
850
+ this.bufferTotalLength = 0;
851
+ this.bufferChunks = [];
852
+ this.bufferTotalLength = 0;
814
853
  this.settingsAckReceived = false;
815
854
  this.peerSettingsReceived = false;
816
855
  // 初始化连接级别的流控制窗口大小(默认值:65,535)
@@ -824,11 +863,38 @@ class HTTP2Parser {
824
863
  this.sendStreamWindows = new Map();
825
864
  this.peerInitialStreamWindow = 65535;
826
865
  this.sendWindowWaiters = [];
866
+ this.settingsAckWaiters = [];
867
+ this.peerSettingsWaiters = [];
868
+ this.endOfStreamWaiters = [];
827
869
  // 结束标志
828
870
  this.endFlag = false;
829
871
  this.writer = writer;
830
872
  this.compatibilityMode = options?.compatibilityMode ?? false;
831
873
  }
874
+ /** 将所有分段合并为一个连续 Uint8Array(仅在必要时调用)*/
875
+ _flattenBuffer() {
876
+ if (this.bufferChunks.length === 0)
877
+ return new Uint8Array(0);
878
+ if (this.bufferChunks.length === 1)
879
+ return this.bufferChunks[0];
880
+ const out = new Uint8Array(this.bufferTotalLength);
881
+ let off = 0;
882
+ for (const c of this.bufferChunks) {
883
+ out.set(c, off);
884
+ off += c.length;
885
+ }
886
+ return out;
887
+ }
888
+ /** 唤醒所有发送窗口等待者 */
889
+ _wakeWindowWaiters() {
890
+ const ws = this.sendWindowWaiters.splice(0);
891
+ for (const w of ws) {
892
+ try {
893
+ w.resolve();
894
+ }
895
+ catch { /* ignore */ }
896
+ }
897
+ }
832
898
  // 持续处理流数据
833
899
  async processStream(stream) {
834
900
  try {
@@ -838,7 +904,6 @@ class HTTP2Parser {
838
904
  }
839
905
  // Stream 结束后的清理工作
840
906
  if (!this.compatibilityMode && !this.endFlag) {
841
- this.endFlag = true;
842
907
  try {
843
908
  this.onEnd?.();
844
909
  }
@@ -846,51 +911,85 @@ class HTTP2Parser {
846
911
  console.error("Error during onEnd callback:", err);
847
912
  }
848
913
  }
914
+ // 无论何种模式,stream 结束时都通知 waitForEndOfStream 等待者,
915
+ // 防止 compatibilityMode=true(server-streaming)时 waitForEndOfStream(0) 永久挂死
916
+ if (!this.endFlag) {
917
+ this._notifyEndOfStream();
918
+ }
849
919
  }
850
920
  catch (error) {
921
+ // 确保 waitForEndOfStream 等待者得到通知,防止 operationPromise 后台挂死
922
+ if (!this.endFlag) {
923
+ this._notifyEndOfStream();
924
+ }
925
+ // 仅过滤我们自己主动触发的清理错误(reason 固定为 'Call cleanup' / 'unaryCall cleanup')。
926
+ // 不使用 /aborted/i,因为 libp2p / 浏览器网络层可能抛出含 "aborted" 字样的真实错误
927
+ // (如 "AbortError: The operation was aborted", "Connection aborted by peer"),
928
+ // 若误匹配会导致 reportError 不被调用,onErrorCallback 丢失,调用方误认为成功。
929
+ const errMsg = error instanceof Error ? error.message : String(error);
930
+ if (/cleanup/i.test(errMsg)) {
931
+ // 预期的主动清理,无需 re-throw,.catch in index.ts 不需要处理它
932
+ return;
933
+ }
851
934
  console.error("Error processing stream:", error);
852
935
  throw error;
853
936
  }
854
937
  }
855
- // 处理单个数据块
938
+ // 处理单个数据块 — 分段列表追加,避免每次 O(n) 全量拷贝
856
939
  _processChunk(chunk) {
857
940
  // chunk 是 Uint8ArrayList 或 Uint8Array
858
941
  const newData = 'subarray' in chunk && typeof chunk.subarray === 'function'
859
942
  ? chunk.subarray()
860
943
  : chunk;
861
- // 原作者之前的 O(N) 内存拷贝优化被保留,去掉了存在 onEnd 竞态的 setTimeout
862
- const newBuffer = new Uint8Array(this.buffer.length + newData.length);
863
- newBuffer.set(this.buffer);
864
- newBuffer.set(newData, this.buffer.length);
865
- this.buffer = newBuffer;
944
+ // 追加到分段列表,O(1),不拷贝历史数据
945
+ if (newData.length > 0) {
946
+ this.bufferChunks.push(newData);
947
+ this.bufferTotalLength += newData.length;
948
+ }
949
+ // 将所有分段合并为一块后处理帧(只合并一次,后续 slice 替换)
950
+ // 仅在确实有完整帧时才触发合并,碎片仅 push 不合并
951
+ if (this.bufferTotalLength < 9)
952
+ return;
953
+ // 合并一次
954
+ const flat = this._flattenBuffer();
955
+ this.bufferChunks = [flat];
956
+ // bufferTotalLength 保持不变
866
957
  // 持续处理所有完整的帧
867
958
  let readOffset = 0;
868
- while (this.buffer.length - readOffset >= 9) {
959
+ while (flat.length - readOffset >= 9) {
869
960
  // 判断是否有HTTP/2前导
870
- if (this.buffer.length - readOffset >= 24 && this.isHttp2Preface(this.buffer.subarray(readOffset))) {
961
+ if (flat.length - readOffset >= 24 && this.isHttp2Preface(flat.subarray(readOffset))) {
871
962
  readOffset += 24;
872
963
  // 发送SETTINGS帧
873
964
  const settingFrame = Http2Frame.createSettingsFrame();
874
965
  this.writer.write(settingFrame);
875
966
  continue;
876
967
  }
877
- const frameHeader = this._parseFrameHeader(this.buffer.subarray(readOffset));
968
+ const frameHeader = this._parseFrameHeader(flat.subarray(readOffset));
878
969
  const totalFrameLength = 9 + frameHeader.length;
879
970
  // 检查是否有完整的帧
880
- if (this.buffer.length - readOffset < totalFrameLength) {
971
+ if (flat.length - readOffset < totalFrameLength) {
881
972
  break;
882
973
  }
883
- // 获取完整帧数据
884
- const frameData = this.buffer.subarray(readOffset, readOffset + totalFrameLength);
974
+ // 获取完整帧数据(subarray 视图,零拷贝)
975
+ const frameData = flat.subarray(readOffset, readOffset + totalFrameLength);
885
976
  // 处理不同类型的帧
886
977
  this._handleFrame(frameHeader, frameData).catch((err) => {
887
978
  console.error("Error handling frame:", err);
888
979
  });
889
- // 移动偏移量
890
980
  readOffset += totalFrameLength;
891
981
  }
982
+ // 保留未消费的尾部字节(slice 一次,后续仍分段追加)
892
983
  if (readOffset > 0) {
893
- this.buffer = this.buffer.slice(readOffset);
984
+ if (readOffset >= flat.length) {
985
+ this.bufferChunks = [];
986
+ this.bufferTotalLength = 0;
987
+ }
988
+ else {
989
+ const remaining = flat.slice(readOffset);
990
+ this.bufferChunks = [remaining];
991
+ this.bufferTotalLength = remaining.length;
992
+ }
894
993
  }
895
994
  }
896
995
  isHttp2Preface(buffer) {
@@ -902,50 +1001,67 @@ class HTTP2Parser {
902
1001
  }
903
1002
  return true;
904
1003
  }
905
- // 移除之前的 for await 循环代码
906
- _oldProcessStream_removed() {
907
- // 这个方法已被上面的事件驱动实现替代
908
- }
909
- // 等待SETTINGS ACK
1004
+ // 等待SETTINGS ACK 事件驱动,无轮询
910
1005
  waitForSettingsAck() {
911
1006
  return new Promise((resolve, reject) => {
912
1007
  if (this.settingsAckReceived) {
913
1008
  resolve();
914
1009
  return;
915
1010
  }
916
- const interval = setInterval(() => {
917
- if (this.settingsAckReceived) {
918
- clearInterval(interval);
919
- clearTimeout(timeout);
920
- resolve();
921
- }
922
- }, 100);
1011
+ const waiter = { resolve, reject };
1012
+ this.settingsAckWaiters.push(waiter);
923
1013
  const timeout = setTimeout(() => {
924
- clearInterval(interval);
1014
+ const idx = this.settingsAckWaiters.indexOf(waiter);
1015
+ if (idx >= 0)
1016
+ this.settingsAckWaiters.splice(idx, 1);
925
1017
  reject(new Error("Settings ACK timeout"));
926
1018
  }, 30000);
1019
+ // 覆盖 resolve 以便超时前自动清理定时器
1020
+ waiter.resolve = () => { clearTimeout(timeout); resolve(); };
1021
+ waiter.reject = (e) => { clearTimeout(timeout); reject(e); };
927
1022
  });
928
1023
  }
929
- // 等待接收来自对端的 SETTINGS(非 ACK
1024
+ /** 内部调用:SETTINGS ACK 收到时唤醒所有等待者 */
1025
+ _notifySettingsAck() {
1026
+ this.settingsAckReceived = true;
1027
+ const ws = this.settingsAckWaiters.splice(0);
1028
+ for (const w of ws) {
1029
+ try {
1030
+ w.resolve();
1031
+ }
1032
+ catch { /* ignore */ }
1033
+ }
1034
+ }
1035
+ // 等待接收来自对端的 SETTINGS(非 ACK)— 事件驱动,无轮询
930
1036
  waitForPeerSettings(timeoutMs = 30000) {
931
1037
  return new Promise((resolve, reject) => {
932
1038
  if (this.peerSettingsReceived) {
933
1039
  resolve();
934
1040
  return;
935
1041
  }
936
- const interval = setInterval(() => {
937
- if (this.peerSettingsReceived) {
938
- clearInterval(interval);
939
- clearTimeout(timeout);
940
- resolve();
941
- }
942
- }, 100);
1042
+ const waiter = { resolve, reject };
1043
+ this.peerSettingsWaiters.push(waiter);
943
1044
  const timeout = setTimeout(() => {
944
- clearInterval(interval);
1045
+ const idx = this.peerSettingsWaiters.indexOf(waiter);
1046
+ if (idx >= 0)
1047
+ this.peerSettingsWaiters.splice(idx, 1);
945
1048
  reject(new Error("Peer SETTINGS timeout"));
946
1049
  }, timeoutMs);
1050
+ waiter.resolve = () => { clearTimeout(timeout); resolve(); };
1051
+ waiter.reject = (e) => { clearTimeout(timeout); reject(e); };
947
1052
  });
948
1053
  }
1054
+ /** 内部调用:收到对端 SETTINGS(非 ACK)时唤醒等待者 */
1055
+ _notifyPeerSettings() {
1056
+ this.peerSettingsReceived = true;
1057
+ const ws = this.peerSettingsWaiters.splice(0);
1058
+ for (const w of ws) {
1059
+ try {
1060
+ w.resolve();
1061
+ }
1062
+ catch { /* ignore */ }
1063
+ }
1064
+ }
949
1065
  // 注册我们要发送数据的出站流(用于初始化该流的对端窗口)
950
1066
  registerOutboundStream(streamId) {
951
1067
  if (!this.sendStreamWindows.has(streamId)) {
@@ -972,54 +1088,51 @@ class HTTP2Parser {
972
1088
  this.sendConnWindow = Math.min(0x7fffffff, this.sendConnWindow + bytes);
973
1089
  const cur = this.sendStreamWindows.get(streamId) ?? 0;
974
1090
  this.sendStreamWindows.set(streamId, Math.min(0x7fffffff, cur + bytes));
1091
+ // 窗口增大,唤醒等待者
1092
+ this._wakeWindowWaiters();
975
1093
  }
976
- // 等待可用发送窗口(两个窗口都需要 >0)
977
- async waitForSendWindow(streamId, minBytes = 1, timeoutMs = 30000) {
978
- const start = Date.now();
1094
+ // 等待可用发送窗口 — 事件驱动,WINDOW_UPDATE/SETTINGS 收到时直接唤醒
1095
+ waitForSendWindow(streamId, minBytes = 1, timeoutMs = 30000) {
1096
+ const { conn, stream } = this.getSendWindows(streamId);
1097
+ if (conn >= minBytes && stream >= minBytes)
1098
+ return Promise.resolve();
979
1099
  return new Promise((resolve, reject) => {
980
- let interval = null;
981
1100
  let settled = false;
982
- const check = () => {
983
- const { conn, stream } = this.getSendWindows(streamId);
984
- if (conn >= minBytes && stream >= minBytes) {
985
- if (!settled) {
986
- settled = true;
987
- if (interval) {
988
- clearInterval(interval);
989
- interval = null;
990
- }
991
- resolve();
992
- }
993
- return true;
994
- }
995
- if (Date.now() - start > timeoutMs) {
996
- if (!settled) {
997
- settled = true;
998
- if (interval) {
999
- clearInterval(interval);
1000
- interval = null;
1001
- }
1002
- reject(new Error('Send window wait timeout'));
1003
- }
1004
- return true;
1101
+ const timeout = timeoutMs > 0
1102
+ ? setTimeout(() => {
1103
+ if (settled)
1104
+ return;
1105
+ settled = true;
1106
+ const idx = this.sendWindowWaiters.findIndex(w => w.resolve === resolveWrap);
1107
+ if (idx >= 0)
1108
+ this.sendWindowWaiters.splice(idx, 1);
1109
+ reject(new Error('Send window wait timeout'));
1110
+ }, timeoutMs)
1111
+ : undefined;
1112
+ const resolveWrap = () => {
1113
+ if (settled)
1114
+ return;
1115
+ const { conn: c2, stream: s2 } = this.getSendWindows(streamId);
1116
+ if (c2 >= minBytes && s2 >= minBytes) {
1117
+ settled = true;
1118
+ if (timeout)
1119
+ clearTimeout(timeout);
1120
+ resolve();
1121
+ }
1122
+ else {
1123
+ // 窗口仍不够,重新入队等待下一次更新
1124
+ this.sendWindowWaiters.push({ resolve: resolveWrap, reject: rejectWrap });
1005
1125
  }
1006
- return false;
1007
1126
  };
1008
- if (check())
1009
- return;
1010
- const tick = () => {
1011
- if (!check()) ;
1127
+ const rejectWrap = (e) => {
1128
+ if (settled)
1129
+ return;
1130
+ settled = true;
1131
+ if (timeout)
1132
+ clearTimeout(timeout);
1133
+ reject(e);
1012
1134
  };
1013
- const wake = () => { tick(); };
1014
- // 简单的等待模型:依赖 WINDOW_UPDATE 到达时调用 wake
1015
- this.sendWindowWaiters.push(wake);
1016
- // 同时做一个轻微的轮询,防止错过唤醒
1017
- interval = setInterval(() => {
1018
- if (check() && interval) {
1019
- clearInterval(interval);
1020
- interval = null;
1021
- }
1022
- }, 50);
1135
+ this.sendWindowWaiters.push({ resolve: resolveWrap, reject: rejectWrap });
1023
1136
  });
1024
1137
  }
1025
1138
  // 处理单个帧
@@ -1027,7 +1140,7 @@ class HTTP2Parser {
1027
1140
  switch (frameHeader.type) {
1028
1141
  case FRAME_TYPES.SETTINGS:
1029
1142
  if ((frameHeader.flags & FRAME_FLAGS.ACK) === FRAME_FLAGS.ACK) {
1030
- this.settingsAckReceived = true;
1143
+ this._notifySettingsAck();
1031
1144
  }
1032
1145
  else {
1033
1146
  //接收到Setting请求,进行解析
@@ -1037,10 +1150,12 @@ class HTTP2Parser {
1037
1150
  for (let i = 0; i < settingsPayload.length; i += 6) {
1038
1151
  // 正确解析:2字节ID + 4字节值
1039
1152
  const id = (settingsPayload[i] << 8) | settingsPayload[i + 1];
1040
- const value = (settingsPayload[i + 2] << 24) |
1153
+ // >>> 0 将结果转为无符号 32 位整数,防止高位为 1 时(如 0xffffffff)
1154
+ // 被 JS 按有符号解读为负数,导致 maxConcurrentStreams 等字段为负值
1155
+ const value = ((settingsPayload[i + 2] << 24) |
1041
1156
  (settingsPayload[i + 3] << 16) |
1042
1157
  (settingsPayload[i + 4] << 8) |
1043
- settingsPayload[i + 5];
1158
+ settingsPayload[i + 5]) >>> 0;
1044
1159
  if (id === 4) {
1045
1160
  // SETTINGS_INITIAL_WINDOW_SIZE
1046
1161
  this.defaultStreamWindowSize = value; // 我方接收窗口(入站)
@@ -1077,47 +1192,47 @@ class HTTP2Parser {
1077
1192
  if (this.onSettings) {
1078
1193
  this.onSettings(frameHeader);
1079
1194
  }
1080
- // 标记已收到对端 SETTINGS
1081
- this.peerSettingsReceived = true;
1082
- // 唤醒等待窗口(以防部分实现通过 SETTINGS 改变有效窗口)
1083
- const waiters = this.sendWindowWaiters.splice(0);
1084
- waiters.forEach(fn => { try {
1085
- fn();
1086
- }
1087
- catch (e) {
1088
- console.debug('waiter error', e);
1089
- } });
1195
+ // 标记已收到对端 SETTINGS 并唤醒等待者
1196
+ this._notifyPeerSettings();
1197
+ // 唤醒发送窗口等待者(以防部分实现通过 SETTINGS 改变有效窗口)
1198
+ this._wakeWindowWaiters();
1090
1199
  }
1091
1200
  break;
1092
- case FRAME_TYPES.DATA:
1201
+ case FRAME_TYPES.DATA: {
1093
1202
  // 处理数据帧
1094
1203
  if (this.onData) {
1095
1204
  this.onData(frameData.slice(9), frameHeader); // 跳过帧头
1096
1205
  }
1097
1206
  // 更新流窗口和连接窗口
1098
- try {
1099
- // 更新流级别的窗口
1100
- if (frameHeader.streamId !== 0) {
1101
- const streamWindowUpdate = Http2Frame.createWindowUpdateFrame(frameHeader.streamId, frameHeader.length ?? 0);
1102
- this.writer.write(streamWindowUpdate);
1207
+ // 仅在帧有实际数据时才发送 WINDOW_UPDATE:
1208
+ // RFC 7540 §6.9.1 明确禁止 increment=0 的 WINDOW_UPDATE,
1209
+ // 服务端必须以 PROTOCOL_ERROR 响应,会导致连接被强制关闭。
1210
+ // DATA 帧(如纯 END_STREAM 帧)length=0,不需要归还窗口。
1211
+ const dataLength = frameHeader.length ?? 0;
1212
+ if (dataLength > 0) {
1213
+ try {
1214
+ // 更新流级别的窗口
1215
+ if (frameHeader.streamId !== 0) {
1216
+ const streamWindowUpdate = Http2Frame.createWindowUpdateFrame(frameHeader.streamId, dataLength);
1217
+ this.writer.write(streamWindowUpdate);
1218
+ }
1219
+ // 更新连接级别的窗口
1220
+ const connWindowUpdate = Http2Frame.createWindowUpdateFrame(0, dataLength);
1221
+ this.writer.write(connWindowUpdate);
1222
+ }
1223
+ catch (err) {
1224
+ console.error("[HTTP2] Error sending window update:", err);
1103
1225
  }
1104
- // 更新连接级别的窗口
1105
- const connWindowUpdate = Http2Frame.createWindowUpdateFrame(0, frameHeader.length ?? 0);
1106
- this.writer.write(connWindowUpdate);
1107
- }
1108
- catch (err) {
1109
- console.error("[HTTP2] Error sending window update:", err);
1110
1226
  }
1111
1227
  //判断是否是最后一个帧
1112
1228
  if ((frameHeader.flags & FRAME_FLAGS.END_STREAM) ===
1113
1229
  FRAME_FLAGS.END_STREAM) {
1114
- this.endFlag = true;
1115
- if (this.onEnd) {
1116
- this.onEnd();
1117
- }
1230
+ this.onEnd?.();
1231
+ this._notifyEndOfStream();
1118
1232
  return;
1119
1233
  }
1120
1234
  break;
1235
+ }
1121
1236
  case FRAME_TYPES.HEADERS:
1122
1237
  // 处理头部帧
1123
1238
  if (this.onHeaders) {
@@ -1126,35 +1241,26 @@ class HTTP2Parser {
1126
1241
  //判断是否是最后一个帧
1127
1242
  if ((frameHeader.flags & FRAME_FLAGS.END_STREAM) ===
1128
1243
  FRAME_FLAGS.END_STREAM) {
1129
- this.endFlag = true;
1130
- if (this.onEnd) {
1131
- this.onEnd();
1132
- }
1244
+ this.onEnd?.();
1245
+ this._notifyEndOfStream();
1133
1246
  return;
1134
1247
  }
1135
1248
  break;
1136
1249
  case FRAME_TYPES.WINDOW_UPDATE:
1137
- // 处理窗口更新帧
1138
- this.handleWindowUpdateFrame(frameHeader, frameData);
1139
- // 更新发送窗口(对端接收窗口)
1250
+ // 处理窗口更新帧(同时更新接收侧诊断计数器和发送侧流控窗口,只解析一次)
1140
1251
  try {
1141
- const inc = this.parseWindowUpdateFrame(frameData, frameHeader).windowSizeIncrement;
1252
+ const result = this.handleWindowUpdateFrame(frameHeader, frameData);
1253
+ // 更新发送方向窗口(对端的接收窗口)
1142
1254
  if (frameHeader.streamId === 0) {
1143
- this.sendConnWindow += inc;
1255
+ this.sendConnWindow += result.windowSizeIncrement;
1144
1256
  }
1145
1257
  else {
1146
1258
  const cur = this.sendStreamWindows.get(frameHeader.streamId) ?? this.peerInitialStreamWindow;
1147
- this.sendStreamWindows.set(frameHeader.streamId, cur + inc);
1259
+ this.sendStreamWindows.set(frameHeader.streamId, cur + result.windowSizeIncrement);
1148
1260
  }
1149
- const waiters = this.sendWindowWaiters.splice(0);
1150
- waiters.forEach(fn => { try {
1151
- fn();
1152
- }
1153
- catch (e) {
1154
- console.debug('waiter error', e);
1155
- } });
1261
+ this._wakeWindowWaiters();
1156
1262
  }
1157
- catch { /* ignore WINDOW_UPDATE parse errors */ }
1263
+ catch { /* ignore WINDOW_UPDATE parse errors (e.g. increment=0 is RFC PROTOCOL_ERROR) */ }
1158
1264
  break;
1159
1265
  case FRAME_TYPES.PING:
1160
1266
  // 处理PING帧
@@ -1183,13 +1289,13 @@ class HTTP2Parser {
1183
1289
  catch (err) {
1184
1290
  console.error('Error during GOAWAY callback:', err);
1185
1291
  }
1186
- this.endFlag = true;
1187
1292
  try {
1188
1293
  this.onEnd?.();
1189
1294
  }
1190
1295
  catch (err) {
1191
1296
  console.error('Error during GOAWAY onEnd callback:', err);
1192
1297
  }
1298
+ this._notifyEndOfStream();
1193
1299
  break;
1194
1300
  }
1195
1301
  // case FRAME_TYPES.PUSH_PROMISE:
@@ -1197,10 +1303,8 @@ class HTTP2Parser {
1197
1303
  // this.handlePushPromiseFrame(frameHeader, frameData);
1198
1304
  // break;
1199
1305
  case FRAME_TYPES.RST_STREAM:
1200
- this.endFlag = true;
1201
- if (this.onEnd) {
1202
- this.onEnd();
1203
- }
1306
+ this.onEnd?.();
1307
+ this._notifyEndOfStream();
1204
1308
  break;
1205
1309
  default:
1206
1310
  console.debug("Unknown frame type:", frameHeader.type);
@@ -1210,7 +1314,8 @@ class HTTP2Parser {
1210
1314
  const length = (buffer[0] << 16) | (buffer[1] << 8) | buffer[2];
1211
1315
  const type = buffer[3];
1212
1316
  const flags = buffer[4];
1213
- const streamId = (buffer[5] << 24) | (buffer[6] << 16) | (buffer[7] << 8) | buffer[8];
1317
+ // RFC 7540 §4.1: most significant bit is reserved and MUST be ignored on receipt
1318
+ const streamId = ((buffer[5] << 24) | (buffer[6] << 16) | (buffer[7] << 8) | buffer[8]) & 0x7fffffff;
1214
1319
  return {
1215
1320
  length,
1216
1321
  type,
@@ -1239,52 +1344,40 @@ class HTTP2Parser {
1239
1344
  throw error;
1240
1345
  }
1241
1346
  }
1242
- //等待流结束
1347
+ // 等待流结束 — 事件驱动,onEnd 触发时直接唤醒,无 setInterval 轮询
1243
1348
  waitForEndOfStream(waitTime) {
1244
1349
  return new Promise((resolve, reject) => {
1245
- // If the stream has already ended, resolve immediately
1246
1350
  if (this.endFlag) {
1247
1351
  resolve();
1248
1352
  return;
1249
1353
  }
1250
- // 如果是0 ,则不设置超时
1251
- let timeout = null;
1252
- if (waitTime > 0) {
1253
- timeout = setTimeout(() => {
1254
- clearInterval(interval);
1354
+ const waiter = { resolve, reject };
1355
+ this.endOfStreamWaiters.push(waiter);
1356
+ const timeout = waitTime > 0
1357
+ ? setTimeout(() => {
1358
+ const idx = this.endOfStreamWaiters.indexOf(waiter);
1359
+ if (idx >= 0)
1360
+ this.endOfStreamWaiters.splice(idx, 1);
1255
1361
  reject(new Error("End of stream timeout"));
1256
- }, waitTime);
1257
- }
1258
- // Check interval for real-time endFlag monitoring
1259
- const checkInterval = 100; // Check every 100 milliseconds
1260
- // Set an interval to check the endFlag regularly
1261
- const interval = setInterval(() => {
1262
- if (this.endFlag) {
1263
- if (timeout !== null) {
1264
- clearTimeout(timeout);
1265
- }
1266
- clearInterval(interval);
1267
- resolve();
1268
- }
1269
- }, checkInterval);
1270
- // If the onEnd is triggered externally, it should now be marked manually
1271
- const originalOnEnd = this.onEnd;
1272
- this.onEnd = () => {
1273
- if (!this.endFlag) {
1274
- // The external trigger may set endFlag; if not, handle here
1275
- this.endFlag = true;
1276
- }
1277
- if (timeout !== null) {
1278
- clearTimeout(timeout);
1279
- }
1280
- clearInterval(interval);
1281
- resolve();
1282
- if (originalOnEnd) {
1283
- originalOnEnd(); // Call the original onEnd function if set
1284
- }
1285
- };
1362
+ }, waitTime)
1363
+ : null;
1364
+ waiter.resolve = () => { if (timeout)
1365
+ clearTimeout(timeout); resolve(); };
1366
+ waiter.reject = (e) => { if (timeout)
1367
+ clearTimeout(timeout); reject(e); };
1286
1368
  });
1287
1369
  }
1370
+ /** 内部调用:流结束时唤醒所有 waitForEndOfStream 等待者 */
1371
+ _notifyEndOfStream() {
1372
+ this.endFlag = true;
1373
+ const ws = this.endOfStreamWaiters.splice(0);
1374
+ for (const w of ws) {
1375
+ try {
1376
+ w.resolve();
1377
+ }
1378
+ catch { /* ignore */ }
1379
+ }
1380
+ }
1288
1381
  // 解析 WINDOW_UPDATE 帧
1289
1382
  parseWindowUpdateFrame(frameBuffer, frameHeader) {
1290
1383
  // WINDOW_UPDATE帧的payload固定为4字节
@@ -1343,6 +1436,8 @@ class StreamWriter {
1343
1436
  this.lastBytesDrainedSeen = 0;
1344
1437
  this.lastBpWarnAt = 0;
1345
1438
  this.isHandlingError = false; // 防止重复错误处理
1439
+ /** drain 事件驱动等待者,替代 flush() 中的 setInterval 轮询 */
1440
+ this.drainWaiters = [];
1346
1441
  // 事件系统
1347
1442
  this.listeners = new Map();
1348
1443
  // 验证 stream 参数
@@ -1444,8 +1539,9 @@ class StreamWriter {
1444
1539
  // 使用 stream.send() 发送数据,返回 false 表示需要等待 drain
1445
1540
  const canContinue = this.stream.send(chunk);
1446
1541
  if (!canContinue) {
1447
- // 等待 drain 事件
1448
- await this.stream.onDrain();
1542
+ // 传入 abort signal,当流被 abort 时 onDrain() 会立即 reject,
1543
+ // 避免在 abort 路径下永久挂住
1544
+ await this.stream.onDrain({ signal: this.abortController.signal });
1449
1545
  }
1450
1546
  }
1451
1547
  catch (err) {
@@ -1461,6 +1557,9 @@ class StreamWriter {
1461
1557
  throw err;
1462
1558
  }
1463
1559
  }
1560
+ // pipeline 正常结束(stream 关闭或 pushable 耗尽)—— 确保资源清理
1561
+ // 若已通过 abort() 触发则 cleanup() 内部幂等处理
1562
+ this.cleanup();
1464
1563
  }
1465
1564
  createTransform() {
1466
1565
  // eslint-disable-next-line @typescript-eslint/no-this-alias
@@ -1482,6 +1581,16 @@ class StreamWriter {
1482
1581
  self.lastDrainEventAt = now;
1483
1582
  self.dispatchEvent(new CustomEvent('drain', { detail: { drained: self.bytesDrained, queueSize: self.queueSize } }));
1484
1583
  }
1584
+ // 唤醒所有在等 flush() 或背压解除 的 drainWaiters(队列降低时就可唤醒)
1585
+ if (self.drainWaiters.length > 0) {
1586
+ const ws = self.drainWaiters.splice(0);
1587
+ for (const fn of ws) {
1588
+ try {
1589
+ fn();
1590
+ }
1591
+ catch { /* ignore */ }
1592
+ }
1593
+ }
1485
1594
  // 记录本次已消耗字节,用于看门狗判断是否前进
1486
1595
  self.lastBytesDrainedSeen = self.bytesDrained;
1487
1596
  }
@@ -1569,10 +1678,11 @@ class StreamWriter {
1569
1678
  return data;
1570
1679
  }
1571
1680
  async writeChunks(buffer) {
1572
- for (let offset = 0; offset < buffer.byteLength; offset += this.options.chunkSize) {
1573
- const end = Math.min(offset + this.options.chunkSize, buffer.byteLength);
1574
- const chunk = new Uint8Array(end - offset);
1575
- chunk.set(new Uint8Array(buffer.slice(offset, end)));
1681
+ const src = new Uint8Array(buffer);
1682
+ for (let offset = 0; offset < src.byteLength; offset += this.options.chunkSize) {
1683
+ const end = Math.min(offset + this.options.chunkSize, src.byteLength);
1684
+ // subarray 创建视图,不拷贝内存。pushable.push 不修改内容,安全。
1685
+ const chunk = src.subarray(offset, end);
1576
1686
  await this.retryableWrite(chunk);
1577
1687
  this.updateProgress(chunk.byteLength);
1578
1688
  }
@@ -1593,18 +1703,12 @@ class StreamWriter {
1593
1703
  if (this.abortController.signal.aborted) {
1594
1704
  throw new Error('Stream aborted during backpressure monitoring');
1595
1705
  }
1596
- await new Promise((resolve, reject) => {
1597
- try {
1598
- this.p.push(chunk);
1599
- }
1600
- catch (err) {
1601
- reject(err);
1602
- }
1603
- resolve();
1604
- });
1706
+ // push 是同步操作,直接调用即可
1707
+ this.p.push(chunk);
1605
1708
  }
1606
1709
  catch (err) {
1607
- if (attempt < this.options.retries) {
1710
+ // aborted 时不重试,立即抛出
1711
+ if (!this.abortController.signal.aborted && attempt < this.options.retries) {
1608
1712
  const delay = this.calculateRetryDelay(attempt);
1609
1713
  await new Promise(r => setTimeout(r, delay));
1610
1714
  return this.retryableWrite(chunk, attempt + 1);
@@ -1613,58 +1717,45 @@ class StreamWriter {
1613
1717
  }
1614
1718
  }
1615
1719
  async monitorBackpressure() {
1616
- const currentSize = this.queueSize;
1617
- const baseThreshold = this.options.bufferSize * 0.7; // 降低基础阈值,更早检测
1618
- const criticalThreshold = this.options.bufferSize * 0.9; // 临界阈值
1619
- // 快速路径:无背压时直接返回
1620
- if (currentSize < baseThreshold) {
1720
+ const baseThreshold = this.options.bufferSize * 0.7;
1721
+ const criticalThreshold = this.options.bufferSize * 0.9;
1722
+ // 快速路径
1723
+ if (this.queueSize < baseThreshold) {
1621
1724
  if (this.isBackpressure) {
1622
1725
  this.isBackpressure = false;
1623
- this.dispatchBackpressureEvent({
1624
- currentSize,
1625
- averageSize: this.getAverageQueueSize(),
1626
- threshold: baseThreshold,
1627
- waitingTime: 0
1628
- });
1726
+ this.dispatchBackpressureEvent({ currentSize: this.queueSize, averageSize: this.getAverageQueueSize(), threshold: baseThreshold, waitingTime: 0 });
1629
1727
  }
1630
1728
  return;
1631
1729
  }
1632
- // 进入背压状态
1633
1730
  if (!this.isBackpressure) {
1634
1731
  this.isBackpressure = true;
1635
- this.dispatchBackpressureEvent({
1636
- currentSize,
1637
- averageSize: this.getAverageQueueSize(),
1638
- threshold: baseThreshold,
1639
- waitingTime: 0
1640
- });
1732
+ this.dispatchBackpressureEvent({ currentSize: this.queueSize, averageSize: this.getAverageQueueSize(), threshold: baseThreshold, waitingTime: 0 });
1641
1733
  }
1642
- // 智能等待策略
1643
- const pressure = currentSize / this.options.bufferSize;
1644
- let waitTime;
1645
- if (currentSize >= criticalThreshold) {
1646
- // 临界状态:长时间等待
1647
- waitTime = 50 + Math.min(200, pressure * 100);
1648
- }
1649
- else {
1650
- // 轻度背压:短时间等待
1651
- waitTime = Math.min(20, pressure * 30);
1652
- }
1653
- // 使用指数退避,但最多等待3次
1654
- let retryCount = 0;
1655
- const maxRetries = 3;
1656
- while (this.queueSize >= baseThreshold && retryCount < maxRetries) {
1734
+ // 事件驱动等待:每轮等到 drain 触发或超时,最多 3 轮
1735
+ const maxRounds = 3;
1736
+ for (let i = 0; i < maxRounds; i++) {
1657
1737
  if (this.abortController.signal.aborted)
1658
1738
  break;
1659
- await new Promise(r => setTimeout(r, waitTime));
1660
- retryCount++;
1661
- // 动态调整等待时间
1662
- waitTime = Math.min(waitTime * 1.5, 100);
1739
+ if (this.queueSize < baseThreshold)
1740
+ break;
1741
+ const isCritical = this.queueSize >= criticalThreshold;
1742
+ const waitMs = isCritical ? 100 : 30;
1743
+ await new Promise(resolve => {
1744
+ let done = false;
1745
+ const timer = setTimeout(() => { if (!done) {
1746
+ done = true;
1747
+ resolve();
1748
+ } }, waitMs);
1749
+ this.drainWaiters.push(() => { if (!done) {
1750
+ done = true;
1751
+ clearTimeout(timer);
1752
+ resolve();
1753
+ } });
1754
+ });
1663
1755
  }
1664
- // 如果仍然背压但达到最大重试次数,记录警告但继续执行
1665
1756
  if (this.queueSize >= baseThreshold) {
1666
1757
  const now = Date.now();
1667
- if (now - this.lastBpWarnAt > 1000) { // 节流警告
1758
+ if (now - this.lastBpWarnAt > 1000) {
1668
1759
  this.lastBpWarnAt = now;
1669
1760
  console.warn(`Stream writer: High backpressure detected (${this.queueSize} bytes), continuing anyway`);
1670
1761
  }
@@ -1756,11 +1847,21 @@ class StreamWriter {
1756
1847
  if (!this.abortController.signal.aborted) {
1757
1848
  this.abortController.abort();
1758
1849
  }
1759
- // 立即拒绝所有待处理的写入任务,避免它们继续执行
1850
+ // 执行所有待处理的写入任务:它们会检查 signal.aborted 并立即 resolve,
1851
+ // 不执行的话调用方的 Promise 会永远挂住
1760
1852
  const pendingTasks = this.writeQueue.splice(0);
1761
- pendingTasks.forEach(() => {
1762
- // 这些任务的 Promise 会在执行时因为检查到 aborted 而被拒绝
1763
- });
1853
+ for (const task of pendingTasks) {
1854
+ task().catch(() => { });
1855
+ }
1856
+ // 唤醒所有 drainWaiters(flush / monitorBackpressure 中的等待者),
1857
+ // 让它们检查 signal.aborted 并立即 resolve,不必等到各自的超时
1858
+ const ws = this.drainWaiters.splice(0);
1859
+ for (const fn of ws) {
1860
+ try {
1861
+ fn();
1862
+ }
1863
+ catch { /* ignore */ }
1864
+ }
1764
1865
  try {
1765
1866
  this.p.end();
1766
1867
  }
@@ -1775,22 +1876,41 @@ class StreamWriter {
1775
1876
  // 等待内部队列被下游完全消费(用于在结束前确保尽量发送完数据)
1776
1877
  // 默认超时 10s,避免无限等待
1777
1878
  async flush(timeoutMs = 10000) {
1778
- const start = Date.now();
1779
1879
  // 快速路径
1780
1880
  if (this.queueSize <= 0 && !this.isProcessingQueue && this.writeQueue.length === 0)
1781
1881
  return;
1782
- // 轮询等待队列清空
1783
- while (true) {
1784
- if (this.abortController.signal.aborted)
1785
- return;
1786
- if (this.queueSize <= 0 && !this.isProcessingQueue && this.writeQueue.length === 0)
1787
- return;
1788
- if (Date.now() - start > timeoutMs) {
1789
- console.warn(`Stream writer: flush timeout with ${this.queueSize} bytes still queued`);
1882
+ if (this.abortController.signal.aborted)
1883
+ return;
1884
+ await new Promise((resolve) => {
1885
+ // 已经清空
1886
+ if (this.queueSize <= 0 && !this.isProcessingQueue && this.writeQueue.length === 0) {
1887
+ resolve();
1790
1888
  return;
1791
1889
  }
1792
- await new Promise(r => setTimeout(r, 10));
1793
- }
1890
+ let done = false;
1891
+ const timer = setTimeout(() => {
1892
+ if (!done) {
1893
+ done = true;
1894
+ console.warn(`Stream writer: flush timeout with ${this.queueSize} bytes still queued`);
1895
+ resolve();
1896
+ }
1897
+ }, timeoutMs);
1898
+ // 由 createTransform 在每个 chunk 被下游消耗后唤醒
1899
+ const check = () => {
1900
+ if (this.abortController.signal.aborted || (this.queueSize <= 0 && !this.isProcessingQueue && this.writeQueue.length === 0)) {
1901
+ if (!done) {
1902
+ done = true;
1903
+ clearTimeout(timer);
1904
+ resolve();
1905
+ }
1906
+ }
1907
+ else {
1908
+ // 下次 drain 时再检查
1909
+ this.drainWaiters.push(check);
1910
+ }
1911
+ };
1912
+ this.drainWaiters.push(check);
1913
+ });
1794
1914
  }
1795
1915
  addEventListener(type, callback) {
1796
1916
  const handlers = this.listeners.get(type) || [];
@@ -2049,18 +2169,41 @@ class Libp2pGrpcClient {
2049
2169
  setToken(token) {
2050
2170
  this.token = token;
2051
2171
  }
2172
+ /** 从 peerAddr 提取 HTTP/2 :authority 字段(host:port 格式) */
2173
+ getAuthority() {
2174
+ try {
2175
+ const addr = this.peerAddr.toString();
2176
+ const ip4 = addr.match(/\/ip4\/(\d[\d.]+)\/tcp\/(\d+)/);
2177
+ if (ip4)
2178
+ return `${ip4[1]}:${ip4[2]}`;
2179
+ const ip6 = addr.match(/\/ip6\/([^/]+)\/tcp\/(\d+)/);
2180
+ if (ip6)
2181
+ return `[${ip6[1]}]:${ip6[2]}`;
2182
+ const dns = addr.match(/\/dns(?:4|6)?\/([.\w-]+)\/tcp\/(\d+)/);
2183
+ if (dns)
2184
+ return `${dns[1]}:${dns[2]}`;
2185
+ }
2186
+ catch { /* ignore */ }
2187
+ return 'localhost';
2188
+ }
2052
2189
  async unaryCall(method, requestData, timeout = 30000) {
2053
2190
  let stream = null;
2054
2191
  let responseData = null;
2055
2192
  let responseBuffer = []; // 添加缓冲区来累积数据
2056
2193
  let responseDataExpectedLength = -1; // 当前响应的期望长度
2194
+ /** 跨 DATA 帧的部分 gRPC 消息头缓冲(当一帧的 payload < 5 字节时积累) */
2195
+ let headerPartialBuffer = [];
2057
2196
  const hpack = new HPACK();
2058
2197
  let exitFlag = false;
2059
2198
  let errMsg = "";
2060
2199
  let isResponseComplete = false; // 添加标志来标识响应是否完成
2200
+ /** 事件驱动:响应完成时的唤醒函数 */
2201
+ let notifyResponseComplete = null;
2061
2202
  let connection = null;
2062
2203
  let state = null;
2063
2204
  let streamSlotAcquired = false;
2205
+ // 提升 writer 作用域到 finally 可访问,确保错误路径下也能调用 abort() 清理资源
2206
+ let writerRef = null;
2064
2207
  try {
2065
2208
  // const stream = await this.node.dialProtocol(this.peerAddr, this.protocol)
2066
2209
  connection = await this.acquireConnection(false);
@@ -2084,6 +2227,7 @@ class Libp2pGrpcClient {
2084
2227
  const writer = new StreamWriter(stream, {
2085
2228
  bufferSize: 16 * 1024 * 1024,
2086
2229
  });
2230
+ writerRef = writer;
2087
2231
  try {
2088
2232
  writer.addEventListener("backpressure", (e) => {
2089
2233
  const d = e.detail || {};
@@ -2114,6 +2258,7 @@ class Libp2pGrpcClient {
2114
2258
  }
2115
2259
  exitFlag = true;
2116
2260
  errMsg = `GOAWAY received: code=${info.errorCode}`;
2261
+ notifyResponseComplete?.(); // 唤醒等待中的 Promise
2117
2262
  try {
2118
2263
  connection?.close();
2119
2264
  }
@@ -2132,41 +2277,59 @@ class Libp2pGrpcClient {
2132
2277
  parser.registerOutboundStream(streamId);
2133
2278
  responseDataExpectedLength = -1; // 重置期望长度
2134
2279
  responseBuffer = []; // 重置缓冲区
2280
+ headerPartialBuffer = []; // 重置跨帧头部缓冲
2135
2281
  parser.onData = (payload, frameHeader) => {
2136
2282
  //接收数据
2137
2283
  if (responseDataExpectedLength === -1) {
2138
2284
  //grpc消息头部未读取
2285
+ // 如果有跨帧积累的部分头字节,先与本帧 payload 合并
2286
+ let effectivePayload = payload;
2287
+ if (headerPartialBuffer.length > 0) {
2288
+ headerPartialBuffer.push(payload);
2289
+ const totalLen = headerPartialBuffer.reduce((s, c) => s + c.length, 0);
2290
+ effectivePayload = new Uint8Array(totalLen);
2291
+ let off = 0;
2292
+ for (const c of headerPartialBuffer) {
2293
+ effectivePayload.set(c, off);
2294
+ off += c.length;
2295
+ }
2296
+ headerPartialBuffer = [];
2297
+ }
2139
2298
  //提取gRPC消息头部
2140
- if (payload.length < 5) {
2299
+ if (effectivePayload.length < 5) {
2300
+ // 头部字节不足 5,先缓存,等待后续帧补全
2301
+ headerPartialBuffer.push(effectivePayload);
2141
2302
  return;
2142
2303
  }
2143
- const lengthBytes = payload.slice(1, 5); // 消息长度的4字节
2144
- responseDataExpectedLength = new DataView(lengthBytes.buffer, lengthBytes.byteOffset).getUint32(0, false); // big-endian
2145
- if (responseDataExpectedLength < 0) {
2146
- throw new Error("Invalid gRPC message length");
2147
- }
2148
- if (responseDataExpectedLength + 5 > payload.length) {
2304
+ const lengthBytes = effectivePayload.slice(1, 5); // 消息长度的4字节
2305
+ responseDataExpectedLength = new DataView(lengthBytes.buffer, lengthBytes.byteOffset).getUint32(0, false); // big-endian(getUint32 返回无符号整数,结果不会为负)
2306
+ if (responseDataExpectedLength + 5 > effectivePayload.length) {
2149
2307
  // 如果当前 payload 不足以包含完整的 gRPC 消息,缓存数据
2150
- const grpcData = payload.subarray(5);
2308
+ const grpcData = effectivePayload.subarray(5);
2151
2309
  responseBuffer.push(grpcData);
2152
2310
  responseDataExpectedLength -= grpcData.length; // 更新期望长度
2153
2311
  return;
2154
2312
  }
2155
2313
  else {
2156
- // 如果当前 payload 足以包含完整的 gRPC 消息,重置缓冲区
2157
- const grpcData = payload.subarray(5); // 提取完整的 gRPC 消息
2314
+ // payload 已包含完整的 gRPC 消息体,精确截取(避免尾部多余字节污染)
2315
+ const msgLen = responseDataExpectedLength;
2316
+ const grpcData = effectivePayload.slice(5, 5 + msgLen);
2158
2317
  responseBuffer.push(grpcData);
2159
2318
  responseData = grpcData;
2160
2319
  isResponseComplete = true;
2161
- responseDataExpectedLength = -1; // 重置期望长度
2320
+ responseDataExpectedLength = -1;
2321
+ notifyResponseComplete?.();
2162
2322
  }
2163
2323
  }
2164
2324
  else if (responseDataExpectedLength > 0) {
2165
2325
  //grpc消息头部已读取
2166
- responseBuffer.push(payload); // 将数据添加到缓冲区
2167
- responseDataExpectedLength -= payload.length; // 更新期望长度
2326
+ responseDataExpectedLength -= payload.length;
2168
2327
  if (responseDataExpectedLength <= 0) {
2169
- // 如果缓冲区中的数据已经完全处理,重置缓冲区
2328
+ // 超收时截掉多余字节
2329
+ const exactPayload = responseDataExpectedLength < 0
2330
+ ? payload.slice(0, payload.length + responseDataExpectedLength)
2331
+ : payload;
2332
+ responseBuffer.push(exactPayload);
2170
2333
  responseData = new Uint8Array(responseBuffer.reduce((sum, chunk) => sum + chunk.length, 0));
2171
2334
  let offset = 0;
2172
2335
  for (const chunk of responseBuffer) {
@@ -2174,41 +2337,36 @@ class Libp2pGrpcClient {
2174
2337
  offset += chunk.length;
2175
2338
  }
2176
2339
  responseDataExpectedLength = -1;
2177
- isResponseComplete = true; // 设置响应完成标志
2340
+ isResponseComplete = true;
2341
+ notifyResponseComplete?.();
2178
2342
  }
2179
- }
2180
- // 检查是否是流的最后一个帧(END_STREAM 标志)
2181
- if (frameHeader && frameHeader.flags & 0x1 && !isResponseComplete) {
2182
- // END_STREAM flag
2183
- // 合并所有缓冲的数据
2184
- const totalLength = responseBuffer.reduce((sum, chunk) => sum + chunk.length, 0);
2185
- responseData = new Uint8Array(totalLength);
2186
- let offset = 0;
2187
- for (const chunk of responseBuffer) {
2188
- responseData.set(chunk, offset);
2189
- offset += chunk.length;
2343
+ else {
2344
+ responseBuffer.push(payload); // 还不完整,继续累积
2190
2345
  }
2191
- isResponseComplete = true;
2192
2346
  }
2193
- };
2194
- parser.onEnd = () => {
2195
- //接收结束
2196
- if (!isResponseComplete) {
2197
- isResponseComplete = true; // 设置响应完成标志
2198
- if (responseBuffer.length === 0) {
2199
- responseData = new Uint8Array(); // 如果没有数据,返回空数组
2200
- }
2201
- else {
2202
- // 合并所有缓冲的数据
2203
- const totalLength = responseBuffer.reduce((sum, chunk) => sum + chunk.length, 0);
2347
+ // END_STREAM 兜底:数据路径已处理大多数情况;此分支仅在边缘情况下触发
2348
+ if (frameHeader && frameHeader.flags & 0x1 && !isResponseComplete) {
2349
+ if (responseBuffer.length > 0) {
2350
+ const totalLength = responseBuffer.reduce((sum, c) => sum + c.length, 0);
2204
2351
  responseData = new Uint8Array(totalLength);
2205
2352
  let offset = 0;
2206
2353
  for (const chunk of responseBuffer) {
2207
2354
  responseData.set(chunk, offset);
2208
2355
  offset += chunk.length;
2209
2356
  }
2210
- isResponseComplete = true;
2211
2357
  }
2358
+ else {
2359
+ responseData = new Uint8Array(0);
2360
+ }
2361
+ isResponseComplete = true;
2362
+ notifyResponseComplete?.();
2363
+ }
2364
+ };
2365
+ parser.onEnd = () => {
2366
+ // 流结束时若响应未标记完成(空响应 / 纯 trailers),强制标记并唤醒等待者
2367
+ if (!isResponseComplete) {
2368
+ isResponseComplete = true;
2369
+ notifyResponseComplete?.();
2212
2370
  }
2213
2371
  };
2214
2372
  parser.onSettings = () => {
@@ -2224,14 +2382,21 @@ class Libp2pGrpcClient {
2224
2382
  else if (plainHeaders.get("grpc-status") !== undefined) {
2225
2383
  exitFlag = true;
2226
2384
  errMsg = plainHeaders.get("grpc-message") || "gRPC call failed";
2385
+ notifyResponseComplete?.(); // 唤醒等待中的 Promise
2227
2386
  }
2228
2387
  };
2229
2388
  // 启动后台流处理,捕获任何异步错误
2230
2389
  parser.processStream(stream).catch((error) => {
2231
- console.error('Error in processStream:', error);
2232
- exitFlag = true;
2233
- if (!errMsg) {
2234
- errMsg = error instanceof Error ? error.message : 'Stream processing failed';
2390
+ // 若响应已完整收到(isResponseComplete=true),后置的网络层错误属于正常的
2391
+ // 连接拆除过程(如服务端 RST、连接关闭),不影响已成功的调用结果,静默忽略。
2392
+ // 若响应尚未完成,才记录错误并唤醒等待者,触发超时/错误路径。
2393
+ if (!isResponseComplete) {
2394
+ console.error('Error in processStream:', error);
2395
+ exitFlag = true;
2396
+ if (!errMsg) {
2397
+ errMsg = error instanceof Error ? error.message : 'Stream processing failed';
2398
+ }
2399
+ notifyResponseComplete?.(); // 流处理异常也需唤醒等待者
2235
2400
  }
2236
2401
  });
2237
2402
  // 握手
@@ -2241,14 +2406,16 @@ class Libp2pGrpcClient {
2241
2406
  const settingFrme = Http2Frame.createSettingsFrame();
2242
2407
  await writer.write(settingFrme);
2243
2408
  // 等待对端 SETTINGS 或 ACK,择一即可,避免偶发握手竞态
2409
+ // 注意:未胜出的 promise 内部有超时定时器,它们最终会 reject。
2410
+ // 必须绑定 .catch(…) 消除错误,否则在 Node.js 新版本中会导致 UnhandledPromiseRejection 崩溃。
2244
2411
  await Promise.race([
2245
- parser.waitForPeerSettings(1000),
2246
- parser.waitForSettingsAck(),
2412
+ parser.waitForPeerSettings(1000).catch(() => { }),
2413
+ parser.waitForSettingsAck().catch(() => { }),
2247
2414
  new Promise((res) => setTimeout(res, 300)),
2248
2415
  ]);
2249
2416
  // 即使未等到,也继续;多数实现会随后发送
2250
2417
  // 创建头部帧
2251
- const headerFrame = Http2Frame.createHeadersFrame(streamId, method, true, this.token);
2418
+ const headerFrame = Http2Frame.createHeadersFrame(streamId, method, true, this.token, this.getAuthority());
2252
2419
  await writer.write(headerFrame);
2253
2420
  // 直接按帧大小分片发送(保持与之前一致的稳定路径)
2254
2421
  const dataFrames = Http2Frame.createDataFrames(streamId, requestData, true);
@@ -2256,22 +2423,21 @@ class Libp2pGrpcClient {
2256
2423
  for (const df of dataFrames) {
2257
2424
  await this.sendFrameWithFlowControl(parser, streamId, df, writer, undefined, frameSendTimeout);
2258
2425
  }
2259
- // 等待responseData 不为空,或超时
2426
+ // 等待 responseData 不为空,或超时(事件驱动,不轮询)
2260
2427
  await new Promise((resolve, reject) => {
2428
+ if (isResponseComplete || exitFlag) {
2429
+ resolve();
2430
+ return;
2431
+ }
2261
2432
  const t = setTimeout(() => {
2433
+ notifyResponseComplete = null;
2262
2434
  reject(new Error("gRPC response timeout"));
2263
2435
  }, timeout);
2264
- const checkResponse = () => {
2265
- if (isResponseComplete || exitFlag) {
2266
- // 使用新的完成标志
2267
- clearTimeout(t);
2268
- resolve(responseData);
2269
- }
2270
- else {
2271
- setTimeout(checkResponse, 50);
2272
- }
2436
+ notifyResponseComplete = () => {
2437
+ clearTimeout(t);
2438
+ notifyResponseComplete = null;
2439
+ resolve();
2273
2440
  };
2274
- checkResponse();
2275
2441
  });
2276
2442
  try {
2277
2443
  await writer.flush(timeout);
@@ -2284,8 +2450,18 @@ class Libp2pGrpcClient {
2284
2450
  throw err;
2285
2451
  }
2286
2452
  finally {
2453
+ // 必须先 abort writer(立即强制停止 pushable + stream),再 close stream。
2454
+ // 若顺序颠倒:stream.close() 会等待服务端半关闭确认,网络异常时永久挂住,
2455
+ // 导致 writer.abort() 永远不执行 → watchdog 定时器 / pushable 泄漏。
2456
+ // writer.abort() 内部幂等,成功路径下 writer.end() 已调用 cleanup(),安全。
2457
+ writerRef?.abort('unaryCall cleanup');
2287
2458
  if (stream) {
2288
- await stream.close();
2459
+ try {
2460
+ await stream.close();
2461
+ }
2462
+ catch {
2463
+ // 流已被 abort,close() 会立即抛出,忽略即可。
2464
+ }
2289
2465
  }
2290
2466
  if (streamSlotAcquired && state) {
2291
2467
  state.activeStreams = Math.max(0, state.activeStreams - 1);
@@ -2320,6 +2496,8 @@ class Libp2pGrpcClient {
2320
2496
  const internalController = new AbortController();
2321
2497
  let timeoutHandle;
2322
2498
  let stream = null;
2499
+ // 保存外部 abort 监听器引用,以便操作结束后移除,防止内存泄漏
2500
+ let contextAbortHandler;
2323
2501
  const profile = options?.transportProfile ?? this.getDefaultTransportProfile(mode);
2324
2502
  const useFlowControl = profile === "flow-control";
2325
2503
  // 取消函数 - 将在最后返回给调用者
@@ -2339,17 +2517,16 @@ class Libp2pGrpcClient {
2339
2517
  };
2340
2518
  // 如果提供了外部信号,监听它
2341
2519
  if (context?.signal) {
2342
- // 如果外部信号已经触发中止,立即返回
2520
+ // 如果外部信号已经触发中止,立即返回——避免启动 IIFE 后在 catch 中再次调用 onErrorCallback
2343
2521
  if (context.signal.aborted) {
2344
2522
  if (onErrorCallback) {
2345
2523
  onErrorCallback(new Error("Operation aborted by context"));
2346
2524
  }
2347
- cancelOperation();
2525
+ return cancelOperation;
2348
2526
  }
2349
- // 监听外部的abort事件
2350
- context.signal.addEventListener("abort", () => {
2351
- cancelOperation();
2352
- });
2527
+ // 监听外部的abort事件(保存引用以便后续移除,防止内存泄漏)
2528
+ contextAbortHandler = () => { cancelOperation(); };
2529
+ context.signal.addEventListener("abort", contextAbortHandler);
2353
2530
  }
2354
2531
  // 超时Promise
2355
2532
  const timeoutPromise = new Promise((_, reject) => {
@@ -2360,13 +2537,45 @@ class Libp2pGrpcClient {
2360
2537
  });
2361
2538
  // 主操作Promise
2362
2539
  const operationPromise = (async () => {
2363
- let messageBuffer = new Uint8Array(0); // 用于累积跨帧的消息数据
2540
+ /**
2541
+ * 统一错误报告:确保 onErrorCallback 只被调用一次,
2542
+ * 并同时中止操作,防止后续再触发 onEndCallback。
2543
+ * 适用于 onGoaway / onHeaders / processStream.catch / onData 等各个错误路径。
2544
+ */
2545
+ let errorCallbackFired = false;
2546
+ const reportError = (err) => {
2547
+ if (errorCallbackFired)
2548
+ return;
2549
+ errorCallbackFired = true;
2550
+ internalController.abort();
2551
+ if (onErrorCallback)
2552
+ onErrorCallback(err);
2553
+ };
2554
+ /** 分段列表缓冲,避免每次 payload 到达时 O(n) 全量拷贝 */
2555
+ let msgChunks = [];
2556
+ let msgTotalLen = 0;
2364
2557
  let expectedMessageLength = -1; // 当前消息的期望长度
2558
+ /** 将分段列表合并为单一 Uint8Array(仅在需要时调用) */
2559
+ const flattenMsgBuffer = () => {
2560
+ if (msgChunks.length === 0)
2561
+ return new Uint8Array(0);
2562
+ if (msgChunks.length === 1)
2563
+ return msgChunks[0];
2564
+ const out = new Uint8Array(msgTotalLen);
2565
+ let off = 0;
2566
+ for (const c of msgChunks) {
2567
+ out.set(c, off);
2568
+ off += c.length;
2569
+ }
2570
+ return out;
2571
+ };
2365
2572
  const hpack = new HPACK();
2366
2573
  let connection = null;
2367
2574
  let connectionKey = null;
2368
2575
  let state = null;
2369
2576
  let streamSlotAcquired = false;
2577
+ // 提升 writer 作用域到 finally 可访问,确保 unary/server-streaming 模式下也能清理资源
2578
+ let writer = null;
2370
2579
  try {
2371
2580
  // 检查是否已经中止
2372
2581
  if (internalController.signal.aborted) {
@@ -2404,7 +2613,7 @@ class Libp2pGrpcClient {
2404
2613
  });
2405
2614
  const streamManager = this.getStreamManagerFor(connection);
2406
2615
  const streamId = await streamManager.getNextAppLevelStreamId();
2407
- const writer = new StreamWriter(stream, {
2616
+ writer = new StreamWriter(stream, {
2408
2617
  bufferSize: 16 * 1024 * 1024,
2409
2618
  });
2410
2619
  try {
@@ -2439,10 +2648,8 @@ class Libp2pGrpcClient {
2439
2648
  if (state) {
2440
2649
  this.rejectStreamWaiters(state, new Error("Connection received GOAWAY"));
2441
2650
  }
2442
- if (onErrorCallback) {
2443
- onErrorCallback(new Error(`GOAWAY received: code=${info.errorCode}`));
2444
- }
2445
- internalController.abort();
2651
+ // reportError 统一完成:标记已报错 + abort + 触发回调(幂等,不会重复触发)
2652
+ reportError(new Error(`GOAWAY received: code=${info.errorCode}`));
2446
2653
  try {
2447
2654
  connection?.close();
2448
2655
  }
@@ -2480,52 +2687,43 @@ class Libp2pGrpcClient {
2480
2687
  };
2481
2688
  // 在各个回调中检查是否已中止
2482
2689
  parser.onData = async (payload) => {
2483
- // 检查是否已中止
2484
- if (internalController.signal.aborted) {
2690
+ if (internalController.signal.aborted)
2485
2691
  return;
2486
- }
2487
2692
  try {
2488
- // 将新数据添加到消息缓冲区
2489
- const newBuffer = new Uint8Array(messageBuffer.length + payload.length);
2490
- newBuffer.set(messageBuffer);
2491
- newBuffer.set(payload, messageBuffer.length);
2492
- messageBuffer = newBuffer;
2693
+ // 追加到分段列表,O(1),不拷贝历史数据
2694
+ msgChunks.push(payload);
2695
+ msgTotalLen += payload.length;
2493
2696
  // 处理缓冲区中的完整消息
2494
- while (messageBuffer.length > 0) {
2495
- // 如果已经中止,停止处理
2496
- if (internalController.signal.aborted) {
2697
+ while (msgTotalLen > 0) {
2698
+ if (internalController.signal.aborted)
2497
2699
  return;
2700
+ // 读取 gRPC 消息头(5字节)
2701
+ if (expectedMessageLength === -1 && msgTotalLen >= 5) {
2702
+ const flat = flattenMsgBuffer();
2703
+ msgChunks = [flat];
2704
+ const lengthBytes = flat.slice(1, 5);
2705
+ expectedMessageLength = new DataView(lengthBytes.buffer, lengthBytes.byteOffset).getUint32(0, false);
2498
2706
  }
2499
- // 如果还没有读取消息长度,且缓冲区有足够数据
2500
- if (expectedMessageLength === -1 && messageBuffer.length >= 5) {
2501
- // 读取 gRPC 消息头:1字节压缩标志 + 4字节长度
2502
- const lengthBytes = messageBuffer.slice(1, 5);
2503
- expectedMessageLength = new DataView(lengthBytes.buffer, lengthBytes.byteOffset).getUint32(0, false); // big-endian
2504
- }
2505
- // 如果知道期望长度且有足够数据
2506
- if (expectedMessageLength !== -1 &&
2507
- messageBuffer.length >= expectedMessageLength + 5) {
2508
- // 提取完整消息(跳过5字节头部)
2509
- const completeMessage = messageBuffer.slice(5, expectedMessageLength + 5);
2510
- // 调用回调处理这个完整消息
2707
+ // 有完整消息
2708
+ if (expectedMessageLength !== -1 && msgTotalLen >= expectedMessageLength + 5) {
2709
+ const flat = flattenMsgBuffer();
2710
+ msgChunks = [flat];
2711
+ const completeMessage = flat.slice(5, expectedMessageLength + 5);
2511
2712
  onDataCallback(completeMessage);
2512
- // 移除已处理的消息,保留剩余数据
2513
- messageBuffer = messageBuffer.slice(expectedMessageLength + 5);
2713
+ // 移除已处理消息,保留剩余
2714
+ const remaining = flat.slice(expectedMessageLength + 5);
2715
+ msgChunks = remaining.length > 0 ? [remaining] : [];
2716
+ msgTotalLen = remaining.length;
2514
2717
  expectedMessageLength = -1;
2515
2718
  }
2516
2719
  else {
2517
- // 没有足够数据构成完整消息,等待更多数据
2518
2720
  break;
2519
2721
  }
2520
2722
  }
2521
2723
  }
2522
2724
  catch (error) {
2523
- if (onErrorCallback) {
2524
- onErrorCallback(error);
2525
- }
2526
- else {
2527
- throw error;
2528
- }
2725
+ // reportError 统一报错并中止,防止 onEndCallback 在数据处理异常后仍被调用
2726
+ reportError(error);
2529
2727
  }
2530
2728
  };
2531
2729
  parser.onSettings = () => {
@@ -2545,20 +2743,16 @@ class Libp2pGrpcClient {
2545
2743
  }
2546
2744
  else if (plainHeaders.get("grpc-status") !== undefined) {
2547
2745
  const errMsg = plainHeaders.get("grpc-message") || "gRPC call failed";
2548
- const err = new Error(errMsg);
2549
- if (onErrorCallback) {
2550
- onErrorCallback(err);
2551
- }
2552
- else {
2553
- throw err;
2554
- }
2746
+ // reportError 统一完成:标记已报错 + abort + 触发回调(幂等,不会重复触发)
2747
+ reportError(new Error(errMsg));
2555
2748
  }
2556
2749
  };
2557
2750
  // 启动后台流处理
2558
2751
  parser.processStream(stream).catch((error) => {
2559
- console.error('Error in processStream:', error);
2560
- if (onErrorCallback) {
2561
- onErrorCallback(error);
2752
+ // abort() 触发的清理错误属于预期行为,不打印错误日志,不重复触发回调
2753
+ if (!internalController.signal.aborted) {
2754
+ console.error('Error in processStream:', error);
2755
+ reportError(error);
2562
2756
  }
2563
2757
  });
2564
2758
  // 检查是否已中止
@@ -2580,10 +2774,12 @@ class Libp2pGrpcClient {
2580
2774
  throw new Error("Operation aborted");
2581
2775
  }
2582
2776
  // 等待对端 SETTINGS 或 ACK,择一即可,避免偶发握手竞态
2777
+ // 注意:未胜出的 promise 内部有超时定时器,它们最终会 reject。
2778
+ // 必须绑定 .catch(…) 消除错误,否则在 Node.js 新版本中会导致 UnhandledPromiseRejection 崩溃。
2583
2779
  {
2584
2780
  await Promise.race([
2585
- parser.waitForPeerSettings(1000),
2586
- parser.waitForSettingsAck(),
2781
+ parser.waitForPeerSettings(1000).catch(() => { }),
2782
+ parser.waitForSettingsAck().catch(() => { }),
2587
2783
  new Promise((res) => setTimeout(res, 300)),
2588
2784
  ]);
2589
2785
  // 即使未等到,也继续;多数实现会随后发送
@@ -2592,12 +2788,8 @@ class Libp2pGrpcClient {
2592
2788
  if (internalController.signal.aborted) {
2593
2789
  throw new Error("Operation aborted");
2594
2790
  }
2595
- // 检查是否已中止
2596
- if (internalController.signal.aborted) {
2597
- throw new Error("Operation aborted");
2598
- }
2599
2791
  // Create header frame
2600
- const headerFrame = Http2Frame.createHeadersFrame(streamId, method, true, this.token);
2792
+ const headerFrame = Http2Frame.createHeadersFrame(streamId, method, true, this.token, this.getAuthority());
2601
2793
  if (mode === "unary" || mode === "server-streaming") {
2602
2794
  await writer.write(headerFrame);
2603
2795
  const dfs = Http2Frame.createDataFrames(streamId, requestData, true);
@@ -2622,7 +2814,18 @@ class Libp2pGrpcClient {
2622
2814
  const batchSize = options?.batchSize || 10;
2623
2815
  // 动态批处理器
2624
2816
  const processingQueue = [];
2817
+ /** 事件驱动:批处理完成后唤醒 waitForQueue 等待者 */
2818
+ const batchDoneWaiters = [];
2625
2819
  let isProcessing = false;
2820
+ const _notifyBatchDone = () => {
2821
+ const ws = batchDoneWaiters.splice(0);
2822
+ for (const fn of ws) {
2823
+ try {
2824
+ fn();
2825
+ }
2826
+ catch { /* ignore */ }
2827
+ }
2828
+ };
2626
2829
  const processNextBatch = async () => {
2627
2830
  if (isProcessing || processingQueue.length === 0)
2628
2831
  return;
@@ -2666,10 +2869,13 @@ class Libp2pGrpcClient {
2666
2869
  finally {
2667
2870
  isProcessing = false;
2668
2871
  // 如果队列中还有数据,继续处理
2669
- if (processingQueue.length > 0 &&
2670
- !internalController.signal.aborted) {
2671
- // 使用 setTimeout 避免阻塞,让新数据有机会加入队列
2672
- setTimeout(() => processNextBatch(), 0);
2872
+ if (processingQueue.length > 0 && !internalController.signal.aborted) {
2873
+ // 直接递归调用(已是 async,自动让出事件循环)
2874
+ processNextBatch().catch((err) => { console.error("Error in processNextBatch:", err); });
2875
+ }
2876
+ else {
2877
+ // 队列清空,唤醒等待者
2878
+ _notifyBatchDone();
2673
2879
  }
2674
2880
  }
2675
2881
  };
@@ -2719,34 +2925,30 @@ class Libp2pGrpcClient {
2719
2925
  });
2720
2926
  throw error;
2721
2927
  }
2722
- // 等待所有剩余的数据处理完成,添加超时保护
2723
- const queueWaitStart = Date.now();
2724
- const maxQueueWaitMs = timeout; // 使用主超时时间
2725
- while (processingQueue.length > 0 || isProcessing) {
2726
- if (internalController.signal.aborted) {
2727
- throw new Error("Operation aborted");
2728
- }
2729
- // 防止无限等待
2730
- if (Date.now() - queueWaitStart > maxQueueWaitMs) {
2731
- // 清理剩余队列
2732
- const remainingQueue = processingQueue.splice(0);
2733
- remainingQueue.forEach((item) => {
2734
- try {
2735
- item.reject(new Error("Queue wait timeout"));
2736
- }
2737
- catch (err) {
2738
- console.warn("Error rejecting timeout promise:", err);
2739
- }
2740
- });
2741
- throw new Error("Queue processing timeout");
2742
- }
2743
- await new Promise((resolve) => setTimeout(resolve, 10));
2744
- }
2928
+ // 等待所有剩余的数据处理完成(事件驱动,无 10ms 轮询)
2929
+ await new Promise((resolve, reject) => {
2930
+ const check = () => {
2931
+ if (internalController.signal.aborted) {
2932
+ reject(new Error("Operation aborted"));
2933
+ return;
2934
+ }
2935
+ if (processingQueue.length === 0 && !isProcessing) {
2936
+ resolve();
2937
+ return;
2938
+ }
2939
+ // processNextBatch 结束时会通知这里
2940
+ batchDoneWaiters.push(check);
2941
+ };
2942
+ check();
2943
+ });
2745
2944
  // 检查是否已中止
2746
2945
  if (internalController.signal.aborted) {
2747
2946
  throw new Error("Operation aborted");
2748
2947
  }
2749
- const finalFrame = Http2Frame.createDataFrame(streamId, new Uint8Array(), true);
2948
+ // 发送纯 HTTP/2 END_STREAM 信号帧(0 字节 payload),而非带 gRPC 消息头的空消息。
2949
+ // createDataFrame 会额外附加 5 字节 gRPC 消息头 [0,0,0,0,0],服务端会将其解析
2950
+ // 为一个长度=0 的额外 gRPC 消息,而不仅仅是流结束信号,可能导致协议混淆。
2951
+ const finalFrame = Http2Frame.createFrame(0x0, 0x01, streamId, new Uint8Array(0));
2750
2952
  await writeFrame(finalFrame);
2751
2953
  // 在结束前尽量冲刷内部队列,避免服务器看到部分数据 + context canceled
2752
2954
  try {
@@ -2759,9 +2961,24 @@ class Libp2pGrpcClient {
2759
2961
  if (internalController.signal.aborted) {
2760
2962
  throw new Error("Operation aborted");
2761
2963
  }
2762
- await parser.waitForEndOfStream(0);
2763
- if (onEndCallback) {
2764
- onEndCallback();
2964
+ // 仅在未中止时等待并回调:
2965
+ // 1. 若已中止(如 onHeaders gRPC 错误),跳过 waitForEndOfStream(0) 避免永久阻塞
2966
+ // (waitForEndOfStream(0) 无超时,需等到 processStream 自然结束,
2967
+ // 而 processStream 结束依赖 stream.close(),但 stream.close() 在 finally 中——形成死锁)
2968
+ // 2. 避免在 onErrorCallback 之后再调用 onEndCallback
2969
+ if (!internalController.signal.aborted) {
2970
+ await parser.waitForEndOfStream(0);
2971
+ // Yield one microtask tick so that processStream.catch (which calls
2972
+ // reportError + internalController.abort()) has a chance to run before
2973
+ // we check abort status. Without this yield, if the stream died
2974
+ // unexpectedly (network error), onEndCallback and onErrorCallback
2975
+ // could both fire because _notifyEndOfStream() is called in
2976
+ // processStream's catch block before the re-throw schedules the
2977
+ // .catch handler as a microtask.
2978
+ await Promise.resolve();
2979
+ if (!internalController.signal.aborted && onEndCallback) {
2980
+ onEndCallback();
2981
+ }
2765
2982
  }
2766
2983
  }
2767
2984
  catch (err) {
@@ -2769,14 +2986,16 @@ class Libp2pGrpcClient {
2769
2986
  if (internalController.signal.aborted &&
2770
2987
  err instanceof Error &&
2771
2988
  err.message === "Operation aborted") {
2772
- if (onErrorCallback) {
2989
+ // onHeaders / onGoaway / processStream 错误已通过 reportError 处理,
2990
+ // 此处仅在回调尚未触发时才报告(外部取消/超时场景)
2991
+ if (!errorCallbackFired && onErrorCallback) {
2773
2992
  onErrorCallback(new Error("Operation cancelled by user"));
2774
2993
  }
2775
2994
  }
2776
- else if (onErrorCallback) {
2995
+ else if (!errorCallbackFired && onErrorCallback) {
2777
2996
  onErrorCallback(err);
2778
2997
  }
2779
- else {
2998
+ else if (!errorCallbackFired) {
2780
2999
  if (err instanceof Error) {
2781
3000
  console.error("asyncCall error:", err.message);
2782
3001
  }
@@ -2787,12 +3006,25 @@ class Libp2pGrpcClient {
2787
3006
  }
2788
3007
  finally {
2789
3008
  clearTimeout(timeoutHandle);
3009
+ // 移除外部 abort 监听器,防止 AbortController 复用时触发迟到的 cancelOperation()
3010
+ if (contextAbortHandler && context?.signal) {
3011
+ context.signal.removeEventListener("abort", contextAbortHandler);
3012
+ }
3013
+ // 首先标记操作已结束(正常或异常),确保 processStream.catch 不会把
3014
+ // writer.abort() 产生的 'Call cleanup' 错误误判为真实错误并触发 onErrorCallback。
3015
+ // internalController.abort() 是幂等的,重复调用安全。
3016
+ internalController.abort();
3017
+ // 必须先 abort writer(立即强制停止 pushable + stream),再 close stream。
3018
+ // 若顺序颠倒:stream.close() 等待服务端半关闭确认,网络异常时永久挂住,
3019
+ // writer.abort() 永远不执行 → watchdog / pushable 泄漏。
3020
+ // abort() 内部幂等,重复调用安全。
3021
+ writer?.abort('Call cleanup');
2790
3022
  if (stream) {
2791
3023
  try {
2792
3024
  await stream.close();
2793
3025
  }
2794
- catch (err) {
2795
- console.error("Error closing stream:", err);
3026
+ catch {
3027
+ // 流已被 abort,close() 会立即抛出,忽略即可。
2796
3028
  }
2797
3029
  }
2798
3030
  // 如果本次强制使用了新连接,结束时尽量关闭它,避免连接泄漏