@restatedev/restate-sdk 1.17.4 → 1.18.1

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 (154) hide show
  1. package/dist/common_api.d.cts +1 -1
  2. package/dist/common_api.d.cts.map +1 -1
  3. package/dist/common_api.d.ts +1 -1
  4. package/dist/common_api.d.ts.map +1 -1
  5. package/dist/common_api.js.map +1 -1
  6. package/dist/context.d.cts +3 -0
  7. package/dist/context.d.cts.map +1 -1
  8. package/dist/context.d.ts +3 -0
  9. package/dist/context.d.ts.map +1 -1
  10. package/dist/context.js.map +1 -1
  11. package/dist/context_impl.cjs +8 -3
  12. package/dist/context_impl.js +8 -3
  13. package/dist/context_impl.js.map +1 -1
  14. package/dist/endpoint/components.cjs +28 -6
  15. package/dist/endpoint/components.js +28 -6
  16. package/dist/endpoint/components.js.map +1 -1
  17. package/dist/endpoint/connect/env.cjs +206 -0
  18. package/dist/endpoint/connect/env.js +199 -0
  19. package/dist/endpoint/connect/env.js.map +1 -0
  20. package/dist/endpoint/connect/index.cjs +113 -0
  21. package/dist/endpoint/connect/index.d.cts +41 -0
  22. package/dist/endpoint/connect/index.d.cts.map +1 -0
  23. package/dist/endpoint/connect/index.d.ts +41 -0
  24. package/dist/endpoint/connect/index.d.ts.map +1 -0
  25. package/dist/endpoint/connect/index.js +114 -0
  26. package/dist/endpoint/connect/index.js.map +1 -0
  27. package/dist/endpoint/connect/key.cjs +53 -0
  28. package/dist/endpoint/connect/key.js +53 -0
  29. package/dist/endpoint/connect/key.js.map +1 -0
  30. package/dist/endpoint/handlers/discovery.cjs +12 -2
  31. package/dist/endpoint/handlers/discovery.js +12 -2
  32. package/dist/endpoint/handlers/discovery.js.map +1 -1
  33. package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings.cjs +1 -1
  34. package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings.js +1 -1
  35. package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings.js.map +1 -1
  36. package/dist/endpoint/tunnel/backoff.cjs +37 -0
  37. package/dist/endpoint/tunnel/backoff.js +36 -0
  38. package/dist/endpoint/tunnel/backoff.js.map +1 -0
  39. package/dist/endpoint/tunnel/connection.cjs +604 -0
  40. package/dist/endpoint/tunnel/connection.js +600 -0
  41. package/dist/endpoint/tunnel/connection.js.map +1 -0
  42. package/dist/endpoint/tunnel/draining.cjs +40 -0
  43. package/dist/endpoint/tunnel/draining.js +40 -0
  44. package/dist/endpoint/tunnel/draining.js.map +1 -0
  45. package/dist/endpoint/tunnel/engine.cjs +264 -0
  46. package/dist/endpoint/tunnel/engine.d.cts +1 -0
  47. package/dist/endpoint/tunnel/engine.d.ts +1 -0
  48. package/dist/endpoint/tunnel/engine.js +265 -0
  49. package/dist/endpoint/tunnel/engine.js.map +1 -0
  50. package/dist/endpoint/tunnel/forwarded.cjs +34 -0
  51. package/dist/endpoint/tunnel/forwarded.js +34 -0
  52. package/dist/endpoint/tunnel/forwarded.js.map +1 -0
  53. package/dist/endpoint/tunnel/handshake.cjs +98 -0
  54. package/dist/endpoint/tunnel/handshake.js +97 -0
  55. package/dist/endpoint/tunnel/handshake.js.map +1 -0
  56. package/dist/endpoint/tunnel/index.d.cts +3 -0
  57. package/dist/endpoint/tunnel/index.d.ts +3 -0
  58. package/dist/endpoint/tunnel/options.cjs +168 -0
  59. package/dist/endpoint/tunnel/options.d.cts +2 -0
  60. package/dist/endpoint/tunnel/options.d.ts +2 -0
  61. package/dist/endpoint/tunnel/options.js +161 -0
  62. package/dist/endpoint/tunnel/options.js.map +1 -0
  63. package/dist/endpoint/tunnel/supervisor.cjs +180 -0
  64. package/dist/endpoint/tunnel/supervisor.js +181 -0
  65. package/dist/endpoint/tunnel/supervisor.js.map +1 -0
  66. package/dist/endpoint/tunnel/targets.cjs +110 -0
  67. package/dist/endpoint/tunnel/targets.js +107 -0
  68. package/dist/endpoint/tunnel/targets.js.map +1 -0
  69. package/dist/endpoint/tunnel/types.d.cts +270 -0
  70. package/dist/endpoint/tunnel/types.d.cts.map +1 -0
  71. package/dist/endpoint/tunnel/types.d.ts +270 -0
  72. package/dist/endpoint/tunnel/types.d.ts.map +1 -0
  73. package/dist/endpoint/tunnel/util.cjs +67 -0
  74. package/dist/endpoint/tunnel/util.js +65 -0
  75. package/dist/endpoint/tunnel/util.js.map +1 -0
  76. package/dist/fetch.d.cts +2 -2
  77. package/dist/fetch.d.ts +2 -2
  78. package/dist/index.cjs +2 -0
  79. package/dist/index.d.cts +4 -2
  80. package/dist/index.d.ts +4 -2
  81. package/dist/index.js +2 -1
  82. package/dist/lambda.d.cts +2 -2
  83. package/dist/lambda.d.ts +2 -2
  84. package/dist/node.cjs +2 -0
  85. package/dist/node.d.cts +5 -2
  86. package/dist/node.d.cts.map +1 -1
  87. package/dist/node.d.ts +5 -2
  88. package/dist/node.d.ts.map +1 -1
  89. package/dist/node.js +2 -1
  90. package/dist/node.js.map +1 -1
  91. package/dist/package.cjs +1 -1
  92. package/dist/package.js +1 -1
  93. package/dist/package.js.map +1 -1
  94. package/dist/types/errors.cjs +4 -2
  95. package/dist/types/errors.d.cts.map +1 -1
  96. package/dist/types/errors.d.ts.map +1 -1
  97. package/dist/types/errors.js +4 -2
  98. package/dist/types/errors.js.map +1 -1
  99. package/dist/types/rpc.d.cts +42 -17
  100. package/dist/types/rpc.d.cts.map +1 -1
  101. package/dist/types/rpc.d.ts +42 -17
  102. package/dist/types/rpc.d.ts.map +1 -1
  103. package/dist/types/rpc.js.map +1 -1
  104. package/package.json +2 -2
  105. package/dist/context_impl.d.ts.map +0 -1
  106. package/dist/endpoint/components.d.ts.map +0 -1
  107. package/dist/endpoint/discovery.d.ts +0 -184
  108. package/dist/endpoint/discovery.d.ts.map +0 -1
  109. package/dist/endpoint/discovery.js +0 -7
  110. package/dist/endpoint/discovery.js.map +0 -1
  111. package/dist/endpoint/endpoint.d.ts.map +0 -1
  112. package/dist/endpoint/handlers/core_logging.d.ts +0 -14
  113. package/dist/endpoint/handlers/core_logging.d.ts.map +0 -1
  114. package/dist/endpoint/handlers/discovery.d.ts +0 -5
  115. package/dist/endpoint/handlers/discovery.d.ts.map +0 -1
  116. package/dist/endpoint/handlers/fetch.d.ts +0 -5
  117. package/dist/endpoint/handlers/fetch.d.ts.map +0 -1
  118. package/dist/endpoint/handlers/generic.d.ts +0 -5
  119. package/dist/endpoint/handlers/generic.d.ts.map +0 -1
  120. package/dist/endpoint/handlers/lambda.d.ts +0 -10
  121. package/dist/endpoint/handlers/lambda.d.ts.map +0 -1
  122. package/dist/endpoint/handlers/preview.d.ts +0 -5
  123. package/dist/endpoint/handlers/preview.d.ts.map +0 -1
  124. package/dist/endpoint/handlers/types.d.ts.map +0 -1
  125. package/dist/endpoint/handlers/types.js +0 -2
  126. package/dist/endpoint/handlers/types.js.map +0 -1
  127. package/dist/endpoint/handlers/utils.d.ts +0 -23
  128. package/dist/endpoint/handlers/utils.d.ts.map +0 -1
  129. package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings.d.ts +0 -454
  130. package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings.d.ts.map +0 -1
  131. package/dist/endpoint/node_endpoint.d.ts +0 -28
  132. package/dist/endpoint/node_endpoint.d.ts.map +0 -1
  133. package/dist/endpoint/types.js +0 -2
  134. package/dist/endpoint/types.js.map +0 -1
  135. package/dist/endpoint/withOptions.d.ts +0 -4
  136. package/dist/endpoint/withOptions.d.ts.map +0 -1
  137. package/dist/endpoint.js +0 -12
  138. package/dist/endpoint.js.map +0 -1
  139. package/dist/error_sanitization.d.ts +0 -13
  140. package/dist/error_sanitization.d.ts.map +0 -1
  141. package/dist/hooks.js +0 -2
  142. package/dist/hooks.js.map +0 -1
  143. package/dist/index.d.ts.map +0 -1
  144. package/dist/index.js.map +0 -1
  145. package/dist/io.d.ts.map +0 -1
  146. package/dist/logging/console_logger_transport.d.ts +0 -5
  147. package/dist/logging/console_logger_transport.d.ts.map +0 -1
  148. package/dist/logging/logger.d.ts.map +0 -1
  149. package/dist/user_agent.d.ts +0 -2
  150. package/dist/user_agent.d.ts.map +0 -1
  151. package/dist/utils/external_progress_channel.d.ts +0 -19
  152. package/dist/utils/external_progress_channel.d.ts.map +0 -1
  153. package/dist/utils/rand.d.ts +0 -13
  154. package/dist/utils/rand.d.ts.map +0 -1
@@ -0,0 +1,600 @@
1
+ import { buildTlsConnectOptions } from "./options.js";
2
+ import { START_TUNNEL_PATH, performHandshake } from "./handshake.js";
3
+ import { forwardedTail } from "./forwarded.js";
4
+ import * as http2 from "node:http2";
5
+ import { randomBytes } from "node:crypto";
6
+ import * as net from "node:net";
7
+ import * as tls from "node:tls";
8
+
9
+ //#region src/endpoint/tunnel/connection.ts
10
+ const CLIENT_DRAIN_SESSION_CLOSE_TIMEOUT_MS = 1e3;
11
+ const TUNNEL_DRAINING_HEADER = "x-restate-tunnel-draining";
12
+ const CROCKFORD_BASE32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
13
+ function encodeBase32(value, length) {
14
+ let out = "";
15
+ for (let i = 0; i < length; i++) {
16
+ out = CROCKFORD_BASE32.charAt(Number(value & 31n)) + out;
17
+ value >>= 5n;
18
+ }
19
+ return out;
20
+ }
21
+ function newTunnelConnectionId() {
22
+ let random = 0n;
23
+ for (const byte of randomBytes(10)) random = random << 8n | BigInt(byte);
24
+ return `${encodeBase32(BigInt(Date.now()), 10)}${encodeBase32(random, 16)}`;
25
+ }
26
+ function formatIdentity(workerId, connectionId) {
27
+ return `worker_id=${workerId} connection_id=${connectionId}`;
28
+ }
29
+ function targetLabel(target) {
30
+ return `${target.host}:${target.port}`;
31
+ }
32
+ function formatConnectionOutcome(outcome) {
33
+ switch (outcome.kind) {
34
+ case "served": return `served uptimeMs=${outcome.uptimeMs}`;
35
+ case "drained": return `drained uptimeMs=${outcome.uptimeMs}`;
36
+ case "retryable": return `retryable reason=${outcome.reason}`;
37
+ case "fatal": return `fatal reason=${outcome.reason}`;
38
+ }
39
+ }
40
+ function formatSettings(settings) {
41
+ const entries = Object.entries(settings).filter(([, value]) => value !== void 0);
42
+ if (entries.length === 0) return "{}";
43
+ return `{${entries.map(([key, value]) => `${key}=${String(value)}`).join(", ")}}`;
44
+ }
45
+ function pathWithoutQuery(url) {
46
+ if (url === void 0) return "?";
47
+ const queryStart = url.indexOf("?");
48
+ return queryStart === -1 ? url : url.slice(0, queryStart);
49
+ }
50
+ function endInternalError(res) {
51
+ try {
52
+ if (!res.headersSent) res.writeHead(500);
53
+ if (!res.writableEnded) res.end("tunnel: SDK handler error");
54
+ } catch {}
55
+ }
56
+ /** Classify an incoming h2 request. Control paths are cloud-originated and
57
+ * arrive UNPREFIXED (before any destination-prefix stripping). */
58
+ function classifyRequest(req) {
59
+ const rawPath = (req.url ?? "").split("?")[0];
60
+ if (req.method === "GET" && rawPath === START_TUNNEL_PATH) return { kind: "start-tunnel" };
61
+ if (rawPath === "/_/health") return { kind: "health" };
62
+ if (rawPath === "/_/drain-tunnel") return { kind: "drain" };
63
+ return { kind: "forwarded" };
64
+ }
65
+ /** Resolves a connection attempt's outcome exactly once. */
66
+ var Completion = class {
67
+ done = false;
68
+ resolveFn;
69
+ promise = new Promise((resolve) => {
70
+ this.resolveFn = resolve;
71
+ });
72
+ get settled() {
73
+ return this.done;
74
+ }
75
+ /** Resolve once; returns false if it was already resolved. */
76
+ resolve(outcome) {
77
+ if (this.done) return false;
78
+ this.done = true;
79
+ this.resolveFn(outcome);
80
+ return true;
81
+ }
82
+ };
83
+ /**
84
+ * Liveness watchdog: periodic h2 PING; `pingMaxMissed` consecutive misses mean
85
+ * the connection is half-open (the OS may never surface it), so `onDead` fires.
86
+ * Owns its own timer/miss state so the connection doesn't have to.
87
+ */
88
+ var Watchdog = class {
89
+ interval;
90
+ missed = 0;
91
+ constructor(session, opts, onDead) {
92
+ this.session = session;
93
+ this.opts = opts;
94
+ this.onDead = onDead;
95
+ }
96
+ start() {
97
+ this.interval = setInterval(() => this.beat(), this.opts.pingIntervalMs);
98
+ this.interval.unref();
99
+ }
100
+ stop() {
101
+ if (this.interval !== void 0) clearInterval(this.interval);
102
+ }
103
+ beat() {
104
+ if (this.session.destroyed) return;
105
+ let acked = false;
106
+ try {
107
+ this.session.ping((err) => {
108
+ if (err === null) {
109
+ acked = true;
110
+ this.missed = 0;
111
+ }
112
+ });
113
+ } catch {
114
+ return;
115
+ }
116
+ setTimeout(() => {
117
+ if (acked || this.session.destroyed) return;
118
+ this.missed++;
119
+ if (this.missed >= this.opts.pingMaxMissed) this.onDead();
120
+ }, this.opts.pingTimeoutMs).unref();
121
+ }
122
+ };
123
+ /**
124
+ * The dial stage: connect TCP (+ TLS), bounded by `connectTimeoutMs` and the
125
+ * slot abort, and require ALPN to have negotiated h2. Owns the socket until it
126
+ * either hands it back connected or destroys it on failure — so all of the
127
+ * connect-phase timer/listener state stays local here.
128
+ */
129
+ function dial(target, deps, plaintext, signal, connectionId) {
130
+ const log = deps.opts.logger;
131
+ const identity = formatIdentity(deps.opts.tunnelWorkerId, connectionId);
132
+ const tlsOptions = plaintext ? void 0 : buildTlsConnectOptions(deps.opts.tls, target.servername);
133
+ const socket = plaintext ? net.connect({
134
+ host: target.host,
135
+ port: target.port
136
+ }) : tls.connect({
137
+ host: target.host,
138
+ port: target.port,
139
+ ...tlsOptions
140
+ });
141
+ return new Promise((resolve) => {
142
+ let done = false;
143
+ const label = targetLabel(target);
144
+ const onError = (err) => fail(`socket error: ${err.message}`);
145
+ const onAbort = () => fail("tunnel closed");
146
+ const timer = setTimeout(() => fail(`connect timeout after ${deps.opts.connectTimeoutMs}ms`), deps.opts.connectTimeoutMs);
147
+ timer.unref();
148
+ const cleanup = () => {
149
+ clearTimeout(timer);
150
+ signal.removeEventListener("abort", onAbort);
151
+ socket.removeListener("error", onError);
152
+ };
153
+ function fail(reason) {
154
+ if (done) return;
155
+ done = true;
156
+ cleanup();
157
+ log(`tunnel: failed to connect to ${label}: ${reason} (${identity})`, "warn");
158
+ socket.destroy();
159
+ resolve({
160
+ ok: false,
161
+ outcome: {
162
+ kind: "retryable",
163
+ reason
164
+ }
165
+ });
166
+ }
167
+ signal.addEventListener("abort", onAbort, { once: true });
168
+ socket.on("error", onError);
169
+ socket.once(plaintext ? "connect" : "secureConnect", () => {
170
+ if (done) return;
171
+ socket.setNoDelay(true);
172
+ const alpn = plaintext ? "plaintext" : `tls alpn=${JSON.stringify(socket.alpnProtocol)}`;
173
+ if (!plaintext && socket.alpnProtocol !== "h2") {
174
+ fail("tunnel server did not negotiate h2 ALPN — it predates standard-h2 control traffic and cannot serve this client");
175
+ return;
176
+ }
177
+ done = true;
178
+ cleanup();
179
+ log(`tunnel: connected socket to ${label} (${alpn}, ${identity})`);
180
+ resolve({
181
+ ok: true,
182
+ socket
183
+ });
184
+ });
185
+ });
186
+ }
187
+ /**
188
+ * Run one connection attempt. Resolves (never rejects) with the outcome
189
+ * when the connection ends; `slotSignal` aborts the attempt at any phase.
190
+ */
191
+ function runConnection(target, slotSignal, deps) {
192
+ let authToken;
193
+ try {
194
+ authToken = deps.opts.authToken();
195
+ } catch (err) {
196
+ return Promise.resolve({
197
+ kind: "retryable",
198
+ reason: `auth token unavailable: ${err instanceof Error ? err.message : String(err)}`
199
+ });
200
+ }
201
+ return new ConnectionAttempt(target, slotSignal, deps, authToken).run();
202
+ }
203
+ var ConnectionAttempt = class {
204
+ state = { kind: "connecting" };
205
+ completion = new Completion();
206
+ /** Lifetime-scoped: destroyed on teardown in any phase, handed to the
207
+ * registry on a server drain. */
208
+ socket;
209
+ plaintext;
210
+ log;
211
+ connectionId = newTunnelConnectionId();
212
+ constructor(target, slotSignal, deps, authToken) {
213
+ this.target = target;
214
+ this.slotSignal = slotSignal;
215
+ this.deps = deps;
216
+ this.authToken = authToken;
217
+ this.log = deps.opts.logger;
218
+ this.plaintext = target.plaintext ?? deps.opts.tls === false;
219
+ }
220
+ get identity() {
221
+ return {
222
+ workerId: this.deps.opts.tunnelWorkerId,
223
+ connectionId: this.connectionId,
224
+ target: targetLabel(this.target)
225
+ };
226
+ }
227
+ identityLog() {
228
+ return formatIdentity(this.deps.opts.tunnelWorkerId, this.connectionId);
229
+ }
230
+ logWithIdentity(message) {
231
+ this.log(`${message} (${this.identityLog()})`);
232
+ }
233
+ run() {
234
+ this.deps.activeConnections.add(this);
235
+ this.drive();
236
+ return this.completion.promise;
237
+ }
238
+ /** Stage pipeline: dial → establish (role-flip). The remaining stages
239
+ * (handshake, serve) are event-driven from the h2 server's request handler. */
240
+ async drive() {
241
+ const dialed = await dial(this.target, this.deps, this.plaintext, this.slotSignal, this.connectionId);
242
+ if (this.completion.settled) {
243
+ if (dialed.ok) dialed.socket.destroy();
244
+ this.deps.activeConnections.delete(this);
245
+ return;
246
+ }
247
+ if (!dialed.ok) {
248
+ this.settle(dialed.outcome);
249
+ return;
250
+ }
251
+ this.socket = dialed.socket;
252
+ this.deps.activeSockets.add(dialed.socket);
253
+ this.slotSignal.addEventListener("abort", this.onAbort, { once: true });
254
+ dialed.socket.on("error", (err) => this.settle(this.endOutcome(`socket error: ${err.message}`), `socket error: ${err.message}`));
255
+ dialed.socket.on("close", () => this.settle(this.endOutcome("connection closed before handshake completed"), "socket closed"));
256
+ this.establish(dialed.socket);
257
+ }
258
+ get closed() {
259
+ return this.state.kind === "closed";
260
+ }
261
+ session() {
262
+ const s = this.state;
263
+ return s.kind === "handshaking" || s.kind === "serving" || s.kind === "draining" ? s.session : void 0;
264
+ }
265
+ get openedAt() {
266
+ const s = this.state;
267
+ return s.kind === "serving" || s.kind === "draining" ? s.openedAt : void 0;
268
+ }
269
+ uptimeMs() {
270
+ return this.openedAt === void 0 ? 0 : Date.now() - this.openedAt;
271
+ }
272
+ /** The end-of-connection outcome: "served" once established, else retryable. */
273
+ endOutcome(reason) {
274
+ return this.openedAt !== void 0 ? {
275
+ kind: "served",
276
+ uptimeMs: this.uptimeMs()
277
+ } : {
278
+ kind: "retryable",
279
+ reason
280
+ };
281
+ }
282
+ onAbort = () => this.settle({
283
+ kind: "retryable",
284
+ reason: "tunnel closed"
285
+ });
286
+ /** Stop the timers/monitors owned by the current phase. */
287
+ stopPhaseResources() {
288
+ const s = this.state;
289
+ if (s.kind === "handshaking") clearTimeout(s.firstRequestTimer);
290
+ else if (s.kind === "serving" || s.kind === "draining") s.watchdog.stop();
291
+ }
292
+ /** Detach from the engine registries and the slot-abort listener. */
293
+ deregister() {
294
+ this.slotSignal.removeEventListener("abort", this.onAbort);
295
+ this.deps.activeConnections.delete(this);
296
+ if (this.socket !== void 0) this.deps.activeSockets.delete(this.socket);
297
+ }
298
+ /**
299
+ * The single terminal path — resolve the outcome (once), destroy the
300
+ * session/socket, and move to `closed`. Idempotent. A server drain does NOT
301
+ * funnel through here for teardown: it detaches via {@link beginServerDrain}
302
+ * and lets the DrainingRegistry destroy the session later.
303
+ */
304
+ settle(outcome, detail) {
305
+ if (this.closed) return;
306
+ const phase = this.state.kind;
307
+ const session = this.session();
308
+ this.stopPhaseResources();
309
+ this.deregister();
310
+ this.state = { kind: "closed" };
311
+ session?.destroy();
312
+ this.socket?.destroy();
313
+ const firstOutcome = this.completion.resolve(outcome);
314
+ this.logWithIdentity(`tunnel: connection to ${targetLabel(this.target)} closed (phase=${phase}, outcome=${formatConnectionOutcome(outcome)}${detail === void 0 ? "" : `, detail=${detail}`}${firstOutcome ? "" : ", already reported"})`);
315
+ }
316
+ closeSessionGracefully(session) {
317
+ return new Promise((resolve) => {
318
+ if (session.closed || session.destroyed) {
319
+ resolve();
320
+ return;
321
+ }
322
+ let done = false;
323
+ const finish = () => {
324
+ if (done) return;
325
+ done = true;
326
+ clearTimeout(timer);
327
+ resolve();
328
+ };
329
+ const timer = setTimeout(() => {
330
+ this.settle({
331
+ kind: "served",
332
+ uptimeMs: this.uptimeMs()
333
+ }, "session.close() timed out");
334
+ finish();
335
+ }, CLIENT_DRAIN_SESSION_CLOSE_TIMEOUT_MS);
336
+ timer.unref();
337
+ session.once("close", finish);
338
+ try {
339
+ session.close();
340
+ } catch {
341
+ this.settle(this.endOutcome("session close failed"), "session close failed");
342
+ finish();
343
+ }
344
+ });
345
+ }
346
+ sendClientDrainGoaway(session) {
347
+ if (session.closed || session.destroyed) return;
348
+ try {
349
+ session.goaway(http2.constants.NGHTTP2_NO_ERROR);
350
+ this.logWithIdentity(`tunnel: sent client-drain GOAWAY to ${targetLabel(this.target)}`);
351
+ } catch (err) {
352
+ this.logWithIdentity(`tunnel: failed to send client-drain GOAWAY to ${targetLabel(this.target)}: ${err instanceof Error ? err.message : String(err)}`);
353
+ }
354
+ }
355
+ establish(socket) {
356
+ this.logWithIdentity(`tunnel: connected to ${this.target.host}:${this.target.port}, starting handshake`);
357
+ const h2 = http2.createServer({
358
+ maxSessionMemory: this.deps.opts.maxSessionMemory,
359
+ settings: {
360
+ maxConcurrentStreams: this.deps.opts.maxConcurrentStreams,
361
+ initialWindowSize: 1024 * 1024,
362
+ maxFrameSize: 65536
363
+ }
364
+ }, (req, res) => this.handleRequest(req, res));
365
+ h2.on("session", (s) => {
366
+ this.logWithIdentity(`tunnel: h2 session established to ${targetLabel(this.target)} (localSettings=${formatSettings(s.localSettings)}, remoteSettings=${formatSettings(s.remoteSettings)})`);
367
+ s.on("localSettings", (settings) => this.logWithIdentity(`tunnel: h2 local settings acknowledged by ${targetLabel(this.target)}: ${formatSettings(settings)}`));
368
+ s.on("remoteSettings", (settings) => this.logWithIdentity(`tunnel: h2 remote settings from ${targetLabel(this.target)}: ${formatSettings(settings)}`));
369
+ if (this.state.kind === "connecting") {
370
+ const firstRequestTimer = setTimeout(() => {
371
+ if (this.state.kind === "handshaking" && this.state.handshake === void 0) this.settle({
372
+ kind: "retryable",
373
+ reason: "server never initiated /_/start-tunnel"
374
+ });
375
+ }, this.deps.opts.handshakeTimeoutMs);
376
+ firstRequestTimer.unref();
377
+ this.state = {
378
+ kind: "handshaking",
379
+ session: s,
380
+ firstRequestTimer,
381
+ handshake: void 0
382
+ };
383
+ }
384
+ try {
385
+ s.setLocalWindowSize?.(this.deps.opts.connectionWindowSize);
386
+ } catch {}
387
+ s.on("close", () => this.settle(this.endOutcome("session closed before handshake completed"), "session closed"));
388
+ s.on("error", (err) => this.settle(this.endOutcome(`session error: ${err.message}`), `session error: ${err.message}`));
389
+ });
390
+ h2.on("sessionError", (err) => this.settle(this.endOutcome(`session error: ${err.message}`), `session error: ${err.message}`));
391
+ h2.emit("connection", socket);
392
+ }
393
+ handleRequest(req, res) {
394
+ switch (classifyRequest(req).kind) {
395
+ case "health":
396
+ res.writeHead(200);
397
+ res.end();
398
+ return;
399
+ case "drain":
400
+ this.handleDrainRequest(res);
401
+ return;
402
+ case "start-tunnel":
403
+ if (this.state.kind === "handshaking" && this.state.handshake === void 0) this.startHandshake(req, res);
404
+ else this.notReady(res);
405
+ return;
406
+ case "forwarded":
407
+ this.handleForwarded(req, res);
408
+ return;
409
+ }
410
+ }
411
+ handleForwarded(req, res) {
412
+ if (this.state.kind === "serving" || this.state.kind === "draining") {
413
+ this.dispatchForwarded(req, res);
414
+ return;
415
+ }
416
+ if (this.state.kind === "handshaking" && this.state.handshake !== void 0) {
417
+ this.state.handshake.then(({ ok }) => {
418
+ if (this.closed || res.stream.destroyed) return;
419
+ try {
420
+ if (ok) this.dispatchForwarded(req, res);
421
+ else {
422
+ this.logWithIdentity(`tunnel: refused forwarded stream ${res.stream.id ?? "?"} before tunnel handshake completed`);
423
+ this.notReady(res);
424
+ }
425
+ } catch {}
426
+ });
427
+ return;
428
+ }
429
+ this.logWithIdentity(`tunnel: refused forwarded stream ${res.stream.id ?? "?"} before tunnel handshake completed`);
430
+ this.notReady(res);
431
+ }
432
+ notReady(res) {
433
+ res.writeHead(503, { [TUNNEL_DRAINING_HEADER]: "true" });
434
+ res.end("tunnel: not ready");
435
+ }
436
+ /** First stream: run the handshake; its outcome opens the gate. */
437
+ startHandshake(req, res) {
438
+ if (this.state.kind !== "handshaking") return;
439
+ clearTimeout(this.state.firstRequestTimer);
440
+ this.state.handshake = performHandshake(req, res, {
441
+ authToken: this.authToken,
442
+ environmentId: this.deps.opts.environmentId,
443
+ tunnelName: this.deps.opts.name,
444
+ tunnelWorkerId: this.deps.opts.tunnelWorkerId,
445
+ tunnelConnectionId: this.connectionId,
446
+ supportsDrain: this.deps.opts.supportsDrain,
447
+ supportsClientDrain: this.deps.opts.supportsClientDrain
448
+ }, this.deps.opts.handshakeTimeoutMs).then((outcome) => {
449
+ if (this.state.kind !== "handshaking") return { ok: false };
450
+ if (outcome.kind === "ok") {
451
+ const { session } = this.state;
452
+ const openedAt = Date.now();
453
+ const watchdog = this.startWatchdog(session);
454
+ this.state = this.deps.isShuttingDown() ? {
455
+ kind: "draining",
456
+ session,
457
+ openedAt,
458
+ trigger: "client",
459
+ watchdog
460
+ } : {
461
+ kind: "serving",
462
+ session,
463
+ openedAt,
464
+ watchdog
465
+ };
466
+ this.logWithIdentity(`tunnel: established (name=${outcome.info.tunnelName}, proxy=${outcome.info.proxyUrl})`);
467
+ this.deps.onEstablished(outcome.info, this.identity);
468
+ return { ok: true };
469
+ }
470
+ this.settle(outcome);
471
+ return { ok: false };
472
+ });
473
+ }
474
+ /** Strip the destination prefix and hand the stream to the SDK. */
475
+ dispatchForwarded(req, res) {
476
+ if (this.state.kind === "draining" && this.state.trigger === "client" || this.deps.isShuttingDown()) {
477
+ this.logWithIdentity(`tunnel: refused forwarded stream ${res.stream.id ?? "?"} during client drain`);
478
+ res.writeHead(503, { [TUNNEL_DRAINING_HEADER]: "true" });
479
+ res.end();
480
+ return;
481
+ }
482
+ const tail = forwardedTail(req.url ?? "");
483
+ if (tail === null) {
484
+ res.writeHead(400);
485
+ res.end("tunnel: malformed forwarded path");
486
+ return;
487
+ }
488
+ req.url = tail;
489
+ this.deps.inflightStarted();
490
+ res.stream.once("close", () => this.deps.inflightEnded());
491
+ res.stream.once("error", (err) => {
492
+ const streamId = res.stream.id ?? "?";
493
+ const logPath = pathWithoutQuery(req.url);
494
+ this.logWithIdentity(`tunnel: forwarded stream ${streamId} ${req.method ?? "?"} ${logPath} failed: ${err.message}`);
495
+ });
496
+ try {
497
+ this.deps.sdkHandler(req, res);
498
+ } catch (err) {
499
+ const streamId = res.stream.id ?? "?";
500
+ const logPath = pathWithoutQuery(req.url);
501
+ this.logWithIdentity(`tunnel: SDK handler threw for forwarded stream ${streamId} ${req.method ?? "?"} ${logPath}: ${err instanceof Error ? err.message : String(err)}`);
502
+ endInternalError(res);
503
+ }
504
+ }
505
+ handleDrainRequest(res) {
506
+ res.writeHead(200);
507
+ res.end();
508
+ this.logWithIdentity(`tunnel: received server drain notification from ${targetLabel(this.target)}`);
509
+ if (!this.deps.opts.supportsDrain) {
510
+ this.logWithIdentity("tunnel: received /_/drain-tunnel (drain not advertised) — acknowledging");
511
+ return;
512
+ }
513
+ if (this.state.kind === "serving") this.beginServerDrain();
514
+ else if (this.state.kind === "handshaking" && this.state.handshake !== void 0) this.state.handshake.then(({ ok }) => {
515
+ if (ok) this.beginServerDrain();
516
+ });
517
+ }
518
+ /**
519
+ * Server-initiated drain: detach the still-serving session to the
520
+ * DrainingRegistry and resolve `run()` so the slot dials a replacement. The
521
+ * detached session keeps serving its in-flight invocations under the
522
+ * registry's grace window — `run()` resolves now, the session closes later
523
+ * (its `close` handler then runs `settle()` → `closed`, a no-op resolve).
524
+ */
525
+ beginServerDrain() {
526
+ if (this.state.kind !== "serving") return;
527
+ const { session, openedAt, watchdog } = this.state;
528
+ this.logWithIdentity("tunnel: server drain notification accepted — opening a replacement connection");
529
+ watchdog.stop();
530
+ this.deregister();
531
+ this.deps.draining.add(session, this.socket, this.deps.opts.drainGraceMs);
532
+ this.state = {
533
+ kind: "draining",
534
+ session,
535
+ openedAt,
536
+ trigger: "server",
537
+ watchdog
538
+ };
539
+ this.completion.resolve({
540
+ kind: "drained",
541
+ uptimeMs: this.uptimeMs()
542
+ });
543
+ }
544
+ /**
545
+ * Client-initiated drain: the engine is shutting this process down. Refuse
546
+ * new invocations and finish in-flight IN PLACE — no redial. The engine
547
+ * waits for in-flight to drain, then tears the connection down.
548
+ */
549
+ beginClientDrain() {
550
+ const s = this.state;
551
+ switch (s.kind) {
552
+ case "serving":
553
+ this.state = {
554
+ kind: "draining",
555
+ session: s.session,
556
+ openedAt: s.openedAt,
557
+ trigger: "client",
558
+ watchdog: s.watchdog
559
+ };
560
+ this.sendClientDrainGoaway(s.session);
561
+ return;
562
+ case "connecting":
563
+ case "handshaking":
564
+ this.settle({
565
+ kind: "retryable",
566
+ reason: "shutting down"
567
+ });
568
+ return;
569
+ case "draining":
570
+ case "closed": return;
571
+ }
572
+ }
573
+ async finishClientDrain(opts) {
574
+ const s = this.state;
575
+ if (s.kind !== "draining" || s.trigger !== "client") return;
576
+ if (opts.force) {
577
+ this.settle({
578
+ kind: "served",
579
+ uptimeMs: this.uptimeMs()
580
+ }, "client drain grace expired");
581
+ return;
582
+ }
583
+ await this.closeSessionGracefully(s.session);
584
+ }
585
+ startWatchdog(session) {
586
+ const watchdog = new Watchdog(session, this.deps.opts, () => {
587
+ this.logWithIdentity("tunnel: pings missed — reconnecting");
588
+ this.settle({
589
+ kind: "served",
590
+ uptimeMs: this.uptimeMs()
591
+ }, "ping watchdog missed too many acknowledgements");
592
+ });
593
+ watchdog.start();
594
+ return watchdog;
595
+ }
596
+ };
597
+
598
+ //#endregion
599
+ export { runConnection };
600
+ //# sourceMappingURL=connection.js.map