Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ManagedEndpointProvider.ts

993 lines33.3 KB

1import * as Alchemy from "alchemy";
2import * as Cloudflare from "alchemy/Cloudflare";
3import * as Arr from "effect/Array";
4import * as Context from "effect/Context";
5import * as Crypto from "effect/Crypto";
6import * as Effect from "effect/Effect";
7import * as Encoding from "effect/Encoding";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Schema from "effect/Schema";
11​
12import type {
13 RelayManagedEndpoint,
14 RelayManagedEndpointOrigin,
15 RelayManagedEndpointRuntimeConfig,
16} from "@t3tools/contracts/relay";
17​
18import * as RelayConfiguration from "../Config.ts";
19import {
20 managedEndpointDigestInput,
21 managedEndpointForHostname,
22 managedEndpointHostname,
23 managedEndpointTunnelName,
24} from "../deploymentConfig.ts";
25import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
26import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts";
27​
28export class ManagedEndpointProvisioningNotConfigured extends Schema.TaggedError<ManagedEndpointProvisioningNotConfigured>()(
29 "ManagedEndpointProvisioningNotConfigured",
30 {
31 userId: Schema.String,
32 environmentId: Schema.String,
33 missingSettings: Schema.Array(
34 Schema.Literals(["managedEndpointBaseDomain", "managedEndpointNamespace"]),
35 ),
36 },
37) {
38 override get message(): string {
39 return `Managed endpoint provisioning is not configured for user '${this.userId}', environment '${this.environmentId}': missing ${this.missingSettings.join(", ")}`;
40 }
42​
43const ManagedEndpointProvisioningStage = Schema.Literals([
44 "derive-environment-hash",
45 "check-tunnel-limit",
46 "reserve-allocation",
47 "ensure-tunnel",
48 "validate-tunnel-response",
49 "record-tunnel",
50 "configure-tunnel",
51 "ensure-dns-record",
52 "record-dns",
53 "get-tunnel-token",
54 "mark-allocation-ready",
55]);
56​
57export class ManagedEndpointProvisioningFailed extends Schema.TaggedError<ManagedEndpointProvisioningFailed>()(
58 "ManagedEndpointProvisioningFailed",
59 {
60 stage: ManagedEndpointProvisioningStage,
61 userId: Schema.String,
62 environmentId: Schema.String,
63 hostname: Schema.optionalKey(Schema.String),
64 tunnelName: Schema.optionalKey(Schema.String),
65 tunnelId: Schema.optionalKey(Schema.String),
66 dnsRecordId: Schema.optionalKey(Schema.String),
67 returnedTunnelName: Schema.optionalKey(Schema.String),
68 returnedTunnelId: Schema.optionalKey(Schema.String),
69 cause: Schema.optional(Schema.Defect()),
70 },
71) {
72 override get message(): string {
73 return `Managed endpoint provisioning failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
74 }
76​
77const ManagedEndpointDeprovisioningStage = Schema.Literals([
78 "load-allocation",
79 "claim-release",
80 "claim-deprovision",
81 "delete-dns-record",
82 "delete-tunnel",
83 "remove-allocation",
84]);
85​
86export class ManagedEndpointDeprovisioningFailed extends Schema.TaggedError<ManagedEndpointDeprovisioningFailed>()(
87 "ManagedEndpointDeprovisioningFailed",
88 {
89 stage: ManagedEndpointDeprovisioningStage,
90 userId: Schema.String,
91 environmentId: Schema.String,
92 tunnelId: Schema.optionalKey(Schema.String),
93 dnsRecordId: Schema.optionalKey(Schema.String),
94 cause: Schema.Defect(),
95 },
96) {
97 override get message(): string {
98 return `Managed endpoint deprovisioning failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
99 }
101​
102export class ManagedEndpointOriginNotAllowed extends Schema.TaggedError<ManagedEndpointOriginNotAllowed>()(
103 "ManagedEndpointOriginNotAllowed",
104 {
105 userId: Schema.String,
106 environmentId: Schema.String,
107 host: Schema.String,
108 port: Schema.Number,
109 },
110) {
111 override get message(): string {
112 return `Managed endpoint origin '${this.host}:${this.port}' is not allowed for user '${this.userId}', environment '${this.environmentId}'`;
113 }
115​
116export type ManagedEndpointProviderError =
117 | ManagedEndpointProvisioningNotConfigured
118 | ManagedEndpointProvisioningFailed
119 | ManagedEndpointOriginNotAllowed
120 | ManagedTunnelLimits.ManagedTunnelLimitExceeded;
121​
122export interface ManagedEndpointProvisioningResult {
123 readonly endpoint: RelayManagedEndpoint;
124 readonly runtime: RelayManagedEndpointRuntimeConfig;
126​
127export type ManagedEndpointDeprovisionTarget = ManagedEndpointAllocations.ManagedEndpointAllocation;
128​
129export class ManagedEndpointProvider extends Context.Service<
130 ManagedEndpointProvider,
131 {
132 readonly provision: (input: {
133 readonly userId: string;
134 readonly environmentId: string;
135 readonly origin: RelayManagedEndpointOrigin;
136 }) => Effect.Effect<ManagedEndpointProvisioningResult, ManagedEndpointProviderError>;
137 /**
138 * Captures the allocation generation owned by an unlink before its link
139 * revocation commits. Passing this target to `deprovision` prevents a
140 * concurrent relink from having its newer allocation torn down.
141 */
142 readonly prepareDeprovision: (input: {
143 readonly userId: string;
144 readonly environmentId: string;
145 }) => Effect.Effect<
146 ManagedEndpointDeprovisionTarget | null,
147 ManagedEndpointDeprovisioningFailed
148 >;
149 readonly deprovision: (input: {
150 readonly userId: string;
151 readonly environmentId: string;
152 readonly target?: ManagedEndpointDeprovisionTarget | null;
153 }) => Effect.Effect<void, ManagedEndpointDeprovisioningFailed>;
154 /**
155 * Deletes the provisioned Cloudflare tunnel while keeping the allocation
156 * (hostname + tunnel name reservation) and DNS record. Cloudflare bills per
157 * provisioned tunnel, so environments release the tunnel when they shut
158 * down; the next `provision` recreates it under the same name and repoints
159 * the CNAME, preserving the endpoint URL.
160 *
161 * Resolves to whether the caller's connector token is now dead: true when
162 * the tunnel was deleted (or none was recorded to begin with), false when
163 * a concurrent provision outbid the release claim and the recorded tunnel
164 * — and any token issued for it — stays live.
165 */
166 readonly release: (input: {
167 readonly userId: string;
168 readonly environmentId: string;
169 }) => Effect.Effect<boolean, ManagedEndpointDeprovisioningFailed>;
170 }
171>()("t3code-relay/environments/ManagedEndpointProvider") {}
172​
173interface ManagedEndpointTunnel {
174 readonly id?: string | null;
175 readonly name?: string | null;
177​
178const ManagedEndpointTunnelClientOperation = Schema.Literals([
179 "list",
180 "create",
181 "put-configuration",
182 "get-token",
183 "delete",
184]);
185​
186export class ManagedEndpointTunnelClientError extends Schema.TaggedError<ManagedEndpointTunnelClientError>()(
187 "ManagedEndpointTunnelClientError",
188 {
189 operation: ManagedEndpointTunnelClientOperation,
190 tunnelName: Schema.optionalKey(Schema.String),
191 tunnelId: Schema.optionalKey(Schema.String),
192 cause: Schema.Defect(),
193 },
194) {
195 override get message(): string {
196 const target = this.tunnelId ?? this.tunnelName;
197 return `Managed endpoint tunnel provider '${this.operation}' request failed${target === undefined ? "" : ` for '${target}'`}`;
198 }
200​
201export class ManagedEndpointTunnelClient extends Context.Service<
202 ManagedEndpointTunnelClient,
203 {
204 readonly list: (request: {
205 readonly name: string;
206 readonly isDeleted: false;
207 }) => Effect.Effect<
208 { readonly result: ReadonlyArray<ManagedEndpointTunnel> },
209 ManagedEndpointTunnelClientError
210 >;
211 readonly create: (request: {
212 readonly name: string;
213 readonly configSrc: "cloudflare";
214 }) => Effect.Effect<ManagedEndpointTunnel, ManagedEndpointTunnelClientError>;
215 readonly putConfiguration: (
216 tunnelId: string,
217 config: {
218 readonly ingress: Array<{
219 readonly hostname?: string;
220 readonly service: string;
221 }>;
222 },
223 ) => Effect.Effect<unknown, ManagedEndpointTunnelClientError>;
224 readonly getToken: (
225 tunnelId: string,
226 ) => Effect.Effect<string, ManagedEndpointTunnelClientError>;
227 readonly delete: (tunnelId: string) => Effect.Effect<unknown, ManagedEndpointTunnelClientError>;
228 }
229>()("t3code-relay/environments/ManagedEndpointProvider/ManagedEndpointTunnelClient") {}
230​
231export const layerTunnelClient = (client: ManagedEndpointTunnelClient["Service"]) =>
232 Layer.succeed(ManagedEndpointTunnelClient, client);
233​
234interface ManagedEndpointCnameRecordInput {
235 readonly type: "CNAME";
236 readonly name: string;
237 readonly content: string;
238 readonly ttl: 1;
239 readonly proxied: true;
241​
242const ManagedEndpointDnsClientOperation = Schema.Literals([
243 "list-records",
244 "create-record",
245 "update-record",
246 "delete-record",
247]);
248​
249export class ManagedEndpointDnsClientError extends Schema.TaggedError<ManagedEndpointDnsClientError>()(
250 "ManagedEndpointDnsClientError",
251 {
252 operation: ManagedEndpointDnsClientOperation,
253 hostname: Schema.optionalKey(Schema.String),
254 dnsRecordId: Schema.optionalKey(Schema.String),
255 cause: Schema.Defect(),
256 },
257) {
258 override get message(): string {
259 const target = this.dnsRecordId ?? this.hostname;
260 return `Managed endpoint DNS provider '${this.operation}' request failed${target === undefined ? "" : ` for '${target}'`}`;
261 }
263​
264export class ManagedEndpointDnsClient extends Context.Service<
265 ManagedEndpointDnsClient,
266 {
267 readonly listRecords: (
268 hostname: string,
269 ) => Effect.Effect<ReadonlyArray<{ readonly id: string }>, ManagedEndpointDnsClientError>;
270 readonly createRecord: (
271 request: ManagedEndpointCnameRecordInput,
272 ) => Effect.Effect<{ readonly id: string }, ManagedEndpointDnsClientError>;
273 readonly updateRecord: (
274 dnsRecordId: string,
275 request: ManagedEndpointCnameRecordInput,
276 ) => Effect.Effect<unknown, ManagedEndpointDnsClientError>;
277 readonly deleteRecord: (
278 dnsRecordId: string,
279 ) => Effect.Effect<unknown, ManagedEndpointDnsClientError>;
280 }
281>()("t3code-relay/environments/ManagedEndpointProvider/ManagedEndpointDnsClient") {}
282​
283export const layerDnsClient = (client: ManagedEndpointDnsClient["Service"]) =>
284 Layer.succeed(ManagedEndpointDnsClient, client);
285​
286const requireCloudflareSettings = Effect.fnUntraced(function* (
287 settings: RelayConfiguration.RelayConfiguration["Service"],
288 input: { readonly userId: string; readonly environmentId: string },
289) {
290 const baseDomain = settings.managedEndpointBaseDomain;
291 const namespace = settings.managedEndpointNamespace;
292 const missingSettings: Array<"managedEndpointBaseDomain" | "managedEndpointNamespace"> = [];
293 if (!baseDomain) {
294 missingSettings.push("managedEndpointBaseDomain");
295 }
296 if (!namespace) {
297 missingSettings.push("managedEndpointNamespace");
298 }
299 if (!baseDomain || !namespace) {
300 return yield* new ManagedEndpointProvisioningNotConfigured({
301 ...input,
302 missingSettings,
303 });
304 }
305 return {
306 baseDomain,
307 namespace,
308 };
309});
310​
311function formatOriginService(origin: RelayManagedEndpointOrigin): string {
312 const host = origin.localHttpHost.includes(":")
313 ? `[${origin.localHttpHost.replace(/^\[(.*)\]$/u, "$1")}]`
314 : origin.localHttpHost;
315 return `http://${host}:${origin.localHttpPort}`;
317​
318function normalizeHostname(hostname: string): string {
319 return hostname
320 .trim()
321 .toLowerCase()
322 .replace(/\.$/u, "")
323 .replace(/^\[(.*)\]$/u, "$1");
325​
326function isLoopbackOrigin(origin: RelayManagedEndpointOrigin): boolean {
327 const hostname = normalizeHostname(origin.localHttpHost);
328 return (
329 (hostname === "127.0.0.1" || hostname === "::1" || hostname === "localhost") &&
330 Number.isInteger(origin.localHttpPort) &&
331 origin.localHttpPort > 0 &&
332 origin.localHttpPort <= 65_535
333 );
335​
336function isNotFoundCause(cause: unknown): boolean {
337 if (typeof cause !== "object" || cause === null) {
338 return false;
339 }
340 if ("_tag" in cause && cause._tag === "NotFound") {
341 return true;
342 }
343 if ("status" in cause && cause.status === 404) {
344 return true;
345 }
346 return "cause" in cause && isNotFoundCause(cause.cause);
348​
349type ManagedEndpointClientError = ManagedEndpointTunnelClientError | ManagedEndpointDnsClientError;
350​
351const ignoreNotFound = <A>(
352 effect: Effect.Effect<A, ManagedEndpointClientError>,
353): Effect.Effect<void, ManagedEndpointClientError> =>
354 effect.pipe(
355 Effect.asVoid,
356 Effect.catchTags({
357 ManagedEndpointTunnelClientError: (error) =>
358 isNotFoundCause(error.cause) ? Effect.void : Effect.fail(error),
359 ManagedEndpointDnsClientError: (error) =>
360 isNotFoundCause(error.cause) ? Effect.void : Effect.fail(error),
361 }),
362 );
363​
364export const make = Effect.gen(function* () {
365 const config = yield* RelayConfiguration.RelayConfiguration;
366 const crypto = yield* Crypto.Crypto;
367 const tunnels = yield* ManagedEndpointTunnelClient;
368 const dns = yield* ManagedEndpointDnsClient;
369 const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;
370 const tunnelLimits = yield* ManagedTunnelLimits.ManagedTunnelLimits;
371​
372 const updateExistingDnsRecords = Effect.fnUntraced(function* (
373 records: ReadonlyArray<{ readonly id: string }>,
374 preferredDnsRecordId: string | null,
375 dnsRecord: ManagedEndpointCnameRecordInput,
376 ) {
377 const keptRecord = records.find((record) => record.id === preferredDnsRecordId) ?? records[0];
378 if (keptRecord === undefined) {
379 return null;
380 }
381 yield* Effect.forEach(
382 records,
383 (record) => (record.id === keptRecord.id ? Effect.void : dns.deleteRecord(record.id)),
384 { discard: true },
385 );
386 yield* dns.updateRecord(keptRecord.id, dnsRecord);
387 return keptRecord.id;
388 });
389​
390 const ensureDnsRecord = Effect.fnUntraced(function* (
391 hostname: string,
392 preferredDnsRecordId: string | null,
393 dnsRecord: ManagedEndpointCnameRecordInput,
394 ) {
395 if (preferredDnsRecordId !== null) {
396 const checkpointedRecordUpdated = yield* dns
397 .updateRecord(preferredDnsRecordId, dnsRecord)
398 .pipe(
399 Effect.as(true),
400 Effect.catchTags({
401 ManagedEndpointDnsClientError: (error) =>
402 isNotFoundCause(error.cause) ? Effect.succeed(false) : Effect.fail(error),
403 }),
404 );
405 if (checkpointedRecordUpdated) {
406 return preferredDnsRecordId;
407 }
408 }
409 const existingDnsRecords = yield* dns.listRecords(hostname);
410 const existingDnsRecordId = yield* updateExistingDnsRecords(
411 existingDnsRecords,
412 preferredDnsRecordId,
413 dnsRecord,
414 );
415 if (existingDnsRecordId !== null) {
416 return existingDnsRecordId;
417 }
418 return yield* dns.createRecord(dnsRecord).pipe(
419 Effect.map((record) => record.id),
420 Effect.catchTags({
421 ManagedEndpointDnsClientError: (createError) =>
422 Effect.gen(function* () {
423 let records = yield* dns.listRecords(hostname);
424 for (let attempt = 0; records.length === 0 && attempt < 4; attempt++) {
425 yield* Effect.sleep("200 millis");
426 records = yield* dns.listRecords(hostname);
427 }
428 return records;
429 }).pipe(
430 Effect.flatMap((records) =>
431 records.length > 0
432 ? updateExistingDnsRecords(records, preferredDnsRecordId, dnsRecord)
433 : Effect.fail(createError),
434 ),
435 Effect.flatMap((dnsRecordId) =>
436 dnsRecordId === null ? Effect.fail(createError) : Effect.succeed(dnsRecordId),
437 ),
438 ),
439 }),
440 );
441 });
442​
443 const prepareDeprovision = Effect.fn("relay.managed_endpoint_provider.prepare_deprovision")(
444 function* (input: { readonly userId: string; readonly environmentId: string }) {
445 return yield* allocations.get(input).pipe(
446 Effect.mapError(
447 (cause) =>
448 new ManagedEndpointDeprovisioningFailed({
449 ...input,
450 stage: "load-allocation",
451 cause,
452 }),
453 ),
454 );
455 },
456 );
457​
458 return ManagedEndpointProvider.of({
459 prepareDeprovision,
460 deprovision: Effect.fn("relay.managed_endpoint_provider.deprovision")(function* (input) {
461 yield* Effect.annotateCurrentSpan({
462 "relay.user_id": input.userId,
463 "relay.environment_id": input.environmentId,
464 });
465 const allocation =
466 input.target === undefined ? yield* prepareDeprovision(input) : input.target;
467 if (allocation === null) {
468 return;
469 }
470 const claimedAt = yield* allocations
471 .claimDeprovision({
472 userId: input.userId,
473 environmentId: input.environmentId,
474 updatedAt: allocation.updatedAt,
475 })
476 .pipe(
477 Effect.mapError(
478 (cause) =>
479 new ManagedEndpointDeprovisioningFailed({
480 ...input,
481 stage: "claim-deprovision",
482 ...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),
483 ...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),
484 cause,
485 }),
486 ),
487 );
488 if (claimedAt === null) {
489 return;
490 }
491 const dnsRecordId = allocation.dnsRecordId;
492 if (dnsRecordId !== null) {
493 yield* ignoreNotFound(dns.deleteRecord(dnsRecordId)).pipe(
494 Effect.mapError(
495 (cause) =>
496 new ManagedEndpointDeprovisioningFailed({
497 ...input,
498 stage: "delete-dns-record",
499 dnsRecordId,
500 cause,
501 }),
502 ),
503 );
504 }
505 const tunnelId = allocation.tunnelId;
506 if (tunnelId !== null) {
507 yield* ignoreNotFound(tunnels.delete(tunnelId)).pipe(
508 Effect.mapError(
509 (cause) =>
510 new ManagedEndpointDeprovisioningFailed({
511 ...input,
512 stage: "delete-tunnel",
513 tunnelId,
514 cause,
515 }),
516 ),
517 );
518 }
519 yield* allocations
520 .removeClaimed({
521 userId: input.userId,
522 environmentId: input.environmentId,
523 updatedAt: claimedAt,
524 })
525 .pipe(
526 Effect.mapError(
527 (cause) =>
528 new ManagedEndpointDeprovisioningFailed({
529 ...input,
530 stage: "remove-allocation",
531 ...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),
532 ...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),
533 cause,
534 }),
535 ),
536 );
537 }),
538 release: Effect.fn("relay.managed_endpoint_provider.release")(function* (input) {
539 yield* Effect.annotateCurrentSpan({
540 "relay.user_id": input.userId,
541 "relay.environment_id": input.environmentId,
542 });
543 const allocation = yield* allocations.get(input).pipe(
544 Effect.mapError(
545 (cause) =>
546 new ManagedEndpointDeprovisioningFailed({
547 ...input,
548 stage: "load-allocation",
549 cause,
550 }),
551 ),
552 );
553 const tunnelId = allocation?.tunnelId ?? null;
554 if (allocation === null || tunnelId === null) {
555 return true;
556 }
557 // Claim the release against the allocation's current generation before
558 // touching Cloudflare. A provision racing this release (fast environment
559 // restart) rewrites updatedAt when it records its tunnel, so a stale
560 // claim means the recorded tunnel may already back a fresh connector and
561 // must be left alive. A provision that starts after the claim instead
562 // fails loudly on the deleted tunnel and the client-side retry
563 // provisions a replacement.
564 const claimed = yield* allocations
565 .claimRelease({
566 userId: input.userId,
567 environmentId: input.environmentId,
568 tunnelId,
569 updatedAt: allocation.updatedAt,
570 })
571 .pipe(
572 Effect.mapError(
573 (cause) =>
574 new ManagedEndpointDeprovisioningFailed({
575 ...input,
576 stage: "claim-release",
577 tunnelId,
578 cause,
579 }),
580 ),
581 );
582 if (!claimed) {
583 return false;
584 }
585 yield* ignoreNotFound(tunnels.delete(tunnelId)).pipe(
586 Effect.mapError(
587 (cause) =>
588 new ManagedEndpointDeprovisioningFailed({
589 ...input,
590 stage: "delete-tunnel",
591 tunnelId,
592 cause,
593 }),
594 ),
595 );
596 // The recorded tunnelId is now stale, but the allocation row is left
597 // untouched deliberately: connect/status authorization requires a fully
598 // recorded allocation, and an offline environment must keep reporting
599 // "offline" (health probe fails) rather than "not authorized". The next
600 // provision lists tunnels by name, finds none, creates a replacement and
601 // re-records the fresh id.
602 return true;
603 }),
604 provision: Effect.fn("relay.managed_endpoint_provider.provision")(function* (input) {
605 yield* Effect.annotateCurrentSpan({
606 "relay.user_id": input.userId,
607 "relay.environment_id": input.environmentId,
608 "relay.managed_endpoint.origin_host": input.origin.localHttpHost,
609 "relay.managed_endpoint.origin_port": input.origin.localHttpPort,
610 });
611 if (!isLoopbackOrigin(input.origin)) {
612 return yield* new ManagedEndpointOriginNotAllowed({
613 userId: input.userId,
614 environmentId: input.environmentId,
615 host: input.origin.localHttpHost,
616 port: input.origin.localHttpPort,
617 });
618 }
619 const cf = yield* requireCloudflareSettings(config, input);
620 const environmentHash = yield* crypto
621 .digest(
622 "SHA-256",
623 new TextEncoder().encode(
624 managedEndpointDigestInput(cf.namespace, input.userId, input.environmentId),
625 ),
626 )
627 .pipe(
628 Effect.map(Encoding.encodeHex),
629 Effect.mapError(
630 (cause) =>
631 new ManagedEndpointProvisioningFailed({
632 userId: input.userId,
633 environmentId: input.environmentId,
634 stage: "derive-environment-hash",
635 cause,
636 }),
637 ),
638 );
639 const requestedHostname = managedEndpointHostname(
640 cf.namespace,
641 cf.baseDomain,
642 environmentHash,
643 );
644 const requestedTunnelName = managedEndpointTunnelName(cf.namespace, environmentHash);
645 yield* tunnelLimits
646 .ensureCapacity({
647 userId: input.userId,
648 environmentId: input.environmentId,
649 })
650 .pipe(
651 Effect.catchTags({
652 ManagedTunnelLimitPersistenceError: (cause) =>
653 Effect.fail(
654 new ManagedEndpointProvisioningFailed({
655 userId: input.userId,
656 environmentId: input.environmentId,
657 stage: "check-tunnel-limit",
658 hostname: requestedHostname,
659 tunnelName: requestedTunnelName,
660 cause,
661 }),
662 ),
663 }),
664 );
665 const allocation = yield* allocations
666 .reserve({
667 userId: input.userId,
668 environmentId: input.environmentId,
669 hostname: requestedHostname,
670 tunnelName: requestedTunnelName,
671 })
672 .pipe(
673 Effect.mapError(
674 (cause) =>
675 new ManagedEndpointProvisioningFailed({
676 userId: input.userId,
677 environmentId: input.environmentId,
678 stage: "reserve-allocation",
679 hostname: requestedHostname,
680 tunnelName: requestedTunnelName,
681 cause,
682 }),
683 ),
684 );
685 const { hostname, tunnelName } = allocation;
686​
687 const tunnelResponse = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe(
688 Effect.map((tunnels) => tunnels.result),
689 Effect.map(Arr.findFirst((tunnel) => tunnel.name === tunnelName)),
690 Effect.flatMap(
691 Option.match({
692 onSome: (tunnel) => Effect.succeed(tunnel),
693 onNone: () => tunnels.create({ name: tunnelName, configSrc: "cloudflare" }),
694 }),
695 ),
696 Effect.mapError(
697 (cause) =>
698 new ManagedEndpointProvisioningFailed({
699 userId: input.userId,
700 environmentId: input.environmentId,
701 stage: "ensure-tunnel",
702 hostname,
703 tunnelName,
704 cause,
705 }),
706 ),
707 );
708 if (!tunnelResponse.id || tunnelResponse.name !== tunnelName) {
709 return yield* new ManagedEndpointProvisioningFailed({
710 userId: input.userId,
711 environmentId: input.environmentId,
712 stage: "validate-tunnel-response",
713 hostname,
714 tunnelName,
715 ...(tunnelResponse.id ? { returnedTunnelId: tunnelResponse.id } : {}),
716 ...(tunnelResponse.name ? { returnedTunnelName: tunnelResponse.name } : {}),
717 });
718 }
719 const tunnel = { id: tunnelResponse.id, name: tunnelResponse.name };
720 yield* allocations
721 .recordTunnel({
722 userId: input.userId,
723 environmentId: input.environmentId,
724 tunnelId: tunnel.id,
725 })
726 .pipe(
727 Effect.mapError(
728 (cause) =>
729 new ManagedEndpointProvisioningFailed({
730 userId: input.userId,
731 environmentId: input.environmentId,
732 stage: "record-tunnel",
733 hostname,
734 tunnelName,
735 tunnelId: tunnel.id,
736 cause,
737 }),
738 ),
739 );
740​
741 yield* tunnels
742 .putConfiguration(tunnel.id, {
743 ingress: [
744 {
745 hostname,
746 service: formatOriginService(input.origin),
747 },
748 { service: "http_status:404" },
749 ],
750 })
751 .pipe(
752 Effect.mapError(
753 (cause) =>
754 new ManagedEndpointProvisioningFailed({
755 userId: input.userId,
756 environmentId: input.environmentId,
757 stage: "configure-tunnel",
758 hostname,
759 tunnelName,
760 tunnelId: tunnel.id,
761 cause,
762 }),
763 ),
764 );
765​
766 const dnsRecord = {
767 type: "CNAME",
768 name: hostname,
769 content: `${tunnel.id}.cfargotunnel.com`,
770 ttl: 1,
771 proxied: true,
772 } as const;
773​
774 const dnsRecordId = yield* ensureDnsRecord(hostname, allocation.dnsRecordId, dnsRecord).pipe(
775 Effect.mapError(
776 (cause) =>
777 new ManagedEndpointProvisioningFailed({
778 userId: input.userId,
779 environmentId: input.environmentId,
780 stage: "ensure-dns-record",
781 hostname,
782 tunnelName,
783 tunnelId: tunnel.id,
784 ...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),
785 cause,
786 }),
787 ),
788 );
789 yield* allocations
790 .recordDns({
791 userId: input.userId,
792 environmentId: input.environmentId,
793 dnsRecordId,
794 })
795 .pipe(
796 Effect.mapError(
797 (cause) =>
798 new ManagedEndpointProvisioningFailed({
799 userId: input.userId,
800 environmentId: input.environmentId,
801 stage: "record-dns",
802 hostname,
803 tunnelName,
804 tunnelId: tunnel.id,
805 dnsRecordId,
806 cause,
807 }),
808 ),
809 );
810​
811 const connectorToken = yield* tunnels.getToken(tunnel.id).pipe(
812 Effect.mapError(
813 (cause) =>
814 new ManagedEndpointProvisioningFailed({
815 userId: input.userId,
816 environmentId: input.environmentId,
817 stage: "get-tunnel-token",
818 hostname,
819 tunnelName,
820 tunnelId: tunnel.id,
821 dnsRecordId,
822 cause,
823 }),
824 ),
825 );
826 yield* allocations
827 .markReady({
828 userId: input.userId,
829 environmentId: input.environmentId,
830 })
831 .pipe(
832 Effect.mapError(
833 (cause) =>
834 new ManagedEndpointProvisioningFailed({
835 userId: input.userId,
836 environmentId: input.environmentId,
837 stage: "mark-allocation-ready",
838 hostname,
839 tunnelName,
840 tunnelId: tunnel.id,
841 dnsRecordId,
842 cause,
843 }),
844 ),
845 );
846​
847 return {
848 endpoint: managedEndpointForHostname(hostname),
849 runtime: {
850 providerKind: "cloudflare_tunnel",
851 connectorToken,
852 tunnelId: tunnel.id,
853 tunnelName: tunnel.name,
854 },
855 } satisfies ManagedEndpointProvisioningResult;
856 }),
857 });
858});
859​
860export const layer = Layer.effect(ManagedEndpointProvider, make);
861​
862export const layerCloudflareBindings = (
863 tunnelClient: Cloudflare.Tunnel.ReadWriteTunnelClient,
864 dnsClient: Cloudflare.DNS.ReadWriteDnsClient,
865 alchemyRuntimeContext: Alchemy.BaseRuntimeContext,
866) =>
867 layer.pipe(
868 Layer.provide(
869 Layer.mergeAll(
870 layerTunnelClient({
871 list: (request) =>
872 tunnelClient.list(request).pipe(
873 Effect.mapError(
874 (cause) =>
875 new ManagedEndpointTunnelClientError({
876 operation: "list",
877 tunnelName: request.name,
878 cause,
879 }),
880 ),
881 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
882 ),
883 create: (request) =>
884 tunnelClient.create(request).pipe(
885 Effect.mapError(
886 (cause) =>
887 new ManagedEndpointTunnelClientError({
888 operation: "create",
889 tunnelName: request.name,
890 cause,
891 }),
892 ),
893 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
894 ),
895 putConfiguration: (tunnelId, config) =>
896 tunnelClient.putConfiguration(tunnelId, config).pipe(
897 Effect.mapError(
898 (cause) =>
899 new ManagedEndpointTunnelClientError({
900 operation: "put-configuration",
901 tunnelId,
902 cause,
903 }),
904 ),
905 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
906 ),
907 getToken: (tunnelId) =>
908 tunnelClient.getToken(tunnelId).pipe(
909 Effect.mapError(
910 (cause) =>
911 new ManagedEndpointTunnelClientError({
912 operation: "get-token",
913 tunnelId,
914 cause,
915 }),
916 ),
917 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
918 ),
919 delete: (tunnelId) =>
920 tunnelClient.delete(tunnelId).pipe(
921 Effect.mapError(
922 (cause) =>
923 new ManagedEndpointTunnelClientError({
924 operation: "delete",
925 tunnelId,
926 cause,
927 }),
928 ),
929 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
930 ),
931 }),
932 layerDnsClient({
933 listRecords: (hostname) =>
934 dnsClient.listDnsRecords({ search: hostname }).pipe(
935 Effect.map((response) =>
936 response.result.filter(
937 (record): record is typeof record & { readonly id: string } =>
938 typeof record.id === "string" &&
939 normalizeHostname(record.name) === normalizeHostname(hostname),
940 ),
941 ),
942 Effect.mapError(
943 (cause) =>
944 new ManagedEndpointDnsClientError({
945 operation: "list-records",
946 hostname,
947 cause,
948 }),
949 ),
950 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
951 ),
952 createRecord: (request) =>
953 dnsClient.createDnsRecord(request).pipe(
954 Effect.map((response) => ({ id: response.id })),
955 Effect.mapError(
956 (cause) =>
957 new ManagedEndpointDnsClientError({
958 operation: "create-record",
959 hostname: request.name,
960 cause,
961 }),
962 ),
963 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
964 ),
965 updateRecord: (dnsRecordId, request) =>
966 dnsClient.updateDnsRecord(dnsRecordId, request).pipe(
967 Effect.mapError(
968 (cause) =>
969 new ManagedEndpointDnsClientError({
970 operation: "update-record",
971 hostname: request.name,
972 dnsRecordId,
973 cause,
974 }),
975 ),
976 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
977 ),
978 deleteRecord: (dnsRecordId) =>
979 dnsClient.deleteDnsRecord(dnsRecordId).pipe(
980 Effect.mapError(
981 (cause) =>
982 new ManagedEndpointDnsClientError({
983 operation: "delete-record",
984 dnsRecordId,
985 cause,
986 }),
987 ),
988 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
989 ),
990 }),
991 ),
992 ),
993 );