@zyno-io/ts-server-foundation 26.728.2026 → 26.731.113

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/dist/src/app/base.d.ts +2 -1
  2. package/dist/src/app/base.d.ts.map +1 -1
  3. package/dist/src/app/base.js +19 -4
  4. package/dist/src/app/base.js.map +1 -1
  5. package/dist/src/app/index.js +1 -1
  6. package/dist/src/database/query.js +1 -1
  7. package/dist/src/di/module.js +1 -1
  8. package/dist/src/helpers/index.d.ts +1 -0
  9. package/dist/src/helpers/index.d.ts.map +1 -1
  10. package/dist/src/helpers/index.js +1 -0
  11. package/dist/src/helpers/index.js.map +1 -1
  12. package/dist/src/helpers/utils/timer.d.ts +3 -0
  13. package/dist/src/helpers/utils/timer.d.ts.map +1 -0
  14. package/dist/src/helpers/utils/timer.js +12 -0
  15. package/dist/src/helpers/utils/timer.js.map +1 -0
  16. package/dist/src/http/base.js +3 -3
  17. package/dist/src/http/base.js.map +1 -1
  18. package/dist/src/http/decorators.d.ts +12 -0
  19. package/dist/src/http/decorators.d.ts.map +1 -1
  20. package/dist/src/http/decorators.js +24 -1
  21. package/dist/src/http/decorators.js.map +1 -1
  22. package/dist/src/http/index.js +1 -1
  23. package/dist/src/http/response.d.ts.map +1 -1
  24. package/dist/src/http/response.js +10 -3
  25. package/dist/src/http/response.js.map +1 -1
  26. package/dist/src/http/router.d.ts +16 -2
  27. package/dist/src/http/router.d.ts.map +1 -1
  28. package/dist/src/http/router.js +119 -28
  29. package/dist/src/http/router.js.map +1 -1
  30. package/dist/src/http/static-files.d.ts +4 -3
  31. package/dist/src/http/static-files.d.ts.map +1 -1
  32. package/dist/src/http/static-files.js +12 -4
  33. package/dist/src/http/static-files.js.map +1 -1
  34. package/dist/src/index.js +1 -1
  35. package/dist/src/services/index.js +1 -1
  36. package/dist/src/services/logger.js +196 -5
  37. package/dist/src/services/logger.js.map +1 -1
  38. package/dist/src/services/mesh-client/index.d.ts +3 -1
  39. package/dist/src/services/mesh-client/index.d.ts.map +1 -1
  40. package/dist/src/services/mesh-client/index.js +6 -2
  41. package/dist/src/services/mesh-client/index.js.map +1 -1
  42. package/dist/src/services/mesh-client/mesh-client-redis-registry.d.ts +53 -7
  43. package/dist/src/services/mesh-client/mesh-client-redis-registry.d.ts.map +1 -1
  44. package/dist/src/services/mesh-client/mesh-client-redis-registry.js +862 -61
  45. package/dist/src/services/mesh-client/mesh-client-redis-registry.js.map +1 -1
  46. package/dist/src/services/mesh-client/mesh-client-registry.d.ts +17 -6
  47. package/dist/src/services/mesh-client/mesh-client-registry.d.ts.map +1 -1
  48. package/dist/src/services/mesh-client/mesh-client-registry.js +43 -2
  49. package/dist/src/services/mesh-client/mesh-client-registry.js.map +1 -1
  50. package/dist/src/services/mesh-client/mesh-client-service.d.ts +115 -48
  51. package/dist/src/services/mesh-client/mesh-client-service.d.ts.map +1 -1
  52. package/dist/src/services/mesh-client/mesh-client-service.js +790 -101
  53. package/dist/src/services/mesh-client/mesh-client-service.js.map +1 -1
  54. package/dist/src/services/mesh-client/mesh-srpc-link-controller.d.ts +129 -17
  55. package/dist/src/services/mesh-client/mesh-srpc-link-controller.d.ts.map +1 -1
  56. package/dist/src/services/mesh-client/mesh-srpc-link-controller.js +1615 -126
  57. package/dist/src/services/mesh-client/mesh-srpc-link-controller.js.map +1 -1
  58. package/dist/src/services/mesh-client/mesh-srpc-remote-connection.d.ts +38 -6
  59. package/dist/src/services/mesh-client/mesh-srpc-remote-connection.d.ts.map +1 -1
  60. package/dist/src/services/mesh-client/mesh-srpc-remote-connection.js +192 -27
  61. package/dist/src/services/mesh-client/mesh-srpc-remote-connection.js.map +1 -1
  62. package/dist/src/services/mesh-client/mesh-srpc-server.d.ts +57 -8
  63. package/dist/src/services/mesh-client/mesh-srpc-server.d.ts.map +1 -1
  64. package/dist/src/services/mesh-client/mesh-srpc-server.js +479 -131
  65. package/dist/src/services/mesh-client/mesh-srpc-server.js.map +1 -1
  66. package/dist/src/services/mesh-client/types.d.ts +77 -6
  67. package/dist/src/services/mesh-client/types.d.ts.map +1 -1
  68. package/dist/src/services/mesh-client/types.js +1 -1
  69. package/dist/src/services/mesh-client/types.js.map +1 -1
  70. package/dist/src/services/mesh-link/auth.d.ts +36 -2
  71. package/dist/src/services/mesh-link/auth.d.ts.map +1 -1
  72. package/dist/src/services/mesh-link/auth.js +97 -21
  73. package/dist/src/services/mesh-link/auth.js.map +1 -1
  74. package/dist/src/services/mesh-link/index.d.ts +2 -2
  75. package/dist/src/services/mesh-link/index.d.ts.map +1 -1
  76. package/dist/src/services/mesh-link/index.js +5 -2
  77. package/dist/src/services/mesh-link/index.js.map +1 -1
  78. package/dist/src/services/mesh-link/peer.d.ts +26 -1
  79. package/dist/src/services/mesh-link/peer.d.ts.map +1 -1
  80. package/dist/src/services/mesh-link/peer.js +220 -26
  81. package/dist/src/services/mesh-link/peer.js.map +1 -1
  82. package/dist/src/services/mesh-link/protocol.d.ts +16 -3
  83. package/dist/src/services/mesh-link/protocol.d.ts.map +1 -1
  84. package/dist/src/services/mesh-link/protocol.js +8 -4
  85. package/dist/src/services/mesh-link/protocol.js.map +1 -1
  86. package/dist/src/services/mesh-link/runtime.d.ts +57 -4
  87. package/dist/src/services/mesh-link/runtime.d.ts.map +1 -1
  88. package/dist/src/services/mesh-link/runtime.js +557 -67
  89. package/dist/src/services/mesh-link/runtime.js.map +1 -1
  90. package/dist/src/services/mesh.d.ts +72 -28
  91. package/dist/src/services/mesh.d.ts.map +1 -1
  92. package/dist/src/services/mesh.js +587 -278
  93. package/dist/src/services/mesh.js.map +1 -1
  94. package/dist/src/services/worker/queue.d.ts +6 -0
  95. package/dist/src/services/worker/queue.d.ts.map +1 -1
  96. package/dist/src/services/worker/queue.js +41 -3
  97. package/dist/src/services/worker/queue.js.map +1 -1
  98. package/dist/src/services/worker/runner.d.ts +1 -1
  99. package/dist/src/services/worker/runner.d.ts.map +1 -1
  100. package/dist/src/services/worker/runner.js +13 -6
  101. package/dist/src/services/worker/runner.js.map +1 -1
  102. package/dist/src/srpc/SrpcByteStream.d.ts +21 -2
  103. package/dist/src/srpc/SrpcByteStream.d.ts.map +1 -1
  104. package/dist/src/srpc/SrpcByteStream.js +271 -61
  105. package/dist/src/srpc/SrpcByteStream.js.map +1 -1
  106. package/dist/src/srpc/SrpcClient.d.ts +57 -13
  107. package/dist/src/srpc/SrpcClient.d.ts.map +1 -1
  108. package/dist/src/srpc/SrpcClient.js +558 -120
  109. package/dist/src/srpc/SrpcClient.js.map +1 -1
  110. package/dist/src/srpc/SrpcServer.d.ts +59 -4
  111. package/dist/src/srpc/SrpcServer.d.ts.map +1 -1
  112. package/dist/src/srpc/SrpcServer.js +683 -80
  113. package/dist/src/srpc/SrpcServer.js.map +1 -1
  114. package/dist/src/srpc/index.js +1 -1
  115. package/dist/src/srpc/observer.js +1 -1
  116. package/dist/src/srpc/types.d.ts +37 -6
  117. package/dist/src/srpc/types.d.ts.map +1 -1
  118. package/dist/src/srpc/types.js +12 -1
  119. package/dist/src/srpc/types.js.map +1 -1
  120. package/docs/content/getting-started.md +22 -20
  121. package/docs/content/http.md +38 -1
  122. package/docs/content/mesh-client.md +175 -53
  123. package/docs/content/mesh-service.md +64 -229
  124. package/docs/content/srpc.md +33 -10
  125. package/package.json +7 -7
@@ -4,12 +4,13 @@ exports.__tsfTypeAliases = exports.SrpcClient = exports.SrpcConflictError = void
4
4
  const tslib_1 = require("tslib");
5
5
  const _a = tslib_1.__importStar(require("@zyno-io/ts-server-foundation/type-metadata-runtime"));
6
6
  const node_crypto_1 = require("node:crypto");
7
+ const node_async_hooks_1 = require("node:async_hooks");
7
8
  const ws_1 = tslib_1.__importDefault(require("ws"));
8
9
  const app_1 = require("../app");
9
10
  const helpers_1 = require("../helpers");
10
11
  const SrpcByteStream_1 = require("./SrpcByteStream");
11
12
  const types_1 = require("./types");
12
- const __tsf_metadata_type = _a.createCompactMetadataRegistryV1("[1,[{\"kind\":2},{\"kind\":18,\"types\":[{\"kind\":20,\"name\":\"supersede\",\"type\":{\"kind\":12,\"types\":[{\"kind\":8},{\"kind\":4}]},\"optional\":true}]},{\"kind\":22,\"type\":{\"kind\":3}},{\"kind\":3},{\"kind\":2,\"typeName\":\"() =\\u003e void\"},{\"kind\":2,\"typeName\":\"P\"},{\"kind\":2,\"typeName\":\"(data: HandlerRequestData\\u003cTServerOutput, P\\u003e) =\\u003e Promise\\u003cResponseData\\u003cTClientInput, P\\u003e\\u003e | ResponseData\\u003cTClientInput, P\\u003e\"},{\"kind\":2,\"typeName\":\"(cause: SrpcDisconnectCause) =\\u003e void\"},{\"kind\":0},{\"kind\":18,\"typeName\":\"ResponseData\\u003cTServerOutput, P\\u003e\",\"types\":[{\"kind\":20,\"name\":\"\u00FE@toStringTag@64\",\"type\":{\"kind\":6},\"optional\":false}]},{\"kind\":18,\"typeName\":\"ISrpcLogger\",\"types\":[]},{\"kind\":6},{\"kind\":18,\"typeName\":\"SrpcMessageFns\",\"types\":[]},{\"kind\":17,\"typeName\":\"SrpcMeta\"},{\"kind\":18,\"typeName\":\"SrpcClientOptions\",\"types\":[{\"kind\":20,\"name\":\"enableReconnect\",\"type\":{\"kind\":12,\"types\":[{\"kind\":8},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"protocolVersion\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true}]}]]", []);
13
+ const __tsf_metadata_type = _a.createCompactMetadataRegistryV1("[1,[{\"kind\":2},{\"kind\":18,\"types\":[{\"kind\":20,\"name\":\"supersede\",\"type\":{\"kind\":12,\"types\":[{\"kind\":8},{\"kind\":4}]},\"optional\":true}]},{\"kind\":22,\"type\":{\"kind\":3}},{\"kind\":3},{\"kind\":18,\"typeName\":\"IByteStream\",\"types\":[{\"kind\":20,\"name\":\"parentStreamId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"remoteSenderIdParity\",\"type\":{\"kind\":12,\"types\":[{\"kind\":12,\"types\":[{\"kind\":10,\"literal\":0},{\"kind\":10,\"literal\":1}]},{\"kind\":4}]},\"optional\":true}]},{\"kind\":2,\"typeName\":\"() =\\u003e void\"},{\"kind\":2,\"typeName\":\"P\"},{\"kind\":2,\"typeName\":\"(data: HandlerRequestData\\u003cTServerOutput, P\\u003e) =\\u003e Promise\\u003cResponseData\\u003cTClientInput, P\\u003e\\u003e | ResponseData\\u003cTClientInput, P\\u003e\"},{\"kind\":2,\"typeName\":\"(cause: SrpcDisconnectCause) =\\u003e void\"},{\"kind\":0},{\"kind\":18,\"typeName\":\"ResponseData\\u003cTServerOutput, P\\u003e\",\"types\":[{\"kind\":20,\"name\":\"\u00FE@toStringTag@64\",\"type\":{\"kind\":6},\"optional\":false}]},{\"kind\":18,\"typeName\":\"ISrpcLogger\",\"types\":[]},{\"kind\":6},{\"kind\":18,\"typeName\":\"SrpcMessageFns\",\"types\":[]},{\"kind\":17,\"typeName\":\"SrpcMeta\"},{\"kind\":18,\"typeName\":\"SrpcClientOptions\",\"types\":[{\"kind\":20,\"name\":\"enableReconnect\",\"type\":{\"kind\":12,\"types\":[{\"kind\":8},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"authAudience\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"senderAnnouncements\",\"type\":{\"kind\":12,\"types\":[{\"kind\":8},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxPendingRequests\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxPendingRequestBytes\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxInFlightServerRequests\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxInFlightServerRequestBytes\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxBufferedBytes\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxMessageBytes\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"connectTimeoutMs\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"lateReplyTombstoneTtlMs\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true}]}]]", []);
13
14
  let _SrpcConflictErrorMetadata_1;
14
15
  class SrpcConflictError extends Error {
15
16
  constructor() {
@@ -21,6 +22,14 @@ class SrpcConflictError extends Error {
21
22
  exports.SrpcConflictError = SrpcConflictError;
22
23
  _SrpcConflictErrorMetadata_1.classType = SrpcConflictError;
23
24
  SrpcConflictError.__tsfType = _SrpcConflictErrorMetadata_1;
25
+ const DefaultMaxRequests = 128;
26
+ const DefaultMaxBytes = 8 * 1024 * 1024;
27
+ const DefaultMaxMessageBytes = 8 * 1024 * 1024;
28
+ const DefaultConnectTimeoutMs = 60000;
29
+ const DefaultLateReplyTombstoneTtlMs = 60000;
30
+ const MaxLateReplyTombstones = 256;
31
+ const MaxByteStreamId = 0x7fffffff;
32
+ const MaxBackpressuredByteStreams = 1024;
24
33
  let _SrpcClientMetadata_1;
25
34
  class SrpcClient {
26
35
  logger;
@@ -30,11 +39,15 @@ class SrpcClient {
30
39
  clientId;
31
40
  clientMeta;
32
41
  clientSecret;
42
+ clientOptions;
43
+ handlerRequestId = new node_async_hooks_1.AsyncLocalStorage();
33
44
  ws;
34
45
  streamConnectionHandlers = new Set();
35
46
  streamDisconnectionHandlers = new Set();
36
47
  streamMessageHandlers = new Map();
37
48
  requestQueue = new Map();
49
+ requestBytes = new Map();
50
+ lateReplyTombstones = new Map();
38
51
  connectResolve;
39
52
  connectReject;
40
53
  reconnectionTimeout;
@@ -42,9 +55,17 @@ class SrpcClient {
42
55
  lastPongMs = 0;
43
56
  intentionalDisconnect = false;
44
57
  supersede = false;
58
+ hasEstablishedGeneration = false;
45
59
  streamId = '';
46
60
  enableReconnect;
47
- protocolVersion;
61
+ senderAnnouncements;
62
+ generation = 0;
63
+ handlerPressureByGeneration = new Map();
64
+ byteStreamsByGeneration = new Map();
65
+ byteStreamPressureByGeneration = new Map();
66
+ byteStreamDisconnectHandlersByGeneration = new Map();
67
+ awaitingActivation;
68
+ clearConnectTimeout;
48
69
  isConnected = false;
49
70
  constructor(logger, uri, clientMessage, serverMessage, clientId, clientMeta, clientSecret, clientOptions) {
50
71
  this.logger = logger;
@@ -54,17 +75,41 @@ class SrpcClient {
54
75
  this.clientId = clientId;
55
76
  this.clientMeta = clientMeta;
56
77
  this.clientSecret = clientSecret;
78
+ this.clientOptions = clientOptions;
79
+ validateClientResourceOptions(clientOptions);
57
80
  this.enableReconnect = clientOptions?.enableReconnect !== false;
58
- this.protocolVersion = clientOptions?.protocolVersion ?? 2;
81
+ this.senderAnnouncements = clientOptions?.senderAnnouncements !== false;
59
82
  }
60
83
  connect(options) {
61
84
  if (this.reconnectionTimeout) {
62
85
  clearTimeout(this.reconnectionTimeout);
63
86
  this.reconnectionTimeout = undefined;
64
87
  }
88
+ const wasConnected = this.isConnected;
89
+ this.clearConnectTimeout?.();
65
90
  this.connectReject?.(new Error('Connection superseded by new connect() call'));
91
+ this.rejectAllRequests(new types_1.SrpcIndeterminateDeliveryError(this.clientId, new Error('Connection superseded by new connect() call')));
66
92
  this.connectResolve = undefined;
67
93
  this.connectReject = undefined;
94
+ this.isConnected = false;
95
+ this.awaitingActivation = undefined;
96
+ if (this.pingInterval)
97
+ clearInterval(this.pingInterval);
98
+ this.pingInterval = undefined;
99
+ if (wasConnected) {
100
+ for (const handler of this.streamDisconnectionHandlers) {
101
+ try {
102
+ handler('supersede');
103
+ }
104
+ catch (error) {
105
+ this.logger.error('SRPC disconnect handler failed', error);
106
+ }
107
+ }
108
+ }
109
+ const previousGeneration = this.generation;
110
+ const generation = ++this.generation;
111
+ this.handlerPressureByGeneration.delete(previousGeneration);
112
+ this.revokeByteStreamGeneration(previousGeneration);
68
113
  if (this.ws) {
69
114
  this.intentionalDisconnect = true;
70
115
  this.ws.close();
@@ -73,22 +118,29 @@ class SrpcClient {
73
118
  this.intentionalDisconnect = false;
74
119
  this.supersede = options?.supersede ?? false;
75
120
  this.streamId = (0, helpers_1.uuid7)();
76
- this.byteStream.parentStreamId = this.streamId;
77
- SrpcByteStream_1.SrpcByteStream.init(this, { startId: 1, step: 2 });
78
- const ws = new ws_1.default(this.generateWsUrl());
121
+ this.currentByteStream = this.createByteStream(generation);
122
+ this.byteStreamsByGeneration.set(generation, this.currentByteStream);
123
+ this.currentByteStream.parentStreamId = this.streamId;
124
+ SrpcByteStream_1.SrpcByteStream.init({ byteStream: this.currentByteStream }, { startId: 1, step: 2 });
125
+ const ws = new ws_1.default(this.generateWsUrl(), { maxPayload: this.maxMessageBytes });
79
126
  ws.binaryType = 'nodebuffer';
80
127
  this.ws = ws;
81
- const connectTimeout = setTimeout(() => {
82
- this.connectReject?.(new Error('Connection failed: timeout'));
83
- this.connectResolve = undefined;
84
- this.connectReject = undefined;
128
+ let connectTimeout;
129
+ const clearConnectTimeout = () => {
130
+ clearTimeout(connectTimeout);
131
+ if (this.clearConnectTimeout === clearConnectTimeout)
132
+ this.clearConnectTimeout = undefined;
133
+ };
134
+ this.clearConnectTimeout = clearConnectTimeout;
135
+ connectTimeout = setTimeout(() => {
136
+ if (!this.isCurrent(ws, generation))
137
+ return;
138
+ this.revokeGeneration(ws, generation, 'timeout', false, new Error('Connection failed: timeout'));
85
139
  ws.close();
86
- this.queueReconnect();
87
- }, 10000);
88
- const clearConnectTimeout = () => clearTimeout(connectTimeout);
89
- ws.once('message', data => this.handleInitialHandshake(ws, data, clearConnectTimeout));
90
- ws.on('close', (code, reason) => this.handleClose(ws, code, reason, clearConnectTimeout));
91
- ws.on('error', error => this.handleError(ws, error, clearConnectTimeout));
140
+ }, this.connectTimeoutMs);
141
+ ws.once('message', data => this.handleInitialHandshake(ws, generation, data, clearConnectTimeout));
142
+ ws.on('close', (code, reason) => this.handleClose(ws, generation, code, reason, clearConnectTimeout));
143
+ ws.on('error', error => this.handleError(ws, generation, error, clearConnectTimeout));
92
144
  const promise = new Promise((resolve, reject) => {
93
145
  this.connectResolve = resolve;
94
146
  this.connectReject = reject;
@@ -97,13 +149,21 @@ class SrpcClient {
97
149
  return promise;
98
150
  }
99
151
  disconnect() {
152
+ const ws = this.ws;
153
+ const generation = this.generation;
100
154
  this.enableReconnect = false;
101
155
  this.intentionalDisconnect = true;
156
+ this.clearConnectTimeout?.();
102
157
  if (this.reconnectionTimeout)
103
158
  clearTimeout(this.reconnectionTimeout);
159
+ this.reconnectionTimeout = undefined;
104
160
  if (this.pingInterval)
105
161
  clearInterval(this.pingInterval);
106
- this.ws?.close(1000, 'Client disconnect');
162
+ this.pingInterval = undefined;
163
+ if (ws && this.isCurrent(ws, generation)) {
164
+ this.revokeGeneration(ws, generation, 'disconnect', true, new Error('Connection closed by client'));
165
+ }
166
+ ws?.close(1000, 'Client disconnect');
107
167
  }
108
168
  triggerConnectionCheck() {
109
169
  if (!this.isConnected)
@@ -111,169 +171,285 @@ class SrpcClient {
111
171
  this.lastPongMs = Date.now() - 20000;
112
172
  this.writeMessage({ pingPong: {} });
113
173
  }
114
- handleInitialHandshake(ws, data, clearConnectTimeout) {
115
- if (this.ws !== ws)
174
+ handleInitialHandshake(ws, generation, data, clearConnectTimeout) {
175
+ if (!this.isCurrent(ws, generation))
116
176
  return;
117
- clearConnectTimeout();
118
177
  const message = this.decodeMessage(data);
119
178
  if (!message?.pingPong) {
120
- ws.close(4000, 'Expected handshake ping');
179
+ this.closeGenerationWithError(ws, generation, 'badArg', 'Expected handshake ping');
121
180
  return;
122
181
  }
123
182
  this.lastPongMs = Date.now();
124
- this.writeMessage({ pingPong: {} });
183
+ if (!this.writeMessage({ pingPong: {} }, generation) || !this.isCurrent(ws, generation))
184
+ return;
185
+ this.awaitingActivation = { ws, generation, clearConnectTimeout };
186
+ ws.on('message', msgData => {
187
+ void this.handleMessage(ws, generation, msgData).catch(error => {
188
+ this.logger.warn('Failed to dispatch SRPC message', error);
189
+ this.closeGenerationWithError(ws, generation, 'badArg', 'Invalid message format');
190
+ });
191
+ });
192
+ }
193
+ completeConnection(ws, generation) {
194
+ if (!this.isCurrent(ws, generation) || this.isConnected)
195
+ return;
196
+ this.awaitingActivation?.clearConnectTimeout();
197
+ this.awaitingActivation = undefined;
125
198
  this.isConnected = true;
199
+ this.hasEstablishedGeneration = true;
126
200
  this.pingInterval = setInterval(() => this.doPingPong(), 55000);
127
201
  this.pingInterval.unref?.();
128
202
  this.connectResolve?.();
129
203
  this.connectResolve = undefined;
130
204
  this.connectReject = undefined;
131
- for (const handler of this.streamConnectionHandlers)
132
- handler();
133
- ws.on('message', msgData => this.handleMessage(msgData));
205
+ for (const handler of this.streamConnectionHandlers) {
206
+ try {
207
+ handler();
208
+ }
209
+ catch (error) {
210
+ this.logger.error('SRPC connection handler failed', error);
211
+ }
212
+ }
134
213
  }
135
- handleClose(ws, code, _reason, clearConnectTimeout) {
136
- if (ws !== this.ws)
214
+ handleClose(ws, generation, code, _reason, clearConnectTimeout) {
215
+ if (!this.isCurrent(ws, generation))
137
216
  return;
138
217
  clearConnectTimeout();
139
218
  const cause = parseDisconnectCause(code);
140
219
  if (cause === 'conflict') {
141
- this.connectReject?.(new SrpcConflictError());
142
- this.connectResolve = undefined;
143
- this.connectReject = undefined;
144
- this.handleDisconnect(cause, true);
220
+ this.revokeGeneration(ws, generation, cause, true, new SrpcConflictError());
145
221
  return;
146
222
  }
147
- this.handleDisconnect(cause);
223
+ this.revokeGeneration(ws, generation, cause);
148
224
  }
149
- handleError(ws, error, clearConnectTimeout) {
150
- if (ws !== this.ws)
225
+ handleError(ws, generation, error, clearConnectTimeout) {
226
+ if (!this.isCurrent(ws, generation))
151
227
  return;
152
228
  clearConnectTimeout();
153
229
  if (!this.intentionalDisconnect)
154
230
  this.logger.warn('SRPC WebSocket error', error);
231
+ this.revokeGeneration(ws, generation, 'disconnect');
155
232
  ws.terminate();
156
- this.handleDisconnect('disconnect');
157
233
  }
158
- handleDisconnect(cause = 'disconnect', suppressReconnect = false) {
159
- if (this.reconnectionTimeout)
160
- return;
161
- if (this.enableReconnect && !suppressReconnect && !this.intentionalDisconnect)
162
- this.queueReconnect();
234
+ revokeGeneration(ws, generation, cause, suppressReconnect = false, connectError = new Error(`Connection failed: ${cause}`)) {
235
+ if (!this.isCurrent(ws, generation))
236
+ return false;
237
+ this.clearConnectTimeout?.();
163
238
  if (this.pingInterval)
164
239
  clearInterval(this.pingInterval);
165
240
  this.pingInterval = undefined;
166
- this.connectReject?.(new Error(`Connection failed: ${cause}`));
241
+ this.connectReject?.(connectError);
167
242
  this.connectResolve = undefined;
168
243
  this.connectReject = undefined;
169
244
  const wasConnected = this.isConnected;
170
245
  this.isConnected = false;
246
+ this.awaitingActivation = undefined;
171
247
  this.ws = undefined;
248
+ this.handlerPressureByGeneration?.delete(generation);
249
+ this.revokeByteStreamGeneration(generation);
250
+ this.rejectAllRequests(new types_1.SrpcIndeterminateDeliveryError(this.clientId ?? '', new Error('Disconnected')));
172
251
  if (wasConnected) {
173
- for (const handler of this.streamDisconnectionHandlers)
174
- handler(cause);
252
+ for (const handler of this.streamDisconnectionHandlers ?? []) {
253
+ try {
254
+ handler(cause);
255
+ }
256
+ catch (error) {
257
+ this.logger.error('SRPC disconnect handler failed', error);
258
+ }
259
+ }
175
260
  }
176
- for (const queueItem of this.requestQueue.values())
177
- queueItem.reject(new Error('Disconnected'));
178
- this.requestQueue.clear();
261
+ if (this.enableReconnect && !suppressReconnect && !this.intentionalDisconnect && !this.reconnectionTimeout)
262
+ this.queueReconnect();
263
+ return true;
264
+ }
265
+ closeGenerationWithError(ws, generation, cause, message) {
266
+ if (!this.revokeGeneration(ws, generation, cause))
267
+ return;
268
+ ws.close(closeCodeForCause(cause), message.slice(0, 123));
179
269
  }
180
270
  queueReconnect() {
181
271
  if (!this.enableReconnect)
182
272
  return;
183
273
  this.reconnectionTimeout = setTimeout(() => {
184
274
  this.reconnectionTimeout = undefined;
185
- this.connect().catch(() => { });
275
+ this.connect({ supersede: this.hasEstablishedGeneration }).catch(() => { });
186
276
  }, 1000);
187
277
  this.reconnectionTimeout.unref?.();
188
278
  }
189
279
  doPingPong() {
190
280
  if (this.lastPongMs < Date.now() - 75000) {
191
- this.ws?.close(4003, 'Pong timeout');
281
+ const ws = this.ws;
282
+ if (ws)
283
+ this.closeGenerationWithError(ws, this.generation, 'timeout', 'Pong timeout');
192
284
  return;
193
285
  }
194
286
  this.writeMessage({ pingPong: {} });
195
287
  }
196
- async handleMessage(data) {
288
+ async handleMessage(ws, generation, data) {
289
+ if (!this.isCurrent(ws, generation))
290
+ return;
291
+ const frameBytes = toBuffer(data).byteLength;
292
+ if (frameBytes > this.maxMessageBytes) {
293
+ this.closeGenerationWithError(ws, generation, 'badArg', 'SRPC message too large');
294
+ return;
295
+ }
197
296
  const message = this.decodeMessage(data);
198
- if (!message)
297
+ if (!message) {
298
+ this.closeGenerationWithError(ws, generation, 'badArg', 'Invalid message format');
199
299
  return;
300
+ }
200
301
  if (message.pingPong) {
201
302
  this.lastPongMs = Date.now();
303
+ if (this.awaitingActivation?.ws === ws && this.awaitingActivation.generation === generation)
304
+ this.completeConnection(ws, generation);
202
305
  return;
203
306
  }
307
+ const activation = this.awaitingActivation;
308
+ const isActivating = activation?.ws === ws && activation.generation === generation;
309
+ if (!this.isConnected && !isActivating)
310
+ return;
204
311
  if (message.byteStreamOperation) {
205
- this.handleByteStreamOperation(message.byteStreamOperation);
312
+ if (!this.validRemoteByteStreamOperation(message.byteStreamOperation)) {
313
+ this.closeGenerationWithError(ws, generation, 'badArg', 'Invalid byte stream ID');
314
+ return;
315
+ }
316
+ this.handleByteStreamOperation(generation, message.byteStreamOperation);
206
317
  return;
207
318
  }
208
319
  if (!message.requestId) {
209
- this.ws?.close(4000, 'Invalid request ID');
320
+ this.closeGenerationWithError(ws, generation, 'badArg', 'Invalid request ID');
210
321
  return;
211
322
  }
212
323
  if (message.reply) {
213
- this.handleReply(message.requestId, message);
324
+ this.handleReply(ws, generation, message.requestId, message);
325
+ return;
326
+ }
327
+ const bytes = frameBytes;
328
+ const pressure = this.handlerPressureByGeneration.get(generation) ?? { requests: 0, bytes: 0 };
329
+ if (pressure.requests >= this.maxInFlightServerRequests || pressure.bytes + bytes > this.maxInFlightServerRequestBytes) {
330
+ this.closeGenerationWithError(ws, generation, 'badArg', 'Too many in-flight server requests');
214
331
  return;
215
332
  }
216
- await this.handleServerRequest(message.requestId, message);
333
+ pressure.requests++;
334
+ pressure.bytes += bytes;
335
+ this.handlerPressureByGeneration.set(generation, pressure);
336
+ try {
337
+ await this.handleServerRequest(generation, message.requestId, message);
338
+ }
339
+ finally {
340
+ if (this.handlerPressureByGeneration.get(generation) === pressure) {
341
+ pressure.requests = Math.max(0, pressure.requests - 1);
342
+ pressure.bytes = Math.max(0, pressure.bytes - bytes);
343
+ if (!pressure.requests)
344
+ this.handlerPressureByGeneration.delete(generation);
345
+ }
346
+ }
217
347
  }
218
- handleByteStreamOperation(op) {
219
- if (op.write)
220
- SrpcByteStream_1.SrpcByteStream.writeReceiver(this, op.streamId, op.write.chunk);
221
- else if (op.finish)
348
+ handleByteStreamOperation(generation, op) {
349
+ if (op.destroy != null && SrpcByteStream_1.SrpcByteStream.consumeTerminalSender(this, op.streamId))
350
+ return;
351
+ if (op.write != null) {
352
+ const state = this.getByteStreamPressureState(generation);
353
+ const wasBackpressured = state.backpressured.has(op.streamId);
354
+ const accepted = SrpcByteStream_1.SrpcByteStream.writeReceiver(this, op.streamId, op.write.chunk);
355
+ this.updateByteStreamBufferedBytes(generation, op.streamId, SrpcByteStream_1.SrpcByteStream.getReceiverBufferedBytes(this, op.streamId));
356
+ if (!accepted && wasBackpressured) {
357
+ SrpcByteStream_1.SrpcByteStream.abortReceiver(this, op.streamId, new Error(`SRPC byte stream ${op.streamId} receiver is not draining`));
358
+ this.clearByteStreamPressure(generation, op.streamId);
359
+ return;
360
+ }
361
+ if (!accepted) {
362
+ if (state.backpressured.size >= MaxBackpressuredByteStreams) {
363
+ SrpcByteStream_1.SrpcByteStream.abortReceiver(this, op.streamId, new Error('Too many backpressured SRPC byte streams'));
364
+ this.clearByteStreamPressure(generation, op.streamId);
365
+ return;
366
+ }
367
+ state.backpressured.add(op.streamId);
368
+ }
369
+ else if (wasBackpressured) {
370
+ state.backpressured.delete(op.streamId);
371
+ }
372
+ if (this.totalByteStreamBufferedBytes(state) > this.maxBufferedBytes) {
373
+ SrpcByteStream_1.SrpcByteStream.abortReceiver(this, op.streamId, new Error('Too many buffered SRPC byte stream bytes'));
374
+ this.clearByteStreamPressure(generation, op.streamId);
375
+ }
376
+ }
377
+ else if (op.finish != null) {
378
+ this.getByteStreamPressureState(generation).backpressured.delete(op.streamId);
222
379
  SrpcByteStream_1.SrpcByteStream.finishReceiver(this, op.streamId);
223
- else if (op.destroy)
380
+ }
381
+ else if (op.destroy != null) {
382
+ this.clearByteStreamPressure(generation, op.streamId);
224
383
  SrpcByteStream_1.SrpcByteStream.destroySubstream(this, op.streamId, op.destroy.error);
384
+ }
225
385
  }
226
- handleReply(requestId, message) {
386
+ handleReply(ws, generation, requestId, message) {
227
387
  const queueItem = this.requestQueue.get(requestId);
228
388
  if (!queueItem) {
229
- this.ws?.close(4000, 'Unknown request ID');
389
+ if (this.isLateReply(requestId))
390
+ return;
391
+ this.closeGenerationWithError(ws, generation, 'badArg', 'Unknown request ID');
230
392
  return;
231
393
  }
232
394
  this.requestQueue.delete(requestId);
233
- if (message.error)
395
+ this.requestBytes.delete(requestId);
396
+ if (message.error !== undefined)
234
397
  queueItem.reject(new types_1.SrpcError(message.error, message.userError));
235
398
  else
236
399
  queueItem.resolve(message);
237
400
  }
238
- async handleServerRequest(requestId, message) {
401
+ async handleServerRequest(generation, requestId, message) {
239
402
  for (const [key, handlerMeta] of this.streamMessageHandlers) {
240
403
  const requestData = message[key];
241
404
  if (requestData == null)
242
405
  continue;
243
406
  try {
244
- const result = await handlerMeta.handler(requestData);
407
+ const result = await this.handlerRequestId.run({ requestId, generation }, () => handlerMeta.handler(requestData));
245
408
  this.writeMessage({
246
409
  requestId,
247
410
  reply: true,
248
411
  [handlerMeta.resultType]: result
249
- });
412
+ }, generation);
250
413
  }
251
414
  catch (error) {
252
- const isUserError = (error instanceof types_1.SrpcError && error.isUserError) ||
253
- (typeof error === 'object' &&
254
- error !== null &&
255
- error.name === 'SrpcError' &&
256
- error.isUserError === true);
257
415
  this.writeMessage({
258
416
  requestId,
259
417
  reply: true,
260
- error: isUserError && error instanceof Error ? error.message : String(error),
261
- userError: isUserError
262
- });
418
+ ...(0, types_1.serializeSrpcError)(error)
419
+ }, generation);
263
420
  }
264
421
  return;
265
422
  }
266
- this.writeMessage({ requestId, reply: true, error: 'Unhandled message type' });
423
+ this.writeMessage({ requestId, reply: true, error: 'Unhandled message type' }, generation);
267
424
  }
268
425
  generateWsUrl() {
269
- const authv = 1;
426
+ const authv = 2;
270
427
  const appv = '0.0.0';
271
428
  const ts = Date.now();
272
429
  const cid = this.clientId;
273
- const signable = `${authv}\n${appv}\n${ts}\n${this.streamId}\n${cid}\n`;
274
430
  const secret = this.clientSecret ?? (0, app_1.getCurrentApp)().config.SRPC_AUTH_SECRET;
275
431
  if (!secret)
276
432
  throw new Error('SRPC_AUTH_SECRET is not configured.');
433
+ const baseUri = this.uri.startsWith('ws://') || this.uri.startsWith('wss://') ? this.uri : `ws://${this.uri}`;
434
+ const url = new URL(baseUri);
435
+ const nonce = (0, helpers_1.uuid7)();
436
+ const features = normalizeFeatures(this.senderAnnouncements ? ['sender-announcements'] : []);
437
+ const metadata = normalizeMetadata(this.clientMeta);
438
+ const supersede = this.supersede ? '1' : '0';
439
+ const audience = this.clientOptions?.authAudience ?? url.pathname;
440
+ const signable = canonicalAuthV2({
441
+ path: url.pathname,
442
+ audience,
443
+ appv,
444
+ ts: String(ts),
445
+ nonce,
446
+ id: this.streamId,
447
+ cid,
448
+ protocol: '2',
449
+ supersede,
450
+ features,
451
+ metadata
452
+ });
277
453
  const signature = (0, node_crypto_1.createHmac)('sha256', secret).update(signable).digest('hex');
278
454
  const params = new URLSearchParams({
279
455
  authv: String(authv),
@@ -282,17 +458,18 @@ class SrpcClient {
282
458
  id: this.streamId,
283
459
  cid,
284
460
  signature,
285
- _v: String(this.protocolVersion)
461
+ _v: '2'
286
462
  });
463
+ params.set('nonce', nonce);
464
+ params.set('aud', audience);
465
+ if (features)
466
+ params.set('_f', features);
287
467
  if (this.supersede) {
288
468
  params.set('_supersede', '1');
289
469
  this.supersede = false;
290
470
  }
291
- for (const [key, value] of Object.entries(this.clientMeta ?? {})) {
292
- params.set(`m--${key}`, String(value));
293
- }
294
- const baseUri = this.uri.startsWith('ws://') || this.uri.startsWith('wss://') ? this.uri : `ws://${this.uri}`;
295
- const url = new URL(baseUri);
471
+ for (const [key, value] of Object.entries(metadata))
472
+ params.set(`m--${key}`, value);
296
473
  url.search = params.toString();
297
474
  return url.toString();
298
475
  }
@@ -305,47 +482,122 @@ class SrpcClient {
305
482
  return null;
306
483
  }
307
484
  }
308
- writeMessage(message) {
309
- if (!this.ws || this.ws.readyState !== ws_1.default.OPEN)
485
+ writeMessage(message, generation = this.generation) {
486
+ let encoded;
487
+ try {
488
+ encoded = (0, types_1.encodeSrpcMessage)(this.clientMessage, message);
489
+ }
490
+ catch (error) {
491
+ this.logger.error('Failed to encode SRPC message', error);
310
492
  return false;
311
- this.ws.send((0, types_1.encodeSrpcMessage)(this.clientMessage, message));
312
- return true;
493
+ }
494
+ return this.writeEncodedMessage(encoded, generation);
313
495
  }
314
- writeMessageAsync(message) {
496
+ writeEncodedMessage(encoded, generation = this.generation) {
315
497
  const ws = this.ws;
316
- if (!ws || ws.readyState !== ws_1.default.OPEN)
498
+ if (!ws || !this.isCurrent(ws, generation) || ws.readyState !== ws_1.default.OPEN)
499
+ return false;
500
+ if (encoded.byteLength > this.maxMessageBytes || (ws.bufferedAmount ?? 0) + encoded.byteLength > this.maxBufferedBytes) {
501
+ this.closeGenerationWithError(ws, generation, 'badArg', 'sRPC stream outgoing buffer limit exceeded');
502
+ return false;
503
+ }
504
+ try {
505
+ ws.send(encoded);
506
+ return true;
507
+ }
508
+ catch (error) {
509
+ this.logger.warn('Failed to send SRPC message', error);
510
+ this.closeGenerationWithError(ws, generation, 'badArg', 'Failed to send SRPC message');
511
+ return false;
512
+ }
513
+ }
514
+ writeMessageAsync(message, generation = this.generation) {
515
+ const ws = this.ws;
516
+ if (!ws || !this.isCurrent(ws, generation) || ws.readyState !== ws_1.default.OPEN)
317
517
  return Promise.reject(new Error('Failed to send SRPC message: not connected'));
318
518
  const encoded = (0, types_1.encodeSrpcMessage)(this.clientMessage, message);
519
+ if (encoded.byteLength > this.maxMessageBytes || (ws.bufferedAmount ?? 0) + encoded.byteLength > this.maxBufferedBytes) {
520
+ this.closeGenerationWithError(ws, generation, 'badArg', 'sRPC stream outgoing buffer limit exceeded');
521
+ return Promise.reject(new types_1.SrpcBackpressureError('sRPC stream outgoing buffer limit exceeded'));
522
+ }
319
523
  return new Promise((resolve, reject) => {
320
- ws.send(encoded, error => {
321
- if (error)
322
- reject(error);
323
- else
324
- resolve();
325
- });
524
+ try {
525
+ ws.send(encoded, error => {
526
+ if (error) {
527
+ this.closeGenerationWithError(ws, generation, 'badArg', 'Failed to send SRPC message');
528
+ reject(error);
529
+ }
530
+ else if (!this.isCurrent(ws, generation))
531
+ reject(new Error('Failed to send SRPC message: generation revoked'));
532
+ else
533
+ resolve();
534
+ });
535
+ }
536
+ catch (error) {
537
+ this.closeGenerationWithError(ws, generation, 'badArg', 'Failed to send SRPC message');
538
+ reject(error instanceof Error ? error : new Error(String(error)));
539
+ }
326
540
  });
327
541
  }
328
- byteStream = {
329
- parentStreamId: '',
330
- write: (streamId, chunk) => this.writeMessageAsync({
331
- byteStreamOperation: { streamId, write: { chunk: chunk } }
332
- }),
333
- finish: (streamId) => {
334
- this.writeMessage({ byteStreamOperation: { streamId, finish: {} } });
335
- },
336
- destroy: (streamId, error) => {
337
- this.writeMessage({
338
- byteStreamOperation: { streamId, destroy: { error: error ? String(error) : undefined } }
339
- });
340
- },
341
- attachDisconnectHandler: (handler) => {
342
- this.ws?.on('close', handler);
343
- },
344
- detachDisconnectHandler: (handler) => {
345
- this.ws?.off('close', handler);
346
- },
347
- getBufferedAmount: () => this.ws?.bufferedAmount ?? 0
348
- };
542
+ currentByteStream = this.createByteStream(0);
543
+ get byteStream() {
544
+ return this.resolveByteStream();
545
+ }
546
+ createByteStream(generation) {
547
+ return {
548
+ parentStreamId: '',
549
+ remoteSenderIdParity: 0,
550
+ receiverBufferChanged: (streamId, bufferedBytes) => this.updateByteStreamBufferedBytes(generation, streamId, bufferedBytes),
551
+ write: (streamId, chunk) => this.writeMessageAsync({ byteStreamOperation: { streamId, write: { chunk: new Uint8Array(chunk) } } }, generation),
552
+ finish: streamId => this.writeMessage({ byteStreamOperation: { streamId, finish: {} } }, generation),
553
+ destroy: (streamId, error) => this.writeMessage({ byteStreamOperation: { streamId, destroy: { error: (0, SrpcByteStream_1.byteStreamDestroyReason)(error) } } }, generation),
554
+ announceSender: streamId => {
555
+ const context = this.handlerRequestId.getStore();
556
+ if (!this.senderAnnouncements || !context || context.generation !== generation)
557
+ return;
558
+ this.writeMessage({ requestId: context.requestId, byteStreamOperation: { streamId, write: { chunk: new Uint8Array() } } }, generation);
559
+ },
560
+ attachDisconnectHandler: handler => {
561
+ let handlers = this.byteStreamDisconnectHandlersByGeneration.get(generation);
562
+ if (!handlers) {
563
+ handlers = new Set();
564
+ this.byteStreamDisconnectHandlersByGeneration.set(generation, handlers);
565
+ }
566
+ handlers.add(handler);
567
+ },
568
+ detachDisconnectHandler: handler => this.byteStreamDisconnectHandlersByGeneration.get(generation)?.delete(handler),
569
+ getBufferedAmount: () => (this.generation === generation ? (this.ws?.bufferedAmount ?? 0) : 0)
570
+ };
571
+ }
572
+ resolveByteStream() {
573
+ const context = this.handlerRequestId.getStore();
574
+ const generation = context?.generation ?? this.generation;
575
+ const activation = this.awaitingActivation;
576
+ const isCurrentActivation = activation?.generation === generation && this.isCurrent(activation.ws, generation);
577
+ if (generation !== this.generation || (!this.isConnected && !isCurrentActivation)) {
578
+ throw new Error('Cannot create an SRPC byte stream from a stale handler generation');
579
+ }
580
+ const transport = this.byteStreamsByGeneration.get(generation);
581
+ if (!transport)
582
+ throw new Error('SRPC handler transport is unavailable');
583
+ return transport;
584
+ }
585
+ revokeByteStreamGeneration(generation) {
586
+ const handlers = this.byteStreamDisconnectHandlersByGeneration?.get(generation);
587
+ this.byteStreamDisconnectHandlersByGeneration?.delete(generation);
588
+ if (handlers) {
589
+ for (const handler of handlers) {
590
+ try {
591
+ handler();
592
+ }
593
+ catch (error) {
594
+ this.logger.error('SRPC byte stream disconnect handler failed', error);
595
+ }
596
+ }
597
+ }
598
+ this.byteStreamsByGeneration?.delete(generation);
599
+ this.byteStreamPressureByGeneration?.delete(generation);
600
+ }
349
601
  registerConnectionHandler(handler) {
350
602
  this.streamConnectionHandlers.add(handler);
351
603
  }
@@ -360,18 +612,36 @@ class SrpcClient {
360
612
  this.streamDisconnectionHandlers.add(handler);
361
613
  }
362
614
  invoke(prefix, data, timeoutMs = 30000) {
615
+ assertTimeout(timeoutMs);
363
616
  const requestType = `${prefix}Request`;
364
617
  const resultType = `${prefix}Response`;
365
618
  const requestId = (0, helpers_1.uuid7)();
619
+ let encoded;
620
+ try {
621
+ encoded = (0, types_1.encodeSrpcMessage)(this.clientMessage, { requestId, [requestType]: data });
622
+ }
623
+ catch (error) {
624
+ return Promise.reject(error);
625
+ }
626
+ const encodedBytes = encoded.byteLength;
627
+ if (encodedBytes > this.maxMessageBytes)
628
+ return Promise.reject(new types_1.SrpcBackpressureError('sRPC request exceeds message limit'));
629
+ if (this.requestQueue.size >= this.maxPendingRequests || this.pendingRequestBytes + encodedBytes > this.maxPendingRequestBytes) {
630
+ return Promise.reject(new types_1.SrpcBackpressureError('Too many pending SRPC requests'));
631
+ }
366
632
  return new Promise((resolve, reject) => {
367
633
  const timeout = setTimeout(() => {
368
- this.requestQueue.delete(requestId);
369
- reject(new Error(`Request timeout after ${timeoutMs}ms`));
634
+ if (!this.requestQueue.delete(requestId))
635
+ return;
636
+ this.requestBytes.delete(requestId);
637
+ this.addLateReplyTombstone(requestId);
638
+ reject(new types_1.SrpcIndeterminateDeliveryError(this.clientId, new Error(`Request timeout after ${timeoutMs}ms`)));
370
639
  }, timeoutMs);
371
640
  this.requestQueue.set(requestId, {
372
641
  exp: Date.now() + timeoutMs,
373
642
  resolve: response => {
374
643
  clearTimeout(timeout);
644
+ this.requestBytes.delete(requestId);
375
645
  const result = response[resultType];
376
646
  if (result == null)
377
647
  reject(new Error('Invalid response from server'));
@@ -380,18 +650,136 @@ class SrpcClient {
380
650
  },
381
651
  reject: error => {
382
652
  clearTimeout(timeout);
653
+ this.requestBytes.delete(requestId);
383
654
  reject(error);
384
655
  }
385
656
  });
386
- const sent = this.writeMessage({ requestId, [requestType]: data });
657
+ this.requestBytes.set(requestId, encodedBytes);
658
+ const sent = this.writeEncodedMessage(encoded, this.generation);
387
659
  if (!sent) {
388
660
  this.requestQueue.delete(requestId);
661
+ this.requestBytes.delete(requestId);
389
662
  clearTimeout(timeout);
390
663
  reject(new Error('Failed to send request: not connected'));
391
664
  }
392
665
  });
393
666
  }
394
- static __tsfType = _SrpcClientMetadata_1 = _a.decodeCompactMetadataV1("[1,{\"kind\":16,\"name\":\"SrpcClient\",\"typeName\":\"SrpcClient\",\"classType\":{\"$tsf\":0},\"properties\":[{\"name\":\"isConnected\",\"type\":{\"$tsfType\":0},\"optional\":false},{\"name\":\"byteStream\",\"type\":{\"$tsfType\":0},\"optional\":false}],\"methods\":[{\"name\":\"connect\",\"parameters\":[{\"name\":\"options\",\"type\":{\"$tsfType\":1},\"optional\":true,\"default\":false}],\"returnType\":{\"$tsfType\":2}},{\"name\":\"disconnect\",\"parameters\":[],\"returnType\":{\"$tsfType\":3}},{\"name\":\"triggerConnectionCheck\",\"parameters\":[],\"returnType\":{\"$tsfType\":3}},{\"name\":\"registerConnectionHandler\",\"parameters\":[{\"name\":\"handler\",\"type\":{\"$tsfType\":4},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":3}},{\"name\":\"registerMessageHandler\",\"parameters\":[{\"name\":\"prefix\",\"type\":{\"$tsfType\":5},\"optional\":false,\"default\":false},{\"name\":\"handler\",\"type\":{\"$tsfType\":6},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":3}},{\"name\":\"registerDisconnectHandler\",\"parameters\":[{\"name\":\"handler\",\"type\":{\"$tsfType\":7},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":3}},{\"name\":\"invoke\",\"parameters\":[{\"name\":\"prefix\",\"type\":{\"$tsfType\":5},\"optional\":false,\"default\":false},{\"name\":\"data\",\"type\":{\"$tsfType\":8},\"optional\":false,\"default\":false},{\"name\":\"timeoutMs\",\"type\":{\"$tsfType\":0},\"optional\":true,\"default\":true}],\"returnType\":{\"$tsfType\":9}}],\"hasConstructor\":true,\"constructorParameters\":[{\"name\":\"logger\",\"type\":{\"$tsfType\":10},\"optional\":false,\"default\":false},{\"name\":\"uri\",\"type\":{\"$tsfType\":11},\"optional\":false,\"default\":false},{\"name\":\"clientMessage\",\"type\":{\"$tsfType\":12},\"optional\":false,\"default\":false},{\"name\":\"serverMessage\",\"type\":{\"$tsfType\":12},\"optional\":false,\"default\":false},{\"name\":\"clientId\",\"type\":{\"$tsfType\":11},\"optional\":false,\"default\":false},{\"name\":\"clientMeta\",\"type\":{\"$tsfType\":13},\"optional\":true,\"default\":false},{\"name\":\"clientSecret\",\"type\":{\"$tsfType\":11},\"optional\":true,\"default\":false},{\"name\":\"clientOptions\",\"type\":{\"$tsfType\":14},\"optional\":true,\"default\":false}]}]", [() => SrpcClient], __tsf_metadata_type);
667
+ isCurrent(ws, generation) {
668
+ return this.ws === ws && this.generation === generation;
669
+ }
670
+ rejectAllRequests(error) {
671
+ for (const [requestId, queueItem] of this.requestQueue?.entries() ?? []) {
672
+ this.addLateReplyTombstone(requestId);
673
+ queueItem.reject(error);
674
+ }
675
+ this.requestQueue?.clear();
676
+ this.requestBytes?.clear();
677
+ }
678
+ validRemoteByteStreamOperation(op) {
679
+ const id = op.streamId;
680
+ if (typeof id !== 'number' || !Number.isSafeInteger(id) || id <= 0 || id > MaxByteStreamId)
681
+ return false;
682
+ const hasWrite = op.write != null;
683
+ const hasFinish = op.finish != null;
684
+ const hasDestroy = op.destroy != null;
685
+ const operationCount = Number(hasWrite) + Number(hasFinish) + Number(hasDestroy);
686
+ if (operationCount !== 1)
687
+ return false;
688
+ if (hasWrite && (!isPlainObject(op.write) || !(op.write.chunk instanceof Uint8Array)))
689
+ return false;
690
+ if (hasFinish && !isPlainObject(op.finish))
691
+ return false;
692
+ if (hasDestroy && (!isPlainObject(op.destroy) || (op.destroy.error != null && typeof op.destroy.error !== 'string')))
693
+ return false;
694
+ if (hasDestroy)
695
+ return id % 2 === 0 || SrpcByteStream_1.SrpcByteStream.hasSender(this, id) || SrpcByteStream_1.SrpcByteStream.hasTerminalSender(this, id);
696
+ return id % 2 === 0;
697
+ }
698
+ getByteStreamPressureState(generation) {
699
+ const existing = this.byteStreamPressureByGeneration.get(generation);
700
+ if (existing)
701
+ return existing;
702
+ const state = { backpressured: new Set(), bufferedBytes: new Map() };
703
+ this.byteStreamPressureByGeneration.set(generation, state);
704
+ return state;
705
+ }
706
+ updateByteStreamBufferedBytes(generation, streamId, bufferedBytes) {
707
+ if (generation !== this.generation)
708
+ return;
709
+ const state = this.getByteStreamPressureState(generation);
710
+ const previous = state.bufferedBytes.get(streamId) ?? 0;
711
+ if (bufferedBytes < previous)
712
+ state.backpressured.delete(streamId);
713
+ if (bufferedBytes > 0)
714
+ state.bufferedBytes.set(streamId, bufferedBytes);
715
+ else
716
+ state.bufferedBytes.delete(streamId);
717
+ }
718
+ clearByteStreamPressure(generation, streamId) {
719
+ const state = this.byteStreamPressureByGeneration.get(generation);
720
+ state?.backpressured.delete(streamId);
721
+ state?.bufferedBytes.delete(streamId);
722
+ }
723
+ totalByteStreamBufferedBytes(state) {
724
+ let total = 0;
725
+ for (const bytes of state.bufferedBytes.values())
726
+ total += bytes;
727
+ return total;
728
+ }
729
+ addLateReplyTombstone(requestId) {
730
+ const now = Date.now();
731
+ this.pruneLateReplyTombstones(now);
732
+ this.lateReplyTombstones.set(requestId, now + this.lateReplyTombstoneTtlMs);
733
+ while (this.lateReplyTombstones.size > MaxLateReplyTombstones) {
734
+ const oldestRequestId = this.lateReplyTombstones.keys().next().value;
735
+ if (oldestRequestId === undefined)
736
+ break;
737
+ this.lateReplyTombstones.delete(oldestRequestId);
738
+ }
739
+ }
740
+ isLateReply(requestId) {
741
+ const now = Date.now();
742
+ this.pruneLateReplyTombstones(now);
743
+ return (this.lateReplyTombstones.get(requestId) ?? 0) > now;
744
+ }
745
+ pruneLateReplyTombstones(now) {
746
+ for (const [requestId, expiresAt] of this.lateReplyTombstones) {
747
+ if (expiresAt <= now)
748
+ this.lateReplyTombstones.delete(requestId);
749
+ }
750
+ }
751
+ get lateReplyTombstoneTtlMs() {
752
+ return configuredPositiveInteger(this.clientOptions?.lateReplyTombstoneTtlMs, DefaultLateReplyTombstoneTtlMs);
753
+ }
754
+ get pendingRequestBytes() {
755
+ let total = 0;
756
+ for (const bytes of this.requestBytes.values())
757
+ total += bytes;
758
+ return total;
759
+ }
760
+ get maxPendingRequests() {
761
+ return configuredPositiveInteger(this.clientOptions?.maxPendingRequests, DefaultMaxRequests);
762
+ }
763
+ get maxPendingRequestBytes() {
764
+ return configuredPositiveInteger(this.clientOptions?.maxPendingRequestBytes, DefaultMaxBytes);
765
+ }
766
+ get maxInFlightServerRequests() {
767
+ return configuredPositiveInteger(this.clientOptions?.maxInFlightServerRequests, DefaultMaxRequests);
768
+ }
769
+ get maxInFlightServerRequestBytes() {
770
+ return configuredPositiveInteger(this.clientOptions?.maxInFlightServerRequestBytes, DefaultMaxBytes);
771
+ }
772
+ get maxBufferedBytes() {
773
+ return configuredPositiveInteger(this.clientOptions?.maxBufferedBytes, DefaultMaxBytes);
774
+ }
775
+ get maxMessageBytes() {
776
+ return configuredPositiveInteger(this.clientOptions?.maxMessageBytes, DefaultMaxMessageBytes);
777
+ }
778
+ get connectTimeoutMs() {
779
+ const value = this.clientOptions?.connectTimeoutMs;
780
+ return value != null && Number.isSafeInteger(value) && value > 0 && value <= helpers_1.MAX_SAFE_TIMER_MS ? value : DefaultConnectTimeoutMs;
781
+ }
782
+ static __tsfType = _SrpcClientMetadata_1 = _a.decodeCompactMetadataV1("[1,{\"kind\":16,\"name\":\"SrpcClient\",\"typeName\":\"SrpcClient\",\"classType\":{\"$tsf\":0},\"properties\":[{\"name\":\"isConnected\",\"type\":{\"$tsfType\":0},\"optional\":false}],\"methods\":[{\"name\":\"connect\",\"parameters\":[{\"name\":\"options\",\"type\":{\"$tsfType\":1},\"optional\":true,\"default\":false}],\"returnType\":{\"$tsfType\":2}},{\"name\":\"disconnect\",\"parameters\":[],\"returnType\":{\"$tsfType\":3}},{\"name\":\"triggerConnectionCheck\",\"parameters\":[],\"returnType\":{\"$tsfType\":3}},{\"name\":\"resolveByteStream\",\"parameters\":[],\"returnType\":{\"$tsfType\":4}},{\"name\":\"registerConnectionHandler\",\"parameters\":[{\"name\":\"handler\",\"type\":{\"$tsfType\":5},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":3}},{\"name\":\"registerMessageHandler\",\"parameters\":[{\"name\":\"prefix\",\"type\":{\"$tsfType\":6},\"optional\":false,\"default\":false},{\"name\":\"handler\",\"type\":{\"$tsfType\":7},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":3}},{\"name\":\"registerDisconnectHandler\",\"parameters\":[{\"name\":\"handler\",\"type\":{\"$tsfType\":8},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":3}},{\"name\":\"invoke\",\"parameters\":[{\"name\":\"prefix\",\"type\":{\"$tsfType\":6},\"optional\":false,\"default\":false},{\"name\":\"data\",\"type\":{\"$tsfType\":9},\"optional\":false,\"default\":false},{\"name\":\"timeoutMs\",\"type\":{\"$tsfType\":0},\"optional\":true,\"default\":true}],\"returnType\":{\"$tsfType\":10}}],\"hasConstructor\":true,\"constructorParameters\":[{\"name\":\"logger\",\"type\":{\"$tsfType\":11},\"optional\":false,\"default\":false},{\"name\":\"uri\",\"type\":{\"$tsfType\":12},\"optional\":false,\"default\":false},{\"name\":\"clientMessage\",\"type\":{\"$tsfType\":13},\"optional\":false,\"default\":false},{\"name\":\"serverMessage\",\"type\":{\"$tsfType\":13},\"optional\":false,\"default\":false},{\"name\":\"clientId\",\"type\":{\"$tsfType\":12},\"optional\":false,\"default\":false},{\"name\":\"clientMeta\",\"type\":{\"$tsfType\":14},\"optional\":true,\"default\":false},{\"name\":\"clientSecret\",\"type\":{\"$tsfType\":12},\"optional\":true,\"default\":false},{\"name\":\"clientOptions\",\"type\":{\"$tsfType\":15},\"optional\":true,\"default\":false}]}]", [() => SrpcClient], __tsf_metadata_type);
395
783
  }
396
784
  exports.SrpcClient = SrpcClient;
397
785
  _SrpcClientMetadata_1.classType = SrpcClient;
@@ -407,6 +795,9 @@ function parseDisconnectCause(code) {
407
795
  return 'timeout';
408
796
  return 'disconnect';
409
797
  }
798
+ function closeCodeForCause(cause) {
799
+ return { disconnect: 1000, badArg: 4000, conflict: 4001, supersede: 4002, timeout: 4003 }[cause];
800
+ }
410
801
  function toBuffer(data) {
411
802
  if (Buffer.isBuffer(data))
412
803
  return data;
@@ -414,5 +805,52 @@ function toBuffer(data) {
414
805
  return Buffer.concat(data);
415
806
  return Buffer.from(data);
416
807
  }
417
- exports.__tsfTypeAliases = JSON.parse("[1,{\"SrpcClientOptions\":{\"kind\":18,\"typeName\":\"SrpcClientOptions\",\"types\":[{\"kind\":20,\"name\":\"enableReconnect\",\"type\":{\"kind\":12,\"types\":[{\"kind\":8},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"protocolVersion\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true}]}}]")[1];
808
+ function configuredPositiveInteger(value, fallback) {
809
+ return value != null && Number.isSafeInteger(value) && value > 0 ? value : fallback;
810
+ }
811
+ function validateClientResourceOptions(options) {
812
+ if (!options)
813
+ return;
814
+ for (const [name, value] of [
815
+ ['maxPendingRequests', options.maxPendingRequests],
816
+ ['maxPendingRequestBytes', options.maxPendingRequestBytes],
817
+ ['maxInFlightServerRequests', options.maxInFlightServerRequests],
818
+ ['maxInFlightServerRequestBytes', options.maxInFlightServerRequestBytes],
819
+ ['maxBufferedBytes', options.maxBufferedBytes],
820
+ ['maxMessageBytes', options.maxMessageBytes]
821
+ ]) {
822
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {
823
+ throw new Error(`sRPC client ${name} must be a positive integer`);
824
+ }
825
+ }
826
+ const timer = options.lateReplyTombstoneTtlMs;
827
+ if (timer !== undefined && (!Number.isSafeInteger(timer) || timer < 1 || timer > helpers_1.MAX_SAFE_TIMER_MS)) {
828
+ throw new Error(`sRPC client lateReplyTombstoneTtlMs must be a safe positive integer between 1 and ${helpers_1.MAX_SAFE_TIMER_MS}`);
829
+ }
830
+ const connectTimeout = options.connectTimeoutMs;
831
+ if (connectTimeout !== undefined && (!Number.isSafeInteger(connectTimeout) || connectTimeout < 1 || connectTimeout > helpers_1.MAX_SAFE_TIMER_MS)) {
832
+ throw new Error(`sRPC client connectTimeoutMs must be a safe positive integer between 1 and ${helpers_1.MAX_SAFE_TIMER_MS}`);
833
+ }
834
+ }
835
+ function assertTimeout(value) {
836
+ (0, helpers_1.assertSafeTimerMs)(value, 'Request timeout');
837
+ }
838
+ function normalizeFeatures(features) {
839
+ return [...new Set(features)].sort().join(',');
840
+ }
841
+ function normalizeMetadata(meta) {
842
+ return Object.fromEntries(Object.entries(meta ?? {})
843
+ .map(([key, value]) => [key, String(value)])
844
+ .sort(([a], [b]) => compareCodeUnits(a, b)));
845
+ }
846
+ function canonicalAuthV2(fields) {
847
+ return JSON.stringify({ version: 2, ...fields });
848
+ }
849
+ function compareCodeUnits(a, b) {
850
+ return a < b ? -1 : a > b ? 1 : 0;
851
+ }
852
+ function isPlainObject(value) {
853
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
854
+ }
855
+ exports.__tsfTypeAliases = JSON.parse("[1,{\"SrpcClientOptions\":{\"kind\":18,\"typeName\":\"SrpcClientOptions\",\"types\":[{\"kind\":20,\"name\":\"enableReconnect\",\"type\":{\"kind\":12,\"types\":[{\"kind\":8},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"authAudience\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"senderAnnouncements\",\"type\":{\"kind\":12,\"types\":[{\"kind\":8},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxPendingRequests\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxPendingRequestBytes\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxInFlightServerRequests\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxInFlightServerRequestBytes\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxBufferedBytes\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxMessageBytes\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"connectTimeoutMs\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"lateReplyTombstoneTtlMs\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true}]}}]")[1];
418
856
  //# sourceMappingURL=SrpcClient.js.map