@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 @@
|
|
|
1
|
+
{"version":3,"file":"connection.js","names":["session: http2.Http2Session","opts: ResolvedOptions","onDead: () => void","authToken: string","target: Target","slotSignal: AbortSignal","deps: ConnectionDeps"],"sources":["../../../src/endpoint/tunnel/connection.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// A single tunnel connection attempt.\n// =============================================================================\n//\n// One dial → serve → end cycle against one tunnel server, structured as an\n// explicit pipeline of stages driven by `ConnectionAttempt.drive()`:\n//\n// dial() — connect TCP + TLS, verify ALPN h2 (a self-contained stage\n// that owns its own connect-timeout / abort wiring).\n// establish() — role-flip: become the HTTP/2 *server* on the socket we\n// dialed; obtain the session.\n// handshake — the cloud (h2 client) opens `GET /_/start-tunnel`; we run\n// the credentials/trailers exchange (handshake.ts).\n// serve — each forwarded invocation is one h2 stream; strip\n// `/<scheme>/<host>/<port>` and hand it to the SDK handler.\n//\n// The lifecycle is one explicit `AttemptState` value, and every phase-owned\n// resource lives ON the phase that owns it — the handshake timer on\n// `handshaking`, the liveness `watchdog` on `serving`/`draining` — so each\n// method narrows the state and destructures what it needs (`const { session,\n// watchdog } = this.state`) rather than reaching for nullable instance fields.\n// Only the two genuinely lifetime-scoped things are fields: `socket` (used for\n// teardown in every phase, and handed to the registry on a server drain) and\n// `completion` (resolves `run()` exactly once).\n//\n// Two behaviours don't fit one linear phase:\n// * `run()`-resolution is decoupled from session teardown. A *server* drain\n// resolves `run()` immediately (so the slot redials) while the detached\n// session keeps serving its in-flight invocations from the\n// DrainingRegistry — the zero-drop property.\n// * New-invocation refusal during shutdown is engine-wide, so it is gated on\n// `deps.isShuttingDown()` in addition to this connection's own state.\n\nimport * as net from \"node:net\";\nimport * as tls from \"node:tls\";\nimport * as http2 from \"node:http2\";\nimport { randomBytes } from \"node:crypto\";\n\nimport type { NodeEndpoint } from \"../node_endpoint.js\";\nimport type { DiagnosticLogger, ResolvedOptions } from \"./options.js\";\nimport { buildTlsConnectOptions } from \"./options.js\";\nimport type { Target } from \"./targets.js\";\nimport {\n performHandshake,\n START_TUNNEL_PATH,\n type HandshakeInfo,\n} from \"./handshake.js\";\nimport { forwardedTail } from \"./forwarded.js\";\nimport type { DrainingRegistry } from \"./draining.js\";\n\n/** Why a connection ended — drives the slot's reconnect policy. */\nexport type ConnectionOutcome =\n | { kind: \"served\"; uptimeMs: number } // handshake ok'd, served, then closed → redial\n | { kind: \"drained\"; uptimeMs: number } // server asked us to rotate → redial promptly\n | { kind: \"retryable\"; reason: string } // redial with backoff\n | { kind: \"fatal\"; reason: string }; // stop the tunnel, surface an error\n\n/**\n * Why a connection is draining.\n * - `server`: the cloud sent `/_/drain-tunnel` (it is rotating this tunnel\n * node). We detach + redial; the old session keeps serving in-flight.\n * - `client`: this process is shutting down (SIGTERM / `shutdown()`). We\n * send GOAWAY, refuse raced invocations, and finish in-flight in place,\n * with no redial.\n */\nexport type DrainTrigger = \"server\" | \"client\";\n\nconst CLIENT_DRAIN_SESSION_CLOSE_TIMEOUT_MS = 1_000;\nconst TUNNEL_DRAINING_HEADER = \"x-restate-tunnel-draining\";\nconst CROCKFORD_BASE32 = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\nfunction encodeBase32(value: bigint, length: number): string {\n let out = \"\";\n for (let i = 0; i < length; i++) {\n out = CROCKFORD_BASE32.charAt(Number(value & 31n)) + out;\n value >>= 5n;\n }\n return out;\n}\n\nfunction newTunnelConnectionId(): string {\n let random = 0n;\n for (const byte of randomBytes(10)) {\n random = (random << 8n) | BigInt(byte);\n }\n return `${encodeBase32(BigInt(Date.now()), 10)}${encodeBase32(random, 16)}`;\n}\n\nfunction formatIdentity(workerId: string, connectionId: string): string {\n return `worker_id=${workerId} connection_id=${connectionId}`;\n}\n\nfunction targetLabel(target: Target): string {\n return `${target.host}:${target.port}`;\n}\n\nfunction formatConnectionOutcome(outcome: ConnectionOutcome): string {\n switch (outcome.kind) {\n case \"served\":\n return `served uptimeMs=${outcome.uptimeMs}`;\n case \"drained\":\n return `drained uptimeMs=${outcome.uptimeMs}`;\n case \"retryable\":\n return `retryable reason=${outcome.reason}`;\n case \"fatal\":\n return `fatal reason=${outcome.reason}`;\n }\n}\n\nfunction formatSettings(settings: http2.Settings): string {\n const entries = Object.entries(settings).filter(\n ([, value]) => value !== undefined\n );\n if (entries.length === 0) return \"{}\";\n return `{${entries\n .map(([key, value]) => `${key}=${String(value)}`)\n .join(\", \")}}`;\n}\n\nfunction pathWithoutQuery(url: string | undefined): string {\n if (url === undefined) return \"?\";\n const queryStart = url.indexOf(\"?\");\n return queryStart === -1 ? url : url.slice(0, queryStart);\n}\n\nfunction endInternalError(res: http2.Http2ServerResponse): void {\n try {\n if (!res.headersSent) res.writeHead(500);\n if (!res.writableEnded) res.end(\"tunnel: SDK handler error\");\n } catch {\n // The stream may already be closing; keep the session lifecycle contained.\n }\n}\n\n/** The Node request handler produced by the SDK's createEndpointHandler. */\ntype SdkHandler = ReturnType<NodeEndpoint[\"handler\"]>;\n\n/**\n * The engine's handle on a live connection: lets `shutdown()` ask each one to\n * begin and finish a client-initiated drain.\n */\nexport interface DrainableConnection {\n beginClientDrain(): void;\n finishClientDrain(opts: { force: boolean }): Promise<void>;\n}\n\nexport interface ConnectionIdentity {\n workerId: string;\n connectionId: string;\n target: string;\n}\n\n/** What a connection attempt needs from the engine. */\nexport interface ConnectionDeps {\n opts: ResolvedOptions;\n /** Built once by the engine; stateless per call, shared across streams. */\n sdkHandler: SdkHandler;\n /** Takes ownership of a detached session on a server-drain handover. */\n draining: DrainingRegistry;\n /** Engine-level socket registry, so close() can destroy in-flight dials. */\n activeSockets: Set<net.Socket>;\n /** Live connections the engine can ask to drain on shutdown(). */\n activeConnections: Set<DrainableConnection>;\n /** Called once per successful handshake (count, learned info, ready). */\n onEstablished: (info: HandshakeInfo, identity: ConnectionIdentity) => void;\n /**\n * True once the engine is gracefully shutting down: new forwarded\n * invocations are refused with the drain sentinel instead of dispatched, so\n * the cloud deselects this connection while in-flight invocations finish.\n * Engine-wide (every connection refuses), so it is checked in addition to\n * this connection's own `draining{client}` state.\n */\n isShuttingDown: () => boolean;\n /** A forwarded invocation began executing (counts toward the drain wait). */\n inflightStarted: () => void;\n /** A forwarded invocation finished (its stream closed). */\n inflightEnded: () => void;\n}\n\n/**\n * The connection's lifecycle as one explicit value. Each phase carries exactly\n * the resources it owns, so a method cannot touch a resource that the current\n * phase has no business with:\n *\n * connecting — dialing the socket + TLS; no h2 session yet.\n * handshaking — session is up; `firstRequestTimer` bounds the wait for the\n * cloud to open /_/start-tunnel; `handshake` is set once it\n * does (gate streams park on it until it resolves).\n * serving — handshake ok'd; forwarding invocations to the SDK, with the\n * liveness `watchdog` running.\n * draining — winding down; `trigger` records who asked. A `client` drain\n * refuses new invocations; a `server` drain keeps serving its\n * detached session until the registry closes it.\n * closed — terminal; the session/socket are gone.\n */\ntype AttemptState =\n | { readonly kind: \"connecting\" }\n | {\n readonly kind: \"handshaking\";\n readonly session: http2.Http2Session;\n readonly firstRequestTimer: NodeJS.Timeout;\n handshake: Promise<{ ok: boolean }> | undefined;\n }\n | {\n readonly kind: \"serving\";\n readonly session: http2.Http2Session;\n readonly openedAt: number;\n readonly watchdog: Watchdog;\n }\n | {\n readonly kind: \"draining\";\n readonly session: http2.Http2Session;\n readonly openedAt: number;\n readonly trigger: DrainTrigger;\n readonly watchdog: Watchdog;\n }\n | { readonly kind: \"closed\" };\n\n/** A request classified by its (control or forwarded) intent — pure routing. */\ntype TunnelRequest =\n | { kind: \"start-tunnel\" } // the cloud opening the handshake stream\n | { kind: \"health\" } // GET /_/health liveness probe\n | { kind: \"drain\" } // /_/drain-tunnel: the cloud asks us to rotate\n | { kind: \"forwarded\" }; // anything else: a forwarded invocation\n\n/** Classify an incoming h2 request. Control paths are cloud-originated and\n * arrive UNPREFIXED (before any destination-prefix stripping). */\nfunction classifyRequest(req: http2.Http2ServerRequest): TunnelRequest {\n const rawPath = (req.url ?? \"\").split(\"?\")[0];\n if (req.method === \"GET\" && rawPath === START_TUNNEL_PATH) {\n return { kind: \"start-tunnel\" };\n }\n if (rawPath === \"/_/health\") return { kind: \"health\" };\n if (rawPath === \"/_/drain-tunnel\") return { kind: \"drain\" };\n return { kind: \"forwarded\" };\n}\n\n/** Resolves a connection attempt's outcome exactly once. */\nclass Completion {\n private done = false;\n private resolveFn!: (outcome: ConnectionOutcome) => void;\n readonly promise: Promise<ConnectionOutcome> = new Promise((resolve) => {\n this.resolveFn = resolve;\n });\n\n get settled(): boolean {\n return this.done;\n }\n\n /** Resolve once; returns false if it was already resolved. */\n resolve(outcome: ConnectionOutcome): boolean {\n if (this.done) return false;\n this.done = true;\n this.resolveFn(outcome);\n return true;\n }\n}\n\n/**\n * Liveness watchdog: periodic h2 PING; `pingMaxMissed` consecutive misses mean\n * the connection is half-open (the OS may never surface it), so `onDead` fires.\n * Owns its own timer/miss state so the connection doesn't have to.\n */\nclass Watchdog {\n private interval: NodeJS.Timeout | undefined;\n private missed = 0;\n\n constructor(\n private readonly session: http2.Http2Session,\n private readonly opts: ResolvedOptions,\n private readonly onDead: () => void\n ) {}\n\n start(): void {\n this.interval = setInterval(() => this.beat(), this.opts.pingIntervalMs);\n this.interval.unref();\n }\n\n stop(): void {\n if (this.interval !== undefined) clearInterval(this.interval);\n }\n\n private beat(): void {\n if (this.session.destroyed) return;\n let acked = false;\n try {\n this.session.ping((err) => {\n if (err === null) {\n acked = true;\n this.missed = 0;\n }\n });\n } catch {\n return;\n }\n const t = setTimeout(() => {\n if (acked || this.session.destroyed) return;\n this.missed++;\n if (this.missed >= this.opts.pingMaxMissed) this.onDead();\n }, this.opts.pingTimeoutMs);\n t.unref();\n }\n}\n\n/** Connect result: a connected, ALPN-verified socket, or a terminal outcome. */\ntype DialResult =\n | { ok: true; socket: net.Socket }\n | { ok: false; outcome: ConnectionOutcome };\n\n/**\n * The dial stage: connect TCP (+ TLS), bounded by `connectTimeoutMs` and the\n * slot abort, and require ALPN to have negotiated h2. Owns the socket until it\n * either hands it back connected or destroys it on failure — so all of the\n * connect-phase timer/listener state stays local here.\n */\nfunction dial(\n target: Target,\n deps: ConnectionDeps,\n plaintext: boolean,\n signal: AbortSignal,\n connectionId: string\n): Promise<DialResult> {\n const log = deps.opts.logger;\n const identity = formatIdentity(deps.opts.tunnelWorkerId, connectionId);\n const tlsOptions = plaintext\n ? undefined\n : buildTlsConnectOptions(deps.opts.tls, target.servername);\n const socket = plaintext\n ? net.connect({ host: target.host, port: target.port })\n : tls.connect({ host: target.host, port: target.port, ...tlsOptions });\n\n return new Promise<DialResult>((resolve) => {\n let done = false;\n const label = targetLabel(target);\n const onError = (err: Error) => fail(`socket error: ${err.message}`);\n const onAbort = () => fail(\"tunnel closed\");\n const timer = setTimeout(\n () => fail(`connect timeout after ${deps.opts.connectTimeoutMs}ms`),\n deps.opts.connectTimeoutMs\n );\n timer.unref();\n\n const cleanup = () => {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", onAbort);\n socket.removeListener(\"error\", onError);\n };\n function fail(reason: string) {\n if (done) return;\n done = true;\n cleanup();\n log(\n `tunnel: failed to connect to ${label}: ${reason} (${identity})`,\n \"warn\"\n );\n socket.destroy();\n resolve({ ok: false, outcome: { kind: \"retryable\", reason } });\n }\n\n signal.addEventListener(\"abort\", onAbort, { once: true });\n socket.on(\"error\", onError);\n socket.once(plaintext ? \"connect\" : \"secureConnect\", () => {\n if (done) return;\n socket.setNoDelay(true);\n const alpn = plaintext\n ? \"plaintext\"\n : `tls alpn=${JSON.stringify((socket as tls.TLSSocket).alpnProtocol)}`;\n // Node's http2 requires ALPN to have negotiated h2 before it will run a\n // server session over a TLS socket. A server that doesn't negotiate is\n // too old for this client (see the README's server-version note).\n if (!plaintext && (socket as tls.TLSSocket).alpnProtocol !== \"h2\") {\n fail(\n \"tunnel server did not negotiate h2 ALPN — it predates standard-h2 control traffic and cannot serve this client\"\n );\n return;\n }\n done = true;\n cleanup();\n log(`tunnel: connected socket to ${label} (${alpn}, ${identity})`);\n resolve({ ok: true, socket });\n });\n });\n}\n\n/**\n * Run one connection attempt. Resolves (never rejects) with the outcome\n * when the connection ends; `slotSignal` aborts the attempt at any phase.\n */\nexport function runConnection(\n target: Target,\n slotSignal: AbortSignal,\n deps: ConnectionDeps\n): Promise<ConnectionOutcome> {\n // Resolved once per attempt, before dialing: a file-sourced token is\n // re-read on every redial so rotations are picked up, and a read failure\n // (e.g. mid-rotation) is a retryable outcome rather than a crash.\n let authToken: string;\n try {\n authToken = deps.opts.authToken();\n } catch (err) {\n return Promise.resolve({\n kind: \"retryable\",\n reason: `auth token unavailable: ${err instanceof Error ? err.message : String(err)}`,\n });\n }\n return new ConnectionAttempt(target, slotSignal, deps, authToken).run();\n}\n\nclass ConnectionAttempt implements DrainableConnection {\n private state: AttemptState = { kind: \"connecting\" };\n private readonly completion = new Completion();\n /** Lifetime-scoped: destroyed on teardown in any phase, handed to the\n * registry on a server drain. */\n private socket: net.Socket | undefined;\n\n private readonly plaintext: boolean;\n private readonly log: DiagnosticLogger;\n private readonly connectionId = newTunnelConnectionId();\n\n constructor(\n private readonly target: Target,\n private readonly slotSignal: AbortSignal,\n private readonly deps: ConnectionDeps,\n private readonly authToken: string\n ) {\n this.log = deps.opts.logger;\n this.plaintext = target.plaintext ?? deps.opts.tls === false;\n }\n\n private get identity(): ConnectionIdentity {\n return {\n workerId: this.deps.opts.tunnelWorkerId,\n connectionId: this.connectionId,\n target: targetLabel(this.target),\n };\n }\n\n private identityLog(): string {\n return formatIdentity(this.deps.opts.tunnelWorkerId, this.connectionId);\n }\n\n private logWithIdentity(message: string): void {\n this.log(`${message} (${this.identityLog()})`);\n }\n\n run(): Promise<ConnectionOutcome> {\n this.deps.activeConnections.add(this);\n void this.drive();\n return this.completion.promise;\n }\n\n /** Stage pipeline: dial → establish (role-flip). The remaining stages\n * (handshake, serve) are event-driven from the h2 server's request handler. */\n private async drive(): Promise<void> {\n const dialed = await dial(\n this.target,\n this.deps,\n this.plaintext,\n this.slotSignal,\n this.connectionId\n );\n // A client-drain (shutdown) or abort may have settled us mid-dial.\n if (this.completion.settled) {\n if (dialed.ok) dialed.socket.destroy();\n this.deps.activeConnections.delete(this);\n return;\n }\n if (!dialed.ok) {\n this.settle(dialed.outcome);\n return;\n }\n this.socket = dialed.socket;\n this.deps.activeSockets.add(dialed.socket);\n this.slotSignal.addEventListener(\"abort\", this.onAbort, { once: true });\n dialed.socket.on(\"error\", (err: Error) =>\n this.settle(\n this.endOutcome(`socket error: ${err.message}`),\n `socket error: ${err.message}`\n )\n );\n dialed.socket.on(\"close\", () =>\n this.settle(\n this.endOutcome(\"connection closed before handshake completed\"),\n \"socket closed\"\n )\n );\n this.establish(dialed.socket);\n }\n\n // ---- state helpers ----\n\n private get closed(): boolean {\n return this.state.kind === \"closed\";\n }\n\n private session(): http2.Http2Session | undefined {\n const s = this.state;\n return s.kind === \"handshaking\" ||\n s.kind === \"serving\" ||\n s.kind === \"draining\"\n ? s.session\n : undefined;\n }\n\n private get openedAt(): number | undefined {\n const s = this.state;\n return s.kind === \"serving\" || s.kind === \"draining\"\n ? s.openedAt\n : undefined;\n }\n\n private uptimeMs(): number {\n return this.openedAt === undefined ? 0 : Date.now() - this.openedAt;\n }\n\n /** The end-of-connection outcome: \"served\" once established, else retryable. */\n private endOutcome(reason: string): ConnectionOutcome {\n return this.openedAt !== undefined\n ? { kind: \"served\", uptimeMs: this.uptimeMs() }\n : { kind: \"retryable\", reason };\n }\n\n // ---- teardown ----\n\n private readonly onAbort = () =>\n this.settle({ kind: \"retryable\", reason: \"tunnel closed\" });\n\n /** Stop the timers/monitors owned by the current phase. */\n private stopPhaseResources(): void {\n const s = this.state;\n if (s.kind === \"handshaking\") clearTimeout(s.firstRequestTimer);\n else if (s.kind === \"serving\" || s.kind === \"draining\") s.watchdog.stop();\n }\n\n /** Detach from the engine registries and the slot-abort listener. */\n private deregister(): void {\n this.slotSignal.removeEventListener(\"abort\", this.onAbort);\n this.deps.activeConnections.delete(this);\n if (this.socket !== undefined) this.deps.activeSockets.delete(this.socket);\n }\n\n /**\n * The single terminal path — resolve the outcome (once), destroy the\n * session/socket, and move to `closed`. Idempotent. A server drain does NOT\n * funnel through here for teardown: it detaches via {@link beginServerDrain}\n * and lets the DrainingRegistry destroy the session later.\n */\n private settle(outcome: ConnectionOutcome, detail?: string): void {\n if (this.closed) return;\n const phase = this.state.kind;\n const session = this.session();\n this.stopPhaseResources();\n this.deregister();\n this.state = { kind: \"closed\" };\n session?.destroy();\n this.socket?.destroy();\n const firstOutcome = this.completion.resolve(outcome);\n this.logWithIdentity(\n `tunnel: connection to ${targetLabel(this.target)} closed (phase=${phase}, outcome=${formatConnectionOutcome(outcome)}${\n detail === undefined ? \"\" : `, detail=${detail}`\n }${firstOutcome ? \"\" : \", already reported\"})`\n );\n }\n\n private closeSessionGracefully(session: http2.Http2Session): Promise<void> {\n return new Promise((resolve) => {\n if (session.closed || session.destroyed) {\n resolve();\n return;\n }\n let done = false;\n const finish = () => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n resolve();\n };\n const timer = setTimeout(() => {\n this.settle(\n { kind: \"served\", uptimeMs: this.uptimeMs() },\n \"session.close() timed out\"\n );\n finish();\n }, CLIENT_DRAIN_SESSION_CLOSE_TIMEOUT_MS);\n timer.unref();\n session.once(\"close\", finish);\n try {\n session.close();\n } catch {\n this.settle(\n this.endOutcome(\"session close failed\"),\n \"session close failed\"\n );\n finish();\n }\n });\n }\n\n private sendClientDrainGoaway(session: http2.Http2Session): void {\n if (session.closed || session.destroyed) return;\n try {\n session.goaway(http2.constants.NGHTTP2_NO_ERROR);\n this.logWithIdentity(\n `tunnel: sent client-drain GOAWAY to ${targetLabel(this.target)}`\n );\n } catch (err) {\n this.logWithIdentity(\n `tunnel: failed to send client-drain GOAWAY to ${targetLabel(this.target)}: ${\n err instanceof Error ? err.message : String(err)\n }`\n );\n // The session may be closing under us. dispatchForwarded still refuses\n // any raced streams once the state flips to client-draining.\n }\n }\n\n // ---- establish: role-flip ----\n\n private establish(socket: net.Socket): void {\n this.logWithIdentity(\n `tunnel: connected to ${this.target.host}:${this.target.port}, starting handshake`\n );\n\n const h2 = http2.createServer(\n {\n maxSessionMemory: this.deps.opts.maxSessionMemory,\n settings: {\n // TODO why not allow to configure the other h2 options?\n maxConcurrentStreams: this.deps.opts.maxConcurrentStreams,\n initialWindowSize: 1024 * 1024,\n maxFrameSize: 65536,\n },\n },\n (req, res) => this.handleRequest(req, res)\n );\n\n h2.on(\"session\", (s) => {\n this.logWithIdentity(\n `tunnel: h2 session established to ${targetLabel(this.target)} (localSettings=${formatSettings(\n s.localSettings\n )}, remoteSettings=${formatSettings(s.remoteSettings)})`\n );\n s.on(\"localSettings\", (settings: http2.Settings) =>\n this.logWithIdentity(\n `tunnel: h2 local settings acknowledged by ${targetLabel(this.target)}: ${formatSettings(settings)}`\n )\n );\n s.on(\"remoteSettings\", (settings: http2.Settings) =>\n this.logWithIdentity(\n `tunnel: h2 remote settings from ${targetLabel(this.target)}: ${formatSettings(settings)}`\n )\n );\n // Role-flip complete: the cloud is now our h2 client. connecting →\n // handshaking, arming the timer that fires if the server never opens\n // /_/start-tunnel.\n if (this.state.kind === \"connecting\") {\n const firstRequestTimer = setTimeout(() => {\n if (\n this.state.kind === \"handshaking\" &&\n this.state.handshake === undefined\n ) {\n this.settle({\n kind: \"retryable\",\n reason: \"server never initiated /_/start-tunnel\",\n });\n }\n }, this.deps.opts.handshakeTimeoutMs);\n firstRequestTimer.unref();\n this.state = {\n kind: \"handshaking\",\n session: s,\n firstRequestTimer,\n handshake: undefined,\n };\n }\n try {\n // Raise the per-connection flow-control window (Node defaults to\n // 64 KiB, throttling aggregate throughput across streams).\n (\n s as unknown as { setLocalWindowSize?: (n: number) => void }\n ).setLocalWindowSize?.(this.deps.opts.connectionWindowSize);\n } catch {\n // Older Node — per-stream windows still apply.\n }\n s.on(\"close\", () =>\n this.settle(\n this.endOutcome(\"session closed before handshake completed\"),\n \"session closed\"\n )\n );\n s.on(\"error\", (err: Error) =>\n this.settle(\n this.endOutcome(`session error: ${err.message}`),\n `session error: ${err.message}`\n )\n );\n });\n h2.on(\"sessionError\", (err: Error) =>\n this.settle(\n this.endOutcome(`session error: ${err.message}`),\n `session error: ${err.message}`\n )\n );\n\n h2.emit(\"connection\", socket);\n }\n\n // ---- request routing ----\n\n private handleRequest(\n req: http2.Http2ServerRequest,\n res: http2.Http2ServerResponse\n ): void {\n switch (classifyRequest(req).kind) {\n case \"health\":\n res.writeHead(200);\n res.end();\n return;\n case \"drain\":\n this.handleDrainRequest(res);\n return;\n case \"start-tunnel\":\n if (\n this.state.kind === \"handshaking\" &&\n this.state.handshake === undefined\n ) {\n this.startHandshake(req, res);\n } else {\n this.notReady(res);\n }\n return;\n case \"forwarded\":\n this.handleForwarded(req, res);\n return;\n }\n }\n\n private handleForwarded(\n req: http2.Http2ServerRequest,\n res: http2.Http2ServerResponse\n ): void {\n // Serving, or draining (a server-drained session keeps serving its\n // in-flight; dispatchForwarded refuses only a client drain / shutdown).\n if (this.state.kind === \"serving\" || this.state.kind === \"draining\") {\n this.dispatchForwarded(req, res);\n return;\n }\n // A stream that raced the handshake parks on its outcome (the cloud fires\n // work the instant the tunnel registers, coalescing it with the\n // ok-trailers) rather than being rejected.\n if (\n this.state.kind === \"handshaking\" &&\n this.state.handshake !== undefined\n ) {\n const handshake = this.state.handshake;\n void handshake.then(({ ok }) => {\n if (this.closed || res.stream.destroyed) return;\n try {\n if (ok) this.dispatchForwarded(req, res);\n else {\n this.logWithIdentity(\n `tunnel: refused forwarded stream ${res.stream.id ?? \"?\"} before tunnel handshake completed`\n );\n this.notReady(res);\n }\n } catch {\n // The session may be tearing down under us.\n }\n });\n return;\n }\n // Before /_/start-tunnel was even opened (or already gone) — not a tunnel\n // server speaking the protocol.\n this.logWithIdentity(\n `tunnel: refused forwarded stream ${res.stream.id ?? \"?\"} before tunnel handshake completed`\n );\n this.notReady(res);\n }\n\n private notReady(res: http2.Http2ServerResponse): void {\n res.writeHead(503, { [TUNNEL_DRAINING_HEADER]: \"true\" });\n res.end(\"tunnel: not ready\");\n }\n\n /** First stream: run the handshake; its outcome opens the gate. */\n private startHandshake(\n req: http2.Http2ServerRequest,\n res: http2.Http2ServerResponse\n ): void {\n if (this.state.kind !== \"handshaking\") return;\n clearTimeout(this.state.firstRequestTimer);\n this.state.handshake = performHandshake(\n req,\n res,\n {\n authToken: this.authToken,\n environmentId: this.deps.opts.environmentId,\n tunnelName: this.deps.opts.name,\n tunnelWorkerId: this.deps.opts.tunnelWorkerId,\n tunnelConnectionId: this.connectionId,\n supportsDrain: this.deps.opts.supportsDrain,\n supportsClientDrain: this.deps.opts.supportsClientDrain,\n },\n this.deps.opts.handshakeTimeoutMs\n ).then((outcome) => {\n // settle (session/socket error) may have raced us to `closed`.\n if (this.state.kind !== \"handshaking\") return { ok: false };\n if (outcome.kind === \"ok\") {\n const { session } = this.state;\n const openedAt = Date.now();\n const watchdog = this.startWatchdog(session);\n // If our own shutdown began while we were handshaking, open straight\n // into a client drain so this connection refuses work from the start.\n this.state = this.deps.isShuttingDown()\n ? { kind: \"draining\", session, openedAt, trigger: \"client\", watchdog }\n : { kind: \"serving\", session, openedAt, watchdog };\n this.logWithIdentity(\n `tunnel: established (name=${outcome.info.tunnelName}, proxy=${outcome.info.proxyUrl})`\n );\n this.deps.onEstablished(outcome.info, this.identity);\n return { ok: true };\n }\n this.settle(outcome);\n return { ok: false };\n });\n }\n\n /** Strip the destination prefix and hand the stream to the SDK. */\n private dispatchForwarded(\n req: http2.Http2ServerRequest,\n res: http2.Http2ServerResponse\n ): void {\n // Client-initiated drain (this connection, or an engine-wide shutdown):\n // refuse new invocations WITHOUT running the handler. The sentinel tells\n // the server to stop routing here; failing the request (rather than\n // running it) lets the runtime retry it on a healthy connection with no\n // risk of double-execution. A *server* drain does not refuse — its\n // detached session keeps serving (the zero-drop property).\n const clientDraining =\n this.state.kind === \"draining\" && this.state.trigger === \"client\";\n if (clientDraining || this.deps.isShuttingDown()) {\n this.logWithIdentity(\n `tunnel: refused forwarded stream ${res.stream.id ?? \"?\"} during client drain`\n );\n res.writeHead(503, { [TUNNEL_DRAINING_HEADER]: \"true\" });\n res.end();\n return;\n }\n const tail = forwardedTail(req.url ?? \"\");\n if (tail === null) {\n res.writeHead(400);\n res.end(\"tunnel: malformed forwarded path\");\n return;\n }\n req.url = tail;\n // Count this invocation as in-flight so shutdown() waits for it to finish.\n this.deps.inflightStarted();\n res.stream.once(\"close\", () => this.deps.inflightEnded());\n res.stream.once(\"error\", (err: Error) => {\n const streamId = res.stream.id ?? \"?\";\n const logPath = pathWithoutQuery(req.url);\n this.logWithIdentity(\n `tunnel: forwarded stream ${streamId} ${req.method ?? \"?\"} ${logPath} failed: ${\n err.message\n }`\n );\n });\n try {\n this.deps.sdkHandler(req, res);\n } catch (err) {\n const streamId = res.stream.id ?? \"?\";\n const logPath = pathWithoutQuery(req.url);\n this.logWithIdentity(\n `tunnel: SDK handler threw for forwarded stream ${streamId} ${\n req.method ?? \"?\"\n } ${logPath}: ${err instanceof Error ? err.message : String(err)}`\n );\n endInternalError(res);\n }\n }\n\n // ---- drain ----\n\n private handleDrainRequest(res: http2.Http2ServerResponse): void {\n res.writeHead(200);\n res.end();\n this.logWithIdentity(\n `tunnel: received server drain notification from ${targetLabel(this.target)}`\n );\n if (!this.deps.opts.supportsDrain) {\n // Not advertised, so unexpected — acknowledge and let the server\n // close on us; the slot's redial loop re-establishes.\n this.logWithIdentity(\n \"tunnel: received /_/drain-tunnel (drain not advertised) — acknowledging\"\n );\n return;\n }\n if (this.state.kind === \"serving\") {\n this.beginServerDrain();\n } else if (\n this.state.kind === \"handshaking\" &&\n this.state.handshake !== undefined\n ) {\n // Drain coalesced with the ok-trailers (the server drains tunnels the\n // moment it shuts down, including ones it just registered): the same\n // gate race as forwarded streams — park the drain on the handshake\n // outcome instead of silently dropping it.\n void this.state.handshake.then(({ ok }) => {\n if (ok) this.beginServerDrain();\n });\n }\n // Before /_/start-tunnel was even opened: not a tunnel server\n // speaking the protocol — ack-and-ignore.\n }\n\n /**\n * Server-initiated drain: detach the still-serving session to the\n * DrainingRegistry and resolve `run()` so the slot dials a replacement. The\n * detached session keeps serving its in-flight invocations under the\n * registry's grace window — `run()` resolves now, the session closes later\n * (its `close` handler then runs `settle()` → `closed`, a no-op resolve).\n */\n private beginServerDrain(): void {\n if (this.state.kind !== \"serving\") return;\n const { session, openedAt, watchdog } = this.state;\n this.logWithIdentity(\n \"tunnel: server drain notification accepted — opening a replacement connection\"\n );\n watchdog.stop(); // the registry owns the session now; stop pinging it\n this.deregister();\n this.deps.draining.add(session, this.socket!, this.deps.opts.drainGraceMs);\n this.state = {\n kind: \"draining\",\n session,\n openedAt,\n trigger: \"server\",\n watchdog,\n };\n this.completion.resolve({ kind: \"drained\", uptimeMs: this.uptimeMs() });\n }\n\n /**\n * Client-initiated drain: the engine is shutting this process down. Refuse\n * new invocations and finish in-flight IN PLACE — no redial. The engine\n * waits for in-flight to drain, then tears the connection down.\n */\n beginClientDrain(): void {\n const s = this.state;\n switch (s.kind) {\n case \"serving\":\n this.state = {\n kind: \"draining\",\n session: s.session,\n openedAt: s.openedAt,\n trigger: \"client\",\n watchdog: s.watchdog,\n };\n this.sendClientDrainGoaway(s.session);\n return;\n case \"connecting\":\n case \"handshaking\":\n // No serving session yet — nothing in-flight to protect; abort.\n this.settle({ kind: \"retryable\", reason: \"shutting down\" });\n return;\n case \"draining\":\n case \"closed\":\n return; // already winding down\n }\n }\n\n async finishClientDrain(opts: { force: boolean }): Promise<void> {\n const s = this.state;\n if (s.kind !== \"draining\" || s.trigger !== \"client\") return;\n if (opts.force) {\n this.settle(\n { kind: \"served\", uptimeMs: this.uptimeMs() },\n \"client drain grace expired\"\n );\n return;\n }\n await this.closeSessionGracefully(s.session);\n }\n\n // ---- liveness ----\n\n private startWatchdog(session: http2.Http2Session): Watchdog {\n const watchdog = new Watchdog(session, this.deps.opts, () => {\n this.logWithIdentity(\"tunnel: pings missed — reconnecting\");\n this.settle(\n { kind: \"served\", uptimeMs: this.uptimeMs() },\n \"ping watchdog missed too many acknowledgements\"\n );\n });\n watchdog.start();\n return watchdog;\n }\n}\n"],"mappings":";;;;;;;;;AA6EA,MAAM,wCAAwC;AAC9C,MAAM,yBAAyB;AAC/B,MAAM,mBAAmB;AAEzB,SAAS,aAAa,OAAe,QAAwB;CAC3D,IAAI,MAAM;AACV,MAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,KAAK;AAC/B,QAAM,iBAAiB,OAAO,OAAO,QAAQ,IAAI,CAAC,GAAG;AACrD,YAAU;;AAEZ,QAAO;;AAGT,SAAS,wBAAgC;CACvC,IAAI,SAAS;AACb,MAAK,MAAM,QAAQ,YAAY,GAAG,CAChC,UAAU,UAAU,KAAM,OAAO,KAAK;AAExC,QAAO,GAAG,aAAa,OAAO,KAAK,KAAK,CAAC,EAAE,GAAG,GAAG,aAAa,QAAQ,GAAG;;AAG3E,SAAS,eAAe,UAAkB,cAA8B;AACtE,QAAO,aAAa,SAAS,iBAAiB;;AAGhD,SAAS,YAAY,QAAwB;AAC3C,QAAO,GAAG,OAAO,KAAK,GAAG,OAAO;;AAGlC,SAAS,wBAAwB,SAAoC;AACnE,SAAQ,QAAQ,MAAhB;EACE,KAAK,SACH,QAAO,mBAAmB,QAAQ;EACpC,KAAK,UACH,QAAO,oBAAoB,QAAQ;EACrC,KAAK,YACH,QAAO,oBAAoB,QAAQ;EACrC,KAAK,QACH,QAAO,gBAAgB,QAAQ;;;AAIrC,SAAS,eAAe,UAAkC;CACxD,MAAM,UAAU,OAAO,QAAQ,SAAS,CAAC,QACtC,GAAG,WAAW,UAAU,OAC1B;AACD,KAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,QAAO,IAAI,QACR,KAAK,CAAC,KAAK,WAAW,GAAG,IAAI,GAAG,OAAO,MAAM,GAAG,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AAY;AAC3D,QAAK,gBAAgB,sCAAsC;AAC3D,QAAK,OACH;IAAE,MAAM;IAAU,UAAU,KAAK,UAAU;IAAE,EAC7C,iDACD;IACD;AACF,WAAS,OAAO;AAChB,SAAO"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/endpoint/tunnel/draining.ts
|
|
3
|
+
var DrainingRegistry = class {
|
|
4
|
+
entries = /* @__PURE__ */ new Set();
|
|
5
|
+
/**
|
|
6
|
+
* Take ownership of a detached (draining) connection: let it serve its
|
|
7
|
+
* in-flight streams for up to `graceMs`, then tear it down. The entry
|
|
8
|
+
* removes itself if the session ends earlier on its own.
|
|
9
|
+
*/
|
|
10
|
+
add(session, socket, graceMs) {
|
|
11
|
+
const entry = {
|
|
12
|
+
session,
|
|
13
|
+
socket,
|
|
14
|
+
timer: setTimeout(() => {
|
|
15
|
+
this.entries.delete(entry);
|
|
16
|
+
session.destroy();
|
|
17
|
+
socket.destroy();
|
|
18
|
+
}, graceMs)
|
|
19
|
+
};
|
|
20
|
+
entry.timer.unref();
|
|
21
|
+
this.entries.add(entry);
|
|
22
|
+
session.on("close", () => {
|
|
23
|
+
clearTimeout(entry.timer);
|
|
24
|
+
this.entries.delete(entry);
|
|
25
|
+
socket.destroy();
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/** Tear down every draining connection. Idempotent. */
|
|
29
|
+
destroyAll() {
|
|
30
|
+
for (const entry of this.entries) {
|
|
31
|
+
clearTimeout(entry.timer);
|
|
32
|
+
entry.session.destroy();
|
|
33
|
+
entry.socket.destroy();
|
|
34
|
+
}
|
|
35
|
+
this.entries.clear();
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
//#endregion
|
|
40
|
+
exports.DrainingRegistry = DrainingRegistry;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
//#region src/endpoint/tunnel/draining.ts
|
|
2
|
+
var DrainingRegistry = class {
|
|
3
|
+
entries = /* @__PURE__ */ new Set();
|
|
4
|
+
/**
|
|
5
|
+
* Take ownership of a detached (draining) connection: let it serve its
|
|
6
|
+
* in-flight streams for up to `graceMs`, then tear it down. The entry
|
|
7
|
+
* removes itself if the session ends earlier on its own.
|
|
8
|
+
*/
|
|
9
|
+
add(session, socket, graceMs) {
|
|
10
|
+
const entry = {
|
|
11
|
+
session,
|
|
12
|
+
socket,
|
|
13
|
+
timer: setTimeout(() => {
|
|
14
|
+
this.entries.delete(entry);
|
|
15
|
+
session.destroy();
|
|
16
|
+
socket.destroy();
|
|
17
|
+
}, graceMs)
|
|
18
|
+
};
|
|
19
|
+
entry.timer.unref();
|
|
20
|
+
this.entries.add(entry);
|
|
21
|
+
session.on("close", () => {
|
|
22
|
+
clearTimeout(entry.timer);
|
|
23
|
+
this.entries.delete(entry);
|
|
24
|
+
socket.destroy();
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
/** Tear down every draining connection. Idempotent. */
|
|
28
|
+
destroyAll() {
|
|
29
|
+
for (const entry of this.entries) {
|
|
30
|
+
clearTimeout(entry.timer);
|
|
31
|
+
entry.session.destroy();
|
|
32
|
+
entry.socket.destroy();
|
|
33
|
+
}
|
|
34
|
+
this.entries.clear();
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
//#endregion
|
|
39
|
+
export { DrainingRegistry };
|
|
40
|
+
//# sourceMappingURL=draining.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"draining.js","names":["entry: DrainingConnection"],"sources":["../../../src/endpoint/tunnel/draining.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 draining registry — graceful-drain handover ownership.\n//\n// When the cloud asks a connection to drain (`/_/drain-tunnel`), the\n// connection is \"detached\": its attempt settles (so the slot dials a\n// replacement) WITHOUT destroying the session, which keeps serving its\n// in-flight invocations. This registry owns those detached sessions:\n// each is bounded by a grace timer, removes itself when the session ends\n// naturally, and is destroyed unconditionally on engine teardown — a\n// fatal or close() must never leave a detached session serving (and\n// pinning the process) for the rest of its grace window.\n\nimport type * as http2 from \"node:http2\";\nimport type * as net from \"node:net\";\n\ninterface DrainingConnection {\n session: http2.Http2Session;\n socket: net.Socket;\n timer: NodeJS.Timeout;\n}\n\nexport class DrainingRegistry {\n private readonly entries = new Set<DrainingConnection>();\n\n /**\n * Take ownership of a detached (draining) connection: let it serve its\n * in-flight streams for up to `graceMs`, then tear it down. The entry\n * removes itself if the session ends earlier on its own.\n */\n add(session: http2.Http2Session, socket: net.Socket, graceMs: number): void {\n const entry: DrainingConnection = {\n session,\n socket,\n timer: setTimeout(() => {\n this.entries.delete(entry);\n session.destroy();\n socket.destroy();\n }, graceMs),\n };\n // unref'd: a draining session must not keep the process alive past\n // engine teardown (destroyAll covers the explicit paths).\n entry.timer.unref();\n this.entries.add(entry);\n session.on(\"close\", () => {\n clearTimeout(entry.timer);\n this.entries.delete(entry);\n socket.destroy();\n });\n }\n\n /** Tear down every draining connection. Idempotent. */\n destroyAll(): void {\n for (const entry of this.entries) {\n clearTimeout(entry.timer);\n entry.session.destroy();\n entry.socket.destroy();\n }\n this.entries.clear();\n }\n}\n"],"mappings":";AA+BA,IAAa,mBAAb,MAA8B;CAC5B,AAAiB,0BAAU,IAAI,KAAyB;;;;;;CAOxD,IAAI,SAA6B,QAAoB,SAAuB;EAC1E,MAAMA,QAA4B;GAChC;GACA;GACA,OAAO,iBAAiB;AACtB,SAAK,QAAQ,OAAO,MAAM;AAC1B,YAAQ,SAAS;AACjB,WAAO,SAAS;MACf,QAAQ;GACZ;AAGD,QAAM,MAAM,OAAO;AACnB,OAAK,QAAQ,IAAI,MAAM;AACvB,UAAQ,GAAG,eAAe;AACxB,gBAAa,MAAM,MAAM;AACzB,QAAK,QAAQ,OAAO,MAAM;AAC1B,UAAO,SAAS;IAChB;;;CAIJ,aAAmB;AACjB,OAAK,MAAM,SAAS,KAAK,SAAS;AAChC,gBAAa,MAAM,MAAM;AACzB,SAAM,QAAQ,SAAS;AACvB,SAAM,OAAO,SAAS;;AAExB,OAAK,QAAQ,OAAO"}
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
const require_withOptions = require('../withOptions.cjs');
|
|
2
|
+
const require_node_endpoint = require('../node_endpoint.cjs');
|
|
3
|
+
const require_options = require('./options.cjs');
|
|
4
|
+
const require_draining = require('./draining.cjs');
|
|
5
|
+
const require_util = require('./util.cjs');
|
|
6
|
+
const require_supervisor = require('./supervisor.cjs');
|
|
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 = require_options.resolveOptions(options);
|
|
126
|
+
const sdkHandler = require_withOptions.withOptions(new require_node_endpoint.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 require_draining.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 require_util.Deferred();
|
|
146
|
+
ready.promise.catch(() => {});
|
|
147
|
+
let state;
|
|
148
|
+
const signalUnregisters = [];
|
|
149
|
+
const supervisor = new require_supervisor.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
|
+
exports.startEngine = startEngine;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import "./types.cjs";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import "./types.js";
|