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
feat(gateway-pools): load-aware selection and transport failover
bernie-g84523dd13473
diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.tsindex e6893151cd..83b8489aeb 100644--- a/backend/e2e-test/mocks/keystore.ts+++ b/backend/e2e-test/mocks/keystore.ts@@ -19,7 +19,7 @@ export const mockKeyStore = (): TKeyStoreFactory => {},setExpiry: async () => 0,ttl: async () => -1,- setItemWithExpiry: async (key, value) => {+ setItemWithExpiry: async (key, _expiryInSeconds, value) => {store[key] = value;return "OK";},@@ -77,8 +77,15 @@ export const mockKeyStore = (): TKeyStoreFactory => {incrementByAndRefreshExpiryIfUnderLimit: async () => {return 1;},- decrementByOrDelete: async () => {- return 0;+ decrementByOrDelete: async (key) => {+ const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;+ const next = current - 1;+ if (next <= 0) {+ delete store[key];+ return 0;+ }+ store[key] = String(next);+ return next;},incrementByWithExpiry: async (key, value) => {const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;@@ -111,9 +118,23 @@ export const mockKeyStore = (): TKeyStoreFactory => {hashGet: async (key, field) => {return hashStore[key]?.[field] ?? null;},+ hashGetAll: async (key) => {+ return { ...(hashStore[key] ?? {}) };+ },+ hashDelete: async (key, field) => {+ if (!hashStore[key]?.[field]) return 0;+ delete hashStore[key][field];+ return 1;+ },pgIncrementBy: async () => {return 1;},+ getItemsPrimary: async (keys) => {+ return keys.map((key) => {+ const value = store[key];+ return typeof value === "string" ? value : null;+ });+ },getItems: async (keys) => {const values = keys.map((key) => {const value = store[key];diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.test.ts b/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.test.tsnew file mode 100644index 0000000000..7f1581fcae--- /dev/null+++ b/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.test.ts@@ -0,0 +1,129 @@+import { chooseLeastLoadedGateway, pickRandomGateway } from "./gateway-pool-selection-fns";++const gateways = [{ id: "a" }, { id: "b" }, { id: "c" }];++describe("chooseLeastLoadedGateway", () => {+ test("returns undefined when there are no candidates", () => {+ expect(chooseLeastLoadedGateway([], new Map())).toBeUndefined();+ });++ test("returns the only candidate without consulting scores", () => {+ const random = vi.fn();+ expect(chooseLeastLoadedGateway([{ id: "a" }], new Map(), random)).toEqual({ id: "a" });+ expect(random).not.toHaveBeenCalled();+ });++ test("takes the clear minimum alone when the runner-up is not close", () => {+ const scores = new Map([+ ["a", 10],+ ["b", 1],+ ["c", 4]+ ]);++ for (let i = 0; i < 500; i += 1) {+ expect(chooseLeastLoadedGateway(gateways, scores)).toEqual({ id: "b" });+ }+ });++ test("spreads across both members when their scores are within the tie band", () => {+ const scores = new Map([+ ["a", 10],+ ["b", 1],+ ["c", 2]+ ]);++ const picked = new Set<string>();+ for (let i = 0; i < 500; i += 1) {+ picked.add(chooseLeastLoadedGateway(gateways, scores)!.id);+ }++ expect(picked).toEqual(new Set(["b", "c"]));+ });++ test("does not hand a two-member pool a coin flip when one is clearly busier", () => {+ // Two gateways is the common HA pool size. Always shortlisting both would make the load score+ // a no-op there and leave the pool behaving exactly like the old random selection.+ const pair = [{ id: "a" }, { id: "b" }];+ const scores = new Map([+ ["a", 8],+ ["b", 0]+ ]);++ for (let i = 0; i < 500; i += 1) {+ expect(chooseLeastLoadedGateway(pair, scores)).toEqual({ id: "b" });+ }+ });++ test("never sends half the traffic to a near-saturated member", () => {+ const scores = new Map([+ ["a", 0],+ ["b", 99],+ ["c", 100]+ ]);++ for (let i = 0; i < 500; i += 1) {+ expect(chooseLeastLoadedGateway(gateways, scores)).toEqual({ id: "a" });+ }+ });++ test("treats a missing score as zero load", () => {+ const scores = new Map([+ ["a", 5],+ ["b", 5]+ ]);++ expect(chooseLeastLoadedGateway(gateways, scores, () => 0)).toEqual({ id: "c" });+ });++ test("reaches every member when the pool is idle and all scores tie", () => {+ // A deterministic tie-break would shortlist the same two members forever, so a third gateway+ // would sit unused for as long as the pool stays idle. That is the common case, not an edge case.+ const seen = new Set<string>();+ for (let i = 0; i < 3000; i += 1) {+ seen.add(chooseLeastLoadedGateway(gateways, new Map())!.id);+ }+ expect(seen).toEqual(new Set(["a", "b", "c"]));+ });++ test("spreads an idle pool roughly evenly", () => {+ const tally: Record<string, number> = { a: 0, b: 0, c: 0 };+ for (let i = 0; i < 30_000; i += 1) {+ tally[chooseLeastLoadedGateway(gateways, new Map())!.id] += 1;+ }+ // Uniform would be 10,000 each. Loose bound: this asserts nobody is starved, not an exact ratio.+ for (const id of ["a", "b", "c"]) {+ expect(tally[id]).toBeGreaterThan(7_000);+ }+ });++ test("still prefers the least loaded once scores differ", () => {+ const scores = new Map([+ ["a", 50],+ ["b", 0],+ ["c", 1]+ ]);++ // Whatever the shuffle does, the heavily loaded member must never be shortlisted.+ for (let i = 0; i < 500; i += 1) {+ expect(chooseLeastLoadedGateway(gateways, scores)!.id).not.toBe("a");+ }+ });++ test("does not mutate the caller's candidate array", () => {+ const input = [{ id: "c" }, { id: "a" }, { id: "b" }];+ chooseLeastLoadedGateway(input, new Map(), () => 0);+ expect(input.map((g) => g.id)).toEqual(["c", "a", "b"]);+ });+});++describe("pickRandomGateway", () => {+ test("returns undefined when there are no candidates", () => {+ expect(pickRandomGateway([], () => 0)).toBeUndefined();+ });++ test("can reach every candidate", () => {+ expect(pickRandomGateway(gateways, () => 0)).toEqual({ id: "a" });+ expect(pickRandomGateway(gateways, () => 0.5)).toEqual({ id: "b" });+ expect(pickRandomGateway(gateways, () => 0.99)).toEqual({ id: "c" });+ });+});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.tsnew file mode 100644index 0000000000..aa9b1c15db--- /dev/null+++ b/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.ts@@ -0,0 +1,50 @@+export type TSelectableGateway = { id: string };++// Two members this close are treated as equally loaded, since cross-pod counts are published+// asynchronously and routinely disagree by one.+const SCORE_TIE_BAND = 1;++/**+ * Picks the least-loaded member, breaking between the two lowest at random.+ *+ * The random tie-break matters because every backend pod reads the same shared counters. Taking the+ * strict minimum would make all of them choose the same idle gateway in the same instant and stampede+ * it, which is the imbalance this is meant to remove.+ */+export const chooseLeastLoadedGateway = <T extends TSelectableGateway>(+ candidates: T[],+ scores: Map<string, number>,+ random: () => number = Math.random+): T | undefined => {+ if (candidates.length === 0) return undefined;+ if (candidates.length === 1) return candidates[0];++ // Shuffle before ranking. An idle pool scores every member zero, and a deterministic tie-break+ // would then always shortlist the same two, leaving every member past the second with no traffic+ // at all. Sort is stable, so shuffling first randomises ties while keeping the least-loaded order.+ const shuffled = [...candidates];+ for (let i = shuffled.length - 1; i > 0; i -= 1) {+ const j = Math.floor(random() * (i + 1));+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];+ }++ const ranked = shuffled.sort((a, b) => (scores.get(a.id) ?? 0) - (scores.get(b.id) ?? 0));++ // Only shortlist the runner-up when it is genuinely comparable. Always taking the two lowest would+ // hand a two-member pool a coin flip regardless of load, and would still send half the traffic to a+ // near-saturated member in a pool scored {0, 99, 100}. The band absorbs the off-by-one that stale+ // cross-pod counts produce, which is the case the random draw exists for.+ const best = scores.get(ranked[0].id) ?? 0;+ const runnerUp = scores.get(ranked[1].id) ?? 0;+ const shortlist = runnerUp - best <= SCORE_TIE_BAND ? ranked.slice(0, 2) : [ranked[0]];++ return shortlist[Math.floor(random() * shortlist.length)];+};++export const pickRandomGateway = <T extends TSelectableGateway>(+ candidates: T[],+ random: () => number = Math.random+): T | undefined => {+ if (candidates.length === 0) return undefined;+ return candidates[Math.floor(random() * candidates.length)];+};diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts b/backend/src/ee/services/gateway-pool/gateway-pool-service.tsindex 12a1dd090b..025aff085b 100644--- a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts+++ b/backend/src/ee/services/gateway-pool/gateway-pool-service.ts@@ -2,7 +2,9 @@ import { ForbiddenError } from "@casl/ability";import { OrganizationActionScope } from "@app/db/schemas";import { DatabaseErrorCode } from "@app/lib/error-codes";-import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";+import { BadRequestError, DatabaseError, GatewayTransportError, NotFoundError } from "@app/lib/errors";+import { runGatewayAttempt } from "@app/lib/gateway-v2/gateway-attempt-context";+import { getGatewayLoadTracker } from "@app/lib/gateway-v2/gateway-load-tracker";import { logger } from "@app/lib/logger";import { OrgServiceActor } from "@app/lib/types";import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";@@ -10,22 +12,23 @@ import { TIdentityKubernetesAuthDALFactory } from "@app/services/identity-kubernimport { TDynamicSecretDALFactory } from "../dynamic-secret/dynamic-secret-dal";import { TGatewayV2DALFactory } from "../gateway-v2/gateway-v2-dal";-import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";-import { TGatewayV2ConnectionDetails } from "../gateway-v2/gateway-v2-types";import { TLicenseServiceFactory } from "../license/license-service";import { OrgPermissionGatewayPoolActions, OrgPermissionSubjects } from "../permission/org-permission";import { TPermissionServiceFactory } from "../permission/permission-service-types";import { TPkiDiscoveryConfigDALFactory } from "../pki-discovery/pki-discovery-config-dal";import { TGatewayPoolDALFactory } from "./gateway-pool-dal";import { TGatewayPoolMembershipDALFactory } from "./gateway-pool-membership-dal";+import { chooseLeastLoadedGateway, pickRandomGateway } from "./gateway-pool-selection-fns";import {+ DEFAULT_POOL_FAILOVER_ATTEMPTS,TAddGatewayToPoolDTO,TCreateGatewayPoolDTO,TDeleteGatewayPoolDTO,TGetGatewayPoolByIdDTO,- TGetPlatformConnectionDetailsByPoolIdDTO,TListGatewayPoolsDTO,TRemoveGatewayFromPoolDTO,+ TRunWithPoolFailoverDTO,+ TSelectGatewayFromPoolDTO,TUpdateGatewayPoolDTO} from "./gateway-pool-types";@@ -33,7 +36,6 @@ type TGatewayPoolServiceFactoryDep = {gatewayPoolDAL: TGatewayPoolDALFactory;gatewayPoolMembershipDAL: TGatewayPoolMembershipDALFactory;gatewayV2DAL: Pick<TGatewayV2DALFactory, "findById">;- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;permissionService: TPermissionServiceFactory;licenseService: Pick<TLicenseServiceFactory, "getPlan">;identityKubernetesAuthDAL: Pick<TIdentityKubernetesAuthDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;@@ -48,7 +50,6 @@ export const gatewayPoolServiceFactory = ({gatewayPoolDAL,gatewayPoolMembershipDAL,gatewayV2DAL,- gatewayV2Service,permissionService,licenseService,identityKubernetesAuthDAL,@@ -257,14 +258,44 @@ export const gatewayPoolServiceFactory = ({return { membership: deleted, poolName: pool.name, gatewayName: gateway.name };};- const pickRandomHealthyGateway = async (poolId: string) => {+ const selectGatewayFromPool = async ({ poolId, exclude, filter, unavailableMessage }: TSelectGatewayFromPoolDTO) => {const healthyGateways = await gatewayPoolMembershipDAL.findHealthyGatewaysByPoolId(poolId);- if (healthyGateways.length === 0) {++ const eligible = healthyGateways+ .filter((gateway) => !exclude?.has(gateway.id))+ .filter((gateway) => (filter ? filter(gateway) : true));++ if (eligible.length === 0) {throw new BadRequestError({- message: "Gateway pool has no healthy gateways."+ message: unavailableMessage ?? "Gateway pool has no healthy gateways."});}- const selected = healthyGateways[Math.floor(Math.random() * healthyGateways.length)];++ const loadTracker = getGatewayLoadTracker();+ let selected: (typeof eligible)[number] | undefined;++ 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.+ const candidates = eligible.filter((gateway) => !suspect.has(gateway.id));+ const pool = candidates.length > 0 ? candidates : eligible;++ const scores = await loadTracker.getScores(pool.map((gateway) => gateway.id));+ selected = chooseLeastLoadedGateway(pool, scores);+ } catch (err) {+ logger.warn({ err, poolId }, `Gateway load lookup failed, falling back to random selection [poolId=${poolId}]`);+ }+ }++ if (!selected) selected = pickRandomGateway(eligible);+ if (!selected)+ throw new BadRequestError({ message: unavailableMessage ?? "Gateway pool has no healthy gateways." });++ await loadTracker?.reserve(selected.id);+logger.info({ poolId, selectedGatewayId: selected.id },`Pool gateway selection: picked gateway [gatewayId=${selected.id}] from pool [poolId=${poolId}]`@@ -272,27 +303,73 @@ export const gatewayPoolServiceFactory = ({return selected;};- const listHealthyGateways = async (poolId: string) => {- return gatewayPoolMembershipDAL.findHealthyGatewaysByPoolId(poolId);- };+ 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.+ */+ const runWithPoolFailover = async <T>(+ {+ poolId,+ gatewayId,+ filter,+ maxAttempts = DEFAULT_POOL_FAILOVER_ATTEMPTS,+ unavailableMessage+ }: TRunWithPoolFailoverDTO,+ operation: (gatewayId: string) => Promise<T>+ ): Promise<{ result: T; gatewayId: string }> => {+ if (gatewayId || !poolId) {+ if (!gatewayId) {+ throw new BadRequestError({ message: unavailableMessage ?? "No gateway or gateway pool is configured." });+ }+ return { result: await operation(gatewayId), gatewayId };+ }- const getPlatformConnectionDetailsByPoolId = async ({- poolId,- targetHost,- targetPort- }: TGetPlatformConnectionDetailsByPoolIdDTO): Promise<TGatewayV2ConnectionDetails | undefined> => {- const pool = await gatewayPoolDAL.findById(poolId);- if (!pool) {- throw new NotFoundError({ message: `Gateway pool with ID ${poolId} not found` });+ const tried = new Set<string>();+ let lastError: unknown;++ // Sequential by design: each attempt has to know which member just failed.+ /* eslint-disable no-await-in-loop */+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {+ let selected: Awaited<ReturnType<typeof selectGatewayFromPool>>;+ 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".+ if (!lastError) throw err;+ break;+ }+ tried.add(selected.id);++ const gatewayAttempt = { transportFailed: false };+ try {+ return {+ result: await runGatewayAttempt(gatewayAttempt, () => operation(selected.id)),+ gatewayId: selected.id+ };+ } catch (err) {+ // Providers rewrap gateway errors in their own BadRequestError, so the async-local flag is+ // the only reliable signal that nothing reached the target.+ if (!gatewayAttempt.transportFailed && !(err instanceof GatewayTransportError)) throw err;+ lastError = err;+ logger.warn(+ { err, poolId, gatewayId: selected.id, attempt },+ `Gateway unreachable, retrying on another pool member [poolId=${poolId}] [gatewayId=${selected.id}]`+ );+ }}+ /* eslint-enable no-await-in-loop */- const selectedGateway = await pickRandomHealthyGateway(poolId);+ throw lastError instanceof Error+ ? lastError+ : new BadRequestError({ message: "Failed to reach any gateway in the pool." });+ };- return gatewayV2Service.getPlatformConnectionDetailsByGatewayId({- gatewayId: selectedGateway.id,- targetHost,- targetPort- });+ const listHealthyGateways = async (poolId: string) => {+ return gatewayPoolMembershipDAL.findHealthyGatewaysByPoolId(poolId);};// Enforce license + RBAC + pool-belongs-to-org before a consumer attaches a pool. Does NOT require a healthy member.@@ -336,7 +413,7 @@ export const gatewayPoolServiceFactory = ({}): Promise<string | null> => {if (gatewayId) return gatewayId;if (gatewayPoolId) {- const picked = await pickRandomHealthyGateway(gatewayPoolId);+ const picked = await pickHealthyGateway(gatewayPoolId);return picked.id;}return null;@@ -386,9 +463,11 @@ export const gatewayPoolServiceFactory = ({deleteGatewayPool,addGatewayToPool,removeGatewayFromPool,- pickRandomHealthyGateway,+ pickHealthyGateway,+ selectGatewayFromPool,+ runWithPoolFailover,listHealthyGateways,- getPlatformConnectionDetailsByPoolId,+getConnectedResources,getConnectedResourcesCount,resolveAttachableGatewayFromPool,diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-types.ts b/backend/src/ee/services/gateway-pool/gateway-pool-types.tsindex d6fcf7dc7a..7cf82f5e0d 100644--- a/backend/src/ee/services/gateway-pool/gateway-pool-types.ts+++ b/backend/src/ee/services/gateway-pool/gateway-pool-types.ts@@ -1,5 +1,10 @@+import { TGatewaysV2 } from "@app/db/schemas";import { OrgServiceActor } from "@app/lib/types";+// One retry past the first attempt. Higher multiplies load onto whichever members are still up,+// which is the flood this is meant to avoid.+export const DEFAULT_POOL_FAILOVER_ATTEMPTS = 2;+export type TCreateGatewayPoolDTO = {name: string;} & OrgServiceActor;@@ -29,8 +34,19 @@ export type TRemoveGatewayFromPoolDTO = {gatewayId: string;} & OrgServiceActor;-export type TGetPlatformConnectionDetailsByPoolIdDTO = {+export type TGatewayPoolMemberFilter = (gateway: TGatewaysV2) => boolean;++export type TSelectGatewayFromPoolDTO = {poolId: string;- targetHost: string;- targetPort: number;+ exclude?: Set<string>;+ filter?: TGatewayPoolMemberFilter;+ unavailableMessage?: string;+};++export type TRunWithPoolFailoverDTO = {+ poolId?: string | null;+ gatewayId?: string | null;+ filter?: TGatewayPoolMemberFilter;+ maxAttempts?: number;+ unavailableMessage?: string;};diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex a017afe9fa..0e6f286c42 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -82,6 +82,9 @@ export const KeyStorePrefixes = {ProxiedServiceUsageDebounce: (serviceId: string) => `proxied-service-usage-debounce:${serviceId}` as const,ServiceTokenStatusUpdate: (serviceTokenId: string) => `service-token-status:${serviceTokenId}`,GatewayIdentityCredential: (identityId: string) => `gateway-credentials:${identityId}`,+ GatewayLoad: (gatewayId: string) => `gateway-load:${gatewayId}` as const,+ GatewayLoadReservation: (gatewayId: string) => `gateway-reservation:${gatewayId}` as const,+ GatewaySuspect: (gatewayId: string) => `gateway-suspect:${gatewayId}` as const,ActiveSSEConnectionsSet: (projectId: string, identityId: string) =>`sse-connections:${projectId}:${identityId}` as const,ActiveSSEConnections: (projectId: string, identityId: string, connectionId: string) =>@@ -259,6 +262,7 @@ export type TKeyStoreFactory = {getItem: (key: string, prefix?: string) => Promise<string | null>;getItemPrimary: (key: string, prefix?: string) => Promise<string | null>;getItems: (keys: string[], prefix?: string) => Promise<(string | null)[]>;+ getItemsPrimary: (keys: string[], prefix?: string) => Promise<(string | null)[]>;setExpiry: (key: string, expiryInSeconds: number) => Promise<number>;ttl: (key: string) => Promise<number>;setItemWithExpiry: (@@ -306,6 +310,8 @@ export type TKeyStoreFactory = {// hash operationshashSet: (key: string, field: string, value: string) => Promise<number>;hashGet: (key: string, field: string) => Promise<string | null>;+ hashGetAll: (key: string) => Promise<Record<string, string>>;+ hashDelete: (key: string, field: string) => Promise<number>;// pgpgIncrementBy: (key: string, dto: { incr?: number; expiry?: string; tx?: Knex }) => Promise<number>;pgGetIntItem: (key: string, prefix?: string) => Promise<number | undefined>;@@ -360,6 +366,9 @@ export const keyStoreFactory = (const getItemPrimary = async (key: string, prefix?: string) => primaryRedis.get(prefix ? `${prefix}:${key}` : key);+ const getItemsPrimary = async (keys: string[], prefix?: string) =>+ primaryRedis.mget(keys.map((key) => (prefix ? `${prefix}:${key}` : key)));+const getItems = async (keys: string[], prefix?: string) =>pickPrimaryOrSecondaryRedis(primaryRedis, redisReadReplicas).mget(keys.map((key) => (prefix ? `${prefix}:${key}` : key))@@ -532,6 +541,10 @@ export const keyStoreFactory = (const hashGet = async (key: string, field: string) => primaryRedis.hget(key, field);+ const hashGetAll = async (key: string) => primaryRedis.hgetall(key);++ const hashDelete = async (key: string, field: string) => primaryRedis.hdel(key, field);+// List operationsconst listPush = async (key: string, value: string) => primaryRedis.rpush(key, value);@@ -654,10 +667,13 @@ export const keyStoreFactory = (getKeysByPattern,deleteItemsByKeyIn,getItems,+ getItemsPrimary,pgGetIntItem,pgIncrementBy,hashSet,hashGet,+ hashGetAll,+ hashDelete,listPush,listRange,listRemove,diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.tsindex 6598c6b9dd..3366447c52 100644--- a/backend/src/keystore/memory.ts+++ b/backend/src/keystore/memory.ts@@ -20,7 +20,7 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {},setExpiry: async () => 0,ttl: async () => -1,- setItemWithExpiry: async (key, value) => {+ setItemWithExpiry: async (key, _expiryInSeconds, value) => {store[key] = value;return "OK";},@@ -83,6 +83,14 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {hashGet: async (key, field) => {return hashStore[key]?.[field] ?? null;},+ hashGetAll: async (key) => {+ return { ...(hashStore[key] ?? {}) };+ },+ hashDelete: async (key, field) => {+ if (!hashStore[key]?.[field]) return 0;+ delete hashStore[key][field];+ return 1;+ },pgIncrementBy: async () => {return 1;},@@ -95,8 +103,15 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {incrementByAndRefreshExpiryIfUnderLimit: async () => {return 1;},- decrementByOrDelete: async () => {- return 0;+ decrementByOrDelete: async (key) => {+ const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;+ const next = current - 1;+ if (next <= 0) {+ delete store[key];+ return 0;+ }+ store[key] = String(next);+ return next;},incrementByWithExpiry: async (key, value) => {const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;@@ -132,6 +147,12 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {}return keys.length;},+ getItemsPrimary: async (keys) => {+ return keys.map((key) => {+ const value = store[key];+ return typeof value === "string" ? value : null;+ });+ },getItems: async (keys) => {const values = keys.map((key) => {const value = store[key];diff --git a/backend/src/lib/errors/index.ts b/backend/src/lib/errors/index.tsindex c7577fe7bf..870d8a59f8 100644--- a/backend/src/lib/errors/index.ts+++ b/backend/src/lib/errors/index.ts@@ -118,6 +118,20 @@ export class BadRequestError extends Error {}}+/**+ * The tunnel to the gateway could never be established, so nothing reached the target and the+ * operation is safe to retry against a different pool member. Any failure raised once the tunnel is+ * up must NOT use this class: the target may have already applied a partial change.+ */+export class GatewayTransportError extends BadRequestError {+ gatewayId?: string;++ constructor({ message, gatewayId }: { message?: string; gatewayId?: string }) {+ super({ message: message ?? "Failed to reach the gateway", name: "GatewayTransportError" });+ this.gatewayId = gatewayId;+ }+}+export class RateLimitError extends Error {constructor({ message }: { message?: string }) {super(message || "Rate limit exceeded");diff --git a/backend/src/lib/gateway-v2/gateway-attempt-context.ts b/backend/src/lib/gateway-v2/gateway-attempt-context.tsnew file mode 100644index 0000000000..8e5cd5e6b0--- /dev/null+++ b/backend/src/lib/gateway-v2/gateway-attempt-context.ts@@ -0,0 +1,25 @@+import { AsyncLocalStorage } from "node:async_hooks";++export type TGatewayAttempt = {+ transportFailed: boolean;+};++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.+ */+export const runGatewayAttempt = async <T>(attempt: TGatewayAttempt, fn: () => Promise<T>): Promise<T> =>+ storage.run(attempt, fn);++export const markAttemptTransportFailure = () => {+ const attempt = storage.getStore();+ if (attempt) attempt.transportFailed = true;+};diff --git a/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts b/backend/src/lib/gateway-v2/gateway-load-tracker.test.tsnew file mode 100644index 0000000000..0492092a12--- /dev/null+++ b/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts@@ -0,0 +1,161 @@+import { KeyStorePrefixes } from "@app/keystore/keystore";+import { inMemoryKeyStore } from "@app/keystore/memory";++import { initGatewayLoadTracker } from "./gateway-load-tracker";++vi.mock("@app/lib/logger", () => ({+ logger: {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn()+ }+}));++const GW_A = "11111111-1111-1111-1111-111111111111";+const GW_B = "22222222-2222-2222-2222-222222222222";++// The debounce means a publish lands on a later tick of the event loop.+const flushPublishes = async () => {+ await vi.advanceTimersByTimeAsync(500);+};++describe("gatewayLoadTracker", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ test("scores an idle gateway at zero", async () => {+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());+ const scores = await tracker.getScores([GW_A, GW_B]);+ expect(scores.get(GW_A)).toBe(0);+ expect(scores.get(GW_B)).toBe(0);+ tracker.shutdown();+ });++ test("counts open channels and releases them on close", async () => {+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());++ tracker.channelOpened(GW_A);+ tracker.channelOpened(GW_A);+ tracker.channelOpened(GW_B);+ expect((await tracker.getScores([GW_A, GW_B])).get(GW_A)).toBe(2);+ expect((await tracker.getScores([GW_A, GW_B])).get(GW_B)).toBe(1);++ tracker.channelClosed(GW_A);+ tracker.channelClosed(GW_A);+ expect((await tracker.getScores([GW_A])).get(GW_A)).toBe(0);++ tracker.shutdown();+ });++ test("a reservation counts toward the score before the channel opens", async () => {+ const keyStore = inMemoryKeyStore();+ const tracker = initGatewayLoadTracker(keyStore);++ await tracker.reserve(GW_A);+ // Without this the second concurrent selection would read zero and stampede the same gateway.+ expect((await tracker.getScores([GW_A, GW_B])).get(GW_A)).toBe(1);+ expect((await tracker.getScores([GW_A, GW_B])).get(GW_B)).toBe(0);++ tracker.shutdown();+ });++ test("releases reservations so repeated selections do not accumulate into round-robin", async () => {+ const keyStore = inMemoryKeyStore();+ const tracker = initGatewayLoadTracker(keyStore);++ for (let i = 0; i < 10; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ await tracker.reserve(GW_A);+ }+ expect((await tracker.getScores([GW_A])).get(GW_A)).toBe(10);++ // Left to expire on their own these would keep counting and turn the score into+ // "selections in the last N seconds", which is request-count round-robin.+ await vi.advanceTimersByTimeAsync(6_000);+ expect((await tracker.getScores([GW_A])).get(GW_A)).toBe(0);++ tracker.shutdown();+ });++ test("sums another pod's published count alongside local channels", async () => {+ const keyStore = inMemoryKeyStore();+ const tracker = initGatewayLoadTracker(keyStore);++ await keyStore.hashSet(KeyStorePrefixes.GatewayLoad(GW_A), "other-pod", `5:${Date.now()}`);+ tracker.channelOpened(GW_A);++ expect((await tracker.getScores([GW_A])).get(GW_A)).toBe(6);+ tracker.shutdown();+ });++ test("ignores a dead pod's stale count instead of counting it forever", async () => {+ const keyStore = inMemoryKeyStore();+ const tracker = initGatewayLoadTracker(keyStore);++ await keyStore.hashSet(KeyStorePrefixes.GatewayLoad(GW_A), "dead-pod", `9:${Date.now() - 120_000}`);++ expect((await tracker.getScores([GW_A])).get(GW_A)).toBe(0);+ tracker.shutdown();+ });++ test("ignores a malformed published entry rather than scoring NaN", async () => {+ const keyStore = inMemoryKeyStore();+ const tracker = initGatewayLoadTracker(keyStore);++ await keyStore.hashSet(KeyStorePrefixes.GatewayLoad(GW_A), "bad-pod", "not-a-count");++ expect((await tracker.getScores([GW_A])).get(GW_A)).toBe(0);+ tracker.shutdown();+ });++ test("drops its own field once it holds nothing, so the hash does not grow per restart", async () => {+ const keyStore = inMemoryKeyStore();+ const tracker = initGatewayLoadTracker(keyStore);++ tracker.channelOpened(GW_A);+ await flushPublishes();+ expect(Object.keys(await keyStore.hashGetAll(KeyStorePrefixes.GatewayLoad(GW_A)))).toHaveLength(1);++ tracker.channelClosed(GW_A);+ await flushPublishes();+ expect(Object.keys(await keyStore.hashGetAll(KeyStorePrefixes.GatewayLoad(GW_A)))).toHaveLength(0);++ tracker.shutdown();+ });++ test("does not double count its own published field against its live count", async () => {+ const keyStore = inMemoryKeyStore();+ const tracker = initGatewayLoadTracker(keyStore);++ tracker.channelOpened(GW_A);+ await flushPublishes();++ expect((await tracker.getScores([GW_A])).get(GW_A)).toBe(1);+ tracker.shutdown();+ });++ test("marks and reports suspect gateways", async () => {+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());++ await tracker.markSuspect(GW_A);+ const suspect = await tracker.getSuspect([GW_A, GW_B]);++ expect(suspect.has(GW_A)).toBe(true);+ expect(suspect.has(GW_B)).toBe(false);+ tracker.shutdown();+ });++ test("returns empty results for an empty gateway list without touching the store", async () => {+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());++ expect((await tracker.getScores([])).size).toBe(0);+ expect((await tracker.getSuspect([])).size).toBe(0);+ tracker.shutdown();+ });+});diff --git a/backend/src/lib/gateway-v2/gateway-load-tracker.ts b/backend/src/lib/gateway-v2/gateway-load-tracker.tsnew file mode 100644index 0000000000..f56e9f23a5--- /dev/null+++ b/backend/src/lib/gateway-v2/gateway-load-tracker.ts@@ -0,0 +1,202 @@+import crypto from "node:crypto";++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.+const RESERVATION_TTL_SECONDS = 20;+const RESERVATION_HOLD_MS = 5_000;+const SUSPECT_TTL_SECONDS = 60;+const LOAD_HASH_TTL_SECONDS = 600;++// Another pod's published count is ignored past this age, so a pod that dies stops skewing selection+// instead of leaving its channels counted forever.+const PUBLISHED_COUNT_MAX_AGE_MS = 90_000;+const PUBLISH_DEBOUNCE_MS = 250;+const PUBLISH_REFRESH_MS = 20_000;++const podId = crypto.randomUUID();++type TGatewayLoadTracker = {+ reserve: (gatewayId: string) => Promise<void>;+ channelOpened: (gatewayId: string) => void;+ channelClosed: (gatewayId: string) => void;+ markSuspect: (gatewayId: string) => Promise<void>;+ getScores: (gatewayIds: string[]) => Promise<Map<string, number>>;+ getSuspect: (gatewayIds: string[]) => Promise<Set<string>>;+ shutdown: () => void;+};++let tracker: TGatewayLoadTracker | undefined;++const loadKey = KeyStorePrefixes.GatewayLoad;+const reservationKey = KeyStorePrefixes.GatewayLoadReservation;+const suspectKey = KeyStorePrefixes.GatewaySuspect;++export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoadTracker => {+ const openChannels = new Map<string, number>();+ const pendingPublish = new Set<string>();+ const reservationTimers = new Set<NodeJS.Timeout>();+ let debounceTimer: NodeJS.Timeout | undefined;++ const publish = async (gatewayId: string) => {+ const count = openChannels.get(gatewayId) ?? 0;+ try {+ // Holding nothing means dropping the field rather than writing a zero, so the hash only ever+ // carries pods with live channels instead of accumulating one entry per restart.+ if (count === 0) {+ await keyStore.hashDelete(loadKey(gatewayId), podId);+ return;+ }+ await keyStore.hashSet(loadKey(gatewayId), podId, `${count}:${Date.now()}`);+ await keyStore.setExpiry(loadKey(gatewayId), LOAD_HASH_TTL_SECONDS);+ } catch (err) {+ logger.debug({ err, gatewayId }, `Failed to publish gateway load [gatewayId=${gatewayId}]`);+ }+ };++ const flushPending = () => {+ const ids = [...pendingPublish];+ pendingPublish.clear();+ debounceTimer = undefined;+ void Promise.all(ids.map((id) => publish(id)));+ };++ const schedulePublish = (gatewayId: string) => {+ pendingPublish.add(gatewayId);+ if (!debounceTimer) {+ debounceTimer = setTimeout(flushPending, PUBLISH_DEBOUNCE_MS);+ debounceTimer.unref();+ }+ };++ // Long-lived channels change the count once and then sit for hours, so the timestamp has to be+ // refreshed independently or other pods would age the entry out while it is still accurate.+ const refreshTimer = setInterval(() => {+ for (const gatewayId of openChannels.keys()) {+ schedulePublish(gatewayId);+ }+ }, PUBLISH_REFRESH_MS);+ refreshTimer.unref();++ const channelOpened = (gatewayId: string) => {+ openChannels.set(gatewayId, (openChannels.get(gatewayId) ?? 0) + 1);+ schedulePublish(gatewayId);+ };++ const channelClosed = (gatewayId: string) => {+ const next = (openChannels.get(gatewayId) ?? 0) - 1;+ if (next > 0) {+ openChannels.set(gatewayId, next);+ } else {+ openChannels.delete(gatewayId);+ }+ schedulePublish(gatewayId);+ };++ const releaseReservation = async (gatewayId: string) => {+ try {+ await keyStore.decrementByOrDelete(reservationKey(gatewayId));+ } catch (err) {+ logger.debug({ err, gatewayId }, `Failed to release gateway reservation [gatewayId=${gatewayId}]`);+ }+ };++ const reserve = async (gatewayId: string) => {+ try {+ await keyStore.incrementByWithExpiry(reservationKey(gatewayId), 1, RESERVATION_TTL_SECONDS);+ } catch (err) {+ logger.debug({ err, gatewayId }, `Failed to reserve gateway capacity [gatewayId=${gatewayId}]`);+ return;+ }+ // The key TTL is only a backstop for a pod that dies holding reservations.+ const timer = setTimeout(() => {+ reservationTimers.delete(timer);+ void releaseReservation(gatewayId);+ }, RESERVATION_HOLD_MS);+ timer.unref();+ reservationTimers.add(timer);+ };++ const markSuspect = async (gatewayId: string) => {+ try {+ await keyStore.setItemWithExpiry(suspectKey(gatewayId), SUSPECT_TTL_SECONDS, "1");+ } catch (err) {+ logger.debug({ err, gatewayId }, `Failed to mark gateway suspect [gatewayId=${gatewayId}]`);+ return;+ }+ logger.warn(+ { gatewayId },+ `Gateway marked suspect after transport failure [gatewayId=${gatewayId}] [ttlSeconds=${SUSPECT_TTL_SECONDS}]`+ );+ };++ const getScores = async (gatewayIds: string[]) => {+ const scores = new Map<string, number>();+ if (gatewayIds.length === 0) return scores;++ const [published, reservations] = await Promise.all([+ Promise.all(gatewayIds.map((id) => keyStore.hashGetAll(loadKey(id)))),+ keyStore.getItemsPrimary(gatewayIds.map((id) => reservationKey(id)))+ ]);++ const cutoff = Date.now() - PUBLISHED_COUNT_MAX_AGE_MS;++ gatewayIds.forEach((gatewayId, idx) => {+ const fields = Object.entries(published[idx] ?? {})+ // This pod's in-memory count is always fresher than what it last published.+ .filter(([fieldPodId]) => fieldPodId !== podId);++ let total = 0;+ for (const [, raw] of fields) {+ const [countStr, tsStr] = raw.split(":");+ const count = Number(countStr);+ const publishedAt = Number(tsStr);+ if (Number.isFinite(count) && Number.isFinite(publishedAt) && publishedAt >= cutoff) {+ total += count;+ }+ }+ total += openChannels.get(gatewayId) ?? 0;+ total += Number(reservations[idx] ?? 0) || 0;+ scores.set(gatewayId, total);+ });++ return scores;+ };++ const getSuspect = async (gatewayIds: string[]) => {+ const suspect = new Set<string>();+ if (gatewayIds.length === 0) return suspect;+ const values = await keyStore.getItemsPrimary(gatewayIds.map((id) => suspectKey(id)));+ gatewayIds.forEach((gatewayId, idx) => {+ if (values[idx]) suspect.add(gatewayId);+ });+ return suspect;+ };++ const shutdown = () => {+ clearInterval(refreshTimer);+ if (debounceTimer) clearTimeout(debounceTimer);+ for (const timer of reservationTimers) clearTimeout(timer);+ reservationTimers.clear();+ };++ tracker = {+ reserve,+ channelOpened,+ channelClosed,+ markSuspect,+ getScores,+ getSuspect,+ shutdown+ };++ return tracker;+};++export const getGatewayLoadTracker = () => tracker;diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.tsindex c68c5c8c63..cba0c1e0f8 100644--- a/backend/src/lib/gateway-v2/gateway-v2.ts+++ b/backend/src/lib/gateway-v2/gateway-v2.ts@@ -9,15 +9,18 @@ import { TGatewayV2ConnectionDetails } from "@app/ee/services/gateway-v2/gatewayimport { splitPemChain } from "@app/services/certificate/certificate-fns";import { getConfig } from "../config/env";-import { BadRequestError } from "../errors";+import { BadRequestError, GatewayTransportError } from "../errors";import { GatewayProxyProtocol } from "../gateway/types";import { logger } from "../logger";+import { markAttemptTransportFailure } from "./gateway-attempt-context";+import { getGatewayLoadTracker } from "./gateway-load-tracker";interface IGatewayRelayServer {server: net.Server;port: number;cleanup: () => Promise<void>;getRelayError: () => string;+ hasEstablishedChannel: () => boolean;}const DEFAULT_RELAY_CONNECTION_TIMEOUT_MS = 100000;@@ -147,6 +150,7 @@ export const createGatewayConnection = async (};export const setupRelayServer = async ({+ gatewayId,protocol,relayHost,gateway,@@ -154,7 +158,6 @@ export const setupRelayServer = async ({httpsAgent,longLived}: {- // Consumed by the load tracker; accepted here so callers thread it through from the start.gatewayId: string;protocol: GatewayProxyProtocol;relayHost: string;@@ -164,6 +167,8 @@ export const setupRelayServer = async ({longLived?: boolean;}): Promise<IGatewayRelayServer> => {const relayErrorMsg: string[] = [];+ let establishedChannel = false;+ const loadTracker = getGatewayLoadTracker();return new Promise((resolve, reject) => {const server = net.createServer();@@ -185,6 +190,17 @@ export const setupRelayServer = async ({// Stage 2: Establish mTLS connection to gateway through the relayconst gatewayConn = await createGatewayConnection(relayConn, gateway, protocol);+ // The caller may have given up while the two handshakes were in flight. Its "close" event+ // has already fired by now, so attaching the teardown listeners below would never run and+ // the channel would stay counted for the life of the pod.+ if (clientConn.destroyed) {+ relayConn.destroy();+ gatewayConn.destroy();+ return;+ }++ establishedChannel = true;+if (longLived) {// Disable the 30s idle-activity timeout that was set during connection establishment.// Without this, the socket is destroyed after 30s of no data, killing idle sessions.@@ -218,7 +234,19 @@ export const setupRelayServer = async ({}}+ // Counted here rather than around the caller's 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.+ loadTracker?.channelOpened(gatewayId);+ let released = false;+ const releaseChannel = () => {+ if (released) return;+ released = true;+ loadTracker?.channelClosed(gatewayId);+ };+const destroyAll = () => {+ releaseChannel();clientConn.destroy();relayConn.destroy();gatewayConn.destroy();@@ -266,7 +294,8 @@ export const setupRelayServer = async ({logger.debug("Error closing server:", err instanceof Error ? err.message : String(err));}},- getRelayError: () => relayErrorMsg.join(",")+ getRelayError: () => relayErrorMsg.join(","),+ hasEstablishedChannel: () => establishedChannel});});});@@ -283,7 +312,7 @@ export const withGatewayV2Proxy = async <T>(): Promise<T> => {const { gatewayId, protocol, relayHost, gateway, relay, httpsAgent, longLived } = options;- const { port, cleanup, getRelayError } = await setupRelayServer({+ const { port, cleanup, getRelayError, hasEstablishedChannel } = await setupRelayServer({gatewayId,protocol,relayHost,@@ -307,6 +336,15 @@ export const withGatewayV2Proxy = async <T>(errorMessage = (err.response?.data as { message: string }).message;}+ // Retryable only when no tunnel ever came up, so the target cannot have seen anything. The relay+ // error list is shared by every channel this proxy served and is never cleared, so a single+ // transient setup failure would otherwise keep marking later target-side errors as retryable.+ if (relayErrorMessage && !hasEstablishedChannel()) {+ markAttemptTransportFailure();+ await getGatewayLoadTracker()?.markSuspect(gatewayId);+ throw new GatewayTransportError({ message: errorMessage, gatewayId });+ }+throw new BadRequestError({ message: errorMessage });} finally {// Ensure cleanup happens regardless of success or failurediff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 8bf19c3aae..7a5768a5ab 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -199,6 +199,7 @@ import { getConfig, TEnvConfig } from "@app/lib/config/env";import { cronJobFactory } from "@app/lib/cron/cron-job";import { crypto } from "@app/lib/crypto/cryptography";import { BadRequestError } from "@app/lib/errors";+import { initGatewayLoadTracker } from "@app/lib/gateway-v2/gateway-load-tracker";import { logger } from "@app/lib/logger";import { Redlock } from "@app/lib/red-lock";import { TQueueServiceFactory } from "@app/queue";@@ -577,6 +578,10 @@ export const registerRoutes = async (const cronJob = cronJobFactory({ redis, redlock });cronJob.start();+ // Reached from the gateway proxy layer in src/lib, which has no DI, so it is installed as a module+ // singleton rather than threaded through every call site.+ initGatewayLoadTracker(keyStore);+await server.register(registerSecretScanningV2Webhooks, {prefix: "/secret-scanning/webhooks"});@@ -1839,7 +1844,6 @@ export const registerRoutes = async (gatewayPoolDAL,gatewayPoolMembershipDAL,gatewayV2DAL,- gatewayV2Service,permissionService,licenseService,identityKubernetesAuthDAL,diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.tsindex 2999f519be..a591f3ed0e 100644--- a/backend/src/services/app-connection/app-connection-service.ts+++ b/backend/src/services/app-connection/app-connection-service.ts@@ -209,7 +209,7 @@ export type TAppConnectionServiceFactoryDep = {gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;gatewayPoolService: Pick<TGatewayPoolServiceFactory,- "pickRandomHealthyGateway" | "resolveAttachableGatewayFromPool" | "resolveEffectiveGatewayId"+ "pickHealthyGateway" | "resolveAttachableGatewayFromPool" | "resolveEffectiveGatewayId" | "runWithPoolFailover">;gatewayDAL: Pick<TGatewayDALFactory, "find">;gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;@@ -581,12 +581,6 @@ export const appConnectionServiceFactory = ({});}- let validationGatewayId: string | null | undefined = gatewayId;- if (gatewayPoolId) {- const picked = await gatewayPoolService.pickRandomHealthyGateway(gatewayPoolId);- validationGatewayId = picked.id;- }-await enterpriseAppCheck(licenseService,app,@@ -601,21 +595,33 @@ export const appConnectionServiceFactory = ({}}- const validatedCredentials = await validateAppConnectionCredentials(- {- app,- credentials,- method,- orgId: actor.orgId,- projectId,- version: 2,- gatewayId: validationGatewayId,- projectType: project?.type- } as TAppConnectionConfig,- gatewayService,- gatewayV2Service,- { identityUaDAL, gitHubAppDAL, kmsService, keyStore, actorId: actor.id }- );+ const runValidation = (validationGatewayId: string | null | undefined) =>+ validateAppConnectionCredentials(+ {+ app,+ credentials,+ method,+ orgId: actor.orgId,+ projectId,+ version: 2,+ gatewayId: validationGatewayId,+ projectType: project?.type+ } as TAppConnectionConfig,+ gatewayService,+ gatewayV2Service,+ { identityUaDAL, gitHubAppDAL, kmsService, keyStore, actorId: actor.id }+ );++ // Validation only dials the target and reads back, so retrying it on another member is safe.+ let validationGatewayId: string | null | undefined = gatewayId;+ let validatedCredentials;+ if (gatewayPoolId) {+ const outcome = await gatewayPoolService.runWithPoolFailover({ poolId: gatewayPoolId }, runValidation);+ validatedCredentials = outcome.result;+ validationGatewayId = outcome.gatewayId;+ } else {+ validatedCredentials = await runValidation(gatewayId);+ }try {const createConnection = async (connectionCredentials: TAppConnection["credentials"]) => {@@ -681,6 +687,8 @@ export const appConnectionServiceFactory = ({let connection: TAppConnectionRaw;if (params.isPlatformManagedCredentials) {+ // Reuses the member validation actually succeeded on, and deliberately does not fail over:+ // this rotates the credential on the target, so a retry could apply the change twice.connection = await TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM[app]({app,@@ -833,17 +841,11 @@ export const appConnectionServiceFactory = ({}let updatedCredentials: undefined | TAppConnection["credentials"];- let validationGatewayId: string | null | undefined;const { app, method } = appConnection as DiscriminativePick<TAppConnectionConfig, "app" | "method">;+ let validationGatewayIdForUpdate: string | null | undefined = effectiveGatewayIdForUpdate;if (credentials) {- validationGatewayId = effectiveGatewayIdForUpdate;- if (effectiveGatewayPoolIdForUpdate) {- const picked = await gatewayPoolService.pickRandomHealthyGateway(effectiveGatewayPoolIdForUpdate);- validationGatewayId = picked.id;- }-// Only checked when the caller explicitly selects an app — merged-in existing credentials// (gitHubAppId undefined) keep already-configured connections editable.if (app === AppConnection.GitHub && method === GitHubConnectionMethod.App && appConnection.projectId) {@@ -886,21 +888,34 @@ export const appConnectionServiceFactory = ({const updateProject = appConnection.projectId ? await projectDAL.findProjectById(appConnection.projectId) : null;- updatedCredentials = await validateAppConnectionCredentials(- {- app,- orgId: actor.orgId,- projectId: appConnection.projectId,- version: appConnection.version,- credentials: credentialsToValidate,- method,- gatewayId: validationGatewayId,- projectType: updateProject?.type- } as TAppConnectionConfig,- gatewayService,- gatewayV2Service,- { identityUaDAL, gitHubAppDAL, kmsService, keyStore, actorId: actor.id }- );+ const runUpdateValidation = (validationGatewayId: string | null | undefined) =>+ validateAppConnectionCredentials(+ {+ app,+ orgId: actor.orgId,+ projectId: appConnection.projectId,+ version: appConnection.version,+ credentials: credentialsToValidate,+ method,+ gatewayId: validationGatewayId,+ projectType: updateProject?.type+ } as TAppConnectionConfig,+ gatewayService,+ gatewayV2Service,+ { identityUaDAL, gitHubAppDAL, kmsService, keyStore, actorId: actor.id }+ );++ // Validation only dials the target and reads back, so retrying it on another member is safe.+ if (effectiveGatewayPoolIdForUpdate) {+ const outcome = await gatewayPoolService.runWithPoolFailover(+ { poolId: effectiveGatewayPoolIdForUpdate },+ runUpdateValidation+ );+ updatedCredentials = outcome.result;+ validationGatewayIdForUpdate = outcome.gatewayId;+ } else {+ updatedCredentials = await runUpdateValidation(effectiveGatewayIdForUpdate);+ }if (!updatedCredentials)throw new BadRequestError({ message: "Unable to validate connection - check credentials" });@@ -961,13 +976,15 @@ export const appConnectionServiceFactory = ({let connection: TAppConnectionRaw;if (params.isPlatformManagedCredentials) {+ // Reuses the member validation actually succeeded on, and deliberately does not fail over:+ // this rotates the credential on the target, so a retry could apply the change twice.connection = await TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM[app]({app,orgId: actor.orgId,credentials: updatedCredentials,method,- gatewayId: validationGatewayId+ gatewayId: validationGatewayIdForUpdate} as TAppConnectionConfig,(platformCredentials) => updateConnection(platformCredentials, tx),gatewayService,diff --git a/backend/src/services/external-migration/external-migration-service.ts b/backend/src/services/external-migration/external-migration-service.tsindex b620d7076b..11527146a0 100644--- a/backend/src/services/external-migration/external-migration-service.ts+++ b/backend/src/services/external-migration/external-migration-service.ts@@ -78,7 +78,7 @@ type TExternalMigrationServiceFactoryDep = {gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;gatewayPoolService: Pick<TGatewayPoolServiceFactory,- "resolveEffectiveGatewayId" | "resolveAttachableGatewayFromPool" | "pickRandomHealthyGateway"+ "resolveEffectiveGatewayId" | "resolveAttachableGatewayFromPool" | "pickHealthyGateway">;};@@ -250,7 +250,7 @@ export const externalMigrationServiceFactory = ({orgId: actorOrgId,actor: { type: actor, id: actorId, orgId: actorOrgId, authMethod: actorAuthMethod }});- const picked = await gatewayPoolService.pickRandomHealthyGateway(gatewayPoolId);+ const picked = await gatewayPoolService.pickHealthyGateway(gatewayPoolId);effectiveGatewayId = picked.id;}diff --git a/backend/src/services/hsm-connector/hsm-connector-routing.ts b/backend/src/services/hsm-connector/hsm-connector-routing.tsindex 4b47ae4118..ff6fb59878 100644--- a/backend/src/services/hsm-connector/hsm-connector-routing.ts+++ b/backend/src/services/hsm-connector/hsm-connector-routing.ts@@ -15,6 +15,8 @@ import {const PKCS11_POOL_RETRY_LIMIT = 2;const TEST_FANOUT_MAX = 10;const PKCS11_TARGET_HOST = "pkcs11";+const NO_CAPABLE_MEMBER_MESSAGE =+ "No HSM-capable gateway available in the pool. Ensure at least one gateway in the pool has HSM support enabled.";type TGatewayRouting = {gatewayId: string | null | undefined;@@ -23,7 +25,7 @@ type TGatewayRouting = {type THsmConnectorRoutingDeps = {gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;- gatewayPoolService: Pick<TGatewayPoolServiceFactory, "listHealthyGateways">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "listHealthyGateways" | "selectGatewayFromPool">;};const isPkcs11Capable = (capabilities: unknown): boolean => {@@ -45,15 +47,16 @@ export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolServicif (!connector.gatewayPoolId) {throw new BadRequestError({ message: "Connector has neither gatewayId nor gatewayPoolId set." });}- const healthy = await gatewayPoolService.listHealthyGateways(connector.gatewayPoolId);- const capable = healthy.filter((g) => isPkcs11Capable(g.capabilities) && !triedGatewayIds.has(g.id));- if (capable.length === 0) {- throw new BadRequestError({- message:- "No HSM-capable gateway available in the pool. Ensure at least one gateway in the pool has HSM support enabled."- });- }- return capable[Math.floor(Math.random() * capable.length)].id;++ // Key material is not portable between HSMs, so a member without the module attached is not an+ // acceptable substitute no matter how idle it is.+ const selected = await gatewayPoolService.selectGatewayFromPool({+ poolId: connector.gatewayPoolId,+ exclude: triedGatewayIds,+ filter: (gateway) => isPkcs11Capable(gateway.capabilities),+ unavailableMessage: NO_CAPABLE_MEMBER_MESSAGE+ });+ return selected.id;};const dispatchPkcs11 = async <T>(args: {@@ -70,7 +73,15 @@ export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolServic// retryable, etc.). Parallelising would fire redundant PKCS#11 calls./* eslint-disable no-await-in-loop */for (let attempt = 0; attempt <= PKCS11_POOL_RETRY_LIMIT; attempt += 1) {- const gatewayId = await pickGateway(args.connector, triedGatewayIds);+ let gatewayId;+ try {+ gatewayId = await pickGateway(args.connector, triedGatewayIds);+ } catch (err) {+ // Once every capable member has been tried, the accumulated PKCS#11 failure is the useful+ // error. Reporting "no HSM-capable gateway" instead points operators at the wrong problem.+ if (!lastError) throw err;+ break;+ }triedGatewayIds.add(gatewayId);const conn = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({@@ -186,10 +197,7 @@ export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolServicif (isPkcs11Capable(g.capabilities)) targets.push(g.id);}if (targets.length === 0) {- throw new BadRequestError({- message:- "No HSM-capable gateway available in the pool. Ensure at least one gateway in the pool has HSM support enabled."- });+ throw new BadRequestError({ message: NO_CAPABLE_MEMBER_MESSAGE });}}diff --git a/backend/src/services/hsm-connector/hsm-connector-service.ts b/backend/src/services/hsm-connector/hsm-connector-service.tsindex 35b6186864..328df10a78 100644--- a/backend/src/services/hsm-connector/hsm-connector-service.ts+++ b/backend/src/services/hsm-connector/hsm-connector-service.ts@@ -42,7 +42,7 @@ export type THsmConnectorServiceFactoryDep = {permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;- gatewayPoolService: Pick<TGatewayPoolServiceFactory, "listHealthyGateways">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "listHealthyGateways" | "selectGatewayFromPool">;gatewayV2DAL: Pick<TGatewayV2DALFactory, "findById">;gatewayPoolDAL: Pick<TGatewayPoolDALFactory, "findById">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.tsindex 122389c673..114cd22b77 100644--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts@@ -18,6 +18,7 @@ import { TGatewayPoolDALFactory } from "@app/ee/services/gateway-pool/gateway-poimport { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { TGatewayV2ConnectionDetails } from "@app/ee/services/gateway-v2/gateway-v2-types";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import {OrgPermissionGatewayActions,@@ -99,10 +100,7 @@ type TIdentityKubernetesAuthServiceFactoryDep = {gatewayV2Service: TGatewayV2ServiceFactory;gatewayDAL: Pick<TGatewayDALFactory, "find">;gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;- gatewayPoolService: Pick<- TGatewayPoolServiceFactory,- "getPlatformConnectionDetailsByPoolId" | "pickRandomHealthyGateway"- >;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "pickHealthyGateway" | "runWithPoolFailover">;gatewayPoolDAL: Pick<TGatewayPoolDALFactory, "findById">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;identityAccessTokenService: Pick<@@ -145,45 +143,59 @@ export const identityKubernetesAuthServiceFactory = ({},gatewayCallback: (host: string, port: number, httpsAgent?: https.Agent) => Promise<T>): Promise<T> => {- const gatewayV2ConnectionDetails = inputs.gatewayPoolId- ? await gatewayPoolService.getPlatformConnectionDetailsByPoolId({- poolId: inputs.gatewayPoolId,- targetHost: inputs.targetHost ?? GATEWAY_AUTH_DEFAULT_HOST,- targetPort: inputs.targetPort ?? 443- })- : await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({- gatewayId: inputs.gatewayId!,- targetHost: inputs.targetHost ?? GATEWAY_AUTH_DEFAULT_HOST,- targetPort: inputs.targetPort ?? 443- });-- if (gatewayV2ConnectionDetails) {- let httpsAgent: https.Agent | undefined;- if (!inputs.reviewTokenThroughGateway) {- httpsAgent = new https.Agent({- ca: inputs.caCert || undefined,- rejectUnauthorized: inputs.verifyTlsCertificate ?? false,- servername: inputs.targetHost- });- }+ let gatewayHttpsAgent: https.Agent | undefined;+ if (!inputs.reviewTokenThroughGateway) {+ gatewayHttpsAgent = new https.Agent({+ ca: inputs.caCert || undefined,+ rejectUnauthorized: inputs.verifyTlsCertificate ?? false,+ servername: inputs.targetHost+ });+ }- const callbackResult = await withGatewayV2Proxy(+ const $proxyThroughGatewayV2 = async (details: TGatewayV2ConnectionDetails) =>+ withGatewayV2Proxy(async (port) => {const res = await gatewayCallback(inputs.reviewTokenThroughGateway ? "http://localhost" : "https://localhost",port,- httpsAgent+ gatewayHttpsAgent);return res;},{- ...gatewayV2ConnectionDetails,protocol: inputs.reviewTokenThroughGateway ? GatewayProxyProtocol.Http : GatewayProxyProtocol.Tcp,- httpsAgent+ ...details,+ httpsAgent: gatewayHttpsAgent});- return callbackResult;+ // Pools are gateway-v2 only, so there is no v1 fallback to preserve on this branch.+ if (inputs.gatewayPoolId) {+ const { result } = await gatewayPoolService.runWithPoolFailover(+ { poolId: inputs.gatewayPoolId },+ async (gatewayId) => {+ const details = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ gatewayId,+ targetHost: inputs.targetHost ?? GATEWAY_AUTH_DEFAULT_HOST,+ targetPort: inputs.targetPort ?? 443+ });+ if (!details) {+ throw new NotFoundError({ message: `Connection details for gateway with ID ${gatewayId} not found` });+ }+ return $proxyThroughGatewayV2(details);+ }+ );+ return result;+ }++ const gatewayV2ConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ gatewayId: inputs.gatewayId!,+ targetHost: inputs.targetHost ?? GATEWAY_AUTH_DEFAULT_HOST,+ targetPort: inputs.targetPort ?? 443+ });++ if (gatewayV2ConnectionDetails) {+ return $proxyThroughGatewayV2(gatewayV2ConnectionDetails);}const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(inputs.gatewayId!);@@ -950,7 +962,7 @@ export const identityKubernetesAuthServiceFactory = ({}// Validate connectivity through a random healthy pool member- const validationGateway = await gatewayPoolService.pickRandomHealthyGateway(gatewayPoolId);+ const validationGateway = await gatewayPoolService.pickHealthyGateway(gatewayPoolId);if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway) {const gatewayExecutor = $createGatewayValidationRequest(validationGateway.id);await validateKubernetesHostConnectivity({ gatewayExecutor });@@ -1285,7 +1297,7 @@ export const identityKubernetesAuthServiceFactory = ({let validationGatewayId: string | null = effectiveGatewayId ?? null;if (!validationGatewayId && effectiveGatewayPoolId) {- const picked = await gatewayPoolService.pickRandomHealthyGateway(effectiveGatewayPoolId);+ const picked = await gatewayPoolService.pickHealthyGateway(effectiveGatewayPoolId);validationGatewayId = picked.id;}