hopwire 0.0.0-stage → 0.1.0

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 (85) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +8 -0
  3. package/README.md +29 -2
  4. package/dist/account.js +168 -0
  5. package/dist/agent/redact.js +101 -0
  6. package/dist/agent/summary.js +32 -0
  7. package/dist/agent-socket.js +93 -0
  8. package/dist/bin.js +22 -0
  9. package/dist/body-capture.js +28 -0
  10. package/dist/browser.js +42 -0
  11. package/dist/cli.js +674 -0
  12. package/dist/commands/connect.js +221 -0
  13. package/dist/commands/doctor.js +107 -0
  14. package/dist/commands/http.js +108 -0
  15. package/dist/commands/login.js +133 -0
  16. package/dist/commands/mcp.js +69 -0
  17. package/dist/commands/rotate.js +57 -0
  18. package/dist/commands/up.js +149 -0
  19. package/dist/commands/watch.js +146 -0
  20. package/dist/config.js +302 -0
  21. package/dist/control-plane-client.js +300 -0
  22. package/dist/data-dir-holder.js +178 -0
  23. package/dist/edge-bridge.js +1031 -0
  24. package/dist/errors.js +53 -0
  25. package/dist/identity.js +134 -0
  26. package/dist/inspector/THIRD-PARTY-NOTICES.txt +330 -0
  27. package/dist/inspector/assets/index-BvwyMIFs.css +2 -0
  28. package/dist/inspector/assets/index-Ctrz3UJp.js +2 -0
  29. package/dist/inspector/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  30. package/dist/inspector/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
  31. package/dist/inspector/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  32. package/dist/inspector/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
  33. package/dist/inspector/assets/space-grotesk-latin-400-normal-CJ-V5oYT.woff2 +0 -0
  34. package/dist/inspector/assets/space-grotesk-latin-500-normal-lFbtlQH6.woff2 +0 -0
  35. package/dist/inspector/assets/space-grotesk-latin-ext-400-normal-CfP_5XZW.woff2 +0 -0
  36. package/dist/inspector/assets/space-grotesk-latin-ext-500-normal-DUe3BAxM.woff2 +0 -0
  37. package/dist/inspector/favicon.svg +1 -0
  38. package/dist/inspector/index.html +16 -0
  39. package/dist/inspector-api.js +508 -0
  40. package/dist/inspector-server.js +150 -0
  41. package/dist/interceptor.js +480 -0
  42. package/dist/log.js +393 -0
  43. package/dist/main.js +37 -0
  44. package/dist/mcp/body.js +134 -0
  45. package/dist/mcp/client.js +169 -0
  46. package/dist/mcp/jsonrpc.js +170 -0
  47. package/dist/mcp/tools.js +715 -0
  48. package/dist/output.js +249 -0
  49. package/dist/p2p-stream.js +226 -0
  50. package/dist/p2p.js +389 -0
  51. package/dist/prompt.js +62 -0
  52. package/dist/proxy-server.js +252 -0
  53. package/dist/serve.js +234 -0
  54. package/dist/style.js +60 -0
  55. package/dist/supervisor.js +146 -0
  56. package/dist/team-keys.js +129 -0
  57. package/dist/update-notice.js +67 -0
  58. package/dist/urls.js +45 -0
  59. package/dist/websocket.js +99 -0
  60. package/node_modules/@hopwire/protocol/LICENSE +201 -0
  61. package/node_modules/@hopwire/protocol/NOTICE +8 -0
  62. package/node_modules/@hopwire/protocol/dist/basic-auth.d.ts +9 -0
  63. package/node_modules/@hopwire/protocol/dist/basic-auth.js +21 -0
  64. package/node_modules/@hopwire/protocol/dist/constants.d.ts +91 -0
  65. package/node_modules/@hopwire/protocol/dist/constants.js +89 -0
  66. package/node_modules/@hopwire/protocol/dist/exchange.d.ts +54 -0
  67. package/node_modules/@hopwire/protocol/dist/exchange.js +71 -0
  68. package/node_modules/@hopwire/protocol/dist/frames.d.ts +177 -0
  69. package/node_modules/@hopwire/protocol/dist/frames.js +191 -0
  70. package/node_modules/@hopwire/protocol/dist/headers.d.ts +20 -0
  71. package/node_modules/@hopwire/protocol/dist/headers.js +58 -0
  72. package/node_modules/@hopwire/protocol/dist/index.d.ts +10 -0
  73. package/node_modules/@hopwire/protocol/dist/index.js +10 -0
  74. package/node_modules/@hopwire/protocol/dist/inspector.d.ts +46 -0
  75. package/node_modules/@hopwire/protocol/dist/inspector.js +42 -0
  76. package/node_modules/@hopwire/protocol/dist/p2p.d.ts +52 -0
  77. package/node_modules/@hopwire/protocol/dist/p2p.js +119 -0
  78. package/node_modules/@hopwire/protocol/dist/plan.d.ts +104 -0
  79. package/node_modules/@hopwire/protocol/dist/plan.js +180 -0
  80. package/node_modules/@hopwire/protocol/dist/subdomain.d.ts +10 -0
  81. package/node_modules/@hopwire/protocol/dist/subdomain.js +30 -0
  82. package/node_modules/@hopwire/protocol/dist/websocket.d.ts +70 -0
  83. package/node_modules/@hopwire/protocol/dist/websocket.js +113 -0
  84. package/node_modules/@hopwire/protocol/package.json +13 -0
  85. package/package.json +38 -5
@@ -0,0 +1,1031 @@
1
+ import { WebSocket } from 'ws';
2
+ import { BASIC_AUTH_HEADER, CHUNK_SIZE_BYTES, CLOSE_CODE_IDLE, CLOSE_CODE_REPLACED, CLOSE_CODE_TOKEN_EXPIRED, EDGE_CONNECT_PATH, FLOW_ACK_BYTES, FLOW_WINDOW_BYTES, KEEPALIVE_HEADER, KEEPALIVE_INTERVAL_MS, KEEPALIVE_MISSED_PONGS, PUBLIC_URL_HEADER, ProtocolError, RECONNECT_BACKOFF_MS, TOKEN_EXPIRES_IN_HEADER, USAGE_HEADER, WS_CLOSE, WS_MESSAGE_MAX_BYTES, closeReason, decodeEdgeToCliMessage, decodeUsageSnapshot, encodeMessage, getHeader, isBase64, keepaliveTexts, webSocketMessageCost, } from '@hopwire/protocol';
3
+ import { TemporaryError, HopwireError } from './errors.js';
4
+ import { printable } from './output.js';
5
+ import { closeLike, onceClosed } from './websocket.js';
6
+ /**
7
+ * Public mode on the wire. This is the only module that opens a connection
8
+ * to the edge; `hopwire http` loads it only for --public, so private mode
9
+ * never contacts the edge.
10
+ *
11
+ * The bridge holds one WebSocket to the edge, opened outbound. Every public
12
+ * request arrives on it as frames and goes through the interceptor with
13
+ * source `public_edge`; the response goes back as frames with the same reqId.
14
+ *
15
+ * A public client's WebSocket arrives the same way (`ws_open`) and goes
16
+ * through the interceptor as well: it opens a WebSocket to the local service,
17
+ * and from the service's 101 on the bridge carries the messages and the close
18
+ * of that connection as frames in both directions. A service that does not
19
+ * accept is answered like a request.
20
+ *
21
+ * A token that expires (a connect token of the control plane) is renewed on
22
+ * the open socket before it runs out: the edge says how long a token counts,
23
+ * the bridge fetches a new one when half of that time has passed and sends it
24
+ * as a frame. The socket, and every request in flight on it, lives on. Only
25
+ * when no new token reached the edge in time does the edge close the socket
26
+ * (4001), and the bridge comes back with a new token and a new socket.
27
+ */
28
+ /** How long the edge may take to answer the upgrade request. */
29
+ const HANDSHAKE_TIMEOUT_MS = 15_000;
30
+ /** Largest frame the bridge accepts: a chunk frame is about 90 kB, a start frame carries the request headers. */
31
+ const MAX_FRAME_BYTES = 4 * 1024 * 1024;
32
+ /** How long `close` waits for the edge to confirm the close before the socket is dropped. */
33
+ const CLOSE_TIMEOUT_MS = 2_000;
34
+ /**
35
+ * How long the connection may stay open after both close frames went over it. A close of the edge (4000, 4001) is
36
+ * only acted on when the connection is gone, and an edge may leave it open for seconds after the handshake (the
37
+ * Workers edge did).
38
+ */
39
+ const CLOSE_HANDSHAKE_TIMEOUT_MS = 500;
40
+ /**
41
+ * A token is renewed once this share of the time it still counts has passed. The rest is the time a control plane
42
+ * that cannot be reached may take to come back before the edge closes the socket.
43
+ */
44
+ const RENEW_AFTER_SHARE = 0.5;
45
+ /** The longest wait of a timer, about 24 days. */
46
+ const MAX_TIMER_MS = 2 ** 31 - 1;
47
+ /** Longest answer of a refused connect request that is read: the edge says why in one sentence. */
48
+ const MAX_REFUSAL_BYTES = 1024;
49
+ /**
50
+ * Connects to the edge and serves the subdomain until `close`. Rejects with
51
+ * a HopwireError when the first connection does not come about; after that a
52
+ * lost connection is taken up again with exponential backoff and jitter.
53
+ */
54
+ export async function startEdgeBridge(options) {
55
+ const timing = {
56
+ keepaliveIntervalMs: KEEPALIVE_INTERVAL_MS,
57
+ missedPongs: KEEPALIVE_MISSED_PONGS,
58
+ backoffInitialMs: RECONNECT_BACKOFF_MS.initial,
59
+ backoffMaxMs: RECONNECT_BACKOFF_MS.max,
60
+ random: Math.random,
61
+ handshakeTimeoutMs: HANDSHAKE_TIMEOUT_MS,
62
+ ...options.timing,
63
+ };
64
+ const { subdomain, interceptor } = options;
65
+ const edge = options.edgeUrl.origin;
66
+ const proto = forwardedProto(options.edgeUrl);
67
+ let token = options.token;
68
+ /**
69
+ * True while the current token must not be offered again: the edge refused it (401, 403) or said that it is
70
+ * over (4001). The next attempt starts with a new token
71
+ */
72
+ let stale = false;
73
+ /** True while a lost connection was reported and its return was not */
74
+ let reportedLost = false;
75
+ let closed = false;
76
+ let socket = null;
77
+ /** The socket of an attempt the edge has not answered yet */
78
+ let pending = null;
79
+ let keepalive = null;
80
+ let retry = null;
81
+ /** The next renewal of the token on the open socket, ahead of its expiry */
82
+ let renewal = null;
83
+ /** Renewals ahead of time in a row for which the control plane could not be reached */
84
+ let renewalFailures = 0;
85
+ /** Failed attempts since the last open socket */
86
+ let failures = 0;
87
+ /** The tenth of the metered usage cap last reported (from the connect answer, then the frames) */
88
+ let meteredStep = 0;
89
+ let meteredMonth = null;
90
+ /** Requests of the current socket by reqId: bodies still arriving and responses still being sent */
91
+ const bodies = new Map();
92
+ const flights = new Map();
93
+ /** WebSockets of the current socket by reqId: the ones the local service accepted and the ones still asked for */
94
+ const tunneled = new Map();
95
+ /** WebSockets to the local service that are not read while the socket to the edge has a window of frames unsent */
96
+ const held = new Set();
97
+ /** Whether metered usage passed a tenth of the cap it was not reported at yet; it counts as reported from now on. */
98
+ const passedStep = (metered) => {
99
+ if (metered.month !== meteredMonth) {
100
+ meteredMonth = metered.month;
101
+ meteredStep = 0;
102
+ }
103
+ const step = metered.capMinor > 0 ? Math.min(10, Math.floor((metered.costMinor * 10) / metered.capMinor)) : 0;
104
+ if (step <= meteredStep) {
105
+ return false;
106
+ }
107
+ meteredStep = step;
108
+ return true;
109
+ };
110
+ let end = () => { };
111
+ const ended = new Promise((resolve) => {
112
+ end = resolve;
113
+ });
114
+ const connectOnce = () => {
115
+ const url = new URL(EDGE_CONNECT_PATH, options.edgeUrl);
116
+ url.searchParams.set('subdomain', subdomain);
117
+ // closeTimeout is an option of ws 8.19 and later that its type definitions do not list yet
118
+ const socketOptions = {
119
+ headers: {
120
+ authorization: `Bearer ${token}`,
121
+ ...(options.basicAuth === undefined
122
+ ? {}
123
+ : { [BASIC_AUTH_HEADER]: Buffer.from(options.basicAuth, 'utf8').toString('base64') }),
124
+ },
125
+ perMessageDeflate: false,
126
+ handshakeTimeout: timing.handshakeTimeoutMs,
127
+ closeTimeout: CLOSE_HANDSHAKE_TIMEOUT_MS,
128
+ maxPayload: MAX_FRAME_BYTES,
129
+ followRedirects: false,
130
+ };
131
+ const candidate = new WebSocket(url, socketOptions);
132
+ pending = candidate;
133
+ return new Promise((resolve) => {
134
+ let publicUrl = null;
135
+ let usage = null;
136
+ let tokenExpiresInMs = null;
137
+ let keepaliveValue = null;
138
+ candidate.once('upgrade', (response) => {
139
+ const header = response.headers[PUBLIC_URL_HEADER.toLowerCase()];
140
+ publicUrl = typeof header === 'string' && header !== '' ? header : null;
141
+ const usageHeader = response.headers[USAGE_HEADER.toLowerCase()];
142
+ usage = typeof usageHeader === 'string' ? decodeUsageSnapshot(usageHeader) : null;
143
+ tokenExpiresInMs = durationOf(response.headers[TOKEN_EXPIRES_IN_HEADER.toLowerCase()]);
144
+ const keepaliveHeader = response.headers[KEEPALIVE_HEADER.toLowerCase()];
145
+ keepaliveValue =
146
+ typeof keepaliveHeader === 'string' && KEEPALIVE_VALUE.test(keepaliveHeader)
147
+ ? keepaliveHeader
148
+ : null;
149
+ });
150
+ candidate.once('open', () => {
151
+ if (closed) {
152
+ candidate.terminate();
153
+ resolve({ kind: 'unreachable', code: 'CLOSED' });
154
+ return;
155
+ }
156
+ // Within the event itself: the first frames may arrive in the same read as the answer to the upgrade
157
+ adopt(candidate, tokenExpiresInMs, keepaliveTexts(keepaliveValue));
158
+ const metered = usage?.metered;
159
+ if (metered !== undefined) {
160
+ // What was passed before this connection is known from the Usage line; only further steps are told
161
+ passedStep(metered);
162
+ }
163
+ resolve({ kind: 'open', publicUrl, usage });
164
+ });
165
+ candidate.once('unexpected-response', (_request, response) => {
166
+ // The edge says in one sentence why it refused; no more of the answer than that is read
167
+ const chunks = [];
168
+ let length = 0;
169
+ const done = () => {
170
+ resolve({
171
+ kind: 'refused',
172
+ status: response.statusCode ?? 0,
173
+ body: Buffer.concat(chunks).toString('utf8').trim(),
174
+ });
175
+ candidate.terminate();
176
+ };
177
+ response.on('data', (chunk) => {
178
+ if (length < MAX_REFUSAL_BYTES) {
179
+ chunks.push(chunk.subarray(0, MAX_REFUSAL_BYTES - length));
180
+ length += chunk.length;
181
+ }
182
+ });
183
+ response.once('end', done);
184
+ response.once('error', done);
185
+ response.once('close', done);
186
+ });
187
+ // Also emitted after one of the outcomes above (a settled promise ignores it), and it stays the error
188
+ // listener of the socket for as long as it lives: its `close` event is what the bridge acts on
189
+ candidate.on('error', (error) => resolve({ kind: 'unreachable', code: errorCode(error) }));
190
+ }).finally(() => {
191
+ if (pending === candidate) {
192
+ pending = null;
193
+ }
194
+ });
195
+ };
196
+ /** The sentence for an answer of the edge that no retry can change, null when trying again makes sense. */
197
+ const refusal = (status, body = '') => {
198
+ if (status === 429) {
199
+ // All tunnels of the organisation's plan are online: the edge names them; trying again changes nothing
200
+ const said = printable(body.split('\n')[0] ?? '').slice(0, 300);
201
+ return new HopwireError(said !== ''
202
+ ? said
203
+ : `The edge at ${edge} refused the tunnel for ${subdomain} (429): your organisation has all tunnels of its plan online; stop one of them first.`);
204
+ }
205
+ if (status === 401) {
206
+ return new HopwireError(options.renewToken === undefined
207
+ ? `The edge at ${edge} refused the token (401); check the token and that it belongs to this edge.`
208
+ : `The edge at ${edge} refused the token (401), and a new one from the control plane as well; check that this edge belongs to the control plane you are logged in to.`);
209
+ }
210
+ if (status === 403) {
211
+ return new HopwireError(`The token does not allow the subdomain ${subdomain} (403); use the subdomain the token was issued for.`);
212
+ }
213
+ if (status === 400) {
214
+ return new HopwireError(`The edge at ${edge} refused the connect request for the subdomain ${subdomain} as malformed (400); check the subdomain and that CLI and edge are the same version.`);
215
+ }
216
+ return null;
217
+ };
218
+ /**
219
+ * One attempt, and after a 401 or 403 one more with a new token when there is a way to get one: a refused token
220
+ * is not offered a second time. After the edge said that the token is over (4001) the new token is fetched
221
+ * first. Without a new token the edge is not asked at all.
222
+ *
223
+ * The new token is offered right after it was fetched, and that attempt is the answer: a 401 or 403 for it is
224
+ * final, which is the one renewal per refusal. A token that was fetched but could not be judged (the edge was
225
+ * away) and is refused on a later attempt, having grown old in between, is a refusal of its own.
226
+ */
227
+ const connect = async () => {
228
+ if (!stale) {
229
+ const attempt = await connectOnce();
230
+ const refusedToken = attempt.kind === 'refused' && (attempt.status === 401 || attempt.status === 403);
231
+ if (!refusedToken || options.renewToken === undefined || closed) {
232
+ return attempt;
233
+ }
234
+ stale = true;
235
+ }
236
+ if (options.renewToken === undefined) {
237
+ return connectOnce();
238
+ }
239
+ try {
240
+ token = await options.renewToken();
241
+ }
242
+ catch (error) {
243
+ return { kind: 'no-token', error };
244
+ }
245
+ stale = false;
246
+ if (closed) {
247
+ // Closed while the token was fetched: no attempt is made for a bridge nobody waits for
248
+ return { kind: 'unreachable', code: 'CLOSED' };
249
+ }
250
+ return connectOnce();
251
+ };
252
+ /** The sentence the bridge gives up with when no new token could be fetched. */
253
+ const withoutToken = (error) => error instanceof HopwireError
254
+ ? error
255
+ : new HopwireError(`No new token could be fetched for the subdomain ${subdomain}, so the edge at ${edge} no longer serves it; start the tunnel again.`);
256
+ /**
257
+ * Renews the token of the open socket ahead of its expiry: a new token is fetched and sent to the edge as a
258
+ * frame, and the edge answers with the time the socket now lasts (token_renewed), which sets the next renewal.
259
+ * Without that answer (an edge that does not take the token) nothing follows, and the edge ends the socket
260
+ * with 4001 when the old token runs out.
261
+ */
262
+ const renewAhead = async (on) => {
263
+ const renewToken = options.renewToken;
264
+ if (renewToken === undefined || socket !== on || closed) {
265
+ return;
266
+ }
267
+ let fresh;
268
+ try {
269
+ fresh = await renewToken();
270
+ }
271
+ catch (error) {
272
+ if (socket !== on || closed) {
273
+ return;
274
+ }
275
+ if (error instanceof TemporaryError) {
276
+ // The control plane is away for the moment: it is asked again while the token in use still counts
277
+ scheduleRenewal(on, reconnectDelayMs(renewalFailures++, timing));
278
+ return;
279
+ }
280
+ // The control plane said no for good (a revoked API token, a released subdomain): the tunnel ends now
281
+ // and not when the edge would close it, so "ended" always means that the subdomain is no longer served
282
+ giveUp(withoutToken(error));
283
+ on.close(1000);
284
+ return;
285
+ }
286
+ if (socket !== on || closed) {
287
+ // The socket went away meanwhile; what follows fetches its own token
288
+ return;
289
+ }
290
+ renewalFailures = 0;
291
+ // Also the token of the next connect request, should the socket be lost
292
+ token = fresh;
293
+ await send(on, { type: 'token_renew', token: fresh }).catch(() => { });
294
+ };
295
+ const scheduleRenewal = (on, delayMs) => {
296
+ if (options.renewToken === undefined) {
297
+ return;
298
+ }
299
+ cancelRenewal();
300
+ renewal = setTimeout(() => {
301
+ renewal = null;
302
+ void renewAhead(on);
303
+ },
304
+ // A timer cannot wait longer; a longer wait would run at once
305
+ Math.min(delayMs, MAX_TIMER_MS));
306
+ };
307
+ const cancelRenewal = () => {
308
+ if (renewal !== null) {
309
+ clearTimeout(renewal);
310
+ renewal = null;
311
+ }
312
+ };
313
+ const adopt = (opened, tokenExpiresInMs, keepaliveText) => {
314
+ socket = opened;
315
+ failures = 0;
316
+ renewalFailures = 0;
317
+ if (tokenExpiresInMs !== null) {
318
+ scheduleRenewal(opened, tokenExpiresInMs * RENEW_AFTER_SHARE);
319
+ }
320
+ let missed = 0;
321
+ keepalive = setInterval(() => {
322
+ if (missed >= timing.missedPongs) {
323
+ // The edge stopped answering: drop the socket, its close starts the reconnect
324
+ opened.terminate();
325
+ return;
326
+ }
327
+ missed++;
328
+ if (opened.readyState === WebSocket.OPEN) {
329
+ opened.send(keepaliveText.ping);
330
+ }
331
+ }, timing.keepaliveIntervalMs);
332
+ opened.on('message', (data, isBinary) => {
333
+ if (isBinary) {
334
+ return;
335
+ }
336
+ const text = data.toString('utf8');
337
+ if (text === keepaliveText.pong) {
338
+ missed = 0;
339
+ return;
340
+ }
341
+ let frame;
342
+ try {
343
+ frame = decodeEdgeToCliMessage(text);
344
+ }
345
+ catch (error) {
346
+ if (error instanceof ProtocolError) {
347
+ // Not a frame of this protocol version; nothing to match it to
348
+ return;
349
+ }
350
+ throw error;
351
+ }
352
+ handle(opened, frame);
353
+ });
354
+ opened.once('close', (code) => lost(opened, code));
355
+ };
356
+ const handle = (from, frame) => {
357
+ switch (frame.type) {
358
+ case 'token_renewed':
359
+ // The edge took the new token: the next one is due when half of its time has passed
360
+ if (from === socket && !closed) {
361
+ scheduleRenewal(from, frame.expiresInMs * RENEW_AFTER_SHARE);
362
+ }
363
+ return;
364
+ case 'limit_reached':
365
+ if (from === socket && !closed) {
366
+ options.onEvent?.({ type: 'limit_reached', meter: frame.meter, resetsInMs: frame.resetsInMs });
367
+ }
368
+ return;
369
+ case 'metered_usage': {
370
+ const metered = {
371
+ month: frame.month,
372
+ currency: frame.currency,
373
+ costMinor: frame.costMinor,
374
+ capMinor: frame.capMinor,
375
+ capped: frame.capped,
376
+ };
377
+ // The cap itself is told by limit_reached
378
+ if (from === socket && !closed && passedStep(metered) && !metered.capped) {
379
+ options.onEvent?.({ type: 'metered_usage', metered });
380
+ }
381
+ return;
382
+ }
383
+ case 'http_request_start': {
384
+ const { reqId } = frame;
385
+ if (bodies.has(reqId) || flights.has(reqId) || tunneled.has(reqId)) {
386
+ return;
387
+ }
388
+ let body = null;
389
+ if (frame.hasBody) {
390
+ body = new BodyQueue(
391
+ // What the local service has taken is reported, so the edge sends no more than a window ahead
392
+ (bytes) => void send(from, { type: 'http_request_ack', reqId, bytes }).catch(() => { }), () => bodies.delete(reqId));
393
+ bodies.set(reqId, body);
394
+ }
395
+ const flight = newFlight();
396
+ flights.set(reqId, flight);
397
+ void serve(from, frame, body, flight).finally(() => {
398
+ if (flights.get(reqId) === flight) {
399
+ flights.delete(reqId);
400
+ }
401
+ });
402
+ return;
403
+ }
404
+ case 'http_request_chunk': {
405
+ const body = bodies.get(frame.reqId);
406
+ if (body === undefined) {
407
+ return;
408
+ }
409
+ if (!isBase64(frame.chunkBase64)) {
410
+ body.fail(new Error('The edge sent a body chunk that is not Base64'));
411
+ return;
412
+ }
413
+ body.push(Buffer.from(frame.chunkBase64, 'base64'));
414
+ return;
415
+ }
416
+ case 'http_request_end':
417
+ bodies.get(frame.reqId)?.end();
418
+ return;
419
+ case 'http_response_ack': {
420
+ const flight = flights.get(frame.reqId);
421
+ if (flight !== undefined) {
422
+ flight.acknowledged = Math.max(flight.acknowledged, frame.bytes);
423
+ flight.wake?.();
424
+ }
425
+ return;
426
+ }
427
+ case 'http_request_cancel': {
428
+ // The edge gave the request up: the client went away or the edge stopped waiting
429
+ abort(flights.get(frame.reqId));
430
+ bodies.get(frame.reqId)?.fail(new Error('The edge gave the request up'));
431
+ // Also an upgrade the local service has not answered yet
432
+ const asked = tunneled.get(frame.reqId);
433
+ if (asked !== undefined && asked.upstream === null) {
434
+ tunneled.delete(frame.reqId);
435
+ abort(asked.flight);
436
+ }
437
+ return;
438
+ }
439
+ case 'ws_open': {
440
+ const { reqId } = frame;
441
+ if (bodies.has(reqId) || flights.has(reqId) || tunneled.has(reqId)) {
442
+ return;
443
+ }
444
+ void openSocket(from, frame);
445
+ return;
446
+ }
447
+ case 'ws_message':
448
+ deliver(from, frame);
449
+ return;
450
+ case 'ws_close': {
451
+ // The public client closed its end, or the edge closed the connection
452
+ const entry = tunneled.get(frame.reqId);
453
+ if (entry === undefined) {
454
+ return;
455
+ }
456
+ tunneled.delete(frame.reqId);
457
+ if (entry.upstream === null) {
458
+ abort(entry.flight);
459
+ }
460
+ else {
461
+ // Read again should it be held back: the closing handshake needs the answer of the service
462
+ held.delete(entry.upstream);
463
+ entry.upstream.resume();
464
+ closeLike(entry.upstream, frame.code, frame.reason);
465
+ }
466
+ return;
467
+ }
468
+ }
469
+ };
470
+ const newFlight = () => ({
471
+ aborted: false,
472
+ abandoned: new AbortController(),
473
+ sent: 0,
474
+ acknowledged: 0,
475
+ wake: null,
476
+ });
477
+ /**
478
+ * Sends a frame. When it has left this machine, the WebSockets to the local service that were held back for
479
+ * the socket to the edge are read again, provided the frames waiting to be sent have dropped below half a
480
+ * window.
481
+ */
482
+ const send = async (to, message) => {
483
+ await sendFrame(to, message);
484
+ if (held.size > 0 && to.bufferedAmount <= FLOW_WINDOW_BYTES / 2) {
485
+ for (const upstream of held) {
486
+ upstream.resume();
487
+ }
488
+ held.clear();
489
+ }
490
+ };
491
+ /**
492
+ * ws_open: a public client asks for a WebSocket. The interceptor asks the local service. With its 101 the
493
+ * edge is told (ws_accept, with the subprotocol the service chose) and upgrades the client; any other answer
494
+ * goes back like the response to a request, and the client gets that instead of an upgrade.
495
+ */
496
+ const openSocket = async (to, frame) => {
497
+ const { reqId } = frame;
498
+ const entry = { flight: newFlight(), upstream: null, arriving: null, unreported: 0 };
499
+ tunneled.set(reqId, entry);
500
+ /** False once the edge took the upgrade back or its socket is gone */
501
+ const wanted = () => tunneled.get(reqId) === entry && !entry.flight.aborted;
502
+ let outcome;
503
+ try {
504
+ outcome = await interceptor.upgrade({
505
+ path: frame.path,
506
+ headers: withForwardedHeaders(frame.headers, proto),
507
+ source: 'public_edge',
508
+ signal: entry.flight.abandoned.signal,
509
+ });
510
+ }
511
+ catch {
512
+ if (wanted()) {
513
+ tunneled.delete(reqId);
514
+ await send(to, {
515
+ type: 'http_response_error',
516
+ reqId,
517
+ status: 502,
518
+ message: 'Hopwire: the request could not be forwarded',
519
+ }).catch(() => { });
520
+ }
521
+ return;
522
+ }
523
+ if (!outcome.accepted) {
524
+ // An ordinary answer; from here on the upgrade is a request that is being answered
525
+ const { response } = outcome;
526
+ const flight = entry.flight;
527
+ if (tunneled.get(reqId) === entry) {
528
+ tunneled.delete(reqId);
529
+ flights.set(reqId, flight);
530
+ }
531
+ await answer(to, reqId, flight, async () => response).finally(() => {
532
+ if (flights.get(reqId) === flight) {
533
+ flights.delete(reqId);
534
+ }
535
+ });
536
+ return;
537
+ }
538
+ const upstream = outcome.socket;
539
+ if (!wanted()) {
540
+ upstream.terminate();
541
+ return;
542
+ }
543
+ entry.upstream = upstream;
544
+ void send(to, { type: 'ws_accept', reqId, protocol: outcome.protocol, headers: outcome.headers }).catch(() => { });
545
+ upstream.on('message', (data, isBinary) => {
546
+ if (tunneled.get(reqId) !== entry) {
547
+ return;
548
+ }
549
+ // In pieces of a chunk, like a body: one frame stays small whatever the message
550
+ let offset = 0;
551
+ do {
552
+ const piece = data.subarray(offset, offset + CHUNK_SIZE_BYTES);
553
+ const first = offset === 0;
554
+ offset += piece.length;
555
+ void send(to, {
556
+ type: 'ws_message',
557
+ reqId,
558
+ binary: isBinary,
559
+ dataBase64: piece.toString('base64'),
560
+ first,
561
+ final: offset >= data.length,
562
+ }).catch(() => { });
563
+ } while (offset < data.length);
564
+ // A service that sends faster than the frames leave is not read until they have
565
+ if (to.bufferedAmount > FLOW_WINDOW_BYTES) {
566
+ upstream.pause();
567
+ held.add(upstream);
568
+ }
569
+ });
570
+ onceClosed(upstream, (code, reason) => {
571
+ held.delete(upstream);
572
+ if (tunneled.get(reqId) !== entry) {
573
+ // Closed from the other side: the edge knows
574
+ return;
575
+ }
576
+ tunneled.delete(reqId);
577
+ void send(to, { type: 'ws_close', reqId, code, reason: closeReason(reason) }).catch(() => { });
578
+ });
579
+ // Paused by the interceptor until somebody listens
580
+ upstream.resume();
581
+ };
582
+ /** ws_message: one piece of a message of the public client; the whole message goes to the local service. */
583
+ const deliver = (from, frame) => {
584
+ const { reqId } = frame;
585
+ const entry = tunneled.get(reqId);
586
+ const upstream = entry?.upstream ?? null;
587
+ if (entry === undefined || upstream === null) {
588
+ return;
589
+ }
590
+ /** The connection cannot go on: both ends are closed with the code */
591
+ const end = (code) => {
592
+ tunneled.delete(reqId);
593
+ held.delete(upstream);
594
+ upstream.resume();
595
+ closeLike(upstream, code, '');
596
+ void send(from, { type: 'ws_close', reqId, code, reason: '' }).catch(() => { });
597
+ };
598
+ if (!isBase64(frame.dataBase64) || frame.first !== (entry.arriving === null)) {
599
+ // Not Base64, a piece without a beginning, or a beginning inside another message
600
+ end(WS_CLOSE.internalError);
601
+ return;
602
+ }
603
+ const arriving = entry.arriving ?? { binary: frame.binary, pieces: [], bytes: 0 };
604
+ const piece = Buffer.from(frame.dataBase64, 'base64');
605
+ arriving.pieces.push(piece);
606
+ arriving.bytes += piece.length;
607
+ if (arriving.bytes > WS_MESSAGE_MAX_BYTES) {
608
+ end(WS_CLOSE.messageTooBig);
609
+ return;
610
+ }
611
+ if (!frame.final) {
612
+ entry.arriving = arriving;
613
+ return;
614
+ }
615
+ entry.arriving = null;
616
+ // Counted the way the edge counted it when it sent the message: payload plus the fixed amount per message
617
+ const bytes = webSocketMessageCost(arriving.bytes);
618
+ upstream.send(Buffer.concat(arriving.pieces), { binary: arriving.binary }, (error) => {
619
+ if (error || tunneled.get(reqId) !== entry) {
620
+ return;
621
+ }
622
+ // What the local service took is reported, which is what lets the edge go on sending for this client
623
+ entry.unreported += bytes;
624
+ if (entry.unreported >= FLOW_ACK_BYTES) {
625
+ void send(from, { type: 'ws_ack', reqId, bytes: entry.unreported }).catch(() => { });
626
+ entry.unreported = 0;
627
+ }
628
+ });
629
+ };
630
+ /** Nobody wants the response any more: nothing more is sent, and the request ends at the local service. */
631
+ const abort = (flight) => {
632
+ if (flight !== undefined && !flight.aborted) {
633
+ flight.aborted = true;
634
+ // Ends the request whatever it waits for: the answer of the service, more of it, or room for its body
635
+ flight.abandoned.abort();
636
+ flight.wake?.();
637
+ }
638
+ };
639
+ /** Runs one public request through the interceptor and sends the response back as frames. */
640
+ const serve = (to, frame, body, flight) => answer(to, frame.reqId, flight, () => interceptor.forward({
641
+ method: frame.method,
642
+ path: frame.path,
643
+ headers: withForwardedHeaders(frame.headers, proto),
644
+ body,
645
+ source: 'public_edge',
646
+ signal: flight.abandoned.signal,
647
+ }));
648
+ /** Sends the response `respond` produces back as frames: start, the body in chunks within the window, end. */
649
+ const answer = async (to, reqId, flight, respond) => {
650
+ try {
651
+ const response = await respond();
652
+ if (!flight.aborted) {
653
+ await send(to, {
654
+ type: 'http_response_start',
655
+ reqId,
656
+ status: response.status,
657
+ headers: response.headers,
658
+ });
659
+ }
660
+ // Leaving the loop early ends the answer of the local service, so nothing is read for a lost socket
661
+ for await (const chunk of response.body) {
662
+ if (flight.aborted) {
663
+ break;
664
+ }
665
+ for (let offset = 0; offset < chunk.length && !flight.aborted; offset += CHUNK_SIZE_BYTES) {
666
+ // No more than a window ahead of what the public client has taken from the edge
667
+ while (!flight.aborted && flight.sent - flight.acknowledged >= FLOW_WINDOW_BYTES) {
668
+ await new Promise((resolve) => {
669
+ flight.wake = resolve;
670
+ });
671
+ }
672
+ if (flight.aborted) {
673
+ break;
674
+ }
675
+ const piece = chunk.subarray(offset, offset + CHUNK_SIZE_BYTES);
676
+ await send(to, { type: 'http_response_chunk', reqId, chunkBase64: piece.toString('base64') });
677
+ flight.sent += piece.length;
678
+ }
679
+ if (flight.aborted) {
680
+ break;
681
+ }
682
+ }
683
+ if (!flight.aborted) {
684
+ await send(to, { type: 'http_response_end', reqId });
685
+ }
686
+ }
687
+ catch {
688
+ if (!flight.aborted) {
689
+ // Before the start the edge answers with this status, after it the edge breaks the body off
690
+ await send(to, {
691
+ type: 'http_response_error',
692
+ reqId,
693
+ status: 502,
694
+ message: 'Hopwire: the request could not be forwarded',
695
+ }).catch(() => { });
696
+ }
697
+ // Also when a frame could not be sent before the answer was read at all (a socket that is closing):
698
+ // the request ends at the local service instead of keeping its connection there
699
+ flight.abandoned.abort();
700
+ // No end of the request body is waited for after an answer that failed: what is held for it is let go
701
+ bodies.get(reqId)?.fail(new Error('The answer to the request failed'));
702
+ }
703
+ };
704
+ /** The socket is gone: its requests fail on this side too, then the reason decides what follows. */
705
+ const lost = (gone, code) => {
706
+ if (socket !== gone) {
707
+ return;
708
+ }
709
+ socket = null;
710
+ if (keepalive !== null) {
711
+ clearInterval(keepalive);
712
+ keepalive = null;
713
+ }
714
+ cancelRenewal();
715
+ failInFlight();
716
+ if (closed) {
717
+ return;
718
+ }
719
+ if (code === CLOSE_CODE_IDLE) {
720
+ giveUp(new HopwireError(`The edge closed the tunnel for ${subdomain} after 24 hours without a request, as the plan of your organisation does; start Hopwire again to reconnect it.`));
721
+ return;
722
+ }
723
+ if (code === CLOSE_CODE_REPLACED) {
724
+ giveUp(new HopwireError(`Another tunnel connected for the subdomain ${subdomain} and replaced this one; stop one of the two or use another subdomain.`));
725
+ return;
726
+ }
727
+ if (code === CLOSE_CODE_TOKEN_EXPIRED) {
728
+ if (options.renewToken === undefined) {
729
+ giveUp(new HopwireError(`The edge at ${edge} closed the tunnel because its token expired or was revoked; start the tunnel again with a valid token.`));
730
+ return;
731
+ }
732
+ // No new token reached the edge before the old one ran out: the tunnel comes back at once with one
733
+ stale = true;
734
+ reconnect(0);
735
+ return;
736
+ }
737
+ retryLater();
738
+ };
739
+ /** The next attempt after a wait. The loss is reported once, not with every attempt that fails. */
740
+ const retryLater = () => {
741
+ const retryInMs = backoff();
742
+ if (!reportedLost) {
743
+ reportedLost = true;
744
+ options.onEvent?.({ type: 'disconnected', retryInMs });
745
+ }
746
+ reconnect(retryInMs);
747
+ };
748
+ const backoff = () => reconnectDelayMs(failures++, timing);
749
+ const reconnect = (delayMs) => {
750
+ retry = setTimeout(() => {
751
+ retry = null;
752
+ void connect().then((attempt) => {
753
+ if (closed) {
754
+ return;
755
+ }
756
+ if (attempt.kind === 'open') {
757
+ // A tunnel that came back at once with a new token was never reported as lost
758
+ if (reportedLost) {
759
+ reportedLost = false;
760
+ options.onEvent?.({ type: 'reconnected' });
761
+ }
762
+ return;
763
+ }
764
+ if (attempt.kind === 'no-token' && !(attempt.error instanceof TemporaryError)) {
765
+ // The control plane said no for good (a revoked API token, a released subdomain)
766
+ giveUp(withoutToken(attempt.error));
767
+ return;
768
+ }
769
+ const final = attempt.kind === 'refused' ? refusal(attempt.status, attempt.body) : null;
770
+ if (final !== null) {
771
+ giveUp(final);
772
+ return;
773
+ }
774
+ // Also for a token that could not be fetched right now: it is asked for again before the edge is
775
+ retryLater();
776
+ });
777
+ }, delayMs);
778
+ };
779
+ const giveUp = (error) => {
780
+ closed = true;
781
+ cancelRenewal();
782
+ end(error);
783
+ };
784
+ const failInFlight = () => {
785
+ for (const flight of flights.values()) {
786
+ abort(flight);
787
+ }
788
+ for (const body of [...bodies.values()]) {
789
+ body.fail(new Error('The connection to the edge was lost'));
790
+ }
791
+ // The tunnel is gone under every WebSocket it carried: the local service is told so
792
+ for (const entry of tunneled.values()) {
793
+ if (entry.upstream === null) {
794
+ abort(entry.flight);
795
+ }
796
+ else {
797
+ entry.upstream.resume();
798
+ closeLike(entry.upstream, WS_CLOSE.goingAway, 'Hopwire: tunnel connection lost');
799
+ }
800
+ }
801
+ tunneled.clear();
802
+ held.clear();
803
+ };
804
+ // A start that is stopped gives up its attempt, or the socket when the edge had just accepted it
805
+ const stopStart = () => {
806
+ closed = true;
807
+ cancelRenewal();
808
+ pending?.terminate();
809
+ socket?.terminate();
810
+ };
811
+ options.signal?.throwIfAborted();
812
+ options.signal?.addEventListener('abort', stopStart, { once: true });
813
+ const first = await connect();
814
+ options.signal?.removeEventListener('abort', stopStart);
815
+ options.signal?.throwIfAborted();
816
+ if (first.kind === 'refused') {
817
+ throw (refusal(first.status, first.body) ??
818
+ new HopwireError(`The edge at ${edge} answered ${first.status} instead of accepting the tunnel; check the edge URL.`));
819
+ }
820
+ if (first.kind === 'no-token') {
821
+ throw withoutToken(first.error);
822
+ }
823
+ if (first.kind === 'unreachable') {
824
+ throw new HopwireError(`The edge at ${edge} cannot be reached (${first.code}); check the edge URL and that the edge is running.`);
825
+ }
826
+ return {
827
+ publicUrl: first.publicUrl,
828
+ usage: first.usage,
829
+ ended,
830
+ async close() {
831
+ closed = true;
832
+ if (retry !== null) {
833
+ clearTimeout(retry);
834
+ retry = null;
835
+ }
836
+ cancelRenewal();
837
+ const open = socket;
838
+ if (open === null) {
839
+ return;
840
+ }
841
+ await new Promise((resolve) => {
842
+ const giveUpWaiting = setTimeout(() => open.terminate(), CLOSE_TIMEOUT_MS);
843
+ open.once('close', () => {
844
+ clearTimeout(giveUpWaiting);
845
+ resolve();
846
+ });
847
+ open.close(1000);
848
+ });
849
+ },
850
+ };
851
+ }
852
+ /**
853
+ * Wait before the next attempt after `failures` failed ones: the step doubles from the initial value up to the
854
+ * maximum, and jitter picks a point between half of the step and the whole step, so that many tunnels that lost the
855
+ * same edge do not return at the same instant.
856
+ */
857
+ export function reconnectDelayMs(failures, timing) {
858
+ const step = Math.min(timing.backoffMaxMs, timing.backoffInitialMs * 2 ** Math.min(failures, 30));
859
+ return Math.round(step * (0.5 + timing.random() / 2));
860
+ }
861
+ /** What the public client spoke to the edge: an edge reached over wss serves its tunnels over https. */
862
+ export function forwardedProto(edgeUrl) {
863
+ return edgeUrl.protocol === 'wss:' ? 'https' : 'http';
864
+ }
865
+ /** What the edge may name as the text of this socket's keepalive. */
866
+ const KEEPALIVE_VALUE = /^[0-9A-Za-z-]{1,64}$/;
867
+ /** What the bridge sets on every public request, whatever the client sent */
868
+ const FORWARDED_HEADERS = new Set(['x-forwarded-host', 'x-forwarded-proto']);
869
+ /**
870
+ * The headers of a public request as the local service gets them: Host
871
+ * unchanged, plus X-Forwarded-Host and X-Forwarded-Proto. Values a client
872
+ * sent under these names are replaced, so the service can rely on them.
873
+ */
874
+ function withForwardedHeaders(headers, proto) {
875
+ const forwarded = [];
876
+ for (const [name, value] of headers) {
877
+ const lower = name.toLowerCase();
878
+ if (FORWARDED_HEADERS.has(lower)) {
879
+ continue;
880
+ }
881
+ if (lower === 'connection') {
882
+ // A header named in Connection is removed on the way to the local service. A client that names these
883
+ // two would have them removed after they were set here, so they are taken out of Connection
884
+ const tokens = value.split(',').filter((token) => !FORWARDED_HEADERS.has(token.trim().toLowerCase()));
885
+ if (tokens.some((token) => token.trim() !== '')) {
886
+ forwarded.push([name, tokens.join(',')]);
887
+ }
888
+ continue;
889
+ }
890
+ forwarded.push([name, value]);
891
+ }
892
+ const host = getHeader(headers, 'host');
893
+ if (host !== undefined) {
894
+ forwarded.push(['x-forwarded-host', host]);
895
+ }
896
+ forwarded.push(['x-forwarded-proto', proto]);
897
+ return forwarded;
898
+ }
899
+ /** Resolves when the frame was handed to the network, so a slow connection slows the sender down. */
900
+ function sendFrame(socket, message) {
901
+ return new Promise((resolve, reject) => {
902
+ if (socket.readyState !== WebSocket.OPEN) {
903
+ reject(new Error('The connection to the edge is closed'));
904
+ return;
905
+ }
906
+ socket.send(encodeMessage(message), (error) => (error ? reject(error) : resolve()));
907
+ });
908
+ }
909
+ /**
910
+ * Most bytes of a request body that may wait in the bridge for the reader. The edge sends a piece while fewer than
911
+ * FLOW_WINDOW_BYTES are unacknowledged, and a piece is up to CHUNK_SIZE_BYTES, so it can have just under a window
912
+ * and a chunk on the way. What waits here is never more than what is unacknowledged: an acknowledgement reports only
913
+ * bytes the reader has taken out.
914
+ */
915
+ export const REQUEST_BODY_HELD_MAX_BYTES = FLOW_WINDOW_BYTES + CHUNK_SIZE_BYTES;
916
+ /**
917
+ * The body of a public request as it arrives in chunk frames. The
918
+ * interceptor reads it as an async iterable; it ends with the end frame and
919
+ * fails when the socket is lost or the edge gave the request up. What the
920
+ * reader has taken is reported, which is what lets the edge send more.
921
+ * A reader that leaves before the end settles it as well. Exported for its tests.
922
+ */
923
+ export class BodyQueue {
924
+ onTaken;
925
+ onSettled;
926
+ chunks = [];
927
+ /** Bytes in `chunks`: what arrived and the reader has not taken yet */
928
+ buffered = 0;
929
+ finished = false;
930
+ error = null;
931
+ wake = null;
932
+ /** Bytes the reader has taken, and the count last reported */
933
+ taken = 0;
934
+ acknowledged = 0;
935
+ constructor(
936
+ /** Called with the total of bytes taken, at the latest every FLOW_ACK_BYTES */
937
+ onTaken,
938
+ /** Called once no more frames are expected */
939
+ onSettled) {
940
+ this.onTaken = onTaken;
941
+ this.onSettled = onSettled;
942
+ }
943
+ push(chunk) {
944
+ if (this.finished || this.error !== null) {
945
+ return;
946
+ }
947
+ this.chunks.push(chunk);
948
+ this.buffered += chunk.length;
949
+ if (this.buffered > REQUEST_BODY_HELD_MAX_BYTES) {
950
+ // An edge keeps to the window, which the acknowledgements open only as the reader takes the body; one
951
+ // that sends more is not held in memory
952
+ this.chunks.length = 0;
953
+ this.buffered = 0;
954
+ this.fail(new Error('The edge sent more of the request body than the flow control window allows'));
955
+ return;
956
+ }
957
+ this.wake?.();
958
+ }
959
+ end() {
960
+ if (this.finished || this.error !== null) {
961
+ return;
962
+ }
963
+ this.finished = true;
964
+ this.settle();
965
+ }
966
+ fail(error) {
967
+ if (this.finished || this.error !== null) {
968
+ return;
969
+ }
970
+ this.error = error;
971
+ this.settle();
972
+ }
973
+ async *[Symbol.asyncIterator]() {
974
+ try {
975
+ for (;;) {
976
+ const chunk = this.chunks.shift();
977
+ if (chunk !== undefined) {
978
+ this.buffered -= chunk.length;
979
+ yield chunk;
980
+ // Asked for the next one: the reader is done with this chunk
981
+ this.taken += chunk.length;
982
+ if (this.taken - this.acknowledged >= FLOW_ACK_BYTES && this.error === null) {
983
+ this.acknowledged = this.taken;
984
+ this.onTaken(this.taken);
985
+ }
986
+ }
987
+ else if (this.error !== null) {
988
+ throw this.error;
989
+ }
990
+ else if (this.finished) {
991
+ return;
992
+ }
993
+ else {
994
+ await new Promise((resolve) => {
995
+ this.wake = resolve;
996
+ });
997
+ this.wake = null;
998
+ }
999
+ }
1000
+ }
1001
+ finally {
1002
+ // A reader that leaves before the end takes no more: what is held is let go and later frames are ignored
1003
+ if (!this.finished && this.error === null) {
1004
+ this.chunks.length = 0;
1005
+ this.buffered = 0;
1006
+ this.fail(new Error('The reader of the request body left'));
1007
+ }
1008
+ }
1009
+ }
1010
+ settle() {
1011
+ this.onSettled();
1012
+ this.wake?.();
1013
+ }
1014
+ }
1015
+ /** The milliseconds a header of the edge names, null when it is missing or no whole number. */
1016
+ function durationOf(header) {
1017
+ if (typeof header !== 'string' || !/^\d{1,15}$/.test(header)) {
1018
+ return null;
1019
+ }
1020
+ return Number(header);
1021
+ }
1022
+ function errorCode(error) {
1023
+ if (typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string') {
1024
+ return error.code;
1025
+ }
1026
+ // ws reports its handshake timeout as a plain Error
1027
+ if (error instanceof Error && error.message.includes('timed out')) {
1028
+ return 'TIMEOUT';
1029
+ }
1030
+ return 'UNKNOWN';
1031
+ }