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 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";
26
27export class ManagedEndpointProvisioningNotConfigured extends Schema.TaggedErrorClass<ManagedEndpointProvisioningNotConfigured>()(
28 "ManagedEndpointProvisioningNotConfigured",
29 {
30 userId: Schema.String,
31 environmentId: Schema.String,
32 missingSettings: Schema.Array(
33 Schema.Literals(["managedEndpointBaseDomain", "managedEndpointNamespace"]),
34 ),
35 },
36) {
37 override get message(): string {
38 return `Managed endpoint provisioning is not configured for user '${this.userId}', environment '${this.environmentId}': missing ${this.missingSettings.join(", ")}`;
39 }
40}
41
42const ManagedEndpointProvisioningStage = Schema.Literals([
43 "derive-environment-hash",
44 "reserve-allocation",
45 "ensure-tunnel",
46 "validate-tunnel-response",
47 "record-tunnel",
48 "configure-tunnel",
49 "ensure-dns-record",
50 "record-dns",
51 "get-tunnel-token",
52 "mark-allocation-ready",
53]);
54
55export class ManagedEndpointProvisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointProvisioningFailed>()(
56 "ManagedEndpointProvisioningFailed",
57 {
58 stage: ManagedEndpointProvisioningStage,
59 userId: Schema.String,
60 environmentId: Schema.String,
61 hostname: Schema.optionalKey(Schema.String),
62 tunnelName: Schema.optionalKey(Schema.String),
63 tunnelId: Schema.optionalKey(Schema.String),
64 dnsRecordId: Schema.optionalKey(Schema.String),
65 returnedTunnelName: Schema.optionalKey(Schema.String),
66 returnedTunnelId: Schema.optionalKey(Schema.String),
67 cause: Schema.optional(Schema.Defect()),
68 },
69) {
70 override get message(): string {
71 return `Managed endpoint provisioning failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
72 }
73}
74
75const ManagedEndpointDeprovisioningStage = Schema.Literals([
76 "load-allocation",
77 "delete-dns-record",
78 "delete-tunnel",
79 "remove-allocation",
80]);
81
82export class ManagedEndpointDeprovisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointDeprovisioningFailed>()(
83 "ManagedEndpointDeprovisioningFailed",
84 {
85 stage: ManagedEndpointDeprovisioningStage,
86 userId: Schema.String,
87 environmentId: Schema.String,
88 tunnelId: Schema.optionalKey(Schema.String),
89 dnsRecordId: Schema.optionalKey(Schema.String),
90 cause: Schema.Defect(),
91 },
92) {
93 override get message(): string {
94 return `Managed endpoint deprovisioning failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
95 }
96}
97
98export class ManagedEndpointOriginNotAllowed extends Schema.TaggedErrorClass<ManagedEndpointOriginNotAllowed>()(
99 "ManagedEndpointOriginNotAllowed",
100 {
101 userId: Schema.String,
102 environmentId: Schema.String,
103 host: Schema.String,
104 port: Schema.Number,
105 },
106) {
107 override get message(): string {
108 return `Managed endpoint origin '${this.host}:${this.port}' is not allowed for user '${this.userId}', environment '${this.environmentId}'`;
109 }
110}
111
112export type ManagedEndpointProviderError =
113 | ManagedEndpointProvisioningNotConfigured
114 | ManagedEndpointProvisioningFailed
115 | ManagedEndpointOriginNotAllowed;
116
117export interface ManagedEndpointProvisioningResult {
118 readonly endpoint: RelayManagedEndpoint;
119 readonly runtime: RelayManagedEndpointRuntimeConfig;
120}
121
122export class ManagedEndpointProvider extends Context.Service<
123 ManagedEndpointProvider,
124 {
125 readonly provision: (input: {
126 readonly userId: string;
127 readonly environmentId: string;
128 readonly origin: RelayManagedEndpointOrigin;
129 }) => Effect.Effect<ManagedEndpointProvisioningResult, ManagedEndpointProviderError>;
130 readonly deprovision: (input: {
131 readonly userId: string;
132 readonly environmentId: string;
133 }) => Effect.Effect<void, ManagedEndpointDeprovisioningFailed>;
134 }
135>()("t3code-relay/environments/ManagedEndpointProvider") {}
136
137interface ManagedEndpointTunnel {
138 readonly id?: string | null;
139 readonly name?: string | null;
140}
141
142const ManagedEndpointTunnelClientOperation = Schema.Literals([
143 "list",
144 "create",
145 "put-configuration",
146 "get-token",
147 "delete",
148]);
149
150export class ManagedEndpointTunnelClientError extends Schema.TaggedErrorClass<ManagedEndpointTunnelClientError>()(
151 "ManagedEndpointTunnelClientError",
152 {
153 operation: ManagedEndpointTunnelClientOperation,
154 tunnelName: Schema.optionalKey(Schema.String),
155 tunnelId: Schema.optionalKey(Schema.String),
156 cause: Schema.Defect(),
157 },
158) {
159 override get message(): string {
160 const target = this.tunnelId ?? this.tunnelName;
161 return `Managed endpoint tunnel provider '${this.operation}' request failed${target === undefined ? "" : ` for '${target}'`}`;
162 }
163}
164
165export class ManagedEndpointTunnelClient extends Context.Service<
166 ManagedEndpointTunnelClient,
167 {
168 readonly list: (request: {
169 readonly name: string;
170 readonly isDeleted: false;
171 }) => Effect.Effect<
172 { readonly result: ReadonlyArray<ManagedEndpointTunnel> },
173 ManagedEndpointTunnelClientError
174 >;
175 readonly create: (request: {
176 readonly name: string;
177 readonly configSrc: "cloudflare";
178 }) => Effect.Effect<ManagedEndpointTunnel, ManagedEndpointTunnelClientError>;
179 readonly putConfiguration: (
180 tunnelId: string,
181 config: {
182 readonly ingress: Array<{
183 readonly hostname?: string;
184 readonly service: string;
185 }>;
186 },
187 ) => Effect.Effect<unknown, ManagedEndpointTunnelClientError>;
188 readonly getToken: (
189 tunnelId: string,
190 ) => Effect.Effect<string, ManagedEndpointTunnelClientError>;
191 readonly delete: (tunnelId: string) => Effect.Effect<unknown, ManagedEndpointTunnelClientError>;
192 }
193>()("t3code-relay/environments/ManagedEndpointProvider/ManagedEndpointTunnelClient") {}
194
195export const layerTunnelClient = (client: ManagedEndpointTunnelClient["Service"]) =>
196 Layer.succeed(ManagedEndpointTunnelClient, client);
197
198interface ManagedEndpointCnameRecordInput {
199 readonly type: "CNAME";
200 readonly name: string;
201 readonly content: string;
202 readonly ttl: 1;
203 readonly proxied: true;
204}
205
206const ManagedEndpointDnsClientOperation = Schema.Literals([
207 "list-records",
208 "create-record",
209 "update-record",
210 "delete-record",
211]);
212
213export class ManagedEndpointDnsClientError extends Schema.TaggedErrorClass<ManagedEndpointDnsClientError>()(
214 "ManagedEndpointDnsClientError",
215 {
216 operation: ManagedEndpointDnsClientOperation,
217 hostname: Schema.optionalKey(Schema.String),
218 dnsRecordId: Schema.optionalKey(Schema.String),
219 cause: Schema.Defect(),
220 },
221) {
222 override get message(): string {
223 const target = this.dnsRecordId ?? this.hostname;
224 return `Managed endpoint DNS provider '${this.operation}' request failed${target === undefined ? "" : ` for '${target}'`}`;
225 }
226}
227
228export class ManagedEndpointDnsClient extends Context.Service<
229 ManagedEndpointDnsClient,
230 {
231 readonly listRecords: (
232 hostname: string,
233 ) => Effect.Effect<ReadonlyArray<{ readonly id: string }>, ManagedEndpointDnsClientError>;
234 readonly createRecord: (
235 request: ManagedEndpointCnameRecordInput,
236 ) => Effect.Effect<{ readonly id: string }, ManagedEndpointDnsClientError>;
237 readonly updateRecord: (
238 dnsRecordId: string,
239 request: ManagedEndpointCnameRecordInput,
240 ) => Effect.Effect<unknown, ManagedEndpointDnsClientError>;
241 readonly deleteRecord: (
242 dnsRecordId: string,
243 ) => Effect.Effect<unknown, ManagedEndpointDnsClientError>;
244 }
245>()("t3code-relay/environments/ManagedEndpointProvider/ManagedEndpointDnsClient") {}
246
247export const layerDnsClient = (client: ManagedEndpointDnsClient["Service"]) =>
248 Layer.succeed(ManagedEndpointDnsClient, client);
249
250const requireCloudflareSettings = Effect.fnUntraced(function* (
251 settings: RelayConfiguration.RelayConfiguration["Service"],
252 input: { readonly userId: string; readonly environmentId: string },
253) {
254 const baseDomain = settings.managedEndpointBaseDomain;
255 const namespace = settings.managedEndpointNamespace;
256 const missingSettings: Array<"managedEndpointBaseDomain" | "managedEndpointNamespace"> = [];
257 if (!baseDomain) {
258 missingSettings.push("managedEndpointBaseDomain");
259 }
260 if (!namespace) {
261 missingSettings.push("managedEndpointNamespace");
262 }
263 if (!baseDomain || !namespace) {
264 return yield* new ManagedEndpointProvisioningNotConfigured({
265 ...input,
266 missingSettings,
267 });
268 }
269 return {
270 baseDomain,
271 namespace,
272 };
273});
274
275function formatOriginService(origin: RelayManagedEndpointOrigin): string {
276 const host = origin.localHttpHost.includes(":")
277 ? `[${origin.localHttpHost.replace(/^\[(.*)\]$/u, "$1")}]`
278 : origin.localHttpHost;
279 return `http://${host}:${origin.localHttpPort}`;
280}
281
282function normalizeHostname(hostname: string): string {
283 return hostname
284 .trim()
285 .toLowerCase()
286 .replace(/\.$/u, "")
287 .replace(/^\[(.*)\]$/u, "$1");
288}
289
290function isLoopbackOrigin(origin: RelayManagedEndpointOrigin): boolean {
291 const hostname = normalizeHostname(origin.localHttpHost);
292 return (
293 (hostname === "127.0.0.1" || hostname === "::1" || hostname === "localhost") &&
294 Number.isInteger(origin.localHttpPort) &&
295 origin.localHttpPort > 0 &&
296 origin.localHttpPort <= 65_535
297 );
298}
299
300function isNotFoundCause(cause: unknown): boolean {
301 if (typeof cause !== "object" || cause === null) {
302 return false;
303 }
304 if ("_tag" in cause && cause._tag === "NotFound") {
305 return true;
306 }
307 if ("status" in cause && cause.status === 404) {
308 return true;
309 }
310 return "cause" in cause && isNotFoundCause(cause.cause);
311}
312
313type ManagedEndpointClientError = ManagedEndpointTunnelClientError | ManagedEndpointDnsClientError;
314
315const ignoreNotFound = <A>(
316 effect: Effect.Effect<A, ManagedEndpointClientError>,
317): Effect.Effect<void, ManagedEndpointClientError> =>
318 effect.pipe(
319 Effect.asVoid,
320 Effect.catchTags({
321 ManagedEndpointTunnelClientError: (error) =>
322 isNotFoundCause(error.cause) ? Effect.void : Effect.fail(error),
323 ManagedEndpointDnsClientError: (error) =>
324 isNotFoundCause(error.cause) ? Effect.void : Effect.fail(error),
325 }),
326 );
327
328export const make = Effect.gen(function* () {
329 const config = yield* RelayConfiguration.RelayConfiguration;
330 const crypto = yield* Crypto.Crypto;
331 const tunnels = yield* ManagedEndpointTunnelClient;
332 const dns = yield* ManagedEndpointDnsClient;
333 const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;
334
335 const updateExistingDnsRecords = Effect.fnUntraced(function* (
336 records: ReadonlyArray<{ readonly id: string }>,
337 preferredDnsRecordId: string | null,
338 dnsRecord: ManagedEndpointCnameRecordInput,
339 ) {
340 const keptRecord = records.find((record) => record.id === preferredDnsRecordId) ?? records[0];
341 if (keptRecord === undefined) {
342 return null;
343 }
344 yield* Effect.forEach(
345 records,
346 (record) => (record.id === keptRecord.id ? Effect.void : dns.deleteRecord(record.id)),
347 { discard: true },
348 );
349 yield* dns.updateRecord(keptRecord.id, dnsRecord);
350 return keptRecord.id;
351 });
352
353 const ensureDnsRecord = Effect.fnUntraced(function* (
354 hostname: string,
355 preferredDnsRecordId: string | null,
356 dnsRecord: ManagedEndpointCnameRecordInput,
357 ) {
358 if (preferredDnsRecordId !== null) {
359 const checkpointedRecordUpdated = yield* dns
360 .updateRecord(preferredDnsRecordId, dnsRecord)
361 .pipe(
362 Effect.as(true),
363 Effect.catchTags({
364 ManagedEndpointDnsClientError: (error) =>
365 isNotFoundCause(error.cause) ? Effect.succeed(false) : Effect.fail(error),
366 }),
367 );
368 if (checkpointedRecordUpdated) {
369 return preferredDnsRecordId;
370 }
371 }
372 const existingDnsRecords = yield* dns.listRecords(hostname);
373 const existingDnsRecordId = yield* updateExistingDnsRecords(
374 existingDnsRecords,
375 preferredDnsRecordId,
376 dnsRecord,
377 );
378 if (existingDnsRecordId !== null) {
379 return existingDnsRecordId;
380 }
381 return yield* dns.createRecord(dnsRecord).pipe(
382 Effect.map((record) => record.id),
383 Effect.catchTags({
384 ManagedEndpointDnsClientError: (createError) =>
385 Effect.gen(function* () {
386 let records = yield* dns.listRecords(hostname);
387 for (let attempt = 0; records.length === 0 && attempt < 4; attempt++) {
388 yield* Effect.sleep("200 millis");
389 records = yield* dns.listRecords(hostname);
390 }
391 return records;
392 }).pipe(
393 Effect.flatMap((records) =>
394 records.length > 0
395 ? updateExistingDnsRecords(records, preferredDnsRecordId, dnsRecord)
396 : Effect.fail(createError),
397 ),
398 Effect.flatMap((dnsRecordId) =>
399 dnsRecordId === null ? Effect.fail(createError) : Effect.succeed(dnsRecordId),
400 ),
401 ),
402 }),
403 );
404 });
405
406 return ManagedEndpointProvider.of({
407 deprovision: Effect.fn("relay.managed_endpoint_provider.deprovision")(function* (input) {
408 yield* Effect.annotateCurrentSpan({
409 "relay.user_id": input.userId,
410 "relay.environment_id": input.environmentId,
411 });
412 const allocation = yield* allocations.get(input).pipe(
413 Effect.mapError(
414 (cause) =>
415 new ManagedEndpointDeprovisioningFailed({
416 ...input,
417 stage: "load-allocation",
418 cause,
419 }),
420 ),
421 );
422 if (allocation === null) {
423 return;
424 }
425 const dnsRecordId = allocation.dnsRecordId;
426 if (dnsRecordId !== null) {
427 yield* ignoreNotFound(dns.deleteRecord(dnsRecordId)).pipe(
428 Effect.mapError(
429 (cause) =>
430 new ManagedEndpointDeprovisioningFailed({
431 ...input,
432 stage: "delete-dns-record",
433 dnsRecordId,
434 cause,
435 }),
436 ),
437 );
438 }
439 const tunnelId = allocation.tunnelId;
440 if (tunnelId !== null) {
441 yield* ignoreNotFound(tunnels.delete(tunnelId)).pipe(
442 Effect.mapError(
443 (cause) =>
444 new ManagedEndpointDeprovisioningFailed({
445 ...input,
446 stage: "delete-tunnel",
447 tunnelId,
448 cause,
449 }),
450 ),
451 );
452 }
453 yield* allocations.remove(input).pipe(
454 Effect.mapError(
455 (cause) =>
456 new ManagedEndpointDeprovisioningFailed({
457 ...input,
458 stage: "remove-allocation",
459 ...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),
460 ...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),
461 cause,
462 }),
463 ),
464 );
465 }),
466 provision: Effect.fn("relay.managed_endpoint_provider.provision")(function* (input) {
467 yield* Effect.annotateCurrentSpan({
468 "relay.user_id": input.userId,
469 "relay.environment_id": input.environmentId,
470 "relay.managed_endpoint.origin_host": input.origin.localHttpHost,
471 "relay.managed_endpoint.origin_port": input.origin.localHttpPort,
472 });
473 if (!isLoopbackOrigin(input.origin)) {
474 return yield* new ManagedEndpointOriginNotAllowed({
475 userId: input.userId,
476 environmentId: input.environmentId,
477 host: input.origin.localHttpHost,
478 port: input.origin.localHttpPort,
479 });
480 }
481 const cf = yield* requireCloudflareSettings(config, input);
482 const environmentHash = yield* crypto
483 .digest(
484 "SHA-256",
485 new TextEncoder().encode(
486 managedEndpointDigestInput(cf.namespace, input.userId, input.environmentId),
487 ),
488 )
489 .pipe(
490 Effect.map(Encoding.encodeHex),
491 Effect.mapError(
492 (cause) =>
493 new ManagedEndpointProvisioningFailed({
494 userId: input.userId,
495 environmentId: input.environmentId,
496 stage: "derive-environment-hash",
497 cause,
498 }),
499 ),
500 );
501 const requestedHostname = managedEndpointHostname(
502 cf.namespace,
503 cf.baseDomain,
504 environmentHash,
505 );
506 const requestedTunnelName = managedEndpointTunnelName(cf.namespace, environmentHash);
507 const allocation = yield* allocations
508 .reserve({
509 userId: input.userId,
510 environmentId: input.environmentId,
511 hostname: requestedHostname,
512 tunnelName: requestedTunnelName,
513 })
514 .pipe(
515 Effect.mapError(
516 (cause) =>
517 new ManagedEndpointProvisioningFailed({
518 userId: input.userId,
519 environmentId: input.environmentId,
520 stage: "reserve-allocation",
521 hostname: requestedHostname,
522 tunnelName: requestedTunnelName,
523 cause,
524 }),
525 ),
526 );
527 const { hostname, tunnelName } = allocation;
528
529 const tunnelResponse = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe(
530 Effect.map((tunnels) => tunnels.result),
531 Effect.map(Arr.findFirst((tunnel) => tunnel.name === tunnelName)),
532 Effect.flatMap(
533 Option.match({
534 onSome: (tunnel) => Effect.succeed(tunnel),
535 onNone: () => tunnels.create({ name: tunnelName, configSrc: "cloudflare" }),
536 }),
537 ),
538 Effect.mapError(
539 (cause) =>
540 new ManagedEndpointProvisioningFailed({
541 userId: input.userId,
542 environmentId: input.environmentId,
543 stage: "ensure-tunnel",
544 hostname,
545 tunnelName,
546 cause,
547 }),
548 ),
549 );
550 if (!tunnelResponse.id || tunnelResponse.name !== tunnelName) {
551 return yield* new ManagedEndpointProvisioningFailed({
552 userId: input.userId,
553 environmentId: input.environmentId,
554 stage: "validate-tunnel-response",
555 hostname,
556 tunnelName,
557 ...(tunnelResponse.id ? { returnedTunnelId: tunnelResponse.id } : {}),
558 ...(tunnelResponse.name ? { returnedTunnelName: tunnelResponse.name } : {}),
559 });
560 }
561 const tunnel = { id: tunnelResponse.id, name: tunnelResponse.name };
562 yield* allocations
563 .recordTunnel({
564 userId: input.userId,
565 environmentId: input.environmentId,
566 tunnelId: tunnel.id,
567 })
568 .pipe(
569 Effect.mapError(
570 (cause) =>
571 new ManagedEndpointProvisioningFailed({
572 userId: input.userId,
573 environmentId: input.environmentId,
574 stage: "record-tunnel",
575 hostname,
576 tunnelName,
577 tunnelId: tunnel.id,
578 cause,
579 }),
580 ),
581 );
582
583 yield* tunnels
584 .putConfiguration(tunnel.id, {
585 ingress: [
586 {
587 hostname,
588 service: formatOriginService(input.origin),
589 },
590 { service: "http_status:404" },
591 ],
592 })
593 .pipe(
594 Effect.mapError(
595 (cause) =>
596 new ManagedEndpointProvisioningFailed({
597 userId: input.userId,
598 environmentId: input.environmentId,
599 stage: "configure-tunnel",
600 hostname,
601 tunnelName,
602 tunnelId: tunnel.id,
603 cause,
604 }),
605 ),
606 );
607
608 const dnsRecord = {
609 type: "CNAME",
610 name: hostname,
611 content: `${tunnel.id}.cfargotunnel.com`,
612 ttl: 1,
613 proxied: true,
614 } as const;
615
616 const dnsRecordId = yield* ensureDnsRecord(hostname, allocation.dnsRecordId, dnsRecord).pipe(
617 Effect.mapError(
618 (cause) =>
619 new ManagedEndpointProvisioningFailed({
620 userId: input.userId,
621 environmentId: input.environmentId,
622 stage: "ensure-dns-record",
623 hostname,
624 tunnelName,
625 tunnelId: tunnel.id,
626 ...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),
627 cause,
628 }),
629 ),
630 );
631 yield* allocations
632 .recordDns({
633 userId: input.userId,
634 environmentId: input.environmentId,
635 dnsRecordId,
636 })
637 .pipe(
638 Effect.mapError(
639 (cause) =>
640 new ManagedEndpointProvisioningFailed({
641 userId: input.userId,
642 environmentId: input.environmentId,
643 stage: "record-dns",
644 hostname,
645 tunnelName,
646 tunnelId: tunnel.id,
647 dnsRecordId,
648 cause,
649 }),
650 ),
651 );
652
653 const connectorToken = yield* tunnels.getToken(tunnel.id).pipe(
654 Effect.mapError(
655 (cause) =>
656 new ManagedEndpointProvisioningFailed({
657 userId: input.userId,
658 environmentId: input.environmentId,
659 stage: "get-tunnel-token",
660 hostname,
661 tunnelName,
662 tunnelId: tunnel.id,
663 dnsRecordId,
664 cause,
665 }),
666 ),
667 );
668 yield* allocations
669 .markReady({
670 userId: input.userId,
671 environmentId: input.environmentId,
672 })
673 .pipe(
674 Effect.mapError(
675 (cause) =>
676 new ManagedEndpointProvisioningFailed({
677 userId: input.userId,
678 environmentId: input.environmentId,
679 stage: "mark-allocation-ready",
680 hostname,
681 tunnelName,
682 tunnelId: tunnel.id,
683 dnsRecordId,
684 cause,
685 }),
686 ),
687 );
688
689 return {
690 endpoint: managedEndpointForHostname(hostname),
691 runtime: {
692 providerKind: "cloudflare_tunnel",
693 connectorToken,
694 tunnelId: tunnel.id,
695 tunnelName: tunnel.name,
696 },
697 } satisfies ManagedEndpointProvisioningResult;
698 }),
699 });
700});
701
702export const layer = Layer.effect(ManagedEndpointProvider, make);
703
704export const layerCloudflareBindings = (
705 tunnelClient: Cloudflare.TunnelReadWriteClient,
706 dnsClient: Cloudflare.DnsReadWriteClient,
707 alchemyRuntimeContext: Alchemy.BaseRuntimeContext,
708) =>
709 layer.pipe(
710 Layer.provide(
711 Layer.mergeAll(
712 layerTunnelClient({
713 list: (request) =>
714 tunnelClient.list(request).pipe(
715 Effect.mapError(
716 (cause) =>
717 new ManagedEndpointTunnelClientError({
718 operation: "list",
719 tunnelName: request.name,
720 cause,
721 }),
722 ),
723 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
724 ),
725 create: (request) =>
726 tunnelClient.create(request).pipe(
727 Effect.mapError(
728 (cause) =>
729 new ManagedEndpointTunnelClientError({
730 operation: "create",
731 tunnelName: request.name,
732 cause,
733 }),
734 ),
735 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
736 ),
737 putConfiguration: (tunnelId, config) =>
738 tunnelClient.putConfiguration(tunnelId, config).pipe(
739 Effect.mapError(
740 (cause) =>
741 new ManagedEndpointTunnelClientError({
742 operation: "put-configuration",
743 tunnelId,
744 cause,
745 }),
746 ),
747 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
748 ),
749 getToken: (tunnelId) =>
750 tunnelClient.getToken(tunnelId).pipe(
751 Effect.mapError(
752 (cause) =>
753 new ManagedEndpointTunnelClientError({
754 operation: "get-token",
755 tunnelId,
756 cause,
757 }),
758 ),
759 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
760 ),
761 delete: (tunnelId) =>
762 tunnelClient.delete(tunnelId).pipe(
763 Effect.mapError(
764 (cause) =>
765 new ManagedEndpointTunnelClientError({
766 operation: "delete",
767 tunnelId,
768 cause,
769 }),
770 ),
771 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
772 ),
773 }),
774 layerDnsClient({
775 listRecords: (hostname) =>
776 dnsClient.listDnsRecords({ search: hostname }).pipe(
777 Effect.map((response) =>
778 response.result.filter(
779 (record): record is typeof record & { readonly id: string } =>
780 typeof record.id === "string" &&
781 normalizeHostname(record.name) === normalizeHostname(hostname),
782 ),
783 ),
784 Effect.mapError(
785 (cause) =>
786 new ManagedEndpointDnsClientError({
787 operation: "list-records",
788 hostname,
789 cause,
790 }),
791 ),
792 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
793 ),
794 createRecord: (request) =>
795 dnsClient.createDnsRecord(request).pipe(
796 Effect.map((response) => ({ id: response.id })),
797 Effect.mapError(
798 (cause) =>
799 new ManagedEndpointDnsClientError({
800 operation: "create-record",
801 hostname: request.name,
802 cause,
803 }),
804 ),
805 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
806 ),
807 updateRecord: (dnsRecordId, request) =>
808 dnsClient.updateDnsRecord(dnsRecordId, request).pipe(
809 Effect.mapError(
810 (cause) =>
811 new ManagedEndpointDnsClientError({
812 operation: "update-record",
813 hostname: request.name,
814 dnsRecordId,
815 cause,
816 }),
817 ),
818 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
819 ),
820 deleteRecord: (dnsRecordId) =>
821 dnsClient.deleteDnsRecord(dnsRecordId).pipe(
822 Effect.mapError(
823 (cause) =>
824 new ManagedEndpointDnsClientError({
825 operation: "delete-record",
826 dnsRecordId,
827 cause,
828 }),
829 ),
830 Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
831 ),
832 }),
833 ),
834 ),
835 );