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

ManagedEndpointProvider.ts

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