fix(relay): reconcile managed endpoint provisioning

Persist per-user environment allocations and checkpoint Cloudflare resources so retries converge partial provisioning state.

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-03 23:48:06 -07:00
1 parent 5af1a917df
commit 0fb87aad6a
10 files changed
+2038 -55

No files matched your search

@@ -0,0 +1,15 @@
CREATE TABLE "relay_managed_endpoint_allocations" (
"user_id" varchar(191),
"environment_id" varchar(191),
"hostname" text NOT NULL,
"tunnel_id" varchar(191),
"tunnel_name" text NOT NULL,
"dns_record_id" varchar(191),
"ready_at" varchar(64),
"created_at" varchar(64) NOT NULL,
"updated_at" varchar(64) NOT NULL,
CONSTRAINT "relay_managed_endpoint_allocations_pkey" PRIMARY KEY("user_id","environment_id")
);
--> statement-breakpoint
CREATE UNIQUE INDEX "idx_relay_managed_endpoint_allocations_hostname" ON "relay_managed_endpoint_allocations" ("hostname");--> statement-breakpoint
CREATE UNIQUE INDEX "idx_relay_managed_endpoint_allocations_tunnel_name" ON "relay_managed_endpoint_allocations" ("tunnel_name");
+3 -1
View File
@@ -50,7 +50,9 @@ describe("managed endpoint names", () => {
it("uses the stage slug and a stable stage-scoped digest suffix", () => {
const hash = "ABCDEF0123456789ABCDEF0123456789";
expect(managedEndpointDigestInput("dev_julius", "env_123")).toBe("dev_julius:env_123");
expect(managedEndpointDigestInput("dev_julius", "user_123", "env_123")).toBe(
"dev_julius:user_123:env_123",
);
expect(managedEndpointHostname("dev_julius", ".example.com.", hash)).toBe(
"tunnels-dev-julius-abcdef0123456789.example.com",
);
+6 -2
View File
@@ -51,8 +51,12 @@ export function relayPublicDomainForStage(stage: string, zoneName: string): stri
return `${relayLabel}.${normalizeZoneName(zoneName)}`;
}
export function managedEndpointDigestInput(stage: string, environmentId: string): string {
return `${stage}:${environmentId}`;
export function managedEndpointDigestInput(
stage: string,
userId: string,
environmentId: string,
): string {
return `${stage}:${userId}:${environmentId}`;
}
export function managedEndpointHostname(stage: string, baseDomain: string, hash: string): string {
@@ -234,6 +234,7 @@ const make = Effect.gen(function* () {
}
const provisioned = input.request.managedTunnelsEnabled
? yield* managedEndpointProvider.provision({
userId: input.userId,
environmentId: verified.environmentId,
origin: verified.origin,
})
@@ -0,0 +1,158 @@
import { and, eq } from "drizzle-orm";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { RelayDb } from "../db.ts";
import { relayManagedEndpointAllocations } from "../persistence/schema.ts";
export interface ManagedEndpointAllocation {
readonly userId: string;
readonly environmentId: string;
readonly hostname: string;
readonly tunnelId: string | null;
readonly tunnelName: string;
readonly dnsRecordId: string | null;
readonly readyAt: string | null;
}
export class ManagedEndpointAllocationPersistenceError extends Data.TaggedError(
"ManagedEndpointAllocationPersistenceError",
)<{
readonly cause: unknown;
}> {}
interface ManagedEndpointAllocationKey {
readonly userId: string;
readonly environmentId: string;
}
interface ReserveManagedEndpointAllocationInput extends ManagedEndpointAllocationKey {
readonly hostname: string;
readonly tunnelName: string;
}
interface RecordManagedEndpointTunnelInput extends ManagedEndpointAllocationKey {
readonly tunnelId: string;
}
interface RecordManagedEndpointDnsInput extends ManagedEndpointAllocationKey {
readonly dnsRecordId: string;
}
export interface ManagedEndpointAllocationsShape {
readonly reserve: (
input: ReserveManagedEndpointAllocationInput,
) => Effect.Effect<ManagedEndpointAllocation, ManagedEndpointAllocationPersistenceError>;
readonly recordTunnel: (
input: RecordManagedEndpointTunnelInput,
) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
readonly recordDns: (
input: RecordManagedEndpointDnsInput,
) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
readonly markReady: (
input: ManagedEndpointAllocationKey,
) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
}
const allocationSelection = {
userId: relayManagedEndpointAllocations.userId,
environmentId: relayManagedEndpointAllocations.environmentId,
hostname: relayManagedEndpointAllocations.hostname,
tunnelId: relayManagedEndpointAllocations.tunnelId,
tunnelName: relayManagedEndpointAllocations.tunnelName,
dnsRecordId: relayManagedEndpointAllocations.dnsRecordId,
readyAt: relayManagedEndpointAllocations.readyAt,
};
const whereAllocation = (input: ManagedEndpointAllocationKey) =>
and(
eq(relayManagedEndpointAllocations.userId, input.userId),
eq(relayManagedEndpointAllocations.environmentId, input.environmentId),
);
const persistenceError = (cause: unknown) =>
cause instanceof ManagedEndpointAllocationPersistenceError
? cause
: new ManagedEndpointAllocationPersistenceError({ cause });
const make = Effect.gen(function* () {
const db = yield* RelayDb;
return ManagedEndpointAllocations.of({
reserve: Effect.fn("relay.managed_endpoint_allocations.reserve")(function* (
input: ReserveManagedEndpointAllocationInput,
) {
const now = DateTime.formatIso(yield* DateTime.now);
const inserted = yield* db
.insert(relayManagedEndpointAllocations)
.values({
...input,
createdAt: now,
updatedAt: now,
})
.onConflictDoNothing()
.returning(allocationSelection);
const allocation =
inserted[0] ??
(yield* db
.select(allocationSelection)
.from(relayManagedEndpointAllocations)
.where(whereAllocation(input))
.limit(1)
.pipe(Effect.map((rows) => rows[0])));
if (allocation === undefined) {
return yield* new ManagedEndpointAllocationPersistenceError({
cause: new Error("Managed endpoint allocation was not persisted."),
});
}
return allocation;
}, Effect.mapError(persistenceError)),
recordTunnel: Effect.fn("relay.managed_endpoint_allocations.record_tunnel")(function* (
input: RecordManagedEndpointTunnelInput,
) {
yield* db
.update(relayManagedEndpointAllocations)
.set({
tunnelId: input.tunnelId,
updatedAt: DateTime.formatIso(yield* DateTime.now),
})
.where(whereAllocation(input));
}, Effect.mapError(persistenceError)),
recordDns: Effect.fn("relay.managed_endpoint_allocations.record_dns")(function* (
input: RecordManagedEndpointDnsInput,
) {
yield* db
.update(relayManagedEndpointAllocations)
.set({
dnsRecordId: input.dnsRecordId,
updatedAt: DateTime.formatIso(yield* DateTime.now),
})
.where(whereAllocation(input));
}, Effect.mapError(persistenceError)),
markReady: Effect.fn("relay.managed_endpoint_allocations.mark_ready")(function* (
input: ManagedEndpointAllocationKey,
) {
const now = DateTime.formatIso(yield* DateTime.now);
yield* db
.update(relayManagedEndpointAllocations)
.set({
readyAt: now,
updatedAt: now,
})
.where(whereAllocation(input));
}, Effect.mapError(persistenceError)),
});
});
export class ManagedEndpointAllocations extends Context.Service<
ManagedEndpointAllocations,
ManagedEndpointAllocationsShape
>()("t3code-relay/environments/ManagedEndpointAllocations") {
static readonly layer = Layer.effect(this, make);
}
@@ -7,6 +7,7 @@ import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import * as RelayConfiguration from "../Config.ts";
import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
const config = RelayConfiguration.RelayConfiguration.of({
@@ -34,10 +35,19 @@ interface TunnelCall {
}
interface DnsCall {
readonly operation: "listCnameRecords" | "createCnameRecord" | "updateCnameRecord";
readonly operation: "listRecords" | "createRecord" | "updateRecord" | "deleteRecord";
readonly input: unknown;
}
interface AllocationCall {
readonly operation: "reserve" | "recordTunnel" | "recordDns" | "markReady";
readonly input: unknown;
}
function allocationKey(input: { readonly userId: string; readonly environmentId: string }) {
return `${input.userId}:${input.environmentId}`;
}
function makeTunnelClient(calls: TunnelCall[] = []) {
return ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
list: (request) =>
@@ -62,47 +72,134 @@ function makeTunnelClient(calls: TunnelCall[] = []) {
});
}
function makeDnsClient(
calls: DnsCall[] = [],
records: ReadonlyArray<{ readonly id: string }> = [],
) {
return ManagedEndpointProvider.ManagedEndpointDnsClient.of({
listCnameRecords: (hostname) =>
function makePersistentTunnelClient(calls: TunnelCall[] = []) {
let tunnel: { readonly id: string; readonly name: string } | null = null;
return ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
list: (request) =>
Effect.sync(() => {
calls.push({ operation: "listCnameRecords", input: hostname });
return records;
calls.push({ operation: "list", input: request });
return { result: tunnel === null ? [] : [tunnel] };
}),
createCnameRecord: (request) =>
create: (request) =>
Effect.sync(() => {
calls.push({ operation: "createCnameRecord", input: request });
calls.push({ operation: "create", input: request });
tunnel = { id: "tunnel-id", name: request.name };
return tunnel;
}),
updateCnameRecord: (dnsRecordId, request) =>
putConfiguration: (tunnelId, tunnelConfig) =>
Effect.sync(() => {
calls.push({ operation: "updateCnameRecord", input: { dnsRecordId, request } });
calls.push({ operation: "putConfiguration", input: { tunnelId, tunnelConfig } });
}),
getToken: (tunnelId) =>
Effect.sync(() => {
calls.push({ operation: "getToken", input: tunnelId });
return "connector-token";
}),
});
}
function providerLayer(tunnelClient = makeTunnelClient(), dnsClient = makeDnsClient()) {
function makeDnsClient(
calls: DnsCall[] = [],
records: ReadonlyArray<{ readonly id: string }> = [],
) {
let currentRecords = [...records];
return ManagedEndpointProvider.ManagedEndpointDnsClient.of({
listRecords: (hostname) =>
Effect.sync(() => {
calls.push({ operation: "listRecords", input: hostname });
return currentRecords;
}),
createRecord: (request) =>
Effect.sync(() => {
calls.push({ operation: "createRecord", input: request });
const record = { id: "created-record-id" };
currentRecords = [record];
return record;
}),
updateRecord: (dnsRecordId, request) =>
Effect.sync(() => {
calls.push({ operation: "updateRecord", input: { dnsRecordId, request } });
}),
deleteRecord: (dnsRecordId) =>
Effect.sync(() => {
calls.push({ operation: "deleteRecord", input: dnsRecordId });
currentRecords = currentRecords.filter((record) => record.id !== dnsRecordId);
}),
});
}
function makeAllocations(calls: AllocationCall[] = []) {
const allocations = new Map<string, ManagedEndpointAllocations.ManagedEndpointAllocation>();
return ManagedEndpointAllocations.ManagedEndpointAllocations.of({
reserve: (input) =>
Effect.sync(() => {
calls.push({ operation: "reserve", input });
const allocation = allocations.get(allocationKey(input)) ?? {
...input,
tunnelId: null,
dnsRecordId: null,
readyAt: null,
};
allocations.set(allocationKey(input), allocation);
return allocation;
}),
recordTunnel: (input) =>
Effect.sync(() => {
calls.push({ operation: "recordTunnel", input });
const allocation = allocations.get(allocationKey(input));
if (allocation !== undefined) {
allocations.set(allocationKey(input), { ...allocation, tunnelId: input.tunnelId });
}
}),
recordDns: (input) =>
Effect.sync(() => {
calls.push({ operation: "recordDns", input });
const allocation = allocations.get(allocationKey(input));
if (allocation !== undefined) {
allocations.set(allocationKey(input), { ...allocation, dnsRecordId: input.dnsRecordId });
}
}),
markReady: (input) =>
Effect.sync(() => {
calls.push({ operation: "markReady", input });
const allocation = allocations.get(allocationKey(input));
if (allocation !== undefined) {
allocations.set(allocationKey(input), {
...allocation,
readyAt: "2026-06-02T00:00:00.000Z",
});
}
}),
});
}
function providerLayer(
tunnelClient = makeTunnelClient(),
dnsClient = makeDnsClient(),
allocations = makeAllocations(),
) {
return ManagedEndpointProvider.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(Layer.succeed(RelayConfiguration.RelayConfiguration, config)),
Layer.provide(Layer.succeed(ManagedEndpointProvider.ManagedEndpointTunnelClient, tunnelClient)),
Layer.provide(Layer.succeed(ManagedEndpointProvider.ManagedEndpointDnsClient, dnsClient)),
Layer.provide(
Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, allocations),
),
);
}
function expectedManagedHostname(environmentId: string): string {
function expectedManagedHostname(environmentId: string, userId = "user_ABC"): string {
const hash = NodeCrypto.createHash("sha256")
.update(`dev_julius:${environmentId}`)
.update(`dev_julius:${userId}:${environmentId}`)
.digest("hex")
.slice(0, 16);
return `tunnels-dev-julius-${hash}.t3code.test`;
}
function expectedManagedTunnelName(environmentId: string): string {
function expectedManagedTunnelName(environmentId: string, userId = "user_ABC"): string {
const hash = NodeCrypto.createHash("sha256")
.update(`dev_julius:${environmentId}`)
.update(`dev_julius:${userId}:${environmentId}`)
.digest("hex")
.slice(0, 16);
return `t3coderelay-managedendpoint-dev-julius-${hash}`;
@@ -112,11 +209,13 @@ describe("ManagedEndpointProvider", () => {
it.effect("provisions a Cloudflare tunnel endpoint and connector token", () => {
const tunnelCalls: TunnelCall[] = [];
const dnsCalls: DnsCall[] = [];
const allocationCalls: AllocationCall[] = [];
return Effect.gen(function* () {
const hostname = expectedManagedHostname("env_ABC");
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
const result = yield* provider.provision({
userId: "user_ABC",
environmentId: "env_ABC",
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
});
@@ -135,9 +234,9 @@ describe("ManagedEndpointProvider", () => {
},
});
expect(dnsCalls).toEqual([
{ operation: "listCnameRecords", input: hostname },
{ operation: "listRecords", input: hostname },
{
operation: "createCnameRecord",
operation: "createRecord",
input: {
type: "CNAME",
name: hostname,
@@ -168,7 +267,21 @@ describe("ManagedEndpointProvider", () => {
name: expectedManagedTunnelName("env_ABC"),
isDeleted: false,
});
}).pipe(Effect.provide(providerLayer(makeTunnelClient(tunnelCalls), makeDnsClient(dnsCalls))));
expect(allocationCalls.map((call) => call.operation)).toEqual([
"reserve",
"recordTunnel",
"recordDns",
"markReady",
]);
}).pipe(
Effect.provide(
providerLayer(
makeTunnelClient(tunnelCalls),
makeDnsClient(dnsCalls),
makeAllocations(allocationCalls),
),
),
);
});
it.effect("uses stage-scoped stable names without leaking unusual environment ids", () => {
@@ -178,6 +291,7 @@ describe("ManagedEndpointProvider", () => {
const environmentId = "ENV With Spaces/../Symbols!" + "x".repeat(80);
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
yield* provider.provision({
userId: "user_ABC",
environmentId,
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
});
@@ -224,6 +338,7 @@ describe("ManagedEndpointProvider", () => {
return Effect.gen(function* () {
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
yield* provider.provision({
userId: "user_ABC",
environmentId: "env-ipv6",
origin: { localHttpHost: "::1", localHttpPort: 3773 },
});
@@ -250,6 +365,7 @@ describe("ManagedEndpointProvider", () => {
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
const result = yield* Effect.result(
provider.provision({
userId: "user_ABC",
environmentId: "env_ABC",
origin: { localHttpHost: "192.168.1.10", localHttpPort: 3773 },
}),
@@ -270,6 +386,7 @@ describe("ManagedEndpointProvider", () => {
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
const result = yield* Effect.result(
provider.provision({
userId: "user_ABC",
environmentId: "env_ABC",
origin: { localHttpHost: "127.0.0.1", localHttpPort: 65_536 },
}),
@@ -283,19 +400,17 @@ describe("ManagedEndpointProvider", () => {
}).pipe(Effect.provide(providerLayer(makeTunnelClient(), makeDnsClient(dnsCalls))));
});
it.effect("updates an existing CNAME record through the DNS client", () => {
it.effect("reconciles an existing same-host DNS record through the DNS client", () => {
const dnsCalls: DnsCall[] = [];
return Effect.gen(function* () {
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
yield* provider.provision({
userId: "user_ABC",
environmentId: "env_ABC",
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
});
expect(dnsCalls.map((call) => call.operation)).toEqual([
"listCnameRecords",
"updateCnameRecord",
]);
expect(dnsCalls.map((call) => call.operation)).toEqual(["listRecords", "updateRecord"]);
expect(dnsCalls[1]?.input).toMatchObject({ dnsRecordId: "existing-record-id" });
}).pipe(
Effect.provide(
@@ -304,20 +419,140 @@ describe("ManagedEndpointProvider", () => {
);
});
it.effect("reuses checkpointed resources when provisioning is retried", () => {
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 request = {
userId: "user_ABC",
environmentId: "env_ABC",
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
} as const;
yield* provider.provision(request);
yield* provider.provision(request);
expect(tunnelCalls.map((call) => call.operation)).toEqual([
"list",
"create",
"putConfiguration",
"getToken",
"list",
"putConfiguration",
"getToken",
]);
expect(dnsCalls.map((call) => call.operation)).toEqual([
"listRecords",
"createRecord",
"listRecords",
"updateRecord",
]);
expect(allocationCalls.map((call) => call.operation)).toEqual([
"reserve",
"recordTunnel",
"recordDns",
"markReady",
"reserve",
"recordTunnel",
"recordDns",
"markReady",
]);
}).pipe(Effect.provide(layer));
});
it.effect("scopes managed endpoint resources by user", () => {
const tunnelCalls: TunnelCall[] = [];
return Effect.gen(function* () {
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
yield* provider.provision({
userId: "user_ABC",
environmentId: "env_shared",
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
});
yield* provider.provision({
userId: "user_DEF",
environmentId: "env_shared",
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
});
expect(
tunnelCalls.filter((call) => call.operation === "list").map((call) => call.input),
).toEqual([
{ name: expectedManagedTunnelName("env_shared", "user_ABC"), isDeleted: false },
{ name: expectedManagedTunnelName("env_shared", "user_DEF"), isDeleted: false },
]);
}).pipe(Effect.provide(providerLayer(makeTunnelClient(tunnelCalls))));
});
it.effect("recovers when DNS creation reports failure after the record became visible", () => {
const dnsCalls: DnsCall[] = [];
const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({
cause: "ambiguous Cloudflare DNS response",
});
let records: ReadonlyArray<{ readonly id: string }> = [];
const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
listRecords: (hostname) =>
Effect.sync(() => {
dnsCalls.push({ operation: "listRecords", input: hostname });
return records;
}),
createRecord: (request) =>
Effect.gen(function* () {
dnsCalls.push({ operation: "createRecord", input: request });
records = [{ id: "created-record-id" }];
return yield* failure;
}),
updateRecord: (dnsRecordId, request) =>
Effect.sync(() => {
dnsCalls.push({ operation: "updateRecord", input: { dnsRecordId, request } });
}),
deleteRecord: (dnsRecordId) =>
Effect.sync(() => {
dnsCalls.push({ operation: "deleteRecord", input: dnsRecordId });
}),
});
return Effect.gen(function* () {
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
yield* provider.provision({
userId: "user_ABC",
environmentId: "env_ABC",
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
});
expect(dnsCalls.map((call) => call.operation)).toEqual([
"listRecords",
"createRecord",
"listRecords",
"updateRecord",
]);
}).pipe(Effect.provide(providerLayer(makeTunnelClient(), dnsClient)));
});
it.effect("fails provisioning when the DNS client fails", () => {
const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({
cause: "Cloudflare DNS failure",
});
const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
listCnameRecords: () => Effect.fail(failure),
createCnameRecord: () => Effect.die("unused"),
updateCnameRecord: () => Effect.die("unused"),
listRecords: () => Effect.fail(failure),
createRecord: () => Effect.die("unused"),
updateRecord: () => Effect.die("unused"),
deleteRecord: () => Effect.die("unused"),
});
return Effect.gen(function* () {
const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
const error = yield* Effect.flip(
provider.provision({
userId: "user_ABC",
environmentId: "env_ABC",
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
}),
@@ -22,6 +22,7 @@ import {
managedEndpointHostname,
managedEndpointTunnelName,
} from "../deploymentConfig.ts";
import { ManagedEndpointAllocations } from "./ManagedEndpointAllocations.ts";
export class ManagedEndpointProvisioningNotConfigured extends Data.TaggedError(
"ManagedEndpointProvisioningNotConfigured",
@@ -52,6 +53,7 @@ export interface ManagedEndpointProvisioningResult {
export interface ManagedEndpointProviderShape {
readonly provision: (input: {
readonly userId: string;
readonly environmentId: string;
readonly origin: RelayManagedEndpointOrigin;
}) => Effect.Effect<ManagedEndpointProvisioningResult, ManagedEndpointProviderError>;
@@ -117,16 +119,19 @@ export class ManagedEndpointDnsClientError extends Data.TaggedError(
}> {}
export interface ManagedEndpointDnsClientShape {
readonly listCnameRecords: (
readonly listRecords: (
hostname: string,
) => Effect.Effect<ReadonlyArray<{ readonly id: string }>, ManagedEndpointDnsClientError>;
readonly createCnameRecord: (
readonly createRecord: (
request: ManagedEndpointCnameRecordInput,
) => Effect.Effect<unknown, ManagedEndpointDnsClientError>;
readonly updateCnameRecord: (
) => Effect.Effect<{ readonly id: string }, ManagedEndpointDnsClientError>;
readonly updateRecord: (
dnsRecordId: string,
request: ManagedEndpointCnameRecordInput,
) => Effect.Effect<unknown, ManagedEndpointDnsClientError>;
readonly deleteRecord: (
dnsRecordId: string,
) => Effect.Effect<unknown, ManagedEndpointDnsClientError>;
}
export class ManagedEndpointDnsClient extends Context.Service<
@@ -175,10 +180,61 @@ const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const tunnels = yield* ManagedEndpointTunnelClient;
const dns = yield* ManagedEndpointDnsClient;
const allocations = yield* ManagedEndpointAllocations;
const updateExistingDnsRecords = Effect.fnUntraced(function* (
records: ReadonlyArray<{ readonly id: string }>,
preferredDnsRecordId: string | null,
dnsRecord: ManagedEndpointCnameRecordInput,
) {
const keptRecord = records.find((record) => record.id === preferredDnsRecordId) ?? records[0];
if (keptRecord === undefined) {
return null;
}
yield* Effect.forEach(
records,
(record) => (record.id === keptRecord.id ? Effect.void : dns.deleteRecord(record.id)),
{ discard: true },
);
yield* dns.updateRecord(keptRecord.id, dnsRecord);
return keptRecord.id;
});
const ensureDnsRecord = Effect.fnUntraced(function* (
hostname: string,
preferredDnsRecordId: string | null,
dnsRecord: ManagedEndpointCnameRecordInput,
) {
const existingDnsRecords = yield* dns.listRecords(hostname);
const existingDnsRecordId = yield* updateExistingDnsRecords(
existingDnsRecords,
preferredDnsRecordId,
dnsRecord,
);
if (existingDnsRecordId !== null) {
return existingDnsRecordId;
}
return yield* dns.createRecord(dnsRecord).pipe(
Effect.map((record) => record.id),
Effect.catch((createError) =>
dns.listRecords(hostname).pipe(
Effect.flatMap((records) =>
records.length > 0
? updateExistingDnsRecords(records, preferredDnsRecordId, dnsRecord)
: Effect.fail(createError),
),
Effect.flatMap((dnsRecordId) =>
dnsRecordId === null ? Effect.fail(createError) : Effect.succeed(dnsRecordId),
),
),
),
);
});
return ManagedEndpointProvider.of({
provision: Effect.fn("relay.managed_endpoint_provider.provision")(function* (input) {
yield* Effect.annotateCurrentSpan({
"relay.user_id": input.userId,
"relay.environment_id": input.environmentId,
"relay.managed_endpoint.origin_host": input.origin.localHttpHost,
"relay.managed_endpoint.origin_port": input.origin.localHttpPort,
@@ -193,14 +249,23 @@ const make = Effect.gen(function* () {
const environmentHash = yield* crypto
.digest(
"SHA-256",
new TextEncoder().encode(managedEndpointDigestInput(cf.namespace, input.environmentId)),
new TextEncoder().encode(
managedEndpointDigestInput(cf.namespace, input.userId, input.environmentId),
),
)
.pipe(
Effect.map(Encoding.encodeHex),
Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })),
);
const hostname = managedEndpointHostname(cf.namespace, cf.baseDomain, environmentHash);
const tunnelName = managedEndpointTunnelName(cf.namespace, environmentHash);
const allocation = yield* allocations
.reserve({
userId: input.userId,
environmentId: input.environmentId,
hostname: managedEndpointHostname(cf.namespace, cf.baseDomain, environmentHash),
tunnelName: managedEndpointTunnelName(cf.namespace, environmentHash),
})
.pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
const { hostname, tunnelName } = allocation;
const tunnel = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe(
Effect.map((tunnels) => tunnels.result),
@@ -218,6 +283,13 @@ const make = Effect.gen(function* () {
),
Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })),
);
yield* allocations
.recordTunnel({
userId: input.userId,
environmentId: input.environmentId,
tunnelId: tunnel.id,
})
.pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
yield* tunnels
.putConfiguration(tunnel.id, {
@@ -231,12 +303,6 @@ const make = Effect.gen(function* () {
})
.pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
const existingDnsRecordId = yield* dns.listCnameRecords(hostname).pipe(
Effect.map(Arr.head),
Effect.map(Option.map((record) => record.id)),
Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })),
);
const dnsRecord = {
type: "CNAME",
name: hostname,
@@ -245,14 +311,26 @@ const make = Effect.gen(function* () {
proxied: true,
} as const;
yield* Option.match(existingDnsRecordId, {
onSome: (id) => dns.updateCnameRecord(id, dnsRecord),
onNone: () => dns.createCnameRecord(dnsRecord),
}).pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
const dnsRecordId = yield* ensureDnsRecord(hostname, allocation.dnsRecordId, dnsRecord).pipe(
Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })),
);
yield* allocations
.recordDns({
userId: input.userId,
environmentId: input.environmentId,
dnsRecordId,
})
.pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
const connectorToken = yield* tunnels
.getToken(tunnel.id)
.pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
yield* allocations
.markReady({
userId: input.userId,
environmentId: input.environmentId,
})
.pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
return {
endpoint: {
@@ -309,22 +387,33 @@ export const layerCloudflareBindings = (
Layer.succeed(
ManagedEndpointDnsClient,
ManagedEndpointDnsClient.of({
listCnameRecords: (hostname) =>
dnsClient.listDnsRecords({ type: "CNAME", name: { exact: hostname } }).pipe(
Effect.map((response) => response.result),
listRecords: (hostname) =>
dnsClient.listDnsRecords({ name: { exact: hostname } }).pipe(
Effect.map((response) =>
response.result.filter(
(record): record is typeof record & { readonly id: string } =>
typeof record.id === "string",
),
),
Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })),
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
),
createCnameRecord: (request) =>
createRecord: (request) =>
dnsClient.createDnsRecord(request).pipe(
Effect.map((response) => ({ id: response.id })),
Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })),
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
),
updateCnameRecord: (dnsRecordId, request) =>
updateRecord: (dnsRecordId, request) =>
dnsClient.updateDnsRecord(dnsRecordId, request).pipe(
Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })),
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
),
deleteRecord: (dnsRecordId) =>
dnsClient.deleteDnsRecord(dnsRecordId).pipe(
Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })),
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
),
}),
),
),
+20
View File
@@ -83,6 +83,26 @@ export const relayEnvironmentLinks = pgTable(
],
);
export const relayManagedEndpointAllocations = pgTable(
"relay_managed_endpoint_allocations",
{
userId: varchar("user_id", { length: 191 }).notNull(),
environmentId: varchar("environment_id", { length: 191 }).notNull(),
hostname: text("hostname").notNull(),
tunnelId: varchar("tunnel_id", { length: 191 }),
tunnelName: text("tunnel_name").notNull(),
dnsRecordId: varchar("dns_record_id", { length: 191 }),
readyAt: varchar("ready_at", { length: 64 }),
createdAt: varchar("created_at", { length: 64 }).notNull(),
updatedAt: varchar("updated_at", { length: 64 }).notNull(),
},
(table) => [
primaryKey({ columns: [table.userId, table.environmentId] }),
uniqueIndex("idx_relay_managed_endpoint_allocations_hostname").on(table.hostname),
uniqueIndex("idx_relay_managed_endpoint_allocations_tunnel_name").on(table.tunnelName),
],
);
export const relayEnvironmentCredentials = pgTable(
"relay_environment_credentials",
{
+7 -1
View File
@@ -38,6 +38,7 @@ import * as DpopProofs from "./auth/DpopProofs.ts";
import * as RelayTokens from "./auth/RelayTokens.ts";
import * as EnvironmentCredentials from "./environments/EnvironmentCredentials.ts";
import * as EnvironmentLinks from "./environments/EnvironmentLinks.ts";
import * as ManagedEndpointAllocations from "./environments/ManagedEndpointAllocations.ts";
import * as LiveActivities from "./agentActivity/LiveActivities.ts";
import { RelayDb, RelayHyperdrive } from "./db.ts";
import { RelayApnsDeliveryDeadLetterQueue, RelayApnsDeliveryQueue } from "./queues.ts";
@@ -197,7 +198,12 @@ export default class Api extends Cloudflare.Worker<Api>()(
Layer.provideMerge(AgentActivityRows.layer),
Layer.provideMerge(Devices.layer),
Layer.provideMerge(EnvironmentCredentials.layer),
Layer.provideMerge(EnvironmentLinks.layer),
Layer.provideMerge(
Layer.mergeAll(
EnvironmentLinks.layer,
ManagedEndpointAllocations.ManagedEndpointAllocations.layer,
),
),
Layer.provideMerge(LiveActivities.layer),
Layer.provideMerge(DeliveryAttempts.layer),
Layer.provideMerge(RelayTokens.layer),