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

ManagedEndpointAllocations.ts

657 lines23.9 KB

1import type { RelayManagedEndpoint, RelayManagedEndpointOrigin } from "@t3tools/contracts/relay";
2import { and, eq, exists, inArray, isNull, sql } from "drizzle-orm";
3import { QueryBuilder } from "drizzle-orm/pg-core";
4import * as Context from "effect/Context";
5import * as DateTime from "effect/DateTime";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Schema from "effect/Schema";
10import * as SqlError from "effect/unstable/sql/SqlError";
11​
12import * as RelayDb from "../db.ts";
13import { isManagedEndpointHostname, managedEndpointForHostname } from "../deploymentConfig.ts";
14import { relayEnvironmentLinks, relayManagedEndpointAllocations } from "../persistence/schema.ts";
15​
16export interface ManagedEndpointAllocation {
17 readonly userId: string;
18 readonly environmentId: string;
19 readonly hostname: string;
20 readonly tunnelId: string | null;
21 readonly tunnelName: string;
22 readonly dnsRecordId: string | null;
23 readonly readyAt: string | null;
24 readonly origin: RelayManagedEndpointOrigin | null;
25 readonly updatedAt: string;
26 readonly generation: number;
28​
29export interface ManagedEndpointTunnelAllocation extends ManagedEndpointAllocation {
30 readonly recoveryEnabled: boolean;
32​
33export const MANAGED_ENDPOINT_ALLOCATION_LOOKUP_BATCH_SIZE = 500;
34​
35export function resolveReadyManagedEndpoint(input: {
36 readonly allocation: ManagedEndpointAllocation;
37 readonly baseDomain: string | undefined;
38}): RelayManagedEndpoint | null {
39 if (
40 !input.baseDomain ||
41 input.allocation.readyAt === null ||
42 input.allocation.tunnelId === null ||
43 input.allocation.dnsRecordId === null ||
44 !isManagedEndpointHostname(input.allocation.hostname, input.baseDomain)
45 ) {
46 return null;
47 }
48 return managedEndpointForHostname(input.allocation.hostname);
50​
51export class ManagedEndpointAllocationPersistenceError extends Schema.TaggedError<ManagedEndpointAllocationPersistenceError>()(
52 "ManagedEndpointAllocationPersistenceError",
53 {
54 operation: Schema.Literals([
55 "get",
56 "reserve",
57 "record-tunnel",
58 "record-dns",
59 "mark-ready",
60 "enable-recovery",
61 "list-tunnels",
62 "lock-tunnel",
63 "claim-release",
64 "claim-deprovision",
65 "remove",
66 "remove-claimed",
67 ]),
68 stage: Schema.Literals(["database-request", "resolve-reservation"]),
69 userId: Schema.String,
70 environmentId: Schema.String,
71 hostname: Schema.optionalKey(Schema.String),
72 tunnelName: Schema.optionalKey(Schema.String),
73 tunnelId: Schema.optionalKey(Schema.String),
74 dnsRecordId: Schema.optionalKey(Schema.String),
75 cause: Schema.optional(Schema.Defect()),
76 },
77) {
78 override get message(): string {
79 return `Managed endpoint allocation '${this.operation}' failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
80 }
82​
83interface ManagedEndpointAllocationKey {
84 readonly userId: string;
85 readonly environmentId: string;
87​
88interface ReserveManagedEndpointAllocationInput extends ManagedEndpointAllocationKey {
89 readonly hostname: string;
90 readonly tunnelName: string;
92​
93interface RecordManagedEndpointTunnelInput extends ManagedEndpointAllocationKey {
94 readonly tunnelId: string;
95 readonly generation: number;
97​
98interface RecordManagedEndpointDnsInput extends ManagedEndpointAllocationKey {
99 readonly dnsRecordId: string;
100 readonly tunnelId: string;
101 readonly generation: number;
103​
104interface MarkManagedEndpointReadyInput extends ManagedEndpointAllocationKey {
105 readonly tunnelId: string;
106 readonly generation: number;
107 readonly origin: RelayManagedEndpointOrigin;
109​
110interface ClaimManagedEndpointReleaseInput extends ManagedEndpointAllocationKey {
111 readonly tunnelId: string;
112 readonly generation: number;
114​
115interface EnableManagedEndpointRecoveryInput extends ManagedEndpointAllocationKey {
116 readonly tunnelId: string;
117 readonly environmentPublicKey: string;
118 readonly origin: RelayManagedEndpointOrigin;
120​
121interface ClaimManagedEndpointDeprovisionInput extends ManagedEndpointAllocationKey {
122 readonly generation: number;
124​
125interface RemoveClaimedManagedEndpointAllocationInput extends ManagedEndpointAllocationKey {
126 readonly generation: number;
128​
129export class ManagedEndpointAllocations extends Context.Service<
130 ManagedEndpointAllocations,
131 {
132 readonly get: (
133 input: ManagedEndpointAllocationKey,
134 ) => Effect.Effect<ManagedEndpointAllocation | null, ManagedEndpointAllocationPersistenceError>;
135 readonly reserve: (
136 input: ReserveManagedEndpointAllocationInput,
137 ) => Effect.Effect<ManagedEndpointAllocation, ManagedEndpointAllocationPersistenceError>;
138 readonly recordTunnel: (
139 input: RecordManagedEndpointTunnelInput,
140 ) => Effect.Effect<number | null, ManagedEndpointAllocationPersistenceError>;
141 readonly recordDns: (
142 input: RecordManagedEndpointDnsInput,
143 ) => Effect.Effect<number | null, ManagedEndpointAllocationPersistenceError>;
144 readonly markReady: (
145 input: MarkManagedEndpointReadyInput,
146 ) => Effect.Effect<boolean, ManagedEndpointAllocationPersistenceError>;
147 readonly enableRecovery: (
148 input: EnableManagedEndpointRecoveryInput,
149 ) => Effect.Effect<boolean, ManagedEndpointAllocationPersistenceError>;
150 readonly listByTunnelNames: (
151 tunnelNames: ReadonlyArray<string>,
152 ) => Effect.Effect<
153 ReadonlyArray<ManagedEndpointTunnelAllocation>,
154 ManagedEndpointAllocationPersistenceError
155 >;
156 /**
157 * Atomically claims the right to delete the allocation's tunnel: succeeds
158 * only while the recorded tunnel and generation still match what the
159 * caller loaded. A concurrent provision increments `generation` when it
160 * records its tunnel, which makes a stale claim fail and keeps the freshly
161 * issued tunnel alive.
162 */
163 readonly claimRelease: (
164 input: ClaimManagedEndpointReleaseInput,
165 ) => Effect.Effect<number | null, ManagedEndpointAllocationPersistenceError>;
166 readonly withClaimedTunnel: <A, E, R>(
167 input: ClaimManagedEndpointReleaseInput,
168 effect: Effect.Effect<A, E, R>,
169 ) => Effect.Effect<Option.Option<A>, E | ManagedEndpointAllocationPersistenceError, R>;
170 /**
171 * Claims the complete allocation for teardown only if its generation still
172 * matches the snapshot captured by the unlink operation.
173 *
174 * Returns the claim generation used by `removeClaimed`, or null when a
175 * concurrent provision has already superseded the snapshot.
176 */
177 readonly claimDeprovision: (
178 input: ClaimManagedEndpointDeprovisionInput,
179 ) => Effect.Effect<number | null, ManagedEndpointAllocationPersistenceError>;
180 readonly remove: (
181 input: ManagedEndpointAllocationKey,
182 ) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
183 readonly removeClaimed: (
184 input: RemoveClaimedManagedEndpointAllocationInput,
185 ) => Effect.Effect<boolean, ManagedEndpointAllocationPersistenceError>;
186 }
187>()("t3code-relay/environments/ManagedEndpointAllocations") {}
188​
189const allocationSelection = {
190 userId: relayManagedEndpointAllocations.userId,
191 environmentId: relayManagedEndpointAllocations.environmentId,
192 hostname: relayManagedEndpointAllocations.hostname,
193 tunnelId: relayManagedEndpointAllocations.tunnelId,
194 tunnelName: relayManagedEndpointAllocations.tunnelName,
195 dnsRecordId: relayManagedEndpointAllocations.dnsRecordId,
196 readyAt: relayManagedEndpointAllocations.readyAt,
197 origin: relayManagedEndpointAllocations.origin,
198 updatedAt: relayManagedEndpointAllocations.updatedAt,
199 generation: relayManagedEndpointAllocations.generation,
200};
201​
202const whereAllocation = (input: ManagedEndpointAllocationKey) =>
203 and(
204 eq(relayManagedEndpointAllocations.userId, input.userId),
205 eq(relayManagedEndpointAllocations.environmentId, input.environmentId),
206 );
207​
208export const make = Effect.gen(function* () {
209 const db = yield* RelayDb.RelayDb;
210​
211 return ManagedEndpointAllocations.of({
212 get: Effect.fn("relay.managed_endpoint_allocations.get")(function* (
213 input: ManagedEndpointAllocationKey,
214 ) {
215 return yield* db
216 .select(allocationSelection)
217 .from(relayManagedEndpointAllocations)
218 .where(whereAllocation(input))
219 .limit(1)
220 .pipe(
221 Effect.map((rows) => rows[0] ?? null),
222 Effect.mapError(
223 (cause) =>
224 new ManagedEndpointAllocationPersistenceError({
225 operation: "get",
226 stage: "database-request",
227 ...input,
228 cause,
229 }),
230 ),
231 );
232 }),
233 reserve: Effect.fn("relay.managed_endpoint_allocations.reserve")(function* (
234 input: ReserveManagedEndpointAllocationInput,
235 ) {
236 const now = DateTime.formatIso(yield* DateTime.now);
237 const inserted = yield* db
238 .insert(relayManagedEndpointAllocations)
239 .values({
240 ...input,
241 createdAt: now,
242 updatedAt: now,
243 })
244 .onConflictDoNothing()
245 .returning(allocationSelection)
246 .pipe(
247 Effect.mapError(
248 (cause) =>
249 new ManagedEndpointAllocationPersistenceError({
250 operation: "reserve",
251 stage: "database-request",
252 ...input,
253 cause,
254 }),
255 ),
256 );
257​
258 const allocation =
259 inserted[0] ??
260 (yield* db
261 .select(allocationSelection)
262 .from(relayManagedEndpointAllocations)
263 .where(whereAllocation(input))
264 .limit(1)
265 .pipe(
266 Effect.map((rows) => rows[0]),
267 Effect.mapError(
268 (cause) =>
269 new ManagedEndpointAllocationPersistenceError({
270 operation: "reserve",
271 stage: "database-request",
272 ...input,
273 cause,
274 }),
275 ),
276 ));
277​
278 if (allocation === undefined) {
279 return yield* new ManagedEndpointAllocationPersistenceError({
280 operation: "reserve",
281 stage: "resolve-reservation",
282 ...input,
283 });
284 }
285​
286 return allocation;
287 }),
288 recordTunnel: Effect.fn("relay.managed_endpoint_allocations.record_tunnel")(function* (
289 input: RecordManagedEndpointTunnelInput,
290 ) {
291 return yield* db
292 .update(relayManagedEndpointAllocations)
293 .set({
294 tunnelId: input.tunnelId,
295 readyAt: sql`case when ${relayManagedEndpointAllocations.tunnelId} = ${input.tunnelId} then ${relayManagedEndpointAllocations.readyAt} else null end`,
296 origin: sql`case when ${relayManagedEndpointAllocations.tunnelId} = ${input.tunnelId} then ${relayManagedEndpointAllocations.origin} else null end`,
297 // Recovery registration is per tunnel: a replacement must register
298 // again before the reaper may treat it as recoverable.
299 recoveryEnabledAt: sql`case when ${relayManagedEndpointAllocations.tunnelId} = ${input.tunnelId} then ${relayManagedEndpointAllocations.recoveryEnabledAt} else null end`,
300 recoveryEnvironmentPublicKey: sql`case when ${relayManagedEndpointAllocations.tunnelId} = ${input.tunnelId} then ${relayManagedEndpointAllocations.recoveryEnvironmentPublicKey} else null end`,
301 updatedAt: DateTime.formatIso(yield* DateTime.now),
302 generation: sql`${relayManagedEndpointAllocations.generation} + 1`,
303 })
304 .where(
305 and(
306 whereAllocation(input),
307 eq(relayManagedEndpointAllocations.generation, input.generation),
308 ),
309 )
310 .returning({ generation: relayManagedEndpointAllocations.generation })
311 .pipe(
312 Effect.map((rows) => rows[0]?.generation ?? null),
313 Effect.mapError(
314 (cause) =>
315 new ManagedEndpointAllocationPersistenceError({
316 operation: "record-tunnel",
317 stage: "database-request",
318 ...input,
319 cause,
320 }),
321 ),
322 );
323 }),
324 recordDns: Effect.fn("relay.managed_endpoint_allocations.record_dns")(function* (
325 input: RecordManagedEndpointDnsInput,
326 ) {
327 return yield* db
328 .update(relayManagedEndpointAllocations)
329 .set({
330 dnsRecordId: input.dnsRecordId,
331 updatedAt: DateTime.formatIso(yield* DateTime.now),
332 generation: sql`${relayManagedEndpointAllocations.generation} + 1`,
333 })
334 .where(
335 and(
336 whereAllocation(input),
337 eq(relayManagedEndpointAllocations.tunnelId, input.tunnelId),
338 eq(relayManagedEndpointAllocations.generation, input.generation),
339 ),
340 )
341 .returning({ generation: relayManagedEndpointAllocations.generation })
342 .pipe(
343 Effect.map((rows) => rows[0]?.generation ?? null),
344 Effect.mapError(
345 (cause) =>
346 new ManagedEndpointAllocationPersistenceError({
347 operation: "record-dns",
348 stage: "database-request",
349 ...input,
350 cause,
351 }),
352 ),
353 );
354 }),
355 markReady: Effect.fn("relay.managed_endpoint_allocations.mark_ready")(function* (
356 input: MarkManagedEndpointReadyInput,
357 ) {
358 const now = DateTime.formatIso(yield* DateTime.now);
359 return yield* db
360 .update(relayManagedEndpointAllocations)
361 .set({
362 readyAt: now,
363 origin: input.origin,
364 updatedAt: now,
365 generation: sql`${relayManagedEndpointAllocations.generation} + 1`,
366 })
367 .where(
368 and(
369 whereAllocation(input),
370 eq(relayManagedEndpointAllocations.tunnelId, input.tunnelId),
371 eq(relayManagedEndpointAllocations.generation, input.generation),
372 ),
373 )
374 .returning({ environmentId: relayManagedEndpointAllocations.environmentId })
375 .pipe(
376 Effect.map((rows) => rows.length > 0),
377 Effect.mapError(
378 (cause) =>
379 new ManagedEndpointAllocationPersistenceError({
380 operation: "mark-ready",
381 stage: "database-request",
382 ...input,
383 cause,
384 }),
385 ),
386 );
387 }),
388 enableRecovery: Effect.fn("relay.managed_endpoint_allocations.enable_recovery")(function* (
389 input: EnableManagedEndpointRecoveryInput,
390 ) {
391 const now = DateTime.formatIso(yield* DateTime.now);
392 return yield* db
393 .update(relayManagedEndpointAllocations)
394 .set({
395 recoveryEnabledAt: now,
396 recoveryEnvironmentPublicKey: input.environmentPublicKey,
397 updatedAt: now,
398 generation: sql`${relayManagedEndpointAllocations.generation} + 1`,
399 })
400 .where(
401 and(
402 whereAllocation(input),
403 eq(relayManagedEndpointAllocations.tunnelId, input.tunnelId),
404 eq(relayManagedEndpointAllocations.origin, input.origin),
405 exists(
406 new QueryBuilder()
407 .select({ userId: relayEnvironmentLinks.userId })
408 .from(relayEnvironmentLinks)
409 .where(
410 and(
411 eq(relayEnvironmentLinks.userId, input.userId),
412 eq(relayEnvironmentLinks.environmentId, input.environmentId),
413 eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
414 eq(relayEnvironmentLinks.endpointProviderKind, "cloudflare_tunnel"),
415 isNull(relayEnvironmentLinks.revokedAt),
416 ),
417 )
418 .for("update"),
419 ),
420 ),
421 )
422 .returning({ environmentId: relayManagedEndpointAllocations.environmentId })
423 .pipe(
424 Effect.map((rows) => rows.length > 0),
425 Effect.mapError(
426 (cause) =>
427 new ManagedEndpointAllocationPersistenceError({
428 operation: "enable-recovery",
429 stage: "database-request",
430 ...input,
431 cause,
432 }),
433 ),
434 );
435 }),
436 listByTunnelNames: Effect.fn("relay.managed_endpoint_allocations.list_by_tunnel_names")(
437 function* (tunnelNames: ReadonlyArray<string>) {
438 if (tunnelNames.length === 0) {
439 return [];
440 }
441 const batches = Array.from(
442 { length: Math.ceil(tunnelNames.length / MANAGED_ENDPOINT_ALLOCATION_LOOKUP_BATCH_SIZE) },
443 (_, index) =>
444 tunnelNames.slice(
445 index * MANAGED_ENDPOINT_ALLOCATION_LOOKUP_BATCH_SIZE,
446 (index + 1) * MANAGED_ENDPOINT_ALLOCATION_LOOKUP_BATCH_SIZE,
447 ),
448 );
449 const results = yield* Effect.forEach(
450 batches,
451 (batch) =>
452 db
453 .select({
454 ...allocationSelection,
455 recoveryEnabledAt: relayManagedEndpointAllocations.recoveryEnabledAt,
456 recoveryEnvironmentPublicKey:
457 relayManagedEndpointAllocations.recoveryEnvironmentPublicKey,
458 linkedEnvironmentPublicKey: relayEnvironmentLinks.environmentPublicKey,
459 })
460 .from(relayManagedEndpointAllocations)
461 .leftJoin(
462 relayEnvironmentLinks,
463 and(
464 eq(relayEnvironmentLinks.userId, relayManagedEndpointAllocations.userId),
465 eq(
466 relayEnvironmentLinks.environmentId,
467 relayManagedEndpointAllocations.environmentId,
468 ),
469 isNull(relayEnvironmentLinks.revokedAt),
470 ),
471 )
472 .where(inArray(relayManagedEndpointAllocations.tunnelName, batch))
473 .pipe(
474 Effect.map((rows) =>
475 rows.map(
476 ({
477 recoveryEnabledAt,
478 recoveryEnvironmentPublicKey,
479 linkedEnvironmentPublicKey,
480 ...allocation
481 }) => ({
482 ...allocation,
483 recoveryEnabled:
484 recoveryEnabledAt !== null &&
485 recoveryEnvironmentPublicKey !== null &&
486 recoveryEnvironmentPublicKey === linkedEnvironmentPublicKey,
487 }),
488 ),
489 ),
490 Effect.mapError(
491 (cause) =>
492 new ManagedEndpointAllocationPersistenceError({
493 operation: "list-tunnels",
494 stage: "database-request",
495 userId: "*",
496 environmentId: "*",
497 cause,
498 }),
499 ),
500 ),
501 { concurrency: 1 },
502 );
503 return results.flat();
504 },
505 ),
506 claimRelease: Effect.fn("relay.managed_endpoint_allocations.claim_release")(function* (
507 input: ClaimManagedEndpointReleaseInput,
508 ) {
509 const claimed = yield* db
510 .update(relayManagedEndpointAllocations)
511 .set({
512 updatedAt: DateTime.formatIso(yield* DateTime.now),
513 generation: sql`${relayManagedEndpointAllocations.generation} + 1`,
514 })
515 .where(
516 and(
517 whereAllocation(input),
518 eq(relayManagedEndpointAllocations.tunnelId, input.tunnelId),
519 eq(relayManagedEndpointAllocations.generation, input.generation),
520 ),
521 )
522 .returning({ generation: relayManagedEndpointAllocations.generation })
523 .pipe(
524 Effect.map((rows) => rows[0]?.generation ?? null),
525 Effect.mapError(
526 (cause) =>
527 new ManagedEndpointAllocationPersistenceError({
528 operation: "claim-release",
529 stage: "database-request",
530 userId: input.userId,
531 environmentId: input.environmentId,
532 tunnelId: input.tunnelId,
533 cause,
534 }),
535 ),
536 );
537 return claimed;
538 }),
539 withClaimedTunnel: Effect.fn("relay.managed_endpoint_allocations.with_claimed_tunnel")(
540 function* <A, E, R>(
541 input: ClaimManagedEndpointReleaseInput,
542 effect: Effect.Effect<A, E, R>,
543 ): Effect.fn.Return<Option.Option<A>, E | ManagedEndpointAllocationPersistenceError, R> {
544 const lockError = (cause: unknown) =>
545 new ManagedEndpointAllocationPersistenceError({
546 operation: "lock-tunnel",
547 stage: "database-request",
548 userId: input.userId,
549 environmentId: input.environmentId,
550 tunnelId: input.tunnelId,
551 cause,
552 });
553 return yield* db.$client
554 .withTransaction(
555 db
556 .select({ generation: relayManagedEndpointAllocations.generation })
557 .from(relayManagedEndpointAllocations)
558 .where(
559 and(
560 whereAllocation(input),
561 eq(relayManagedEndpointAllocations.tunnelId, input.tunnelId),
562 eq(relayManagedEndpointAllocations.generation, input.generation),
563 ),
564 )
565 .limit(1)
566 .for("update")
567 .pipe(
568 Effect.mapError(lockError),
569 Effect.flatMap((rows) =>
570 rows.length === 0 ? Effect.succeedNone : Effect.asSome(effect),
571 ),
572 ),
573 )
574 .pipe(
575 Effect.mapError((cause) => (SqlError.isSqlError(cause) ? lockError(cause) : cause)),
576 );
577 },
578 ),
579 claimDeprovision: Effect.fn("relay.managed_endpoint_allocations.claim_deprovision")(function* (
580 input: ClaimManagedEndpointDeprovisionInput,
581 ) {
582 const claimed = yield* db
583 .update(relayManagedEndpointAllocations)
584 .set({
585 updatedAt: DateTime.formatIso(yield* DateTime.now),
586 generation: sql`${relayManagedEndpointAllocations.generation} + 1`,
587 })
588 .where(
589 and(
590 whereAllocation(input),
591 eq(relayManagedEndpointAllocations.generation, input.generation),
592 ),
593 )
594 .returning({ generation: relayManagedEndpointAllocations.generation })
595 .pipe(
596 Effect.map((rows) => rows[0]?.generation ?? null),
597 Effect.mapError(
598 (cause) =>
599 new ManagedEndpointAllocationPersistenceError({
600 operation: "claim-deprovision",
601 stage: "database-request",
602 userId: input.userId,
603 environmentId: input.environmentId,
604 cause,
605 }),
606 ),
607 );
608 return claimed;
609 }),
610 remove: Effect.fn("relay.managed_endpoint_allocations.remove")(function* (
611 input: ManagedEndpointAllocationKey,
612 ) {
613 yield* db
614 .delete(relayManagedEndpointAllocations)
615 .where(whereAllocation(input))
616 .pipe(
617 Effect.mapError(
618 (cause) =>
619 new ManagedEndpointAllocationPersistenceError({
620 operation: "remove",
621 stage: "database-request",
622 ...input,
623 cause,
624 }),
625 ),
626 );
627 }),
628 removeClaimed: Effect.fn("relay.managed_endpoint_allocations.remove_claimed")(function* (
629 input: RemoveClaimedManagedEndpointAllocationInput,
630 ) {
631 return yield* db
632 .delete(relayManagedEndpointAllocations)
633 .where(
634 and(
635 whereAllocation(input),
636 eq(relayManagedEndpointAllocations.generation, input.generation),
637 ),
638 )
639 .returning({ userId: relayManagedEndpointAllocations.userId })
640 .pipe(
641 Effect.map((rows) => rows.length > 0),
642 Effect.mapError(
643 (cause) =>
644 new ManagedEndpointAllocationPersistenceError({
645 operation: "remove-claimed",
646 stage: "database-request",
647 userId: input.userId,
648 environmentId: input.environmentId,
649 cause,
650 }),
651 ),
652 );
653 }),
654 });
655});
656​
657export const layer = Layer.effect(ManagedEndpointAllocations, make);