@devries-cameron20 / t3code Mirror · read-only / commits / d7ff7e7333
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 24, 22:45 UTC

[codex] Audit managed endpoint error context (#3245)

Co-authored-by: codex <codex@users.noreply.github.com>

Julius Marminge committed Jun 20, 2026 at 12:30 UTC d7ff7e73336482d64449f72a4bd31d9ce9f4c01e
4 files changed +678 -104
infra/relay/src/environments/ManagedEndpointAllocations.test.ts new
+93
@@ -0,0 +1,93 @@
1 +import { describe, expect, it } from "@effect/vitest";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +
5 +import * as RelayDb from "../db.ts";
6 +import { relayManagedEndpointAllocations } from "../persistence/schema.ts";
7 +import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
8 +
9 +const layerWithDb = (db: RelayDb.RelayDb["Service"]) =>
10 + ManagedEndpointAllocations.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, db)));
11 +
12 +describe("ManagedEndpointAllocations", () => {
13 + it.effect("retains database failures with allocation operation and identity", () => {
14 + const cause = new Error("database unavailable");
15 + const fakeDb = {
16 + select: () => ({
17 + from: (table: unknown) => {
18 + expect(table).toBe(relayManagedEndpointAllocations);
19 + return {
20 + where: () => ({
21 + limit: () => Effect.fail(cause),
22 + }),
23 + };
24 + },
25 + }),
26 + } as unknown as RelayDb.RelayDb["Service"];
27 +
28 + return Effect.gen(function* () {
29 + const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;
30 + const error = yield* Effect.flip(
31 + allocations.get({ userId: "user-1", environmentId: "environment-1" }),
32 + );
33 +
34 + expect(error).toMatchObject({
35 + _tag: "ManagedEndpointAllocationPersistenceError",
36 + operation: "get",
37 + stage: "database-request",
38 + userId: "user-1",
39 + environmentId: "environment-1",
40 + });
41 + expect(error.cause).toBe(cause);
42 + }).pipe(Effect.provide(layerWithDb(fakeDb)));
43 + });
44 +
45 + it.effect("reports an unresolved reservation without manufacturing a cause", () => {
46 + const fakeDb = {
47 + insert: (table: unknown) => {
48 + expect(table).toBe(relayManagedEndpointAllocations);
49 + return {
50 + values: () => ({
51 + onConflictDoNothing: () => ({
52 + returning: () => Effect.succeed([]),
53 + }),
54 + }),
55 + };
56 + },
57 + select: () => ({
58 + from: (table: unknown) => {
59 + expect(table).toBe(relayManagedEndpointAllocations);
60 + return {
61 + where: () => ({
62 + limit: () => Effect.succeed([]),
63 + }),
64 + };
65 + },
66 + }),
67 + } as unknown as RelayDb.RelayDb["Service"];
68 +
69 + return Effect.gen(function* () {
70 + const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;
71 + const error = yield* Effect.flip(
72 + allocations.reserve({
73 + userId: "user-1",
74 + environmentId: "environment-1",
75 + hostname: "environment-1.example.test",
76 + tunnelName: "environment-1-tunnel",
77 + }),
78 + );
79 +
80 + expect(error).toMatchObject({
81 + _tag: "ManagedEndpointAllocationPersistenceError",
82 + operation: "reserve",
83 + stage: "resolve-reservation",
84 + userId: "user-1",
85 + environmentId: "environment-1",
86 + hostname: "environment-1.example.test",
87 + tunnelName: "environment-1-tunnel",
88 + });
89 + expect(error.cause).toBeUndefined();
90 + expect(error.message).toContain("'resolve-reservation'");
91 + }).pipe(Effect.provide(layerWithDb(fakeDb)));
92 + });
93 +});
infra/relay/src/environments/ManagedEndpointAllocations.ts
+110 -23
@@ -38,15 +38,29 @@ export function resolveReadyManagedEndpoint(input: {
38
39 export class ManagedEndpointAllocationPersistenceError extends Schema.TaggedErrorClass<ManagedEndpointAllocationPersistenceError>()(
40 "ManagedEndpointAllocationPersistenceError",
41 - { cause: Schema.Defect() },
41 + {
42 + operation: Schema.Literals([
43 + "get",
44 + "reserve",
45 + "record-tunnel",
46 + "record-dns",
47 + "mark-ready",
48 + "remove",
49 + ]),
50 + stage: Schema.Literals(["database-request", "resolve-reservation"]),
51 + userId: Schema.String,
52 + environmentId: Schema.String,
53 + hostname: Schema.optionalKey(Schema.String),
54 + tunnelName: Schema.optionalKey(Schema.String),
55 + tunnelId: Schema.optionalKey(Schema.String),
56 + dnsRecordId: Schema.optionalKey(Schema.String),
57 + cause: Schema.optional(Schema.Defect()),
58 + },
59 ) {
60 override get message(): string {
44 - return "Failed to persist managed endpoint allocation";
61 + return `Managed endpoint allocation '${this.operation}' failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
62 }
63 }
47 -const isManagedEndpointAllocationPersistenceError = Schema.is(
48 - ManagedEndpointAllocationPersistenceError,
49 -);
64
65 interface ManagedEndpointAllocationKey {
66 readonly userId: string;
@@ -106,11 +120,6 @@ const whereAllocation = (input: ManagedEndpointAllocationKey) =>
120 eq(relayManagedEndpointAllocations.environmentId, input.environmentId),
121 );
122
109 -const persistenceError = (cause: unknown) =>
110 - isManagedEndpointAllocationPersistenceError(cause)
111 - ? cause
112 - : new ManagedEndpointAllocationPersistenceError({ cause });
113 -
123 const make = Effect.gen(function* () {
124 const db = yield* RelayDb.RelayDb;
125
@@ -125,7 +134,15 @@ const make = Effect.gen(function* () {
134 .limit(1)
135 .pipe(
136 Effect.map((rows) => rows[0] ?? null),
128 - Effect.mapError(persistenceError),
137 + Effect.mapError(
138 + (cause) =>
139 + new ManagedEndpointAllocationPersistenceError({
140 + operation: "get",
141 + stage: "database-request",
142 + ...input,
143 + cause,
144 + }),
145 + ),
146 );
147 }),
148 reserve: Effect.fn("relay.managed_endpoint_allocations.reserve")(function* (
@@ -140,7 +157,18 @@ const make = Effect.gen(function* () {
157 updatedAt: now,
158 })
159 .onConflictDoNothing()
143 - .returning(allocationSelection);
160 + .returning(allocationSelection)
161 + .pipe(
162 + Effect.mapError(
163 + (cause) =>
164 + new ManagedEndpointAllocationPersistenceError({
165 + operation: "reserve",
166 + stage: "database-request",
167 + ...input,
168 + cause,
169 + }),
170 + ),
171 + );
172
173 const allocation =
174 inserted[0] ??
@@ -149,16 +177,29 @@ const make = Effect.gen(function* () {
177 .from(relayManagedEndpointAllocations)
178 .where(whereAllocation(input))
179 .limit(1)
152 - .pipe(Effect.map((rows) => rows[0])));
180 + .pipe(
181 + Effect.map((rows) => rows[0]),
182 + Effect.mapError(
183 + (cause) =>
184 + new ManagedEndpointAllocationPersistenceError({
185 + operation: "reserve",
186 + stage: "database-request",
187 + ...input,
188 + cause,
189 + }),
190 + ),
191 + ));
192
193 if (allocation === undefined) {
194 return yield* new ManagedEndpointAllocationPersistenceError({
156 - cause: new Error("Managed endpoint allocation was not persisted."),
195 + operation: "reserve",
196 + stage: "resolve-reservation",
197 + ...input,
198 });
199 }
200
201 return allocation;
161 - }, Effect.mapError(persistenceError)),
202 + }),
203 recordTunnel: Effect.fn("relay.managed_endpoint_allocations.record_tunnel")(function* (
204 input: RecordManagedEndpointTunnelInput,
205 ) {
@@ -168,8 +209,19 @@ const make = Effect.gen(function* () {
209 tunnelId: input.tunnelId,
210 updatedAt: DateTime.formatIso(yield* DateTime.now),
211 })
171 - .where(whereAllocation(input));
172 - }, Effect.mapError(persistenceError)),
212 + .where(whereAllocation(input))
213 + .pipe(
214 + Effect.mapError(
215 + (cause) =>
216 + new ManagedEndpointAllocationPersistenceError({
217 + operation: "record-tunnel",
218 + stage: "database-request",
219 + ...input,
220 + cause,
221 + }),
222 + ),
223 + );
224 + }),
225 recordDns: Effect.fn("relay.managed_endpoint_allocations.record_dns")(function* (
226 input: RecordManagedEndpointDnsInput,
227 ) {
@@ -179,8 +231,19 @@ const make = Effect.gen(function* () {
231 dnsRecordId: input.dnsRecordId,
232 updatedAt: DateTime.formatIso(yield* DateTime.now),
233 })
182 - .where(whereAllocation(input));
183 - }, Effect.mapError(persistenceError)),
234 + .where(whereAllocation(input))
235 + .pipe(
236 + Effect.mapError(
237 + (cause) =>
238 + new ManagedEndpointAllocationPersistenceError({
239 + operation: "record-dns",
240 + stage: "database-request",
241 + ...input,
242 + cause,
243 + }),
244 + ),
245 + );
246 + }),
247 markReady: Effect.fn("relay.managed_endpoint_allocations.mark_ready")(function* (
248 input: ManagedEndpointAllocationKey,
249 ) {
@@ -191,13 +254,37 @@ const make = Effect.gen(function* () {
254 readyAt: now,
255 updatedAt: now,
256 })
194 - .where(whereAllocation(input));
195 - }, Effect.mapError(persistenceError)),
257 + .where(whereAllocation(input))
258 + .pipe(
259 + Effect.mapError(
260 + (cause) =>
261 + new ManagedEndpointAllocationPersistenceError({
262 + operation: "mark-ready",
263 + stage: "database-request",
264 + ...input,
265 + cause,
266 + }),
267 + ),
268 + );
269 + }),
270 remove: Effect.fn("relay.managed_endpoint_allocations.remove")(function* (
271 input: ManagedEndpointAllocationKey,
272 ) {
199 - yield* db.delete(relayManagedEndpointAllocations).where(whereAllocation(input));
200 - }, Effect.mapError(persistenceError)),
273 + yield* db
274 + .delete(relayManagedEndpointAllocations)
275 + .where(whereAllocation(input))
276 + .pipe(
277 + Effect.mapError(
278 + (cause) =>
279 + new ManagedEndpointAllocationPersistenceError({
280 + operation: "remove",
281 + stage: "database-request",
282 + ...input,
283 + cause,
284 + }),
285 + ),
286 + );
287 + }),
288 });
289 });
290
infra/relay/src/environments/ManagedEndpointProvider.test.ts
+83 -5
@@ -130,6 +130,9 @@ function makeDnsClient(
130 calls.push({ operation: "updateRecord", input: { dnsRecordId, request } });
131 if (!currentRecords.some((record) => record.id === dnsRecordId)) {
132 return yield* new ManagedEndpointProvider.ManagedEndpointDnsClientError({
133 + operation: "update-record",
134 + hostname: request.name,
135 + dnsRecordId,
136 cause: `DNS record ${dnsRecordId} does not exist.`,
137 });
138 }
@@ -398,7 +401,13 @@ describe("ManagedEndpointProvider", () => {
401 expect(dnsCalls).toHaveLength(0);
402 expect(result._tag).toBe("Failure");
403 if (result._tag === "Failure") {
401 - expect(result.failure._tag).toBe("ManagedEndpointOriginNotAllowed");
404 + expect(result.failure).toMatchObject({
405 + _tag: "ManagedEndpointOriginNotAllowed",
406 + userId: "user_ABC",
407 + environmentId: "env_ABC",
408 + host: "192.168.1.10",
409 + port: 3773,
410 + });
411 }
412 }).pipe(Effect.provide(providerLayer(makeTunnelClient(), makeDnsClient(dnsCalls))));
413 });
@@ -593,6 +602,8 @@ describe("ManagedEndpointProvider", () => {
602 const tunnelCalls: TunnelCall[] = [];
603 let deleteAttempts = 0;
604 const failure = new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
605 + operation: "delete",
606 + tunnelId: "tunnel-id",
607 cause: "Cloudflare tunnel deletion failed",
608 });
609 const tunnels = makePersistentTunnelClient(tunnelCalls);
@@ -618,6 +629,16 @@ describe("ManagedEndpointProvider", () => {
629 });
630 const first = yield* Effect.result(provider.deprovision(key));
631 expect(first._tag).toBe("Failure");
632 + if (first._tag === "Failure") {
633 + expect(first.failure).toMatchObject({
634 + _tag: "ManagedEndpointDeprovisioningFailed",
635 + stage: "delete-tunnel",
636 + userId: key.userId,
637 + environmentId: key.environmentId,
638 + tunnelId: "tunnel-id",
639 + });
640 + expect(first.failure.cause).toBe(failure);
641 + }
642 yield* provider.deprovision(key);
643
644 expect(allocationCalls.map((call) => call.operation)).toEqual([
@@ -639,13 +660,23 @@ describe("ManagedEndpointProvider", () => {
660 ...makeTunnelClient(),
661 delete: () =>
662 Effect.fail(
642 - new ManagedEndpointProvider.ManagedEndpointTunnelClientError({ cause: notFound }),
663 + new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
664 + operation: "delete",
665 + tunnelId: "tunnel-id",
666 + cause: notFound,
667 + }),
668 ),
669 });
670 const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
671 ...makeDnsClient(),
672 deleteRecord: () =>
648 - Effect.fail(new ManagedEndpointProvider.ManagedEndpointDnsClientError({ cause: notFound })),
673 + Effect.fail(
674 + new ManagedEndpointProvider.ManagedEndpointDnsClientError({
675 + operation: "delete-record",
676 + dnsRecordId: "created-record-id",
677 + cause: notFound,
678 + }),
679 + ),
680 });
681 const layer = providerLayer(tunnelClient, dnsClient, makeAllocations(allocationCalls));
682
@@ -690,6 +721,8 @@ describe("ManagedEndpointProvider", () => {
721 it.effect("recovers when DNS creation reports failure after the record became visible", () => {
722 const dnsCalls: DnsCall[] = [];
723 const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({
724 + operation: "create-record",
725 + hostname: expectedManagedHostname("env_ABC"),
726 cause: "ambiguous Cloudflare DNS response",
727 });
728 let records: ReadonlyArray<{ readonly id: string }> = [];
@@ -732,8 +765,43 @@ describe("ManagedEndpointProvider", () => {
765 }).pipe(Effect.provide(providerLayer(makeTunnelClient(), dnsClient)));
766 });
767
768 + it.effect("reports malformed tunnel responses without manufacturing a cause", () => {
769 + const dnsCalls: DnsCall[] = [];
770 + const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
771 + ...makeTunnelClient(),
772 + create: () => Effect.succeed({ id: "returned-tunnel-id", name: null }),
773 + });
774 +
775 + return Effect.gen(function* () {
776 + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
777 + const error = yield* Effect.flip(
778 + provider.provision({
779 + userId: "user_ABC",
780 + environmentId: "env_ABC",
781 + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
782 + }),
783 + );
784 +
785 + expect(error).toMatchObject({
786 + _tag: "ManagedEndpointProvisioningFailed",
787 + stage: "validate-tunnel-response",
788 + userId: "user_ABC",
789 + environmentId: "env_ABC",
790 + hostname: expectedManagedHostname("env_ABC"),
791 + tunnelName: expectedManagedTunnelName("env_ABC"),
792 + returnedTunnelId: "returned-tunnel-id",
793 + });
794 + if (error._tag === "ManagedEndpointProvisioningFailed") {
795 + expect(error.cause).toBeUndefined();
796 + }
797 + expect(dnsCalls).toHaveLength(0);
798 + }).pipe(Effect.provide(providerLayer(tunnelClient, makeDnsClient(dnsCalls))));
799 + });
800 +
801 it.effect("fails provisioning when the DNS client fails", () => {
802 const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({
803 + operation: "list-records",
804 + hostname: expectedManagedHostname("env_ABC"),
805 cause: "Cloudflare DNS failure",
806 });
807 const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
@@ -753,8 +821,18 @@ describe("ManagedEndpointProvider", () => {
821 }),
822 );
823
756 - expect(error._tag).toBe("ManagedEndpointProvisioningFailed");
757 - expect(error.cause).toBe(failure);
824 + expect(error).toMatchObject({
825 + _tag: "ManagedEndpointProvisioningFailed",
826 + stage: "ensure-dns-record",
827 + userId: "user_ABC",
828 + environmentId: "env_ABC",
829 + hostname: expectedManagedHostname("env_ABC"),
830 + tunnelName: expectedManagedTunnelName("env_ABC"),
831 + tunnelId: "tunnel-id",
832 + });
833 + if (error._tag === "ManagedEndpointProvisioningFailed") {
834 + expect(error.cause).toBe(failure);
835 + }
836 }).pipe(Effect.provide(providerLayer(makeTunnelClient(), dnsClient)));
837 });
838 });
infra/relay/src/environments/ManagedEndpointProvider.ts
+392 -76
@@ -7,7 +7,6 @@ import * as Effect from "effect/Effect";
7 import * as Encoding from "effect/Encoding";
8 import * as Layer from "effect/Layer";
9 import * as Option from "effect/Option";
10 -import * as Result from "effect/Result";
10 import * as Schema from "effect/Schema";
11
12 import type {
@@ -27,40 +26,86 @@ import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
26
27 export class ManagedEndpointProvisioningNotConfigured extends Schema.TaggedErrorClass<ManagedEndpointProvisioningNotConfigured>()(
28 "ManagedEndpointProvisioningNotConfigured",
30 - {},
29 + {
30 + userId: Schema.String,
31 + environmentId: Schema.String,
32 + missingSettings: Schema.Array(
33 + Schema.Literals(["managedEndpointBaseDomain", "managedEndpointNamespace"]),
34 + ),
35 + },
36 ) {
37 override get message(): string {
33 - return "Managed endpoint provisioning is not configured";
38 + return `Managed endpoint provisioning is not configured for user '${this.userId}', environment '${this.environmentId}': missing ${this.missingSettings.join(", ")}`;
39 }
40 }
41
42 +const ManagedEndpointProvisioningStage = Schema.Literals([
43 + "derive-environment-hash",
44 + "reserve-allocation",
45 + "ensure-tunnel",
46 + "validate-tunnel-response",
47 + "record-tunnel",
48 + "configure-tunnel",
49 + "ensure-dns-record",
50 + "record-dns",
51 + "get-tunnel-token",
52 + "mark-allocation-ready",
53 +]);
54 +
55 export class ManagedEndpointProvisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointProvisioningFailed>()(
56 "ManagedEndpointProvisioningFailed",
39 - { cause: Schema.Defect() },
57 + {
58 + stage: ManagedEndpointProvisioningStage,
59 + userId: Schema.String,
60 + environmentId: Schema.String,
61 + hostname: Schema.optionalKey(Schema.String),
62 + tunnelName: Schema.optionalKey(Schema.String),
63 + tunnelId: Schema.optionalKey(Schema.String),
64 + dnsRecordId: Schema.optionalKey(Schema.String),
65 + returnedTunnelName: Schema.optionalKey(Schema.String),
66 + returnedTunnelId: Schema.optionalKey(Schema.String),
67 + cause: Schema.optional(Schema.Defect()),
68 + },
69 ) {
70 override get message(): string {
42 - return "Managed endpoint provisioning failed";
71 + return `Managed endpoint provisioning failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
72 }
73 }
74
75 +const ManagedEndpointDeprovisioningStage = Schema.Literals([
76 + "load-allocation",
77 + "delete-dns-record",
78 + "delete-tunnel",
79 + "remove-allocation",
80 +]);
81 +
82 export class ManagedEndpointDeprovisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointDeprovisioningFailed>()(
83 "ManagedEndpointDeprovisioningFailed",
48 - { cause: Schema.Defect() },
84 + {
85 + stage: ManagedEndpointDeprovisioningStage,
86 + userId: Schema.String,
87 + environmentId: Schema.String,
88 + tunnelId: Schema.optionalKey(Schema.String),
89 + dnsRecordId: Schema.optionalKey(Schema.String),
90 + cause: Schema.Defect(),
91 + },
92 ) {
93 override get message(): string {
51 - return "Managed endpoint deprovisioning failed";
94 + return `Managed endpoint deprovisioning failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
95 }
96 }
97
98 export class ManagedEndpointOriginNotAllowed extends Schema.TaggedErrorClass<ManagedEndpointOriginNotAllowed>()(
99 "ManagedEndpointOriginNotAllowed",
100 {
101 + userId: Schema.String,
102 + environmentId: Schema.String,
103 host: Schema.String,
104 port: Schema.Number,
105 },
106 ) {
107 override get message(): string {
63 - return `Managed endpoint origin '${this.host}:${this.port}' is not allowed`;
108 + return `Managed endpoint origin '${this.host}:${this.port}' is not allowed for user '${this.userId}', environment '${this.environmentId}'`;
109 }
110 }
111
@@ -94,12 +139,26 @@ interface ManagedEndpointTunnel {
139 readonly name?: string | null;
140 }
141
142 +const ManagedEndpointTunnelClientOperation = Schema.Literals([
143 + "list",
144 + "create",
145 + "put-configuration",
146 + "get-token",
147 + "delete",
148 +]);
149 +
150 export class ManagedEndpointTunnelClientError extends Schema.TaggedErrorClass<ManagedEndpointTunnelClientError>()(
151 "ManagedEndpointTunnelClientError",
99 - { cause: Schema.Defect() },
152 + {
153 + operation: ManagedEndpointTunnelClientOperation,
154 + tunnelName: Schema.optionalKey(Schema.String),
155 + tunnelId: Schema.optionalKey(Schema.String),
156 + cause: Schema.Defect(),
157 + },
158 ) {
159 override get message(): string {
102 - return "Managed endpoint tunnel provider request failed";
160 + const target = this.tunnelId ?? this.tunnelName;
161 + return `Managed endpoint tunnel provider '${this.operation}' request failed${target === undefined ? "" : ` for '${target}'`}`;
162 }
163 }
164
@@ -147,12 +206,25 @@ interface ManagedEndpointCnameRecordInput {
206 readonly proxied: true;
207 }
208
209 +const ManagedEndpointDnsClientOperation = Schema.Literals([
210 + "list-records",
211 + "create-record",
212 + "update-record",
213 + "delete-record",
214 +]);
215 +
216 export class ManagedEndpointDnsClientError extends Schema.TaggedErrorClass<ManagedEndpointDnsClientError>()(
217 "ManagedEndpointDnsClientError",
152 - { cause: Schema.Defect() },
218 + {
219 + operation: ManagedEndpointDnsClientOperation,
220 + hostname: Schema.optionalKey(Schema.String),
221 + dnsRecordId: Schema.optionalKey(Schema.String),
222 + cause: Schema.Defect(),
223 + },
224 ) {
225 override get message(): string {
155 - return "Managed endpoint DNS provider request failed";
226 + const target = this.dnsRecordId ?? this.hostname;
227 + return `Managed endpoint DNS provider '${this.operation}' request failed${target === undefined ? "" : ` for '${target}'`}`;
228 }
229 }
230
@@ -183,13 +255,26 @@ export const layerDnsClient = (client: ManagedEndpointDnsClient["Service"]) =>
255
256 const requireCloudflareSettings = Effect.fnUntraced(function* (
257 settings: RelayConfiguration.RelayConfiguration["Service"],
258 + input: { readonly userId: string; readonly environmentId: string },
259 ) {
187 - if (!settings.managedEndpointBaseDomain || !settings.managedEndpointNamespace) {
188 - return yield* new ManagedEndpointProvisioningNotConfigured();
260 + const baseDomain = settings.managedEndpointBaseDomain;
261 + const namespace = settings.managedEndpointNamespace;
262 + const missingSettings: Array<"managedEndpointBaseDomain" | "managedEndpointNamespace"> = [];
263 + if (!baseDomain) {
264 + missingSettings.push("managedEndpointBaseDomain");
265 + }
266 + if (!namespace) {
267 + missingSettings.push("managedEndpointNamespace");
268 + }
269 + if (!baseDomain || !namespace) {
270 + return yield* new ManagedEndpointProvisioningNotConfigured({
271 + ...input,
272 + missingSettings,
273 + });
274 }
275 return {
191 - baseDomain: settings.managedEndpointBaseDomain,
192 - namespace: settings.managedEndpointNamespace,
276 + baseDomain,
277 + namespace,
278 };
279 });
280
@@ -231,10 +316,19 @@ function isNotFoundCause(cause: unknown): boolean {
316 return "cause" in cause && isNotFoundCause(cause.cause);
317 }
318
234 -const ignoreNotFound = <A, E>(effect: Effect.Effect<A, E>): Effect.Effect<void, E> =>
319 +type ManagedEndpointClientError = ManagedEndpointTunnelClientError | ManagedEndpointDnsClientError;
320 +
321 +const ignoreNotFound = <A>(
322 + effect: Effect.Effect<A, ManagedEndpointClientError>,
323 +): Effect.Effect<void, ManagedEndpointClientError> =>
324 effect.pipe(
325 Effect.asVoid,
237 - Effect.catch((cause) => (isNotFoundCause(cause) ? Effect.void : Effect.fail(cause))),
326 + Effect.catchTags({
327 + ManagedEndpointTunnelClientError: (error) =>
328 + isNotFoundCause(error.cause) ? Effect.void : Effect.fail(error),
329 + ManagedEndpointDnsClientError: (error) =>
330 + isNotFoundCause(error.cause) ? Effect.void : Effect.fail(error),
331 + }),
332 );
333
334 const make = Effect.gen(function* () {
@@ -289,25 +383,26 @@ const make = Effect.gen(function* () {
383 }
384 return yield* dns.createRecord(dnsRecord).pipe(
385 Effect.map((record) => record.id),
292 - Effect.catch((createError) =>
293 - Effect.gen(function* () {
294 - let records = yield* dns.listRecords(hostname);
295 - for (let attempt = 0; records.length === 0 && attempt < 4; attempt++) {
296 - yield* Effect.sleep("200 millis");
297 - records = yield* dns.listRecords(hostname);
298 - }
299 - return records;
300 - }).pipe(
301 - Effect.flatMap((records) =>
302 - records.length > 0
303 - ? updateExistingDnsRecords(records, preferredDnsRecordId, dnsRecord)
304 - : Effect.fail(createError),
305 - ),
306 - Effect.flatMap((dnsRecordId) =>
307 - dnsRecordId === null ? Effect.fail(createError) : Effect.succeed(dnsRecordId),
386 + Effect.catchTags({
387 + ManagedEndpointDnsClientError: (createError) =>
388 + Effect.gen(function* () {
389 + let records = yield* dns.listRecords(hostname);
390 + for (let attempt = 0; records.length === 0 && attempt < 4; attempt++) {
391 + yield* Effect.sleep("200 millis");
392 + records = yield* dns.listRecords(hostname);
393 + }
394 + return records;
395 + }).pipe(
396 + Effect.flatMap((records) =>
397 + records.length > 0
398 + ? updateExistingDnsRecords(records, preferredDnsRecordId, dnsRecord)
399 + : Effect.fail(createError),
400 + ),
401 + Effect.flatMap((dnsRecordId) =>
402 + dnsRecordId === null ? Effect.fail(createError) : Effect.succeed(dnsRecordId),
403 + ),
404 ),
309 - ),
310 - ),
405 + }),
406 );
407 });
408
@@ -317,25 +412,59 @@ const make = Effect.gen(function* () {
412 "relay.user_id": input.userId,
413 "relay.environment_id": input.environmentId,
414 });
320 - const allocation = yield* allocations
321 - .get(input)
322 - .pipe(Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })));
415 + const allocation = yield* allocations.get(input).pipe(
416 + Effect.mapError(
417 + (cause) =>
418 + new ManagedEndpointDeprovisioningFailed({
419 + ...input,
420 + stage: "load-allocation",
421 + cause,
422 + }),
423 + ),
424 + );
425 if (allocation === null) {
426 return;
427 }
326 - if (allocation.dnsRecordId !== null) {
327 - yield* ignoreNotFound(dns.deleteRecord(allocation.dnsRecordId)).pipe(
328 - Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })),
428 + const dnsRecordId = allocation.dnsRecordId;
429 + if (dnsRecordId !== null) {
430 + yield* ignoreNotFound(dns.deleteRecord(dnsRecordId)).pipe(
431 + Effect.mapError(
432 + (cause) =>
433 + new ManagedEndpointDeprovisioningFailed({
434 + ...input,
435 + stage: "delete-dns-record",
436 + dnsRecordId,
437 + cause,
438 + }),
439 + ),
440 );
441 }
331 - if (allocation.tunnelId !== null) {
332 - yield* ignoreNotFound(tunnels.delete(allocation.tunnelId)).pipe(
333 - Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })),
442 + const tunnelId = allocation.tunnelId;
443 + if (tunnelId !== null) {
444 + yield* ignoreNotFound(tunnels.delete(tunnelId)).pipe(
445 + Effect.mapError(
446 + (cause) =>
447 + new ManagedEndpointDeprovisioningFailed({
448 + ...input,
449 + stage: "delete-tunnel",
450 + tunnelId,
451 + cause,
452 + }),
453 + ),
454 );
455 }
336 - yield* allocations
337 - .remove(input)
338 - .pipe(Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })));
456 + yield* allocations.remove(input).pipe(
457 + Effect.mapError(
458 + (cause) =>
459 + new ManagedEndpointDeprovisioningFailed({
460 + ...input,
461 + stage: "remove-allocation",
462 + ...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),
463 + ...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),
464 + cause,
465 + }),
466 + ),
467 + );
468 }),
469 provision: Effect.fn("relay.managed_endpoint_provider.provision")(function* (input) {
470 yield* Effect.annotateCurrentSpan({
@@ -346,11 +475,13 @@ const make = Effect.gen(function* () {
475 });
476 if (!isLoopbackOrigin(input.origin)) {
477 return yield* new ManagedEndpointOriginNotAllowed({
478 + userId: input.userId,
479 + environmentId: input.environmentId,
480 host: input.origin.localHttpHost,
481 port: input.origin.localHttpPort,
482 });
483 }
353 - const cf = yield* requireCloudflareSettings(config);
484 + const cf = yield* requireCloudflareSettings(config, input);
485 const environmentHash = yield* crypto
486 .digest(
487 "SHA-256",
@@ -360,19 +491,45 @@ const make = Effect.gen(function* () {
491 )
492 .pipe(
493 Effect.map(Encoding.encodeHex),
363 - Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })),
494 + Effect.mapError(
495 + (cause) =>
496 + new ManagedEndpointProvisioningFailed({
497 + userId: input.userId,
498 + environmentId: input.environmentId,
499 + stage: "derive-environment-hash",
500 + cause,
501 + }),
502 + ),
503 );
504 + const requestedHostname = managedEndpointHostname(
505 + cf.namespace,
506 + cf.baseDomain,
507 + environmentHash,
508 + );
509 + const requestedTunnelName = managedEndpointTunnelName(cf.namespace, environmentHash);
510 const allocation = yield* allocations
511 .reserve({
512 userId: input.userId,
513 environmentId: input.environmentId,
369 - hostname: managedEndpointHostname(cf.namespace, cf.baseDomain, environmentHash),
370 - tunnelName: managedEndpointTunnelName(cf.namespace, environmentHash),
514 + hostname: requestedHostname,
515 + tunnelName: requestedTunnelName,
516 })
372 - .pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
517 + .pipe(
518 + Effect.mapError(
519 + (cause) =>
520 + new ManagedEndpointProvisioningFailed({
521 + userId: input.userId,
522 + environmentId: input.environmentId,
523 + stage: "reserve-allocation",
524 + hostname: requestedHostname,
525 + tunnelName: requestedTunnelName,
526 + cause,
527 + }),
528 + ),
529 + );
530 const { hostname, tunnelName } = allocation;
531
375 - const tunnel = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe(
532 + const tunnelResponse = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe(
533 Effect.map((tunnels) => tunnels.result),
534 Effect.map(Arr.findFirst((tunnel) => tunnel.name === tunnelName)),
535 Effect.flatMap(
@@ -381,20 +538,50 @@ const make = Effect.gen(function* () {
538 onNone: () => tunnels.create({ name: tunnelName, configSrc: "cloudflare" }),
539 }),
540 ),
384 - Effect.filterMapOrFail((tunnel) =>
385 - tunnel.id && tunnel.name
386 - ? Result.succeed({ id: tunnel.id, name: tunnel.name })
387 - : Result.fail(new ManagedEndpointProvisioningFailed({ cause: tunnel })),
541 + Effect.mapError(
542 + (cause) =>
543 + new ManagedEndpointProvisioningFailed({
544 + userId: input.userId,
545 + environmentId: input.environmentId,
546 + stage: "ensure-tunnel",
547 + hostname,
548 + tunnelName,
549 + cause,
550 + }),
551 ),
389 - Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })),
552 );
553 + if (!tunnelResponse.id || !tunnelResponse.name) {
554 + return yield* new ManagedEndpointProvisioningFailed({
555 + userId: input.userId,
556 + environmentId: input.environmentId,
557 + stage: "validate-tunnel-response",
558 + hostname,
559 + tunnelName,
560 + ...(tunnelResponse.id ? { returnedTunnelId: tunnelResponse.id } : {}),
561 + ...(tunnelResponse.name ? { returnedTunnelName: tunnelResponse.name } : {}),
562 + });
563 + }
564 + const tunnel = { id: tunnelResponse.id, name: tunnelResponse.name };
565 yield* allocations
566 .recordTunnel({
567 userId: input.userId,
568 environmentId: input.environmentId,
569 tunnelId: tunnel.id,
570 })
397 - .pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
571 + .pipe(
572 + Effect.mapError(
573 + (cause) =>
574 + new ManagedEndpointProvisioningFailed({
575 + userId: input.userId,
576 + environmentId: input.environmentId,
577 + stage: "record-tunnel",
578 + hostname,
579 + tunnelName,
580 + tunnelId: tunnel.id,
581 + cause,
582 + }),
583 + ),
584 + );
585
586 yield* tunnels
587 .putConfiguration(tunnel.id, {
@@ -406,7 +593,20 @@ const make = Effect.gen(function* () {
593 { service: "http_status:404" },
594 ],
595 })
409 - .pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
596 + .pipe(
597 + Effect.mapError(
598 + (cause) =>
599 + new ManagedEndpointProvisioningFailed({
600 + userId: input.userId,
601 + environmentId: input.environmentId,
602 + stage: "configure-tunnel",
603 + hostname,
604 + tunnelName,
605 + tunnelId: tunnel.id,
606 + cause,
607 + }),
608 + ),
609 + );
610
611 const dnsRecord = {
612 type: "CNAME",
@@ -417,7 +617,19 @@ const make = Effect.gen(function* () {
617 } as const;
618
619 const dnsRecordId = yield* ensureDnsRecord(hostname, allocation.dnsRecordId, dnsRecord).pipe(
420 - Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })),
620 + Effect.mapError(
621 + (cause) =>
622 + new ManagedEndpointProvisioningFailed({
623 + userId: input.userId,
624 + environmentId: input.environmentId,
625 + stage: "ensure-dns-record",
626 + hostname,
627 + tunnelName,
628 + tunnelId: tunnel.id,
629 + ...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),
630 + cause,
631 + }),
632 + ),
633 );
634 yield* allocations
635 .recordDns({
@@ -425,17 +637,57 @@ const make = Effect.gen(function* () {
637 environmentId: input.environmentId,
638 dnsRecordId,
639 })
428 - .pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
640 + .pipe(
641 + Effect.mapError(
642 + (cause) =>
643 + new ManagedEndpointProvisioningFailed({
644 + userId: input.userId,
645 + environmentId: input.environmentId,
646 + stage: "record-dns",
647 + hostname,
648 + tunnelName,
649 + tunnelId: tunnel.id,
650 + dnsRecordId,
651 + cause,
652 + }),
653 + ),
654 + );
655
430 - const connectorToken = yield* tunnels
431 - .getToken(tunnel.id)
432 - .pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
656 + const connectorToken = yield* tunnels.getToken(tunnel.id).pipe(
657 + Effect.mapError(
658 + (cause) =>
659 + new ManagedEndpointProvisioningFailed({
660 + userId: input.userId,
661 + environmentId: input.environmentId,
662 + stage: "get-tunnel-token",
663 + hostname,
664 + tunnelName,
665 + tunnelId: tunnel.id,
666 + dnsRecordId,
667 + cause,
668 + }),
669 + ),
670 + );
671 yield* allocations
672 .markReady({
673 userId: input.userId,
674 environmentId: input.environmentId,
675 })
438 - .pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
676 + .pipe(
677 + Effect.mapError(
678 + (cause) =>
679 + new ManagedEndpointProvisioningFailed({
680 + userId: input.userId,
681 + environmentId: input.environmentId,
682 + stage: "mark-allocation-ready",
683 + hostname,
684 + tunnelName,
685 + tunnelId: tunnel.id,
686 + dnsRecordId,
687 + cause,
688 + }),
689 + ),
690 + );
691
692 return {
693 endpoint: managedEndpointForHostname(hostname),
@@ -464,27 +716,62 @@ export const layerCloudflareBindings = (
716 ManagedEndpointTunnelClient.of({
717 list: (request) =>
718 tunnelClient.list(request).pipe(
467 - Effect.mapError((cause) => new ManagedEndpointTunnelClientError({ cause })),
719 + Effect.mapError(
720 + (cause) =>
721 + new ManagedEndpointTunnelClientError({
722 + operation: "list",
723 + tunnelName: request.name,
724 + cause,
725 + }),
726 + ),
727 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
728 ),
729 create: (request) =>
730 tunnelClient.create(request).pipe(
472 - Effect.mapError((cause) => new ManagedEndpointTunnelClientError({ cause })),
731 + Effect.mapError(
732 + (cause) =>
733 + new ManagedEndpointTunnelClientError({
734 + operation: "create",
735 + tunnelName: request.name,
736 + cause,
737 + }),
738 + ),
739 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
740 ),
741 putConfiguration: (tunnelId, config) =>
742 tunnelClient.putConfiguration(tunnelId, config).pipe(
477 - Effect.mapError((cause) => new ManagedEndpointTunnelClientError({ cause })),
743 + Effect.mapError(
744 + (cause) =>
745 + new ManagedEndpointTunnelClientError({
746 + operation: "put-configuration",
747 + tunnelId,
748 + cause,
749 + }),
750 + ),
751 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
752 ),
753 getToken: (tunnelId) =>
754 tunnelClient.getToken(tunnelId).pipe(
482 - Effect.mapError((cause) => new ManagedEndpointTunnelClientError({ cause })),
755 + Effect.mapError(
756 + (cause) =>
757 + new ManagedEndpointTunnelClientError({
758 + operation: "get-token",
759 + tunnelId,
760 + cause,
761 + }),
762 + ),
763 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
764 ),
765 delete: (tunnelId) =>
766 tunnelClient.delete(tunnelId).pipe(
487 - Effect.mapError((cause) => new ManagedEndpointTunnelClientError({ cause })),
767 + Effect.mapError(
768 + (cause) =>
769 + new ManagedEndpointTunnelClientError({
770 + operation: "delete",
771 + tunnelId,
772 + cause,
773 + }),
774 + ),
775 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
776 ),
777 }),
@@ -500,23 +787,52 @@ export const layerCloudflareBindings = (
787 normalizeHostname(record.name) === normalizeHostname(hostname),
788 ),
789 ),
503 - Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })),
790 + Effect.mapError(
791 + (cause) =>
792 + new ManagedEndpointDnsClientError({
793 + operation: "list-records",
794 + hostname,
795 + cause,
796 + }),
797 + ),
798 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
799 ),
800 createRecord: (request) =>
801 dnsClient.createDnsRecord(request).pipe(
802 Effect.map((response) => ({ id: response.id })),
509 - Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })),
803 + Effect.mapError(
804 + (cause) =>
805 + new ManagedEndpointDnsClientError({
806 + operation: "create-record",
807 + hostname: request.name,
808 + cause,
809 + }),
810 + ),
811 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
812 ),
813 updateRecord: (dnsRecordId, request) =>
814 dnsClient.updateDnsRecord(dnsRecordId, request).pipe(
514 - Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })),
815 + Effect.mapError(
816 + (cause) =>
817 + new ManagedEndpointDnsClientError({
818 + operation: "update-record",
819 + hostname: request.name,
820 + dnsRecordId,
821 + cause,
822 + }),
823 + ),
824 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
825 ),
826 deleteRecord: (dnsRecordId) =>
827 dnsClient.deleteDnsRecord(dnsRecordId).pipe(
519 - Effect.mapError((cause) => new ManagedEndpointDnsClientError({ cause })),
828 + Effect.mapError(
829 + (cause) =>
830 + new ManagedEndpointDnsClientError({
831 + operation: "delete-record",
832 + dnsRecordId,
833 + cause,
834 + }),
835 + ),
836 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
837 ),
838 }),