@restatedev/restate-sdk 1.18.0 → 1.18.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/common_api.d.cts.map +1 -1
- package/dist/common_api.d.ts.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/connect/env.cjs +208 -0
- package/dist/endpoint/connect/env.js +201 -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 +62 -0
- package/dist/endpoint/connect/key.js +62 -0
- package/dist/endpoint/connect/key.js.map +1 -0
- 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 +269 -0
- package/dist/endpoint/tunnel/types.d.cts.map +1 -0
- package/dist/endpoint/tunnel/types.d.ts +269 -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/index.cjs +2 -0
- package/dist/index.d.cts +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -1
- package/dist/node.cjs +2 -0
- package/dist/node.d.cts +4 -1
- package/dist/node.d.cts.map +1 -1
- package/dist/node.d.ts +4 -1
- 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/rpc.d.ts.map +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { resolveTargets, targetKey } from "./targets.js";
|
|
2
|
+
import { runConnection } from "./connection.js";
|
|
3
|
+
import { Backoff, MIN_UPTIME_FOR_BACKOFF_RESET_MS } from "./backoff.js";
|
|
4
|
+
import { delay, raceAbortable } from "./util.js";
|
|
5
|
+
|
|
6
|
+
//#region src/endpoint/tunnel/supervisor.ts
|
|
7
|
+
function formatTargetList(keys) {
|
|
8
|
+
return keys.length === 0 ? "<none>" : keys.join(", ");
|
|
9
|
+
}
|
|
10
|
+
var Supervisor = class {
|
|
11
|
+
slots = /* @__PURE__ */ new Map();
|
|
12
|
+
/** Aborting this cascades to every slot (each slot chains its ctl to it). */
|
|
13
|
+
stopSignal = new AbortController();
|
|
14
|
+
/** Wakes the resolve loop out of a sleep / DNS race (E3). */
|
|
15
|
+
wake = new AbortController();
|
|
16
|
+
stopping = false;
|
|
17
|
+
fatal;
|
|
18
|
+
lastResolvedKeys;
|
|
19
|
+
/** Resolves when the resolve loop has exited AND every slot has settled. */
|
|
20
|
+
done;
|
|
21
|
+
constructor(opts, deps, hooks, log) {
|
|
22
|
+
this.opts = opts;
|
|
23
|
+
this.deps = deps;
|
|
24
|
+
this.hooks = hooks;
|
|
25
|
+
this.log = log;
|
|
26
|
+
this.stopSignal.signal.addEventListener("abort", () => this.wake.abort(), { once: true });
|
|
27
|
+
this.done = this.supervise();
|
|
28
|
+
}
|
|
29
|
+
get fatalError() {
|
|
30
|
+
return this.fatal;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Stop starting/resolving new connections; existing slots keep running so
|
|
34
|
+
* their connections can finish draining in place (client-initiated drain).
|
|
35
|
+
*/
|
|
36
|
+
stopResolving() {
|
|
37
|
+
this.stopping = true;
|
|
38
|
+
this.log("tunnel: supervisor stopping target resolution");
|
|
39
|
+
this.wake.abort();
|
|
40
|
+
}
|
|
41
|
+
/** Abort every slot and the resolve loop (engine teardown). */
|
|
42
|
+
abortAll() {
|
|
43
|
+
this.stopping = true;
|
|
44
|
+
this.log("tunnel: supervisor aborting all connections");
|
|
45
|
+
this.stopSignal.abort();
|
|
46
|
+
}
|
|
47
|
+
startSlot(key, target) {
|
|
48
|
+
const ctl = new AbortController();
|
|
49
|
+
this.stopSignal.signal.addEventListener("abort", () => ctl.abort(), {
|
|
50
|
+
once: true,
|
|
51
|
+
signal: ctl.signal
|
|
52
|
+
});
|
|
53
|
+
const slot = {
|
|
54
|
+
ctl,
|
|
55
|
+
done: Promise.resolve()
|
|
56
|
+
};
|
|
57
|
+
slot.done = this.runSlot(target, ctl).finally(() => {
|
|
58
|
+
if (this.slots.get(key) === slot) this.slots.delete(key);
|
|
59
|
+
});
|
|
60
|
+
this.slots.set(key, slot);
|
|
61
|
+
}
|
|
62
|
+
/** The reconnect policy's bounds: why to stop, or undefined to keep trying. */
|
|
63
|
+
giveUpReason(attempts, streakStartedAt) {
|
|
64
|
+
const { reconnectMaxAttempts, reconnectMaxDurationMs } = this.opts;
|
|
65
|
+
if (reconnectMaxAttempts !== void 0 && attempts >= reconnectMaxAttempts) return `gave up reconnecting after ${attempts} attempt(s) (reconnectRetryPolicy.maxAttempts)`;
|
|
66
|
+
if (reconnectMaxDurationMs !== void 0 && streakStartedAt !== void 0 && Date.now() - streakStartedAt >= reconnectMaxDurationMs) return `gave up reconnecting after ${Date.now() - streakStartedAt} ms (reconnectRetryPolicy.maxDuration)`;
|
|
67
|
+
}
|
|
68
|
+
/** The per-server loop: dial → serve → classify outcome → backoff → redial. */
|
|
69
|
+
async runSlot(target, ctl) {
|
|
70
|
+
const backoff = new Backoff(this.opts.reconnectInitialMs, this.opts.reconnectFactor, this.opts.reconnectMaxMs);
|
|
71
|
+
let attempts = 0;
|
|
72
|
+
let streakStartedAt;
|
|
73
|
+
while (!this.stopping && !ctl.signal.aborted && this.fatal === void 0) {
|
|
74
|
+
attempts++;
|
|
75
|
+
streakStartedAt ??= Date.now();
|
|
76
|
+
const outcome = await runConnection(target, ctl.signal, this.deps);
|
|
77
|
+
if (this.stopping || ctl.signal.aborted) break;
|
|
78
|
+
if (outcome.kind === "fatal") {
|
|
79
|
+
this.fatal = /* @__PURE__ */ new Error(`tunnel: ${outcome.reason}`);
|
|
80
|
+
this.log(`tunnel: FATAL — ${outcome.reason}; stopping all connections`, "debug");
|
|
81
|
+
this.hooks.onFatal(this.fatal);
|
|
82
|
+
this.stopSignal.abort();
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
if (outcome.kind === "served" || outcome.kind === "drained") {
|
|
86
|
+
const heldLongEnough = outcome.uptimeMs >= MIN_UPTIME_FOR_BACKOFF_RESET_MS;
|
|
87
|
+
if (heldLongEnough) {
|
|
88
|
+
backoff.reset();
|
|
89
|
+
attempts = 0;
|
|
90
|
+
streakStartedAt = void 0;
|
|
91
|
+
}
|
|
92
|
+
if (outcome.kind === "drained" && heldLongEnough) {
|
|
93
|
+
this.log("tunnel: draining — reconnecting immediately", "info");
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
this.log(outcome.kind === "drained" ? "tunnel: drained shortly after connecting — reconnecting with backoff" : "tunnel: connection ended — reconnecting", "warn");
|
|
97
|
+
} else this.log(`tunnel: ${outcome.reason} — reconnecting`, "warn");
|
|
98
|
+
const gaveUp = this.giveUpReason(attempts, streakStartedAt);
|
|
99
|
+
if (gaveUp !== void 0 && this.hooks.hasOtherConnections()) {
|
|
100
|
+
this.log(`tunnel: ${gaveUp} for ${targetKey(target)} — other connections keep serving`, "warn");
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (gaveUp !== void 0) {
|
|
104
|
+
this.fatal = /* @__PURE__ */ new Error(`tunnel: ${gaveUp}`);
|
|
105
|
+
this.log(`tunnel: FATAL — ${gaveUp}; stopping all connections`, "debug");
|
|
106
|
+
this.hooks.onFatal(this.fatal);
|
|
107
|
+
this.stopSignal.abort();
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
await delay(backoff.next(), ctl.signal);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** Resolve the server set, reconcile slots, repeat. For SRV discovery the
|
|
114
|
+
* set is re-resolved every resolveIntervalMs; an explicit set is fixed. */
|
|
115
|
+
async supervise() {
|
|
116
|
+
let resolutionFailures = 0;
|
|
117
|
+
let resolutionStreakStartedAt;
|
|
118
|
+
while (!this.stopping && this.fatal === void 0) {
|
|
119
|
+
let targets;
|
|
120
|
+
try {
|
|
121
|
+
const resolution = resolveTargets({
|
|
122
|
+
...this.opts,
|
|
123
|
+
logger: this.log
|
|
124
|
+
});
|
|
125
|
+
resolution.catch(() => {});
|
|
126
|
+
const raced = await raceAbortable(resolution, this.wake.signal);
|
|
127
|
+
if (raced === null) break;
|
|
128
|
+
targets = raced;
|
|
129
|
+
} catch (err) {
|
|
130
|
+
this.log(`tunnel: target resolution failed: ${err instanceof Error ? err.message : String(err)} — retrying`, "warn");
|
|
131
|
+
if (this.slots.size === 0) {
|
|
132
|
+
resolutionFailures++;
|
|
133
|
+
resolutionStreakStartedAt ??= Date.now();
|
|
134
|
+
const gaveUp = this.giveUpReason(resolutionFailures, resolutionStreakStartedAt);
|
|
135
|
+
if (gaveUp !== void 0) {
|
|
136
|
+
this.fatal = /* @__PURE__ */ new Error(`tunnel: ${gaveUp}`);
|
|
137
|
+
this.log(`tunnel: FATAL — ${gaveUp}; stopping all connections`, "debug");
|
|
138
|
+
this.hooks.onFatal(this.fatal);
|
|
139
|
+
this.stopSignal.abort();
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
await delay(Math.min(5e3, this.opts.resolveIntervalMs), this.wake.signal);
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
resolutionFailures = 0;
|
|
147
|
+
resolutionStreakStartedAt = void 0;
|
|
148
|
+
if (this.stopping || this.fatal !== void 0) break;
|
|
149
|
+
const desired = new Map(targets.map((t) => [targetKey(t), t]));
|
|
150
|
+
const desiredKeys = [...desired.keys()].sort();
|
|
151
|
+
if (this.lastResolvedKeys === void 0 || desiredKeys.length !== this.lastResolvedKeys.length || desiredKeys.some((key, i) => key !== this.lastResolvedKeys[i])) {
|
|
152
|
+
const source = this.opts.srvName === void 0 ? "configured tunnel targets" : `SRV ${this.opts.srvName}`;
|
|
153
|
+
this.log(`tunnel: target set from ${source}: ${formatTargetList(desiredKeys)}`);
|
|
154
|
+
if (this.lastResolvedKeys !== void 0) {
|
|
155
|
+
const previous = new Set(this.lastResolvedKeys);
|
|
156
|
+
const current = new Set(desiredKeys);
|
|
157
|
+
const added = desiredKeys.filter((key) => !previous.has(key));
|
|
158
|
+
const removed = this.lastResolvedKeys.filter((key) => !current.has(key));
|
|
159
|
+
if (added.length > 0) this.log(`tunnel: discovered new tunnel target(s): ${formatTargetList(added)}`, "info");
|
|
160
|
+
if (removed.length > 0) this.log(`tunnel: tunnel target(s) disappeared: ${formatTargetList(removed)}`, "info");
|
|
161
|
+
}
|
|
162
|
+
this.lastResolvedKeys = desiredKeys;
|
|
163
|
+
}
|
|
164
|
+
for (const [key, target] of desired) if (!this.slots.has(key)) {
|
|
165
|
+
this.log(`tunnel: starting connection to ${key}`);
|
|
166
|
+
this.startSlot(key, target);
|
|
167
|
+
}
|
|
168
|
+
for (const [key, slot] of this.slots) if (!desired.has(key)) {
|
|
169
|
+
this.log(`tunnel: ${key} no longer resolves — tearing down`);
|
|
170
|
+
slot.ctl.abort();
|
|
171
|
+
}
|
|
172
|
+
if (this.opts.srvName === void 0) break;
|
|
173
|
+
await delay(this.opts.resolveIntervalMs, this.wake.signal);
|
|
174
|
+
}
|
|
175
|
+
await Promise.all([...this.slots.values()].map((s) => s.done));
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
//#endregion
|
|
180
|
+
export { Supervisor };
|
|
181
|
+
//# sourceMappingURL=supervisor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"supervisor.js","names":["opts: ResolvedOptions","deps: ConnectionDeps","hooks: SupervisorHooks","log: DiagnosticLogger","slot: Slot","streakStartedAt: number | undefined","resolutionStreakStartedAt: number | undefined","targets: Target[]"],"sources":["../../../src/endpoint/tunnel/supervisor.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 slot supervisor.\n// =============================================================================\n//\n// Multi-homing — one tunnel connection per resolved tunnel server (like the\n// Rust client; the slot set IS the resolved set, it is not configurable). The\n// supervisor resolves the server set, reconciles the slot map against it\n// (starting connections to servers that appear, tearing down ones that\n// vanish), and re-resolves every `resolveIntervalMs` for SRV discovery. Each\n// slot runs its own reconnect loop with fatal-vs-retryable classification.\n//\n// Invariants:\n// E1. A FATAL outcome (unauthorized / bad-tunnel-name / name mismatch) on\n// ANY slot stops the WHOLE tunnel — the credentials are shared, so every\n// other slot would hit the same wall. It aborts every slot and reports\n// via `hooks.onFatal`; the engine surfaces it on `error`/`ready`.\n// E2. Backoff resets only after a connection held for\n// MIN_UPTIME_FOR_BACKOFF_RESET_MS; a drain only skips the backoff sleep\n// under the same guard (drain-spam must compound).\n// E3. Teardown is prompt: `abortAll()` aborts in-flight dials via per-slot\n// signals and wakes the resolve loop out of any sleep; the (un-abortable)\n// DNS work is raced against the wake signal, never awaited.\n\nimport type { DiagnosticLogger, ResolvedOptions } from \"./options.js\";\nimport { resolveTargets, targetKey, type Target } from \"./targets.js\";\nimport { runConnection, type ConnectionDeps } from \"./connection.js\";\nimport { Backoff, MIN_UPTIME_FOR_BACKOFF_RESET_MS } from \"./backoff.js\";\nimport { delay, raceAbortable } from \"./util.js\";\n\n/** A running per-server connection loop. */\ninterface Slot {\n ctl: AbortController;\n done: Promise<void>;\n}\n\nfunction formatTargetList(keys: string[]): string {\n return keys.length === 0 ? \"<none>\" : keys.join(\", \");\n}\n\nexport interface SupervisorHooks {\n /** A slot hit a non-retryable failure; the whole tunnel must stop (E1). */\n onFatal: (err: Error) => void;\n /** True while any other connection attempt or session is alive. */\n hasOtherConnections: () => boolean;\n}\n\nexport class Supervisor {\n private readonly slots = new Map<string, Slot>();\n /** Aborting this cascades to every slot (each slot chains its ctl to it). */\n private readonly stopSignal = new AbortController();\n /** Wakes the resolve loop out of a sleep / DNS race (E3). */\n private readonly wake = new AbortController();\n private stopping = false;\n private fatal: Error | undefined;\n private lastResolvedKeys: string[] | undefined;\n\n /** Resolves when the resolve loop has exited AND every slot has settled. */\n readonly done: Promise<void>;\n\n constructor(\n private readonly opts: ResolvedOptions,\n private readonly deps: ConnectionDeps,\n private readonly hooks: SupervisorHooks,\n private readonly log: DiagnosticLogger\n ) {\n this.stopSignal.signal.addEventListener(\"abort\", () => this.wake.abort(), {\n once: true,\n });\n this.done = this.supervise();\n }\n\n get fatalError(): Error | undefined {\n return this.fatal;\n }\n\n /**\n * Stop starting/resolving new connections; existing slots keep running so\n * their connections can finish draining in place (client-initiated drain).\n */\n stopResolving(): void {\n this.stopping = true;\n this.log(\"tunnel: supervisor stopping target resolution\");\n this.wake.abort();\n }\n\n /** Abort every slot and the resolve loop (engine teardown). */\n abortAll(): void {\n this.stopping = true;\n this.log(\"tunnel: supervisor aborting all connections\");\n this.stopSignal.abort();\n }\n\n private startSlot(key: string, target: Target): void {\n const ctl = new AbortController();\n // Chain to the global stop so abortAll() cascades; self-detaching.\n this.stopSignal.signal.addEventListener(\"abort\", () => ctl.abort(), {\n once: true,\n signal: ctl.signal,\n });\n const slot: Slot = { ctl, done: Promise.resolve() };\n slot.done = this.runSlot(target, ctl).finally(() => {\n // Guarded: this key may have vanished and re-appeared, in which case a\n // NEWER slot owns it — don't delete someone else's registration.\n if (this.slots.get(key) === slot) this.slots.delete(key);\n });\n this.slots.set(key, slot);\n }\n\n /** The reconnect policy's bounds: why to stop, or undefined to keep trying. */\n private giveUpReason(\n attempts: number,\n streakStartedAt: number | undefined\n ): string | undefined {\n const { reconnectMaxAttempts, reconnectMaxDurationMs } = this.opts;\n if (\n reconnectMaxAttempts !== undefined &&\n attempts >= reconnectMaxAttempts\n ) {\n return `gave up reconnecting after ${attempts} attempt(s) (reconnectRetryPolicy.maxAttempts)`;\n }\n if (\n reconnectMaxDurationMs !== undefined &&\n streakStartedAt !== undefined &&\n Date.now() - streakStartedAt >= reconnectMaxDurationMs\n ) {\n return `gave up reconnecting after ${Date.now() - streakStartedAt} ms (reconnectRetryPolicy.maxDuration)`;\n }\n return undefined;\n }\n\n /** The per-server loop: dial → serve → classify outcome → backoff → redial. */\n private async runSlot(target: Target, ctl: AbortController): Promise<void> {\n const backoff = new Backoff(\n this.opts.reconnectInitialMs,\n this.opts.reconnectFactor,\n this.opts.reconnectMaxMs\n );\n\n // Attempts in a row without a stable connection, and when the streak began.\n let attempts = 0;\n let streakStartedAt: number | undefined;\n while (!this.stopping && !ctl.signal.aborted && this.fatal === undefined) {\n attempts++;\n streakStartedAt ??= Date.now();\n const outcome = await runConnection(target, ctl.signal, this.deps);\n if (this.stopping || ctl.signal.aborted) break;\n if (outcome.kind === \"fatal\") {\n // E1: shared credentials — stop everything.\n this.fatal = new Error(`tunnel: ${outcome.reason}`);\n this.log(\n `tunnel: FATAL — ${outcome.reason}; stopping all connections`,\n \"debug\"\n );\n this.hooks.onFatal(this.fatal);\n this.stopSignal.abort();\n break;\n }\n if (outcome.kind === \"served\" || outcome.kind === \"drained\") {\n // E2: only a connection that actually held resets the backoff.\n const heldLongEnough =\n outcome.uptimeMs >= MIN_UPTIME_FOR_BACKOFF_RESET_MS;\n if (heldLongEnough) {\n backoff.reset();\n attempts = 0;\n streakStartedAt = undefined;\n }\n if (outcome.kind === \"drained\" && heldLongEnough) {\n // A stable connection was asked to rotate and the server is holding\n // the old one open for us — replace it NOW.\n this.log(\"tunnel: draining — reconnecting immediately\", \"info\");\n continue;\n }\n this.log(\n outcome.kind === \"drained\"\n ? \"tunnel: drained shortly after connecting — reconnecting with backoff\"\n : \"tunnel: connection ended — reconnecting\",\n \"warn\"\n );\n } else {\n this.log(`tunnel: ${outcome.reason} — reconnecting`, \"warn\");\n }\n const gaveUp = this.giveUpReason(attempts, streakStartedAt);\n if (gaveUp !== undefined && this.hooks.hasOtherConnections()) {\n // Other servers are serving: drop this one, keep the deployment up.\n // Re-resolution brings the target back with a fresh streak.\n this.log(\n `tunnel: ${gaveUp} for ${targetKey(target)} — other connections keep serving`,\n \"warn\"\n );\n return;\n }\n if (gaveUp !== undefined) {\n this.fatal = new Error(`tunnel: ${gaveUp}`);\n this.log(\n `tunnel: FATAL — ${gaveUp}; stopping all connections`,\n \"debug\"\n );\n this.hooks.onFatal(this.fatal);\n this.stopSignal.abort();\n break;\n }\n await delay(backoff.next(), ctl.signal);\n }\n }\n\n /** Resolve the server set, reconcile slots, repeat. For SRV discovery the\n * set is re-resolved every resolveIntervalMs; an explicit set is fixed. */\n private async supervise(): Promise<void> {\n // Resolution failures while nothing is connected count toward the\n // reconnect bounds too: a wrong SRV name must not retry forever.\n let resolutionFailures = 0;\n let resolutionStreakStartedAt: number | undefined;\n while (!this.stopping && this.fatal === undefined) {\n let targets: Target[];\n try {\n // E3: race the (un-abortable) DNS work against the wake signal so\n // teardown/fatal don't block on a slow resolver — a late result is\n // discarded by the stopping/fatal check below.\n const resolution = resolveTargets({ ...this.opts, logger: this.log });\n resolution.catch(() => {}); // a late rejection must not be unhandled\n const raced = await raceAbortable(resolution, this.wake.signal);\n if (raced === null) break; // woken: stopping or fatal\n targets = raced;\n } catch (err) {\n // Keep whatever slots exist serving; retry the resolution later\n // (the Rust client does the same on SRV failures).\n this.log(\n `tunnel: target resolution failed: ${err instanceof Error ? err.message : String(err)} — retrying`,\n \"warn\"\n );\n if (this.slots.size === 0) {\n resolutionFailures++;\n resolutionStreakStartedAt ??= Date.now();\n const gaveUp = this.giveUpReason(\n resolutionFailures,\n resolutionStreakStartedAt\n );\n if (gaveUp !== undefined) {\n this.fatal = new Error(`tunnel: ${gaveUp}`);\n this.log(\n `tunnel: FATAL — ${gaveUp}; stopping all connections`,\n \"debug\"\n );\n this.hooks.onFatal(this.fatal);\n this.stopSignal.abort();\n break;\n }\n }\n await delay(\n Math.min(5_000, this.opts.resolveIntervalMs),\n this.wake.signal\n );\n continue;\n }\n resolutionFailures = 0;\n resolutionStreakStartedAt = undefined;\n if (this.stopping || this.fatal !== undefined) break;\n\n const desired = new Map(targets.map((t) => [targetKey(t), t] as const));\n const desiredKeys = [...desired.keys()].sort();\n if (\n this.lastResolvedKeys === undefined ||\n desiredKeys.length !== this.lastResolvedKeys.length ||\n desiredKeys.some((key, i) => key !== this.lastResolvedKeys![i])\n ) {\n const source =\n this.opts.srvName === undefined\n ? \"configured tunnel targets\"\n : `SRV ${this.opts.srvName}`;\n this.log(\n `tunnel: target set from ${source}: ${formatTargetList(desiredKeys)}`\n );\n if (this.lastResolvedKeys !== undefined) {\n const previous = new Set(this.lastResolvedKeys);\n const current = new Set(desiredKeys);\n const added = desiredKeys.filter((key) => !previous.has(key));\n const removed = this.lastResolvedKeys.filter(\n (key) => !current.has(key)\n );\n if (added.length > 0) {\n this.log(\n `tunnel: discovered new tunnel target(s): ${formatTargetList(added)}`,\n \"info\"\n );\n }\n if (removed.length > 0) {\n this.log(\n `tunnel: tunnel target(s) disappeared: ${formatTargetList(removed)}`,\n \"info\"\n );\n }\n }\n this.lastResolvedKeys = desiredKeys;\n }\n for (const [key, target] of desired) {\n if (!this.slots.has(key)) {\n this.log(`tunnel: starting connection to ${key}`);\n this.startSlot(key, target);\n }\n }\n for (const [key, slot] of this.slots) {\n if (!desired.has(key)) {\n this.log(`tunnel: ${key} no longer resolves — tearing down`);\n slot.ctl.abort();\n }\n }\n\n if (this.opts.srvName === undefined) break; // explicit servers: fixed set\n await delay(this.opts.resolveIntervalMs, this.wake.signal);\n }\n // Slots still in the map are live; evicted ones have already settled. No\n // slot can start after the loop exits (stopping/fatal both gate startSlot).\n await Promise.all([...this.slots.values()].map((s) => s.done));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('../../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
let node_dns = require("node:dns");
|
|
3
|
+
node_dns = require_rolldown_runtime.__toESM(node_dns);
|
|
4
|
+
|
|
5
|
+
//#region src/endpoint/tunnel/targets.ts
|
|
6
|
+
function formatError(err) {
|
|
7
|
+
return err instanceof Error ? err.message : String(err);
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Parse one explicit tunnel-server address: `"host:port"`, or a URL whose
|
|
11
|
+
* scheme picks TLS (`https`) / plaintext (`http`) for that server.
|
|
12
|
+
* Throws on a malformed address.
|
|
13
|
+
*/
|
|
14
|
+
function parseServerAddress(address) {
|
|
15
|
+
if (address.includes("://")) {
|
|
16
|
+
let url;
|
|
17
|
+
try {
|
|
18
|
+
url = new URL(address);
|
|
19
|
+
} catch {
|
|
20
|
+
throw new Error(`tunnel: invalid tunnel server URL ${JSON.stringify(address)}`);
|
|
21
|
+
}
|
|
22
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error(`tunnel: unsupported tunnel server scheme ${JSON.stringify(url.protocol)} (use http or https)`);
|
|
23
|
+
if (url.pathname !== "/" || url.search !== "") throw new Error(`tunnel: tunnel server URL must not have a path or query: ${JSON.stringify(address)}`);
|
|
24
|
+
const port$1 = url.port !== "" ? Number(url.port) : url.protocol === "https:" ? 443 : 80;
|
|
25
|
+
return {
|
|
26
|
+
host: url.hostname,
|
|
27
|
+
port: port$1,
|
|
28
|
+
servername: url.hostname,
|
|
29
|
+
plaintext: url.protocol === "http:"
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const idx = address.lastIndexOf(":");
|
|
33
|
+
if (idx <= 0 || idx === address.length - 1) throw new Error(`tunnel: invalid tunnel server address ${JSON.stringify(address)} (expected "host:port" or a URL)`);
|
|
34
|
+
const host = address.slice(0, idx);
|
|
35
|
+
const port = Number(address.slice(idx + 1));
|
|
36
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`tunnel: invalid port in tunnel server address ${JSON.stringify(address)}`);
|
|
37
|
+
return {
|
|
38
|
+
host,
|
|
39
|
+
port,
|
|
40
|
+
servername: host
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Resolve the current set of tunnel servers. Called fresh per connection
|
|
45
|
+
* attempt, so DNS changes are picked up across redials.
|
|
46
|
+
*
|
|
47
|
+
* - Explicit `tunnelServers`: parsed as-is (no DNS here — the dial resolves
|
|
48
|
+
* the hostname).
|
|
49
|
+
* - `srvName` (region-derived or given directly): a DNS SRV lookup, each
|
|
50
|
+
* record expanded to ALL of its addresses (priority asc, weight desc).
|
|
51
|
+
*
|
|
52
|
+
* Error taxonomy (mirrors the Rust resolver): a NEGATIVE answer for an SRV
|
|
53
|
+
* target (the name genuinely has no address — ENOTFOUND/ENODATA) removes
|
|
54
|
+
* that target, and an all-negative answer yields an EMPTY list (the
|
|
55
|
+
* supervisor then reconciles everything away, like Rust's empty set). A
|
|
56
|
+
* TRANSPORT error (EAI_AGAIN, timeouts, SERVFAIL) THROWS instead — the
|
|
57
|
+
* supervisor must keep the existing connections serving and retry, not
|
|
58
|
+
* tear down healthy slots over a resolver blip.
|
|
59
|
+
*/
|
|
60
|
+
async function resolveTargets(spec) {
|
|
61
|
+
const log = spec.logger ?? (() => {});
|
|
62
|
+
if (spec.tunnelServers !== void 0) {
|
|
63
|
+
const targets$1 = spec.tunnelServers.map(parseServerAddress);
|
|
64
|
+
if (targets$1.length === 0) throw new Error("tunnel: tunnelServers is empty");
|
|
65
|
+
log(`tunnel: using configured tunnel target(s): ${targets$1.map(targetKey).join(", ")}`);
|
|
66
|
+
return targets$1;
|
|
67
|
+
}
|
|
68
|
+
const srvName = spec.srvName;
|
|
69
|
+
log(`tunnel: resolving tunnel targets from SRV ${srvName}`);
|
|
70
|
+
const records = await node_dns.promises.resolveSrv(srvName);
|
|
71
|
+
records.sort((a, b) => a.priority - b.priority || b.weight - a.weight);
|
|
72
|
+
log(`tunnel: SRV ${srvName} returned ${records.length} record(s): ${records.map((r) => `${r.name}:${r.port}`).join(", ") || "<none>"}`);
|
|
73
|
+
const lookups = await Promise.allSettled(records.map((r) => node_dns.promises.lookup(r.name, { all: true })));
|
|
74
|
+
const targets = [];
|
|
75
|
+
const seen = /* @__PURE__ */ new Set();
|
|
76
|
+
for (let i = 0; i < records.length; i++) {
|
|
77
|
+
const r = records[i];
|
|
78
|
+
const result = lookups[i];
|
|
79
|
+
if (result.status === "rejected") {
|
|
80
|
+
const code = result.reason?.code;
|
|
81
|
+
if (code === "ENOTFOUND" || code === "ENODATA") {
|
|
82
|
+
log(`tunnel: SRV target ${r.name}:${r.port} has no address (${code})`);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
log(`tunnel: address lookup for SRV target ${r.name}:${r.port} failed: ${formatError(result.reason)}`);
|
|
86
|
+
throw result.reason;
|
|
87
|
+
}
|
|
88
|
+
for (const a of result.value) {
|
|
89
|
+
const key = `${a.address}:${r.port}`;
|
|
90
|
+
if (seen.has(key)) continue;
|
|
91
|
+
seen.add(key);
|
|
92
|
+
targets.push({
|
|
93
|
+
host: a.address,
|
|
94
|
+
port: r.port,
|
|
95
|
+
servername: srvName
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
log(`tunnel: SRV ${srvName} expanded to ${targets.length} target(s): ${targets.map(targetKey).join(", ") || "<none>"}`);
|
|
100
|
+
return targets;
|
|
101
|
+
}
|
|
102
|
+
/** Stable identity of a target — the unit of one tunnel connection. */
|
|
103
|
+
function targetKey(t) {
|
|
104
|
+
return `${t.host}:${t.port}`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
//#endregion
|
|
108
|
+
exports.parseServerAddress = parseServerAddress;
|
|
109
|
+
exports.resolveTargets = resolveTargets;
|
|
110
|
+
exports.targetKey = targetKey;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import * as dns from "node:dns";
|
|
2
|
+
|
|
3
|
+
//#region src/endpoint/tunnel/targets.ts
|
|
4
|
+
function formatError(err) {
|
|
5
|
+
return err instanceof Error ? err.message : String(err);
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Parse one explicit tunnel-server address: `"host:port"`, or a URL whose
|
|
9
|
+
* scheme picks TLS (`https`) / plaintext (`http`) for that server.
|
|
10
|
+
* Throws on a malformed address.
|
|
11
|
+
*/
|
|
12
|
+
function parseServerAddress(address) {
|
|
13
|
+
if (address.includes("://")) {
|
|
14
|
+
let url;
|
|
15
|
+
try {
|
|
16
|
+
url = new URL(address);
|
|
17
|
+
} catch {
|
|
18
|
+
throw new Error(`tunnel: invalid tunnel server URL ${JSON.stringify(address)}`);
|
|
19
|
+
}
|
|
20
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error(`tunnel: unsupported tunnel server scheme ${JSON.stringify(url.protocol)} (use http or https)`);
|
|
21
|
+
if (url.pathname !== "/" || url.search !== "") throw new Error(`tunnel: tunnel server URL must not have a path or query: ${JSON.stringify(address)}`);
|
|
22
|
+
const port$1 = url.port !== "" ? Number(url.port) : url.protocol === "https:" ? 443 : 80;
|
|
23
|
+
return {
|
|
24
|
+
host: url.hostname,
|
|
25
|
+
port: port$1,
|
|
26
|
+
servername: url.hostname,
|
|
27
|
+
plaintext: url.protocol === "http:"
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
const idx = address.lastIndexOf(":");
|
|
31
|
+
if (idx <= 0 || idx === address.length - 1) throw new Error(`tunnel: invalid tunnel server address ${JSON.stringify(address)} (expected "host:port" or a URL)`);
|
|
32
|
+
const host = address.slice(0, idx);
|
|
33
|
+
const port = Number(address.slice(idx + 1));
|
|
34
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`tunnel: invalid port in tunnel server address ${JSON.stringify(address)}`);
|
|
35
|
+
return {
|
|
36
|
+
host,
|
|
37
|
+
port,
|
|
38
|
+
servername: host
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Resolve the current set of tunnel servers. Called fresh per connection
|
|
43
|
+
* attempt, so DNS changes are picked up across redials.
|
|
44
|
+
*
|
|
45
|
+
* - Explicit `tunnelServers`: parsed as-is (no DNS here — the dial resolves
|
|
46
|
+
* the hostname).
|
|
47
|
+
* - `srvName` (region-derived or given directly): a DNS SRV lookup, each
|
|
48
|
+
* record expanded to ALL of its addresses (priority asc, weight desc).
|
|
49
|
+
*
|
|
50
|
+
* Error taxonomy (mirrors the Rust resolver): a NEGATIVE answer for an SRV
|
|
51
|
+
* target (the name genuinely has no address — ENOTFOUND/ENODATA) removes
|
|
52
|
+
* that target, and an all-negative answer yields an EMPTY list (the
|
|
53
|
+
* supervisor then reconciles everything away, like Rust's empty set). A
|
|
54
|
+
* TRANSPORT error (EAI_AGAIN, timeouts, SERVFAIL) THROWS instead — the
|
|
55
|
+
* supervisor must keep the existing connections serving and retry, not
|
|
56
|
+
* tear down healthy slots over a resolver blip.
|
|
57
|
+
*/
|
|
58
|
+
async function resolveTargets(spec) {
|
|
59
|
+
const log = spec.logger ?? (() => {});
|
|
60
|
+
if (spec.tunnelServers !== void 0) {
|
|
61
|
+
const targets$1 = spec.tunnelServers.map(parseServerAddress);
|
|
62
|
+
if (targets$1.length === 0) throw new Error("tunnel: tunnelServers is empty");
|
|
63
|
+
log(`tunnel: using configured tunnel target(s): ${targets$1.map(targetKey).join(", ")}`);
|
|
64
|
+
return targets$1;
|
|
65
|
+
}
|
|
66
|
+
const srvName = spec.srvName;
|
|
67
|
+
log(`tunnel: resolving tunnel targets from SRV ${srvName}`);
|
|
68
|
+
const records = await dns.promises.resolveSrv(srvName);
|
|
69
|
+
records.sort((a, b) => a.priority - b.priority || b.weight - a.weight);
|
|
70
|
+
log(`tunnel: SRV ${srvName} returned ${records.length} record(s): ${records.map((r) => `${r.name}:${r.port}`).join(", ") || "<none>"}`);
|
|
71
|
+
const lookups = await Promise.allSettled(records.map((r) => dns.promises.lookup(r.name, { all: true })));
|
|
72
|
+
const targets = [];
|
|
73
|
+
const seen = /* @__PURE__ */ new Set();
|
|
74
|
+
for (let i = 0; i < records.length; i++) {
|
|
75
|
+
const r = records[i];
|
|
76
|
+
const result = lookups[i];
|
|
77
|
+
if (result.status === "rejected") {
|
|
78
|
+
const code = result.reason?.code;
|
|
79
|
+
if (code === "ENOTFOUND" || code === "ENODATA") {
|
|
80
|
+
log(`tunnel: SRV target ${r.name}:${r.port} has no address (${code})`);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
log(`tunnel: address lookup for SRV target ${r.name}:${r.port} failed: ${formatError(result.reason)}`);
|
|
84
|
+
throw result.reason;
|
|
85
|
+
}
|
|
86
|
+
for (const a of result.value) {
|
|
87
|
+
const key = `${a.address}:${r.port}`;
|
|
88
|
+
if (seen.has(key)) continue;
|
|
89
|
+
seen.add(key);
|
|
90
|
+
targets.push({
|
|
91
|
+
host: a.address,
|
|
92
|
+
port: r.port,
|
|
93
|
+
servername: srvName
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
log(`tunnel: SRV ${srvName} expanded to ${targets.length} target(s): ${targets.map(targetKey).join(", ") || "<none>"}`);
|
|
98
|
+
return targets;
|
|
99
|
+
}
|
|
100
|
+
/** Stable identity of a target — the unit of one tunnel connection. */
|
|
101
|
+
function targetKey(t) {
|
|
102
|
+
return `${t.host}:${t.port}`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
//#endregion
|
|
106
|
+
export { parseServerAddress, resolveTargets, targetKey };
|
|
107
|
+
//# sourceMappingURL=targets.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"targets.js","names":["url: URL","port","log: DiagnosticLogger","targets","targets: Target[]"],"sources":["../../../src/endpoint/tunnel/targets.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// Tunnel-server discovery: explicit addresses or region-based DNS SRV.\n\nimport * as dns from \"node:dns\";\n\n/** A dialable tunnel server. */\nexport interface Target {\n host: string;\n port: number;\n /**\n * TLS SNI / verification name. For SRV-discovered targets this is the SRV\n * QUERY name (`tunnel.<region>.restate.cloud` — what the cloud's cert\n * covers), regardless of which per-record host is dialed; for explicit\n * addresses it is the configured host.\n */\n servername: string;\n /**\n * Per-target plaintext override: set when an explicit `http://` URL was\n * given. `undefined` means \"follow the global `tls` option\".\n */\n plaintext?: boolean;\n}\n\ntype DiagnosticLogger = (\n message: string,\n level?: \"debug\" | \"info\" | \"warn\" | \"error\"\n) => void;\n\nfunction formatError(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Parse one explicit tunnel-server address: `\"host:port\"`, or a URL whose\n * scheme picks TLS (`https`) / plaintext (`http`) for that server.\n * Throws on a malformed address.\n */\nexport function parseServerAddress(address: string): Target {\n if (address.includes(\"://\")) {\n let url: URL;\n try {\n url = new URL(address);\n } catch {\n throw new Error(\n `tunnel: invalid tunnel server URL ${JSON.stringify(address)}`\n );\n }\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n throw new Error(\n `tunnel: unsupported tunnel server scheme ${JSON.stringify(url.protocol)} (use http or https)`\n );\n }\n if (url.pathname !== \"/\" || url.search !== \"\") {\n throw new Error(\n `tunnel: tunnel server URL must not have a path or query: ${JSON.stringify(address)}`\n );\n }\n const port =\n url.port !== \"\" ? Number(url.port) : url.protocol === \"https:\" ? 443 : 80;\n return {\n host: url.hostname,\n port,\n servername: url.hostname,\n plaintext: url.protocol === \"http:\",\n };\n }\n // \"host:port\" — split on the LAST colon so IPv6-ish hosts survive.\n const idx = address.lastIndexOf(\":\");\n if (idx <= 0 || idx === address.length - 1) {\n throw new Error(\n `tunnel: invalid tunnel server address ${JSON.stringify(address)} (expected \"host:port\" or a URL)`\n );\n }\n const host = address.slice(0, idx);\n const port = Number(address.slice(idx + 1));\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `tunnel: invalid port in tunnel server address ${JSON.stringify(address)}`\n );\n }\n return { host, port, servername: host };\n}\n\n/**\n * Resolve the current set of tunnel servers. Called fresh per connection\n * attempt, so DNS changes are picked up across redials.\n *\n * - Explicit `tunnelServers`: parsed as-is (no DNS here — the dial resolves\n * the hostname).\n * - `srvName` (region-derived or given directly): a DNS SRV lookup, each\n * record expanded to ALL of its addresses (priority asc, weight desc).\n *\n * Error taxonomy (mirrors the Rust resolver): a NEGATIVE answer for an SRV\n * target (the name genuinely has no address — ENOTFOUND/ENODATA) removes\n * that target, and an all-negative answer yields an EMPTY list (the\n * supervisor then reconciles everything away, like Rust's empty set). A\n * TRANSPORT error (EAI_AGAIN, timeouts, SERVFAIL) THROWS instead — the\n * supervisor must keep the existing connections serving and retry, not\n * tear down healthy slots over a resolver blip.\n */\nexport async function resolveTargets(spec: {\n srvName?: string;\n tunnelServers?: string[];\n logger?: DiagnosticLogger;\n}): Promise<Target[]> {\n const log: DiagnosticLogger = spec.logger ?? (() => {});\n if (spec.tunnelServers !== undefined) {\n const targets = spec.tunnelServers.map(parseServerAddress);\n if (targets.length === 0) {\n throw new Error(\"tunnel: tunnelServers is empty\");\n }\n log(\n `tunnel: using configured tunnel target(s): ${targets.map(targetKey).join(\", \")}`\n );\n return targets;\n }\n const srvName = spec.srvName!;\n log(`tunnel: resolving tunnel targets from SRV ${srvName}`);\n const records = await dns.promises.resolveSrv(srvName);\n records.sort((a, b) => a.priority - b.priority || b.weight - a.weight);\n log(\n `tunnel: SRV ${srvName} returned ${records.length} record(s): ${\n records.map((r) => `${r.name}:${r.port}`).join(\", \") || \"<none>\"\n }`\n );\n // Expand each SRV target to its addresses: the tunnel connects to EVERY\n // resolved address (one connection per IP), exactly like the Rust client,\n // which flat-maps SRV targets through A/AAAA lookups into per-IP URIs.\n // Lookups run concurrently (Rust uses FuturesUnordered) so one slow\n // resolver doesn't serialize the rest. SNI / certificate verification\n // uses the SRV QUERY name (the cloud's cert covers the SRV name, not\n // per-node hostnames) — mirroring the Rust FixedServerNameResolver.\n const lookups = await Promise.allSettled(\n records.map((r) => dns.promises.lookup(r.name, { all: true }))\n );\n const targets: Target[] = [];\n const seen = new Set<string>();\n for (let i = 0; i < records.length; i++) {\n const r = records[i]!;\n const result = lookups[i]!;\n if (result.status === \"rejected\") {\n const code = (result.reason as NodeJS.ErrnoException | undefined)?.code;\n if (code === \"ENOTFOUND\" || code === \"ENODATA\") {\n log(`tunnel: SRV target ${r.name}:${r.port} has no address (${code})`);\n continue; // negative answer: this SRV target genuinely has no address\n }\n // Transport error — fail the whole resolution so the supervisor\n // keeps existing slots and retries.\n log(\n `tunnel: address lookup for SRV target ${r.name}:${r.port} failed: ${formatError(result.reason)}`\n );\n throw result.reason;\n }\n for (const a of result.value) {\n const key = `${a.address}:${r.port}`;\n if (seen.has(key)) continue;\n seen.add(key);\n targets.push({ host: a.address, port: r.port, servername: srvName });\n }\n }\n log(\n `tunnel: SRV ${srvName} expanded to ${targets.length} target(s): ${\n targets.map(targetKey).join(\", \") || \"<none>\"\n }`\n );\n return targets;\n}\n\n/** Stable identity of a target — the unit of one tunnel connection. */\nexport function targetKey(t: Target): string {\n return `${t.host}:${t.port}`;\n}\n"],"mappings":";;;AAsCA,SAAS,YAAY,KAAsB;AACzC,QAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;;;;;;;AAQzD,SAAgB,mBAAmB,SAAyB;AAC1D,KAAI,QAAQ,SAAS,MAAM,EAAE;EAC3B,IAAIA;AACJ,MAAI;AACF,SAAM,IAAI,IAAI,QAAQ;UAChB;AACN,SAAM,IAAI,MACR,qCAAqC,KAAK,UAAU,QAAQ,GAC7D;;AAEH,MAAI,IAAI,aAAa,WAAW,IAAI,aAAa,SAC/C,OAAM,IAAI,MACR,4CAA4C,KAAK,UAAU,IAAI,SAAS,CAA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