Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
chore(gateway-pools): trim explanatory comments
bernie-gaa8b068993ee
diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.ts b/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.tsindex 706dbef7b4..4fc9ba9f75 100644--- a/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.ts+++ b/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.ts@@ -11,13 +11,9 @@ export const pickRandomGateway = <T extends TSelectableGateway>(};/**- * Load-aware selection only runs when every member reports its own connection count.- ** A gateway new enough to report sends its real count, including PAM sessions the platform never- * sees. A gateway too old to report can only be scored on the connections the platform itself- * opened, which is always lower and misses whatever it is really carrying. There is no way to line- * those two numbers up, and no reason to trust the second one on its own, so any pool that is not- * fully upgraded picks at random instead.+ * sees. One too old to report can only be scored on what the platform opened itself, which is always+ * lower. Rather than trust that, a pool that is not fully upgraded picks at random.*/export const everyMemberReportsLoad = <T extends TSelectableGateway>(candidates: T[],diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts b/backend/src/ee/services/gateway-pool/gateway-pool-service.tsindex 5e34e90a16..473f57b356 100644--- a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts+++ b/backend/src/ee/services/gateway-pool/gateway-pool-service.ts@@ -285,24 +285,21 @@ export const gatewayPoolServiceFactory = ({const loadTracker = getGatewayLoadTracker();let selected: (typeof eligible)[number] | undefined;let claimedAtomically = false;- // Outlives the try: if anything in the load path fails we still want the suspect filter, or the- // fallback would happily hand back the member whose transport just failed.+ // Outlives the try so the fallback keeps the suspect filter.let pool = eligible;if (loadTracker) {try {const ids = eligible.map((gateway) => gateway.id);const suspect = await loadTracker.getSuspect(ids);- // A pool where every member recently failed is still worth attempting: refusing to route is a- // guaranteed outage, whereas the suspect marks may simply have aged badly.+ // All-suspect is still worth attempting: refusing to route is a guaranteed outage.const candidates = eligible.filter((gateway) => !suspect.has(gateway.id));pool = candidates.length > 0 ? candidates : eligible;const scores = await loadTracker.getScores(pool.map((gateway) => gateway.id));if (everyMemberReportsLoad(pool, scores)) {- // Choose and claim atomically. Reading the minimum and then writing the reservation as two- // calls lets every concurrent selection observe the same minimum and pile onto it.+ // Two calls would let every concurrent selection read the same minimum and pile onto it.const claimed = await loadTracker.claimLeastLoaded(shuffleForTieBreak(pool, Math.random).map((gateway) => ({id: gateway.id,@@ -312,8 +309,7 @@ export const gatewayPoolServiceFactory = ({selected = pool.find((gateway) => gateway.id === claimed);if (selected) claimedAtomically = true;} else {- // At least one member is too old to report its load, so there is no sound comparison to- // make and nothing to claim against.+ // A member too old to report leaves nothing sound to compare or claim against.selected = pickRandomGateway(pool);}} catch (err) {@@ -325,8 +321,7 @@ export const gatewayPoolServiceFactory = ({if (!selected)throw new BadRequestError({ message: unavailableMessage ?? "Gateway pool has no healthy gateways." });- // Bookkeeping must never be able to fail a selection, whatever the tracker does internally.- // The atomic path has already claimed its member.+ // Bookkeeping must never fail a selection. The atomic path already claimed its member.if (!claimedAtomically) {try {await loadTracker?.reserve(selected.id);@@ -344,11 +339,7 @@ export const gatewayPoolServiceFactory = ({const pickHealthyGateway = async (poolId: string) => selectGatewayFromPool({ poolId });- /**- * Runs an operation against a pool, retrying on another member when the tunnel could not be- * established. Only GatewayTransportError retries, because it is the one failure that guarantees- * nothing reached the target.- */+ /** Retries on another member only for a failed tunnel, the one case that cannot have reached the target. */const runWithPoolFailover = async <T>({poolId,@@ -376,8 +367,7 @@ export const gatewayPoolServiceFactory = ({try {selected = await selectGatewayFromPool({ poolId, exclude: tried, filter, unavailableMessage });} catch (err) {- // Running out of untried members is only interesting on the first attempt. After that the- // transport failure that got us here is the useful error, not "pool has no healthy gateways".+ // After the first attempt the transport failure is the useful error, not "no healthy gateways".if (!lastError) throw err;break;}diff --git a/backend/src/lib/gateway-v2/gateway-attempt-context.ts b/backend/src/lib/gateway-v2/gateway-attempt-context.tsindex 350136bec3..b9b0226771 100644--- a/backend/src/lib/gateway-v2/gateway-attempt-context.ts+++ b/backend/src/lib/gateway-v2/gateway-attempt-context.ts@@ -8,14 +8,8 @@ export type TGatewayAttempt = {const storage = new AsyncLocalStorage<TGatewayAttempt>();/**- * Records that the tunnel to a gateway could never be established, so the target saw nothing and- * the work can safely move to another pool member.- *- * This is a side channel rather than an error type because nearly every app-connection provider- * catches whatever the gateway layer throws and rewraps it in its own BadRequestError ("Unable to- * validate connection: ..."), which destroys any marker carried on the exception. The flag lives in- * async-local storage so it stays scoped to one attempt and concurrent requests to the same gateway- * cannot see each other's failures, which would otherwise let a target-side error trigger a retry.+ * A side channel rather than an error type, because providers rewrap whatever the gateway layer+ * throws and destroy any marker on the exception. Async-local so one attempt cannot see another's.*/export const runGatewayAttempt = async <T>(attempt: TGatewayAttempt, fn: () => Promise<T>): Promise<T> =>storage.run(attempt, fn);@@ -25,10 +19,7 @@ export const markAttemptTransportFailure = () => {if (attempt) attempt.transportFailed = true;};-/**- * Once any tunnel in this attempt comes up, the target may have been reached, so the attempt is no- * longer safe to replay even if an earlier tunnel in the same attempt failed and was swallowed.- */+/** Once any tunnel comes up the target may have been reached, so the attempt is not replayable. */export const markAttemptTunnelEstablished = () => {const attempt = storage.getStore();if (attempt) attempt.tunnelEstablished = true;diff --git a/backend/src/lib/gateway-v2/gateway-load-tracker.ts b/backend/src/lib/gateway-v2/gateway-load-tracker.tsindex 0cd62bf4c4..7eb94d2b17 100644--- a/backend/src/lib/gateway-v2/gateway-load-tracker.ts+++ b/backend/src/lib/gateway-v2/gateway-load-tracker.ts@@ -2,24 +2,17 @@ import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { logger } from "../logger";-// A reservation bridges the gap between choosing a gateway and its channel actually opening, so two-// concurrent selections cannot both read a stale zero and stampede the same member. It only has to-// span a relay dial plus two TLS handshakes, and it is released explicitly: left to expire on its-// own the counter would behave like "selections in the last N seconds", which is request-count-// round-robin rather than the occupancy signal this is supposed to be.+// A reservation marks a gateway as chosen until its channel opens, so concurrent selections do not+// all read the same stale count and stampede one member.const RESERVATION_TTL_SECONDS = 240;-// Backstop only, for a selection whose channel never opens. The relay dial allows 100s and the-// gateway handshake 120s, so releasing sooner would reopen the window the reservation covers.+// Must outlast a relay dial (100s) plus a gateway handshake (120s), or the window reopens.const RESERVATION_HOLD_MS = 230_000;const SUSPECT_TTL_SECONDS = 60;export type TGatewayScore = {- /**- * Occupancy without reservations. The claim script reads the reservation keys itself, so adding- * them here as well would mean fetching them twice for the same decision.- */+ /** Occupancy without reservations; the claim script reads those keys itself. */base: number;- /** False when this member is too old to report its own count, which disables load-aware selection. */+ /** False when this member is too old to report, which disables load-aware selection. */reported: boolean;};@@ -45,8 +38,7 @@ const reservationKey = KeyStorePrefixes.GatewayLoadReservation;const suspectKey = KeyStorePrefixes.GatewaySuspect;export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoadTracker => {- // Open timestamps rather than a bare count, so a channel opened since a gateway's last report can- // be added on top of that report instead of being invisible until the next one lands.+ // Timestamps rather than a count, so channels opened since a gateway's last report can be added on top.const openChannels = new Map<string, number[]>();const reservationTimers = new Set<NodeJS.Timeout>();const pendingReservations = new Map<string, NodeJS.Timeout[]>();@@ -59,8 +51,6 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad}};- // The key TTL is only a backstop for a pod that dies holding reservations; the channel handoff or- // this timer is what normally releases them.function trackReservationRelease(gatewayId: string) {const timer = setTimeout(() => {reservationTimers.delete(timer);@@ -88,8 +78,7 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoadconst open = openChannels.get(gatewayId);if (open) open.push(Date.now());else openChannels.set(gatewayId, [Date.now()]);- // The channel now carries the load the reservation was standing in for. Holding both would- // double count the member for the rest of the backstop window.+ // The channel now carries the load the reservation stood in for; holding both double counts.const pending = pendingReservations.get(gatewayId);const timer = pending?.shift();if (timer) {@@ -101,16 +90,14 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoadconst channelClosed = (gatewayId: string) => {const open = openChannels.get(gatewayId);- // Drops the oldest: only the count and the open times matter, not which socket this was.open?.shift();if (!open?.length) openChannels.delete(gatewayId);};const reserve = async (gatewayId: string) => {try {- // Routed through the same claim path as a pool selection so the expiry is set only on the- // first increment. incrementByWithExpiry refreshes it on every call, which on a busy gateway- // means the key never elapses and a crashed pod's reservations stay counted forever.+ // Same claim path as a selection, so the expiry is set only on the first increment. Refreshing+ // it every call means a busy key never elapses and a dead pod's reservations persist.await keyStore.claimLeastLoaded([reservationKey(gatewayId)], [0], RESERVATION_TTL_SECONDS);} catch (err) {logger.debug({ err, gatewayId }, `Failed to reserve gateway capacity [gatewayId=${gatewayId}]`);@@ -119,10 +106,7 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoadtrackReservationRelease(gatewayId);};- /**- * Picks and claims in one round trip. Ties fall to the caller's ordering, so the caller shuffles- * first to keep the random tie-break that stops every pod choosing the same idle member.- */+ /** Ties fall to the caller's ordering, so callers shuffle first for a random tie-break. */const claimLeastLoaded = async (candidates: { id: string; base: number }[]) => {if (candidates.length === 0) return undefined;const idx = await keyStore.claimLeastLoaded(@@ -169,14 +153,11 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoadgatewayIds.forEach((gatewayId, idx) => {const report = parseStamped(reported[idx]);- // A gateway that cannot report is left at zero on purpose. Selection refuses to compare a pool- // containing one, so the number is never used, and inventing a platform-side count here would- // only look like a real occupancy to whoever reads it next.+ // Left at zero on purpose: selection refuses to compare a pool containing one, so a+ // platform-side count here would only look like a real occupancy without being one.let occupancy = 0;if (report) {- // The report is a snapshot up to its own timestamp. Anything this pod opened since then is- // not in it yet, and without this every selection inside one report interval reads the same- // stale number and piles onto the same member.+ // Without this every selection inside one report interval reads the same stale count.const openedSinceReport = (openChannels.get(gatewayId) ?? []).filter((openedAt) => openedAt > report.at).length;occupancy = report.count + openedSinceReport;}@@ -197,8 +178,7 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoadreturn suspect;};- // Nothing here writes to Redis. Reservations this pod still holds are left to their TTL, which is- // the backstop that exists precisely for a pod that goes away without releasing them.+ // Reservations still held are left to their TTL, which exists for exactly this case.const shutdown = () => {tracker = undefined;for (const timer of reservationTimers) clearTimeout(timer);diff --git a/backend/src/lib/gateway-v2/gateway-retry.ts b/backend/src/lib/gateway-v2/gateway-retry.tsindex 0cbc155451..5b7c068c2d 100644--- a/backend/src/lib/gateway-v2/gateway-retry.ts+++ b/backend/src/lib/gateway-v2/gateway-retry.ts@@ -1,17 +1,9 @@/**- * When a failed gateway operation may be replayed on another pool member.- *- * The rule both helpers enforce is the same: retry only when nothing can have reached the target.- * A half-applied change (a password rotation, a write) replayed on a second member would apply- * twice, so anything that might have got through is not retryable no matter what it looks like.+ * Retry only when nothing can have reached the target. A half-applied change replayed on a second+ * member would apply twice.*/-/**- * Per proxy. `relayError` is non-empty once any channel this proxy served failed to come up, and it- * is never cleared, so on its own it stays true for the rest of the proxy's life. Requiring that no- * channel ever established is what stops a single transient setup failure from marking every later- * target-side error as safe to replay.- */+/** `relayError` is never cleared, so requiring that no channel established is what bounds it. */export const isGatewayTransportFailure = ({relayError,establishedChannel@@ -20,11 +12,7 @@ export const isGatewayTransportFailure = ({establishedChannel: boolean;}): boolean => Boolean(relayError) && !establishedChannel;-/**- * Per attempt, across however many tunnels the caller's operation opened. An early tunnel can fail- * and be swallowed by provider code while a later one reaches the target, so a transport failure- * alone is not enough: no tunnel in the attempt may have come up.- */+/** An early tunnel can fail while a later one reaches the target, so a transport failure alone is not enough. */export const isAttemptRetryable = ({transportFailed,tunnelEstablished,diff --git a/backend/src/lib/gateway-v2/gateway-v2.test.ts b/backend/src/lib/gateway-v2/gateway-v2.test.tsindex 3cf72a5fc5..82fd3e20fb 100644--- a/backend/src/lib/gateway-v2/gateway-v2.test.ts+++ b/backend/src/lib/gateway-v2/gateway-v2.test.ts@@ -13,12 +13,8 @@ const tracker = vi.hoisted(() => ({markSuspect: vi.fn()}));-// The fake relay listens on an ephemeral loopback port, so the harness has to carry that port in-// relayHost, which the implementation forwards as the TLS servername. A real relayHost is a-// hostname with no port (a gateway is always reached on 8443), so this shape only exists here, and-// Node rejects a servername containing a colon outright rather than matching it against a SAN.-// Dropping it leaves verification to run against the connected host, which the cert covers, and-// keeps the rest of the real TLS stack in the test.+// A real relayHost carries no port, but the fake relay needs an ephemeral one, and Node rejects a+// servername containing a colon. Dropping it verifies against the connected host instead.vi.mock("node:tls", async (importOriginal) => {const actual = await importOriginal<typeof import("node:tls")>();const connect = (options: tls.ConnectionOptions, callback?: () => void) =>diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.tsindex f05e4a02a0..843d67789d 100644--- a/backend/src/lib/gateway-v2/gateway-v2.ts+++ b/backend/src/lib/gateway-v2/gateway-v2.ts@@ -168,11 +168,9 @@ export const setupRelayServer = async ({httpsAgent?: https.Agent;longLived?: boolean;/**- * Opens the tunnel during setup and hands it to the first client instead of dialing lazily.- * Callers that give the port to a long-lived session need this: otherwise setup succeeds against- * a dead gateway and the failure only surfaces once a user is attached, far too late to pick- * another pool member. The connection is kept and reused rather than probed and dropped, so the- * gateway sees one channel that becomes the session, not a session that opens and immediately dies.+ * Opens the tunnel during setup and hands it to the first client, so an unreachable gateway fails+ * here rather than once a user is already attached. Reused rather than probed and dropped, so the+ * gateway sees one channel that becomes the session.*/eager?: boolean;}): Promise<IGatewayRelayServer> => {@@ -204,9 +202,8 @@ export const setupRelayServer = async ({throw err;}- // Marked as soon as both handshakes complete: the gateway dials the target the moment it- // accepts the channel, so the target may already have been reached even if we abandon this- // connection now. Treating the attempt as replayable after that point is what this prevents.+ // The gateway dials the target the moment it accepts the channel, so from here the attempt is+ // no longer safe to replay even if we abandon this connection.establishedChannel = true;markAttemptTunnelEstablished();@@ -243,9 +240,8 @@ export const setupRelayServer = async ({}}- // Counted per channel rather than per caller operation: one operation can open many channels- // (a pooled SQL client, an HTTP client without keepalive, a discovery sweep), and it is the- // channel that costs the gateway a goroutine.+ // Per channel, not per operation: one operation can open many, and the channel is what costs+ // the gateway a goroutine.loadTracker?.channelOpened(gatewayId);let released = false;@@ -285,8 +281,7 @@ export const setupRelayServer = async ({pendingUpstream = null;const { relayConn, gatewayConn, releaseChannel } = claimed ?? (await openUpstream());- // The caller may have given up while the handshakes were in flight. Its "close" event has- // already fired by now, so attaching the teardown listeners below would never run and the+ // Its "close" already fired, so the teardown listeners below would never run and the// channel would stay counted for the life of the pod.if (clientConn.destroyed) {releaseChannel();@@ -359,8 +354,8 @@ export const setupRelayServer = async ({const upstream = await openUpstream();pendingUpstream = upstream;- // If the gateway or relay drops the tunnel before anyone claims it, fall back to dialing- // on demand rather than handing the session a socket that is already dead.+ // Dropped before anyone claims it, so the next client dials fresh rather than inheriting+ // a dead socket.const dropIfUnclaimed = () => {if (pendingUpstream === upstream) discardPendingUpstream();};