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

ManagedEndpointReaper.ts

309 lines10.2 KB

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