diff --git a/infra/relay/src/db.ts b/infra/relay/src/db.ts index 3b43e820e1..e1f1e6d281 100644 --- a/infra/relay/src/db.ts +++ b/infra/relay/src/db.ts @@ -24,35 +24,33 @@ function withEnvironmentLock( input: { readonly userId: string; readonly environmentId: string }, effect: Effect.Effect, ): Effect.Effect { - return Effect.scoped( + // A blocking advisory lock lets waiters occupy the whole pool. Each waiter + // instead tries inside a short transaction, releasing its connection before + // retrying. The winning transaction pins all protected database work to the + // lock-owning connection and releases the lock automatically on completion. + const attempt = db.$client.withTransaction( Effect.gen(function* () { - const connection = yield* db.$client.reserve; - const lockParams = [input.userId, input.environmentId] as const; - yield* connection.executeUnprepared( - "SELECT pg_advisory_lock(hashtext($1), hashtext($2))", - lockParams, - undefined, - ); - return yield* effect.pipe( - Effect.ensuring( - connection - .executeUnprepared( - "SELECT pg_advisory_unlock(hashtext($1), hashtext($2))", - lockParams, - undefined, - ) - .pipe( - Effect.catch((error: SqlError) => - Effect.logWarning("failed to release relay environment lock", { - ...input, - error, - }), - ), - ), - ), + const rows = yield* db.$client.unsafe<{ readonly locked: boolean }>( + "SELECT pg_try_advisory_xact_lock(hashtext($1), hashtext($2)) AS locked", + [input.userId, input.environmentId], ); + if (rows[0]?.locked !== true) { + return { acquired: false } as const; + } + // Preserve provider checkpoints on domain failures by committing their + // Result. SQL failures still abort the transaction at the driver level. + return { acquired: true, result: yield* Effect.result(effect) } as const; }), ); + const acquire = (): Effect.Effect => + attempt.pipe( + Effect.flatMap((outcome) => + outcome.acquired + ? Effect.fromResult(outcome.result) + : Effect.sleep("50 millis").pipe(Effect.andThen(Effect.suspend(acquire))), + ), + ); + return Effect.suspend(acquire); } export class RelayTransactions extends Context.Service< diff --git a/infra/relay/src/http/Api.test.ts b/infra/relay/src/http/Api.test.ts index 8923932e85..beacaffeab 100644 --- a/infra/relay/src/http/Api.test.ts +++ b/infra/relay/src/http/Api.test.ts @@ -285,8 +285,8 @@ describe("relay environment unlink", () => { "transaction", "link", "credential", - "deprovision", "unlock", + "deprovision", ]); }).pipe( Effect.provide( diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts index 9b6600303d..e13f862292 100644 --- a/infra/relay/src/http/Api.ts +++ b/infra/relay/src/http/Api.ts @@ -437,7 +437,7 @@ export const unlinkEnvironmentRecord = Effect.fn("relay.api.client.unlinkEnviron const transactions = yield* RelayDb.RelayTransactions; const links = yield* EnvironmentLinks.EnvironmentLinks; const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider; - return yield* transactions.withEnvironmentLock( + const { deprovisionTarget, unlinked } = yield* transactions.withEnvironmentLock( input, Effect.gen(function* () { const deprovisionTarget = yield* managedEndpointProvider.prepareDeprovision(input); @@ -450,18 +450,17 @@ export const unlinkEnvironmentRecord = Effect.fn("relay.api.client.unlinkEnviron environmentId: link.environmentId, environmentPublicKey: link.environmentPublicKey, }); - - // External teardown cannot share the SQL transaction. Run it only after - // revocation commits so a database failure leaves a fully usable active - // link. Still run teardown when the link is already revoked, allowing a - // retry to finish cleanup after an earlier Cloudflare failure. - yield* managedEndpointProvider.deprovision({ - ...input, - target: deprovisionTarget, - }); - return unlinked; + return { deprovisionTarget, unlinked }; }), ); + // External teardown runs after revocation commits and releases the lock. + // Its captured allocation generation keeps a concurrent relink safe while + // still allowing a retry to finish an earlier incomplete cleanup. + yield* managedEndpointProvider.deprovision({ + ...input, + target: deprovisionTarget, + }); + return unlinked; }, );