Open History to see the last commit
1import * as Context from "effect/Context";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6
7import type { ManagedEndpointCleanupMode } from "../Config.ts";
8import * as RelayConfiguration from "../Config.ts";
9import { managedEndpointTunnelNamePrefix } from "../deploymentConfig.ts";
10import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
11import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
12
13export const MANAGED_ENDPOINT_GRACE_PERIOD_MINUTES = 5;
14// A tunnel that never connected is usually a link still being set up: a slow
15// cloudflared download or a user who walked away mid-pairing. Give it an hour.
16export const MANAGED_ENDPOINT_INACTIVE_GRACE_PERIOD_MINUTES = 60;
17export const MANAGED_ENDPOINT_SWEEP_PAGE_SIZE = 100;
18export const MANAGED_ENDPOINT_SWEEP_ATTEMPT_LIMIT = 100;
19export const MANAGED_ENDPOINT_SWEEP_LIST_REQUEST_LIMIT = 10;
20
21export interface ManagedEndpointSweepResult {
22 readonly mode: ManagedEndpointCleanupMode;
23 readonly listRequests: number;
24 readonly scanned: number;
25 readonly attempted: number;
26 readonly deleted: number;
27 readonly wouldDelete: number;
28 readonly skippedLegacy: number;
29 readonly skippedOrphan: number;
30 readonly failed: number;
31 readonly truncated: boolean;
32}
33
34export class ManagedEndpointReaper extends Context.Service<
35 ManagedEndpointReaper,
36 {
37 readonly sweep: Effect.Effect<
38 ManagedEndpointSweepResult,
39 | ManagedEndpointProvider.ManagedEndpointTunnelClientError
40 | ManagedEndpointAllocations.ManagedEndpointAllocationPersistenceError
41 >;
42 }
43>()("t3code-relay/environments/ManagedEndpointReaper") {}
44
45function isExpiredManagedTunnel(input: {
46 readonly tunnel: ManagedEndpointProvider.ManagedEndpointTunnel;
47 readonly status: "down" | "inactive";
48 readonly prefix: string;
49 readonly cutoff: DateTime.Utc;
50}): input is typeof input & {
51 readonly tunnel: ManagedEndpointProvider.ManagedEndpointTunnel & {
52 readonly id: string;
53 readonly name: string;
54 };
55} {
56 const { tunnel, status, prefix, cutoff } = input;
57 if (
58 typeof tunnel.id !== "string" ||
59 typeof tunnel.name !== "string" ||
60 tunnel.status !== status ||
61 !tunnel.name.startsWith(prefix) ||
62 !/^[a-f0-9]{16}$/u.test(tunnel.name.slice(prefix.length))
63 ) {
64 return false;
65 }
66 const inactiveAt = status === "down" ? tunnel.connsInactiveAt : tunnel.createdAt;
67 if (typeof inactiveAt !== "string") {
68 return false;
69 }
70 const timestamp = DateTime.make(inactiveAt);
71 return Option.isSome(timestamp) && timestamp.value.epochMilliseconds <= cutoff.epochMilliseconds;
72}
73
74function isRateLimited(cause: unknown): boolean {
75 if (typeof cause !== "object" || cause === null) {
76 return false;
77 }
78 if ("_tag" in cause && cause._tag === "TooManyRequests") {
79 return true;
80 }
81 if ("status" in cause && cause.status === 429) {
82 return true;
83 }
84 return "cause" in cause && isRateLimited(cause.cause);
85}
86
87function rotatedPages(input: {
88 readonly totalCount: number | undefined;
89 readonly slot: number;
90 readonly limit: number;
91}): ReadonlyArray<number> {
92 if (input.limit <= 0) return [];
93 if (input.totalCount === undefined) {
94 return Array.from({ length: input.limit }, (_, index) => index + 2);
95 }
96 const laterPageCount = Math.max(
97 0,
98 Math.ceil(input.totalCount / MANAGED_ENDPOINT_SWEEP_PAGE_SIZE) - 1,
99 );
100 if (laterPageCount === 0) return [];
101 const count = Math.min(input.limit, laterPageCount);
102 const start = input.slot % laterPageCount;
103 return Array.from({ length: count }, (_, index) => 2 + ((start + index) % laterPageCount));
104}
105
106const emptyResult = (mode: ManagedEndpointCleanupMode): ManagedEndpointSweepResult => ({
107 mode,
108 listRequests: 0,
109 scanned: 0,
110 attempted: 0,
111 deleted: 0,
112 wouldDelete: 0,
113 skippedLegacy: 0,
114 skippedOrphan: 0,
115 failed: 0,
116 truncated: false,
117});
118
119export const make = Effect.gen(function* () {
120 const config = yield* RelayConfiguration.RelayConfiguration;
121 const tunnels = yield* ManagedEndpointProvider.ManagedEndpointTunnelClient;
122 const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;
123 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
124
125 const sweep = Effect.gen(function* () {
126 const mode = config.managedEndpointCleanupMode ?? "off";
127 const namespace = config.managedEndpointNamespace;
128 if (mode === "off" || !namespace) return emptyResult(mode);
129
130 const now = yield* DateTime.now;
131 const cutoffFor = (status: "down" | "inactive") =>
132 DateTime.subtract(now, {
133 minutes:
134 status === "down"
135 ? MANAGED_ENDPOINT_GRACE_PERIOD_MINUTES
136 : MANAGED_ENDPOINT_INACTIVE_GRACE_PERIOD_MINUTES,
137 });
138 const prefix = managedEndpointTunnelNamePrefix(namespace);
139 const slot = Math.floor(
140 now.epochMilliseconds / (MANAGED_ENDPOINT_GRACE_PERIOD_MINUTES * 60 * 1_000),
141 );
142 let listRequests = 0;
143 let truncated = false;
144 const expired: Array<{
145 readonly tunnel: ManagedEndpointProvider.ManagedEndpointTunnel & {
146 readonly id: string;
147 readonly name: string;
148 };
149 readonly status: "down" | "inactive";
150 readonly cutoff: DateTime.Utc;
151 }> = [];
152
153 for (const status of ["down", "inactive"] as const) {
154 const cutoff = cutoffFor(status);
155 const cutoffIso = DateTime.formatIso(cutoff);
156 const listPage = (page: number) => {
157 listRequests += 1;
158 return tunnels.list({
159 isDeleted: false,
160 includePrefix: prefix,
161 status,
162 existedAt: cutoffIso,
163 ...(status === "down" ? { wasInactiveAt: cutoffIso } : {}),
164 page,
165 perPage: MANAGED_ENDPOINT_SWEEP_PAGE_SIZE,
166 });
167 };
168 const first = yield* listPage(1);
169 const totalCount =
170 typeof first.resultInfo?.totalCount === "number" ? first.resultInfo.totalCount : undefined;
171 const pages = rotatedPages({
172 totalCount,
173 slot,
174 limit: Math.floor(MANAGED_ENDPOINT_SWEEP_LIST_REQUEST_LIMIT / 2) - 1,
175 });
176 const responses = [first, ...(yield* Effect.forEach(pages, listPage, { concurrency: 1 }))];
177 if (
178 totalCount !== undefined &&
179 Math.ceil(totalCount / MANAGED_ENDPOINT_SWEEP_PAGE_SIZE) > responses.length
180 ) {
181 truncated = true;
182 } else if (
183 totalCount === undefined &&
184 responses.at(-1)?.result.length === MANAGED_ENDPOINT_SWEEP_PAGE_SIZE
185 ) {
186 truncated = true;
187 }
188 for (const response of responses) {
189 expired.push(
190 ...response.result
191 .map((tunnel) => ({ tunnel, status, prefix, cutoff }))
192 .filter(isExpiredManagedTunnel)
193 .map(({ tunnel }) => ({ tunnel, status, cutoff })),
194 );
195 }
196 }
197
198 const collected = [...new Map(expired.map((entry) => [entry.tunnel.id, entry])).values()];
199 // Start each sweep one attempt budget further along so a run of
200 // candidates whose deletes keep failing cannot hold the budget forever
201 // and starve everything listed after them.
202 const offset =
203 collected.length === 0 ? 0 : (slot * MANAGED_ENDPOINT_SWEEP_ATTEMPT_LIMIT) % collected.length;
204 const uniqueExpired = [...collected.slice(offset), ...collected.slice(0, offset)];
205 const recorded = yield* allocations.listByTunnelNames(
206 uniqueExpired.map(({ tunnel }) => tunnel.name),
207 );
208 const recordedByTunnelName = new Map(
209 recorded.map((allocation) => [allocation.tunnelName, allocation]),
210 );
211 let attempted = 0;
212 let deleted = 0;
213 let wouldDelete = 0;
214 let skippedLegacy = 0;
215 let skippedOrphan = 0;
216 let failed = 0;
217
218 for (const { tunnel, status, cutoff } of uniqueExpired) {
219 const cutoffIso = DateTime.formatIso(cutoff);
220 const allocation = recordedByTunnelName.get(tunnel.name);
221 if (
222 allocation !== undefined &&
223 allocation.tunnelId !== null &&
224 allocation.tunnelId !== tunnel.id
225 ) {
226 continue;
227 }
228 const owner = allocation?.tunnelId === tunnel.id ? allocation : undefined;
229 if (owner !== undefined && !owner.recoveryEnabled) {
230 skippedLegacy += 1;
231 continue;
232 }
233 if (allocation !== undefined && owner === undefined) continue;
234 // A tunnel with no allocation row cannot be claimed, so a relink that
235 // adopts it by name races any delete here. Count it and leave it for a
236 // manual sweep instead.
237 if (owner === undefined) {
238 skippedOrphan += 1;
239 continue;
240 }
241 wouldDelete += 1;
242 if (mode === "dry-run") continue;
243 if (attempted >= MANAGED_ENDPOINT_SWEEP_ATTEMPT_LIMIT) {
244 truncated = true;
245 break;
246 }
247 attempted += 1;
248 const result = yield* provider
249 .release({
250 userId: owner.userId,
251 environmentId: owner.environmentId,
252 expectedTunnelId: tunnel.id,
253 expectedInactiveBefore: cutoffIso,
254 expectedStatus: status,
255 })
256 .pipe(Effect.result);
257 if (result._tag === "Failure") {
258 failed += 1;
259 yield* Effect.logWarning("Failed to delete an inactive managed tunnel", {
260 tunnelId: tunnel.id,
261 tunnelName: tunnel.name,
262 cause: result.failure,
263 });
264 if (isRateLimited(result.failure)) {
265 truncated = true;
266 break;
267 }
268 } else if (result.success) {
269 deleted += 1;
270 yield* Effect.logInfo("Deleted an inactive managed tunnel", {
271 tunnelId: tunnel.id,
272 tunnelName: tunnel.name,
273 status,
274 });
275 }
276 }
277
278 return {
279 mode,
280 listRequests,
281 scanned: uniqueExpired.length,
282 attempted,
283 deleted,
284 wouldDelete,
285 skippedLegacy,
286 skippedOrphan,
287 failed,
288 truncated,
289 };
290 }).pipe(
291 // Dry-run rollout reads these counters from the exported span.
292 Effect.tap((result) =>
293 Effect.annotateCurrentSpan(
294 Object.fromEntries(
295 Object.entries(result).map(([key, value]) => [
296 `relay.managed_endpoint_reaper.${key}`,
297 value,
298 ]),
299 ),
300 ),
301 ),
302 Effect.withSpan("relay.managed_endpoint_reaper.sweep"),
303 );
304
305 return ManagedEndpointReaper.of({ sweep });
306});
307
308export const layer = Layer.effect(ManagedEndpointReaper, make);