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