fix(relay): clean up managed endpoints on unlink

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-04 14:03:01 -07:00
1 parent a7b8af3604
commit aaf881ac96
7 files changed
+338 -30

No files matched your search

+14 -14
View File
@@ -624,7 +624,7 @@ describe("web cloud link environment client", () => {
}),
);
it.effect("revokes the primary cloud link before clearing local relay credentials", () =>
it.effect("clears local relay credentials before revoking the primary cloud link", () =>
Effect.gen(function* () {
vi.mocked(readPrimaryEnvironmentDescriptor).mockReturnValue({
environmentId: EnvironmentId.make("env-1"),
@@ -642,10 +642,10 @@ describe("web cloud link environment client", () => {
});
const fetchMock = vi
.fn()
.mockResolvedValueOnce(Response.json({ ok: true }))
.mockResolvedValueOnce(
Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }),
);
)
.mockResolvedValueOnce(Response.json({ ok: true }));
vi.stubGlobal("fetch", fetchMock);
yield* withCloudServices(
@@ -654,16 +654,16 @@ describe("web cloud link environment client", () => {
}),
);
expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
"https://relay.example.test/v1/client/environment-links/env-1",
);
expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("DELETE");
expect(fetchMock.mock.calls[0]?.[1]?.headers.authorization).toBe("Bearer clerk-token");
expect(String(fetchMock.mock.calls[1]?.[0])).toBe("http://127.0.0.1:3000/api/cloud/unlink");
expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({
expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/cloud/unlink");
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
method: "POST",
credentials: "include",
});
expect(String(fetchMock.mock.calls[1]?.[0])).toBe(
"https://relay.example.test/v1/client/environment-links/env-1",
);
expect(fetchMock.mock.calls[1]?.[1]?.method).toBe("DELETE");
expect(fetchMock.mock.calls[1]?.[1]?.headers.authorization).toBe("Bearer clerk-token");
}),
);
@@ -685,10 +685,10 @@ describe("web cloud link environment client", () => {
});
const fetchMock = vi
.fn()
.mockResolvedValueOnce(Response.json({ error: "unavailable" }, { status: 503 }))
.mockResolvedValueOnce(
Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }),
);
)
.mockResolvedValueOnce(Response.json({ error: "unavailable" }, { status: 503 }));
vi.stubGlobal("fetch", fetchMock);
yield* withCloudServices(
@@ -698,8 +698,8 @@ describe("web cloud link environment client", () => {
);
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(String(fetchMock.mock.calls[1]?.[0])).toBe("http://127.0.0.1:3000/api/cloud/unlink");
expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({
expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/cloud/unlink");
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
method: "POST",
credentials: "include",
});
+9 -9
View File
@@ -487,6 +487,14 @@ export function unlinkPrimaryEnvironmentFromCloud(input: {
message: "Local environment is not ready yet.",
});
}
const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/"));
yield* client.cloud
.unlink({ headers: {} })
.pipe(
withPrimaryEnvironmentRequestInit,
Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")),
);
const configuredRelayUrl = relayUrl();
if (configuredRelayUrl && input.clerkToken) {
const relayClient = yield* ManagedRelayClient;
@@ -497,20 +505,12 @@ export function unlinkPrimaryEnvironmentFromCloud(input: {
})
.pipe(
Effect.catch((cause) =>
Effect.logWarning("Could not revoke cloud environment link before local unlink.", {
Effect.logWarning("Could not revoke cloud environment link after local unlink.", {
cause,
}),
),
);
}
const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/"));
yield* client.cloud
.unlink({ headers: {} })
.pipe(
withPrimaryEnvironmentRequestInit,
Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")),
);
});
}
@@ -133,6 +133,7 @@ function testLayer(input?: {
revokeForEnvironmentPublicKey: () => Effect.succeed(false),
}),
Layer.succeed(ManagedEndpointProvider.ManagedEndpointProvider, {
deprovision: () => Effect.void,
provision: () =>
Effect.succeed({
endpoint: {
@@ -43,6 +43,9 @@ interface RecordManagedEndpointDnsInput extends ManagedEndpointAllocationKey {
}
export interface ManagedEndpointAllocationsShape {
readonly get: (
input: ManagedEndpointAllocationKey,
) => Effect.Effect<ManagedEndpointAllocation | null, ManagedEndpointAllocationPersistenceError>;
readonly reserve: (
input: ReserveManagedEndpointAllocationInput,
) => Effect.Effect<ManagedEndpointAllocation, ManagedEndpointAllocationPersistenceError>;
@@ -55,6 +58,9 @@ export interface ManagedEndpointAllocationsShape {
readonly markReady: (
input: ManagedEndpointAllocationKey,
) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
readonly remove: (
input: ManagedEndpointAllocationKey,
) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
}
const allocationSelection = {
@@ -82,6 +88,19 @@ const make = Effect.gen(function* () {
const db = yield* RelayDb;
return ManagedEndpointAllocations.of({
get: Effect.fn("relay.managed_endpoint_allocations.get")(function* (
input: ManagedEndpointAllocationKey,
) {
return yield* db
.select(allocationSelection)
.from(relayManagedEndpointAllocations)
.where(whereAllocation(input))
.limit(1)
.pipe(
Effect.map((rows) => rows[0] ?? null),
Effect.mapError(persistenceError),
);
}),
reserve: Effect.fn("relay.managed_endpoint_allocations.reserve")(function* (
input: ReserveManagedEndpointAllocationInput,
) {
@@ -147,6 +166,11 @@ const make = Effect.gen(function* () {
})
.where(whereAllocation(input));
}, Effect.mapError(persistenceError)),
remove: Effect.fn("relay.managed_endpoint_allocations.remove")(function* (
input: ManagedEndpointAllocationKey,
) {
yield* db.delete(relayManagedEndpointAllocations).where(whereAllocation(input));
}, Effect.mapError(persistenceError)),
});
});
@@ -30,7 +30,7 @@ const config = RelayConfiguration.RelayConfiguration.of({
});
interface TunnelCall {
readonly operation: "list" | "create" | "putConfiguration" | "getToken";
readonly operation: "list" | "create" | "putConfiguration" | "getToken" | "delete";
readonly input: unknown;
}
@@ -40,7 +40,7 @@ interface DnsCall {
}
interface AllocationCall {
readonly operation: "reserve" | "recordTunnel" | "recordDns" | "markReady";
readonly operation: "get" | "reserve" | "recordTunnel" | "recordDns" | "markReady" | "remove";
readonly input: unknown;
}
@@ -69,6 +69,10 @@ function makeTunnelClient(calls: TunnelCall[] = []) {
calls.push({ operation: "getToken", input: tunnelId });
return "connector-token";
}),
delete: (tunnelId) =>
Effect.sync(() => {
calls.push({ operation: "delete", input: tunnelId });
}),
});
}
@@ -95,6 +99,11 @@ function makePersistentTunnelClient(calls: TunnelCall[] = []) {
calls.push({ operation: "getToken", input: tunnelId });
return "connector-token";
}),
delete: (tunnelId) =>
Effect.sync(() => {
calls.push({ operation: "delete", input: tunnelId });
tunnel = null;
}),
});
}
@@ -117,8 +126,13 @@ function makeDnsClient(
return record;
}),
updateRecord: (dnsRecordId, request) =>
Effect.sync(() => {
Effect.gen(function* () {
calls.push({ operation: "updateRecord", input: { dnsRecordId, request } });
if (!currentRecords.some((record) => record.id === dnsRecordId)) {
return yield* new ManagedEndpointProvider.ManagedEndpointDnsClientError({
cause: `DNS record ${dnsRecordId} does not exist.`,
});
}
}),
deleteRecord: (dnsRecordId) =>
Effect.sync(() => {
@@ -131,6 +145,11 @@ function makeDnsClient(
function makeAllocations(calls: AllocationCall[] = []) {
const allocations = new Map<string, ManagedEndpointAllocations.ManagedEndpointAllocation>();
return ManagedEndpointAllocations.ManagedEndpointAllocations.of({
get: (input) =>
Effect.sync(() => {
calls.push({ operation: "get", input });
return allocations.get(allocationKey(input)) ?? null;
}),
reserve: (input) =>
Effect.sync(() => {
calls.push({ operation: "reserve", input });
@@ -170,6 +189,11 @@ function makeAllocations(calls: AllocationCall[] = []) {
});
}
}),
remove: (input) =>
Effect.sync(() => {
calls.push({ operation: "remove", input });
allocations.delete(allocationKey(input));
}),
});
}
@@ -451,7 +475,6 @@ describe("ManagedEndpointProvider", () => {
expect(dnsCalls.map((call) => call.operation)).toEqual([
"listRecords",
"createRecord",
"listRecords",
"updateRecord",
]);
expect(allocationCalls.map((call) => call.operation)).toEqual([
@@ -467,6 +490,178 @@ describe("ManagedEndpointProvider", () => {
}).pipe(Effect.provide(layer));
});
it.effect("recreates a checkpointed DNS record when it was removed externally", () => {
const dnsCalls: DnsCall[] = [];
const allocationCalls: AllocationCall[] = [];
const dnsClient = makeDnsClient(dnsCalls);
const layer = providerLayer(
makePersistentTunnelClient(),
dnsClient,
makeAllocations(allocationCalls),
);
return Effect.gen(function* () {
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
const request = {
userId: "user_ABC",
environmentId: "env_ABC",
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
} as const;
yield* provider.provision(request);
yield* dnsClient.deleteRecord("created-record-id");
yield* provider.provision(request);
expect(dnsCalls.map((call) => call.operation)).toEqual([
"listRecords",
"createRecord",
"deleteRecord",
"updateRecord",
"listRecords",
"createRecord",
]);
}).pipe(Effect.provide(layer));
});
it.effect(
"deprovisions checkpointed DNS and tunnel resources before removing the allocation",
() => {
const tunnelCalls: TunnelCall[] = [];
const dnsCalls: DnsCall[] = [];
const allocationCalls: AllocationCall[] = [];
const layer = providerLayer(
makePersistentTunnelClient(tunnelCalls),
makeDnsClient(dnsCalls),
makeAllocations(allocationCalls),
);
return Effect.gen(function* () {
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
yield* provider.provision({
...key,
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
});
yield* provider.deprovision(key);
expect(dnsCalls.map((call) => call.operation)).toEqual([
"listRecords",
"createRecord",
"deleteRecord",
]);
expect(tunnelCalls.map((call) => call.operation)).toEqual([
"list",
"create",
"putConfiguration",
"getToken",
"delete",
]);
expect(allocationCalls.map((call) => call.operation)).toEqual([
"reserve",
"recordTunnel",
"recordDns",
"markReady",
"get",
"remove",
]);
}).pipe(Effect.provide(layer));
},
);
it.effect("treats an absent allocation as already deprovisioned", () => {
const tunnelCalls: TunnelCall[] = [];
const dnsCalls: DnsCall[] = [];
const allocationCalls: AllocationCall[] = [];
const layer = providerLayer(
makePersistentTunnelClient(tunnelCalls),
makeDnsClient(dnsCalls),
makeAllocations(allocationCalls),
);
return Effect.gen(function* () {
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
yield* provider.deprovision(key);
expect(tunnelCalls).toEqual([]);
expect(dnsCalls).toEqual([]);
expect(allocationCalls).toEqual([{ operation: "get", input: key }]);
}).pipe(Effect.provide(layer));
});
it.effect("keeps the allocation when tunnel cleanup fails so unlink can retry", () => {
const allocationCalls: AllocationCall[] = [];
const tunnelCalls: TunnelCall[] = [];
let deleteAttempts = 0;
const failure = new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
cause: "Cloudflare tunnel deletion failed",
});
const tunnels = makePersistentTunnelClient(tunnelCalls);
const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
...tunnels,
delete: (tunnelId) =>
Effect.gen(function* () {
tunnelCalls.push({ operation: "delete", input: tunnelId });
deleteAttempts++;
if (deleteAttempts === 1) {
return yield* failure;
}
}),
});
const layer = providerLayer(tunnelClient, makeDnsClient(), makeAllocations(allocationCalls));
return Effect.gen(function* () {
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
yield* provider.provision({
...key,
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
});
const first = yield* Effect.result(provider.deprovision(key));
expect(first._tag).toBe("Failure");
yield* provider.deprovision(key);
expect(allocationCalls.map((call) => call.operation)).toEqual([
"reserve",
"recordTunnel",
"recordDns",
"markReady",
"get",
"get",
"remove",
]);
}).pipe(Effect.provide(layer));
});
it.effect("treats already deleted remote resources as successfully deprovisioned", () => {
const allocationCalls: AllocationCall[] = [];
const notFound = { _tag: "NotFound" } as const;
const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
...makeTunnelClient(),
delete: () =>
Effect.fail(
new ManagedEndpointProvider.ManagedEndpointTunnelClientError({ cause: notFound }),
),
});
const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
...makeDnsClient(),
deleteRecord: () =>
Effect.fail(new ManagedEndpointProvider.ManagedEndpointDnsClientError({ cause: notFound })),
});
const layer = providerLayer(tunnelClient, dnsClient, makeAllocations(allocationCalls));
return Effect.gen(function* () {
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
yield* provider.provision({
...key,
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
});
yield* provider.deprovision(key);
expect(allocationCalls.map((call) => call.operation)).toContain("remove");
}).pipe(Effect.provide(layer));
});
it.effect("scopes managed endpoint resources by user", () => {
const tunnelCalls: TunnelCall[] = [];
@@ -34,6 +34,12 @@ export class ManagedEndpointProvisioningFailed extends Data.TaggedError(
readonly cause: unknown;
}> {}
export class ManagedEndpointDeprovisioningFailed extends Data.TaggedError(
"ManagedEndpointDeprovisioningFailed",
)<{
readonly cause: unknown;
}> {}
export class ManagedEndpointOriginNotAllowed extends Data.TaggedError(
"ManagedEndpointOriginNotAllowed",
)<{
@@ -57,6 +63,10 @@ export interface ManagedEndpointProviderShape {
readonly environmentId: string;
readonly origin: RelayManagedEndpointOrigin;
}) => Effect.Effect<ManagedEndpointProvisioningResult, ManagedEndpointProviderError>;
readonly deprovision: (input: {
readonly userId: string;
readonly environmentId: string;
}) => Effect.Effect<void, ManagedEndpointDeprovisioningFailed>;
}
export class ManagedEndpointProvider extends Context.Service<
@@ -97,6 +107,7 @@ export interface ManagedEndpointTunnelClientShape {
},
) => Effect.Effect<unknown, ManagedEndpointTunnelClientError>;
readonly getToken: (tunnelId: string) => Effect.Effect<string, ManagedEndpointTunnelClientError>;
readonly delete: (tunnelId: string) => Effect.Effect<unknown, ManagedEndpointTunnelClientError>;
}
export class ManagedEndpointTunnelClient extends Context.Service<
@@ -162,6 +173,7 @@ function normalizeHostname(hostname: string): string {
return hostname
.trim()
.toLowerCase()
.replace(/\.$/u, "")
.replace(/^\[(.*)\]$/u, "$1");
}
@@ -175,6 +187,25 @@ function isLoopbackOrigin(origin: RelayManagedEndpointOrigin): boolean {
);
}
function isNotFoundCause(cause: unknown): boolean {
if (typeof cause !== "object" || cause === null) {
return false;
}
if ("_tag" in cause && cause._tag === "NotFound") {
return true;
}
if ("status" in cause && cause.status === 404) {
return true;
}
return "cause" in cause && isNotFoundCause(cause.cause);
}
const ignoreNotFound = <A, E>(effect: Effect.Effect<A, E>): Effect.Effect<void, E> =>
effect.pipe(
Effect.asVoid,
Effect.catch((cause) => (isNotFoundCause(cause) ? Effect.void : Effect.fail(cause))),
);
const make = Effect.gen(function* () {
const config = yield* RelayConfiguration.RelayConfiguration;
const crypto = yield* Crypto.Crypto;
@@ -205,6 +236,17 @@ const make = Effect.gen(function* () {
preferredDnsRecordId: string | null,
dnsRecord: ManagedEndpointCnameRecordInput,
) {
if (preferredDnsRecordId !== null) {
const checkpointedRecordUpdated = yield* dns
.updateRecord(preferredDnsRecordId, dnsRecord)
.pipe(
Effect.as(true),
Effect.catch(() => Effect.succeed(false)),
);
if (checkpointedRecordUpdated) {
return preferredDnsRecordId;
}
}
const existingDnsRecords = yield* dns.listRecords(hostname);
const existingDnsRecordId = yield* updateExistingDnsRecords(
existingDnsRecords,
@@ -217,7 +259,14 @@ const make = Effect.gen(function* () {
return yield* dns.createRecord(dnsRecord).pipe(
Effect.map((record) => record.id),
Effect.catch((createError) =>
dns.listRecords(hostname).pipe(
Effect.gen(function* () {
let records = yield* dns.listRecords(hostname);
for (let attempt = 0; records.length === 0 && attempt < 4; attempt++) {
yield* Effect.sleep("200 millis");
records = yield* dns.listRecords(hostname);
}
return records;
}).pipe(
Effect.flatMap((records) =>
records.length > 0
? updateExistingDnsRecords(records, preferredDnsRecordId, dnsRecord)
@@ -232,6 +281,31 @@ const make = Effect.gen(function* () {
});
return ManagedEndpointProvider.of({
deprovision: Effect.fn("relay.managed_endpoint_provider.deprovision")(function* (input) {
yield* Effect.annotateCurrentSpan({
"relay.user_id": input.userId,
"relay.environment_id": input.environmentId,
});
const allocation = yield* allocations
.get(input)
.pipe(Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })));
if (allocation === null) {
return;
}
if (allocation.dnsRecordId !== null) {
yield* ignoreNotFound(dns.deleteRecord(allocation.dnsRecordId)).pipe(
Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })),
);
}
if (allocation.tunnelId !== null) {
yield* ignoreNotFound(tunnels.delete(allocation.tunnelId)).pipe(
Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })),
);
}
yield* allocations
.remove(input)
.pipe(Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })));
}),
provision: Effect.fn("relay.managed_endpoint_provider.provision")(function* (input) {
yield* Effect.annotateCurrentSpan({
"relay.user_id": input.userId,
@@ -382,17 +456,23 @@ export const layerCloudflareBindings = (
Effect.mapError((cause) => new ManagedEndpointTunnelClientError({ cause })),
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
),
delete: (tunnelId) =>
tunnelClient.delete(tunnelId).pipe(
Effect.mapError((cause) => new ManagedEndpointTunnelClientError({ cause })),
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
),
}),
),
Layer.succeed(
ManagedEndpointDnsClient,
ManagedEndpointDnsClient.of({
listRecords: (hostname) =>
dnsClient.listDnsRecords({ name: { exact: hostname } }).pipe(
dnsClient.listDnsRecords({ search: hostname }).pipe(
Effect.map((response) =>
response.result.filter(
(record): record is typeof record & { readonly id: string } =>
typeof record.id === "string",
typeof record.id === "string" &&
normalizeHostname(record.name) === normalizeHostname(hostname),
),
),
Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })),
+8
View File
@@ -60,6 +60,7 @@ import * as RelayConfiguration from "../Config.ts";
import * as AgentActivityPublisher from "../agentActivity/AgentActivityPublisher.ts";
import * as EnvironmentConnector from "../environments/EnvironmentConnector.ts";
import * as EnvironmentLinker from "../environments/EnvironmentLinker.ts";
import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts";
import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts";
import * as MobileRegistrations from "../agentActivity/MobileRegistrations.ts";
import { withSpanAttributes } from "../observability.ts";
@@ -410,6 +411,7 @@ export const clientApi = HttpApiBuilder.group(
const relayTokens = yield* RelayTokens.RelayTokens;
const linker = yield* EnvironmentLinker.EnvironmentLinker;
const links = yield* EnvironmentLinks.EnvironmentLinks;
const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
const devices = yield* Devices.Devices;
return handlers
@@ -526,6 +528,12 @@ export const clientApi = HttpApiBuilder.group(
Effect.fn("relay.api.client.unlinkEnvironment")(function* (args) {
const { params } = args;
const { userId } = yield* RelayClientPrincipal;
yield* managedEndpointProvider
.deprovision({
userId,
environmentId: params.environmentId,
})
.pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable")));
const link = yield* links.getForUser({
userId,
environmentId: params.environmentId,