Open History to see the last commit
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 DateTime from "effect/DateTime";
7import * as Effect from "effect/Effect";
8import * as Hex from "effect/encoding/Hex";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Schema from "effect/Schema";
12
13import type {
14 RelayManagedEndpoint,
15 RelayManagedEndpointOrigin,
16 RelayManagedEndpointRuntimeConfig,
17} from "@t3tools/contracts/relay";
18
19import * as RelayConfiguration from "../Config.ts";
20import {
21 managedEndpointDigestInput,
22 managedEndpointForHostname,
23 managedEndpointHostname,
24 managedEndpointTunnelName,
25} from "../deploymentConfig.ts";
26import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
27import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts";
28
29export class ManagedEndpointProvisioningNotConfigured extends Schema.TaggedError<ManagedEndpointProvisioningNotConfigured>()(
30 "ManagedEndpointProvisioningNotConfigured",
31 {
32 userId: Schema.String,
33 environmentId: Schema.String,
34 missingSettings: Schema.Array(
35 Schema.Literals(["managedEndpointBaseDomain", "managedEndpointNamespace"]),
36 ),
37 },
38) {
39 override get message(): string {
40 return `Managed endpoint provisioning is not configured for user '${this.userId}', environment '${this.environmentId}': missing ${this.missingSettings.join(", ")}`;
41 }
42}
43
44const ManagedEndpointProvisioningStage = Schema.Literals([
45 "derive-environment-hash",
46 "check-tunnel-limit",
47 "reserve-allocation",
48 "ensure-tunnel",
49 "validate-tunnel-response",
50 "record-tunnel",
51 "configure-tunnel",
52 "ensure-dns-record",
53 "record-dns",
54 "get-tunnel-token",
55 "mark-allocation-ready",
56 "load-allocation",
57 "verify-endpoint",
58 "verify-tunnel",
59 "sync-origin",
60]);
61
62const ManagedEndpointProvisioningFailureReason = Schema.Literals([
63 "claim-lost",
64 "endpoint-mismatch",
65 "invalid-tunnel-response",
66]);
67
68export class ManagedEndpointProvisioningFailed extends Schema.TaggedError<ManagedEndpointProvisioningFailed>()(
69 "ManagedEndpointProvisioningFailed",
70 {
71 stage: ManagedEndpointProvisioningStage,
72 reason: Schema.optionalKey(ManagedEndpointProvisioningFailureReason),
73 userId: Schema.String,
74 environmentId: Schema.String,
75 hostname: Schema.optionalKey(Schema.String),
76 tunnelName: Schema.optionalKey(Schema.String),
77 tunnelId: Schema.optionalKey(Schema.String),
78 dnsRecordId: Schema.optionalKey(Schema.String),
79 returnedTunnelName: Schema.optionalKey(Schema.String),
80 returnedTunnelId: Schema.optionalKey(Schema.String),
81 cause: Schema.optional(Schema.Defect()),
82 },
83) {
84 override get message(): string {
85 return `Managed endpoint provisioning failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
86 }
87}
88
89const ManagedEndpointDeprovisioningStage = Schema.Literals([
90 "load-allocation",
91 "load-tunnel",
92 "claim-release",
93 "claim-deprovision",
94 "delete-dns-record",
95 "delete-tunnel",
96 "remove-allocation",
97]);
98
99export class ManagedEndpointDeprovisioningFailed extends Schema.TaggedError<ManagedEndpointDeprovisioningFailed>()(
100 "ManagedEndpointDeprovisioningFailed",
101 {
102 stage: ManagedEndpointDeprovisioningStage,
103 userId: Schema.String,
104 environmentId: Schema.String,
105 tunnelId: Schema.optionalKey(Schema.String),
106 dnsRecordId: Schema.optionalKey(Schema.String),
107 cause: Schema.Defect(),
108 },
109) {
110 override get message(): string {
111 return `Managed endpoint deprovisioning failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
112 }
113}
114
115export class ManagedEndpointOriginNotAllowed extends Schema.TaggedError<ManagedEndpointOriginNotAllowed>()(
116 "ManagedEndpointOriginNotAllowed",
117 {
118 userId: Schema.String,
119 environmentId: Schema.String,
120 host: Schema.String,
121 port: Schema.Number,
122 },
123) {
124 override get message(): string {
125 return `Managed endpoint origin '${this.host}:${this.port}' is not allowed for user '${this.userId}', environment '${this.environmentId}'`;
126 }
127}
128
129export type ManagedEndpointProviderError =
130 | ManagedEndpointProvisioningNotConfigured
131 | ManagedEndpointProvisioningFailed
132 | ManagedEndpointOriginNotAllowed
133 | ManagedTunnelLimits.ManagedTunnelLimitExceeded;
134
135export interface ManagedEndpointProvisioningResult {
136 readonly endpoint: RelayManagedEndpoint;
137 readonly runtime: RelayManagedEndpointRuntimeConfig;
138}
139
140export type ManagedEndpointOriginSyncResult = "ready" | "recovery_required";
141
142export type ManagedEndpointDeprovisionTarget = ManagedEndpointAllocations.ManagedEndpointAllocation;
143
144export class ManagedEndpointProvider extends Context.Service<
145 ManagedEndpointProvider,
146 {
147 readonly provision: (input: {
148 readonly userId: string;
149 readonly environmentId: string;
150 readonly origin: RelayManagedEndpointOrigin;
151 }) => Effect.Effect<ManagedEndpointProvisioningResult, ManagedEndpointProviderError>;
152 readonly reconcileOrigin: (input: {
153 readonly userId: string;
154 readonly environmentId: string;
155 readonly tunnelId: string;
156 readonly origin: RelayManagedEndpointOrigin;
157 readonly endpoint: RelayManagedEndpoint;
158 }) => Effect.Effect<ManagedEndpointOriginSyncResult, ManagedEndpointProviderError>;
159 /**
160 * Captures the allocation generation owned by an unlink before its link
161 * revocation commits. Passing this target to `deprovision` prevents a
162 * concurrent relink from having its newer allocation torn down.
163 */
164 readonly prepareDeprovision: (input: {
165 readonly userId: string;
166 readonly environmentId: string;
167 }) => Effect.Effect<
168 ManagedEndpointDeprovisionTarget | null,
169 ManagedEndpointDeprovisioningFailed
170 >;
171 readonly deprovision: (input: {
172 readonly userId: string;
173 readonly environmentId: string;
174 readonly target?: ManagedEndpointDeprovisionTarget | null;
175 }) => Effect.Effect<boolean, ManagedEndpointDeprovisioningFailed>;
176 /**
177 * Resolves to whether the caller's connector token is now dead: true when
178 * the tunnel was deleted (or none was recorded to begin with), false when
179 * a concurrent provision outbid the release claim and the recorded tunnel
180 * — and any token issued for it — stays live.
181 */
182 readonly release: (input: {
183 readonly userId: string;
184 readonly environmentId: string;
185 readonly expectedTunnelId?: string;
186 readonly expectedInactiveBefore?: string;
187 readonly expectedStatus?: "inactive" | "down";
188 readonly markReleased?: boolean;
189 }) => Effect.Effect<boolean, ManagedEndpointDeprovisioningFailed>;
190 }
191>()("t3code-relay/environments/ManagedEndpointProvider") {}
192
193export interface ManagedEndpointTunnel {
194 readonly id?: string | null;
195 readonly name?: string | null;
196 readonly status?: string | null;
197 readonly createdAt?: string | null;
198 readonly connsInactiveAt?: string | null;
199 readonly deletedAt?: string | null;
200}
201
202export interface ManagedEndpointTunnelListRequest {
203 readonly isDeleted: false;
204 readonly name?: string;
205 readonly includePrefix?: string;
206 readonly status?: "inactive" | "down";
207 readonly existedAt?: string;
208 readonly wasInactiveAt?: string;
209 readonly page?: number;
210 readonly perPage?: number;
211}
212
213const ManagedEndpointTunnelClientOperation = Schema.Literals([
214 "get",
215 "list",
216 "create",
217 "put-configuration",
218 "get-token",
219 "delete",
220]);
221
222export class ManagedEndpointTunnelClientError extends Schema.TaggedError<ManagedEndpointTunnelClientError>()(
223 "ManagedEndpointTunnelClientError",
224 {
225 operation: ManagedEndpointTunnelClientOperation,
226 tunnelName: Schema.optionalKey(Schema.String),
227 tunnelId: Schema.optionalKey(Schema.String),
228 cause: Schema.Defect(),
229 },
230) {
231 override get message(): string {
232 const target = this.tunnelId ?? this.tunnelName;
233 return `Managed endpoint tunnel provider '${this.operation}' request failed${target === undefined ? "" : ` for '${target}'`}`;
234 }
235}
236
237export class ManagedEndpointTunnelClient extends Context.Service<
238 ManagedEndpointTunnelClient,
239 {
240 readonly get: (
241 tunnelId: string,
242 ) => Effect.Effect<ManagedEndpointTunnel, ManagedEndpointTunnelClientError>;
243 readonly list: (request: ManagedEndpointTunnelListRequest) => Effect.Effect<
244 {
245 readonly result: ReadonlyArray<ManagedEndpointTunnel>;
246 readonly resultInfo?: {
247 readonly page?: number | null;
248 readonly perPage?: number | null;
249 readonly totalCount?: number | null;
250 } | null;
251 },
252 ManagedEndpointTunnelClientError
253 >;
254 readonly create: (request: {
255 readonly name: string;
256 readonly configSrc: "cloudflare";
257 }) => Effect.Effect<ManagedEndpointTunnel, ManagedEndpointTunnelClientError>;
258 readonly putConfiguration: (
259 tunnelId: string,
260 config: {
261 readonly ingress: Array<{
262 readonly hostname?: string;
263 readonly service: string;
264 }>;
265 },
266 ) => Effect.Effect<unknown, ManagedEndpointTunnelClientError>;
267 readonly getToken: (
268 tunnelId: string,
269 ) => Effect.Effect<string, ManagedEndpointTunnelClientError>;
270 readonly delete: (tunnelId: string) => Effect.Effect<unknown, ManagedEndpointTunnelClientError>;
271 }
272>()("t3code-relay/environments/ManagedEndpointProvider/ManagedEndpointTunnelClient") {}
273
274export const layerTunnelClient = (client: ManagedEndpointTunnelClient["Service"]) =>
275 Layer.succeed(ManagedEndpointTunnelClient, client);
276
277interface ManagedEndpointCnameRecordInput {
278 readonly type: "CNAME";
279 readonly name: string;
280 readonly content: string;
281 readonly ttl: 1;
282 readonly proxied: true;
283}
284
285const ManagedEndpointDnsClientOperation = Schema.Literals([
286 "list-records",
287 "create-record",
288 "update-record",
289 "delete-record",
290]);
291
292export class ManagedEndpointDnsClientError extends Schema.TaggedError<ManagedEndpointDnsClientError>()(
293 "ManagedEndpointDnsClientError",
294 {
295 operation: ManagedEndpointDnsClientOperation,
296 hostname: Schema.optionalKey(Schema.String),
297 dnsRecordId: Schema.optionalKey(Schema.String),
298 cause: Schema.Defect(),
299 },
300) {
301 override get message(): string {
302 const target = this.dnsRecordId ?? this.hostname;
303 return `Managed endpoint DNS provider '${this.operation}' request failed${target === undefined ? "" : ` for '${target}'`}`;
304 }
305}
306
307export class ManagedEndpointDnsClient extends Context.Service<
308 ManagedEndpointDnsClient,
309 {
310 readonly listRecords: (
311 hostname: string,
312 ) => Effect.Effect<ReadonlyArray<{ readonly id: string }>, ManagedEndpointDnsClientError>;
313 readonly createRecord: (
314 request: ManagedEndpointCnameRecordInput,
315 ) => Effect.Effect<{ readonly id: string }, ManagedEndpointDnsClientError>;
316 readonly updateRecord: (
317 dnsRecordId: string,
318 request: ManagedEndpointCnameRecordInput,
319 ) => Effect.Effect<unknown, ManagedEndpointDnsClientError>;
320 readonly deleteRecord: (
321 dnsRecordId: string,
322 ) => Effect.Effect<unknown, ManagedEndpointDnsClientError>;
323 }
324>()("t3code-relay/environments/ManagedEndpointProvider/ManagedEndpointDnsClient") {}
325
326export const layerDnsClient = (client: ManagedEndpointDnsClient["Service"]) =>
327 Layer.succeed(ManagedEndpointDnsClient, client);
328
329const requireCloudflareSettings = Effect.fnUntraced(function* (
330 settings: RelayConfiguration.RelayConfiguration["Service"],
331 input: { readonly userId: string; readonly environmentId: string },
332) {
333 const baseDomain = settings.managedEndpointBaseDomain;
334 const namespace = settings.managedEndpointNamespace;
335 const missingSettings: Array<"managedEndpointBaseDomain" | "managedEndpointNamespace"> = [];
336 if (!baseDomain) {
337 missingSettings.push("managedEndpointBaseDomain");
338 }
339 if (!namespace) {
340 missingSettings.push("managedEndpointNamespace");
341 }
342 if (!baseDomain || !namespace) {
343 return yield* new ManagedEndpointProvisioningNotConfigured({
344 ...input,
345 missingSettings,
346 });
347 }
348 return {
349 baseDomain,
350 namespace,
351 };
352});
353
354function formatOriginService(origin: RelayManagedEndpointOrigin): string {
355 const host = origin.localHttpHost.includes(":")
356 ? `[${origin.localHttpHost.replace(/^\[(.*)\]$/u, "$1")}]`
357 : origin.localHttpHost;
358 return `http://${host}:${origin.localHttpPort}`;
359}
360
361function normalizeHostname(hostname: string): string {
362 return hostname
363 .trim()
364 .toLowerCase()
365 .replace(/\.$/u, "")
366 .replace(/^\[(.*)\]$/u, "$1");
367}
368
369function isLoopbackOrigin(origin: RelayManagedEndpointOrigin): boolean {
370 const hostname = normalizeHostname(origin.localHttpHost);
371 return (
372 (hostname === "127.0.0.1" || hostname === "::1" || hostname === "localhost") &&
373 Number.isInteger(origin.localHttpPort) &&
374 origin.localHttpPort > 0 &&
375 origin.localHttpPort <= 65_535
376 );
377}
378
379export function isManagedEndpointNotFound(cause: unknown): boolean {
380 if (typeof cause !== "object" || cause === null) {
381 return false;
382 }
383 if ("_tag" in cause && (cause._tag === "NotFound" || cause._tag === "TunnelNotFound")) {
384 return true;
385 }
386 if ("status" in cause && cause.status === 404) {
387 return true;
388 }
389 return "cause" in cause && isManagedEndpointNotFound(cause.cause);
390}
391
392/**
393 * Cloudflare refuses to delete a tunnel while a connector is still attached,
394 * either one that has not finished draining or another runtime still serving
395 * the tunnel.
396 */
397export function isManagedEndpointTunnelInUse(cause: unknown): boolean {
398 if (typeof cause !== "object" || cause === null) {
399 return false;
400 }
401 if (
402 "message" in cause &&
403 typeof cause.message === "string" &&
404 cause.message.includes("has active connections")
405 ) {
406 return true;
407 }
408 return "cause" in cause && isManagedEndpointTunnelInUse(cause.cause);
409}
410
411type ManagedEndpointClientError = ManagedEndpointTunnelClientError | ManagedEndpointDnsClientError;
412
413const ignoreNotFound = <A>(
414 effect: Effect.Effect<A, ManagedEndpointClientError>,
415): Effect.Effect<void, ManagedEndpointClientError> =>
416 effect.pipe(
417 Effect.asVoid,
418 Effect.catchTags({
419 ManagedEndpointTunnelClientError: (error) =>
420 isManagedEndpointNotFound(error.cause) ? Effect.void : Effect.fail(error),
421 ManagedEndpointDnsClientError: (error) =>
422 isManagedEndpointNotFound(error.cause) ? Effect.void : Effect.fail(error),
423 }),
424 );
425
426export const make = Effect.gen(function* () {
427 const config = yield* RelayConfiguration.RelayConfiguration;
428 const crypto = yield* Crypto.Crypto;
429 const tunnels = yield* ManagedEndpointTunnelClient;
430 const dns = yield* ManagedEndpointDnsClient;
431 const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;
432 const tunnelLimits = yield* ManagedTunnelLimits.ManagedTunnelLimits;
433
434 const updateExistingDnsRecords = Effect.fnUntraced(function* (
435 records: ReadonlyArray<{ readonly id: string }>,
436 preferredDnsRecordId: string | null,
437 dnsRecord: ManagedEndpointCnameRecordInput,
438 ) {
439 const keptRecord = records.find((record) => record.id === preferredDnsRecordId) ?? records[0];
440 if (keptRecord === undefined) {
441 return null;
442 }
443 yield* Effect.forEach(
444 records,
445 (record) => (record.id === keptRecord.id ? Effect.void : dns.deleteRecord(record.id)),
446 { discard: true },
447 );
448 yield* dns.updateRecord(keptRecord.id, dnsRecord);
449 return keptRecord.id;
450 });
451
452 const ensureDnsRecord = Effect.fnUntraced(function* (
453 hostname: string,
454 preferredDnsRecordId: string | null,
455 dnsRecord: ManagedEndpointCnameRecordInput,
456 ) {
457 if (preferredDnsRecordId !== null) {
458 const checkpointedRecordUpdated = yield* dns
459 .updateRecord(preferredDnsRecordId, dnsRecord)
460 .pipe(
461 Effect.as(true),
462 Effect.catchTags({
463 ManagedEndpointDnsClientError: (error) =>
464 isManagedEndpointNotFound(error.cause) ? Effect.succeed(false) : Effect.fail(error),
465 }),
466 );
467 if (checkpointedRecordUpdated) {
468 return preferredDnsRecordId;
469 }
470 }
471 const existingDnsRecords = yield* dns.listRecords(hostname);
472 const existingDnsRecordId = yield* updateExistingDnsRecords(
473 existingDnsRecords,
474 preferredDnsRecordId,
475 dnsRecord,
476 );
477 if (existingDnsRecordId !== null) {
478 return existingDnsRecordId;
479 }
480 return yield* dns.createRecord(dnsRecord).pipe(
481 Effect.map((record) => record.id),
482 Effect.catchTags({
483 ManagedEndpointDnsClientError: (createError) =>
484 Effect.gen(function* () {
485 let records = yield* dns.listRecords(hostname);
486 for (let attempt = 0; records.length === 0 && attempt < 4; attempt++) {
487 yield* Effect.sleep("200 millis");
488 records = yield* dns.listRecords(hostname);
489 }
490 return records;
491 }).pipe(
492 Effect.flatMap((records) =>
493 records.length > 0
494 ? updateExistingDnsRecords(records, preferredDnsRecordId, dnsRecord)
495 : Effect.fail(createError),
496 ),
497 Effect.filterOrFail(
498 (dnsRecordId) => dnsRecordId !== null,
499 () => createError,
500 ),
501 ),
502 }),
503 );
504 });
505
506 const prepareDeprovision = Effect.fn("relay.managed_endpoint_provider.prepare_deprovision")(
507 function* (input: { readonly userId: string; readonly environmentId: string }) {
508 return yield* allocations.get(input).pipe(
509 Effect.mapError(
510 (cause) =>
511 new ManagedEndpointDeprovisioningFailed({
512 ...input,
513 stage: "load-allocation",
514 cause,
515 }),
516 ),
517 );
518 },
519 );
520
521 const reconcileOrigin = Effect.fn("relay.managed_endpoint_provider.reconcile_origin")(
522 function* (input: {
523 readonly userId: string;
524 readonly environmentId: string;
525 readonly tunnelId: string;
526 readonly origin: RelayManagedEndpointOrigin;
527 readonly endpoint: RelayManagedEndpoint;
528 }) {
529 if (!isLoopbackOrigin(input.origin)) {
530 return yield* new ManagedEndpointOriginNotAllowed({
531 userId: input.userId,
532 environmentId: input.environmentId,
533 host: input.origin.localHttpHost,
534 port: input.origin.localHttpPort,
535 });
536 }
537 const allocation = yield* allocations.get(input).pipe(
538 Effect.mapError(
539 (cause) =>
540 new ManagedEndpointProvisioningFailed({
541 ...input,
542 stage: "load-allocation",
543 cause,
544 }),
545 ),
546 );
547 if (
548 allocation === null ||
549 allocation.tunnelId !== input.tunnelId ||
550 allocation.dnsRecordId === null ||
551 allocation.readyAt === null
552 ) {
553 return "recovery_required";
554 }
555 const cf = yield* requireCloudflareSettings(config, input);
556 const recordedEndpoint = ManagedEndpointAllocations.resolveReadyManagedEndpoint({
557 allocation,
558 baseDomain: cf.baseDomain,
559 });
560 if (
561 recordedEndpoint === null ||
562 recordedEndpoint.httpBaseUrl !== input.endpoint.httpBaseUrl ||
563 recordedEndpoint.wsBaseUrl !== input.endpoint.wsBaseUrl ||
564 recordedEndpoint.providerKind !== input.endpoint.providerKind
565 ) {
566 return yield* new ManagedEndpointProvisioningFailed({
567 ...input,
568 stage: "verify-endpoint",
569 reason: "endpoint-mismatch",
570 hostname: allocation.hostname,
571 });
572 }
573 // A release keeps the recorded tunnel id, so the record alone cannot
574 // tell a live tunnel from one deleted by a shutdown whose host was
575 // killed before it dropped its config. Ask Cloudflare, or the host
576 // starts a connector that can never connect.
577 const recorded = yield* tunnels.get(input.tunnelId).pipe(
578 Effect.asSome,
579 Effect.catchTags({
580 ManagedEndpointTunnelClientError: (cause) =>
581 isManagedEndpointNotFound(cause.cause)
582 ? Effect.succeedNone
583 : Effect.fail(
584 new ManagedEndpointProvisioningFailed({
585 userId: input.userId,
586 environmentId: input.environmentId,
587 stage: "verify-tunnel",
588 tunnelId: input.tunnelId,
589 cause,
590 }),
591 ),
592 }),
593 );
594 if (Option.isNone(recorded) || recorded.value.deletedAt) {
595 return "recovery_required";
596 }
597 if (
598 allocation.origin?.localHttpHost === input.origin.localHttpHost &&
599 allocation.origin.localHttpPort === input.origin.localHttpPort
600 ) {
601 return "ready";
602 }
603
604 const updated = yield* allocations
605 .withClaimedTunnel(
606 {
607 userId: input.userId,
608 environmentId: input.environmentId,
609 tunnelId: input.tunnelId,
610 generation: allocation.generation,
611 },
612 tunnels
613 .putConfiguration(input.tunnelId, {
614 ingress: [
615 {
616 hostname: allocation.hostname,
617 service: formatOriginService(input.origin),
618 },
619 { service: "http_status:404" },
620 ],
621 })
622 .pipe(
623 Effect.as("configured" as const),
624 Effect.catchTags({
625 ManagedEndpointTunnelClientError: (error) =>
626 isManagedEndpointNotFound(error.cause)
627 ? Effect.succeed("missing" as const)
628 : Effect.fail(error),
629 }),
630 Effect.filterOrElse(
631 (result): result is "missing" => result === "missing",
632 () =>
633 allocations
634 .markReady({
635 ...input,
636 generation: allocation.generation,
637 })
638 .pipe(
639 Effect.map((updated) =>
640 updated ? ("configured" as const) : ("stale" as const),
641 ),
642 ),
643 ),
644 ),
645 )
646 .pipe(
647 Effect.mapError(
648 (cause) =>
649 new ManagedEndpointProvisioningFailed({
650 ...input,
651 stage: "sync-origin",
652 cause,
653 }),
654 ),
655 );
656 if (Option.isNone(updated) || updated.value === "stale") {
657 return yield* new ManagedEndpointProvisioningFailed({
658 ...input,
659 stage: "sync-origin",
660 reason: "claim-lost",
661 });
662 }
663 return updated.value === "configured" ? "ready" : "recovery_required";
664 },
665 );
666
667 return ManagedEndpointProvider.of({
668 prepareDeprovision,
669 reconcileOrigin,
670 deprovision: Effect.fn("relay.managed_endpoint_provider.deprovision")(function* (input) {
671 yield* Effect.annotateCurrentSpan({
672 "relay.user_id": input.userId,
673 "relay.environment_id": input.environmentId,
674 });
675 const allocation =
676 input.target === undefined ? yield* prepareDeprovision(input) : input.target;
677 if (allocation === null) {
678 return true;
679 }
680 const claimedGeneration = yield* allocations
681 .claimDeprovision({
682 userId: input.userId,
683 environmentId: input.environmentId,
684 generation: allocation.generation,
685 })
686 .pipe(
687 Effect.mapError(
688 (cause) =>
689 new ManagedEndpointDeprovisioningFailed({
690 ...input,
691 stage: "claim-deprovision",
692 ...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),
693 ...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),
694 cause,
695 }),
696 ),
697 );
698 if (claimedGeneration === null) {
699 return false;
700 }
701 const tunnelId = allocation.tunnelId;
702 const deprovision = Effect.gen(function* () {
703 const dnsRecordId = allocation.dnsRecordId;
704 if (dnsRecordId !== null) {
705 yield* ignoreNotFound(dns.deleteRecord(dnsRecordId)).pipe(
706 Effect.mapError(
707 (cause) =>
708 new ManagedEndpointDeprovisioningFailed({
709 ...input,
710 stage: "delete-dns-record",
711 dnsRecordId,
712 cause,
713 }),
714 ),
715 );
716 }
717 if (tunnelId !== null) {
718 yield* ignoreNotFound(tunnels.delete(tunnelId)).pipe(
719 Effect.mapError(
720 (cause) =>
721 new ManagedEndpointDeprovisioningFailed({
722 ...input,
723 stage: "delete-tunnel",
724 tunnelId,
725 cause,
726 }),
727 ),
728 );
729 }
730 return yield* allocations
731 .removeClaimed({
732 userId: input.userId,
733 environmentId: input.environmentId,
734 generation: claimedGeneration,
735 })
736 .pipe(
737 Effect.mapError(
738 (cause) =>
739 new ManagedEndpointDeprovisioningFailed({
740 ...input,
741 stage: "remove-allocation",
742 ...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),
743 ...(allocation.dnsRecordId === null
744 ? {}
745 : { dnsRecordId: allocation.dnsRecordId }),
746 cause,
747 }),
748 ),
749 );
750 });
751 if (tunnelId === null) {
752 return yield* deprovision;
753 }
754 const removed = yield* allocations
755 .withClaimedTunnel(
756 {
757 userId: input.userId,
758 environmentId: input.environmentId,
759 tunnelId,
760 generation: claimedGeneration,
761 },
762 deprovision,
763 )
764 .pipe(
765 Effect.catchTags({
766 ManagedEndpointAllocationPersistenceError: (cause) =>
767 Effect.fail(
768 new ManagedEndpointDeprovisioningFailed({
769 ...input,
770 stage: "claim-deprovision",
771 tunnelId,
772 cause,
773 }),
774 ),
775 }),
776 );
777 return Option.getOrElse(removed, () => false);
778 }),
779 release: Effect.fn("relay.managed_endpoint_provider.release")(function* (input) {
780 yield* Effect.annotateCurrentSpan({
781 "relay.user_id": input.userId,
782 "relay.environment_id": input.environmentId,
783 });
784 const allocation = yield* allocations.get(input).pipe(
785 Effect.mapError(
786 (cause) =>
787 new ManagedEndpointDeprovisioningFailed({
788 ...input,
789 stage: "load-allocation",
790 cause,
791 }),
792 ),
793 );
794 const tunnelId = allocation?.tunnelId ?? null;
795 if (allocation === null || tunnelId === null) {
796 return true;
797 }
798 if (input.expectedTunnelId !== undefined && input.expectedTunnelId !== tunnelId) {
799 return false;
800 }
801 // Claim the release against the allocation's current generation before
802 // touching Cloudflare. A provision racing this release (fast environment
803 // restart) increments the generation when it records its tunnel, so a stale
804 // claim means the recorded tunnel may already back a fresh connector and
805 // must be left alive.
806 const claimedGeneration = yield* allocations
807 .claimRelease({
808 userId: input.userId,
809 environmentId: input.environmentId,
810 tunnelId,
811 generation: allocation.generation,
812 })
813 .pipe(
814 Effect.mapError(
815 (cause) =>
816 new ManagedEndpointDeprovisioningFailed({
817 ...input,
818 stage: "claim-release",
819 tunnelId,
820 cause,
821 }),
822 ),
823 );
824 if (claimedGeneration === null) {
825 return false;
826 }
827 const confirmTunnelGone = (
828 failure: ManagedEndpointDeprovisioningFailed,
829 ): Effect.Effect<void, ManagedEndpointDeprovisioningFailed> =>
830 tunnels.get(tunnelId).pipe(
831 Effect.andThen(Effect.fail(failure)),
832 Effect.catchTags({
833 ManagedEndpointTunnelClientError: (lookupFailure) =>
834 isManagedEndpointNotFound(lookupFailure.cause) ? Effect.void : Effect.fail(failure),
835 }),
836 );
837 const deleteTunnel = ignoreNotFound(tunnels.delete(tunnelId)).pipe(
838 Effect.mapError(
839 (cause) =>
840 new ManagedEndpointDeprovisioningFailed({
841 ...input,
842 stage: "delete-tunnel",
843 tunnelId,
844 cause,
845 }),
846 ),
847 );
848 if (input.expectedInactiveBefore !== undefined && input.expectedStatus !== undefined) {
849 const expectedStatus = input.expectedStatus;
850 const inactiveBefore = input.expectedInactiveBefore;
851 const currentTunnel = yield* tunnels.get(tunnelId).pipe(
852 Effect.asSome,
853 Effect.catchTags({
854 ManagedEndpointTunnelClientError: (cause) =>
855 isManagedEndpointNotFound(cause.cause)
856 ? Effect.succeedNone
857 : Effect.fail(
858 new ManagedEndpointDeprovisioningFailed({
859 ...input,
860 stage: "load-tunnel",
861 tunnelId,
862 cause,
863 }),
864 ),
865 }),
866 );
867 if (Option.isNone(currentTunnel)) {
868 return true;
869 }
870 const inactiveAt =
871 expectedStatus === "down"
872 ? currentTunnel.value.connsInactiveAt
873 : currentTunnel.value.createdAt;
874 if (
875 currentTunnel.value.id !== tunnelId ||
876 currentTunnel.value.status !== expectedStatus ||
877 typeof inactiveAt !== "string"
878 ) {
879 return false;
880 }
881 const inactiveTime = DateTime.make(inactiveAt);
882 const cutoff = DateTime.make(inactiveBefore);
883 if (
884 Option.isNone(inactiveTime) ||
885 Option.isNone(cutoff) ||
886 inactiveTime.value.epochMilliseconds > cutoff.value.epochMilliseconds
887 ) {
888 return false;
889 }
890 }
891 const released = yield* allocations
892 .withClaimedTunnel(
893 {
894 userId: input.userId,
895 environmentId: input.environmentId,
896 tunnelId,
897 generation: claimedGeneration,
898 },
899 Effect.gen(function* () {
900 const finalGeneration = yield* allocations
901 .claimRelease({
902 userId: input.userId,
903 environmentId: input.environmentId,
904 tunnelId,
905 generation: claimedGeneration,
906 ...(input.markReleased === true ? { markReleased: true } : {}),
907 })
908 .pipe(
909 Effect.mapError(
910 (cause) =>
911 new ManagedEndpointDeprovisioningFailed({
912 ...input,
913 stage: "claim-release",
914 tunnelId,
915 cause,
916 }),
917 ),
918 );
919 if (finalGeneration === null) {
920 return false;
921 }
922 // A delete whose response is lost (a timeout) may still have
923 // removed the tunnel. Ask Cloudflare before rolling back: if the
924 // tunnel is gone, the delete happened and the claim, including any
925 // released marker, must commit, since no later sweep can find
926 // this tunnel again to retry.
927 return yield* deleteTunnel.pipe(
928 Effect.as(true),
929 Effect.catchIf(
930 (error) => isManagedEndpointTunnelInUse(error.cause),
931 () => Effect.succeed(false),
932 ),
933 Effect.catchTags({
934 ManagedEndpointDeprovisioningFailed: (failure) =>
935 confirmTunnelGone(failure).pipe(Effect.as(true)),
936 }),
937 );
938 }),
939 )
940 .pipe(
941 Effect.catchTags({
942 ManagedEndpointAllocationPersistenceError: (cause) =>
943 Effect.fail(
944 new ManagedEndpointDeprovisioningFailed({
945 ...input,
946 stage: "claim-release",
947 tunnelId,
948 cause,
949 }),
950 ),
951 }),
952 );
953 // The recorded tunnelId is now stale, but the allocation row is left
954 // untouched deliberately: connect/status authorization requires a fully
955 // recorded allocation, and an offline environment must keep reporting
956 // "offline" (health probe fails) rather than "not authorized".
957 return Option.getOrElse(released, () => false);
958 }),
959 provision: Effect.fn("relay.managed_endpoint_provider.provision")(function* (input) {
960 yield* Effect.annotateCurrentSpan({
961 "relay.user_id": input.userId,
962 "relay.environment_id": input.environmentId,
963 "relay.managed_endpoint.origin_host": input.origin.localHttpHost,
964 "relay.managed_endpoint.origin_port": input.origin.localHttpPort,
965 });
966 if (!isLoopbackOrigin(input.origin)) {
967 return yield* new ManagedEndpointOriginNotAllowed({
968 userId: input.userId,
969 environmentId: input.environmentId,
970 host: input.origin.localHttpHost,
971 port: input.origin.localHttpPort,
972 });
973 }
974 const cf = yield* requireCloudflareSettings(config, input);
975 const environmentHash = yield* crypto
976 .digest(
977 "SHA-256",
978 new TextEncoder().encode(
979 managedEndpointDigestInput(cf.namespace, input.userId, input.environmentId),
980 ),
981 )
982 .pipe(
983 Effect.map(Hex.encode),
984 Effect.mapError(
985 (cause) =>
986 new ManagedEndpointProvisioningFailed({
987 userId: input.userId,
988 environmentId: input.environmentId,
989 stage: "derive-environment-hash",
990 cause,
991 }),
992 ),
993 );
994 const requestedHostname = managedEndpointHostname(
995 cf.namespace,
996 cf.baseDomain,
997 environmentHash,
998 );
999 const requestedTunnelName = managedEndpointTunnelName(cf.namespace, environmentHash);
1000 yield* tunnelLimits
1001 .ensureCapacity({
1002 userId: input.userId,
1003 environmentId: input.environmentId,
1004 })
1005 .pipe(
1006 Effect.catchTags({
1007 ManagedTunnelLimitPersistenceError: (cause) =>
1008 Effect.fail(
1009 new ManagedEndpointProvisioningFailed({
1010 userId: input.userId,
1011 environmentId: input.environmentId,
1012 stage: "check-tunnel-limit",
1013 hostname: requestedHostname,
1014 tunnelName: requestedTunnelName,
1015 cause,
1016 }),
1017 ),
1018 }),
1019 );
1020 const allocation = yield* allocations
1021 .reserve({
1022 userId: input.userId,
1023 environmentId: input.environmentId,
1024 hostname: requestedHostname,
1025 tunnelName: requestedTunnelName,
1026 })
1027 .pipe(
1028 Effect.mapError(
1029 (cause) =>
1030 new ManagedEndpointProvisioningFailed({
1031 userId: input.userId,
1032 environmentId: input.environmentId,
1033 stage: "reserve-allocation",
1034 hostname: requestedHostname,
1035 tunnelName: requestedTunnelName,
1036 cause,
1037 }),
1038 ),
1039 );
1040 const { hostname, tunnelName } = allocation;
1041
1042 const tunnelResponse = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe(
1043 Effect.map((tunnels) => tunnels.result),
1044 Effect.map(Arr.findFirst((tunnel) => tunnel.name === tunnelName)),
1045 Effect.flatMap(
1046 Option.match({
1047 onSome: (tunnel) => Effect.succeed(tunnel),
1048 onNone: () => tunnels.create({ name: tunnelName, configSrc: "cloudflare" }),
1049 }),
1050 ),
1051 Effect.mapError(
1052 (cause) =>
1053 new ManagedEndpointProvisioningFailed({
1054 userId: input.userId,
1055 environmentId: input.environmentId,
1056 stage: "ensure-tunnel",
1057 hostname,
1058 tunnelName,
1059 cause,
1060 }),
1061 ),
1062 );
1063 if (!tunnelResponse.id || tunnelResponse.name !== tunnelName) {
1064 return yield* new ManagedEndpointProvisioningFailed({
1065 userId: input.userId,
1066 environmentId: input.environmentId,
1067 stage: "validate-tunnel-response",
1068 reason: "invalid-tunnel-response",
1069 hostname,
1070 tunnelName,
1071 ...(tunnelResponse.id ? { returnedTunnelId: tunnelResponse.id } : {}),
1072 ...(tunnelResponse.name ? { returnedTunnelName: tunnelResponse.name } : {}),
1073 });
1074 }
1075 const tunnel = { id: tunnelResponse.id, name: tunnelResponse.name };
1076 const tunnelGeneration = yield* allocations
1077 .recordTunnel({
1078 userId: input.userId,
1079 environmentId: input.environmentId,
1080 tunnelId: tunnel.id,
1081 generation: allocation.generation,
1082 })
1083 .pipe(
1084 Effect.mapError(
1085 (cause) =>
1086 new ManagedEndpointProvisioningFailed({
1087 userId: input.userId,
1088 environmentId: input.environmentId,
1089 stage: "record-tunnel",
1090 hostname,
1091 tunnelName,
1092 tunnelId: tunnel.id,
1093 cause,
1094 }),
1095 ),
1096 );
1097 if (tunnelGeneration === null) {
1098 // A newer provision can adopt this tunnel by name at any point after
1099 // our claim fails. Leave it available for that provision or a retry.
1100 return yield* new ManagedEndpointProvisioningFailed({
1101 userId: input.userId,
1102 environmentId: input.environmentId,
1103 stage: "record-tunnel",
1104 reason: "claim-lost",
1105 hostname,
1106 tunnelName,
1107 tunnelId: tunnel.id,
1108 });
1109 }
1110
1111 const configured = yield* allocations
1112 .withClaimedTunnel(
1113 {
1114 userId: input.userId,
1115 environmentId: input.environmentId,
1116 tunnelId: tunnel.id,
1117 generation: tunnelGeneration,
1118 },
1119 tunnels
1120 .putConfiguration(tunnel.id, {
1121 ingress: [
1122 {
1123 hostname,
1124 service: formatOriginService(input.origin),
1125 },
1126 { service: "http_status:404" },
1127 ],
1128 })
1129 .pipe(
1130 Effect.mapError(
1131 (cause) =>
1132 new ManagedEndpointProvisioningFailed({
1133 userId: input.userId,
1134 environmentId: input.environmentId,
1135 stage: "configure-tunnel",
1136 hostname,
1137 tunnelName,
1138 tunnelId: tunnel.id,
1139 cause,
1140 }),
1141 ),
1142 ),
1143 )
1144 .pipe(
1145 Effect.catchTags({
1146 ManagedEndpointAllocationPersistenceError: (cause) =>
1147 Effect.fail(
1148 new ManagedEndpointProvisioningFailed({
1149 userId: input.userId,
1150 environmentId: input.environmentId,
1151 stage: "configure-tunnel",
1152 hostname,
1153 tunnelName,
1154 tunnelId: tunnel.id,
1155 cause,
1156 }),
1157 ),
1158 }),
1159 );
1160 if (Option.isNone(configured)) {
1161 return yield* new ManagedEndpointProvisioningFailed({
1162 userId: input.userId,
1163 environmentId: input.environmentId,
1164 stage: "configure-tunnel",
1165 reason: "claim-lost",
1166 hostname,
1167 tunnelName,
1168 tunnelId: tunnel.id,
1169 });
1170 }
1171
1172 const dnsRecord = {
1173 type: "CNAME",
1174 name: hostname,
1175 content: `${tunnel.id}.cfargotunnel.com`,
1176 ttl: 1,
1177 proxied: true,
1178 } as const;
1179
1180 const recordedDns = yield* allocations
1181 .withClaimedTunnel(
1182 {
1183 userId: input.userId,
1184 environmentId: input.environmentId,
1185 tunnelId: tunnel.id,
1186 generation: tunnelGeneration,
1187 },
1188 Effect.gen(function* () {
1189 const dnsRecordId = yield* ensureDnsRecord(
1190 hostname,
1191 allocation.dnsRecordId,
1192 dnsRecord,
1193 ).pipe(
1194 Effect.mapError(
1195 (cause) =>
1196 new ManagedEndpointProvisioningFailed({
1197 userId: input.userId,
1198 environmentId: input.environmentId,
1199 stage: "ensure-dns-record",
1200 hostname,
1201 tunnelName,
1202 tunnelId: tunnel.id,
1203 ...(allocation.dnsRecordId === null
1204 ? {}
1205 : { dnsRecordId: allocation.dnsRecordId }),
1206 cause,
1207 }),
1208 ),
1209 );
1210 const dnsGeneration = yield* allocations
1211 .recordDns({
1212 userId: input.userId,
1213 environmentId: input.environmentId,
1214 dnsRecordId,
1215 tunnelId: tunnel.id,
1216 generation: tunnelGeneration,
1217 })
1218 .pipe(
1219 Effect.mapError(
1220 (cause) =>
1221 new ManagedEndpointProvisioningFailed({
1222 userId: input.userId,
1223 environmentId: input.environmentId,
1224 stage: "record-dns",
1225 hostname,
1226 tunnelName,
1227 tunnelId: tunnel.id,
1228 dnsRecordId,
1229 cause,
1230 }),
1231 ),
1232 );
1233 if (dnsGeneration === null) {
1234 return yield* new ManagedEndpointProvisioningFailed({
1235 userId: input.userId,
1236 environmentId: input.environmentId,
1237 stage: "record-dns",
1238 reason: "claim-lost",
1239 hostname,
1240 tunnelName,
1241 tunnelId: tunnel.id,
1242 dnsRecordId,
1243 });
1244 }
1245 return { dnsRecordId, dnsGeneration };
1246 }),
1247 )
1248 .pipe(
1249 Effect.catchTags({
1250 ManagedEndpointAllocationPersistenceError: (cause) =>
1251 Effect.fail(
1252 new ManagedEndpointProvisioningFailed({
1253 userId: input.userId,
1254 environmentId: input.environmentId,
1255 stage: "record-dns",
1256 hostname,
1257 tunnelName,
1258 tunnelId: tunnel.id,
1259 cause,
1260 }),
1261 ),
1262 }),
1263 );
1264 if (Option.isNone(recordedDns)) {
1265 return yield* new ManagedEndpointProvisioningFailed({
1266 userId: input.userId,
1267 environmentId: input.environmentId,
1268 stage: "record-dns",
1269 reason: "claim-lost",
1270 hostname,
1271 tunnelName,
1272 tunnelId: tunnel.id,
1273 });
1274 }
1275 const { dnsRecordId, dnsGeneration } = recordedDns.value;
1276
1277 const connectorToken = yield* tunnels.getToken(tunnel.id).pipe(
1278 Effect.mapError(
1279 (cause) =>
1280 new ManagedEndpointProvisioningFailed({
1281 userId: input.userId,
1282 environmentId: input.environmentId,
1283 stage: "get-tunnel-token",
1284 hostname,
1285 tunnelName,
1286 tunnelId: tunnel.id,
1287 dnsRecordId,
1288 cause,
1289 }),
1290 ),
1291 );
1292 const ready = yield* allocations
1293 .markReady({
1294 userId: input.userId,
1295 environmentId: input.environmentId,
1296 tunnelId: tunnel.id,
1297 generation: dnsGeneration,
1298 origin: input.origin,
1299 })
1300 .pipe(
1301 Effect.mapError(
1302 (cause) =>
1303 new ManagedEndpointProvisioningFailed({
1304 userId: input.userId,
1305 environmentId: input.environmentId,
1306 stage: "mark-allocation-ready",
1307 hostname,
1308 tunnelName,
1309 tunnelId: tunnel.id,
1310 dnsRecordId,
1311 cause,
1312 }),
1313 ),
1314 );
1315 if (!ready) {
1316 return yield* new ManagedEndpointProvisioningFailed({
1317 userId: input.userId,
1318 environmentId: input.environmentId,
1319 stage: "mark-allocation-ready",
1320 reason: "claim-lost",
1321 hostname,
1322 tunnelName,
1323 tunnelId: tunnel.id,
1324 dnsRecordId,
1325 });
1326 }
1327
1328 return {
1329 endpoint: managedEndpointForHostname(hostname),
1330 runtime: {
1331 providerKind: "cloudflare_tunnel",
1332 connectorToken,
1333 tunnelId: tunnel.id,
1334 tunnelName: tunnel.name,
1335 },
1336 } satisfies ManagedEndpointProvisioningResult;
1337 }),
1338 });
1339});
1340
1341export const layer = Layer.effect(ManagedEndpointProvider, make);
1342
1343export const layerCloudflareBindings = (
1344 tunnelClient: Cloudflare.Tunnel.ReadWriteTunnelClient,
1345 dnsClient: Cloudflare.DNS.ReadWriteDnsClient,
1346 alchemyRuntimeContext: Alchemy.BaseRuntimeContext,
1347) =>
1348 layer.pipe(
1349 Layer.provideMerge(
1350 Layer.mergeAll(
1351 layerTunnelClient({
1352 get: (tunnelId) =>
1353 tunnelClient.get(tunnelId).pipe(
1354 Effect.timeout("8 seconds"),
1355 Effect.mapError(
1356 (cause) =>
1357 new ManagedEndpointTunnelClientError({
1358 operation: "get",
1359 tunnelId,
1360 cause,
1361 }),
1362 ),
1363 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1364 ),
1365 list: (request) =>
1366 tunnelClient.list(request).pipe(
1367 Effect.timeout("8 seconds"),
1368 Effect.mapError(
1369 (cause) =>
1370 new ManagedEndpointTunnelClientError({
1371 operation: "list",
1372 ...(request.name === undefined ? {} : { tunnelName: request.name }),
1373 cause,
1374 }),
1375 ),
1376 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1377 ),
1378 create: (request) =>
1379 tunnelClient.create(request).pipe(
1380 Effect.timeout("8 seconds"),
1381 Effect.mapError(
1382 (cause) =>
1383 new ManagedEndpointTunnelClientError({
1384 operation: "create",
1385 tunnelName: request.name,
1386 cause,
1387 }),
1388 ),
1389 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1390 ),
1391 putConfiguration: (tunnelId, config) =>
1392 tunnelClient.putConfiguration(tunnelId, config).pipe(
1393 Effect.timeout("8 seconds"),
1394 Effect.mapError(
1395 (cause) =>
1396 new ManagedEndpointTunnelClientError({
1397 operation: "put-configuration",
1398 tunnelId,
1399 cause,
1400 }),
1401 ),
1402 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1403 ),
1404 getToken: (tunnelId) =>
1405 tunnelClient.getToken(tunnelId).pipe(
1406 Effect.timeout("8 seconds"),
1407 Effect.mapError(
1408 (cause) =>
1409 new ManagedEndpointTunnelClientError({
1410 operation: "get-token",
1411 tunnelId,
1412 cause,
1413 }),
1414 ),
1415 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1416 ),
1417 delete: (tunnelId) =>
1418 tunnelClient.delete(tunnelId).pipe(
1419 Effect.timeout("8 seconds"),
1420 Effect.mapError(
1421 (cause) =>
1422 new ManagedEndpointTunnelClientError({
1423 operation: "delete",
1424 tunnelId,
1425 cause,
1426 }),
1427 ),
1428 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1429 ),
1430 }),
1431 layerDnsClient({
1432 listRecords: (hostname) =>
1433 dnsClient.listDnsRecords({ search: hostname }).pipe(
1434 Effect.timeout("8 seconds"),
1435 Effect.map((response) =>
1436 response.result.filter(
1437 (record): record is typeof record & { readonly id: string } =>
1438 typeof record.id === "string" &&
1439 normalizeHostname(record.name) === normalizeHostname(hostname),
1440 ),
1441 ),
1442 Effect.mapError(
1443 (cause) =>
1444 new ManagedEndpointDnsClientError({
1445 operation: "list-records",
1446 hostname,
1447 cause,
1448 }),
1449 ),
1450 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1451 ),
1452 createRecord: (request) =>
1453 dnsClient.createDnsRecord(request).pipe(
1454 Effect.timeout("8 seconds"),
1455 Effect.map((response) => ({ id: response.id })),
1456 Effect.mapError(
1457 (cause) =>
1458 new ManagedEndpointDnsClientError({
1459 operation: "create-record",
1460 hostname: request.name,
1461 cause,
1462 }),
1463 ),
1464 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1465 ),
1466 updateRecord: (dnsRecordId, request) =>
1467 dnsClient.updateDnsRecord(dnsRecordId, request).pipe(
1468 Effect.timeout("8 seconds"),
1469 Effect.mapError(
1470 (cause) =>
1471 new ManagedEndpointDnsClientError({
1472 operation: "update-record",
1473 hostname: request.name,
1474 dnsRecordId,
1475 cause,
1476 }),
1477 ),
1478 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1479 ),
1480 deleteRecord: (dnsRecordId) =>
1481 dnsClient.deleteDnsRecord(dnsRecordId).pipe(
1482 Effect.timeout("8 seconds"),
1483 Effect.mapError(
1484 (cause) =>
1485 new ManagedEndpointDnsClientError({
1486 operation: "delete-record",
1487 dnsRecordId,
1488 cause,
1489 }),
1490 ),
1491 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1492 ),
1493 }),
1494 ),
1495 ),
1496 );