iosignal 7.0.0 → 7.0.2

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.
@@ -17,7 +17,7 @@ var fs = require('fs');
17
17
  var process$1 = require('process');
18
18
  var path = require('path');
19
19
 
20
- var version$1 = "7.0.0";
20
+ var version$1 = "7.0.2";
21
21
  var pkg = {
22
22
  version: version$1};
23
23
 
@@ -966,7 +966,7 @@ class IOCore extends EventEmitter {
966
966
 
967
967
 
968
968
  /**
969
- * Performs common cleanup for the connection. It clears pending promises,
969
+ * Performs common cleanup for the connection. It rejects pending RPCs,
970
970
  * resets the socket reference, and sets the state to closed.
971
971
  * This method is guarded to only run once.
972
972
  * If autoReconnect is false, it also clears the keep-alive timer.
@@ -1001,6 +1001,12 @@ class IOCore extends EventEmitter {
1001
1001
  }
1002
1002
  this.socket = null;
1003
1003
  }
1004
+ const error = new Error('Connection closed');
1005
+ error.code = 'CONNECTION_CLOSED';
1006
+ for (const [, reject, timeoutId] of this.promiseMap.values()) {
1007
+ clearTimeout(timeoutId);
1008
+ reject(error);
1009
+ }
1004
1010
  this.promiseMap.clear();
1005
1011
  this.cid = '';
1006
1012
  if (this.boho) this.boho.isAuthorized = false;
@@ -1694,11 +1700,12 @@ class IOCore extends EventEmitter {
1694
1700
  call(target, topic, ...args) {
1695
1701
  if (!target || !topic)
1696
1702
  return Promise.reject(new Error('request need target and topic)'))
1703
+ this.mid = (this.mid + 1) & 0xffff;
1697
1704
  let sigPack;
1698
1705
  if (args.length > 0) {
1699
1706
  sigPack = $$1.pack(
1700
1707
  $$1.MB('#MsgType', '8', IOMsg.CALL),
1701
- $$1.MB('mid', '16', ++this.mid),
1708
+ $$1.MB('mid', '16', this.mid),
1702
1709
  $$1.MB('target', target),
1703
1710
  $$1.MB('topic', topic),
1704
1711
  $$1.MBA(...args)
@@ -1706,7 +1713,7 @@ class IOCore extends EventEmitter {
1706
1713
  } else {
1707
1714
  sigPack = $$1.pack(
1708
1715
  $$1.MB('#MsgType', '8', IOMsg.CALL),
1709
- $$1.MB('mid', '16', ++this.mid),
1716
+ $$1.MB('mid', '16', this.mid),
1710
1717
  $$1.MB('target', target),
1711
1718
  $$1.MB('topic', topic)
1712
1719
  );
@@ -2058,54 +2065,45 @@ class CongRx extends require$$0.Transform {
2058
2065
 
2059
2066
 
2060
2067
  parse() {
2061
- let head = this.buffer[0];
2062
- let headerLen;
2063
- let payloadSize;
2064
-
2065
- if (head == CongType.TYPE_LEN1) {
2066
- headerLen = 2;
2067
- if (this.buffer.byteLength < headerLen) return;
2068
- payloadSize = this.buffer.readUint8(1);
2069
-
2070
- } else if (head == CongType.TYPE_LEN2) {
2071
- headerLen = 3;
2072
- if (this.buffer.byteLength < headerLen) return;
2073
- payloadSize = this.buffer.readUint16LE(1);
2074
-
2075
- } else if (head == CongType.TYPE_LEN3) {
2076
- headerLen = 4;
2077
- if (this.buffer.byteLength < headerLen) return;
2078
- payloadSize = this.buffer.readUint16LE(1) + this.buffer.readUint8(3) * 65536;
2079
-
2080
- } else if (head == CongType.TYPE_LEN4) {
2081
- headerLen = 5;
2082
- if (this.buffer.byteLength < headerLen) return;
2083
- payloadSize = this.buffer.readUint32LE(1);
2084
-
2085
- } else {
2086
- this.emit('wrong', this.buffer);
2087
- this.buffer = Buffer.alloc(0);
2088
- }
2068
+ while (this.buffer.byteLength > 0) {
2069
+ const head = this.buffer[0];
2070
+ let headerLen;
2071
+ let payloadSize;
2072
+
2073
+ if (head === CongType.TYPE_LEN1) {
2074
+ headerLen = 2;
2075
+ if (this.buffer.byteLength < headerLen) return;
2076
+ payloadSize = this.buffer.readUint8(1);
2077
+ } else if (head === CongType.TYPE_LEN2) {
2078
+ headerLen = 3;
2079
+ if (this.buffer.byteLength < headerLen) return;
2080
+ payloadSize = this.buffer.readUint16LE(1);
2081
+ } else if (head === CongType.TYPE_LEN3) {
2082
+ headerLen = 4;
2083
+ if (this.buffer.byteLength < headerLen) return;
2084
+ payloadSize = this.buffer.readUint16LE(1) + this.buffer.readUint8(3) * 65536;
2085
+ } else if (head === CongType.TYPE_LEN4) {
2086
+ headerLen = 5;
2087
+ if (this.buffer.byteLength < headerLen) return;
2088
+ payloadSize = this.buffer.readUint32LE(1);
2089
+ } else {
2090
+ this.emit('wrong', this.buffer);
2091
+ this.buffer = Buffer.alloc(0);
2092
+ return;
2093
+ }
2089
2094
 
2095
+ const frameSize = headerLen + payloadSize;
2096
+ if (this.buffer.byteLength < frameSize) return;
2090
2097
 
2091
- if (payloadSize == this.buffer.byteLength - headerLen) {
2092
- this.frames.push(this.buffer.subarray(headerLen));
2093
- this.buffer = Buffer.alloc(0);
2094
- return
2095
- } else if (payloadSize < this.buffer.byteLength - headerLen) {
2096
- this.frames.push(this.buffer.subarray(headerLen, headerLen + payloadSize));
2097
- this.buffer = this.buffer.subarray(headerLen + payloadSize);
2098
- this.parse();
2099
- } else {
2100
- // not ready
2101
- // console.log('+')
2102
- return
2098
+ this.frames.push(this.buffer.subarray(headerLen, frameSize));
2099
+ if (this.buffer.byteLength === frameSize) {
2100
+ this.buffer = Buffer.alloc(0);
2101
+ return;
2102
+ }
2103
+ // Consume each complete frame without growing the call stack.
2104
+ this.buffer = this.buffer.subarray(frameSize);
2103
2105
  }
2104
-
2105
-
2106
2106
  }
2107
-
2108
-
2109
2107
  }
2110
2108
 
2111
2109
  class IOCongSocket extends IOCore {
@@ -7333,6 +7331,7 @@ let serverOption = {
7333
7331
  httpServer: null,
7334
7332
  wsPath: null,
7335
7333
  timeout: 50000,
7334
+ pingTimeoutGrace: 5000,
7336
7335
  showMessage: 'none',
7337
7336
  showMetric: 0,
7338
7337
  showChannel: 0,
@@ -7484,6 +7483,7 @@ class RemoteCore {
7484
7483
  rxQuotaChecker(message) {
7485
7484
  let rxBytes = message.byteLength;
7486
7485
  this.manager.rxBytes += rxBytes;
7486
+ if (this.manager.telemetry) { this.manager.telemetry.rxBytes += rxBytes; this.manager.telemetry.rxMessages++; }
7487
7487
 
7488
7488
  if (serverOption.useQuota.signalSize && (rxBytes > this.quota.signalSize)) {
7489
7489
  console.log('## quota: size over');
@@ -7955,6 +7955,10 @@ const decoder$2 = new TextDecoder();
7955
7955
  class Remote extends RemoteCore {
7956
7956
  constructor(socket, req, manager) {
7957
7957
  super(socket, manager);
7958
+ this.txQueuePeakBytes = 0;
7959
+ this.txWriteFalseCount = 0;
7960
+ this.txBlockedSince = null;
7961
+ this.txDrainMaxMs = 0;
7958
7962
  this.socketType = socket.socketType;
7959
7963
 
7960
7964
  if (this.socketType === 'websocket') {
@@ -7991,6 +7995,11 @@ class Remote extends RemoteCore {
7991
7995
  this.manager.removeRemote(this);
7992
7996
  };
7993
7997
  } else { // TCP else
7998
+ socket.on('drain', () => {
7999
+ if (this.txBlockedSince === null) return;
8000
+ this.txDrainMaxMs = Math.max(this.txDrainMaxMs, node_perf_hooks.performance.now() - this.txBlockedSince);
8001
+ this.txBlockedSince = null;
8002
+ });
7994
8003
  this.congRx = new CongRx();
7995
8004
  socket.on('data', data => { this.congRx.write(data); });
7996
8005
 
@@ -8059,6 +8068,7 @@ class Remote extends RemoteCore {
8059
8068
  // any type of received messages: message, ping, pong
8060
8069
  receiveMonitor() {
8061
8070
  this.socket.rxCounter++;
8071
+ if (this.socket.isAlive === false) this.manager.heartbeatPending.delete(this);
8062
8072
  this.socket.isAlive = true;
8063
8073
  }
8064
8074
 
@@ -8122,10 +8132,16 @@ class Remote extends RemoteCore {
8122
8132
  }
8123
8133
  }
8124
8134
 
8135
+ recordTxQueue() {
8136
+ const queued = this.socket.bufferedAmount ?? this.socket.writableLength ?? 0;
8137
+ if (queued > this.txQueuePeakBytes) this.txQueuePeakBytes = queued;
8138
+ }
8139
+
8125
8140
  // node.js server side remote.
8126
8141
  send(message, isBinary) {
8127
8142
  // console.log(`<-S [${IOMsg[ message[0]]}]`)
8128
8143
  this.manager.txBytes += message.byteLength;
8144
+ if (this.manager.telemetry) { this.manager.telemetry.txBytes += message.byteLength; this.manager.telemetry.txMessages++; }
8129
8145
  this.socket.txCounter++;
8130
8146
  if (this.socketType === 'websocket') {
8131
8147
  if (this.socket.readyState === 1) {
@@ -8134,6 +8150,7 @@ class Remote extends RemoteCore {
8134
8150
  } else {
8135
8151
  this.socket.send(message);
8136
8152
  }
8153
+ this.recordTxQueue();
8137
8154
  } else {
8138
8155
  console.log('server(ws)Remote.send() called. not open state. current readyState:', this.socket.readyState );
8139
8156
  this.close(true);
@@ -8141,7 +8158,12 @@ class Remote extends RemoteCore {
8141
8158
 
8142
8159
  } else { //CongSocket
8143
8160
  if (this.socket.readyState == 'open') {
8144
- this.socket.write(pack(message));
8161
+ const writable = this.socket.write(pack(message));
8162
+ this.recordTxQueue();
8163
+ if (!writable) {
8164
+ this.txWriteFalseCount++;
8165
+ if (this.txBlockedSince === null) this.txBlockedSince = node_perf_hooks.performance.now();
8166
+ }
8145
8167
  } else {
8146
8168
  console.log('server(cong)Remote.send() called. not open state. current readyState:', this.socket.readyState );
8147
8169
  this.close(true);
@@ -8345,6 +8367,12 @@ class Manager {
8345
8367
 
8346
8368
  constructor(server, authManager) {
8347
8369
  this.server = server;
8370
+ this.pingPeriod = serverOption.timeout;
8371
+ this.pingGrace = serverOption.pingTimeoutGrace;
8372
+ if (!Number.isFinite(this.pingPeriod) || this.pingPeriod <= 0 ||
8373
+ !Number.isFinite(this.pingGrace) || this.pingGrace < 0) {
8374
+ throw new RangeError('Invalid heartbeat period or grace');
8375
+ }
8348
8376
  this.txBytes = 0;
8349
8377
  this.rxBytes = 0;
8350
8378
 
@@ -8371,25 +8399,20 @@ class Manager {
8371
8399
  this.metrics = new Metrics(this);
8372
8400
  this.lastSSID = 0;
8373
8401
 
8374
- this.pingIntervalID = setInterval(e => {
8375
- this.remotes.forEach(function each(remo) {
8376
- let socket = remo.socket;
8377
- if (socket.isAlive === false) {
8378
- console.log('## timeout. cid:', remo.cid);
8379
- remo.close();
8380
- return;
8381
- }
8382
-
8383
- socket.txCounter++;
8384
- socket.isAlive = false;
8385
- if (remo.socketType === 'websocket') {
8386
- socket.ping();
8387
- } else {
8388
- remo.ping();
8389
- }
8390
-
8391
- });
8392
- }, serverOption.timeout);
8402
+ const groups = Math.min(50, Math.max(1, Math.floor(this.pingPeriod / 1000)));
8403
+ this.pingGroups = Array.from({ length: groups }, () => new Set());
8404
+ this.nextPingGroup = 0;
8405
+ this.pingGroupCursor = 0;
8406
+ // Same timeout for all entries: insertion order is also deadline order.
8407
+ this.heartbeatPending = new Map();
8408
+ this.pingTickMs = this.pingPeriod / groups;
8409
+ this.heartbeatStopped = false;
8410
+ const tick = () => {
8411
+ if (this.heartbeatStopped) return;
8412
+ this.heartbeatTick();
8413
+ if (!this.heartbeatStopped) this.pingIntervalID = setTimeout(tick, this.pingTickMs);
8414
+ };
8415
+ this.pingIntervalID = setTimeout(tick, this.pingTickMs);
8393
8416
 
8394
8417
  if (serverOption.showMetric) {
8395
8418
  this.monitIntervalID = setInterval((e) => {
@@ -8401,10 +8424,37 @@ class Manager {
8401
8424
  }
8402
8425
 
8403
8426
 
8427
+ heartbeatTick() {
8428
+ const now = node_perf_hooks.performance.now();
8429
+ // Process only expired requests, not every connected peer.
8430
+ for (const [remote, deadline] of this.heartbeatPending) {
8431
+ if (deadline > now) break;
8432
+ this.heartbeatPending.delete(remote);
8433
+ if (!remote._closing && remote.socket.isAlive === false) remote.close(true);
8434
+ }
8435
+ // The single timer schedules its next tick after this work; missed groups are not replayed.
8436
+ const group = this.pingGroups[this.pingGroupCursor];
8437
+ this.pingGroupCursor = (this.pingGroupCursor + 1) % this.pingGroups.length;
8438
+ for (const remote of group) {
8439
+ if (remote._closing || this.heartbeatPending.has(remote)) continue;
8440
+ remote.socket.isAlive = false;
8441
+ this.heartbeatPending.set(remote, node_perf_hooks.performance.now() + this.pingPeriod + this.pingGrace);
8442
+ try {
8443
+ remote.ping();
8444
+ } catch {
8445
+ this.heartbeatPending.delete(remote);
8446
+ remote.close(true);
8447
+ }
8448
+ }
8449
+ }
8450
+
8404
8451
  addRemote(socket, req) {
8405
8452
  socket.isAlive = true;
8406
8453
  let remote = new Remote(socket, req, this);
8407
8454
  this.remotes.add(remote);
8455
+ remote.pingGroup = this.nextPingGroup;
8456
+ this.pingGroups[remote.pingGroup].add(remote);
8457
+ this.nextPingGroup = (this.nextPingGroup + 1) % this.pingGroups.length;
8408
8458
  remote.send(remote.issueAuthChallenge());
8409
8459
  remote.send( Buffer.from([ IOMsg.SERVER_READY]) );
8410
8460
  remote.setState(STATE.SERVER_READY);
@@ -8418,6 +8468,8 @@ class Manager {
8418
8468
  removeRemote(remote) {
8419
8469
 
8420
8470
  remote._closing = true;
8471
+ this.pingGroups[remote.pingGroup]?.delete(remote);
8472
+ this.heartbeatPending.delete(remote);
8421
8473
  remote.setState(STATE.CLOSED);
8422
8474
 
8423
8475
  let remoteInfo = `- IP:${remote.ip} #${remote.ssid} cid:${remote.cid} ${remote?.socket.socketType === 'websocket' ? "WS" : "CS"} `;
@@ -8596,6 +8648,7 @@ class Manager {
8596
8648
 
8597
8649
  }
8598
8650
 
8651
+ if (this.telemetry) this.telemetry.publishes++;
8599
8652
  let sentCounter = 0;
8600
8653
  if (this.channel_map.has(tag)) {
8601
8654
  // console.log('raw channel_map matched tag:', tag)
@@ -8607,6 +8660,7 @@ class Manager {
8607
8660
  } else {
8608
8661
  limit = remotes.size;
8609
8662
  }
8663
+ if (this.telemetry) this.telemetry.quotaExcluded += remotes.size - limit;
8610
8664
  let peers = remotes.values();
8611
8665
  while (sentCounter < limit) {
8612
8666
  let c = peers.next().value;
@@ -8626,6 +8680,7 @@ class Manager {
8626
8680
  // } else {
8627
8681
  // // console.log(`pub >> [${tag}] sent: ${sentCounter} [no quota limit] total: ${remotes.size} subscribers. ` )
8628
8682
  // }
8683
+ if (this.telemetry) this.telemetry.deliveryAttempts += sentCounter;
8629
8684
  return ['ok', sentCounter]
8630
8685
  }
8631
8686
  }
@@ -8759,7 +8814,10 @@ class Manager {
8759
8814
 
8760
8815
  close() {
8761
8816
  this.metrics.close();
8762
- clearInterval(this.pingIntervalID);
8817
+ this.heartbeatStopped = true;
8818
+ clearTimeout(this.pingIntervalID);
8819
+ this.heartbeatPending.clear();
8820
+ for (const group of this.pingGroups) group.clear();
8763
8821
  if (this.monitIntervalID) {
8764
8822
  clearInterval(this.monitIntervalID);
8765
8823
  }
@@ -8799,6 +8857,13 @@ class Server extends require$$0$3 {
8799
8857
  this.port = null;
8800
8858
  this.congPort = null;
8801
8859
 
8860
+ if (options.pingTimeoutGrace !== undefined) {
8861
+ if (!Number.isFinite(options.pingTimeoutGrace) || options.pingTimeoutGrace < 0) {
8862
+ throw new RangeError('pingTimeoutGrace must be a finite non-negative number');
8863
+ }
8864
+ serverOption.pingTimeoutGrace = options.pingTimeoutGrace;
8865
+ }
8866
+
8802
8867
  if (options.timeout) {
8803
8868
  let pingT = parseInt(options.timeout);
8804
8869
  if (pingT && pingT >= 1000) serverOption.timeout = pingT;
@@ -8932,44 +8997,36 @@ class Server extends require$$0$3 {
8932
8997
  throw new Error(`Service ${service} : no commands or !Array.`)
8933
8998
  }
8934
8999
 
8935
- // Service TYPE 1. single call() function.
8936
- if ( service_module.call && typeof service_module.call == 'function' ) {
8937
- this.on(service, (remote, req) => {
8938
- try {
8939
- if (!service_module.checkPermission(remote, req)) {
8940
- remote.response(req.mid, STATUS.ERROR, "NO_PERMISSION.");
8941
- return
8942
- }
8943
- if( service_module.commands.includes( req.topic )){
8944
- // console.log('server service_module req', req )
8945
- service_module.call(remote, req);
8946
- }else {
8947
- remote.response(req.mid, STATUS.ERROR, "UNKNOWN_COMMAND");
8948
- }
8949
- } catch (error) {
8950
- console.error(`Unhandled Service Error in service [${service}]:`, error);
8951
- remote.response(req.mid, STATUS.ERROR, "INTERNAL_SERVER_ERROR");
9000
+ const handleError = (remote, req, error) => {
9001
+ console.error(`Unhandled Service Error in service [${service}]:`, error);
9002
+ if (remote._closing) return;
9003
+ // A disconnected transport can also fail while reporting the service error.
9004
+ try {
9005
+ remote.response(req.mid, STATUS.ERROR, "INTERNAL_SERVER_ERROR");
9006
+ } catch (responseError) {
9007
+ console.error(`Service error response failed [${service}]:`, responseError);
9008
+ }
9009
+ };
9010
+ const useCall = typeof service_module.call === 'function';
9011
+ this.on(service, (remote, req) => {
9012
+ try {
9013
+ if (!service_module.checkPermission(remote, req)) {
9014
+ remote.response(req.mid, STATUS.ERROR, "NO_PERMISSION.");
9015
+ return;
8952
9016
  }
8953
- });
8954
- } else {
8955
- // Service TYPE 2. multiple functions.
8956
- this.on(service, (remote, req) => {
8957
- try {
8958
- if (!service_module.checkPermission(remote, req)) {
8959
- remote.response(req.mid, STATUS.ERROR, "NO_PERMISSION.");
8960
- return
8961
- }
8962
- if( service_module.commands.includes( req.topic )){
8963
- service_module[req.topic](remote, req);
8964
- }else {
8965
- remote.response(req.mid, STATUS.ERROR, "UNKNOWN_COMMAND");
8966
- }
8967
- } catch (error) {
8968
- console.error(`Unhandled Service Error in service [${service}]:`, error);
8969
- remote.response(req.mid, STATUS.ERROR, "INTERNAL_SERVER_ERROR");
9017
+ if (!service_module.commands.includes(req.topic)) {
9018
+ remote.response(req.mid, STATUS.ERROR, "UNKNOWN_COMMAND");
9019
+ return;
8970
9020
  }
8971
- });
8972
- }
9021
+ // Keep synchronous invocation and the service receiver; also observe async failures.
9022
+ const result = useCall
9023
+ ? service_module.call(remote, req)
9024
+ : service_module[req.topic](remote, req);
9025
+ Promise.resolve(result).catch(error => handleError(remote, req, error));
9026
+ } catch (error) {
9027
+ handleError(remote, req, error);
9028
+ }
9029
+ });
8973
9030
  this.serviceNames.add(service);
8974
9031
  // console.log(`[Service attached: ${service} ] accept commands: ${service_module.commands}`)
8975
9032
  return this