@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.
- package/dist/common_api.d.cts +1 -1
- package/dist/common_api.d.cts.map +1 -1
- package/dist/common_api.d.ts +1 -1
- package/dist/common_api.d.ts.map +1 -1
- package/dist/common_api.js.map +1 -1
- package/dist/context.d.cts +3 -0
- package/dist/context.d.cts.map +1 -1
- package/dist/context.d.ts +3 -0
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js.map +1 -1
- package/dist/context_impl.cjs +8 -3
- package/dist/context_impl.js +8 -3
- package/dist/context_impl.js.map +1 -1
- package/dist/endpoint/components.cjs +28 -6
- package/dist/endpoint/components.js +28 -6
- package/dist/endpoint/components.js.map +1 -1
- package/dist/endpoint/connect/env.cjs +206 -0
- package/dist/endpoint/connect/env.js +199 -0
- package/dist/endpoint/connect/env.js.map +1 -0
- package/dist/endpoint/connect/index.cjs +113 -0
- package/dist/endpoint/connect/index.d.cts +41 -0
- package/dist/endpoint/connect/index.d.cts.map +1 -0
- package/dist/endpoint/connect/index.d.ts +41 -0
- package/dist/endpoint/connect/index.d.ts.map +1 -0
- package/dist/endpoint/connect/index.js +114 -0
- package/dist/endpoint/connect/index.js.map +1 -0
- package/dist/endpoint/connect/key.cjs +53 -0
- package/dist/endpoint/connect/key.js +53 -0
- package/dist/endpoint/connect/key.js.map +1 -0
- package/dist/endpoint/handlers/discovery.cjs +12 -2
- package/dist/endpoint/handlers/discovery.js +12 -2
- package/dist/endpoint/handlers/discovery.js.map +1 -1
- package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings.cjs +1 -1
- package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings.js +1 -1
- package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings.js.map +1 -1
- package/dist/endpoint/tunnel/backoff.cjs +37 -0
- package/dist/endpoint/tunnel/backoff.js +36 -0
- package/dist/endpoint/tunnel/backoff.js.map +1 -0
- package/dist/endpoint/tunnel/connection.cjs +604 -0
- package/dist/endpoint/tunnel/connection.js +600 -0
- package/dist/endpoint/tunnel/connection.js.map +1 -0
- package/dist/endpoint/tunnel/draining.cjs +40 -0
- package/dist/endpoint/tunnel/draining.js +40 -0
- package/dist/endpoint/tunnel/draining.js.map +1 -0
- package/dist/endpoint/tunnel/engine.cjs +264 -0
- package/dist/endpoint/tunnel/engine.d.cts +1 -0
- package/dist/endpoint/tunnel/engine.d.ts +1 -0
- package/dist/endpoint/tunnel/engine.js +265 -0
- package/dist/endpoint/tunnel/engine.js.map +1 -0
- package/dist/endpoint/tunnel/forwarded.cjs +34 -0
- package/dist/endpoint/tunnel/forwarded.js +34 -0
- package/dist/endpoint/tunnel/forwarded.js.map +1 -0
- package/dist/endpoint/tunnel/handshake.cjs +98 -0
- package/dist/endpoint/tunnel/handshake.js +97 -0
- package/dist/endpoint/tunnel/handshake.js.map +1 -0
- package/dist/endpoint/tunnel/index.d.cts +3 -0
- package/dist/endpoint/tunnel/index.d.ts +3 -0
- package/dist/endpoint/tunnel/options.cjs +168 -0
- package/dist/endpoint/tunnel/options.d.cts +2 -0
- package/dist/endpoint/tunnel/options.d.ts +2 -0
- package/dist/endpoint/tunnel/options.js +161 -0
- package/dist/endpoint/tunnel/options.js.map +1 -0
- package/dist/endpoint/tunnel/supervisor.cjs +180 -0
- package/dist/endpoint/tunnel/supervisor.js +181 -0
- package/dist/endpoint/tunnel/supervisor.js.map +1 -0
- package/dist/endpoint/tunnel/targets.cjs +110 -0
- package/dist/endpoint/tunnel/targets.js +107 -0
- package/dist/endpoint/tunnel/targets.js.map +1 -0
- package/dist/endpoint/tunnel/types.d.cts +270 -0
- package/dist/endpoint/tunnel/types.d.cts.map +1 -0
- package/dist/endpoint/tunnel/types.d.ts +270 -0
- package/dist/endpoint/tunnel/types.d.ts.map +1 -0
- package/dist/endpoint/tunnel/util.cjs +67 -0
- package/dist/endpoint/tunnel/util.js +65 -0
- package/dist/endpoint/tunnel/util.js.map +1 -0
- package/dist/fetch.d.cts +2 -2
- package/dist/fetch.d.ts +2 -2
- package/dist/index.cjs +2 -0
- package/dist/index.d.cts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +2 -1
- package/dist/lambda.d.cts +2 -2
- package/dist/lambda.d.ts +2 -2
- package/dist/node.cjs +2 -0
- package/dist/node.d.cts +5 -2
- package/dist/node.d.cts.map +1 -1
- package/dist/node.d.ts +5 -2
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +2 -1
- package/dist/node.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/dist/package.js.map +1 -1
- package/dist/types/errors.cjs +4 -2
- package/dist/types/errors.d.cts.map +1 -1
- package/dist/types/errors.d.ts.map +1 -1
- package/dist/types/errors.js +4 -2
- package/dist/types/errors.js.map +1 -1
- package/dist/types/rpc.d.cts +42 -17
- package/dist/types/rpc.d.cts.map +1 -1
- package/dist/types/rpc.d.ts +42 -17
- package/dist/types/rpc.d.ts.map +1 -1
- package/dist/types/rpc.js.map +1 -1
- package/package.json +2 -2
- package/dist/context_impl.d.ts.map +0 -1
- package/dist/endpoint/components.d.ts.map +0 -1
- package/dist/endpoint/discovery.d.ts +0 -184
- package/dist/endpoint/discovery.d.ts.map +0 -1
- package/dist/endpoint/discovery.js +0 -7
- package/dist/endpoint/discovery.js.map +0 -1
- package/dist/endpoint/endpoint.d.ts.map +0 -1
- package/dist/endpoint/handlers/core_logging.d.ts +0 -14
- package/dist/endpoint/handlers/core_logging.d.ts.map +0 -1
- package/dist/endpoint/handlers/discovery.d.ts +0 -5
- package/dist/endpoint/handlers/discovery.d.ts.map +0 -1
- package/dist/endpoint/handlers/fetch.d.ts +0 -5
- package/dist/endpoint/handlers/fetch.d.ts.map +0 -1
- package/dist/endpoint/handlers/generic.d.ts +0 -5
- package/dist/endpoint/handlers/generic.d.ts.map +0 -1
- package/dist/endpoint/handlers/lambda.d.ts +0 -10
- package/dist/endpoint/handlers/lambda.d.ts.map +0 -1
- package/dist/endpoint/handlers/preview.d.ts +0 -5
- package/dist/endpoint/handlers/preview.d.ts.map +0 -1
- package/dist/endpoint/handlers/types.d.ts.map +0 -1
- package/dist/endpoint/handlers/types.js +0 -2
- package/dist/endpoint/handlers/types.js.map +0 -1
- package/dist/endpoint/handlers/utils.d.ts +0 -23
- package/dist/endpoint/handlers/utils.d.ts.map +0 -1
- package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings.d.ts +0 -454
- package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings.d.ts.map +0 -1
- package/dist/endpoint/node_endpoint.d.ts +0 -28
- package/dist/endpoint/node_endpoint.d.ts.map +0 -1
- package/dist/endpoint/types.js +0 -2
- package/dist/endpoint/types.js.map +0 -1
- package/dist/endpoint/withOptions.d.ts +0 -4
- package/dist/endpoint/withOptions.d.ts.map +0 -1
- package/dist/endpoint.js +0 -12
- package/dist/endpoint.js.map +0 -1
- package/dist/error_sanitization.d.ts +0 -13
- package/dist/error_sanitization.d.ts.map +0 -1
- package/dist/hooks.js +0 -2
- package/dist/hooks.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/io.d.ts.map +0 -1
- package/dist/logging/console_logger_transport.d.ts +0 -5
- package/dist/logging/console_logger_transport.d.ts.map +0 -1
- package/dist/logging/logger.d.ts.map +0 -1
- package/dist/user_agent.d.ts +0 -2
- package/dist/user_agent.d.ts.map +0 -1
- package/dist/utils/external_progress_channel.d.ts +0 -19
- package/dist/utils/external_progress_channel.d.ts.map +0 -1
- package/dist/utils/rand.d.ts +0 -13
- package/dist/utils/rand.d.ts.map +0 -1
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { withOptions } from "../withOptions.js";
|
|
2
|
+
import { NodeEndpoint } from "../node_endpoint.js";
|
|
3
|
+
import { resolveOptions } from "./options.js";
|
|
4
|
+
import { DrainingRegistry } from "./draining.js";
|
|
5
|
+
import { Deferred } from "./util.js";
|
|
6
|
+
import { Supervisor } from "./supervisor.js";
|
|
7
|
+
|
|
8
|
+
//#region src/endpoint/tunnel/engine.ts
|
|
9
|
+
/**
|
|
10
|
+
* Counts forwarded invocations in flight and lets a graceful shutdown wait for
|
|
11
|
+
* them to finish. Spans both actively-served and server-drained (detached)
|
|
12
|
+
* sessions, since every dispatch increments and every stream close decrements
|
|
13
|
+
* regardless of which session it belongs to.
|
|
14
|
+
*/
|
|
15
|
+
var InflightTracker = class {
|
|
16
|
+
count = 0;
|
|
17
|
+
notifyDrained;
|
|
18
|
+
get inFlight() {
|
|
19
|
+
return this.count;
|
|
20
|
+
}
|
|
21
|
+
started() {
|
|
22
|
+
this.count++;
|
|
23
|
+
}
|
|
24
|
+
ended() {
|
|
25
|
+
this.count = Math.max(0, this.count - 1);
|
|
26
|
+
if (this.count === 0 && this.notifyDrained !== void 0) {
|
|
27
|
+
const notify = this.notifyDrained;
|
|
28
|
+
this.notifyDrained = void 0;
|
|
29
|
+
notify();
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** Resolve true once nothing is in flight, or false after `graceMs`.
|
|
33
|
+
* Only one shutdown runs at a time, so a single waiter suffices. */
|
|
34
|
+
whenDrained(graceMs) {
|
|
35
|
+
return new Promise((resolve) => {
|
|
36
|
+
if (this.count === 0) {
|
|
37
|
+
resolve(true);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const timer = setTimeout(() => {
|
|
41
|
+
this.notifyDrained = void 0;
|
|
42
|
+
resolve(false);
|
|
43
|
+
}, graceMs);
|
|
44
|
+
timer.unref();
|
|
45
|
+
this.notifyDrained = () => {
|
|
46
|
+
clearTimeout(timer);
|
|
47
|
+
resolve(true);
|
|
48
|
+
};
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* The deployment URL to register, from the `proxy-url` trailer of the
|
|
54
|
+
* handshake (`<proxy base>/<bare environment id>/<name>`), shared contract
|
|
55
|
+
* with the CLI and the Cloud UI:
|
|
56
|
+
*
|
|
57
|
+
* `<proxy base>:9080/<bare environment id>/<name>/http/in-process/9080/`
|
|
58
|
+
*
|
|
59
|
+
* The port is **always 9080** (the proxy), never the zone-specific port the
|
|
60
|
+
* trailer may carry (9081–9083), so every replica and every reconnect prints
|
|
61
|
+
* the same URL. The `/http/in-process/9080/` tail is a constant: an
|
|
62
|
+
* in-process deployment is never dialed, the server routes by the name.
|
|
63
|
+
*/
|
|
64
|
+
function buildDeploymentUrl(proxyUrl) {
|
|
65
|
+
try {
|
|
66
|
+
const proxy = new URL(proxyUrl);
|
|
67
|
+
proxy.port = "9080";
|
|
68
|
+
return `${proxy.toString().replace(/\/+$/, "")}/http/in-process/9080/`;
|
|
69
|
+
} catch {
|
|
70
|
+
return `${proxyUrl.replace(/\/+$/, "")}/http/in-process/9080/`;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const signalShutdownRegistrations = /* @__PURE__ */ new Map();
|
|
74
|
+
const signalShutdownHandlers = /* @__PURE__ */ new Map();
|
|
75
|
+
let signalShutdownInProgress = false;
|
|
76
|
+
async function runGracefulShutdownSignal(signal) {
|
|
77
|
+
if (signalShutdownInProgress) return;
|
|
78
|
+
signalShutdownInProgress = true;
|
|
79
|
+
const registrations = [...signalShutdownRegistrations.get(signal) ?? []];
|
|
80
|
+
await Promise.allSettled(registrations.map((entry) => entry.shutdown(signal)));
|
|
81
|
+
try {
|
|
82
|
+
process.exit(0);
|
|
83
|
+
} finally {
|
|
84
|
+
signalShutdownInProgress = false;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function registerGracefulShutdownSignals(signals, participant) {
|
|
88
|
+
const unregisters = signals.map((signal) => {
|
|
89
|
+
let registrations = signalShutdownRegistrations.get(signal);
|
|
90
|
+
if (registrations === void 0) {
|
|
91
|
+
registrations = /* @__PURE__ */ new Set();
|
|
92
|
+
signalShutdownRegistrations.set(signal, registrations);
|
|
93
|
+
}
|
|
94
|
+
registrations.add(participant);
|
|
95
|
+
if (!signalShutdownHandlers.has(signal)) {
|
|
96
|
+
const handler = () => void runGracefulShutdownSignal(signal);
|
|
97
|
+
signalShutdownHandlers.set(signal, handler);
|
|
98
|
+
process.once(signal, handler);
|
|
99
|
+
}
|
|
100
|
+
return () => {
|
|
101
|
+
const current = signalShutdownRegistrations.get(signal);
|
|
102
|
+
if (current === void 0) return;
|
|
103
|
+
current.delete(participant);
|
|
104
|
+
if (current.size > 0) return;
|
|
105
|
+
const handler = signalShutdownHandlers.get(signal);
|
|
106
|
+
if (handler !== void 0) process.removeListener(signal, handler);
|
|
107
|
+
signalShutdownHandlers.delete(signal);
|
|
108
|
+
signalShutdownRegistrations.delete(signal);
|
|
109
|
+
};
|
|
110
|
+
});
|
|
111
|
+
return () => {
|
|
112
|
+
for (const unregister of unregisters) unregister();
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Connect this deployment to Restate Cloud and serve `services` over the
|
|
117
|
+
* connection. Returns immediately; connection management runs in the
|
|
118
|
+
* background until `close()`/`shutdown()` (or the `signal`) stops it; `ready`
|
|
119
|
+
* settles with the first handshake.
|
|
120
|
+
*
|
|
121
|
+
* The engine entry point behind `connect()`; the identity arrives resolved
|
|
122
|
+
* and `connect()` projects the handle onto its public shape.
|
|
123
|
+
*/
|
|
124
|
+
function startEngine(options) {
|
|
125
|
+
const resolvedOptions = resolveOptions(options);
|
|
126
|
+
const sdkHandler = withOptions(new NodeEndpoint(), {
|
|
127
|
+
services: options.services,
|
|
128
|
+
identityKeys: resolvedOptions.identityKeys,
|
|
129
|
+
defaultServiceOptions: options.defaultServiceOptions,
|
|
130
|
+
logger: options.logger,
|
|
131
|
+
journalValueCodecProvider: options.journalValueCodecProvider
|
|
132
|
+
}).handler({ bidirectional: resolvedOptions.bidirectional });
|
|
133
|
+
const log = resolvedOptions.logger;
|
|
134
|
+
const logWithWorker = (message, level) => log(`${message} (worker_id=${resolvedOptions.tunnelWorkerId})`, level);
|
|
135
|
+
const opts = resolvedOptions;
|
|
136
|
+
const activeSockets = /* @__PURE__ */ new Set();
|
|
137
|
+
const activeConnections = /* @__PURE__ */ new Set();
|
|
138
|
+
const draining = new DrainingRegistry();
|
|
139
|
+
const inflight = new InflightTracker();
|
|
140
|
+
const output = {
|
|
141
|
+
connectionCount: 0,
|
|
142
|
+
lastInfo: void 0,
|
|
143
|
+
fatalError: void 0
|
|
144
|
+
};
|
|
145
|
+
const ready = new Deferred();
|
|
146
|
+
ready.promise.catch(() => {});
|
|
147
|
+
let state;
|
|
148
|
+
const signalUnregisters = [];
|
|
149
|
+
const supervisor = new Supervisor(opts, {
|
|
150
|
+
opts,
|
|
151
|
+
sdkHandler,
|
|
152
|
+
draining,
|
|
153
|
+
activeSockets,
|
|
154
|
+
activeConnections,
|
|
155
|
+
onEstablished: (info, identity) => {
|
|
156
|
+
if (state.kind === "closed") return;
|
|
157
|
+
const firstConnection = output.connectionCount === 0;
|
|
158
|
+
output.connectionCount++;
|
|
159
|
+
output.lastInfo = info;
|
|
160
|
+
if (firstConnection) log(`tunnel: service ready (name=${info.tunnelName}, proxy=${info.proxyUrl}, tunnel=${info.tunnelUrl}, worker_id=${identity.workerId}, connection_id=${identity.connectionId}, target=${identity.target})`, "debug");
|
|
161
|
+
else log(`tunnel: additional connection ready (connections=${output.connectionCount}, name=${info.tunnelName}, worker_id=${identity.workerId}, connection_id=${identity.connectionId}, target=${identity.target})`);
|
|
162
|
+
ready.resolve();
|
|
163
|
+
},
|
|
164
|
+
isShuttingDown: () => state.kind === "draining",
|
|
165
|
+
inflightStarted: () => inflight.started(),
|
|
166
|
+
inflightEnded: () => inflight.ended()
|
|
167
|
+
}, {
|
|
168
|
+
onFatal: (err) => {
|
|
169
|
+
output.fatalError = err;
|
|
170
|
+
ready.reject(err);
|
|
171
|
+
options.onFatal?.(err);
|
|
172
|
+
},
|
|
173
|
+
hasOtherConnections: () => activeConnections.size > 0
|
|
174
|
+
}, logWithWorker);
|
|
175
|
+
state = {
|
|
176
|
+
kind: "running",
|
|
177
|
+
active: {
|
|
178
|
+
supervisor,
|
|
179
|
+
keepAlive: setInterval(() => {}, 2147483647)
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
/** Abrupt teardown; idempotent. Destructures the live machinery from the
|
|
183
|
+
* state, so it can only run while running/draining. */
|
|
184
|
+
const teardown = () => {
|
|
185
|
+
if (state.kind === "closed") return;
|
|
186
|
+
const { supervisor: supervisor$1, keepAlive } = state.active;
|
|
187
|
+
state = { kind: "closed" };
|
|
188
|
+
for (const unregister of signalUnregisters) unregister();
|
|
189
|
+
signalUnregisters.length = 0;
|
|
190
|
+
supervisor$1.abortAll();
|
|
191
|
+
for (const socket of activeSockets) socket.destroy();
|
|
192
|
+
activeSockets.clear();
|
|
193
|
+
draining.destroyAll();
|
|
194
|
+
clearInterval(keepAlive);
|
|
195
|
+
};
|
|
196
|
+
const done = supervisor.done.then(() => {
|
|
197
|
+
teardown();
|
|
198
|
+
ready.reject(output.fatalError ?? /* @__PURE__ */ new Error("tunnel: closed before the first handshake"));
|
|
199
|
+
});
|
|
200
|
+
const drainGracefully = async (active, graceMs) => {
|
|
201
|
+
const { supervisor: supervisor$1 } = active;
|
|
202
|
+
supervisor$1.stopResolving();
|
|
203
|
+
for (const c of [...activeConnections]) c.beginClientDrain();
|
|
204
|
+
logWithWorker(`tunnel: graceful shutdown — refusing new invocations, draining ${inflight.inFlight} in-flight`, "info");
|
|
205
|
+
const drained = await inflight.whenDrained(graceMs);
|
|
206
|
+
await Promise.all([...activeConnections].map((c) => c.finishClientDrain({ force: !drained })));
|
|
207
|
+
teardown();
|
|
208
|
+
await done;
|
|
209
|
+
};
|
|
210
|
+
const close = async () => {
|
|
211
|
+
teardown();
|
|
212
|
+
await done;
|
|
213
|
+
};
|
|
214
|
+
const shutdown = ({ graceMs } = {}) => {
|
|
215
|
+
if (state.kind === "draining") return state.completed;
|
|
216
|
+
if (state.kind === "closed") return done;
|
|
217
|
+
const { active } = state;
|
|
218
|
+
const completed = drainGracefully(active, graceMs ?? resolvedOptions.drainGraceMs);
|
|
219
|
+
state = {
|
|
220
|
+
kind: "draining",
|
|
221
|
+
active,
|
|
222
|
+
completed
|
|
223
|
+
};
|
|
224
|
+
return completed;
|
|
225
|
+
};
|
|
226
|
+
if (resolvedOptions.gracefulShutdown !== void 0) {
|
|
227
|
+
const { signals, graceMs } = resolvedOptions.gracefulShutdown;
|
|
228
|
+
signalUnregisters.push(registerGracefulShutdownSignals(signals, { async shutdown(signal) {
|
|
229
|
+
logWithWorker(`tunnel: received ${signal} — shutting down gracefully`, "info");
|
|
230
|
+
await shutdown({ graceMs });
|
|
231
|
+
} }));
|
|
232
|
+
}
|
|
233
|
+
if (options.signal?.aborted) close();
|
|
234
|
+
else options.signal?.addEventListener("abort", () => void close(), { once: true });
|
|
235
|
+
return {
|
|
236
|
+
close,
|
|
237
|
+
shutdown,
|
|
238
|
+
get connectionCount() {
|
|
239
|
+
return output.connectionCount;
|
|
240
|
+
},
|
|
241
|
+
name: resolvedOptions.name,
|
|
242
|
+
get tunnelName() {
|
|
243
|
+
return output.lastInfo?.tunnelName;
|
|
244
|
+
},
|
|
245
|
+
get proxyUrl() {
|
|
246
|
+
return output.lastInfo?.proxyUrl;
|
|
247
|
+
},
|
|
248
|
+
get tunnelUrl() {
|
|
249
|
+
return output.lastInfo?.tunnelUrl;
|
|
250
|
+
},
|
|
251
|
+
get deploymentUrl() {
|
|
252
|
+
const lastInfo = output.lastInfo;
|
|
253
|
+
if (lastInfo === void 0) return void 0;
|
|
254
|
+
return buildDeploymentUrl(lastInfo.proxyUrl);
|
|
255
|
+
},
|
|
256
|
+
get error() {
|
|
257
|
+
return output.fatalError;
|
|
258
|
+
},
|
|
259
|
+
ready: ready.promise
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
//#endregion
|
|
264
|
+
export { startEngine };
|
|
265
|
+
//# sourceMappingURL=engine.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"engine.js","names":["logWithWorker: typeof log","output: Output","state: EngineState","signalUnregisters: Array<() => void>"],"sources":["../../../src/endpoint/tunnel/engine.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\n// The tunnel engine.\n// =============================================================================\n//\n// startEngine() serves a Restate SDK deployment over OUTBOUND connections to\n// Restate Cloud's tunnel servers — no inbound listener. `connect()` resolves\n// the identity and calls it. The pieces:\n//\n// connection.ts — one dial → role-flip → handshake → serve cycle\n// supervisor.ts — the slot supervisor (one connection per resolved server)\n// handshake.ts — the /_/start-tunnel credentials/trailers exchange\n// forwarded.ts — the /<scheme>/<host>/<port> destination-prefix strip\n// targets.ts — server discovery (SRV per-IP expansion / explicit list)\n// draining.ts — server-drain handover ownership\n// backoff.ts — jittered exponential reconnect policy\n//\n// The engine has three kinds of state, kept deliberately separate:\n//\n// * Injected infrastructure — the registries (activeSockets/activeConnections/\n// draining/inflight) that ConnectionDeps hands to every connection. By\n// definition the per-connection layer reads these, so they are created once\n// and injected, not stored in a lifecycle phase.\n// * Observable output — connectionCount / lastInfo / fatalError, which the\n// handle exposes in every phase (including after close()), so they live in\n// one lifetime record rather than a phase.\n// * Lifecycle state — `EngineState`, a disjoint union whose live phases own\n// the supervisor + the event-loop anchor (and, while draining, the in-flight\n// drain promise). Each transition narrows the state and destructures what it\n// needs, so no function reaches for the live machinery in the wrong phase\n// (and `closed` provably has none).\n\nimport type * as net from \"node:net\";\nimport type { RestateEndpoint } from \"../../endpoint.js\";\nimport { NodeEndpoint } from \"../node_endpoint.js\";\nimport { withOptions } from \"../withOptions.js\";\n\nimport type { EngineHandle, EngineOptions } from \"./types.js\";\nimport { resolveOptions } from \"./options.js\";\nimport type { HandshakeInfo } from \"./handshake.js\";\nimport {\n type ConnectionDeps,\n type ConnectionIdentity,\n type DrainableConnection,\n} from \"./connection.js\";\nimport { DrainingRegistry } from \"./draining.js\";\nimport { Supervisor } from \"./supervisor.js\";\nimport { Deferred } from \"./util.js\";\n\n/**\n * Counts forwarded invocations in flight and lets a graceful shutdown wait for\n * them to finish. Spans both actively-served and server-drained (detached)\n * sessions, since every dispatch increments and every stream close decrements\n * regardless of which session it belongs to.\n */\nclass InflightTracker {\n private count = 0;\n private notifyDrained: (() => void) | undefined;\n\n get inFlight(): number {\n return this.count;\n }\n\n started(): void {\n this.count++;\n }\n\n ended(): void {\n this.count = Math.max(0, this.count - 1);\n if (this.count === 0 && this.notifyDrained !== undefined) {\n const notify = this.notifyDrained;\n this.notifyDrained = undefined;\n notify();\n }\n }\n\n /** Resolve true once nothing is in flight, or false after `graceMs`.\n * Only one shutdown runs at a time, so a single waiter suffices. */\n whenDrained(graceMs: number): Promise<boolean> {\n return new Promise((resolve) => {\n if (this.count === 0) {\n resolve(true);\n return;\n }\n const timer = setTimeout(() => {\n this.notifyDrained = undefined;\n resolve(false);\n }, graceMs);\n timer.unref();\n this.notifyDrained = () => {\n clearTimeout(timer);\n resolve(true);\n };\n });\n }\n}\n\n/**\n * The deployment URL to register, from the `proxy-url` trailer of the\n * handshake (`<proxy base>/<bare environment id>/<name>`), shared contract\n * with the CLI and the Cloud UI:\n *\n * `<proxy base>:9080/<bare environment id>/<name>/http/in-process/9080/`\n *\n * The port is **always 9080** (the proxy), never the zone-specific port the\n * trailer may carry (9081–9083), so every replica and every reconnect prints\n * the same URL. The `/http/in-process/9080/` tail is a constant: an\n * in-process deployment is never dialed, the server routes by the name.\n */\nexport function buildDeploymentUrl(proxyUrl: string): string {\n try {\n const proxy = new URL(proxyUrl);\n proxy.port = \"9080\";\n const base = proxy.toString().replace(/\\/+$/, \"\");\n return `${base}/http/in-process/9080/`;\n } catch {\n return `${proxyUrl.replace(/\\/+$/, \"\")}/http/in-process/9080/`;\n }\n}\n\n/** The engine's observable output — readable from the handle in every phase. */\ninterface Output {\n connectionCount: number;\n lastInfo: HandshakeInfo | undefined;\n fatalError: Error | undefined;\n}\n\n/** The live machinery, owned by the running/draining phases and gone in closed. */\ninterface Active {\n readonly supervisor: Supervisor;\n /** Anchors the event loop while live (a bare awaited promise won't keep Node\n * alive between a session closing and the next redial timer). */\n readonly keepAlive: NodeJS.Timeout;\n}\n\n/** The engine lifecycle as one disjoint state; live phases carry `Active`. */\ntype EngineState =\n | { readonly kind: \"running\"; readonly active: Active }\n | {\n readonly kind: \"draining\";\n readonly active: Active;\n readonly completed: Promise<void>;\n }\n | { readonly kind: \"closed\" };\n\ninterface SignalShutdownParticipant {\n shutdown(signal: NodeJS.Signals): Promise<void>;\n}\n\nconst signalShutdownRegistrations = new Map<\n NodeJS.Signals,\n Set<SignalShutdownParticipant>\n>();\nconst signalShutdownHandlers = new Map<NodeJS.Signals, () => void>();\nlet signalShutdownInProgress = false;\n\nasync function runGracefulShutdownSignal(\n signal: NodeJS.Signals\n): Promise<void> {\n if (signalShutdownInProgress) return;\n signalShutdownInProgress = true;\n const registrations = [...(signalShutdownRegistrations.get(signal) ?? [])];\n await Promise.allSettled(\n registrations.map((entry) => entry.shutdown(signal))\n );\n try {\n process.exit(0);\n } finally {\n // Tests stub process.exit(); real process.exit() does not return.\n signalShutdownInProgress = false;\n }\n}\n\nfunction registerGracefulShutdownSignals(\n signals: NodeJS.Signals[],\n participant: SignalShutdownParticipant\n): () => void {\n const unregisters = signals.map((signal) => {\n let registrations = signalShutdownRegistrations.get(signal);\n if (registrations === undefined) {\n registrations = new Set();\n signalShutdownRegistrations.set(signal, registrations);\n }\n registrations.add(participant);\n if (!signalShutdownHandlers.has(signal)) {\n const handler = () => void runGracefulShutdownSignal(signal);\n signalShutdownHandlers.set(signal, handler);\n process.once(signal, handler);\n }\n return () => {\n const current = signalShutdownRegistrations.get(signal);\n if (current === undefined) return;\n current.delete(participant);\n if (current.size > 0) return;\n const handler = signalShutdownHandlers.get(signal);\n if (handler !== undefined) process.removeListener(signal, handler);\n signalShutdownHandlers.delete(signal);\n signalShutdownRegistrations.delete(signal);\n };\n });\n return () => {\n for (const unregister of unregisters) unregister();\n };\n}\n\n/**\n * Connect this deployment to Restate Cloud and serve `services` over the\n * connection. Returns immediately; connection management runs in the\n * background until `close()`/`shutdown()` (or the `signal`) stops it; `ready`\n * settles with the first handshake.\n *\n * The engine entry point behind `connect()`; the identity arrives resolved\n * and `connect()` projects the handle onto its public shape.\n */\nexport function startEngine(options: EngineOptions): EngineHandle {\n const resolvedOptions = resolveOptions(options);\n\n // Built once, shared across connections and streams (it is stateless per\n // call). identityKeys delegates per-request JWT verification to the SDK —\n // it checks `aud` against the post-strip `req.url` pathname.\n const sdkHandler = withOptions<RestateEndpoint>(new NodeEndpoint(), {\n services: options.services,\n // The environment's signing key IS the request-identity key: every\n // forwarded request must carry a JWT signed by this environment.\n identityKeys: resolvedOptions.identityKeys,\n defaultServiceOptions: options.defaultServiceOptions,\n logger: options.logger,\n journalValueCodecProvider: options.journalValueCodecProvider,\n }).handler({ bidirectional: resolvedOptions.bidirectional });\n\n // Diagnostics: the SDK logger by default (see resolveDiagnosticLogger).\n const log = resolvedOptions.logger;\n const logWithWorker: typeof log = (message, level) =>\n log(`${message} (worker_id=${resolvedOptions.tunnelWorkerId})`, level);\n const opts = resolvedOptions;\n\n // Injected infrastructure: the per-connection layer reads these via deps.\n const activeSockets = new Set<net.Socket>();\n const activeConnections = new Set<DrainableConnection>();\n const draining = new DrainingRegistry();\n const inflight = new InflightTracker();\n\n // Observable output (valid in every phase, including after close).\n const output: Output = {\n connectionCount: 0,\n lastInfo: undefined,\n fatalError: undefined,\n };\n\n // Resolves on the first successful handshake; rejects on a fatal stop or if\n // the tunnel closes before connecting. The catch keeps a never-awaited\n // rejection from surfacing as unhandled.\n const ready = new Deferred<void>();\n void ready.promise.catch(() => {});\n\n // Assigned synchronously below once the live machinery exists; the deps\n // closures only read it at runtime, long after.\n let state: EngineState;\n\n // Opt-in process-signal registrations, removed on teardown so a closed\n // connection can never later intercept a signal and exit the host process.\n const signalUnregisters: Array<() => void> = [];\n\n const connectionDeps: ConnectionDeps = {\n opts,\n sdkHandler,\n draining,\n activeSockets,\n activeConnections,\n onEstablished: (info, identity: ConnectionIdentity) => {\n if (state.kind === \"closed\") return;\n const firstConnection = output.connectionCount === 0;\n output.connectionCount++;\n output.lastInfo = info;\n if (firstConnection) {\n log(\n `tunnel: service ready (name=${info.tunnelName}, proxy=${info.proxyUrl}, tunnel=${info.tunnelUrl}, worker_id=${identity.workerId}, connection_id=${identity.connectionId}, target=${identity.target})`,\n \"debug\"\n );\n } else {\n log(\n `tunnel: additional connection ready (connections=${output.connectionCount}, name=${info.tunnelName}, worker_id=${identity.workerId}, connection_id=${identity.connectionId}, target=${identity.target})`\n );\n }\n ready.resolve();\n },\n isShuttingDown: () => state.kind === \"draining\",\n inflightStarted: () => inflight.started(),\n inflightEnded: () => inflight.ended(),\n };\n\n const supervisor = new Supervisor(\n opts,\n connectionDeps,\n {\n onFatal: (err) => {\n output.fatalError = err; // E1 surfaces on ready/error\n ready.reject(err);\n options.onFatal?.(err);\n },\n hasOtherConnections: () => activeConnections.size > 0,\n },\n logWithWorker\n );\n\n const keepAlive = setInterval(() => {}, 0x7fffffff);\n\n state = { kind: \"running\", active: { supervisor, keepAlive } };\n\n // ---- transitions ----\n\n /** Abrupt teardown; idempotent. Destructures the live machinery from the\n * state, so it can only run while running/draining. */\n const teardown = (): void => {\n if (state.kind === \"closed\") return;\n const { supervisor, keepAlive } = state.active;\n state = { kind: \"closed\" };\n for (const unregister of signalUnregisters) unregister();\n signalUnregisters.length = 0;\n supervisor.abortAll();\n for (const socket of activeSockets) socket.destroy();\n activeSockets.clear();\n draining.destroyAll();\n clearInterval(keepAlive);\n };\n\n // Resolves when the supervisor has fully wound down; then tear down (covers a\n // fatal that stopped us with no close()/shutdown() call) and settle `ready`.\n const done = supervisor.done.then(() => {\n teardown();\n ready.reject(\n output.fatalError ??\n new Error(\"tunnel: closed before the first handshake\")\n );\n });\n\n const drainGracefully = async (\n active: Active,\n graceMs: number\n ): Promise<void> => {\n const { supervisor } = active;\n // Stop dialing/resolving new connections (existing ones keep serving) and\n // move every live connection into a client-drain: serving ones refuse new\n // invocations and finish in-flight in place; not-yet-serving ones abort.\n // Snapshot — beginClientDrain may settle a connection, removing it.\n supervisor.stopResolving();\n for (const c of [...activeConnections]) c.beginClientDrain();\n logWithWorker(\n `tunnel: graceful shutdown — refusing new invocations, draining ${inflight.inFlight} in-flight`,\n \"info\"\n );\n const drained = await inflight.whenDrained(graceMs);\n // In-flight drained: ask h2 to close cleanly. Grace elapsed: force the\n // still-open sessions down, which tears down any stuck streams.\n await Promise.all(\n [...activeConnections].map((c) =>\n c.finishClientDrain({ force: !drained })\n )\n );\n // Now tear down the supervisor and any idle retry loops. For the graceful\n // case the live h2 sessions have already closed; for the forced case this\n // is idempotent cleanup.\n teardown();\n await done;\n };\n\n const close = async (): Promise<void> => {\n teardown();\n await done;\n };\n\n const shutdown = ({ graceMs }: { graceMs?: number } = {}): Promise<void> => {\n // Coalesce: a drain already in progress, or already closed.\n if (state.kind === \"draining\") return state.completed;\n if (state.kind === \"closed\") return done;\n // Start the drain and record its promise on the state before the first\n // await, so every connection sees isShuttingDown() for the whole drain.\n // (drainGracefully runs synchronously up to inflight.whenDrained, so no new\n // invocation can interleave before `state` is set.)\n const { active } = state;\n const completed = drainGracefully(\n active,\n graceMs ?? resolvedOptions.drainGraceMs\n );\n state = { kind: \"draining\", active, completed };\n return completed;\n };\n\n // Install process-signal handlers (graceful shutdown is on by default; see\n // ConnectionOptions.gracefulShutdown). Registered BEFORE the\n // already-aborted-signal handling below, so that path's synchronous close()\n // tears them down via teardown() rather than leaving a live handler on a\n // connection that is already closed.\n if (resolvedOptions.gracefulShutdown !== undefined) {\n const { signals, graceMs } = resolvedOptions.gracefulShutdown;\n signalUnregisters.push(\n registerGracefulShutdownSignals(signals, {\n async shutdown(signal) {\n logWithWorker(\n `tunnel: received ${signal} — shutting down gracefully`,\n \"info\"\n );\n await shutdown({ graceMs });\n },\n })\n );\n }\n\n if (options.signal?.aborted) {\n // An already-aborted signal means \"don't run\" — stop before dialing.\n void close();\n } else {\n options.signal?.addEventListener(\"abort\", () => void close(), {\n once: true,\n });\n }\n\n // ---- the public handle (reads the observable output) ----\n\n return {\n close,\n shutdown,\n get connectionCount() {\n return output.connectionCount;\n },\n name: resolvedOptions.name,\n get tunnelName() {\n return output.lastInfo?.tunnelName;\n },\n get proxyUrl() {\n return output.lastInfo?.proxyUrl;\n },\n get tunnelUrl() {\n return output.lastInfo?.tunnelUrl;\n },\n get deploymentUrl() {\n const lastInfo = output.lastInfo;\n if (lastInfo === undefined) return undefined;\n return buildDeploymentUrl(lastInfo.proxyUrl);\n },\n get error() {\n return output.fatalError;\n },\n ready: ready.promise,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAgEA,IAAM,kBAAN,MAAsB;CACpB,AAAQ,QAAQ;CAChB,AAAQ;CAER,IAAI,WAAmB;AACrB,SAAO,KAAK;;CAGd,UAAgB;AACd,OAAK;;CAGP,QAAc;AACZ,OAAK,QAAQ,KAAK,IAAI,GAAG,KAAK,QAAQ,EAAE;AACxC,MAAI,KAAK,UAAU,KAAK,KAAK,kBAAkB,QAAW;GACxD,MAAM,SAAS,KAAK;AACpB,QAAK,gBAAgB;AACrB,WAAQ;;;;;CAMZ,YAAY,SAAmC;AAC7C,SAAO,IAAI,SAAS,YAAY;AAC9B,OAAI,KAAK,UAAU,GAAG;AACpB,YAAQ,KAAK;AACb;;GAEF,MAAM,QAAQ,iBAAiB;AAC7B,SAAK,gBAAgB;AACrB,YAAQ,MAAM;MACb,QAAQ;AACX,SAAM,OAAO;AACb,QAAK,sBAAsB;AACzB,iBAAa,MAAM;AACnB,YAAQ,KAAK;;IAEf;;;;;;;;;;;;;;;AAgBN,SAAgB,mBAAmB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AC5C,MAAI,MAAM,SAAS,SAAU,QAAO;EAKpC,MAAM,EAAE,WAAW;EACnB,MAAM,YAAY,gBAChB,QACA,WAAW,gBAAgB,aAC5B;AACD,UAAQ;GAAE,MAAM;GAAY;GAAQ;GAAW;AAC/C,SAAO;;AAQT,KAAI,gBAAgB,qBAAqB,QAAW;EAClD,MAAM,EAAE,SAAS,YAAY,gBAAgB;AAC7C,oBAAkB,KAChB,gCAAgC,SAAS,EACvC,MAAM,SAAS,QAAQ;AACrB,iBACE,oBAAoB,OAAO,8BAC3B,OACD;AACD,SAAM,SAAS,EAAE,SAAS,CAAC;KAE9B,CAAC,CACH;;AAGH,KAAI,QAAQ,QAAQ,QAElB,CAAK,OAAO;KAEZ,SAAQ,QAAQ,iBAAiB,eAAe,KAAK,OAAO,EAAE,EAC5D,MAAM,MACP,CAAC;AAKJ,QAAO;EACL;EACA;EACA,IAAI,kBAAkB;AACpB,UAAO,OAAO;;EAEhB,MAAM,gBAAgB;EACtB,IAAI,aAAa;AACf,UAAO,OAAO,UAAU;;EAE1B,IAAI,WAAW;AACb,UAAO,OAAO,UAAU;;EAE1B,IAAI,YAAY;AACd,UAAO,OAAO,UAAU;;EAE1B,IAAI,gBAAgB;GAClB,MAAM,WAAW,OAAO;AACxB,OAAI,aAAa,OAAW,QAAO;AACnC,UAAO,mBAAmB,SAAS,SAAS;;EAE9C,IAAI,QAAQ;AACV,UAAO,OAAO;;EAEhB,OAAO,MAAM;EACd"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/endpoint/tunnel/forwarded.ts
|
|
3
|
+
/**
|
|
4
|
+
* Strip the tunnel's forwarded prefix `/<scheme>/<host>/<port>` and return
|
|
5
|
+
* the tail — the path the SDK should see.
|
|
6
|
+
*
|
|
7
|
+
* A forwarded invocation arrives down the tunnel with its destination
|
|
8
|
+
* encoded in the path (`/http/my-service.ns.svc.cluster.local/9080/invoke/...`);
|
|
9
|
+
* the cloud proxy has already stripped the `/<env>/<tunnel>` rendezvous
|
|
10
|
+
* prefix. For an in-process SDK deployment the scheme/host/port are
|
|
11
|
+
* vestigial (the receiver *is* the service), so we drop exactly those three
|
|
12
|
+
* segments and keep the tail (`/discover`, `/invoke/<svc>/<handler>`, …).
|
|
13
|
+
*
|
|
14
|
+
* The tail is passed through without re-encoding: the SDK verifies each
|
|
15
|
+
* request's identity JWT against the signed service-relative path (its
|
|
16
|
+
* routing and verification tolerate extra path *prefixes*, but re-encoding,
|
|
17
|
+
* normalization or case folding of the tail itself would break the match).
|
|
18
|
+
* The query string is preserved (it is not part of `aud`).
|
|
19
|
+
*
|
|
20
|
+
* Returns `null` if the path isn't a forwarded `/<scheme>/<host>/<port>/...`
|
|
21
|
+
* path.
|
|
22
|
+
*/
|
|
23
|
+
function forwardedTail(rawUrl) {
|
|
24
|
+
const qIdx = rawUrl.indexOf("?");
|
|
25
|
+
const path = qIdx === -1 ? rawUrl : rawUrl.slice(0, qIdx);
|
|
26
|
+
const query = qIdx === -1 ? "" : rawUrl.slice(qIdx);
|
|
27
|
+
const seg = path.split("/");
|
|
28
|
+
if (seg.length < 4 || seg[1] === "" || seg[2] === "" || !/^\d+$/.test(seg[3])) return null;
|
|
29
|
+
const tail = "/" + seg.slice(4).join("/");
|
|
30
|
+
return query ? tail + query : tail;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
//#endregion
|
|
34
|
+
exports.forwardedTail = forwardedTail;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
//#region src/endpoint/tunnel/forwarded.ts
|
|
2
|
+
/**
|
|
3
|
+
* Strip the tunnel's forwarded prefix `/<scheme>/<host>/<port>` and return
|
|
4
|
+
* the tail — the path the SDK should see.
|
|
5
|
+
*
|
|
6
|
+
* A forwarded invocation arrives down the tunnel with its destination
|
|
7
|
+
* encoded in the path (`/http/my-service.ns.svc.cluster.local/9080/invoke/...`);
|
|
8
|
+
* the cloud proxy has already stripped the `/<env>/<tunnel>` rendezvous
|
|
9
|
+
* prefix. For an in-process SDK deployment the scheme/host/port are
|
|
10
|
+
* vestigial (the receiver *is* the service), so we drop exactly those three
|
|
11
|
+
* segments and keep the tail (`/discover`, `/invoke/<svc>/<handler>`, …).
|
|
12
|
+
*
|
|
13
|
+
* The tail is passed through without re-encoding: the SDK verifies each
|
|
14
|
+
* request's identity JWT against the signed service-relative path (its
|
|
15
|
+
* routing and verification tolerate extra path *prefixes*, but re-encoding,
|
|
16
|
+
* normalization or case folding of the tail itself would break the match).
|
|
17
|
+
* The query string is preserved (it is not part of `aud`).
|
|
18
|
+
*
|
|
19
|
+
* Returns `null` if the path isn't a forwarded `/<scheme>/<host>/<port>/...`
|
|
20
|
+
* path.
|
|
21
|
+
*/
|
|
22
|
+
function forwardedTail(rawUrl) {
|
|
23
|
+
const qIdx = rawUrl.indexOf("?");
|
|
24
|
+
const path = qIdx === -1 ? rawUrl : rawUrl.slice(0, qIdx);
|
|
25
|
+
const query = qIdx === -1 ? "" : rawUrl.slice(qIdx);
|
|
26
|
+
const seg = path.split("/");
|
|
27
|
+
if (seg.length < 4 || seg[1] === "" || seg[2] === "" || !/^\d+$/.test(seg[3])) return null;
|
|
28
|
+
const tail = "/" + seg.slice(4).join("/");
|
|
29
|
+
return query ? tail + query : tail;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
//#endregion
|
|
33
|
+
export { forwardedTail };
|
|
34
|
+
//# sourceMappingURL=forwarded.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"forwarded.js","names":[],"sources":["../../../src/endpoint/tunnel/forwarded.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\n// Forwarded-path handling. Pure — no I/O.\n\n/**\n * Strip the tunnel's forwarded prefix `/<scheme>/<host>/<port>` and return\n * the tail — the path the SDK should see.\n *\n * A forwarded invocation arrives down the tunnel with its destination\n * encoded in the path (`/http/my-service.ns.svc.cluster.local/9080/invoke/...`);\n * the cloud proxy has already stripped the `/<env>/<tunnel>` rendezvous\n * prefix. For an in-process SDK deployment the scheme/host/port are\n * vestigial (the receiver *is* the service), so we drop exactly those three\n * segments and keep the tail (`/discover`, `/invoke/<svc>/<handler>`, …).\n *\n * The tail is passed through without re-encoding: the SDK verifies each\n * request's identity JWT against the signed service-relative path (its\n * routing and verification tolerate extra path *prefixes*, but re-encoding,\n * normalization or case folding of the tail itself would break the match).\n * The query string is preserved (it is not part of `aud`).\n *\n * Returns `null` if the path isn't a forwarded `/<scheme>/<host>/<port>/...`\n * path.\n */\nexport function forwardedTail(rawUrl: string): string | null {\n const qIdx = rawUrl.indexOf(\"?\");\n const path = qIdx === -1 ? rawUrl : rawUrl.slice(0, qIdx);\n const query = qIdx === -1 ? \"\" : rawUrl.slice(qIdx);\n const seg = path.split(\"/\"); // [\"\", scheme, host, port, ...tail]\n // The port segment must be numeric — that's what distinguishes a real\n // forwarded prefix from an unprefixed SDK path that happens to have three\n // segments (e.g. `/invoke/Svc/handler` must NOT parse as scheme=invoke,\n // host=Svc, port=handler and dispatch `/` to the SDK).\n if (\n seg.length < 4 ||\n seg[1] === \"\" ||\n seg[2] === \"\" ||\n !/^\\d+$/.test(seg[3]!)\n ) {\n return null;\n }\n const tail = \"/\" + seg.slice(4).join(\"/\");\n return query ? tail + query : tail;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,cAAc,QAA+B;CAC3D,MAAM,OAAO,OAAO,QAAQ,IAAI;CAChC,MAAM,OAAO,SAAS,KAAK,SAAS,OAAO,MAAM,GAAG,KAAK;CACzD,MAAM,QAAQ,SAAS,KAAK,KAAK,OAAO,MAAM,KAAK;CACnD,MAAM,MAAM,KAAK,MAAM,IAAI;AAK3B,KACE,IAAI,SAAS,KACb,IAAI,OAAO,MACX,IAAI,OAAO,MACX,CAAC,QAAQ,KAAK,IAAI,GAAI,CAEtB,QAAO;CAET,MAAM,OAAO,MAAM,IAAI,MAAM,EAAE,CAAC,KAAK,IAAI;AACzC,QAAO,QAAQ,OAAO,QAAQ"}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/endpoint/tunnel/handshake.ts
|
|
3
|
+
const START_TUNNEL_PATH = "/_/start-tunnel";
|
|
4
|
+
/** Handshake deadline — mirrors the tunnel server's own 5s timeout. */
|
|
5
|
+
const HANDSHAKE_TIMEOUT_MS = 5e3;
|
|
6
|
+
/**
|
|
7
|
+
* Run the receiver side of the /_/start-tunnel exchange on its stream.
|
|
8
|
+
* Resolves with an outcome; never rejects.
|
|
9
|
+
*/
|
|
10
|
+
function performHandshake(req, res, creds, timeoutMs = HANDSHAKE_TIMEOUT_MS) {
|
|
11
|
+
return new Promise((resolve) => {
|
|
12
|
+
let settled = false;
|
|
13
|
+
const finish = (outcome) => {
|
|
14
|
+
if (settled) return;
|
|
15
|
+
settled = true;
|
|
16
|
+
clearTimeout(deadline);
|
|
17
|
+
resolve(outcome);
|
|
18
|
+
};
|
|
19
|
+
const deadline = setTimeout(() => {
|
|
20
|
+
finish({
|
|
21
|
+
kind: "retryable",
|
|
22
|
+
reason: `handshake trailers not received within ${timeoutMs}ms`
|
|
23
|
+
});
|
|
24
|
+
req.stream.destroy();
|
|
25
|
+
}, timeoutMs);
|
|
26
|
+
deadline.unref();
|
|
27
|
+
const onTrailers = (trailers) => {
|
|
28
|
+
const status = trailers["tunnel-status"];
|
|
29
|
+
if (status !== "ok") {
|
|
30
|
+
if (status === "unauthorized" || status === "bad-tunnel-name") finish({
|
|
31
|
+
kind: "fatal",
|
|
32
|
+
reason: `tunnel-status: ${String(status)}`
|
|
33
|
+
});
|
|
34
|
+
else finish({
|
|
35
|
+
kind: "retryable",
|
|
36
|
+
reason: `tunnel-status: ${String(status ?? "<missing>")}`
|
|
37
|
+
});
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const tunnelName = trailers["tunnel-name"];
|
|
41
|
+
const proxyUrl = trailers["proxy-url"];
|
|
42
|
+
const tunnelUrl = trailers["tunnel-url"];
|
|
43
|
+
if (typeof tunnelName !== "string" || typeof proxyUrl !== "string" || typeof tunnelUrl !== "string") {
|
|
44
|
+
finish({
|
|
45
|
+
kind: "retryable",
|
|
46
|
+
reason: "handshake ok but proxy-url/tunnel-url/tunnel-name missing"
|
|
47
|
+
});
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (tunnelName !== creds.tunnelName) {
|
|
51
|
+
finish({
|
|
52
|
+
kind: "fatal",
|
|
53
|
+
reason: `tunnel-name mismatch: requested ${JSON.stringify(creds.tunnelName)}, got ${JSON.stringify(tunnelName)}`
|
|
54
|
+
});
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
finish({
|
|
58
|
+
kind: "ok",
|
|
59
|
+
info: {
|
|
60
|
+
tunnelName,
|
|
61
|
+
proxyUrl,
|
|
62
|
+
tunnelUrl
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
req.stream.on("trailers", onTrailers);
|
|
67
|
+
req.on("end", () => {
|
|
68
|
+
if (!settled && req.trailers && Object.keys(req.trailers).length > 0) onTrailers(req.trailers);
|
|
69
|
+
});
|
|
70
|
+
req.on("error", (err) => {
|
|
71
|
+
finish({
|
|
72
|
+
kind: "retryable",
|
|
73
|
+
reason: `handshake stream error: ${err.message}`
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
req.stream.on("close", () => {
|
|
77
|
+
finish({
|
|
78
|
+
kind: "retryable",
|
|
79
|
+
reason: "handshake stream closed before trailers"
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
req.resume();
|
|
83
|
+
res.writeHead(200, {
|
|
84
|
+
authorization: `Bearer ${creds.authToken}`,
|
|
85
|
+
"environment-id": creds.environmentId,
|
|
86
|
+
"tunnel-name": creds.tunnelName,
|
|
87
|
+
"tunnel-worker-id": creds.tunnelWorkerId,
|
|
88
|
+
"tunnel-connection-id": creds.tunnelConnectionId,
|
|
89
|
+
...creds.supportsDrain && { "supports-drain": "true" },
|
|
90
|
+
...creds.supportsClientDrain && { "supports-client-drain": "true" }
|
|
91
|
+
});
|
|
92
|
+
res.end();
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
//#endregion
|
|
97
|
+
exports.START_TUNNEL_PATH = START_TUNNEL_PATH;
|
|
98
|
+
exports.performHandshake = performHandshake;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
//#region src/endpoint/tunnel/handshake.ts
|
|
2
|
+
const START_TUNNEL_PATH = "/_/start-tunnel";
|
|
3
|
+
/** Handshake deadline — mirrors the tunnel server's own 5s timeout. */
|
|
4
|
+
const HANDSHAKE_TIMEOUT_MS = 5e3;
|
|
5
|
+
/**
|
|
6
|
+
* Run the receiver side of the /_/start-tunnel exchange on its stream.
|
|
7
|
+
* Resolves with an outcome; never rejects.
|
|
8
|
+
*/
|
|
9
|
+
function performHandshake(req, res, creds, timeoutMs = HANDSHAKE_TIMEOUT_MS) {
|
|
10
|
+
return new Promise((resolve) => {
|
|
11
|
+
let settled = false;
|
|
12
|
+
const finish = (outcome) => {
|
|
13
|
+
if (settled) return;
|
|
14
|
+
settled = true;
|
|
15
|
+
clearTimeout(deadline);
|
|
16
|
+
resolve(outcome);
|
|
17
|
+
};
|
|
18
|
+
const deadline = setTimeout(() => {
|
|
19
|
+
finish({
|
|
20
|
+
kind: "retryable",
|
|
21
|
+
reason: `handshake trailers not received within ${timeoutMs}ms`
|
|
22
|
+
});
|
|
23
|
+
req.stream.destroy();
|
|
24
|
+
}, timeoutMs);
|
|
25
|
+
deadline.unref();
|
|
26
|
+
const onTrailers = (trailers) => {
|
|
27
|
+
const status = trailers["tunnel-status"];
|
|
28
|
+
if (status !== "ok") {
|
|
29
|
+
if (status === "unauthorized" || status === "bad-tunnel-name") finish({
|
|
30
|
+
kind: "fatal",
|
|
31
|
+
reason: `tunnel-status: ${String(status)}`
|
|
32
|
+
});
|
|
33
|
+
else finish({
|
|
34
|
+
kind: "retryable",
|
|
35
|
+
reason: `tunnel-status: ${String(status ?? "<missing>")}`
|
|
36
|
+
});
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const tunnelName = trailers["tunnel-name"];
|
|
40
|
+
const proxyUrl = trailers["proxy-url"];
|
|
41
|
+
const tunnelUrl = trailers["tunnel-url"];
|
|
42
|
+
if (typeof tunnelName !== "string" || typeof proxyUrl !== "string" || typeof tunnelUrl !== "string") {
|
|
43
|
+
finish({
|
|
44
|
+
kind: "retryable",
|
|
45
|
+
reason: "handshake ok but proxy-url/tunnel-url/tunnel-name missing"
|
|
46
|
+
});
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (tunnelName !== creds.tunnelName) {
|
|
50
|
+
finish({
|
|
51
|
+
kind: "fatal",
|
|
52
|
+
reason: `tunnel-name mismatch: requested ${JSON.stringify(creds.tunnelName)}, got ${JSON.stringify(tunnelName)}`
|
|
53
|
+
});
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
finish({
|
|
57
|
+
kind: "ok",
|
|
58
|
+
info: {
|
|
59
|
+
tunnelName,
|
|
60
|
+
proxyUrl,
|
|
61
|
+
tunnelUrl
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
};
|
|
65
|
+
req.stream.on("trailers", onTrailers);
|
|
66
|
+
req.on("end", () => {
|
|
67
|
+
if (!settled && req.trailers && Object.keys(req.trailers).length > 0) onTrailers(req.trailers);
|
|
68
|
+
});
|
|
69
|
+
req.on("error", (err) => {
|
|
70
|
+
finish({
|
|
71
|
+
kind: "retryable",
|
|
72
|
+
reason: `handshake stream error: ${err.message}`
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
req.stream.on("close", () => {
|
|
76
|
+
finish({
|
|
77
|
+
kind: "retryable",
|
|
78
|
+
reason: "handshake stream closed before trailers"
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
req.resume();
|
|
82
|
+
res.writeHead(200, {
|
|
83
|
+
authorization: `Bearer ${creds.authToken}`,
|
|
84
|
+
"environment-id": creds.environmentId,
|
|
85
|
+
"tunnel-name": creds.tunnelName,
|
|
86
|
+
"tunnel-worker-id": creds.tunnelWorkerId,
|
|
87
|
+
"tunnel-connection-id": creds.tunnelConnectionId,
|
|
88
|
+
...creds.supportsDrain && { "supports-drain": "true" },
|
|
89
|
+
...creds.supportsClientDrain && { "supports-client-drain": "true" }
|
|
90
|
+
});
|
|
91
|
+
res.end();
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
//#endregion
|
|
96
|
+
export { START_TUNNEL_PATH, performHandshake };
|
|
97
|
+
//# sourceMappingURL=handshake.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handshake.js","names":[],"sources":["../../../src/endpoint/tunnel/handshake.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\n// The /_/start-tunnel handshake.\n// =============================================================================\n//\n// The tunnel server (the HTTP/2 client on the role-flipped connection)\n// opens its FIRST stream as `GET /_/start-tunnel`, with a request body that\n// stays open and later delivers HTTP/2 TRAILERS. The exchange:\n//\n// 1. We answer immediately: `200` whose RESPONSE HEADERS carry our\n// credentials — `authorization: Bearer <token>`,\n// `environment-id: env_<id>`, `tunnel-name: <name>`, advisory diagnostic\n// ids (`tunnel-worker-id`, `tunnel-connection-id`), and `supports-drain:\n// true` when the drain handover is enabled (the default — see the\n// /_/drain-tunnel handling in connect.ts).\n// 2. The server validates the credentials, then completes the handshake\n// by sending TRAILERS on its still-open request body:\n// `tunnel-status: ok | unauthorized | bad-tunnel-name | too-many-tunnels`\n// plus, on ok: `proxy-url`, `tunnel-url`, `tunnel-name`.\n//\n// Node gotcha (PoC-verified): the high-level Http2ServerRequest \"trailers\"\n// event does NOT fire. Trailers must be read from the raw stream —\n// `req.stream.on(\"trailers\", ...)` — or from `req.trailers` after \"end\".\n// The body must be drained for either to fire.\n//\n// Outcome taxonomy (drives the reconnect policy in connect.ts):\n// - fatal: unauthorized, bad-tunnel-name, or a tunnel-name echo\n// mismatch. Configuration errors — redialing cannot fix\n// them, and hammering the auth path is harmful.\n// - retryable: too-many-tunnels (often a previous instance still\n// draining), timeout, malformed/missing trailers, stream\n// errors, and unknown statuses (forward compatibility).\n\nimport type * as http2 from \"node:http2\";\n\n/** What the server tells us about the established tunnel. */\nexport interface HandshakeInfo {\n tunnelName: string;\n proxyUrl: string;\n tunnelUrl: string;\n}\n\nexport type HandshakeOutcome =\n | { kind: \"ok\"; info: HandshakeInfo }\n | { kind: \"fatal\"; reason: string }\n | { kind: \"retryable\"; reason: string };\n\nexport interface HandshakeCredentials {\n authToken: string;\n environmentId: string;\n tunnelName: string;\n /** Stable-ish per SDK worker/process, for cross-side diagnostics. */\n tunnelWorkerId: string;\n /** Unique per h2 tunnel connection attempt, for cross-side diagnostics. */\n tunnelConnectionId: string;\n /**\n * Advertise `supports-drain: true`. Only set this when the engine\n * actually implements the `/_/drain-tunnel` handover — advertising it\n * obliges us to open a replacement connection on drain.\n */\n supportsDrain: boolean;\n /**\n * Advertise `supports-client-drain: true`. Tells the server that on\n * shutdown we proactively send GOAWAY and refuse any raced streams with the\n * `x-restate-tunnel-draining` sentinel (rather than dropping them); only\n * then does the server trust that sentinel to deselect this connection.\n */\n supportsClientDrain: boolean;\n}\n\nexport const START_TUNNEL_PATH = \"/_/start-tunnel\";\n\n/** Handshake deadline — mirrors the tunnel server's own 5s timeout. */\nexport const HANDSHAKE_TIMEOUT_MS = 5_000;\n\n/**\n * Run the receiver side of the /_/start-tunnel exchange on its stream.\n * Resolves with an outcome; never rejects.\n */\nexport function performHandshake(\n req: http2.Http2ServerRequest,\n res: http2.Http2ServerResponse,\n creds: HandshakeCredentials,\n timeoutMs: number = HANDSHAKE_TIMEOUT_MS\n): Promise<HandshakeOutcome> {\n return new Promise((resolve) => {\n let settled = false;\n const finish = (outcome: HandshakeOutcome) => {\n if (settled) return;\n settled = true;\n clearTimeout(deadline);\n resolve(outcome);\n };\n\n const deadline = setTimeout(() => {\n finish({\n kind: \"retryable\",\n reason: `handshake trailers not received within ${timeoutMs}ms`,\n });\n req.stream.destroy();\n }, timeoutMs);\n deadline.unref();\n\n const onTrailers = (trailers: http2.IncomingHttpHeaders) => {\n const status = trailers[\"tunnel-status\"];\n if (status !== \"ok\") {\n if (status === \"unauthorized\" || status === \"bad-tunnel-name\") {\n finish({ kind: \"fatal\", reason: `tunnel-status: ${String(status)}` });\n } else {\n finish({\n kind: \"retryable\",\n reason: `tunnel-status: ${String(status ?? \"<missing>\")}`,\n });\n }\n return;\n }\n const tunnelName = trailers[\"tunnel-name\"];\n const proxyUrl = trailers[\"proxy-url\"];\n const tunnelUrl = trailers[\"tunnel-url\"];\n if (\n typeof tunnelName !== \"string\" ||\n typeof proxyUrl !== \"string\" ||\n typeof tunnelUrl !== \"string\"\n ) {\n finish({\n kind: \"retryable\",\n reason: \"handshake ok but proxy-url/tunnel-url/tunnel-name missing\",\n });\n return;\n }\n if (tunnelName !== creds.tunnelName) {\n // We requested a specific name; the server must echo it. A different\n // name means our registration URL would not route here.\n finish({\n kind: \"fatal\",\n reason: `tunnel-name mismatch: requested ${JSON.stringify(creds.tunnelName)}, got ${JSON.stringify(tunnelName)}`,\n });\n return;\n }\n finish({ kind: \"ok\", info: { tunnelName, proxyUrl, tunnelUrl } });\n };\n\n // PoC-verified: only the raw stream's \"trailers\" event fires; also read\n // req.trailers after \"end\" as a belt-and-braces fallback.\n req.stream.on(\"trailers\", onTrailers);\n req.on(\"end\", () => {\n if (!settled && req.trailers && Object.keys(req.trailers).length > 0) {\n onTrailers(req.trailers);\n }\n });\n req.on(\"error\", (err) => {\n finish({\n kind: \"retryable\",\n reason: `handshake stream error: ${err.message}`,\n });\n });\n req.stream.on(\"close\", () => {\n finish({\n kind: \"retryable\",\n reason: \"handshake stream closed before trailers\",\n });\n });\n // Drain the (empty) body so \"end\"/\"trailers\" can fire.\n req.resume();\n\n // Answer with our credentials. The request side stays open for trailers.\n res.writeHead(200, {\n authorization: `Bearer ${creds.authToken}`,\n \"environment-id\": creds.environmentId,\n \"tunnel-name\": creds.tunnelName,\n \"tunnel-worker-id\": creds.tunnelWorkerId,\n \"tunnel-connection-id\": creds.tunnelConnectionId,\n ...(creds.supportsDrain && { \"supports-drain\": \"true\" }),\n ...(creds.supportsClientDrain && { \"supports-client-drain\": \"true\" }),\n });\n res.end();\n });\n}\n"],"mappings":";AA+EA,MAAa,oBAAoB;;AAGjC,MAAa,uBAAuB;;;;;AAMpC,SAAgB,iBACd,KACA,KACA,OACA,YAAoB,sBACO;AAC3B,QAAO,IAAI,SAAS,YAAY;EAC9B,IAAI,UAAU;EACd,MAAM,UAAU,YAA8B;AAC5C,OAAI,QAAS;AACb,aAAU;AACV,gBAAa,SAAS;AACtB,WAAQ,QAAQ;;EAGlB,MAAM,WAAW,iBAAiB;AAChC,UAAO;IACL,MAAM;IACN,QAAQ,0CAA0C,UAAU;IAC7D,CAAC;AACF,OAAI,OAAO,SAAS;KACnB,UAAU;AACb,WAAS,OAAO;EAEhB,MAAM,cAAc,aAAwC;GAC1D,MAAM,SAAS,SAAS;AACxB,OAAI,WAAW,MAAM;AACnB,QAAI,WAAW,kBAAkB,WAAW,kBAC1C,QAAO;KAAE,MAAM;KAAS,QAAQ,kBAAkB,OAAO,OAAO;KAAI,CAAC;QAErE,QAAO;KACL,MAAM;KACN,QAAQ,kBAAkB,OAAO,UAAU,YAAY;KACxD,CAAC;AAEJ;;GAEF,MAAM,aAAa,SAAS;GAC5B,M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