GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Fix relay credential lookup for unlinked environments (#4692) · pingdotgg/t3code@e00781a

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • infra/relay/src
    • db.ts
    • environments
      • EnvironmentConnector.test.ts
      • EnvironmentCredentials.test.ts
      • EnvironmentCredentials.ts
      • EnvironmentLinker.test.ts
      • ManagedEndpointAllocations.test.ts
      • ManagedEndpointAllocations.ts
      • ManagedEndpointProvider.test.ts
      • ManagedEndpointProvider.ts
      • ManagedTunnelLimits.test.ts
      • ManagedTunnelLimits.ts
    • http
      • Api.test.ts
      • Api.ts
    • worker.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎infra/relay/src/db.ts‎

Copy file name to clipboardExpand all lines: infra/relay/src/db.ts
+18Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import * as RemovalPolicy from "alchemy/RemovalPolicy";
77
import type { EffectPgDatabase } from "drizzle-orm/effect-postgres";
88
import * as Context from "effect/Context";
99
import * as Effect from "effect/Effect";
10+
import * as Layer from "effect/Layer";
1011

1112
import { relayDatabaseMode } from "./dbConfig.ts";
1213

@@ -17,6 +18,23 @@ export class RelayDb extends Context.Service<
1718
}
1819
>()("t3code-relay/db/RelayDb") {}
1920

21+
export class RelayTransactions extends Context.Service<
22+
RelayTransactions,
23+
{
24+
readonly withTransaction: RelayDb["Service"]["$client"]["withTransaction"];
25+
}
26+
>()("t3code-relay/db/RelayTransactions") {
27+
static readonly layer = Layer.effect(
28+
RelayTransactions,
29+
Effect.gen(function* () {
30+
const db = yield* RelayDb;
31+
return RelayTransactions.of({
32+
withTransaction: db.$client.withTransaction,
33+
});
34+
}),
35+
);
36+
}
37+
2038
export const PlanetscaleDatabase = Effect.gen(function* () {
2139
const { stage } = yield* Alchemy.Stack;
2240
const schema = yield* Drizzle.Schema("RelaySchema", {
Collapse file

‎infra/relay/src/environments/EnvironmentConnector.test.ts‎

Copy file name to clipboardExpand all lines: infra/relay/src/environments/EnvironmentConnector.test.ts
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,9 @@ function makeAllocations(
198198
recordDns: () => Effect.die("unused"),
199199
markReady: () => Effect.die("unused"),
200200
claimRelease: () => Effect.die("unused"),
201+
claimDeprovision: () => Effect.die("unused"),
201202
remove: () => Effect.die("unused"),
203+
removeClaimed: () => Effect.die("unused"),
202204
};
203205
}
204206

Collapse file

‎infra/relay/src/environments/EnvironmentCredentials.test.ts‎

Copy file name to clipboardExpand all lines: infra/relay/src/environments/EnvironmentCredentials.test.ts
+14-4Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
22
import { describe, expect, it } from "@effect/vitest";
3-
import { PgDialect, QueryBuilder } from "drizzle-orm/pg-core";
3+
import { PgDialect } from "drizzle-orm/pg-core";
44
import * as Effect from "effect/Effect";
55
import * as Layer from "effect/Layer";
66

@@ -58,13 +58,17 @@ describe("EnvironmentCredentials", () => {
5858
it.effect("does not retain credential tokens when lookup persistence fails", () => {
5959
const cause = new Error("database unavailable");
6060
const token = "t3env_sensitive-credential-token";
61+
const whereConditions: Array<unknown> = [];
6162
const fakeDb = {
6263
select: () => ({
6364
from: (table: unknown) => {
6465
expect(table).toBe(relayEnvironmentCredentials);
6566
return {
66-
where: () => ({
67-
limit: () => Effect.fail(cause),
67+
where: (condition: unknown) => ({
68+
limit: () => {
69+
whereConditions.push(condition);
70+
return Effect.fail(cause);
71+
},
6872
}),
6973
};
7074
},
@@ -81,6 +85,13 @@ describe("EnvironmentCredentials", () => {
8185
});
8286
expect(error.cause).toBe(cause);
8387
expect(error).not.toHaveProperty("token");
88+
expect(whereConditions).toHaveLength(1);
89+
90+
const query = new PgDialect().sqlToQuery(whereConditions[0] as never);
91+
expect(query.sql).toContain("exists");
92+
expect(query.sql).toContain('"relay_environment_links"."environment_id"');
93+
expect(query.sql).toContain('"relay_environment_links"."environment_public_key"');
94+
expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');
8495
}).pipe(
8596
Effect.provide(
8697
EnvironmentCredentials.layer.pipe(
@@ -180,7 +191,6 @@ describe("EnvironmentCredentials", () => {
180191
const updateValues: Array<Record<string, unknown>> = [];
181192
const whereConditions: Array<unknown> = [];
182193
const fakeDb = {
183-
select: (fields: Parameters<QueryBuilder["select"]>[0]) => new QueryBuilder().select(fields),
184194
update: (table: unknown) => {
185195
expect(table).toBe(relayEnvironmentCredentials);
186196
return {
Collapse file

‎infra/relay/src/environments/EnvironmentCredentials.ts‎

Copy file name to clipboardExpand all lines: infra/relay/src/environments/EnvironmentCredentials.ts
+21-2Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ import * as Encoding from "effect/Encoding";
66
import * as Layer from "effect/Layer";
77
import * as Option from "effect/Option";
88
import * as Schema from "effect/Schema";
9-
import { and, eq, isNull, ne, notExists } from "drizzle-orm";
9+
import { and, eq, exists, isNull, ne, notExists } from "drizzle-orm";
10+
import { QueryBuilder } from "drizzle-orm/pg-core";
1011

1112
import * as RelayDb from "../db.ts";
1213
import { relayEnvironmentCredentials, relayEnvironmentLinks } from "../persistence/schema.ts";
@@ -196,6 +197,24 @@ const make = Effect.gen(function* () {
196197
and(
197198
eq(relayEnvironmentCredentials.credentialHash, credentialHash),
198199
isNull(relayEnvironmentCredentials.revokedAt),
200+
exists(
201+
new QueryBuilder()
202+
.select({ userId: relayEnvironmentLinks.userId })
203+
.from(relayEnvironmentLinks)
204+
.where(
205+
and(
206+
eq(
207+
relayEnvironmentLinks.environmentId,
208+
relayEnvironmentCredentials.environmentId,
209+
),
210+
eq(
211+
relayEnvironmentLinks.environmentPublicKey,
212+
relayEnvironmentCredentials.environmentPublicKey,
213+
),
214+
isNull(relayEnvironmentLinks.revokedAt),
215+
),
216+
),
217+
),
199218
),
200219
)
201220
.limit(1)
@@ -238,7 +257,7 @@ const make = Effect.gen(function* () {
238257
eq(relayEnvironmentCredentials.environmentPublicKey, input.environmentPublicKey),
239258
isNull(relayEnvironmentCredentials.revokedAt),
240259
notExists(
241-
db
260+
new QueryBuilder()
242261
.select({ userId: relayEnvironmentLinks.userId })
243262
.from(relayEnvironmentLinks)
244263
.where(
Collapse file

‎infra/relay/src/environments/EnvironmentLinker.test.ts‎

Copy file name to clipboardExpand all lines: infra/relay/src/environments/EnvironmentLinker.test.ts
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ function testLayer(input?: {
136136
revokeForEnvironmentPublicKey: () => Effect.succeed(false),
137137
}),
138138
Layer.succeed(ManagedEndpointProvider.ManagedEndpointProvider, {
139+
prepareDeprovision: () => Effect.succeed(null),
139140
deprovision: input?.deprovision ?? (() => Effect.void),
140141
release: () => Effect.succeed(true),
141142
provision: () =>
Collapse file

‎infra/relay/src/environments/ManagedEndpointAllocations.test.ts‎

Copy file name to clipboardExpand all lines: infra/relay/src/environments/ManagedEndpointAllocations.test.ts
+55Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,61 @@ const layerWithDb = (db: RelayDb.RelayDb["Service"]) =>
1010
ManagedEndpointAllocations.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, db)));
1111

1212
describe("ManagedEndpointAllocations", () => {
13+
it.effect("returns a claim generation only when deprovision wins the allocation CAS", () => {
14+
let claimedAt: string | undefined;
15+
const fakeDb = {
16+
update: (table: unknown) => {
17+
expect(table).toBe(relayManagedEndpointAllocations);
18+
return {
19+
set: (values: { readonly updatedAt: string }) => {
20+
claimedAt = values.updatedAt;
21+
return {
22+
where: () => ({
23+
returning: () => Effect.succeed([{ userId: "user-1" }]),
24+
}),
25+
};
26+
},
27+
};
28+
},
29+
} as unknown as RelayDb.RelayDb["Service"];
30+
31+
return Effect.gen(function* () {
32+
const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;
33+
const generation = yield* allocations.claimDeprovision({
34+
userId: "user-1",
35+
environmentId: "environment-1",
36+
updatedAt: "captured-generation",
37+
});
38+
39+
expect(generation).toBe(claimedAt);
40+
expect(generation).not.toBeNull();
41+
}).pipe(Effect.provide(layerWithDb(fakeDb)));
42+
});
43+
44+
it.effect("does not remove an allocation superseded after a deprovision claim", () => {
45+
const fakeDb = {
46+
delete: (table: unknown) => {
47+
expect(table).toBe(relayManagedEndpointAllocations);
48+
return {
49+
where: () => ({
50+
returning: () => Effect.succeed([]),
51+
}),
52+
};
53+
},
54+
} as unknown as RelayDb.RelayDb["Service"];
55+
56+
return Effect.gen(function* () {
57+
const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;
58+
expect(
59+
yield* allocations.removeClaimed({
60+
userId: "user-1",
61+
environmentId: "environment-1",
62+
updatedAt: "outdated-claim-generation",
63+
}),
64+
).toBe(false);
65+
}).pipe(Effect.provide(layerWithDb(fakeDb)));
66+
});
67+
1368
it.effect("retains database failures with allocation operation and identity", () => {
1469
const cause = new Error("database unavailable");
1570
const fakeDb = {
Collapse file

‎infra/relay/src/environments/ManagedEndpointAllocations.ts‎

Copy file name to clipboardExpand all lines: infra/relay/src/environments/ManagedEndpointAllocations.ts
+78Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,9 @@ export class ManagedEndpointAllocationPersistenceError extends Schema.TaggedErro
5151
"record-dns",
5252
"mark-ready",
5353
"claim-release",
54+
"claim-deprovision",
5455
"remove",
56+
"remove-claimed",
5557
]),
5658
stage: Schema.Literals(["database-request", "resolve-reservation"]),
5759
userId: Schema.String,
@@ -91,6 +93,14 @@ interface ClaimManagedEndpointReleaseInput extends ManagedEndpointAllocationKey
9193
readonly updatedAt: string;
9294
}
9395

96+
interface ClaimManagedEndpointDeprovisionInput extends ManagedEndpointAllocationKey {
97+
readonly updatedAt: string;
98+
}
99+
100+
interface RemoveClaimedManagedEndpointAllocationInput extends ManagedEndpointAllocationKey {
101+
readonly updatedAt: string;
102+
}
103+
94104
export class ManagedEndpointAllocations extends Context.Service<
95105
ManagedEndpointAllocations,
96106
{
@@ -119,9 +129,22 @@ export class ManagedEndpointAllocations extends Context.Service<
119129
readonly claimRelease: (
120130
input: ClaimManagedEndpointReleaseInput,
121131
) => 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>;
122142
readonly remove: (
123143
input: ManagedEndpointAllocationKey,
124144
) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
145+
readonly removeClaimed: (
146+
input: RemoveClaimedManagedEndpointAllocationInput,
147+
) => Effect.Effect<boolean, ManagedEndpointAllocationPersistenceError>;
125148
}
126149
>()("t3code-relay/environments/ManagedEndpointAllocations") {}
127150

@@ -321,6 +344,35 @@ export const make = Effect.gen(function* () {
321344
);
322345
return claimed;
323346
}),
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+
}),
324376
remove: Effect.fn("relay.managed_endpoint_allocations.remove")(function* (
325377
input: ManagedEndpointAllocationKey,
326378
) {
@@ -339,6 +391,32 @@ export const make = Effect.gen(function* () {
339391
),
340392
);
341393
}),
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+
}),
342420
});
343421
});
344422

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.