Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Redacted from "effect/Redacted";
6import * as TestClock from "effect/testing/TestClock";
7import * as Tracer from "effect/Tracer";
8
9import * as RelayConfiguration from "../Config.ts";
10import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
11import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
12import * as ManagedEndpointReaper from "./ManagedEndpointReaper.ts";
13
14const NOW = "2026-08-25T12:00:00.000Z";
15const NOW_MILLIS = DateTime.makeUnsafe(NOW).epochMilliseconds;
16const PREFIX = "t3coderelay-managedendpoint-prod-";
17
18function tunnel(input: {
19 readonly id: string;
20 readonly suffix: string;
21 readonly status: "down" | "inactive" | "healthy" | "degraded";
22 readonly timestamp?: string | null;
23 readonly prefix?: string;
24}): ManagedEndpointProvider.ManagedEndpointTunnel {
25 return {
26 id: input.id,
27 name: `${input.prefix ?? PREFIX}${input.suffix}`,
28 status: input.status,
29 ...(input.timestamp === undefined
30 ? {}
31 : input.status === "inactive"
32 ? { createdAt: input.timestamp }
33 : { connsInactiveAt: input.timestamp }),
34 };
35}
36
37function recoverableOwners(
38 tunnels: ReadonlyArray<ManagedEndpointProvider.ManagedEndpointTunnel>,
39): ReadonlyArray<ManagedEndpointAllocations.ManagedEndpointTunnelAllocation> {
40 return tunnels.map((entry) => allocation({ tunnelId: entry.id!, recoveryEnabled: true }));
41}
42
43function allocation(input: {
44 readonly tunnelId: string | null;
45 readonly recoveryEnabled: boolean;
46}): ManagedEndpointAllocations.ManagedEndpointTunnelAllocation {
47 return {
48 userId: "user-1",
49 environmentId: `environment-${input.tunnelId ?? "pending"}`,
50 hostname: `${input.tunnelId ?? "pending"}.example.test`,
51 tunnelId: input.tunnelId,
52 tunnelName: `${PREFIX}aaaaaaaaaaaaaaaa`,
53 dnsRecordId: "dns-1",
54 readyAt: "2026-08-25T11:00:00.000Z",
55 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
56 updatedAt: "2026-08-25T11:00:00.000Z",
57 generation: 1,
58 recoveryEnabled: input.recoveryEnabled,
59 };
60}
61
62function harness(input?: {
63 readonly tunnels?: ReadonlyArray<ManagedEndpointProvider.ManagedEndpointTunnel>;
64 readonly allocations?: ReadonlyArray<ManagedEndpointAllocations.ManagedEndpointTunnelAllocation>;
65 readonly namespace?: string;
66 readonly failTunnelId?: string;
67 readonly rateLimitedTunnelId?: string;
68 readonly failAllDeletes?: boolean;
69 readonly failDeleteWhen?: (tunnelId: string) => boolean;
70 readonly missingOnDeleteTunnelId?: string;
71 readonly missingOnGetTunnelId?: string;
72 readonly reserveOnGetTunnelId?: string;
73 readonly refreshedTunnels?: ReadonlyMap<string, ManagedEndpointProvider.ManagedEndpointTunnel>;
74 readonly skipTunnelId?: string;
75 readonly cleanupMode?: RelayConfiguration.ManagedEndpointCleanupMode;
76}) {
77 const listRequests: ManagedEndpointProvider.ManagedEndpointTunnelListRequest[] = [];
78 const deleted: string[] = [];
79 const releases: Array<
80 Parameters<ManagedEndpointProvider.ManagedEndpointProvider["Service"]["release"]>[0]
81 > = [];
82 const remaining = [...(input?.tunnels ?? [])];
83 const recorded = (input?.allocations ?? []).map((entry) => {
84 const matching = remaining.find((candidate) => candidate.id === entry.tunnelId);
85 return typeof matching?.name === "string" ? { ...entry, tunnelName: matching.name } : entry;
86 });
87 const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
88 get: (tunnelId) =>
89 Effect.suspend(() => {
90 if (tunnelId === input?.missingOnGetTunnelId) {
91 return Effect.fail(
92 new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
93 operation: "get",
94 tunnelId,
95 cause: { _tag: "NotFound" },
96 }),
97 );
98 }
99 const found =
100 input?.refreshedTunnels?.get(tunnelId) ??
101 remaining.find((candidate) => candidate.id === tunnelId);
102 if (found === undefined) {
103 return Effect.fail(
104 new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
105 operation: "get",
106 tunnelId,
107 cause: { _tag: "NotFound" },
108 }),
109 );
110 }
111 if (tunnelId === input?.reserveOnGetTunnelId && typeof found.name === "string") {
112 recorded.push({
113 ...allocation({ tunnelId, recoveryEnabled: false }),
114 tunnelName: found.name,
115 });
116 }
117 return Effect.succeed(found);
118 }),
119 list: (request) =>
120 Effect.sync(() => {
121 listRequests.push(request);
122 const matching = remaining.filter((entry) => entry.status === request.status);
123 const start = ((request.page ?? 1) - 1) * (request.perPage ?? 100);
124 return {
125 result: matching.slice(start, start + (request.perPage ?? 100)),
126 resultInfo: {
127 page: request.page ?? 1,
128 perPage: request.perPage ?? 100,
129 totalCount: matching.length,
130 },
131 };
132 }),
133 create: () => Effect.die("unused"),
134 putConfiguration: () => Effect.die("unused"),
135 getToken: () => Effect.die("unused"),
136 delete: (tunnelId) =>
137 input?.failAllDeletes === true ||
138 input?.failDeleteWhen?.(tunnelId) === true ||
139 tunnelId === input?.failTunnelId ||
140 tunnelId === input?.rateLimitedTunnelId ||
141 tunnelId === input?.missingOnDeleteTunnelId
142 ? Effect.fail(
143 new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
144 operation: "delete",
145 tunnelId,
146 cause:
147 tunnelId === input?.missingOnDeleteTunnelId
148 ? { _tag: "NotFound" }
149 : tunnelId === input?.rateLimitedTunnelId
150 ? {
151 cause: {
152 _tag: "TooManyRequests",
153 message: "Cloudflare rate limit exceeded",
154 retryAfter: 60,
155 },
156 }
157 : "Cloudflare refused the deletion",
158 }),
159 )
160 : Effect.sync(() => {
161 deleted.push(tunnelId);
162 const index = remaining.findIndex((candidate) => candidate.id === tunnelId);
163 if (index !== -1) {
164 remaining.splice(index, 1);
165 }
166 }),
167 });
168 const allocationService = ManagedEndpointAllocations.ManagedEndpointAllocations.of({
169 get: () => Effect.die("unused"),
170 reserve: () => Effect.die("unused"),
171 recordTunnel: () => Effect.die("unused"),
172 recordDns: () => Effect.die("unused"),
173 markReady: () => Effect.die("unused"),
174 enableRecovery: () => Effect.die("unused"),
175 listByTunnelNames: (tunnelNames) =>
176 Effect.succeed(recorded.filter((entry) => tunnelNames.includes(entry.tunnelName))),
177 claimRelease: () => Effect.die("unused"),
178 withClaimedTunnel: () => Effect.die("unused"),
179 claimDeprovision: () => Effect.die("unused"),
180 remove: () => Effect.die("unused"),
181 removeClaimed: () => Effect.die("unused"),
182 });
183 const provider = ManagedEndpointProvider.ManagedEndpointProvider.of({
184 provision: () => Effect.die("unused"),
185 reconcileOrigin: () => Effect.die("unused"),
186 prepareDeprovision: () => Effect.die("unused"),
187 deprovision: () => Effect.die("unused"),
188 release: (request) =>
189 Effect.gen(function* () {
190 releases.push(request);
191 if (request.expectedTunnelId === input?.skipTunnelId) {
192 return false;
193 }
194 if (request.expectedTunnelId !== undefined) {
195 // Surface Cloudflare failures the same way the real release does.
196 yield* tunnelClient.delete(request.expectedTunnelId).pipe(
197 Effect.mapError(
198 (cause) =>
199 new ManagedEndpointProvider.ManagedEndpointDeprovisioningFailed({
200 stage: "delete-tunnel",
201 userId: request.userId,
202 environmentId: request.environmentId,
203 tunnelId: request.expectedTunnelId!,
204 cause,
205 }),
206 ),
207 );
208 }
209 return true;
210 }),
211 });
212 const config = RelayConfiguration.RelayConfiguration.of({
213 relayIssuer: "https://relay.example.test",
214 apns: {
215 environment: "sandbox",
216 teamId: "team-id",
217 keyId: "key-id",
218 privateKey: Redacted.make("private-key"),
219 bundleId: "com.t3tools.t3code.dev",
220 },
221 apnsDeliveryJobSigningSecret: Redacted.make("job-secret"),
222 clerkSecretKey: Redacted.make("clerk-secret"),
223 clerkPublishableKey: "pk_test_test",
224 clerkJwtAudience: "t3-code-relay",
225 cloudMintPrivateKey: Redacted.make("cloud-private-key"),
226 cloudMintPublicKey: "cloud-public-key",
227 managedEndpointBaseDomain: "example.test",
228 managedEndpointNamespace: input?.namespace ?? "prod",
229 managedEndpointCleanupMode: input?.cleanupMode ?? "enabled",
230 });
231
232 return {
233 listRequests,
234 deleted,
235 releases,
236 layer: ManagedEndpointReaper.layer.pipe(
237 Layer.provide(
238 Layer.mergeAll(
239 RelayConfiguration.layer(config),
240 ManagedEndpointProvider.layerTunnelClient(tunnelClient),
241 Layer.succeed(ManagedEndpointProvider.ManagedEndpointProvider, provider),
242 Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, allocationService),
243 ),
244 ),
245 ),
246 };
247}
248
249describe("ManagedEndpointReaper", () => {
250 it.effect("removes expired down and inactive tunnels from recoverable environments", () => {
251 const state = harness({
252 tunnels: [
253 tunnel({
254 id: "down-1",
255 suffix: "aaaaaaaaaaaaaaaa",
256 status: "down",
257 timestamp: "2026-08-25T11:55:00.000Z",
258 }),
259 tunnel({
260 id: "inactive-1",
261 suffix: "bbbbbbbbbbbbbbbb",
262 status: "inactive",
263 timestamp: "2026-08-25T10:59:00.000Z",
264 }),
265 ],
266 allocations: [
267 allocation({ tunnelId: "down-1", recoveryEnabled: true }),
268 allocation({ tunnelId: "inactive-1", recoveryEnabled: true }),
269 ],
270 });
271
272 return Effect.gen(function* () {
273 yield* TestClock.setTime(NOW_MILLIS);
274 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
275 expect(yield* reaper.sweep).toMatchObject({
276 scanned: 2,
277 deleted: 2,
278 skippedLegacy: 0,
279 failed: 0,
280 });
281 expect(state.deleted).toEqual(["down-1", "inactive-1"]);
282 expect(state.releases.map((request) => request.expectedTunnelId)).toEqual([
283 "down-1",
284 "inactive-1",
285 ]);
286 expect(state.listRequests).toEqual([
287 {
288 isDeleted: false,
289 includePrefix: PREFIX,
290 status: "down",
291 existedAt: "2026-08-25T11:55:00.000Z",
292 wasInactiveAt: "2026-08-25T11:55:00.000Z",
293 page: 1,
294 perPage: 100,
295 },
296 {
297 isDeleted: false,
298 includePrefix: PREFIX,
299 status: "inactive",
300 existedAt: "2026-08-25T11:00:00.000Z",
301 page: 1,
302 perPage: 100,
303 },
304 ]);
305 }).pipe(Effect.provide(state.layer));
306 });
307
308 it.effect("keeps a tunnel that never connected until it is an hour old", () => {
309 const state = harness({
310 tunnels: [
311 tunnel({
312 id: "pairing",
313 suffix: "cccccccccccccccc",
314 status: "inactive",
315 timestamp: "2026-08-25T11:30:00.000Z",
316 }),
317 ],
318 allocations: [allocation({ tunnelId: "pairing", recoveryEnabled: true })],
319 });
320
321 return Effect.gen(function* () {
322 yield* TestClock.setTime(NOW_MILLIS);
323 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
324 expect((yield* reaper.sweep).deleted).toBe(0);
325 expect(state.deleted).toEqual([]);
326 }).pipe(Effect.provide(state.layer));
327 });
328
329 it.effect("keeps recent tunnels, other stages, and tunnels without valid timestamps", () => {
330 const state = harness({
331 tunnels: [
332 tunnel({
333 id: "recent",
334 suffix: "aaaaaaaaaaaaaaaa",
335 status: "down",
336 timestamp: "2026-08-25T11:55:01.000Z",
337 }),
338 tunnel({
339 id: "other-stage",
340 prefix: `${PREFIX}julius-`,
341 suffix: "bbbbbbbbbbbbbbbb",
342 status: "down",
343 timestamp: "2026-08-25T11:00:00.000Z",
344 }),
345 tunnel({
346 id: "missing-time",
347 suffix: "cccccccccccccccc",
348 status: "inactive",
349 timestamp: null,
350 }),
351 ],
352 });
353
354 return Effect.gen(function* () {
355 yield* TestClock.setTime(NOW_MILLIS);
356 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
357 expect(yield* reaper.sweep).toMatchObject({
358 scanned: 0,
359 deleted: 0,
360 skippedLegacy: 0,
361 failed: 0,
362 });
363 expect(state.deleted).toEqual([]);
364 }).pipe(Effect.provide(state.layer));
365 });
366
367 it.effect("keeps tunnels owned by environments that cannot recover yet", () => {
368 const state = harness({
369 tunnels: [
370 tunnel({
371 id: "legacy",
372 suffix: "aaaaaaaaaaaaaaaa",
373 status: "down",
374 timestamp: "2026-08-25T11:00:00.000Z",
375 }),
376 ],
377 allocations: [allocation({ tunnelId: "legacy", recoveryEnabled: false })],
378 });
379
380 return Effect.gen(function* () {
381 yield* TestClock.setTime(NOW_MILLIS);
382 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
383 expect(yield* reaper.sweep).toMatchObject({
384 scanned: 1,
385 deleted: 0,
386 skippedLegacy: 1,
387 failed: 0,
388 });
389 expect(state.deleted).toEqual([]);
390 }).pipe(Effect.provide(state.layer));
391 });
392
393 it.effect("counts an expired tunnel with no allocation instead of deleting it", () => {
394 const state = harness({
395 tunnels: [
396 tunnel({
397 id: "orphan",
398 suffix: "cccccccccccccccc",
399 status: "down",
400 timestamp: "2026-08-25T11:00:00.000Z",
401 }),
402 ],
403 });
404
405 return Effect.gen(function* () {
406 yield* TestClock.setTime(NOW_MILLIS);
407 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
408 expect(yield* reaper.sweep).toMatchObject({
409 scanned: 1,
410 wouldDelete: 0,
411 deleted: 0,
412 skippedOrphan: 1,
413 });
414 expect(state.deleted).toEqual([]);
415 }).pipe(Effect.provide(state.layer));
416 });
417 it.effect("keeps an expired tunnel while its allocation is incomplete", () => {
418 const state = harness({
419 tunnels: [
420 tunnel({
421 id: "unrecorded",
422 suffix: "aaaaaaaaaaaaaaaa",
423 status: "inactive",
424 timestamp: "2026-08-25T11:00:00.000Z",
425 }),
426 ],
427 allocations: [allocation({ tunnelId: null, recoveryEnabled: false })],
428 });
429
430 return Effect.gen(function* () {
431 yield* TestClock.setTime(NOW_MILLIS);
432 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
433 expect((yield* reaper.sweep).deleted).toBe(0);
434 expect(state.deleted).toEqual([]);
435 }).pipe(Effect.provide(state.layer));
436 });
437
438 it.effect("does not count a tunnel that was replaced before its release", () => {
439 const state = harness({
440 tunnels: [
441 tunnel({
442 id: "replaced",
443 suffix: "aaaaaaaaaaaaaaaa",
444 status: "down",
445 timestamp: "2026-08-25T11:00:00.000Z",
446 }),
447 ],
448 allocations: [allocation({ tunnelId: "replaced", recoveryEnabled: true })],
449 skipTunnelId: "replaced",
450 });
451
452 return Effect.gen(function* () {
453 yield* TestClock.setTime(NOW_MILLIS);
454 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
455 expect((yield* reaper.sweep).deleted).toBe(0);
456 expect(state.deleted).toEqual([]);
457 }).pipe(Effect.provide(state.layer));
458 });
459
460 it.effect("stops the sweep after a structured Cloudflare rate limit error", () => {
461 const state = harness({
462 tunnels: [
463 tunnel({
464 id: "limited",
465 suffix: "aaaaaaaaaaaaaaaa",
466 status: "down",
467 timestamp: "2026-08-25T11:00:00.000Z",
468 }),
469 tunnel({
470 id: "next",
471 suffix: "bbbbbbbbbbbbbbbb",
472 status: "down",
473 timestamp: "2026-08-25T11:00:00.000Z",
474 }),
475 ],
476 allocations: [
477 allocation({ tunnelId: "limited", recoveryEnabled: true }),
478 allocation({ tunnelId: "next", recoveryEnabled: true }),
479 ],
480 rateLimitedTunnelId: "limited",
481 });
482
483 return Effect.gen(function* () {
484 yield* TestClock.setTime(NOW_MILLIS);
485 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
486 expect(yield* reaper.sweep).toMatchObject({
487 attempted: 1,
488 deleted: 0,
489 failed: 1,
490 truncated: true,
491 });
492 expect(state.deleted).toEqual([]);
493 }).pipe(Effect.provide(state.layer));
494 });
495
496 it.effect("continues past a page of older hosts to find recoverable tunnels", () => {
497 const entries = Array.from({ length: 101 }, (_, index) =>
498 tunnel({
499 id: `tunnel-${index}`,
500 suffix: index.toString(16).padStart(16, "0"),
501 status: "down",
502 timestamp: "2026-08-25T11:00:00.000Z",
503 }),
504 );
505 const state = harness({
506 tunnels: entries,
507 allocations: entries.map((entry, index) =>
508 allocation({ tunnelId: entry.id!, recoveryEnabled: index === 100 }),
509 ),
510 });
511
512 return Effect.gen(function* () {
513 yield* TestClock.setTime(NOW_MILLIS);
514 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
515 expect(yield* reaper.sweep).toMatchObject({
516 scanned: 101,
517 deleted: 1,
518 skippedLegacy: 100,
519 failed: 0,
520 });
521 expect(state.deleted).toEqual(["tunnel-100"]);
522 expect(
523 state.listRequests
524 .filter((request) => request.status === "down")
525 .map((request) => request.page),
526 ).toEqual([1, 2]);
527 }).pipe(Effect.provide(state.layer));
528 });
529
530 it.effect("collects every page before deletions shift Cloudflare pagination", () => {
531 const entries = Array.from({ length: 120 }, (_, index) =>
532 tunnel({
533 id: `tunnel-${index}`,
534 suffix: index.toString(16).padStart(16, "0"),
535 status: "down",
536 timestamp: "2026-08-25T11:00:00.000Z",
537 }),
538 );
539 const state = harness({
540 tunnels: entries,
541 allocations: entries.map((entry, index) =>
542 allocation({ tunnelId: entry.id!, recoveryEnabled: index < 50 || index >= 100 }),
543 ),
544 });
545
546 return Effect.gen(function* () {
547 yield* TestClock.setTime(NOW_MILLIS);
548 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
549 expect(yield* reaper.sweep).toMatchObject({
550 scanned: 120,
551 deleted: 70,
552 skippedLegacy: 50,
553 failed: 0,
554 });
555 expect(state.deleted).toContain("tunnel-119");
556 }).pipe(Effect.provide(state.layer));
557 });
558
559 it.effect("limits each cleanup run to 100 tunnel deletions", () => {
560 const entries = Array.from({ length: 105 }, (_, index) =>
561 tunnel({
562 id: `tunnel-${index}`,
563 suffix: index.toString(16).padStart(16, "0"),
564 status: "down",
565 timestamp: "2026-08-25T11:00:00.000Z",
566 }),
567 );
568 const state = harness({ tunnels: entries, allocations: recoverableOwners(entries) });
569
570 return Effect.gen(function* () {
571 yield* TestClock.setTime(NOW_MILLIS);
572 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
573 expect((yield* reaper.sweep).deleted).toBe(100);
574 expect(state.deleted).toHaveLength(100);
575 }).pipe(Effect.provide(state.layer));
576 });
577
578 it.effect("records dry-run counters on the sweep span", () => {
579 const spans: Array<Tracer.NativeSpan> = [];
580 const tracer = Tracer.make({
581 span: (options) => {
582 const span = new Tracer.NativeSpan(options);
583 spans.push(span);
584 return span;
585 },
586 });
587 const expired = [
588 tunnel({
589 id: "recoverable",
590 suffix: "aaaaaaaaaaaaaaaa",
591 status: "down",
592 timestamp: "2026-08-25T11:00:00.000Z",
593 }),
594 tunnel({
595 id: "legacy",
596 suffix: "bbbbbbbbbbbbbbbb",
597 status: "down",
598 timestamp: "2026-08-25T11:00:00.000Z",
599 }),
600 ];
601 const state = harness({
602 cleanupMode: "dry-run",
603 tunnels: expired,
604 allocations: [
605 allocation({ tunnelId: "recoverable", recoveryEnabled: true }),
606 allocation({ tunnelId: "legacy", recoveryEnabled: false }),
607 ],
608 });
609
610 return Effect.gen(function* () {
611 yield* TestClock.setTime(NOW_MILLIS);
612 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
613 yield* reaper.sweep;
614 const sweepSpan = spans.find((span) => span.name === "relay.managed_endpoint_reaper.sweep");
615 expect(Object.fromEntries(sweepSpan?.attributes ?? [])).toMatchObject({
616 "relay.managed_endpoint_reaper.mode": "dry-run",
617 "relay.managed_endpoint_reaper.scanned": 2,
618 "relay.managed_endpoint_reaper.wouldDelete": 1,
619 "relay.managed_endpoint_reaper.skippedLegacy": 1,
620 "relay.managed_endpoint_reaper.deleted": 0,
621 });
622 expect(state.deleted).toEqual([]);
623 }).pipe(Effect.provide(state.layer), Effect.withTracer(tracer));
624 });
625
626 it.effect("does no Cloudflare work while cleanup is off", () => {
627 const state = harness({
628 cleanupMode: "off",
629 tunnels: [
630 tunnel({
631 id: "expired",
632 suffix: "aaaaaaaaaaaaaaaa",
633 status: "down",
634 timestamp: "2026-08-25T11:00:00.000Z",
635 }),
636 ],
637 allocations: [allocation({ tunnelId: "expired", recoveryEnabled: true })],
638 });
639
640 return Effect.gen(function* () {
641 yield* TestClock.setTime(NOW_MILLIS);
642 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
643 expect(yield* reaper.sweep).toEqual({
644 mode: "off",
645 listRequests: 0,
646 scanned: 0,
647 attempted: 0,
648 deleted: 0,
649 wouldDelete: 0,
650 skippedLegacy: 0,
651 skippedOrphan: 0,
652 failed: 0,
653 truncated: false,
654 });
655 expect(state.listRequests).toEqual([]);
656 expect(state.deleted).toEqual([]);
657 }).pipe(Effect.provide(state.layer));
658 });
659
660 it.effect("reports candidates without mutating them in dry-run mode", () => {
661 const state = harness({
662 cleanupMode: "dry-run",
663 tunnels: [
664 tunnel({
665 id: "expired",
666 suffix: "aaaaaaaaaaaaaaaa",
667 status: "down",
668 timestamp: "2026-08-25T11:00:00.000Z",
669 }),
670 ],
671 allocations: [allocation({ tunnelId: "expired", recoveryEnabled: true })],
672 });
673
674 return Effect.gen(function* () {
675 yield* TestClock.setTime(NOW_MILLIS);
676 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
677 expect(yield* reaper.sweep).toMatchObject({
678 mode: "dry-run",
679 scanned: 1,
680 attempted: 0,
681 deleted: 0,
682 wouldDelete: 1,
683 });
684 expect(state.deleted).toEqual([]);
685 expect(state.releases).toEqual([]);
686 }).pipe(Effect.provide(state.layer));
687 });
688
689 it.effect("caps failed deletion attempts and Cloudflare list pages", () => {
690 const entries = Array.from({ length: 250 }, (_, index) =>
691 tunnel({
692 id: `failed-${index}`,
693 suffix: index.toString(16).padStart(16, "0"),
694 status: "down",
695 timestamp: "2026-08-25T11:00:00.000Z",
696 }),
697 );
698 const state = harness({
699 tunnels: entries,
700 allocations: recoverableOwners(entries),
701 failAllDeletes: true,
702 });
703
704 return Effect.gen(function* () {
705 yield* TestClock.setTime(NOW_MILLIS);
706 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
707 expect(yield* reaper.sweep).toMatchObject({
708 attempted: 100,
709 deleted: 0,
710 failed: 100,
711 truncated: true,
712 });
713 expect(state.listRequests.length).toBeLessThanOrEqual(
714 ManagedEndpointReaper.MANAGED_ENDPOINT_SWEEP_LIST_REQUEST_LIMIT,
715 );
716 }).pipe(Effect.provide(state.layer));
717 });
718
719 it.effect("rotates the deletion order so persistent failures do not starve later tunnels", () => {
720 const entries = Array.from({ length: 200 }, (_, index) =>
721 tunnel({
722 id: `tunnel-${index}`,
723 suffix: index.toString(16).padStart(16, "0"),
724 status: "down",
725 timestamp: "2026-08-25T11:00:00.000Z",
726 }),
727 );
728 // The first 100 candidates always fail to delete.
729 const state = harness({
730 tunnels: entries,
731 allocations: recoverableOwners(entries),
732 failDeleteWhen: (id) => Number(id.split("-")[1]) < 100,
733 });
734
735 return Effect.gen(function* () {
736 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
737 yield* TestClock.setTime(NOW_MILLIS);
738 yield* reaper.sweep;
739 yield* TestClock.setTime(NOW_MILLIS + 5 * 60 * 1_000);
740 yield* reaper.sweep;
741 const later = state.deleted.filter((id) => Number(id.split("-")[1]) >= 100);
742 expect(later.length).toBeGreaterThan(0);
743 }).pipe(Effect.provide(state.layer));
744 });
745
746 it.effect("rotates bounded pages across a large legacy prefix", () => {
747 const entries = Array.from({ length: 1_000 }, (_, index) =>
748 tunnel({
749 id: `legacy-${index}`,
750 suffix: index.toString(16).padStart(16, "0"),
751 status: "down",
752 timestamp: "2026-08-25T11:00:00.000Z",
753 }),
754 );
755 const state = harness({
756 cleanupMode: "dry-run",
757 tunnels: entries,
758 allocations: entries.map((entry) =>
759 allocation({ tunnelId: entry.id!, recoveryEnabled: false }),
760 ),
761 });
762
763 return Effect.gen(function* () {
764 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
765 yield* TestClock.setTime(NOW_MILLIS);
766 yield* reaper.sweep;
767 const firstPages = state.listRequests
768 .filter((request) => request.status === "down")
769 .map((request) => request.page);
770 state.listRequests.length = 0;
771 yield* TestClock.setTime(NOW_MILLIS + 5 * 60 * 1_000);
772 yield* reaper.sweep;
773 const secondPages = state.listRequests
774 .filter((request) => request.status === "down")
775 .map((request) => request.page);
776 expect(firstPages).not.toEqual(secondPages);
777 expect(firstPages).toHaveLength(5);
778 expect(secondPages).toHaveLength(5);
779 }).pipe(Effect.provide(state.layer));
780 });
781
782 it.effect("rotates the attempt budget across both statuses over consecutive sweeps", () => {
783 const entries = (["down", "inactive"] as const).flatMap((status) =>
784 Array.from({ length: 100 }, (_, index) =>
785 tunnel({
786 id: `${status}-${index}`,
787 suffix: `${status === "down" ? "a" : "b"}${index.toString(16).padStart(15, "0")}`,
788 status,
789 timestamp: "2026-08-25T10:00:00.000Z",
790 }),
791 ),
792 );
793 const state = harness({ tunnels: entries, allocations: recoverableOwners(entries) });
794
795 return Effect.gen(function* () {
796 const reaper = yield* ManagedEndpointReaper.ManagedEndpointReaper;
797 yield* TestClock.setTime(NOW_MILLIS);
798 yield* reaper.sweep;
799 const firstStatus = state.deleted[0]!.split("-")[0];
800 expect(state.deleted).toHaveLength(100);
801 expect(state.deleted.every((id) => id.startsWith(`${firstStatus}-`))).toBe(true);
802
803 state.deleted.length = 0;
804 yield* TestClock.setTime(NOW_MILLIS + 5 * 60 * 1_000);
805 yield* reaper.sweep;
806 expect(state.deleted).toHaveLength(100);
807 expect(state.deleted.every((id) => !id.startsWith(`${firstStatus}-`))).toBe(true);
808 }).pipe(Effect.provide(state.layer));
809 });
810});