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

ManagedEndpointAllocations.ts

423 lines14.0 KB

1import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";
2import { and, eq } from "drizzle-orm";
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Schema from "effect/Schema";
8​
9import * as RelayDb from "../db.ts";
10import { isManagedEndpointHostname, managedEndpointForHostname } from "../deploymentConfig.ts";
11import { relayManagedEndpointAllocations } from "../persistence/schema.ts";
12​
13export interface ManagedEndpointAllocation {
14 readonly userId: string;
15 readonly environmentId: string;
16 readonly hostname: string;
17 readonly tunnelId: string | null;
18 readonly tunnelName: string;
19 readonly dnsRecordId: string | null;
20 readonly readyAt: string | null;
21 /**
22 * Doubles as the allocation's generation marker: every mutation rewrites it,
23 * so `claimRelease` can detect a provision that raced a release.
24 */
25 readonly updatedAt: string;
27​
28export function resolveReadyManagedEndpoint(input: {
29 readonly allocation: ManagedEndpointAllocation;
30 readonly baseDomain: string | undefined;
31}): RelayManagedEndpoint | null {
32 if (
33 !input.baseDomain ||
34 input.allocation.readyAt === null ||
35 input.allocation.tunnelId === null ||
36 input.allocation.dnsRecordId === null ||
37 !isManagedEndpointHostname(input.allocation.hostname, input.baseDomain)
38 ) {
39 return null;
40 }
41 return managedEndpointForHostname(input.allocation.hostname);
43​
44export class ManagedEndpointAllocationPersistenceError extends Schema.TaggedErrorClass<ManagedEndpointAllocationPersistenceError>()(
45 "ManagedEndpointAllocationPersistenceError",
46 {
47 operation: Schema.Literals([
48 "get",
49 "reserve",
50 "record-tunnel",
51 "record-dns",
52 "mark-ready",
53 "claim-release",
54 "claim-deprovision",
55 "remove",
56 "remove-claimed",
57 ]),
58 stage: Schema.Literals(["database-request", "resolve-reservation"]),
59 userId: Schema.String,
60 environmentId: Schema.String,
61 hostname: Schema.optionalKey(Schema.String),
62 tunnelName: Schema.optionalKey(Schema.String),
63 tunnelId: Schema.optionalKey(Schema.String),
64 dnsRecordId: Schema.optionalKey(Schema.String),
65 cause: Schema.optional(Schema.Defect()),
66 },
67) {
68 override get message(): string {
69 return `Managed endpoint allocation '${this.operation}' failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;
70 }
72​
73interface ManagedEndpointAllocationKey {
74 readonly userId: string;
75 readonly environmentId: string;
77​
78interface ReserveManagedEndpointAllocationInput extends ManagedEndpointAllocationKey {
79 readonly hostname: string;
80 readonly tunnelName: string;
82​
83interface RecordManagedEndpointTunnelInput extends ManagedEndpointAllocationKey {
84 readonly tunnelId: string;
86​
87interface RecordManagedEndpointDnsInput extends ManagedEndpointAllocationKey {
88 readonly dnsRecordId: string;
90​
91interface ClaimManagedEndpointReleaseInput extends ManagedEndpointAllocationKey {
92 readonly tunnelId: string;
93 readonly updatedAt: string;
95​
96interface ClaimManagedEndpointDeprovisionInput extends ManagedEndpointAllocationKey {
97 readonly updatedAt: string;
99​
100interface RemoveClaimedManagedEndpointAllocationInput extends ManagedEndpointAllocationKey {
101 readonly updatedAt: string;
103​
104export class ManagedEndpointAllocations extends Context.Service<
105 ManagedEndpointAllocations,
106 {
107 readonly get: (
108 input: ManagedEndpointAllocationKey,
109 ) => Effect.Effect<ManagedEndpointAllocation | null, ManagedEndpointAllocationPersistenceError>;
110 readonly reserve: (
111 input: ReserveManagedEndpointAllocationInput,
112 ) => Effect.Effect<ManagedEndpointAllocation, ManagedEndpointAllocationPersistenceError>;
113 readonly recordTunnel: (
114 input: RecordManagedEndpointTunnelInput,
115 ) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
116 readonly recordDns: (
117 input: RecordManagedEndpointDnsInput,
118 ) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
119 readonly markReady: (
120 input: ManagedEndpointAllocationKey,
121 ) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
122 /**
123 * Atomically claims the right to delete the allocation's tunnel: succeeds
124 * only while the recorded tunnel and generation still match what the
125 * caller loaded. A concurrent provision rewrites `updatedAt` when it
126 * records its tunnel, which makes a stale claim fail and keeps the freshly
127 * issued tunnel alive.
128 */
129 readonly claimRelease: (
130 input: ClaimManagedEndpointReleaseInput,
131 ) => Effect.Effect<boolean, ManagedEndpointAllocationPersistenceError>;
132 /**
133 * Claims the complete allocation for teardown only if its generation still
134 * matches the snapshot captured by the unlink operation.
135 *
136 * Returns the claim generation used by `removeClaimed`, or null when a
137 * concurrent provision has already superseded the snapshot.
138 */
139 readonly claimDeprovision: (
140 input: ClaimManagedEndpointDeprovisionInput,
141 ) => Effect.Effect<string | null, ManagedEndpointAllocationPersistenceError>;
142 readonly remove: (
143 input: ManagedEndpointAllocationKey,
144 ) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
145 readonly removeClaimed: (
146 input: RemoveClaimedManagedEndpointAllocationInput,
147 ) => Effect.Effect<boolean, ManagedEndpointAllocationPersistenceError>;
148 }
149>()("t3code-relay/environments/ManagedEndpointAllocations") {}
150​
151const allocationSelection = {
152 userId: relayManagedEndpointAllocations.userId,
153 environmentId: relayManagedEndpointAllocations.environmentId,
154 hostname: relayManagedEndpointAllocations.hostname,
155 tunnelId: relayManagedEndpointAllocations.tunnelId,
156 tunnelName: relayManagedEndpointAllocations.tunnelName,
157 dnsRecordId: relayManagedEndpointAllocations.dnsRecordId,
158 readyAt: relayManagedEndpointAllocations.readyAt,
159 updatedAt: relayManagedEndpointAllocations.updatedAt,
160};
161​
162const whereAllocation = (input: ManagedEndpointAllocationKey) =>
163 and(
164 eq(relayManagedEndpointAllocations.userId, input.userId),
165 eq(relayManagedEndpointAllocations.environmentId, input.environmentId),
166 );
167​
168export const make = Effect.gen(function* () {
169 const db = yield* RelayDb.RelayDb;
170​
171 return ManagedEndpointAllocations.of({
172 get: Effect.fn("relay.managed_endpoint_allocations.get")(function* (
173 input: ManagedEndpointAllocationKey,
174 ) {
175 return yield* db
176 .select(allocationSelection)
177 .from(relayManagedEndpointAllocations)
178 .where(whereAllocation(input))
179 .limit(1)
180 .pipe(
181 Effect.map((rows) => rows[0] ?? null),
182 Effect.mapError(
183 (cause) =>
184 new ManagedEndpointAllocationPersistenceError({
185 operation: "get",
186 stage: "database-request",
187 ...input,
188 cause,
189 }),
190 ),
191 );
192 }),
193 reserve: Effect.fn("relay.managed_endpoint_allocations.reserve")(function* (
194 input: ReserveManagedEndpointAllocationInput,
195 ) {
196 const now = DateTime.formatIso(yield* DateTime.now);
197 const inserted = yield* db
198 .insert(relayManagedEndpointAllocations)
199 .values({
200 ...input,
201 createdAt: now,
202 updatedAt: now,
203 })
204 .onConflictDoNothing()
205 .returning(allocationSelection)
206 .pipe(
207 Effect.mapError(
208 (cause) =>
209 new ManagedEndpointAllocationPersistenceError({
210 operation: "reserve",
211 stage: "database-request",
212 ...input,
213 cause,
214 }),
215 ),
216 );
217​
218 const allocation =
219 inserted[0] ??
220 (yield* db
221 .select(allocationSelection)
222 .from(relayManagedEndpointAllocations)
223 .where(whereAllocation(input))
224 .limit(1)
225 .pipe(
226 Effect.map((rows) => rows[0]),
227 Effect.mapError(
228 (cause) =>
229 new ManagedEndpointAllocationPersistenceError({
230 operation: "reserve",
231 stage: "database-request",
232 ...input,
233 cause,
234 }),
235 ),
236 ));
237​
238 if (allocation === undefined) {
239 return yield* new ManagedEndpointAllocationPersistenceError({
240 operation: "reserve",
241 stage: "resolve-reservation",
242 ...input,
243 });
244 }
245​
246 return allocation;
247 }),
248 recordTunnel: Effect.fn("relay.managed_endpoint_allocations.record_tunnel")(function* (
249 input: RecordManagedEndpointTunnelInput,
250 ) {
251 yield* db
252 .update(relayManagedEndpointAllocations)
253 .set({
254 tunnelId: input.tunnelId,
255 updatedAt: DateTime.formatIso(yield* DateTime.now),
256 })
257 .where(whereAllocation(input))
258 .pipe(
259 Effect.mapError(
260 (cause) =>
261 new ManagedEndpointAllocationPersistenceError({
262 operation: "record-tunnel",
263 stage: "database-request",
264 ...input,
265 cause,
266 }),
267 ),
268 );
269 }),
270 recordDns: Effect.fn("relay.managed_endpoint_allocations.record_dns")(function* (
271 input: RecordManagedEndpointDnsInput,
272 ) {
273 yield* db
274 .update(relayManagedEndpointAllocations)
275 .set({
276 dnsRecordId: input.dnsRecordId,
277 updatedAt: DateTime.formatIso(yield* DateTime.now),
278 })
279 .where(whereAllocation(input))
280 .pipe(
281 Effect.mapError(
282 (cause) =>
283 new ManagedEndpointAllocationPersistenceError({
284 operation: "record-dns",
285 stage: "database-request",
286 ...input,
287 cause,
288 }),
289 ),
290 );
291 }),
292 markReady: Effect.fn("relay.managed_endpoint_allocations.mark_ready")(function* (
293 input: ManagedEndpointAllocationKey,
294 ) {
295 const now = DateTime.formatIso(yield* DateTime.now);
296 yield* db
297 .update(relayManagedEndpointAllocations)
298 .set({
299 readyAt: now,
300 updatedAt: now,
301 })
302 .where(whereAllocation(input))
303 .pipe(
304 Effect.mapError(
305 (cause) =>
306 new ManagedEndpointAllocationPersistenceError({
307 operation: "mark-ready",
308 stage: "database-request",
309 ...input,
310 cause,
311 }),
312 ),
313 );
314 }),
315 claimRelease: Effect.fn("relay.managed_endpoint_allocations.claim_release")(function* (
316 input: ClaimManagedEndpointReleaseInput,
317 ) {
318 const claimed = yield* db
319 .update(relayManagedEndpointAllocations)
320 .set({
321 updatedAt: DateTime.formatIso(yield* DateTime.now),
322 })
323 .where(
324 and(
325 whereAllocation(input),
326 eq(relayManagedEndpointAllocations.tunnelId, input.tunnelId),
327 eq(relayManagedEndpointAllocations.updatedAt, input.updatedAt),
328 ),
329 )
330 .returning({ userId: relayManagedEndpointAllocations.userId })
331 .pipe(
332 Effect.map((rows) => rows.length > 0),
333 Effect.mapError(
334 (cause) =>
335 new ManagedEndpointAllocationPersistenceError({
336 operation: "claim-release",
337 stage: "database-request",
338 userId: input.userId,
339 environmentId: input.environmentId,
340 tunnelId: input.tunnelId,
341 cause,
342 }),
343 ),
344 );
345 return claimed;
346 }),
347 claimDeprovision: Effect.fn("relay.managed_endpoint_allocations.claim_deprovision")(function* (
348 input: ClaimManagedEndpointDeprovisionInput,
349 ) {
350 const claimedAt = DateTime.formatIso(yield* DateTime.now);
351 const claimed = yield* db
352 .update(relayManagedEndpointAllocations)
353 .set({ updatedAt: claimedAt })
354 .where(
355 and(
356 whereAllocation(input),
357 eq(relayManagedEndpointAllocations.updatedAt, input.updatedAt),
358 ),
359 )
360 .returning({ userId: relayManagedEndpointAllocations.userId })
361 .pipe(
362 Effect.map((rows) => rows.length > 0),
363 Effect.mapError(
364 (cause) =>
365 new ManagedEndpointAllocationPersistenceError({
366 operation: "claim-deprovision",
367 stage: "database-request",
368 userId: input.userId,
369 environmentId: input.environmentId,
370 cause,
371 }),
372 ),
373 );
374 return claimed ? claimedAt : null;
375 }),
376 remove: Effect.fn("relay.managed_endpoint_allocations.remove")(function* (
377 input: ManagedEndpointAllocationKey,
378 ) {
379 yield* db
380 .delete(relayManagedEndpointAllocations)
381 .where(whereAllocation(input))
382 .pipe(
383 Effect.mapError(
384 (cause) =>
385 new ManagedEndpointAllocationPersistenceError({
386 operation: "remove",
387 stage: "database-request",
388 ...input,
389 cause,
390 }),
391 ),
392 );
393 }),
394 removeClaimed: Effect.fn("relay.managed_endpoint_allocations.remove_claimed")(function* (
395 input: RemoveClaimedManagedEndpointAllocationInput,
396 ) {
397 return yield* db
398 .delete(relayManagedEndpointAllocations)
399 .where(
400 and(
401 whereAllocation(input),
402 eq(relayManagedEndpointAllocations.updatedAt, input.updatedAt),
403 ),
404 )
405 .returning({ userId: relayManagedEndpointAllocations.userId })
406 .pipe(
407 Effect.map((rows) => rows.length > 0),
408 Effect.mapError(
409 (cause) =>
410 new ManagedEndpointAllocationPersistenceError({
411 operation: "remove-claimed",
412 stage: "database-request",
413 userId: input.userId,
414 environmentId: input.environmentId,
415 cause,
416 }),
417 ),
418 );
419 }),
420 });
421});
422​
423export const layer = Layer.effect(ManagedEndpointAllocations, make);