Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(gateway-pools): address review, and use the gateway's own load count

bernie-gf19363fb87e0
diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.ts
index 540688b6f0..6e4014bc26 100644
--- a/backend/src/ee/routes/v2/gateway-router.ts
+++ b/backend/src/ee/routes/v2/gateway-router.ts
@@ -61,6 +61,37 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
}
});
+ // Deliberately separate from /heartbeat: that one probes back through the relay and writes to the
+ // database, which is far too costly to run at the cadence pool selection needs. This only touches
+ // the load tracker's Redis keys.
+ server.route({
+ method: "POST",
+ url: "/load",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: "gatewayLoadReport",
+ body: z.object({
+ activeChannels: z.number().int().min(0).max(1_000_000)
+ }),
+ response: {
+ 200: z.object({
+ message: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ await server.services.gatewayV2.reportLoad({
+ orgPermission: req.permission,
+ activeChannels: req.body.activeChannels
+ });
+
+ return { message: "Successfully reported gateway load" };
+ }
+ });
+
server.route({
method: "POST",
url: "/heartbeat",
diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-failover.test.ts b/backend/src/ee/services/gateway-pool/gateway-pool-failover.test.ts
new file mode 100644
index 0000000000..d757814285
--- /dev/null
+++ b/backend/src/ee/services/gateway-pool/gateway-pool-failover.test.ts
@@ -0,0 +1,237 @@
+import { BadRequestError, GatewayTransportError } from "@app/lib/errors";
+
+type TDeps = Parameters<typeof import("./gateway-pool-service").gatewayPoolServiceFactory>[0];
+
+const markSuspect = vi.fn();
+const getSuspect = vi.fn().mockResolvedValue(new Set<string>());
+const getScores = vi.fn();
+const reserve = vi.fn();
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }
+}));
+
+vi.mock("@app/lib/gateway-v2/gateway-load-tracker", () => ({
+ getGatewayLoadTracker: () => ({ markSuspect, getSuspect, getScores, reserve })
+}));
+
+// eslint-disable-next-line import/first
+import { gatewayPoolServiceFactory } from "./gateway-pool-service";
+
+const POOL_ID = "11111111-1111-1111-1111-111111111111";
+const MEMBERS: { id: string; capabilities?: unknown }[] = [{ id: "gw-a" }, { id: "gw-b" }, { id: "gw-c" }];
+
+const buildService = (members = MEMBERS) =>
+ gatewayPoolServiceFactory({
+ gatewayPoolDAL: { findById: vi.fn().mockResolvedValue({ id: POOL_ID, orgId: "org" }) },
+ gatewayPoolMembershipDAL: { findHealthyGatewaysByPoolId: vi.fn().mockResolvedValue(members) },
+ gatewayV2DAL: { findById: vi.fn() },
+ permissionService: {},
+ licenseService: { getPlan: vi.fn() },
+ identityKubernetesAuthDAL: {},
+ pkiDiscoveryConfigDAL: {},
+ appConnectionDAL: {},
+ dynamicSecretDAL: {}
+ } as unknown as TDeps);
+
+describe("selectGatewayFromPool under load-tracker failure", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // clearAllMocks keeps implementations, so a rejection set by one test would leak into the next.
+ markSuspect.mockResolvedValue(undefined);
+ reserve.mockResolvedValue(undefined);
+ getSuspect.mockResolvedValue(new Set<string>());
+ getScores.mockResolvedValue(new Map(MEMBERS.map((m) => [m.id, { score: 0, reported: true }])));
+ });
+
+ test("still selects, and spreads, when Redis reads fail", async () => {
+ const svc = buildService();
+ getScores.mockRejectedValue(new Error("ECONNREFUSED"));
+
+ const picked = new Set<string>();
+ for (let i = 0; i < 300; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ picked.add((await svc.selectGatewayFromPool({ poolId: POOL_ID })).id);
+ }
+
+ // A Redis outage must degrade to random selection, never fail the request.
+ expect(picked).toEqual(new Set(["gw-a", "gw-b", "gw-c"]));
+ });
+
+ test("still selects when the suspect lookup fails", async () => {
+ const svc = buildService();
+ getSuspect.mockRejectedValue(new Error("ECONNREFUSED"));
+
+ await expect(svc.selectGatewayFromPool({ poolId: POOL_ID })).resolves.toBeDefined();
+ });
+
+ test("a failed reservation write does not fail the selection", async () => {
+ const svc = buildService();
+ reserve.mockRejectedValue(new Error("ECONNREFUSED"));
+
+ await expect(svc.selectGatewayFromPool({ poolId: POOL_ID })).resolves.toBeDefined();
+ });
+
+ test("skips a suspect member but still routes when every member is suspect", async () => {
+ const svc = buildService();
+ getSuspect.mockResolvedValue(new Set(["gw-a"]));
+ const picked = new Set<string>();
+ for (let i = 0; i < 200; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ picked.add((await svc.selectGatewayFromPool({ poolId: POOL_ID })).id);
+ }
+ expect(picked.has("gw-a")).toBe(false);
+
+ getSuspect.mockResolvedValue(new Set(["gw-a", "gw-b", "gw-c"]));
+ // Refusing to route at all would be a guaranteed outage; the marks may simply have aged badly.
+ await expect(svc.selectGatewayFromPool({ poolId: POOL_ID })).resolves.toBeDefined();
+ });
+
+ test("404s an unknown pool rather than blaming gateway health", async () => {
+ const svc = gatewayPoolServiceFactory({
+ gatewayPoolDAL: { findById: vi.fn().mockResolvedValue(undefined) },
+ gatewayPoolMembershipDAL: { findHealthyGatewaysByPoolId: vi.fn() },
+ gatewayV2DAL: { findById: vi.fn() },
+ permissionService: {},
+ licenseService: { getPlan: vi.fn() },
+ identityKubernetesAuthDAL: {},
+ pkiDiscoveryConfigDAL: {},
+ appConnectionDAL: {},
+ dynamicSecretDAL: {}
+ } as unknown as TDeps);
+
+ await expect(svc.selectGatewayFromPool({ poolId: POOL_ID })).rejects.toThrow(
+ `Gateway pool with ID ${POOL_ID} not found`
+ );
+ });
+
+ test("applies a capability filter before anything else, so HSM cannot land on a bare gateway", async () => {
+ const svc = gatewayPoolServiceFactory({
+ gatewayPoolDAL: { findById: vi.fn().mockResolvedValue({ id: POOL_ID, orgId: "org" }) },
+ gatewayPoolMembershipDAL: {
+ findHealthyGatewaysByPoolId: vi.fn().mockResolvedValue([
+ { id: "gw-a", capabilities: {} },
+ { id: "gw-hsm", capabilities: { pkcs11: true } },
+ { id: "gw-c", capabilities: null }
+ ])
+ },
+ gatewayV2DAL: { findById: vi.fn() },
+ permissionService: {},
+ licenseService: { getPlan: vi.fn() },
+ identityKubernetesAuthDAL: {},
+ pkiDiscoveryConfigDAL: {},
+ appConnectionDAL: {},
+ dynamicSecretDAL: {}
+ } as unknown as TDeps);
+
+ for (let i = 0; i < 200; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const picked = await svc.selectGatewayFromPool({
+ poolId: POOL_ID,
+ filter: (g) => (g.capabilities as { pkcs11?: boolean } | null)?.pkcs11 === true
+ });
+ expect(picked.id).toBe("gw-hsm");
+ }
+ });
+
+ test("reports the caller's message when a filter excludes every member", async () => {
+ const svc = buildService([{ id: "gw-a", capabilities: {} }]);
+
+ await expect(
+ svc.selectGatewayFromPool({
+ poolId: POOL_ID,
+ filter: () => false,
+ unavailableMessage: "No HSM-capable gateway available in the pool."
+ })
+ ).rejects.toThrow("No HSM-capable gateway available in the pool.");
+ });
+});
+
+describe("runWithPoolFailover", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // clearAllMocks keeps implementations, so a rejection set by one test would leak into the next.
+ markSuspect.mockResolvedValue(undefined);
+ reserve.mockResolvedValue(undefined);
+ getSuspect.mockResolvedValue(new Set<string>());
+ getScores.mockResolvedValue(new Map(MEMBERS.map((m) => [m.id, { score: 0, reported: true }])));
+ });
+
+ test("returns the result and the member it ran on", async () => {
+ const svc = buildService();
+ const out = await svc.runWithPoolFailover({ poolId: POOL_ID }, async () => "done");
+
+ expect(out.result).toBe("done");
+ expect(MEMBERS.map((m) => m.id)).toContain(out.gatewayId);
+ });
+
+ test("retries on another member when no tunnel was established", async () => {
+ const svc = buildService();
+ const seen: string[] = [];
+
+ const out = await svc.runWithPoolFailover({ poolId: POOL_ID }, async (gatewayId) => {
+ seen.push(gatewayId);
+ if (seen.length === 1) throw new GatewayTransportError({ message: "relay unreachable", gatewayId });
+ return "recovered";
+ });
+
+ expect(out.result).toBe("recovered");
+ expect(seen).toHaveLength(2);
+ expect(seen[0]).not.toBe(seen[1]);
+ });
+
+ test("never retries a failure raised after the target was reached", async () => {
+ const svc = buildService();
+ const seen: string[] = [];
+
+ // The defining safety property: a rotation that half-applied must not run twice.
+ await expect(
+ svc.runWithPoolFailover({ poolId: POOL_ID }, async (gatewayId) => {
+ seen.push(gatewayId);
+ throw new BadRequestError({ message: "password authentication failed" });
+ })
+ ).rejects.toThrow("password authentication failed");
+
+ expect(seen).toHaveLength(1);
+ });
+
+ test("stops at the attempt cap instead of walking the whole pool", async () => {
+ const svc = buildService();
+ const seen: string[] = [];
+
+ await expect(
+ svc.runWithPoolFailover({ poolId: POOL_ID }, async (gatewayId) => {
+ seen.push(gatewayId);
+ throw new GatewayTransportError({ message: "relay unreachable", gatewayId });
+ })
+ ).rejects.toThrow("relay unreachable");
+
+ // Two attempts, not three: retrying every member multiplies load onto whatever is still up.
+ expect(seen).toHaveLength(2);
+ });
+
+ test("surfaces the transport failure, not a selection error, once members run out", async () => {
+ const svc = buildService([{ id: "only-one" }]);
+
+ await expect(
+ svc.runWithPoolFailover({ poolId: POOL_ID }, async (gatewayId) => {
+ throw new GatewayTransportError({ message: "relay unreachable", gatewayId });
+ })
+ ).rejects.toThrow("relay unreachable");
+ });
+
+ test("runs directly with no selection when a specific gateway is configured", async () => {
+ const svc = buildService();
+ const out = await svc.runWithPoolFailover({ gatewayId: "pinned" }, async (gatewayId) => gatewayId);
+
+ expect(out).toEqual({ result: "pinned", gatewayId: "pinned" });
+ expect(reserve).not.toHaveBeenCalled();
+ });
+
+ test("rejects when neither a gateway nor a pool is configured", async () => {
+ const svc = buildService();
+ await expect(svc.runWithPoolFailover({}, async () => "x")).rejects.toThrow(
+ "No gateway or gateway pool is configured."
+ );
+ });
+});
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.ts
index 7f1581fcae..c3e6d8b554 100644
--- 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.ts
@@ -1,5 +1,11 @@
+import { TGatewayScore } from "@app/lib/gateway-v2/gateway-load-tracker";
+
import { chooseLeastLoadedGateway, pickRandomGateway } from "./gateway-pool-selection-fns";
+// Every member reports unless a test says otherwise; a mixed pool is covered separately.
+const reported = (entries: Record<string, number>): Map<string, TGatewayScore> =>
+ new Map(Object.entries(entries).map(([id, score]) => [id, { score, reported: true }]));
+
const gateways = [{ id: "a" }, { id: "b" }, { id: "c" }];
describe("chooseLeastLoadedGateway", () => {
@@ -14,23 +20,15 @@ describe("chooseLeastLoadedGateway", () => {
});
test("takes the clear minimum alone when the runner-up is not close", () => {
- const scores = new Map([
- ["a", 10],
- ["b", 1],
- ["c", 4]
- ]);
+ const scores = reported({ 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]
- ]);
+ test("spreads across members that tie exactly", () => {
+ const scores = reported({ a: 10, b: 1, c: 1 });
const picked = new Set<string>();
for (let i = 0; i < 500; i += 1) {
@@ -40,14 +38,22 @@ describe("chooseLeastLoadedGateway", () => {
expect(picked).toEqual(new Set(["b", "c"]));
});
- test("does not hand a two-member pool a coin flip when one is clearly busier", () => {
+ test("a single reservation is decisive, so a concurrent selection moves on", () => {
+ // A reservation is worth exactly +1. If a tie band of 1 were tolerated it would cancel the
+ // reservation out and re-shortlist the member the previous selection just claimed.
+ const pair = [{ id: "a" }, { id: "b" }];
+ const afterReservingA = reported({ a: 1, b: 0 });
+
+ for (let i = 0; i < 500; i += 1) {
+ expect(chooseLeastLoadedGateway(pair, afterReservingA)).toEqual({ id: "b" });
+ }
+ });
+
+ test("does not hand a two-member pool a coin flip when one is 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]
- ]);
+ const scores = reported({ a: 8, b: 0 });
for (let i = 0; i < 500; i += 1) {
expect(chooseLeastLoadedGateway(pair, scores)).toEqual({ id: "b" });
@@ -55,24 +61,58 @@ describe("chooseLeastLoadedGateway", () => {
});
test("never sends half the traffic to a near-saturated member", () => {
- const scores = new Map([
- ["a", 0],
- ["b", 99],
- ["c", 100]
- ]);
+ const scores = reported({ 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]
+ test("does not compare a member it has no data for", () => {
+ // c is absent entirely, so the set is not on one scale. Guessing it is idle would pull traffic
+ // toward the one member we know least about.
+ const scores = reported({ a: 5, b: 5 });
+ const picked = new Set<string>();
+ for (let i = 0; i < 500; i += 1) {
+ picked.add(chooseLeastLoadedGateway(gateways, scores)!.id);
+ }
+ expect(picked).toEqual(new Set(["a", "b", "c"]));
+ });
+
+ test("gives a mixed-version pool no load awareness rather than a biased guess", () => {
+ // b is too old to report, so its score covers only platform-opened channels and is strictly
+ // lower than a reporting peer's true occupancy. Comparing them would favour b all rollout long.
+ const mixed = new Map([
+ ["a", { score: 40, reported: true }],
+ ["b", { score: 0, reported: false }],
+ ["c", { score: 41, reported: true }]
]);
- expect(chooseLeastLoadedGateway(gateways, scores, () => 0)).toEqual({ id: "c" });
+ const tally: Record<string, number> = { a: 0, b: 0, c: 0 };
+ for (let i = 0; i < 3000; i += 1) {
+ tally[chooseLeastLoadedGateway(gateways, mixed)!.id] += 1;
+ }
+
+ // Uniform, not "b wins every time".
+ for (const id of ["a", "b", "c"]) expect(tally[id]).toBeGreaterThan(700);
+ });
+
+ test("uses load awareness when every member reports", () => {
+ const scores = reported({ a: 40, b: 0, c: 41 });
+ for (let i = 0; i < 500; i += 1) {
+ expect(chooseLeastLoadedGateway(gateways, scores)).toEqual({ id: "b" });
+ }
+ });
+
+ test("uses load awareness when no member reports, since the scale is consistent", () => {
+ const legacy = new Map([
+ ["a", { score: 9, reported: false }],
+ ["b", { score: 1, reported: false }],
+ ["c", { score: 8, reported: false }]
+ ]);
+ for (let i = 0; i < 500; i += 1) {
+ expect(chooseLeastLoadedGateway(gateways, legacy)).toEqual({ id: "b" });
+ }
});
test("reaches every member when the pool is idle and all scores tie", () => {
@@ -97,11 +137,7 @@ describe("chooseLeastLoadedGateway", () => {
});
test("still prefers the least loaded once scores differ", () => {
- const scores = new Map([
- ["a", 50],
- ["b", 0],
- ["c", 1]
- ]);
+ const scores = reported({ 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) {
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.ts
index aa9b1c15db..eb1935a2fe 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
@@ -1,8 +1,19 @@
+import { TGatewayScore } from "@app/lib/gateway-v2/gateway-load-tracker";
+
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;
+// Only exact ties are randomised. A reservation is worth exactly +1, so any wider band would cancel
+// it out and re-shortlist the member a concurrent selection just claimed, which is the stampede the
+// reservation exists to prevent.
+const SCORE_TIE_BAND = 0;
+
+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)];
+};
/**
* Picks the least-loaded member, breaking between the two lowest at random.
@@ -13,12 +24,21 @@ const SCORE_TIE_BAND = 1;
*/
export const chooseLeastLoadedGateway = <T extends TSelectableGateway>(
candidates: T[],
- scores: Map<string, number>,
+ scores: Map<string, TGatewayScore>,
random: () => number = Math.random
): T | undefined => {
if (candidates.length === 0) return undefined;
if (candidates.length === 1) return candidates[0];
+ // A member too old to report its own count is scored only on the channels this platform opened,
+ // which is a strictly lower number than a reporting peer's true occupancy. Comparing the two would
+ // make the un-upgraded member look idle and pull traffic toward it for the whole rollout, so a
+ // mixed pool gets no load awareness at all rather than a biased guess.
+ const reportedCount = candidates.filter((c) => scores.get(c.id)?.reported).length;
+ if (reportedCount > 0 && reportedCount < candidates.length) {
+ return pickRandomGateway(candidates, random);
+ }
+
// 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.
@@ -28,23 +48,15 @@ export const chooseLeastLoadedGateway = <T extends TSelectableGateway>(
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
- const ranked = shuffled.sort((a, b) => (scores.get(a.id) ?? 0) - (scores.get(b.id) ?? 0));
+ const scoreOf = (id: string) => scores.get(id)?.score ?? 0;
+ const ranked = shuffled.sort((a, b) => scoreOf(a.id) - scoreOf(b.id));
- // 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;
+ // Only shortlist the runner-up when it ties. 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}.
+ const best = scoreOf(ranked[0].id);
+ const runnerUp = scoreOf(ranked[1].id);
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.ts
index 025aff085b..d7a57a5a10 100644
--- a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts
+++ b/backend/src/ee/services/gateway-pool/gateway-pool-service.ts
@@ -259,6 +259,11 @@ export const gatewayPoolServiceFactory = ({
};
const selectGatewayFromPool = async ({ poolId, exclude, filter, unavailableMessage }: TSelectGatewayFromPoolDTO) => {
+ const targetPool = await gatewayPoolDAL.findById(poolId);
+ if (!targetPool) {
+ throw new NotFoundError({ message: `Gateway pool with ID ${poolId} not found` });
+ }
+
const healthyGateways = await gatewayPoolMembershipDAL.findHealthyGatewaysByPoolId(poolId);
const eligible = healthyGateways
@@ -294,7 +299,12 @@ export const gatewayPoolServiceFactory = ({
if (!selected)
throw new BadRequestError({ message: unavailableMessage ?? "Gateway pool has no healthy gateways." });
- await loadTracker?.reserve(selected.id);
+ // Bookkeeping must never be able to fail a selection, whatever the tracker does internally.
+ try {
+ await loadTracker?.reserve(selected.id);
+ } catch (err) {
+ logger.warn({ err, poolId }, `Failed to reserve gateway capacity [poolId=${poolId}]`);
+ }
logger.info(
{ poolId, selectedGatewayId: selected.id },
@@ -344,7 +354,7 @@ export const gatewayPoolServiceFactory = ({
}
tried.add(selected.id);
- const gatewayAttempt = { transportFailed: false };
+ const gatewayAttempt = { transportFailed: false, tunnelEstablished: false };
try {
return {
result: await runGatewayAttempt(gatewayAttempt, () => operation(selected.id)),
@@ -353,7 +363,9 @@ export const gatewayPoolServiceFactory = ({
} 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;
+ const retryable =
+ (gatewayAttempt.transportFailed || err instanceof GatewayTransportError) && !gatewayAttempt.tunnelEstablished;
+ if (!retryable) throw err;
lastError = err;
logger.warn(
{ err, poolId, gatewayId: selected.id, attempt },
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
index a636ff8a97..6ef99e063b 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -10,6 +10,7 @@ import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
import { groupBy } from "@app/lib/fn";
import { GatewayProxyProtocol } from "@app/lib/gateway/types";
+import { getGatewayLoadTracker } from "@app/lib/gateway-v2/gateway-load-tracker";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { logger } from "@app/lib/logger";
import { OrgServiceActor } from "@app/lib/types";
@@ -986,6 +987,27 @@ export const gatewayV2ServiceFactory = ({
await $checkGatewayHealth(gateway.id);
};
+ const reportLoad = async ({
+ orgPermission,
+ activeChannels
+ }: {
+ orgPermission: OrgServiceActor;
+ activeChannels: number;
+ }) => {
+ const gateway =
+ orgPermission.type === ActorType.GATEWAY
+ ? await gatewayV2DAL.findById(orgPermission.id)
+ : await gatewayV2DAL.findOne({ orgId: orgPermission.orgId, identityId: orgPermission.id });
+
+ if (!gateway || gateway.orgId !== orgPermission.orgId) {
+ throw new NotFoundError({ message: `Gateway ${orgPermission.id} not found.` });
+ }
+
+ // Deliberately no heartbeat side effect: liveness stays with /heartbeat so a gateway cannot look
+ // healthy purely by reporting load, and so this stays a single Redis write.
+ await getGatewayLoadTracker()?.recordReportedLoad(gateway.id, activeChannels);
+ };
+
const deleteGatewayById = async ({ orgPermission, id }: { orgPermission: OrgServiceActor; id: string }) => {
const gateway = await gatewayV2DAL.findOne({ id, orgId: orgPermission.orgId });
if (!gateway) {
@@ -1321,6 +1343,7 @@ export const gatewayV2ServiceFactory = ({
return {
listGateways,
registerGateway,
+ reportLoad,
getPlatformConnectionDetailsByGatewayId,
getPAMConnectionDetails,
deleteGatewayById,
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index 0e6f286c42..f3e61b83b3 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -83,6 +83,7 @@ export const KeyStorePrefixes = {
ServiceTokenStatusUpdate: (serviceTokenId: string) => `service-token-status:${serviceTokenId}`,
GatewayIdentityCredential: (identityId: string) => `gateway-credentials:${identityId}`,
GatewayLoad: (gatewayId: string) => `gateway-load:${gatewayId}` as const,
+ GatewayReportedLoad: (gatewayId: string) => `gateway-reported-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) =>
diff --git a/backend/src/lib/errors/index.ts b/backend/src/lib/errors/index.ts
index 870d8a59f8..a28857566e 100644
--- a/backend/src/lib/errors/index.ts
+++ b/backend/src/lib/errors/index.ts
@@ -127,7 +127,9 @@ export class GatewayTransportError extends BadRequestError {
gatewayId?: string;
constructor({ message, gatewayId }: { message?: string; gatewayId?: string }) {
- super({ message: message ?? "Failed to reach the gateway", name: "GatewayTransportError" });
+ // Deliberately keeps the BadRequest name so the serialised `error` field is unchanged for
+ // callers. Retry decisions use instanceof, never the name.
+ super({ message: message ?? "Failed to reach the gateway" });
this.gatewayId = gatewayId;
}
}
diff --git a/backend/src/lib/gateway-v2/gateway-attempt-context.ts b/backend/src/lib/gateway-v2/gateway-attempt-context.ts
index 8e5cd5e6b0..350136bec3 100644
--- a/backend/src/lib/gateway-v2/gateway-attempt-context.ts
+++ b/backend/src/lib/gateway-v2/gateway-attempt-context.ts
@@ -2,6 +2,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
export type TGatewayAttempt = {
transportFailed: boolean;
+ tunnelEstablished: boolean;
};
const storage = new AsyncLocalStorage<TGatewayAttempt>();
@@ -23,3 +24,12 @@ export const markAttemptTransportFailure = () => {
const attempt = storage.getStore();
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.
+ */
+export const markAttemptTunnelEstablished = () => {
+ const attempt = storage.getStore();
+ if (attempt) attempt.tunnelEstablished = true;
+};
diff --git a/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts b/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts
index 0492092a12..ab132a8b6a 100644
--- a/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts
+++ b/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts
@@ -32,8 +32,8 @@ describe("gatewayLoadTracker", () => {
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);
+ expect(scores.get(GW_A)?.score).toBe(0);
+ expect(scores.get(GW_B)?.score).toBe(0);
tracker.shutdown();
});
@@ -43,12 +43,12 @@ describe("gatewayLoadTracker", () => {
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);
+ expect((await tracker.getScores([GW_A, GW_B])).get(GW_A)?.score).toBe(2);
+ expect((await tracker.getScores([GW_A, GW_B])).get(GW_B)?.score).toBe(1);
tracker.channelClosed(GW_A);
tracker.channelClosed(GW_A);
- expect((await tracker.getScores([GW_A])).get(GW_A)).toBe(0);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(0);
tracker.shutdown();
});
@@ -59,13 +59,31 @@ describe("gatewayLoadTracker", () => {
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);
+ expect((await tracker.getScores([GW_A, GW_B])).get(GW_A)?.score).toBe(1);
+ expect((await tracker.getScores([GW_A, GW_B])).get(GW_B)?.score).toBe(0);
tracker.shutdown();
});
- test("releases reservations so repeated selections do not accumulate into round-robin", async () => {
+ test("hands the reservation off to the channel instead of double counting", async () => {
+ const keyStore = inMemoryKeyStore();
+ const tracker = initGatewayLoadTracker(keyStore);
+
+ await tracker.reserve(GW_A);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(1);
+
+ // The channel now carries the load the reservation stood in for, so the score must stay at 1
+ // rather than counting both.
+ tracker.channelOpened(GW_A);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(1);
+
+ tracker.channelClosed(GW_A);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(0);
+
+ tracker.shutdown();
+ });
+
+ test("releases a reservation whose channel never opens", async () => {
const keyStore = inMemoryKeyStore();
const tracker = initGatewayLoadTracker(keyStore);
@@ -73,12 +91,12 @@ describe("gatewayLoadTracker", () => {
// eslint-disable-next-line no-await-in-loop
await tracker.reserve(GW_A);
}
- expect((await tracker.getScores([GW_A])).get(GW_A)).toBe(10);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).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);
+ // Left to accumulate these would turn the score into "selections in the last N seconds", which
+ // is request-count round-robin rather than occupancy.
+ await vi.advanceTimersByTimeAsync(240_000);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(0);
tracker.shutdown();
});
@@ -90,7 +108,7 @@ describe("gatewayLoadTracker", () => {
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);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(6);
tracker.shutdown();
});
@@ -100,7 +118,7 @@ describe("gatewayLoadTracker", () => {
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);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(0);
tracker.shutdown();
});
@@ -110,7 +128,7 @@ describe("gatewayLoadTracker", () => {
await keyStore.hashSet(KeyStorePrefixes.GatewayLoad(GW_A), "bad-pod", "not-a-count");
- expect((await tracker.getScores([GW_A])).get(GW_A)).toBe(0);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(0);
tracker.shutdown();
});
@@ -136,7 +154,74 @@ describe("gatewayLoadTracker", () => {
tracker.channelOpened(GW_A);
await flushPublishes();
- expect((await tracker.getScores([GW_A])).get(GW_A)).toBe(1);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(1);
+ tracker.shutdown();
+ });
+
+ test("prefers the gateway's own count over the platform's partial view", async () => {
+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());
+
+ // The platform only ever sees channels it opened itself. A PAM CLI session dials the relay
+ // directly, so without the gateway's own count this member would score 0 and look idle.
+ tracker.channelOpened(GW_A);
+ await tracker.recordReportedLoad(GW_A, 50);
+
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(50);
+
+ tracker.shutdown();
+ });
+
+ test("does not sum its own view into the gateway's count", async () => {
+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());
+
+ // The reported 3 already includes the 3 this pod opened; summing would say 6.
+ tracker.channelOpened(GW_A);
+ tracker.channelOpened(GW_A);
+ tracker.channelOpened(GW_A);
+ await tracker.recordReportedLoad(GW_A, 3);
+
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(3);
+
+ tracker.shutdown();
+ });
+
+ test("still adds reservations on top of a reported count", async () => {
+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());
+
+ // A reservation covers a channel the gateway has not seen yet, so it is additive.
+ await tracker.recordReportedLoad(GW_A, 4);
+ await tracker.reserve(GW_A);
+
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(5);
+
+ tracker.shutdown();
+ });
+
+ test("falls back to the platform's view for a gateway too old to report, and flags the scale", async () => {
+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());
+
+ tracker.channelOpened(GW_A);
+ tracker.channelOpened(GW_A);
+ await tracker.recordReportedLoad(GW_B, 7);
+
+ const scores = await tracker.getScores([GW_A, GW_B]);
+ expect(scores.get(GW_A)).toEqual({ score: 2, reported: false });
+ expect(scores.get(GW_B)).toEqual({ score: 7, reported: true });
+
+ tracker.shutdown();
+ });
+
+ test("falls back when a gateway stops reporting", async () => {
+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());
+
+ await tracker.recordReportedLoad(GW_A, 40);
+ tracker.channelOpened(GW_A);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(40);
+
+ // Past the freshness window the stale 40 must not pin the member out of rotation forever.
+ await vi.advanceTimersByTimeAsync(40_000);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(1);
+
tracker.shutdown();
});
diff --git a/backend/src/lib/gateway-v2/gateway-load-tracker.ts b/backend/src/lib/gateway-v2/gateway-load-tracker.ts
index f56e9f23a5..db36a6c971 100644
--- a/backend/src/lib/gateway-v2/gateway-load-tracker.ts
+++ b/backend/src/lib/gateway-v2/gateway-load-tracker.ts
@@ -9,8 +9,10 @@ import { logger } from "../logger";
// 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 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.
+const RESERVATION_HOLD_MS = 230_000;
const SUSPECT_TTL_SECONDS = 60;
const LOAD_HASH_TTL_SECONDS = 600;
@@ -22,19 +24,34 @@ const PUBLISH_REFRESH_MS = 20_000;
const podId = crypto.randomUUID();
+export type TGatewayScore = {
+ score: number;
+ /** False when this member is too old to report its own count, so its score is on a different scale. */
+ reported: boolean;
+};
+
type TGatewayLoadTracker = {
+ recordReportedLoad: (gatewayId: string, activeChannels: number) => Promise<void>;
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>>;
+ getScores: (gatewayIds: string[]) => Promise<Map<string, TGatewayScore>>;
getSuspect: (gatewayIds: string[]) => Promise<Set<string>>;
shutdown: () => void;
};
let tracker: TGatewayLoadTracker | undefined;
+// A gateway's own count is authoritative: it is taken at the one place every channel must pass
+// through, so it sees work the platform never proxied (a PAM CLI session dials the relay itself) and
+// any future caller too. The per-pod counters below only cover platform-initiated channels and exist
+// as a fallback for gateways too old to report.
+const REPORTED_LOAD_TTL_SECONDS = 60;
+const REPORTED_LOAD_MAX_AGE_MS = 35_000;
+
const loadKey = KeyStorePrefixes.GatewayLoad;
+const reportedKey = KeyStorePrefixes.GatewayReportedLoad;
const reservationKey = KeyStorePrefixes.GatewayLoadReservation;
const suspectKey = KeyStorePrefixes.GatewaySuspect;
@@ -42,9 +59,12 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
const openChannels = new Map<string, number>();
const pendingPublish = new Set<string>();
const reservationTimers = new Set<NodeJS.Timeout>();
+ const pendingReservations = new Map<string, NodeJS.Timeout[]>();
let debounceTimer: NodeJS.Timeout | undefined;
- const publish = async (gatewayId: string) => {
+ const publishChain = new Map<string, Promise<void>>();
+
+ const publishNow = 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
@@ -60,6 +80,15 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
}
};
+ // Overlapping flushes must not interleave, or a hashSet for count 1 can land after the hashDelete
+ // for count 0 and leave this pod's field claiming load it does not hold.
+ const publish = (gatewayId: string) => {
+ const prev = publishChain.get(gatewayId) ?? Promise.resolve();
+ const next = prev.then(() => publishNow(gatewayId));
+ publishChain.set(gatewayId, next);
+ return next;
+ };
+
const flushPending = () => {
const ids = [...pendingPublish];
pendingPublish.clear();
@@ -84,8 +113,33 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
}, PUBLISH_REFRESH_MS);
refreshTimer.unref();
+ const recordReportedLoad = async (gatewayId: string, activeChannels: number) => {
+ await keyStore.setItemWithExpiry(
+ reportedKey(gatewayId),
+ REPORTED_LOAD_TTL_SECONDS,
+ `${activeChannels}:${Date.now()}`
+ );
+ };
+
+ 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 channelOpened = (gatewayId: string) => {
openChannels.set(gatewayId, (openChannels.get(gatewayId) ?? 0) + 1);
+ // 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.
+ const pending = pendingReservations.get(gatewayId);
+ const timer = pending?.shift();
+ if (timer) {
+ clearTimeout(timer);
+ reservationTimers.delete(timer);
+ void releaseReservation(gatewayId);
+ }
schedulePublish(gatewayId);
};
@@ -99,14 +153,6 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
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);
@@ -117,10 +163,16 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
// The key TTL is only a backstop for a pod that dies holding reservations.
const timer = setTimeout(() => {
reservationTimers.delete(timer);
+ const queue = pendingReservations.get(gatewayId);
+ const idx = queue?.indexOf(timer) ?? -1;
+ if (queue && idx >= 0) queue.splice(idx, 1);
void releaseReservation(gatewayId);
}, RESERVATION_HOLD_MS);
timer.unref();
reservationTimers.add(timer);
+ const queue = pendingReservations.get(gatewayId);
+ if (queue) queue.push(timer);
+ else pendingReservations.set(gatewayId, [timer]);
};
const markSuspect = async (gatewayId: string) => {
@@ -137,33 +189,50 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
};
const getScores = async (gatewayIds: string[]) => {
- const scores = new Map<string, number>();
+ const scores = new Map<string, TGatewayScore>();
if (gatewayIds.length === 0) return scores;
- const [published, reservations] = await Promise.all([
+ const [published, reservations, reported] = await Promise.all([
Promise.all(gatewayIds.map((id) => keyStore.hashGetAll(loadKey(id)))),
- keyStore.getItemsPrimary(gatewayIds.map((id) => reservationKey(id)))
+ keyStore.getItemsPrimary(gatewayIds.map((id) => reservationKey(id))),
+ keyStore.getItemsPrimary(gatewayIds.map((id) => reportedKey(id)))
]);
- const cutoff = Date.now() - PUBLISHED_COUNT_MAX_AGE_MS;
+ const now = Date.now();
+ const publishedCutoff = now - PUBLISHED_COUNT_MAX_AGE_MS;
+ const reportedCutoff = now - REPORTED_LOAD_MAX_AGE_MS;
+
+ const parseStamped = (raw: string | null, cutoff: number) => {
+ if (!raw) return undefined;
+ const [countStr, tsStr] = raw.split(":");
+ const count = Number(countStr);
+ const at = Number(tsStr);
+ if (!Number.isFinite(count) || !Number.isFinite(at) || at < cutoff) return undefined;
+ return count;
+ };
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;
+ // Never sum the two views: the gateway's own count already includes the channels this pod
+ // opened, so adding the per-pod counters would double count platform traffic.
+ const reportedOccupancy = parseStamped(reported[idx], reportedCutoff);
+ let occupancy = reportedOccupancy;
+
+ if (occupancy === undefined) {
+ const fields = Object.entries(published[idx] ?? {})
+ // This pod's in-memory count is always fresher than what it last published.
+ .filter(([fieldPodId]) => fieldPodId !== podId);
+
+ occupancy = 0;
+ for (const [, raw] of fields) {
+ occupancy += parseStamped(raw, publishedCutoff) ?? 0;
}
+ occupancy += openChannels.get(gatewayId) ?? 0;
}
- total += openChannels.get(gatewayId) ?? 0;
- total += Number(reservations[idx] ?? 0) || 0;
- scores.set(gatewayId, total);
+
+ scores.set(gatewayId, {
+ score: occupancy + (Number(reservations[idx] ?? 0) || 0),
+ reported: reportedOccupancy !== undefined
+ });
});
return scores;
@@ -183,10 +252,12 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
clearInterval(refreshTimer);
if (debounceTimer) clearTimeout(debounceTimer);
for (const timer of reservationTimers) clearTimeout(timer);
+ pendingReservations.clear();
reservationTimers.clear();
};
tracker = {
+ recordReportedLoad,
reserve,
channelOpened,
channelClosed,
diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.ts
index cba0c1e0f8..1647dd2779 100644
--- a/backend/src/lib/gateway-v2/gateway-v2.ts
+++ b/backend/src/lib/gateway-v2/gateway-v2.ts
@@ -12,7 +12,7 @@ import { getConfig } from "../config/env";
import { BadRequestError, GatewayTransportError } from "../errors";
import { GatewayProxyProtocol } from "../gateway/types";
import { logger } from "../logger";
-import { markAttemptTransportFailure } from "./gateway-attempt-context";
+import { markAttemptTransportFailure, markAttemptTunnelEstablished } from "./gateway-attempt-context";
import { getGatewayLoadTracker } from "./gateway-load-tracker";
interface IGatewayRelayServer {
@@ -200,6 +200,7 @@ export const setupRelayServer = async ({
}
establishedChannel = true;
+ markAttemptTunnelEstablished();
if (longLived) {
// Disable the 30s idle-activity timeout that was set during connection establishment.
@@ -312,15 +313,27 @@ export const withGatewayV2Proxy = async <T>(
): Promise<T> => {
const { gatewayId, protocol, relayHost, gateway, relay, httpsAgent, longLived } = options;
- const { port, cleanup, getRelayError, hasEstablishedChannel } = await setupRelayServer({
- gatewayId,
- protocol,
- relayHost,
- gateway,
- relay,
- httpsAgent,
- longLived
- });
+ let relayServer;
+ try {
+ relayServer = await setupRelayServer({
+ gatewayId,
+ protocol,
+ relayHost,
+ gateway,
+ relay,
+ httpsAgent,
+ longLived
+ });
+ } catch (err) {
+ // The local listener never came up, so no tunnel was attempted and nothing reached the target.
+ markAttemptTransportFailure();
+ throw new GatewayTransportError({
+ message: err instanceof Error ? err.message : String(err),
+ gatewayId
+ });
+ }
+
+ const { port, cleanup, getRelayError, hasEstablishedChannel } = relayServer;
try {
// Execute the callback with the allocated port
diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts
index a591f3ed0e..3b94b4ab57 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,
- "pickHealthyGateway" | "resolveAttachableGatewayFromPool" | "resolveEffectiveGatewayId" | "runWithPoolFailover"
+ "resolveAttachableGatewayFromPool" | "resolveEffectiveGatewayId" | "runWithPoolFailover"
>;
gatewayDAL: Pick<TGatewayDALFactory, "find">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;
@@ -614,7 +614,7 @@ export const appConnectionServiceFactory = ({
// Validation only dials the target and reads back, so retrying it on another member is safe.
let validationGatewayId: string | null | undefined = gatewayId;
- let validatedCredentials;
+ let validatedCredentials: Awaited<ReturnType<typeof runValidation>>;
if (gatewayPoolId) {
const outcome = await gatewayPoolService.runWithPoolFailover({ poolId: gatewayPoolId }, runValidation);
validatedCredentials = outcome.result;