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

main
ts 1,746 lines 60.5 KB
Raw
1 import * as CloudflareRetry from "@distilled.cloud/cloudflare/Retry";
2 import * as Alchemy from "alchemy";
3 import * as Cloudflare from "@alchemy.run/cloudflare";
4 import * as Arr from "effect/Array";
5 import * as Cause from "effect/Cause";
6 import * as Clock from "effect/Clock";
7 import * as Context from "effect/Context";
8 import * as Digest from "effect/crypto/Digest";
9 import * as DateTime from "effect/DateTime";
10 import * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import * as Hex from "effect/encoding/Hex";
13 import * as Layer from "effect/Layer";
14 import * as Option from "effect/Option";
15 import * as Schema from "effect/Schema";
16
17 import type {
18 RelayManagedEndpoint,
19 RelayManagedEndpointOrigin,
20 RelayManagedEndpointRuntimeConfig,
21 } from "@t3tools/contracts/relay";
22
23 import * as RelayConfiguration from "../Config.ts";
24 import {
25 managedEndpointDigestInput,
26 managedEndpointForHostname,
27 managedEndpointHostname,
28 managedEndpointTunnelName,
29 } from "../deploymentConfig.ts";
30 import * as CloudflareApiPause from "./CloudflareApiPause.ts";
31 import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
32 import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts";
33
34 export class ManagedEndpointProvisioningNotConfigured extends Schema.TaggedError<ManagedEndpointProvisioningNotConfigured>()(
35 "ManagedEndpointProvisioningNotConfigured",
36 {
37 userId: Schema.String,
38 environmentId: Schema.String,
39 missingSettings: Schema.Array(
40 Schema.Literals(["managedEndpointBaseDomain", "managedEndpointNamespace"]),
41 ),
42 },
43 ) {
44 override get message(): string {
45 return `Managed endpoint provisioning is not configured for user '${this.userId}', environment '${this.environmentId}': missing ${this.missingSettings.join(", ")}`;
46 }
47 }
48
49 const ManagedEndpointProvisioningStage = Schema.Literals([
50 "derive-environment-hash",
51 "check-tunnel-limit",
52 "reserve-allocation",
53 "ensure-tunnel",
54 "validate-tunnel-response",
55 "record-tunnel",
56 "configure-tunnel",
57 "ensure-dns-record",
58 "record-dns",
59 "get-tunnel-token",
60 "mark-allocation-ready",
61 "load-allocation",
62 "verify-endpoint",
63 "verify-tunnel",
64 "sync-origin",
65 ]);
66
67 const ManagedEndpointProvisioningFailureReason = Schema.Literals([
68 "claim-lost",
69 "endpoint-mismatch",
70 "invalid-tunnel-response",
71 ]);
72
73 export class ManagedEndpointProvisioningFailed extends Schema.TaggedError<ManagedEndpointProvisioningFailed>()(
74 "ManagedEndpointProvisioningFailed",
75 {
76 stage: ManagedEndpointProvisioningStage,
77 reason: Schema.optionalKey(ManagedEndpointProvisioningFailureReason),
78 userId: Schema.String,
79 environmentId: Schema.String,
80 hostname: Schema.optionalKey(Schema.String),
81 tunnelName: Schema.optionalKey(Schema.String),
82 tunnelId: Schema.optionalKey(Schema.String),
83 dnsRecordId: Schema.optionalKey(Schema.String),
84 returnedTunnelName: Schema.optionalKey(Schema.String),
85 returnedTunnelId: Schema.optionalKey(Schema.String),
86 cause: Schema.optional(Schema.Defect()),
87 },
88 ) {
89 override get message(): string {
90 return `Managed endpoint provisioning failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
91 }
92 }
93
94 const ManagedEndpointDeprovisioningStage = Schema.Literals([
95 "load-allocation",
96 "load-tunnel",
97 "claim-release",
98 "claim-deprovision",
99 "delete-dns-record",
100 "delete-tunnel",
101 "remove-allocation",
102 ]);
103
104 export class ManagedEndpointDeprovisioningFailed extends Schema.TaggedError<ManagedEndpointDeprovisioningFailed>()(
105 "ManagedEndpointDeprovisioningFailed",
106 {
107 stage: ManagedEndpointDeprovisioningStage,
108 userId: Schema.String,
109 environmentId: Schema.String,
110 tunnelId: Schema.optionalKey(Schema.String),
111 dnsRecordId: Schema.optionalKey(Schema.String),
112 cause: Schema.Defect(),
113 },
114 ) {
115 override get message(): string {
116 return `Managed endpoint deprovisioning failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
117 }
118 }
119
120 export class ManagedEndpointOriginNotAllowed extends Schema.TaggedError<ManagedEndpointOriginNotAllowed>()(
121 "ManagedEndpointOriginNotAllowed",
122 {
123 userId: Schema.String,
124 environmentId: Schema.String,
125 host: Schema.String,
126 port: Schema.Number,
127 },
128 ) {
129 override get message(): string {
130 return `Managed endpoint origin '${this.host}:${this.port}' is not allowed for user '${this.userId}', environment '${this.environmentId}'`;
131 }
132 }
133
134 export type ManagedEndpointProviderError =
135 | ManagedEndpointProvisioningNotConfigured
136 | ManagedEndpointProvisioningFailed
137 | ManagedEndpointOriginNotAllowed
138 | ManagedTunnelLimits.ManagedTunnelLimitExceeded;
139
140 export interface ManagedEndpointProvisioningResult {
141 readonly endpoint: RelayManagedEndpoint;
142 readonly runtime: RelayManagedEndpointRuntimeConfig;
143 }
144
145 export type ManagedEndpointOriginSyncResult = "ready" | "recovery_required";
146
147 export type ManagedEndpointDeprovisionTarget = ManagedEndpointAllocations.ManagedEndpointAllocation;
148
149 export class ManagedEndpointProvider extends Context.Service<
150 ManagedEndpointProvider,
151 {
152 readonly provision: (input: {
153 readonly userId: string;
154 readonly environmentId: string;
155 readonly origin: RelayManagedEndpointOrigin;
156 /**
157 * Return a ready tunnel that already serves this origin with only a
158 * liveness check and a fresh token, skipping ingress and DNS repair.
159 */
160 readonly reuseReadyTunnel?: boolean;
161 }) => Effect.Effect<ManagedEndpointProvisioningResult, ManagedEndpointProviderError>;
162 readonly reconcileOrigin: (input: {
163 readonly userId: string;
164 readonly environmentId: string;
165 readonly tunnelId: string;
166 readonly origin: RelayManagedEndpointOrigin;
167 readonly endpoint: RelayManagedEndpoint;
168 }) => Effect.Effect<ManagedEndpointOriginSyncResult, ManagedEndpointProviderError>;
169 /** Capture before revocation so a concurrent relink's newer allocation survives deprovision. */
170 readonly prepareDeprovision: (input: {
171 readonly userId: string;
172 readonly environmentId: string;
173 }) => Effect.Effect<
174 ManagedEndpointDeprovisionTarget | null,
175 ManagedEndpointDeprovisioningFailed
176 >;
177 readonly deprovision: (input: {
178 readonly userId: string;
179 readonly environmentId: string;
180 readonly target?: ManagedEndpointDeprovisionTarget | null;
181 }) => Effect.Effect<boolean, ManagedEndpointDeprovisioningFailed>;
182 /** True means the connector token is dead; false means concurrent provisioning kept its tunnel live. */
183 readonly release: (input: {
184 readonly userId: string;
185 readonly environmentId: string;
186 readonly expectedTunnelId?: string;
187 readonly expectedInactiveBefore?: string;
188 readonly expectedStatus?: "inactive" | "down";
189 readonly markReleased?: boolean;
190 }) => Effect.Effect<boolean, ManagedEndpointDeprovisioningFailed>;
191 }
192 >()("t3code-relay/environments/ManagedEndpointProvider") {}
193
194 export interface ManagedEndpointTunnel {
195 readonly id?: string | null;
196 readonly name?: string | null;
197 readonly status?: string | null;
198 readonly createdAt?: string | null;
199 readonly connsInactiveAt?: string | null;
200 readonly deletedAt?: string | null;
201 }
202
203 export interface ManagedEndpointTunnelListRequest {
204 readonly isDeleted: false;
205 readonly name?: string;
206 readonly includePrefix?: string;
207 readonly status?: "inactive" | "down";
208 readonly existedAt?: string;
209 readonly wasInactiveAt?: string;
210 readonly page?: number;
211 readonly perPage?: number;
212 }
213
214 const ManagedEndpointTunnelClientOperation = Schema.Literals([
215 "get",
216 "list",
217 "create",
218 "put-configuration",
219 "get-configuration",
220 "get-token",
221 "delete",
222 ]);
223
224 export class ManagedEndpointTunnelClientError extends Schema.TaggedError<ManagedEndpointTunnelClientError>()(
225 "ManagedEndpointTunnelClientError",
226 {
227 operation: ManagedEndpointTunnelClientOperation,
228 tunnelName: Schema.optionalKey(Schema.String),
229 tunnelId: Schema.optionalKey(Schema.String),
230 cause: Schema.Defect(),
231 },
232 ) {
233 override get message(): string {
234 const target = this.tunnelId ?? this.tunnelName;
235 return `Managed endpoint tunnel provider '${this.operation}' request failed${target === undefined ? "" : ` for '${target}'`}`;
236 }
237 }
238
239 export class ManagedEndpointTunnelClient extends Context.Service<
240 ManagedEndpointTunnelClient,
241 {
242 readonly get: (
243 tunnelId: string,
244 ) => Effect.Effect<ManagedEndpointTunnel, ManagedEndpointTunnelClientError>;
245 readonly list: (
246 request: ManagedEndpointTunnelListRequest,
247 options?: { readonly timeout?: Duration.Input },
248 ) => Effect.Effect<
249 {
250 readonly result: ReadonlyArray<ManagedEndpointTunnel>;
251 readonly resultInfo?: {
252 readonly page?: number | null;
253 readonly perPage?: number | null;
254 readonly totalCount?: number | null;
255 } | null;
256 },
257 ManagedEndpointTunnelClientError
258 >;
259 readonly create: (request: {
260 readonly name: string;
261 readonly configSrc: "cloudflare";
262 }) => Effect.Effect<ManagedEndpointTunnel, ManagedEndpointTunnelClientError>;
263 readonly putConfiguration: (
264 tunnelId: string,
265 config: {
266 readonly ingress: Array<{
267 readonly hostname?: string;
268 readonly service: string;
269 }>;
270 },
271 ) => Effect.Effect<unknown, ManagedEndpointTunnelClientError>;
272 readonly getConfiguration: (tunnelId: string) => Effect.Effect<
273 {
274 readonly ingress: ReadonlyArray<{
275 readonly hostname?: string | null;
276 readonly path?: string | null;
277 readonly service: string;
278 }>;
279 },
280 ManagedEndpointTunnelClientError
281 >;
282 readonly getToken: (
283 tunnelId: string,
284 ) => Effect.Effect<string, ManagedEndpointTunnelClientError>;
285 readonly delete: (tunnelId: string) => Effect.Effect<unknown, ManagedEndpointTunnelClientError>;
286 }
287 >()("t3code-relay/environments/ManagedEndpointProvider/ManagedEndpointTunnelClient") {}
288
289 export const layerTunnelClient = (client: ManagedEndpointTunnelClient["Service"]) =>
290 Layer.succeed(ManagedEndpointTunnelClient, client);
291
292 interface ManagedEndpointCnameRecordInput {
293 readonly type: "CNAME";
294 readonly name: string;
295 readonly content: string;
296 readonly ttl: 1;
297 readonly proxied: true;
298 }
299
300 const ManagedEndpointDnsClientOperation = Schema.Literals([
301 "list-records",
302 "create-record",
303 "update-record",
304 "delete-record",
305 ]);
306
307 export class ManagedEndpointDnsClientError extends Schema.TaggedError<ManagedEndpointDnsClientError>()(
308 "ManagedEndpointDnsClientError",
309 {
310 operation: ManagedEndpointDnsClientOperation,
311 hostname: Schema.optionalKey(Schema.String),
312 dnsRecordId: Schema.optionalKey(Schema.String),
313 cause: Schema.Defect(),
314 },
315 ) {
316 override get message(): string {
317 const target = this.dnsRecordId ?? this.hostname;
318 return `Managed endpoint DNS provider '${this.operation}' request failed${target === undefined ? "" : ` for '${target}'`}`;
319 }
320 }
321
322 export class ManagedEndpointDnsClient extends Context.Service<
323 ManagedEndpointDnsClient,
324 {
325 readonly listRecords: (
326 hostname: string,
327 ) => Effect.Effect<ReadonlyArray<{ readonly id: string }>, ManagedEndpointDnsClientError>;
328 readonly createRecord: (
329 request: ManagedEndpointCnameRecordInput,
330 ) => Effect.Effect<{ readonly id: string }, ManagedEndpointDnsClientError>;
331 readonly updateRecord: (
332 dnsRecordId: string,
333 request: ManagedEndpointCnameRecordInput,
334 ) => Effect.Effect<unknown, ManagedEndpointDnsClientError>;
335 readonly deleteRecord: (
336 dnsRecordId: string,
337 ) => Effect.Effect<unknown, ManagedEndpointDnsClientError>;
338 }
339 >()("t3code-relay/environments/ManagedEndpointProvider/ManagedEndpointDnsClient") {}
340
341 export const layerDnsClient = (client: ManagedEndpointDnsClient["Service"]) =>
342 Layer.succeed(ManagedEndpointDnsClient, client);
343
344 const requireCloudflareSettings = Effect.fnUntraced(function* (
345 settings: RelayConfiguration.RelayConfiguration["Service"],
346 input: { readonly userId: string; readonly environmentId: string },
347 ) {
348 const baseDomain = settings.managedEndpointBaseDomain;
349 const namespace = settings.managedEndpointNamespace;
350 const missingSettings: Array<"managedEndpointBaseDomain" | "managedEndpointNamespace"> = [];
351 if (!baseDomain) {
352 missingSettings.push("managedEndpointBaseDomain");
353 }
354 if (!namespace) {
355 missingSettings.push("managedEndpointNamespace");
356 }
357 if (!baseDomain || !namespace) {
358 return yield* new ManagedEndpointProvisioningNotConfigured({
359 ...input,
360 missingSettings,
361 });
362 }
363 return {
364 baseDomain,
365 namespace,
366 };
367 });
368
369 function formatOriginService(origin: RelayManagedEndpointOrigin): string {
370 const host = origin.localHttpHost.includes(":")
371 ? `[${origin.localHttpHost.replace(/^\[(.*)\]$/u, "$1")}]`
372 : origin.localHttpHost;
373 return `http://${host}:${origin.localHttpPort}`;
374 }
375
376 function normalizeHostname(hostname: string): string {
377 return hostname
378 .trim()
379 .toLowerCase()
380 .replace(/\.$/u, "")
381 .replace(/^\[(.*)\]$/u, "$1");
382 }
383
384 function isLoopbackOrigin(origin: RelayManagedEndpointOrigin): boolean {
385 const hostname = normalizeHostname(origin.localHttpHost);
386 return (
387 (hostname === "127.0.0.1" || hostname === "::1" || hostname === "localhost") &&
388 Number.isInteger(origin.localHttpPort) &&
389 origin.localHttpPort > 0 &&
390 origin.localHttpPort <= 65_535
391 );
392 }
393
394 function isManagedEndpointNotFound(cause: unknown): boolean {
395 if (typeof cause !== "object" || cause === null) {
396 return false;
397 }
398 if (
399 "_tag" in cause &&
400 (cause._tag === "NotFound" ||
401 cause._tag === "TunnelNotFound" ||
402 cause._tag === "RecordNotFound")
403 ) {
404 return true;
405 }
406 if ("status" in cause && cause.status === 404) {
407 return true;
408 }
409 return "cause" in cause && isManagedEndpointNotFound(cause.cause);
410 }
411
412 export class CloudflareApiPaused extends Schema.TaggedError<CloudflareApiPaused>()(
413 "CloudflareApiPaused",
414 { retryAfterMillis: Schema.Number },
415 ) {
416 override get message(): string {
417 return `Cloudflare API calls are paused for ${this.retryAfterMillis}ms after a rate limit`;
418 }
419 }
420
421 export function isCloudflareRateLimited(cause: unknown): boolean {
422 if (typeof cause !== "object" || cause === null) {
423 return false;
424 }
425 if (
426 "_tag" in cause &&
427 (cause._tag === "TooManyRequests" ||
428 cause._tag === "CloudflareRateLimited" ||
429 cause._tag === "CloudflareApiPaused")
430 ) {
431 return true;
432 }
433 if ("status" in cause && cause.status === 429) {
434 return true;
435 }
436 return "cause" in cause && isCloudflareRateLimited(cause.cause);
437 }
438
439 const CLOUDFLARE_DEFAULT_RATE_LIMIT_PAUSE = Duration.seconds(30);
440 const CLOUDFLARE_MAX_RATE_LIMIT_PAUSE = Duration.minutes(2);
441
442 function cloudflareRateLimitPauseMillis(cause: unknown): number {
443 const retryAfter =
444 typeof cause === "object" && cause !== null && "retryAfter" in cause
445 ? cause.retryAfter
446 : undefined;
447 const pause = Duration.isDuration(retryAfter) ? retryAfter : CLOUDFLARE_DEFAULT_RATE_LIMIT_PAUSE;
448 return Duration.toMillis(Duration.min(pause, CLOUDFLARE_MAX_RATE_LIMIT_PAUSE));
449 }
450
451 /**
452 * How long a caller should wait before retrying, when `cause` is a Cloudflare
453 * rate limit or a call refused during the pause that follows one.
454 */
455 export function cloudflareRetryAfterMillis(cause: unknown): number | undefined {
456 for (let current = cause, depth = 0; depth < 8; depth++) {
457 if (typeof current !== "object" || current === null) return undefined;
458 if ("_tag" in current && current._tag === "CloudflareApiPaused") {
459 const retryAfterMillis: unknown = Reflect.get(current, "retryAfterMillis");
460 return typeof retryAfterMillis === "number" ? retryAfterMillis : undefined;
461 }
462 if (
463 ("_tag" in current &&
464 (current._tag === "TooManyRequests" || current._tag === "CloudflareRateLimited")) ||
465 ("status" in current && current.status === 429)
466 ) {
467 return cloudflareRateLimitPauseMillis(current);
468 }
469 if (!("cause" in current)) return undefined;
470 current = current.cause;
471 }
472 return undefined;
473 }
474
475 // The SDK's default policy sleeps through Retry-After inside the request, which
476 // held every caller until its timeout and kept the account over its limit.
477 // Rate limits surface at once instead; other transient failures still retry.
478 const withoutRateLimitRetries: CloudflareRetry.Factory = (lastError) => {
479 const defaults = CloudflareRetry.makeDefault(lastError);
480 return {
481 ...defaults,
482 while: (error) => !isCloudflareRateLimited(error) && (defaults.while?.(error) ?? false),
483 };
484 };
485
486 // Every isolate rereads the shared pause at most this often, so a quiet
487 // period costs one query per isolate rather than one per Cloudflare call.
488 const CLOUDFLARE_PAUSE_REFRESH_MILLIS = 5_000;
489
490 /**
491 * The rate limit is account-wide, so once one call is rejected every other
492 * call is too, from any isolate. Failing them without a request leaves the
493 * account room to recover instead of extending the limit.
494 */
495 const makeCloudflareApiGate = (alchemyRuntimeContext: Alchemy.BaseRuntimeContext) => {
496 let pausedUntilMillis = 0;
497 let checkedAtMillis = Number.NEGATIVE_INFINITY;
498 return (pause: CloudflareApiPause.CloudflareApiPause["Service"]) => {
499 const recordRateLimit = Effect.fn("relay.cloudflare_api_pause.rate_limited")(function* (
500 cause: unknown,
501 ) {
502 const pauseMillis = cloudflareRateLimitPauseMillis(cause);
503 const until = (yield* Clock.currentTimeMillis) + pauseMillis;
504 pausedUntilMillis = Math.max(pausedUntilMillis, until);
505 yield* Effect.annotateCurrentSpan({ "relay.cloudflare.pause_ms": pauseMillis });
506 yield* pause.pauseUntil(until);
507 });
508 return <A, E>(
509 call: Effect.Effect<A, E, Alchemy.RuntimeContext>,
510 timeout: Duration.Input = "8 seconds",
511 ): Effect.Effect<A, E | CloudflareApiPaused | Cause.TimeoutError> =>
512 Effect.gen(function* () {
513 const now = yield* Clock.currentTimeMillis;
514 if (now >= pausedUntilMillis && now - checkedAtMillis >= CLOUDFLARE_PAUSE_REFRESH_MILLIS) {
515 checkedAtMillis = now;
516 // Read first: a 429 recorded while the read is in flight must win.
517 const shared = yield* pause.pausedUntilMillis;
518 pausedUntilMillis = Math.max(pausedUntilMillis, shared);
519 }
520 // A paused call never reaches Cloudflare, so it leaves no 429 behind.
521 // Its own span keeps a storm visible to the rate-limit monitors.
522 if (now < pausedUntilMillis) {
523 return yield* new CloudflareApiPaused({ retryAfterMillis: pausedUntilMillis - now }).pipe(
524 Effect.withSpan("relay.cloudflare_api_pause.rejected"),
525 );
526 }
527 return yield* call.pipe(
528 Effect.provideService(CloudflareRetry.Retry, withoutRateLimitRetries),
529 Effect.timeout(timeout),
530 Effect.tapError((cause) =>
531 isCloudflareRateLimited(cause) ? recordRateLimit(cause) : Effect.void,
532 ),
533 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
534 );
535 });
536 };
537 };
538
539 /**
540 * Cloudflare refuses to delete a tunnel while a connector is still attached,
541 * either one that has not finished draining or another runtime still serving
542 * the tunnel.
543 */
544 function isManagedEndpointTunnelInUse(cause: unknown): boolean {
545 if (typeof cause !== "object" || cause === null) {
546 return false;
547 }
548 if (
549 "message" in cause &&
550 typeof cause.message === "string" &&
551 cause.message.includes("has active connections")
552 ) {
553 return true;
554 }
555 return "cause" in cause && isManagedEndpointTunnelInUse(cause.cause);
556 }
557
558 type ManagedEndpointClientError = ManagedEndpointTunnelClientError | ManagedEndpointDnsClientError;
559
560 const ignoreNotFound = <A>(
561 effect: Effect.Effect<A, ManagedEndpointClientError>,
562 ): Effect.Effect<void, ManagedEndpointClientError> =>
563 effect.pipe(
564 Effect.asVoid,
565 Effect.catchTags({
566 ManagedEndpointTunnelClientError: (error) =>
567 isManagedEndpointNotFound(error.cause) ? Effect.void : Effect.fail(error),
568 ManagedEndpointDnsClientError: (error) =>
569 isManagedEndpointNotFound(error.cause) ? Effect.void : Effect.fail(error),
570 }),
571 );
572
573 const make = Effect.gen(function* () {
574 const config = yield* RelayConfiguration.RelayConfiguration;
575 const digest = yield* Digest.Digest;
576 const tunnels = yield* ManagedEndpointTunnelClient;
577 const dns = yield* ManagedEndpointDnsClient;
578 const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;
579 const tunnelLimits = yield* ManagedTunnelLimits.ManagedTunnelLimits;
580
581 const updateExistingDnsRecords = Effect.fnUntraced(function* (
582 records: ReadonlyArray<{ readonly id: string }>,
583 preferredDnsRecordId: string | null,
584 dnsRecord: ManagedEndpointCnameRecordInput,
585 ) {
586 const keptRecord = records.find((record) => record.id === preferredDnsRecordId) ?? records[0];
587 if (keptRecord === undefined) {
588 return null;
589 }
590 yield* Effect.forEach(
591 records,
592 (record) => (record.id === keptRecord.id ? Effect.void : dns.deleteRecord(record.id)),
593 { discard: true },
594 );
595 yield* dns.updateRecord(keptRecord.id, dnsRecord);
596 return keptRecord.id;
597 });
598
599 const ensureDnsRecord = Effect.fnUntraced(function* (
600 hostname: string,
601 preferredDnsRecordId: string | null,
602 dnsRecord: ManagedEndpointCnameRecordInput,
603 ) {
604 if (preferredDnsRecordId !== null) {
605 const checkpointedRecordUpdated = yield* dns
606 .updateRecord(preferredDnsRecordId, dnsRecord)
607 .pipe(
608 Effect.as(true),
609 Effect.catchTags({
610 ManagedEndpointDnsClientError: (error) =>
611 isManagedEndpointNotFound(error.cause) ? Effect.succeed(false) : Effect.fail(error),
612 }),
613 );
614 if (checkpointedRecordUpdated) {
615 return preferredDnsRecordId;
616 }
617 }
618 const existingDnsRecords = yield* dns.listRecords(hostname);
619 const existingDnsRecordId = yield* updateExistingDnsRecords(
620 existingDnsRecords,
621 preferredDnsRecordId,
622 dnsRecord,
623 );
624 if (existingDnsRecordId !== null) {
625 return existingDnsRecordId;
626 }
627 return yield* dns.createRecord(dnsRecord).pipe(
628 Effect.map((record) => record.id),
629 Effect.catchTags({
630 ManagedEndpointDnsClientError: (createError) =>
631 Effect.gen(function* () {
632 let records = yield* dns.listRecords(hostname);
633 for (let attempt = 0; records.length === 0 && attempt < 4; attempt++) {
634 yield* Effect.sleep("200 millis");
635 records = yield* dns.listRecords(hostname);
636 }
637 return records;
638 }).pipe(
639 Effect.flatMap((records) =>
640 records.length > 0
641 ? updateExistingDnsRecords(records, preferredDnsRecordId, dnsRecord)
642 : Effect.fail(createError),
643 ),
644 Effect.filterOrFail(
645 (dnsRecordId) => dnsRecordId !== null,
646 () => createError,
647 ),
648 ),
649 }),
650 );
651 });
652
653 // Hosts ask for recovery whenever their connector cannot register, mostly
654 // for local reasons a fresh provision cannot fix. Those requests outnumber
655 // every other Cloudflare caller, so a tunnel that is ready for the same
656 // origin costs two reads instead of a full provision.
657 const reuseReadyTunnel = Effect.fnUntraced(function* (
658 allocation: ManagedEndpointAllocations.ManagedEndpointAllocation,
659 origin: RelayManagedEndpointOrigin,
660 ) {
661 const { tunnelId } = allocation;
662 if (
663 tunnelId === null ||
664 allocation.readyAt === null ||
665 allocation.dnsRecordId === null ||
666 allocation.tunnelReleasedAt !== null ||
667 allocation.origin?.localHttpHost !== origin.localHttpHost ||
668 allocation.origin.localHttpPort !== origin.localHttpPort
669 ) {
670 return Option.none<ManagedEndpointProvisioningResult>();
671 }
672 const failed = (
673 stage: "verify-tunnel" | "get-tunnel-token",
674 cause: ManagedEndpointTunnelClientError,
675 ) =>
676 new ManagedEndpointProvisioningFailed({
677 userId: allocation.userId,
678 environmentId: allocation.environmentId,
679 stage,
680 hostname: allocation.hostname,
681 tunnelName: allocation.tunnelName,
682 tunnelId,
683 cause,
684 });
685 const recorded = yield* tunnels.get(tunnelId).pipe(
686 Effect.asSome,
687 Effect.catchTags({
688 ManagedEndpointTunnelClientError: (cause) =>
689 isManagedEndpointNotFound(cause.cause)
690 ? Effect.succeedNone
691 : Effect.fail(failed("verify-tunnel", cause)),
692 }),
693 );
694 if (Option.isNone(recorded) || recorded.value.deletedAt) {
695 return Option.none<ManagedEndpointProvisioningResult>();
696 }
697 const connectorToken = yield* tunnels
698 .getToken(tunnelId)
699 .pipe(Effect.mapError((cause) => failed("get-tunnel-token", cause)));
700 yield* Effect.annotateCurrentSpan({ "relay.managed_endpoint.reused_ready_tunnel": true });
701 return Option.some<ManagedEndpointProvisioningResult>({
702 endpoint: managedEndpointForHostname(allocation.hostname),
703 runtime: {
704 providerKind: "cloudflare_tunnel",
705 connectorToken,
706 tunnelId,
707 tunnelName: allocation.tunnelName,
708 },
709 });
710 });
711
712 const prepareDeprovision = Effect.fn("relay.managed_endpoint_provider.prepare_deprovision")(
713 function* (input: { readonly userId: string; readonly environmentId: string }) {
714 return yield* allocations.get(input).pipe(
715 Effect.mapError(
716 (cause) =>
717 new ManagedEndpointDeprovisioningFailed({
718 ...input,
719 stage: "load-allocation",
720 cause,
721 }),
722 ),
723 );
724 },
725 );
726
727 const reconcileOrigin = Effect.fn("relay.managed_endpoint_provider.reconcile_origin")(
728 function* (input: {
729 readonly userId: string;
730 readonly environmentId: string;
731 readonly tunnelId: string;
732 readonly origin: RelayManagedEndpointOrigin;
733 readonly endpoint: RelayManagedEndpoint;
734 }) {
735 if (!isLoopbackOrigin(input.origin)) {
736 return yield* new ManagedEndpointOriginNotAllowed({
737 userId: input.userId,
738 environmentId: input.environmentId,
739 host: input.origin.localHttpHost,
740 port: input.origin.localHttpPort,
741 });
742 }
743 const allocation = yield* allocations.get(input).pipe(
744 Effect.mapError(
745 (cause) =>
746 new ManagedEndpointProvisioningFailed({
747 ...input,
748 stage: "load-allocation",
749 cause,
750 }),
751 ),
752 );
753 if (
754 allocation === null ||
755 allocation.tunnelId !== input.tunnelId ||
756 allocation.dnsRecordId === null ||
757 allocation.readyAt === null
758 ) {
759 return "recovery_required";
760 }
761 const cf = yield* requireCloudflareSettings(config, input);
762 const recordedEndpoint = ManagedEndpointAllocations.resolveReadyManagedEndpoint({
763 allocation,
764 baseDomain: cf.baseDomain,
765 });
766 if (
767 recordedEndpoint === null ||
768 recordedEndpoint.httpBaseUrl !== input.endpoint.httpBaseUrl ||
769 recordedEndpoint.wsBaseUrl !== input.endpoint.wsBaseUrl ||
770 recordedEndpoint.providerKind !== input.endpoint.providerKind
771 ) {
772 return yield* new ManagedEndpointProvisioningFailed({
773 ...input,
774 stage: "verify-endpoint",
775 reason: "endpoint-mismatch",
776 hostname: allocation.hostname,
777 });
778 }
779 const verifyTunnel = <A>(read: Effect.Effect<A, ManagedEndpointTunnelClientError>) =>
780 read.pipe(
781 Effect.asSome,
782 Effect.catchTags({
783 ManagedEndpointTunnelClientError: (cause) =>
784 isManagedEndpointNotFound(cause.cause)
785 ? Effect.succeedNone
786 : Effect.fail(
787 new ManagedEndpointProvisioningFailed({
788 userId: input.userId,
789 environmentId: input.environmentId,
790 stage: "verify-tunnel",
791 tunnelId: input.tunnelId,
792 cause,
793 }),
794 ),
795 }),
796 );
797 // Released records retain tunnel ids; verify Cloudflare still has the tunnel before reconnecting.
798 const recorded = yield* verifyTunnel(tunnels.get(input.tunnelId));
799 if (Option.isNone(recorded) || recorded.value.deletedAt) {
800 return "recovery_required";
801 }
802 const originService = formatOriginService(input.origin);
803 if (
804 allocation.origin?.localHttpHost === input.origin.localHttpHost &&
805 allocation.origin.localHttpPort === input.origin.localHttpPort
806 ) {
807 // Live ingress can drift from the recorded origin; only a matching rule skips the rewrite.
808 const configuration = yield* verifyTunnel(tunnels.getConfiguration(input.tunnelId));
809 if (Option.isNone(configuration)) {
810 return "recovery_required";
811 }
812 const hostname = normalizeHostname(allocation.hostname);
813 // Cloudflare routes by the first matching rule, so an earlier wildcard or catch-all wins.
814 const rule = configuration.value.ingress.find((entry) => {
815 if (entry.hostname == null) return true;
816 const candidate = normalizeHostname(entry.hostname);
817 return (
818 candidate === hostname ||
819 (candidate.startsWith("*.") && hostname.endsWith(candidate.slice(1)))
820 );
821 });
822 // A path-restricted rule leaves other paths to later rules, so it cannot prove routing.
823 if (rule?.service === originService && !rule.path) {
824 return "ready";
825 }
826 }
827
828 const updated = yield* allocations
829 .withClaimedTunnel(
830 {
831 userId: input.userId,
832 environmentId: input.environmentId,
833 tunnelId: input.tunnelId,
834 generation: allocation.generation,
835 },
836 tunnels
837 .putConfiguration(input.tunnelId, {
838 ingress: [
839 { hostname: allocation.hostname, service: originService },
840 { service: "http_status:404" },
841 ],
842 })
843 .pipe(
844 Effect.as("configured" as const),
845 Effect.catchTags({
846 ManagedEndpointTunnelClientError: (error) =>
847 isManagedEndpointNotFound(error.cause)
848 ? Effect.succeed("missing" as const)
849 : Effect.fail(error),
850 }),
851 Effect.filterOrElse(
852 (result): result is "missing" => result === "missing",
853 () =>
854 allocations
855 .markReady({
856 ...input,
857 generation: allocation.generation,
858 })
859 .pipe(
860 Effect.map((updated) =>
861 updated ? ("configured" as const) : ("stale" as const),
862 ),
863 ),
864 ),
865 ),
866 )
867 .pipe(
868 Effect.mapError(
869 (cause) =>
870 new ManagedEndpointProvisioningFailed({
871 ...input,
872 stage: "sync-origin",
873 cause,
874 }),
875 ),
876 );
877 if (Option.isNone(updated) || updated.value === "stale") {
878 return yield* new ManagedEndpointProvisioningFailed({
879 ...input,
880 stage: "sync-origin",
881 reason: "claim-lost",
882 });
883 }
884 return updated.value === "configured" ? "ready" : "recovery_required";
885 },
886 );
887
888 return ManagedEndpointProvider.of({
889 prepareDeprovision,
890 reconcileOrigin,
891 deprovision: Effect.fn("relay.managed_endpoint_provider.deprovision")(function* (input) {
892 yield* Effect.annotateCurrentSpan({
893 "relay.user_id": input.userId,
894 "relay.environment_id": input.environmentId,
895 });
896 const allocation =
897 input.target === undefined ? yield* prepareDeprovision(input) : input.target;
898 if (allocation === null) {
899 return true;
900 }
901 const claimedGeneration = yield* allocations
902 .claimDeprovision({
903 userId: input.userId,
904 environmentId: input.environmentId,
905 generation: allocation.generation,
906 })
907 .pipe(
908 Effect.mapError(
909 (cause) =>
910 new ManagedEndpointDeprovisioningFailed({
911 ...input,
912 stage: "claim-deprovision",
913 ...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),
914 ...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),
915 cause,
916 }),
917 ),
918 );
919 if (claimedGeneration === null) {
920 return false;
921 }
922 const tunnelId = allocation.tunnelId;
923 let tunnelDeleted = false;
924 const deprovision = Effect.gen(function* () {
925 const dnsRecordId = allocation.dnsRecordId;
926 if (dnsRecordId !== null) {
927 yield* ignoreNotFound(dns.deleteRecord(dnsRecordId)).pipe(
928 Effect.mapError(
929 (cause) =>
930 new ManagedEndpointDeprovisioningFailed({
931 ...input,
932 stage: "delete-dns-record",
933 dnsRecordId,
934 cause,
935 }),
936 ),
937 );
938 }
939 if (tunnelId !== null) {
940 yield* ignoreNotFound(tunnels.delete(tunnelId)).pipe(
941 Effect.mapError(
942 (cause) =>
943 new ManagedEndpointDeprovisioningFailed({
944 ...input,
945 stage: "delete-tunnel",
946 tunnelId,
947 cause,
948 }),
949 ),
950 );
951 tunnelDeleted = true;
952 }
953 return yield* allocations
954 .removeClaimed({
955 userId: input.userId,
956 environmentId: input.environmentId,
957 generation: claimedGeneration,
958 })
959 .pipe(
960 Effect.mapError(
961 (cause) =>
962 new ManagedEndpointDeprovisioningFailed({
963 ...input,
964 stage: "remove-allocation",
965 ...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),
966 ...(allocation.dnsRecordId === null
967 ? {}
968 : { dnsRecordId: allocation.dnsRecordId }),
969 cause,
970 }),
971 ),
972 );
973 });
974 if (tunnelId === null) {
975 return yield* deprovision;
976 }
977 const removed = yield* allocations
978 .withClaimedTunnel(
979 {
980 userId: input.userId,
981 environmentId: input.environmentId,
982 tunnelId,
983 generation: claimedGeneration,
984 },
985 deprovision,
986 )
987 .pipe(
988 Effect.catchTags({
989 ManagedEndpointAllocationPersistenceError: (cause) =>
990 Effect.fail(
991 new ManagedEndpointDeprovisioningFailed({
992 ...input,
993 stage: "claim-deprovision",
994 tunnelId,
995 cause,
996 }),
997 ),
998 }),
999 // The rollback keeps the deleted tunnel's id; mark it released so the tunnel limit stops
1000 // counting it. onError also covers an interrupted unlink, which rolls back the same way.
1001 Effect.onError(() =>
1002 tunnelDeleted
1003 ? allocations
1004 .claimRelease({
1005 userId: input.userId,
1006 environmentId: input.environmentId,
1007 tunnelId,
1008 generation: claimedGeneration,
1009 markReleased: true,
1010 })
1011 .pipe(
1012 Effect.catch((error) =>
1013 Effect.logWarning("Failed to mark a deleted managed tunnel released", {
1014 userId: input.userId,
1015 environmentId: input.environmentId,
1016 tunnelId,
1017 error: error.message,
1018 }),
1019 ),
1020 )
1021 : Effect.void,
1022 ),
1023 );
1024 return Option.getOrElse(removed, () => false);
1025 }),
1026 release: Effect.fn("relay.managed_endpoint_provider.release")(function* (input) {
1027 yield* Effect.annotateCurrentSpan({
1028 "relay.user_id": input.userId,
1029 "relay.environment_id": input.environmentId,
1030 });
1031 const allocation = yield* allocations.get(input).pipe(
1032 Effect.mapError(
1033 (cause) =>
1034 new ManagedEndpointDeprovisioningFailed({
1035 ...input,
1036 stage: "load-allocation",
1037 cause,
1038 }),
1039 ),
1040 );
1041 const tunnelId = allocation?.tunnelId ?? null;
1042 if (allocation === null || tunnelId === null) {
1043 return true;
1044 }
1045 if (input.expectedTunnelId !== undefined && input.expectedTunnelId !== tunnelId) {
1046 return false;
1047 }
1048 // Claim before deleting: concurrent provisioning can advance the generation and reuse the tunnel.
1049 const claimedGeneration = yield* allocations
1050 .claimRelease({
1051 userId: input.userId,
1052 environmentId: input.environmentId,
1053 tunnelId,
1054 generation: allocation.generation,
1055 })
1056 .pipe(
1057 Effect.mapError(
1058 (cause) =>
1059 new ManagedEndpointDeprovisioningFailed({
1060 ...input,
1061 stage: "claim-release",
1062 tunnelId,
1063 cause,
1064 }),
1065 ),
1066 );
1067 if (claimedGeneration === null) {
1068 return false;
1069 }
1070 const confirmTunnelGone = (
1071 failure: ManagedEndpointDeprovisioningFailed,
1072 ): Effect.Effect<void, ManagedEndpointDeprovisioningFailed> =>
1073 tunnels.get(tunnelId).pipe(
1074 Effect.andThen(Effect.fail(failure)),
1075 Effect.catchTags({
1076 ManagedEndpointTunnelClientError: (lookupFailure) =>
1077 isManagedEndpointNotFound(lookupFailure.cause) ? Effect.void : Effect.fail(failure),
1078 }),
1079 );
1080 const deleteTunnel = ignoreNotFound(tunnels.delete(tunnelId)).pipe(
1081 Effect.mapError(
1082 (cause) =>
1083 new ManagedEndpointDeprovisioningFailed({
1084 ...input,
1085 stage: "delete-tunnel",
1086 tunnelId,
1087 cause,
1088 }),
1089 ),
1090 );
1091 if (input.expectedInactiveBefore !== undefined && input.expectedStatus !== undefined) {
1092 const expectedStatus = input.expectedStatus;
1093 const inactiveBefore = input.expectedInactiveBefore;
1094 const currentTunnel = yield* tunnels.get(tunnelId).pipe(
1095 Effect.asSome,
1096 Effect.catchTags({
1097 ManagedEndpointTunnelClientError: (cause) =>
1098 isManagedEndpointNotFound(cause.cause)
1099 ? Effect.succeedNone
1100 : Effect.fail(
1101 new ManagedEndpointDeprovisioningFailed({
1102 ...input,
1103 stage: "load-tunnel",
1104 tunnelId,
1105 cause,
1106 }),
1107 ),
1108 }),
1109 );
1110 if (Option.isNone(currentTunnel)) {
1111 return true;
1112 }
1113 const inactiveAt =
1114 expectedStatus === "down"
1115 ? currentTunnel.value.connsInactiveAt
1116 : currentTunnel.value.createdAt;
1117 if (
1118 currentTunnel.value.id !== tunnelId ||
1119 currentTunnel.value.status !== expectedStatus ||
1120 typeof inactiveAt !== "string"
1121 ) {
1122 return false;
1123 }
1124 const inactiveTime = DateTime.make(inactiveAt);
1125 const cutoff = DateTime.make(inactiveBefore);
1126 if (
1127 Option.isNone(inactiveTime) ||
1128 Option.isNone(cutoff) ||
1129 inactiveTime.value.epochMilliseconds > cutoff.value.epochMilliseconds
1130 ) {
1131 return false;
1132 }
1133 }
1134 const released = yield* allocations
1135 .withClaimedTunnel(
1136 {
1137 userId: input.userId,
1138 environmentId: input.environmentId,
1139 tunnelId,
1140 generation: claimedGeneration,
1141 },
1142 Effect.gen(function* () {
1143 const finalGeneration = yield* allocations
1144 .claimRelease({
1145 userId: input.userId,
1146 environmentId: input.environmentId,
1147 tunnelId,
1148 generation: claimedGeneration,
1149 ...(input.markReleased === true ? { markReleased: true } : {}),
1150 })
1151 .pipe(
1152 Effect.mapError(
1153 (cause) =>
1154 new ManagedEndpointDeprovisioningFailed({
1155 ...input,
1156 stage: "claim-release",
1157 tunnelId,
1158 cause,
1159 }),
1160 ),
1161 );
1162 if (finalGeneration === null) {
1163 return false;
1164 }
1165 // A timed-out deletion may have succeeded; confirm Cloudflare state before rolling back the claim.
1166 return yield* deleteTunnel.pipe(
1167 Effect.as(true),
1168 Effect.catchTags({
1169 ManagedEndpointDeprovisioningFailed: (failure) =>
1170 isManagedEndpointTunnelInUse(failure.cause)
1171 ? Effect.fail(failure)
1172 : confirmTunnelGone(failure).pipe(Effect.as(true)),
1173 }),
1174 );
1175 }),
1176 )
1177 .pipe(
1178 Effect.catchTags({
1179 // Return false only after the refused deletion rolls back the release marker.
1180 ManagedEndpointDeprovisioningFailed: (failure) =>
1181 isManagedEndpointTunnelInUse(failure.cause)
1182 ? Effect.succeedSome(false)
1183 : Effect.fail(failure),
1184 ManagedEndpointAllocationPersistenceError: (cause) =>
1185 Effect.fail(
1186 new ManagedEndpointDeprovisioningFailed({
1187 ...input,
1188 stage: "claim-release",
1189 tunnelId,
1190 cause,
1191 }),
1192 ),
1193 }),
1194 );
1195 // Keep the allocation recorded so offline environments stay authorized and report offline, not unauthorized.
1196 return Option.getOrElse(released, () => false);
1197 }),
1198 provision: Effect.fn("relay.managed_endpoint_provider.provision")(function* (input) {
1199 yield* Effect.annotateCurrentSpan({
1200 "relay.user_id": input.userId,
1201 "relay.environment_id": input.environmentId,
1202 "relay.managed_endpoint.origin_host": input.origin.localHttpHost,
1203 "relay.managed_endpoint.origin_port": input.origin.localHttpPort,
1204 });
1205 if (!isLoopbackOrigin(input.origin)) {
1206 return yield* new ManagedEndpointOriginNotAllowed({
1207 userId: input.userId,
1208 environmentId: input.environmentId,
1209 host: input.origin.localHttpHost,
1210 port: input.origin.localHttpPort,
1211 });
1212 }
1213 const cf = yield* requireCloudflareSettings(config, input);
1214 const environmentHash = yield* digest
1215 .digest(
1216 Digest.sha256,
1217 new TextEncoder().encode(
1218 managedEndpointDigestInput(cf.namespace, input.userId, input.environmentId),
1219 ),
1220 )
1221 .pipe(
1222 Effect.map(Hex.encode),
1223 Effect.mapError(
1224 (cause) =>
1225 new ManagedEndpointProvisioningFailed({
1226 userId: input.userId,
1227 environmentId: input.environmentId,
1228 stage: "derive-environment-hash",
1229 cause,
1230 }),
1231 ),
1232 );
1233 const requestedHostname = managedEndpointHostname(
1234 cf.namespace,
1235 cf.baseDomain,
1236 environmentHash,
1237 );
1238 const requestedTunnelName = managedEndpointTunnelName(cf.namespace, environmentHash);
1239 const reserveAllocation = allocations
1240 .reserve({
1241 userId: input.userId,
1242 environmentId: input.environmentId,
1243 hostname: requestedHostname,
1244 tunnelName: requestedTunnelName,
1245 })
1246 .pipe(
1247 Effect.mapError(
1248 (cause) =>
1249 new ManagedEndpointProvisioningFailed({
1250 userId: input.userId,
1251 environmentId: input.environmentId,
1252 stage: "reserve-allocation",
1253 hostname: requestedHostname,
1254 tunnelName: requestedTunnelName,
1255 cause,
1256 }),
1257 ),
1258 );
1259 const allocation = yield* tunnelLimits
1260 .withCapacity(
1261 { userId: input.userId, environmentId: input.environmentId },
1262 reserveAllocation,
1263 )
1264 .pipe(
1265 Effect.catchTags({
1266 ManagedTunnelLimitPersistenceError: (cause) =>
1267 Effect.fail(
1268 new ManagedEndpointProvisioningFailed({
1269 userId: input.userId,
1270 environmentId: input.environmentId,
1271 stage: "check-tunnel-limit",
1272 hostname: requestedHostname,
1273 tunnelName: requestedTunnelName,
1274 cause,
1275 }),
1276 ),
1277 }),
1278 );
1279 const { hostname, tunnelName } = allocation;
1280
1281 if (input.reuseReadyTunnel === true) {
1282 const reused = yield* reuseReadyTunnel(allocation, input.origin);
1283 if (Option.isSome(reused)) {
1284 return reused.value;
1285 }
1286 }
1287
1288 const tunnelResponse = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe(
1289 Effect.map((tunnels) => tunnels.result),
1290 Effect.map(Arr.findFirst((tunnel) => tunnel.name === tunnelName)),
1291 Effect.flatMap(
1292 Option.match({
1293 onSome: (tunnel) => Effect.succeed(tunnel),
1294 onNone: () => tunnels.create({ name: tunnelName, configSrc: "cloudflare" }),
1295 }),
1296 ),
1297 Effect.mapError(
1298 (cause) =>
1299 new ManagedEndpointProvisioningFailed({
1300 userId: input.userId,
1301 environmentId: input.environmentId,
1302 stage: "ensure-tunnel",
1303 hostname,
1304 tunnelName,
1305 cause,
1306 }),
1307 ),
1308 );
1309 if (!tunnelResponse.id || tunnelResponse.name !== tunnelName) {
1310 return yield* new ManagedEndpointProvisioningFailed({
1311 userId: input.userId,
1312 environmentId: input.environmentId,
1313 stage: "validate-tunnel-response",
1314 reason: "invalid-tunnel-response",
1315 hostname,
1316 tunnelName,
1317 ...(tunnelResponse.id ? { returnedTunnelId: tunnelResponse.id } : {}),
1318 ...(tunnelResponse.name ? { returnedTunnelName: tunnelResponse.name } : {}),
1319 });
1320 }
1321 const tunnel = { id: tunnelResponse.id, name: tunnelResponse.name };
1322 const tunnelGeneration = yield* allocations
1323 .recordTunnel({
1324 userId: input.userId,
1325 environmentId: input.environmentId,
1326 tunnelId: tunnel.id,
1327 generation: allocation.generation,
1328 })
1329 .pipe(
1330 Effect.mapError(
1331 (cause) =>
1332 new ManagedEndpointProvisioningFailed({
1333 userId: input.userId,
1334 environmentId: input.environmentId,
1335 stage: "record-tunnel",
1336 hostname,
1337 tunnelName,
1338 tunnelId: tunnel.id,
1339 cause,
1340 }),
1341 ),
1342 );
1343 if (tunnelGeneration === null) {
1344 // A newer provision can adopt this tunnel by name after our claim fails; leave it available.
1345 return yield* new ManagedEndpointProvisioningFailed({
1346 userId: input.userId,
1347 environmentId: input.environmentId,
1348 stage: "record-tunnel",
1349 reason: "claim-lost",
1350 hostname,
1351 tunnelName,
1352 tunnelId: tunnel.id,
1353 });
1354 }
1355
1356 const configured = yield* allocations
1357 .withClaimedTunnel(
1358 {
1359 userId: input.userId,
1360 environmentId: input.environmentId,
1361 tunnelId: tunnel.id,
1362 generation: tunnelGeneration,
1363 },
1364 tunnels
1365 .putConfiguration(tunnel.id, {
1366 ingress: [
1367 {
1368 hostname,
1369 service: formatOriginService(input.origin),
1370 },
1371 { service: "http_status:404" },
1372 ],
1373 })
1374 .pipe(
1375 Effect.mapError(
1376 (cause) =>
1377 new ManagedEndpointProvisioningFailed({
1378 userId: input.userId,
1379 environmentId: input.environmentId,
1380 stage: "configure-tunnel",
1381 hostname,
1382 tunnelName,
1383 tunnelId: tunnel.id,
1384 cause,
1385 }),
1386 ),
1387 ),
1388 )
1389 .pipe(
1390 Effect.catchTags({
1391 ManagedEndpointAllocationPersistenceError: (cause) =>
1392 Effect.fail(
1393 new ManagedEndpointProvisioningFailed({
1394 userId: input.userId,
1395 environmentId: input.environmentId,
1396 stage: "configure-tunnel",
1397 hostname,
1398 tunnelName,
1399 tunnelId: tunnel.id,
1400 cause,
1401 }),
1402 ),
1403 }),
1404 );
1405 if (Option.isNone(configured)) {
1406 return yield* new ManagedEndpointProvisioningFailed({
1407 userId: input.userId,
1408 environmentId: input.environmentId,
1409 stage: "configure-tunnel",
1410 reason: "claim-lost",
1411 hostname,
1412 tunnelName,
1413 tunnelId: tunnel.id,
1414 });
1415 }
1416
1417 const dnsRecord = {
1418 type: "CNAME",
1419 name: hostname,
1420 content: `${tunnel.id}.cfargotunnel.com`,
1421 ttl: 1,
1422 proxied: true,
1423 } as const;
1424
1425 const recordedDns = yield* allocations
1426 .withClaimedTunnel(
1427 {
1428 userId: input.userId,
1429 environmentId: input.environmentId,
1430 tunnelId: tunnel.id,
1431 generation: tunnelGeneration,
1432 },
1433 Effect.gen(function* () {
1434 const dnsRecordId = yield* ensureDnsRecord(
1435 hostname,
1436 allocation.dnsRecordId,
1437 dnsRecord,
1438 ).pipe(
1439 Effect.mapError(
1440 (cause) =>
1441 new ManagedEndpointProvisioningFailed({
1442 userId: input.userId,
1443 environmentId: input.environmentId,
1444 stage: "ensure-dns-record",
1445 hostname,
1446 tunnelName,
1447 tunnelId: tunnel.id,
1448 ...(allocation.dnsRecordId === null
1449 ? {}
1450 : { dnsRecordId: allocation.dnsRecordId }),
1451 cause,
1452 }),
1453 ),
1454 );
1455 const dnsGeneration = yield* allocations
1456 .recordDns({
1457 userId: input.userId,
1458 environmentId: input.environmentId,
1459 dnsRecordId,
1460 tunnelId: tunnel.id,
1461 generation: tunnelGeneration,
1462 })
1463 .pipe(
1464 Effect.mapError(
1465 (cause) =>
1466 new ManagedEndpointProvisioningFailed({
1467 userId: input.userId,
1468 environmentId: input.environmentId,
1469 stage: "record-dns",
1470 hostname,
1471 tunnelName,
1472 tunnelId: tunnel.id,
1473 dnsRecordId,
1474 cause,
1475 }),
1476 ),
1477 );
1478 if (dnsGeneration === null) {
1479 return yield* new ManagedEndpointProvisioningFailed({
1480 userId: input.userId,
1481 environmentId: input.environmentId,
1482 stage: "record-dns",
1483 reason: "claim-lost",
1484 hostname,
1485 tunnelName,
1486 tunnelId: tunnel.id,
1487 dnsRecordId,
1488 });
1489 }
1490 return { dnsRecordId, dnsGeneration };
1491 }),
1492 )
1493 .pipe(
1494 Effect.catchTags({
1495 ManagedEndpointAllocationPersistenceError: (cause) =>
1496 Effect.fail(
1497 new ManagedEndpointProvisioningFailed({
1498 userId: input.userId,
1499 environmentId: input.environmentId,
1500 stage: "record-dns",
1501 hostname,
1502 tunnelName,
1503 tunnelId: tunnel.id,
1504 cause,
1505 }),
1506 ),
1507 }),
1508 );
1509 if (Option.isNone(recordedDns)) {
1510 return yield* new ManagedEndpointProvisioningFailed({
1511 userId: input.userId,
1512 environmentId: input.environmentId,
1513 stage: "record-dns",
1514 reason: "claim-lost",
1515 hostname,
1516 tunnelName,
1517 tunnelId: tunnel.id,
1518 });
1519 }
1520 const { dnsRecordId, dnsGeneration } = recordedDns.value;
1521
1522 const connectorToken = yield* tunnels.getToken(tunnel.id).pipe(
1523 Effect.mapError(
1524 (cause) =>
1525 new ManagedEndpointProvisioningFailed({
1526 userId: input.userId,
1527 environmentId: input.environmentId,
1528 stage: "get-tunnel-token",
1529 hostname,
1530 tunnelName,
1531 tunnelId: tunnel.id,
1532 dnsRecordId,
1533 cause,
1534 }),
1535 ),
1536 );
1537 const ready = yield* allocations
1538 .markReady({
1539 userId: input.userId,
1540 environmentId: input.environmentId,
1541 tunnelId: tunnel.id,
1542 generation: dnsGeneration,
1543 origin: input.origin,
1544 })
1545 .pipe(
1546 Effect.mapError(
1547 (cause) =>
1548 new ManagedEndpointProvisioningFailed({
1549 userId: input.userId,
1550 environmentId: input.environmentId,
1551 stage: "mark-allocation-ready",
1552 hostname,
1553 tunnelName,
1554 tunnelId: tunnel.id,
1555 dnsRecordId,
1556 cause,
1557 }),
1558 ),
1559 );
1560 if (!ready) {
1561 return yield* new ManagedEndpointProvisioningFailed({
1562 userId: input.userId,
1563 environmentId: input.environmentId,
1564 stage: "mark-allocation-ready",
1565 reason: "claim-lost",
1566 hostname,
1567 tunnelName,
1568 tunnelId: tunnel.id,
1569 dnsRecordId,
1570 });
1571 }
1572
1573 return {
1574 endpoint: managedEndpointForHostname(hostname),
1575 runtime: {
1576 providerKind: "cloudflare_tunnel",
1577 connectorToken,
1578 tunnelId: tunnel.id,
1579 tunnelName: tunnel.name,
1580 },
1581 } satisfies ManagedEndpointProvisioningResult;
1582 }),
1583 });
1584 });
1585
1586 export const layer = Layer.effect(ManagedEndpointProvider, make);
1587
1588 export const layerCloudflareBindings = (
1589 tunnelClient: Cloudflare.Tunnel.ReadWriteTunnelClient,
1590 dnsClient: Cloudflare.DNS.ReadWriteDnsClient,
1591 alchemyRuntimeContext: Alchemy.BaseRuntimeContext,
1592 ) => {
1593 // Created once per isolate so its cached pause survives layer rebuilds.
1594 const cloudflare = makeCloudflareApiGate(alchemyRuntimeContext);
1595 return layer.pipe(
1596 Layer.provideMerge(
1597 Layer.unwrap(
1598 Effect.gen(function* () {
1599 const pause = yield* CloudflareApiPause.CloudflareApiPause;
1600 const gate = cloudflare(pause);
1601 return Layer.mergeAll(
1602 layerTunnelClient({
1603 get: (tunnelId) =>
1604 gate(tunnelClient.get(tunnelId)).pipe(
1605 Effect.mapError(
1606 (cause) =>
1607 new ManagedEndpointTunnelClientError({
1608 operation: "get",
1609 tunnelId,
1610 cause,
1611 }),
1612 ),
1613 ),
1614 list: (request, options) =>
1615 gate(tunnelClient.list(request), options?.timeout).pipe(
1616 Effect.mapError(
1617 (cause) =>
1618 new ManagedEndpointTunnelClientError({
1619 operation: "list",
1620 ...(request.name === undefined ? {} : { tunnelName: request.name }),
1621 cause,
1622 }),
1623 ),
1624 ),
1625 create: (request) =>
1626 gate(tunnelClient.create(request)).pipe(
1627 Effect.mapError(
1628 (cause) =>
1629 new ManagedEndpointTunnelClientError({
1630 operation: "create",
1631 tunnelName: request.name,
1632 cause,
1633 }),
1634 ),
1635 ),
1636 putConfiguration: (tunnelId, config) =>
1637 gate(tunnelClient.putConfiguration(tunnelId, config)).pipe(
1638 Effect.mapError(
1639 (cause) =>
1640 new ManagedEndpointTunnelClientError({
1641 operation: "put-configuration",
1642 tunnelId,
1643 cause,
1644 }),
1645 ),
1646 ),
1647 getConfiguration: (tunnelId) =>
1648 gate(tunnelClient.getConfiguration(tunnelId)).pipe(
1649 Effect.map(({ config }) => ({ ingress: config?.ingress ?? [] })),
1650 // Cloudflare reports a tunnel without remote configuration as code 1055, not 404.
1651 Effect.catchTags({
1652 TunnelConfigurationNotFound: () => Effect.succeed({ ingress: [] }),
1653 }),
1654 Effect.mapError(
1655 (cause) =>
1656 new ManagedEndpointTunnelClientError({
1657 operation: "get-configuration",
1658 tunnelId,
1659 cause,
1660 }),
1661 ),
1662 ),
1663 getToken: (tunnelId) =>
1664 gate(tunnelClient.getToken(tunnelId)).pipe(
1665 Effect.mapError(
1666 (cause) =>
1667 new ManagedEndpointTunnelClientError({
1668 operation: "get-token",
1669 tunnelId,
1670 cause,
1671 }),
1672 ),
1673 ),
1674 delete: (tunnelId) =>
1675 gate(tunnelClient.delete(tunnelId)).pipe(
1676 Effect.mapError(
1677 (cause) =>
1678 new ManagedEndpointTunnelClientError({
1679 operation: "delete",
1680 tunnelId,
1681 cause,
1682 }),
1683 ),
1684 ),
1685 }),
1686 layerDnsClient({
1687 listRecords: (hostname) =>
1688 gate(dnsClient.listDnsRecords({ search: hostname })).pipe(
1689 Effect.map((response) =>
1690 response.result.filter(
1691 (record): record is typeof record & { readonly id: string } =>
1692 typeof record.id === "string" &&
1693 normalizeHostname(record.name) === normalizeHostname(hostname),
1694 ),
1695 ),
1696 Effect.mapError(
1697 (cause) =>
1698 new ManagedEndpointDnsClientError({
1699 operation: "list-records",
1700 hostname,
1701 cause,
1702 }),
1703 ),
1704 ),
1705 createRecord: (request) =>
1706 gate(dnsClient.createDnsRecord(request)).pipe(
1707 Effect.map((response) => ({ id: response.id })),
1708 Effect.mapError(
1709 (cause) =>
1710 new ManagedEndpointDnsClientError({
1711 operation: "create-record",
1712 hostname: request.name,
1713 cause,
1714 }),
1715 ),
1716 ),
1717 updateRecord: (dnsRecordId, request) =>
1718 gate(dnsClient.updateDnsRecord(dnsRecordId, request)).pipe(
1719 Effect.mapError(
1720 (cause) =>
1721 new ManagedEndpointDnsClientError({
1722 operation: "update-record",
1723 hostname: request.name,
1724 dnsRecordId,
1725 cause,
1726 }),
1727 ),
1728 ),
1729 deleteRecord: (dnsRecordId) =>
1730 gate(dnsClient.deleteDnsRecord(dnsRecordId)).pipe(
1731 Effect.mapError(
1732 (cause) =>
1733 new ManagedEndpointDnsClientError({
1734 operation: "delete-record",
1735 dnsRecordId,
1736 cause,
1737 }),
1738 ),
1739 ),
1740 }),
1741 );
1742 }),
1743 ),
1744 ),
1745 );
1746 };