Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 9 additions & 21 deletions infra/relay/src/environments/ManagedEndpointAllocations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,14 @@ export const make = Effect.gen(function* () {
createdAt: now,
updatedAt: now,
})
.onConflictDoNothing()
// Re-reserving refreshes updatedAt, which keeps a pending row inside the tunnel limit's pending window.
.onConflictDoUpdate({
target: [
relayManagedEndpointAllocations.userId,
relayManagedEndpointAllocations.environmentId,
],
set: { updatedAt: now },
})
.returning(allocationSelection)
.pipe(
Effect.mapError(
Expand All @@ -273,26 +280,7 @@ export const make = Effect.gen(function* () {
),
);

const allocation =
inserted[0] ??
(yield* db
.select(allocationSelection)
.from(relayManagedEndpointAllocations)
.where(whereAllocation(input))
.limit(1)
.pipe(
Effect.map((rows) => rows[0]),
Effect.mapError(
(cause) =>
new ManagedEndpointAllocationPersistenceError({
operation: "reserve",
stage: "database-request",
...input,
cause,
}),
),
));

const allocation = inserted[0];
if (allocation === undefined) {
return yield* new ManagedEndpointAllocationPersistenceError({
operation: "reserve",
Expand Down
9 changes: 6 additions & 3 deletions infra/relay/src/environments/ManagedEndpointProvider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,10 +341,13 @@ function makeTunnelLimits(
result: ManagedTunnelLimits.ManagedTunnelLimitExceeded | null = null,
) {
return ManagedTunnelLimits.ManagedTunnelLimits.of({
ensureCapacity: (input) =>
Effect.suspend(() => {
withCapacity: (input, reserve) =>
Effect.gen(function* () {
calls.push(input);
return result === null ? Effect.void : Effect.fail(result);
if (result !== null) {
return yield* result;
}
return yield* reserve;
}),
});
}
Expand Down
42 changes: 21 additions & 21 deletions infra/relay/src/environments/ManagedEndpointProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1169,27 +1169,7 @@ export const make = Effect.gen(function* () {
environmentHash,
);
const requestedTunnelName = managedEndpointTunnelName(cf.namespace, environmentHash);
yield* tunnelLimits
.ensureCapacity({
userId: input.userId,
environmentId: input.environmentId,
})
.pipe(
Effect.catchTags({
ManagedTunnelLimitPersistenceError: (cause) =>
Effect.fail(
new ManagedEndpointProvisioningFailed({
userId: input.userId,
environmentId: input.environmentId,
stage: "check-tunnel-limit",
hostname: requestedHostname,
tunnelName: requestedTunnelName,
cause,
}),
),
}),
);
const allocation = yield* allocations
const reserveAllocation = allocations
.reserve({
userId: input.userId,
environmentId: input.environmentId,
Expand All @@ -1209,6 +1189,26 @@ export const make = Effect.gen(function* () {
}),
),
);
const allocation = yield* tunnelLimits
.withCapacity(
{ userId: input.userId, environmentId: input.environmentId },
reserveAllocation,
)
.pipe(
Effect.catchTags({
ManagedTunnelLimitPersistenceError: (cause) =>
Effect.fail(
new ManagedEndpointProvisioningFailed({
userId: input.userId,
environmentId: input.environmentId,
stage: "check-tunnel-limit",
hostname: requestedHostname,
tunnelName: requestedTunnelName,
cause,
}),
),
}),
);
const { hostname, tunnelName } = allocation;

if (input.reuseReadyTunnel === true) {
Expand Down
129 changes: 129 additions & 0 deletions infra/relay/src/environments/ManagedTunnelLimits.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import { describe, expect, it } from "@effect/vitest";
import { PgDialect } from "drizzle-orm/pg-core";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Semaphore from "effect/Semaphore";
import * as TestClock from "effect/testing/TestClock";

import * as RelayDb from "../db.ts";
import { relayManagedEndpointAllocations } from "../persistence/schema.ts";
import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts";

class FakeTransaction extends Context.Service<FakeTransaction, { holdsLock: boolean }>()(
"t3code-relay/environments/ManagedTunnelLimits.test/FakeTransaction",
) {}

// Models Postgres just enough: the advisory lock only works inside a transaction and is held until it ends.
function makeFakeDb(
reserved: Array<{ readonly userId: string; readonly environmentId: string }>,
countConditions: Array<unknown> = [],
) {
const userLock = Semaphore.makeUnsafe(1);
return {
$client: {
withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) => {
const transaction = { holdsLock: false };
return effect.pipe(
Effect.provideService(FakeTransaction, transaction),
Effect.ensuring(
Effect.suspend(() => (transaction.holdsLock ? userLock.release(1) : Effect.void)),
),
);
},
},
execute: () =>
Effect.gen(function* () {
const transaction = yield* Effect.serviceOption(FakeTransaction);
if (transaction._tag === "None") {
return yield* Effect.die("advisory lock taken outside a transaction");
}
yield* userLock.take(1);
transaction.value.holdsLock = true;
return [];
}),
select: () => ({
from: (table: unknown) => ({
where: (condition: unknown) =>
table === relayManagedEndpointAllocations
? Effect.yieldNow.pipe(
Effect.tap(() => Effect.sync(() => countConditions.push(condition))),
Effect.as([
{ activeTunnels: reserved.filter((row) => row.userId === "user-1").length },
]),
)
: { limit: () => Effect.succeed([]) },
}),
}),
} as unknown as RelayDb.RelayDb["Service"];
}

describe("ManagedTunnelLimits", () => {
it.effect("rejects concurrent reservations past the limit", () => {
const reserved: Array<{ readonly userId: string; readonly environmentId: string }> = [];
const attempts = ManagedTunnelLimits.DEFAULT_MANAGED_TUNNEL_LIMIT + 2;

return Effect.gen(function* () {
const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits;
const results = yield* Effect.forEach(
Array.from({ length: attempts }, (_, index) => `environment-${index}`),
(environmentId) => {
const input = { userId: "user-1", environmentId };
return limits
.withCapacity(
input,
Effect.sync(() => reserved.push(input)),
)
.pipe(Effect.result);
},
{ concurrency: "unbounded" },
);

expect(reserved).toHaveLength(ManagedTunnelLimits.DEFAULT_MANAGED_TUNNEL_LIMIT);
expect(
results.filter(
(result) =>
result._tag === "Failure" && result.failure._tag === "ManagedTunnelLimitExceeded",
),
).toHaveLength(2);
}).pipe(
Effect.provide(
ManagedTunnelLimits.layer.pipe(
Layer.provide(Layer.succeed(RelayDb.RelayDb, makeFakeDb(reserved))),
),
),
);
});

it.effect(
"counts reservations only within the pending window unless they hold a live tunnel",
() => {
const countConditions: Array<unknown> = [];
const now = DateTime.makeUnsafe("2026-10-27T12:00:00.000Z");

return Effect.gen(function* () {
yield* TestClock.setTime(now.epochMilliseconds);
const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits;
yield* limits.withCapacity(
{ userId: "user-1", environmentId: "environment-1" },
Effect.void,
);

const query = new PgDialect().sqlToQuery(countConditions[0] as never);
const sqlText = query.sql.replaceAll(/[()]/g, "");
expect(sqlText).toContain(
'"relay_managed_endpoint_allocations"."updated_at" > $3 or "relay_managed_endpoint_allocations"."tunnel_id" is not null and "relay_managed_endpoint_allocations"."tunnel_released_at" is null and not exists',
);
expect(query.params[2]).toBe("2026-10-27T11:45:00.000Z");
expect(sqlText).toContain('"relay_environment_links"."revoked_at" is not null');
}).pipe(
Effect.provide(
ManagedTunnelLimits.layer.pipe(
Layer.provide(Layer.succeed(RelayDb.RelayDb, makeFakeDb([], countConditions))),
),
),
);
},
);
});
Loading
Loading