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

ManagedEndpointProvider.test.ts

1,262 lines43.8 KB

1import * as NodeCrypto from "node:crypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3​
4import { describe, expect, it } from "@effect/vitest";
5import * as Alchemy from "alchemy";
6import * as Cloudflare from "alchemy/Cloudflare";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Redacted from "effect/Redacted";
10​
11import * as RelayConfiguration from "../Config.ts";
12import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
13import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
14import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts";
15​
16const config = RelayConfiguration.RelayConfiguration.of({
17 relayIssuer: "https://relay.example.test",
18 apns: {
19 environment: "sandbox",
20 teamId: "team-id",
21 keyId: "key-id",
22 privateKey: Redacted.make("private-key"),
23 bundleId: "com.t3tools.t3code.dev",
24 },
25 apnsDeliveryJobSigningSecret: Redacted.make("job-secret"),
26 clerkSecretKey: Redacted.make("clerk-secret"),
27 clerkPublishableKey: "pk_test_test",
28 clerkJwtAudience: "t3-code-relay",
29 cloudMintPrivateKey: Redacted.make("cloud-private-key"),
30 cloudMintPublicKey: "cloud-public-key",
31 managedEndpointBaseDomain: "t3code.test",
32 managedEndpointNamespace: "dev_julius",
33});
34​
35interface TunnelCall {
36 readonly operation: "list" | "create" | "putConfiguration" | "getToken" | "delete";
37 readonly input: unknown;
39​
40interface DnsCall {
41 readonly operation: "listRecords" | "createRecord" | "updateRecord" | "deleteRecord";
42 readonly input: unknown;
44​
45interface AllocationCall {
46 readonly operation:
47 | "get"
48 | "reserve"
49 | "recordTunnel"
50 | "recordDns"
51 | "markReady"
52 | "claimRelease"
53 | "claimDeprovision"
54 | "remove"
55 | "removeClaimed";
56 readonly input: unknown;
58​
59function allocationKey(input: { readonly userId: string; readonly environmentId: string }) {
60 return `${input.userId}:${input.environmentId}`;
62​
63function makeTunnelClient(calls: TunnelCall[] = []) {
64 return ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
65 list: (request) =>
66 Effect.sync(() => {
67 calls.push({ operation: "list", input: request });
68 return { result: [] };
69 }),
70 create: (request) =>
71 Effect.sync(() => {
72 calls.push({ operation: "create", input: request });
73 return { id: "tunnel-id", name: request.name };
74 }),
75 putConfiguration: (tunnelId, tunnelConfig) =>
76 Effect.sync(() => {
77 calls.push({ operation: "putConfiguration", input: { tunnelId, tunnelConfig } });
78 }),
79 getToken: (tunnelId) =>
80 Effect.sync(() => {
81 calls.push({ operation: "getToken", input: tunnelId });
82 return "connector-token";
83 }),
84 delete: (tunnelId) =>
85 Effect.sync(() => {
86 calls.push({ operation: "delete", input: tunnelId });
87 }),
88 });
90​
91function makePersistentTunnelClient(calls: TunnelCall[] = []) {
92 let tunnel: { readonly id: string; readonly name: string } | null = null;
93 return ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
94 list: (request) =>
95 Effect.sync(() => {
96 calls.push({ operation: "list", input: request });
97 return { result: tunnel === null ? [] : [tunnel] };
98 }),
99 create: (request) =>
100 Effect.sync(() => {
101 calls.push({ operation: "create", input: request });
102 tunnel = { id: "tunnel-id", name: request.name };
103 return tunnel;
104 }),
105 putConfiguration: (tunnelId, tunnelConfig) =>
106 Effect.sync(() => {
107 calls.push({ operation: "putConfiguration", input: { tunnelId, tunnelConfig } });
108 }),
109 getToken: (tunnelId) =>
110 Effect.sync(() => {
111 calls.push({ operation: "getToken", input: tunnelId });
112 return "connector-token";
113 }),
114 delete: (tunnelId) =>
115 Effect.sync(() => {
116 calls.push({ operation: "delete", input: tunnelId });
117 tunnel = null;
118 }),
119 });
121​
122function makeDnsClient(
123 calls: DnsCall[] = [],
124 records: ReadonlyArray<{ readonly id: string }> = [],
125) {
126 let currentRecords = [...records];
127 return ManagedEndpointProvider.ManagedEndpointDnsClient.of({
128 listRecords: (hostname) =>
129 Effect.sync(() => {
130 calls.push({ operation: "listRecords", input: hostname });
131 return currentRecords;
132 }),
133 createRecord: (request) =>
134 Effect.sync(() => {
135 calls.push({ operation: "createRecord", input: request });
136 const record = { id: "created-record-id" };
137 currentRecords = [record];
138 return record;
139 }),
140 updateRecord: (dnsRecordId, request) =>
141 Effect.gen(function* () {
142 calls.push({ operation: "updateRecord", input: { dnsRecordId, request } });
143 if (!currentRecords.some((record) => record.id === dnsRecordId)) {
144 return yield* new ManagedEndpointProvider.ManagedEndpointDnsClientError({
145 operation: "update-record",
146 hostname: request.name,
147 dnsRecordId,
148 cause: { _tag: "NotFound", dnsRecordId },
149 });
150 }
151 }),
152 deleteRecord: (dnsRecordId) =>
153 Effect.sync(() => {
154 calls.push({ operation: "deleteRecord", input: dnsRecordId });
155 currentRecords = currentRecords.filter((record) => record.id !== dnsRecordId);
156 }),
157 });
159​
160function makeAllocations(calls: AllocationCall[] = []) {
161 const allocations = new Map<string, ManagedEndpointAllocations.ManagedEndpointAllocation>();
162 let generation = 0;
163 const mutate = (
164 key: string,
165 change: (
166 allocation: ManagedEndpointAllocations.ManagedEndpointAllocation,
167 ) => ManagedEndpointAllocations.ManagedEndpointAllocation,
168 ) => {
169 const allocation = allocations.get(key);
170 if (allocation !== undefined) {
171 allocations.set(key, { ...change(allocation), updatedAt: `generation-${++generation}` });
172 }
173 };
174 return ManagedEndpointAllocations.ManagedEndpointAllocations.of({
175 get: (input) =>
176 Effect.sync(() => {
177 calls.push({ operation: "get", input });
178 return allocations.get(allocationKey(input)) ?? null;
179 }),
180 reserve: (input) =>
181 Effect.sync(() => {
182 calls.push({ operation: "reserve", input });
183 const allocation = allocations.get(allocationKey(input)) ?? {
184 ...input,
185 tunnelId: null,
186 dnsRecordId: null,
187 readyAt: null,
188 updatedAt: `generation-${++generation}`,
189 };
190 allocations.set(allocationKey(input), allocation);
191 return allocation;
192 }),
193 recordTunnel: (input) =>
194 Effect.sync(() => {
195 calls.push({ operation: "recordTunnel", input });
196 mutate(allocationKey(input), (allocation) => ({
197 ...allocation,
198 tunnelId: input.tunnelId,
199 }));
200 }),
201 recordDns: (input) =>
202 Effect.sync(() => {
203 calls.push({ operation: "recordDns", input });
204 mutate(allocationKey(input), (allocation) => ({
205 ...allocation,
206 dnsRecordId: input.dnsRecordId,
207 }));
208 }),
209 markReady: (input) =>
210 Effect.sync(() => {
211 calls.push({ operation: "markReady", input });
212 mutate(allocationKey(input), (allocation) => ({
213 ...allocation,
214 readyAt: "2026-06-02T00:00:00.000Z",
215 }));
216 }),
217 claimRelease: (input) =>
218 Effect.sync(() => {
219 calls.push({ operation: "claimRelease", input });
220 const allocation = allocations.get(allocationKey(input));
221 if (
222 allocation === undefined ||
223 allocation.tunnelId !== input.tunnelId ||
224 allocation.updatedAt !== input.updatedAt
225 ) {
226 return false;
227 }
228 mutate(allocationKey(input), (current) => current);
229 return true;
230 }),
231 claimDeprovision: (input) =>
232 Effect.sync(() => {
233 calls.push({ operation: "claimDeprovision", input });
234 const allocation = allocations.get(allocationKey(input));
235 if (allocation === undefined || allocation.updatedAt !== input.updatedAt) {
236 return null;
237 }
238 mutate(allocationKey(input), (current) => current);
239 return allocations.get(allocationKey(input))?.updatedAt ?? null;
240 }),
241 remove: (input) =>
242 Effect.sync(() => {
243 calls.push({ operation: "remove", input });
244 allocations.delete(allocationKey(input));
245 }),
246 removeClaimed: (input) =>
247 Effect.sync(() => {
248 calls.push({ operation: "removeClaimed", input });
249 const allocation = allocations.get(allocationKey(input));
250 if (allocation === undefined || allocation.updatedAt !== input.updatedAt) {
251 return false;
252 }
253 allocations.delete(allocationKey(input));
254 return true;
255 }),
256 });
258​
259function makeTunnelLimits(
260 calls: Array<{ readonly userId: string; readonly environmentId: string }> = [],
261 result: ManagedTunnelLimits.ManagedTunnelLimitExceeded | null = null,
262) {
263 return ManagedTunnelLimits.ManagedTunnelLimits.of({
264 ensureCapacity: (input) =>
265 Effect.suspend(() => {
266 calls.push(input);
267 return result === null ? Effect.void : Effect.fail(result);
268 }),
269 });
271​
272function providerLayer(
273 tunnelClient = makeTunnelClient(),
274 dnsClient = makeDnsClient(),
275 allocations = makeAllocations(),
276 tunnelLimits = makeTunnelLimits(),
277) {
278 return ManagedEndpointProvider.layer.pipe(
279 Layer.provideMerge(NodeServices.layer),
280 Layer.provide(RelayConfiguration.layer(config)),
281 Layer.provide(ManagedEndpointProvider.layerTunnelClient(tunnelClient)),
282 Layer.provide(ManagedEndpointProvider.layerDnsClient(dnsClient)),
283 Layer.provide(
284 Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, allocations),
285 ),
286 Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, tunnelLimits)),
287 );
289​
290function expectedManagedHostname(environmentId: string, userId = "user_ABC"): string {
291 const hash = NodeCrypto.createHash("sha256")
292 .update(`dev_julius:${userId}:${environmentId}`)
293 .digest("hex")
294 .slice(0, 16);
295 return `dev-julius-${hash}.t3code.test`;
297​
298function expectedManagedTunnelName(environmentId: string, userId = "user_ABC"): string {
299 const hash = NodeCrypto.createHash("sha256")
300 .update(`dev_julius:${userId}:${environmentId}`)
301 .digest("hex")
302 .slice(0, 16);
303 return `t3coderelay-managedendpoint-dev-julius-${hash}`;
305​
306describe("ManagedEndpointProvider", () => {
307 it.effect("does not require the deployment RuntimeContext when building the Worker layer", () => {
308 const tunnelClient = {
309 list: () => Effect.succeed({ result: [] }),
310 create: (request: { readonly name: string }) =>
311 Effect.succeed({ id: "tunnel-id", name: request.name }),
312 putConfiguration: () => Effect.void,
313 getToken: () => Effect.succeed("connector-token"),
314 delete: () => Effect.void,
315 } as unknown as Cloudflare.Tunnel.ReadWriteTunnelClient;
316 const dnsClient = {
317 listDnsRecords: () => Effect.succeed({ result: [] }),
318 createDnsRecord: () => Effect.succeed({ id: "dns-record-id" }),
319 updateDnsRecord: () => Effect.void,
320 deleteDnsRecord: () => Effect.void,
321 } as unknown as Cloudflare.DNS.ReadWriteDnsClient;
322 const runtimeContext = {} as Alchemy.BaseRuntimeContext;
323 const layer = ManagedEndpointProvider.layerCloudflareBindings(
324 tunnelClient,
325 dnsClient,
326 runtimeContext,
327 ).pipe(
328 Layer.provideMerge(NodeServices.layer),
329 Layer.provide(RelayConfiguration.layer(config)),
330 Layer.provide(
331 Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, makeAllocations()),
332 ),
333 Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, makeTunnelLimits())),
334 );
335​
336 return Effect.gen(function* () {
337 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
338 const result = yield* provider.provision({
339 userId: "user_ABC",
340 environmentId: "env_ABC",
341 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
342 });
343​
344 expect(result.runtime.connectorToken).toBe("connector-token");
345 }).pipe(Effect.provide(layer));
346 });
347​
348 it.effect("provisions a Cloudflare tunnel endpoint and connector token", () => {
349 const tunnelCalls: TunnelCall[] = [];
350 const dnsCalls: DnsCall[] = [];
351 const allocationCalls: AllocationCall[] = [];
352​
353 return Effect.gen(function* () {
354 const hostname = expectedManagedHostname("env_ABC");
355 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
356 const result = yield* provider.provision({
357 userId: "user_ABC",
358 environmentId: "env_ABC",
359 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
360 });
361​
362 expect(result).toEqual({
363 endpoint: {
364 httpBaseUrl: `https://${hostname}/`,
365 wsBaseUrl: `wss://${hostname}/ws`,
366 providerKind: "cloudflare_tunnel",
367 },
368 runtime: {
369 providerKind: "cloudflare_tunnel",
370 connectorToken: "connector-token",
371 tunnelId: "tunnel-id",
372 tunnelName: expectedManagedTunnelName("env_ABC"),
373 },
374 });
375 expect(dnsCalls).toEqual([
376 { operation: "listRecords", input: hostname },
377 {
378 operation: "createRecord",
379 input: {
380 type: "CNAME",
381 name: hostname,
382 content: "tunnel-id.cfargotunnel.com",
383 ttl: 1,
384 proxied: true,
385 },
386 },
387 ]);
388 expect(tunnelCalls.map((call) => call.operation)).toEqual([
389 "list",
390 "create",
391 "putConfiguration",
392 "getToken",
393 ]);
394 expect(tunnelCalls[2]?.input).toMatchObject({
395 tunnelConfig: {
396 ingress: [
397 {
398 hostname,
399 service: "http://127.0.0.1:3773",
400 },
401 { service: "http_status:404" },
402 ],
403 },
404 });
405 expect(tunnelCalls[0]?.input).toEqual({
406 name: expectedManagedTunnelName("env_ABC"),
407 isDeleted: false,
408 });
409 expect(allocationCalls.map((call) => call.operation)).toEqual([
410 "reserve",
411 "recordTunnel",
412 "recordDns",
413 "markReady",
414 ]);
415 }).pipe(
416 Effect.provide(
417 providerLayer(
418 makeTunnelClient(tunnelCalls),
419 makeDnsClient(dnsCalls),
420 makeAllocations(allocationCalls),
421 ),
422 ),
423 );
424 });
425​
426 it.effect("checks the managed tunnel limit before reserving an allocation", () => {
427 const limitCalls: Array<{ readonly userId: string; readonly environmentId: string }> = [];
428​
429 return Effect.gen(function* () {
430 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
431 yield* provider.provision({
432 userId: "user_ABC",
433 environmentId: "env_ABC",
434 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
435 });
436​
437 expect(limitCalls).toEqual([{ userId: "user_ABC", environmentId: "env_ABC" }]);
438 }).pipe(
439 Effect.provide(
440 providerLayer(
441 makeTunnelClient(),
442 makeDnsClient(),
443 makeAllocations(),
444 makeTunnelLimits(limitCalls),
445 ),
446 ),
447 );
448 });
449​
450 it.effect("refuses to provision past the managed tunnel limit without side effects", () => {
451 const tunnelCalls: TunnelCall[] = [];
452 const dnsCalls: DnsCall[] = [];
453 const allocationCalls: AllocationCall[] = [];
454 const exceeded = new ManagedTunnelLimits.ManagedTunnelLimitExceeded({
455 userId: "user_ABC",
456 environmentId: "env_ABC",
457 maxTunnels: 10,
458 activeTunnels: 10,
459 });
460​
461 return Effect.gen(function* () {
462 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
463 const error = yield* Effect.flip(
464 provider.provision({
465 userId: "user_ABC",
466 environmentId: "env_ABC",
467 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
468 }),
469 );
470​
471 expect(error).toBe(exceeded);
472 expect(tunnelCalls).toEqual([]);
473 expect(dnsCalls).toEqual([]);
474 expect(allocationCalls).toEqual([]);
475 }).pipe(
476 Effect.provide(
477 providerLayer(
478 makeTunnelClient(tunnelCalls),
479 makeDnsClient(dnsCalls),
480 makeAllocations(allocationCalls),
481 makeTunnelLimits([], exceeded),
482 ),
483 ),
484 );
485 });
486​
487 it.effect("uses stage-scoped stable names without leaking unusual environment ids", () => {
488 const tunnelCalls: TunnelCall[] = [];
489​
490 return Effect.gen(function* () {
491 const environmentId = "ENV With Spaces/../Symbols!" + "x".repeat(80);
492 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
493 yield* provider.provision({
494 userId: "user_ABC",
495 environmentId,
496 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
497 });
498​
499 const requestedName = (
500 tunnelCalls.find((call) => call.operation === "list")?.input as
501 | { readonly name?: string }
502 | undefined
503 )?.name;
504 expect(requestedName).toMatch(/^t3coderelay-managedendpoint-dev-julius-[a-f0-9]{16}$/);
505 const configBody = (
506 tunnelCalls.find((call) => call.operation === "putConfiguration")?.input as
507 | { readonly tunnelConfig?: unknown }
508 | undefined
509 )?.tunnelConfig;
510 expect(configBody).toMatchObject({
511 ingress: [
512 {
513 hostname: expect.stringMatching(/^dev-julius-[a-f0-9]{16}\.t3code\.test$/),
514 },
515 { service: "http_status:404" },
516 ],
517 });
518 const hostname = (
519 configBody as
520 | {
521 readonly ingress?: readonly [{ readonly hostname?: unknown }, unknown];
522 }
523 | undefined
524 )?.ingress?.[0]?.hostname;
525 expect(typeof hostname === "string" ? hostname.split(".")[0]?.length : 0).toBeLessThanOrEqual(
526 63,
527 );
528 expect(tunnelCalls.find((call) => call.operation === "create")?.input).toMatchObject({
529 name: requestedName,
530 configSrc: "cloudflare",
531 });
532 }).pipe(Effect.provide(providerLayer(makeTunnelClient(tunnelCalls))));
533 });
534​
535 it.effect("formats IPv6 loopback origins as valid Cloudflare ingress service URLs", () => {
536 const tunnelCalls: TunnelCall[] = [];
537​
538 return Effect.gen(function* () {
539 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
540 yield* provider.provision({
541 userId: "user_ABC",
542 environmentId: "env-ipv6",
543 origin: { localHttpHost: "::1", localHttpPort: 3773 },
544 });
545​
546 expect(
547 tunnelCalls.find((call) => call.operation === "putConfiguration")?.input,
548 ).toMatchObject({
549 tunnelConfig: {
550 ingress: [
551 {
552 service: "http://[::1]:3773",
553 },
554 { service: "http_status:404" },
555 ],
556 },
557 });
558 }).pipe(Effect.provide(providerLayer(makeTunnelClient(tunnelCalls))));
559 });
560​
561 it.effect("rejects non-loopback managed endpoint origins before calling Cloudflare", () => {
562 const dnsCalls: DnsCall[] = [];
563​
564 return Effect.gen(function* () {
565 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
566 const result = yield* Effect.result(
567 provider.provision({
568 userId: "user_ABC",
569 environmentId: "env_ABC",
570 origin: { localHttpHost: "192.168.1.10", localHttpPort: 3773 },
571 }),
572 );
573​
574 expect(dnsCalls).toHaveLength(0);
575 expect(result._tag).toBe("Failure");
576 if (result._tag === "Failure") {
577 expect(result.failure).toMatchObject({
578 _tag: "ManagedEndpointOriginNotAllowed",
579 userId: "user_ABC",
580 environmentId: "env_ABC",
581 host: "192.168.1.10",
582 port: 3773,
583 });
584 }
585 }).pipe(Effect.provide(providerLayer(makeTunnelClient(), makeDnsClient(dnsCalls))));
586 });
587​
588 it.effect("rejects invalid managed endpoint origin ports before calling Cloudflare", () => {
589 const dnsCalls: DnsCall[] = [];
590​
591 return Effect.gen(function* () {
592 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
593 const result = yield* Effect.result(
594 provider.provision({
595 userId: "user_ABC",
596 environmentId: "env_ABC",
597 origin: { localHttpHost: "127.0.0.1", localHttpPort: 65_536 },
598 }),
599 );
600​
601 expect(dnsCalls).toHaveLength(0);
602 expect(result._tag).toBe("Failure");
603 if (result._tag === "Failure") {
604 expect(result.failure._tag).toBe("ManagedEndpointOriginNotAllowed");
605 }
606 }).pipe(Effect.provide(providerLayer(makeTunnelClient(), makeDnsClient(dnsCalls))));
607 });
608​
609 it.effect("reconciles an existing same-host DNS record through the DNS client", () => {
610 const dnsCalls: DnsCall[] = [];
611 return Effect.gen(function* () {
612 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
613 yield* provider.provision({
614 userId: "user_ABC",
615 environmentId: "env_ABC",
616 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
617 });
618​
619 expect(dnsCalls.map((call) => call.operation)).toEqual(["listRecords", "updateRecord"]);
620 expect(dnsCalls[1]?.input).toMatchObject({ dnsRecordId: "existing-record-id" });
621 }).pipe(
622 Effect.provide(
623 providerLayer(makeTunnelClient(), makeDnsClient(dnsCalls, [{ id: "existing-record-id" }])),
624 ),
625 );
626 });
627​
628 it.effect("reuses checkpointed resources when provisioning is retried", () => {
629 const tunnelCalls: TunnelCall[] = [];
630 const dnsCalls: DnsCall[] = [];
631 const allocationCalls: AllocationCall[] = [];
632 const layer = providerLayer(
633 makePersistentTunnelClient(tunnelCalls),
634 makeDnsClient(dnsCalls),
635 makeAllocations(allocationCalls),
636 );
637​
638 return Effect.gen(function* () {
639 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
640 const request = {
641 userId: "user_ABC",
642 environmentId: "env_ABC",
643 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
644 } as const;
645 yield* provider.provision(request);
646 yield* provider.provision(request);
647​
648 expect(tunnelCalls.map((call) => call.operation)).toEqual([
649 "list",
650 "create",
651 "putConfiguration",
652 "getToken",
653 "list",
654 "putConfiguration",
655 "getToken",
656 ]);
657 expect(dnsCalls.map((call) => call.operation)).toEqual([
658 "listRecords",
659 "createRecord",
660 "updateRecord",
661 ]);
662 expect(allocationCalls.map((call) => call.operation)).toEqual([
663 "reserve",
664 "recordTunnel",
665 "recordDns",
666 "markReady",
667 "reserve",
668 "recordTunnel",
669 "recordDns",
670 "markReady",
671 ]);
672 }).pipe(Effect.provide(layer));
673 });
674​
675 it.effect("recreates a checkpointed DNS record when it was removed externally", () => {
676 const dnsCalls: DnsCall[] = [];
677 const allocationCalls: AllocationCall[] = [];
678 const dnsClient = makeDnsClient(dnsCalls);
679 const layer = providerLayer(
680 makePersistentTunnelClient(),
681 dnsClient,
682 makeAllocations(allocationCalls),
683 );
684​
685 return Effect.gen(function* () {
686 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
687 const request = {
688 userId: "user_ABC",
689 environmentId: "env_ABC",
690 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
691 } as const;
692 yield* provider.provision(request);
693 yield* dnsClient.deleteRecord("created-record-id");
694 yield* provider.provision(request);
695​
696 expect(dnsCalls.map((call) => call.operation)).toEqual([
697 "listRecords",
698 "createRecord",
699 "deleteRecord",
700 "updateRecord",
701 "listRecords",
702 "createRecord",
703 ]);
704 }).pipe(Effect.provide(layer));
705 });
706​
707 it.effect("does not hide non-not-found checkpoint update failures", () => {
708 const dnsCalls: DnsCall[] = [];
709 const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({
710 operation: "update-record",
711 dnsRecordId: "created-record-id",
712 cause: new Error("Cloudflare DNS unavailable"),
713 });
714 let records: ReadonlyArray<{ readonly id: string }> = [];
715 const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
716 listRecords: (hostname) =>
717 Effect.sync(() => {
718 dnsCalls.push({ operation: "listRecords", input: hostname });
719 return records;
720 }),
721 createRecord: (request) =>
722 Effect.sync(() => {
723 dnsCalls.push({ operation: "createRecord", input: request });
724 const record = { id: "created-record-id" };
725 records = [record];
726 return record;
727 }),
728 updateRecord: (dnsRecordId, request) =>
729 Effect.sync(() => {
730 dnsCalls.push({ operation: "updateRecord", input: { dnsRecordId, request } });
731 }).pipe(Effect.andThen(Effect.fail(failure))),
732 deleteRecord: () => Effect.void,
733 });
734 const layer = providerLayer(makePersistentTunnelClient(), dnsClient, makeAllocations());
735​
736 return Effect.gen(function* () {
737 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
738 const request = {
739 userId: "user_ABC",
740 environmentId: "env_ABC",
741 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
742 } as const;
743 yield* provider.provision(request);
744 const error = yield* Effect.flip(provider.provision(request));
745​
746 expect(error).toMatchObject({
747 _tag: "ManagedEndpointProvisioningFailed",
748 stage: "ensure-dns-record",
749 userId: "user_ABC",
750 environmentId: "env_ABC",
751 });
752 expect(dnsCalls.map((call) => call.operation)).toEqual([
753 "listRecords",
754 "createRecord",
755 "updateRecord",
756 ]);
757 }).pipe(Effect.provide(layer));
758 });
759​
760 it.effect(
761 "deprovisions checkpointed DNS and tunnel resources before removing the allocation",
762 () => {
763 const tunnelCalls: TunnelCall[] = [];
764 const dnsCalls: DnsCall[] = [];
765 const allocationCalls: AllocationCall[] = [];
766 const layer = providerLayer(
767 makePersistentTunnelClient(tunnelCalls),
768 makeDnsClient(dnsCalls),
769 makeAllocations(allocationCalls),
770 );
771​
772 return Effect.gen(function* () {
773 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
774 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
775 yield* provider.provision({
776 ...key,
777 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
778 });
779 yield* provider.deprovision(key);
780​
781 expect(dnsCalls.map((call) => call.operation)).toEqual([
782 "listRecords",
783 "createRecord",
784 "deleteRecord",
785 ]);
786 expect(tunnelCalls.map((call) => call.operation)).toEqual([
787 "list",
788 "create",
789 "putConfiguration",
790 "getToken",
791 "delete",
792 ]);
793 expect(allocationCalls.map((call) => call.operation)).toEqual([
794 "reserve",
795 "recordTunnel",
796 "recordDns",
797 "markReady",
798 "get",
799 "claimDeprovision",
800 "removeClaimed",
801 ]);
802 }).pipe(Effect.provide(layer));
803 },
804 );
805​
806 it.effect("does not deprovision an allocation superseded by a concurrent relink", () => {
807 const tunnelCalls: TunnelCall[] = [];
808 const dnsCalls: DnsCall[] = [];
809 const allocationCalls: AllocationCall[] = [];
810 const layer = providerLayer(
811 makePersistentTunnelClient(tunnelCalls),
812 makeDnsClient(dnsCalls),
813 makeAllocations(allocationCalls),
814 );
815​
816 return Effect.gen(function* () {
817 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
818 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
819 const request = {
820 ...key,
821 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
822 } as const;
823 yield* provider.provision(request);
824 const unlinkTarget = yield* provider.prepareDeprovision(key);
825 expect(unlinkTarget).not.toBeNull();
826 if (unlinkTarget === null) {
827 return;
828 }
829​
830 // A relink refreshes the allocation generation after unlink captured its
831 // target but before unlink begins external teardown.
832 yield* provider.provision(request);
833 const tunnelCallCount = tunnelCalls.length;
834 const dnsCallCount = dnsCalls.length;
835 const allocationCallCount = allocationCalls.length;
836​
837 yield* provider.deprovision({ ...key, target: unlinkTarget });
838​
839 expect(tunnelCalls).toHaveLength(tunnelCallCount);
840 expect(dnsCalls).toHaveLength(dnsCallCount);
841 expect(allocationCalls.slice(allocationCallCount).map((call) => call.operation)).toEqual([
842 "claimDeprovision",
843 ]);
844 }).pipe(Effect.provide(layer));
845 });
846​
847 it.effect("releases the tunnel while keeping the allocation, DNS record, and hostname", () => {
848 const tunnelCalls: TunnelCall[] = [];
849 const dnsCalls: DnsCall[] = [];
850 const allocationCalls: AllocationCall[] = [];
851 const layer = providerLayer(
852 makePersistentTunnelClient(tunnelCalls),
853 makeDnsClient(dnsCalls),
854 makeAllocations(allocationCalls),
855 );
856​
857 return Effect.gen(function* () {
858 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
859 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
860 const origin = { localHttpHost: "127.0.0.1", localHttpPort: 3773 } as const;
861 const first = yield* provider.provision({ ...key, origin });
862 const released = yield* provider.release(key);
863 const second = yield* provider.provision({ ...key, origin });
864​
865 expect(released).toBe(true);
866 expect(second.endpoint).toEqual(first.endpoint);
867 expect(tunnelCalls.map((call) => call.operation)).toEqual([
868 // first provision
869 "list",
870 "create",
871 "putConfiguration",
872 "getToken",
873 // release deletes only the tunnel...
874 "delete",
875 // ...and the next provision recreates it under the same name
876 "list",
877 "create",
878 "putConfiguration",
879 "getToken",
880 ]);
881 // The DNS record survives the release and is repointed, never deleted.
882 expect(dnsCalls.map((call) => call.operation)).toEqual([
883 "listRecords",
884 "createRecord",
885 "updateRecord",
886 ]);
887 expect(allocationCalls.map((call) => call.operation)).not.toContain("remove");
888 }).pipe(Effect.provide(layer));
889 });
890​
891 it.effect("treats an environment without a recorded tunnel as already released", () => {
892 const tunnelCalls: TunnelCall[] = [];
893 const dnsCalls: DnsCall[] = [];
894 const layer = providerLayer(
895 makePersistentTunnelClient(tunnelCalls),
896 makeDnsClient(dnsCalls),
897 makeAllocations(),
898 );
899​
900 return Effect.gen(function* () {
901 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
902 const released = yield* provider.release({ userId: "user_ABC", environmentId: "env_ABC" });
903​
904 expect(released).toBe(true);
905 expect(tunnelCalls).toEqual([]);
906 expect(dnsCalls).toEqual([]);
907 }).pipe(Effect.provide(layer));
908 });
909​
910 it.effect("keeps the tunnel alive when a concurrent provision outdates the release claim", () => {
911 const tunnelCalls: TunnelCall[] = [];
912 const allocations = makeAllocations();
913 // Simulates a provision racing the release: the allocation generation no
914 // longer matches what the release loaded, so the claim fails.
915 const outdated = ManagedEndpointAllocations.ManagedEndpointAllocations.of({
916 ...allocations,
917 claimRelease: () => Effect.succeed(false),
918 });
919 const layer = providerLayer(makePersistentTunnelClient(tunnelCalls), makeDnsClient(), outdated);
920​
921 return Effect.gen(function* () {
922 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
923 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
924 yield* provider.provision({
925 ...key,
926 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
927 });
928 const released = yield* provider.release(key);
929​
930 // false tells the caller its connector token is still live, so it must
931 // keep its runtime config.
932 expect(released).toBe(false);
933 expect(tunnelCalls.map((call) => call.operation)).toEqual([
934 "list",
935 "create",
936 "putConfiguration",
937 "getToken",
938 ]);
939 }).pipe(Effect.provide(layer));
940 });
941​
942 it.effect("treats an already deleted tunnel as successfully released", () => {
943 const notFound = { _tag: "NotFound" } as const;
944 const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
945 ...makeTunnelClient(),
946 delete: (tunnelId) =>
947 Effect.fail(
948 new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
949 operation: "delete",
950 tunnelId,
951 cause: notFound,
952 }),
953 ),
954 });
955 const layer = providerLayer(tunnelClient, makeDnsClient(), makeAllocations());
956​
957 return Effect.gen(function* () {
958 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
959 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
960 yield* provider.provision({
961 ...key,
962 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
963 });
964 yield* provider.release(key);
965 }).pipe(Effect.provide(layer));
966 });
967​
968 it.effect("surfaces non-not-found tunnel deletion failures when releasing", () => {
969 const failure = new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
970 operation: "delete",
971 tunnelId: "tunnel-id",
972 cause: "Cloudflare tunnel deletion failed",
973 });
974 const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
975 ...makeTunnelClient(),
976 delete: () => Effect.fail(failure),
977 });
978 const layer = providerLayer(tunnelClient, makeDnsClient(), makeAllocations());
979​
980 return Effect.gen(function* () {
981 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
982 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
983 yield* provider.provision({
984 ...key,
985 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
986 });
987 const error = yield* Effect.flip(provider.release(key));
988​
989 expect(error).toMatchObject({
990 _tag: "ManagedEndpointDeprovisioningFailed",
991 stage: "delete-tunnel",
992 userId: key.userId,
993 environmentId: key.environmentId,
994 tunnelId: "tunnel-id",
995 });
996 expect(error.cause).toBe(failure);
997 }).pipe(Effect.provide(layer));
998 });
999​
1000 it.effect("treats an absent allocation as already deprovisioned", () => {
1001 const tunnelCalls: TunnelCall[] = [];
1002 const dnsCalls: DnsCall[] = [];
1003 const allocationCalls: AllocationCall[] = [];
1004 const layer = providerLayer(
1005 makePersistentTunnelClient(tunnelCalls),
1006 makeDnsClient(dnsCalls),
1007 makeAllocations(allocationCalls),
1008 );
1009​
1010 return Effect.gen(function* () {
1011 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1012 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1013 yield* provider.deprovision(key);
1014​
1015 expect(tunnelCalls).toEqual([]);
1016 expect(dnsCalls).toEqual([]);
1017 expect(allocationCalls).toEqual([{ operation: "get", input: key }]);
1018 }).pipe(Effect.provide(layer));
1019 });
1020​
1021 it.effect("keeps the allocation when tunnel cleanup fails so unlink can retry", () => {
1022 const allocationCalls: AllocationCall[] = [];
1023 const tunnelCalls: TunnelCall[] = [];
1024 let deleteAttempts = 0;
1025 const failure = new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
1026 operation: "delete",
1027 tunnelId: "tunnel-id",
1028 cause: "Cloudflare tunnel deletion failed",
1029 });
1030 const tunnels = makePersistentTunnelClient(tunnelCalls);
1031 const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
1032 ...tunnels,
1033 delete: (tunnelId) =>
1034 Effect.gen(function* () {
1035 tunnelCalls.push({ operation: "delete", input: tunnelId });
1036 deleteAttempts++;
1037 if (deleteAttempts === 1) {
1038 return yield* failure;
1040 }),
1041 });
1042 const layer = providerLayer(tunnelClient, makeDnsClient(), makeAllocations(allocationCalls));
1043​
1044 return Effect.gen(function* () {
1045 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1046 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1047 yield* provider.provision({
1048 ...key,
1049 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1050 });
1051 const first = yield* Effect.result(provider.deprovision(key));
1052 expect(first._tag).toBe("Failure");
1053 if (first._tag === "Failure") {
1054 expect(first.failure).toMatchObject({
1055 _tag: "ManagedEndpointDeprovisioningFailed",
1056 stage: "delete-tunnel",
1057 userId: key.userId,
1058 environmentId: key.environmentId,
1059 tunnelId: "tunnel-id",
1060 });
1061 expect(first.failure.cause).toBe(failure);
1063 yield* provider.deprovision(key);
1064​
1065 expect(allocationCalls.map((call) => call.operation)).toEqual([
1066 "reserve",
1067 "recordTunnel",
1068 "recordDns",
1069 "markReady",
1070 "get",
1071 "claimDeprovision",
1072 "get",
1073 "claimDeprovision",
1074 "removeClaimed",
1075 ]);
1076 }).pipe(Effect.provide(layer));
1077 });
1078​
1079 it.effect("treats already deleted remote resources as successfully deprovisioned", () => {
1080 const allocationCalls: AllocationCall[] = [];
1081 const notFound = { _tag: "NotFound" } as const;
1082 const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
1083 ...makeTunnelClient(),
1084 delete: () =>
1085 Effect.fail(
1086 new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
1087 operation: "delete",
1088 tunnelId: "tunnel-id",
1089 cause: notFound,
1090 }),
1091 ),
1092 });
1093 const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
1094 ...makeDnsClient(),
1095 deleteRecord: () =>
1096 Effect.fail(
1097 new ManagedEndpointProvider.ManagedEndpointDnsClientError({
1098 operation: "delete-record",
1099 dnsRecordId: "created-record-id",
1100 cause: notFound,
1101 }),
1102 ),
1103 });
1104 const layer = providerLayer(tunnelClient, dnsClient, makeAllocations(allocationCalls));
1105​
1106 return Effect.gen(function* () {
1107 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1108 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1109 yield* provider.provision({
1110 ...key,
1111 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1112 });
1113 yield* provider.deprovision(key);
1114​
1115 expect(allocationCalls.map((call) => call.operation)).toContain("removeClaimed");
1116 }).pipe(Effect.provide(layer));
1117 });
1118​
1119 it.effect("scopes managed endpoint resources by user", () => {
1120 const tunnelCalls: TunnelCall[] = [];
1121​
1122 return Effect.gen(function* () {
1123 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1124 yield* provider.provision({
1125 userId: "user_ABC",
1126 environmentId: "env_shared",
1127 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1128 });
1129 yield* provider.provision({
1130 userId: "user_DEF",
1131 environmentId: "env_shared",
1132 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1133 });
1134​
1135 expect(
1136 tunnelCalls.filter((call) => call.operation === "list").map((call) => call.input),
1137 ).toEqual([
1138 { name: expectedManagedTunnelName("env_shared", "user_ABC"), isDeleted: false },
1139 { name: expectedManagedTunnelName("env_shared", "user_DEF"), isDeleted: false },
1140 ]);
1141 }).pipe(Effect.provide(providerLayer(makeTunnelClient(tunnelCalls))));
1142 });
1143​
1144 it.effect("recovers when DNS creation reports failure after the record became visible", () => {
1145 const dnsCalls: DnsCall[] = [];
1146 const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({
1147 operation: "create-record",
1148 hostname: expectedManagedHostname("env_ABC"),
1149 cause: "ambiguous Cloudflare DNS response",
1150 });
1151 let records: ReadonlyArray<{ readonly id: string }> = [];
1152 const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
1153 listRecords: (hostname) =>
1154 Effect.sync(() => {
1155 dnsCalls.push({ operation: "listRecords", input: hostname });
1156 return records;
1157 }),
1158 createRecord: (request) =>
1159 Effect.gen(function* () {
1160 dnsCalls.push({ operation: "createRecord", input: request });
1161 records = [{ id: "created-record-id" }];
1162 return yield* failure;
1163 }),
1164 updateRecord: (dnsRecordId, request) =>
1165 Effect.sync(() => {
1166 dnsCalls.push({ operation: "updateRecord", input: { dnsRecordId, request } });
1167 }),
1168 deleteRecord: (dnsRecordId) =>
1169 Effect.sync(() => {
1170 dnsCalls.push({ operation: "deleteRecord", input: dnsRecordId });
1171 }),
1172 });
1173​
1174 return Effect.gen(function* () {
1175 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1176 yield* provider.provision({
1177 userId: "user_ABC",
1178 environmentId: "env_ABC",
1179 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1180 });
1181​
1182 expect(dnsCalls.map((call) => call.operation)).toEqual([
1183 "listRecords",
1184 "createRecord",
1185 "listRecords",
1186 "updateRecord",
1187 ]);
1188 }).pipe(Effect.provide(providerLayer(makeTunnelClient(), dnsClient)));
1189 });
1190​
1191 it.effect("reports mismatched tunnel responses without manufacturing a cause", () => {
1192 const dnsCalls: DnsCall[] = [];
1193 const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
1194 ...makeTunnelClient(),
1195 create: () => Effect.succeed({ id: "returned-tunnel-id", name: "unexpected-tunnel" }),
1196 });
1197​
1198 return Effect.gen(function* () {
1199 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1200 const error = yield* Effect.flip(
1201 provider.provision({
1202 userId: "user_ABC",
1203 environmentId: "env_ABC",
1204 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1205 }),
1206 );
1207​
1208 expect(error).toMatchObject({
1209 _tag: "ManagedEndpointProvisioningFailed",
1210 stage: "validate-tunnel-response",
1211 userId: "user_ABC",
1212 environmentId: "env_ABC",
1213 hostname: expectedManagedHostname("env_ABC"),
1214 tunnelName: expectedManagedTunnelName("env_ABC"),
1215 returnedTunnelId: "returned-tunnel-id",
1216 returnedTunnelName: "unexpected-tunnel",
1217 });
1218 if (error._tag === "ManagedEndpointProvisioningFailed") {
1219 expect(error.cause).toBeUndefined();
1221 expect(dnsCalls).toHaveLength(0);
1222 }).pipe(Effect.provide(providerLayer(tunnelClient, makeDnsClient(dnsCalls))));
1223 });
1224​
1225 it.effect("fails provisioning when the DNS client fails", () => {
1226 const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({
1227 operation: "list-records",
1228 hostname: expectedManagedHostname("env_ABC"),
1229 cause: "Cloudflare DNS failure",
1230 });
1231 const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
1232 listRecords: () => Effect.fail(failure),
1233 createRecord: () => Effect.die("unused"),
1234 updateRecord: () => Effect.die("unused"),
1235 deleteRecord: () => Effect.die("unused"),
1236 });
1237​
1238 return Effect.gen(function* () {
1239 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1240 const error = yield* Effect.flip(
1241 provider.provision({
1242 userId: "user_ABC",
1243 environmentId: "env_ABC",
1244 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1245 }),
1246 );
1247​
1248 expect(error).toMatchObject({
1249 _tag: "ManagedEndpointProvisioningFailed",
1250 stage: "ensure-dns-record",
1251 userId: "user_ABC",
1252 environmentId: "env_ABC",
1253 hostname: expectedManagedHostname("env_ABC"),
1254 tunnelName: expectedManagedTunnelName("env_ABC"),
1255 tunnelId: "tunnel-id",
1256 });
1257 if (error._tag === "ManagedEndpointProvisioningFailed") {
1258 expect(error.cause).toBe(failure);
1260 }).pipe(Effect.provide(providerLayer(makeTunnelClient(), dnsClient)));
1261 });
1262});