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