fix(integrations): serialize refresh and cursor writes

This commit is contained in:
Marc-André Bombeck committed 2026-07-20 12:09:32 +02:00
1 parent a8ac376cf7
commit 5d784a639c
6 files changed
+590 -167

No files matched your search

+31
View File
@@ -1,3 +1,5 @@
import type { Prisma } from "@/generated/prisma/client";
/**
* Shared OAuth rotating-refresh-token persistence helper.
*
@@ -58,3 +60,32 @@ export async function persistRotatedToken(
// rather than parking the connection at reauth.
return opts.readPeerAccessToken();
}
export type SerializedRefreshProvider = "whoop" | "withings";
/**
* Provider refreshes hold a database transaction open around one bounded
* external request. `maxWait` bounds pool acquisition and `timeout` bounds the
* advisory-lock wait, provider call, and durable token replacement together.
*/
export const PROVIDER_REFRESH_TRANSACTION_OPTIONS = {
maxWait: 10_000,
timeout: 60_000,
} as const;
/**
* Serialize one provider/user refresh attempt for the transaction lifetime.
* Callers must re-read token state after this returns: a prior contender may
* have committed a fresh token while this transaction waited for the lock.
*/
export async function acquireProviderTokenRefreshLock(
tx: Pick<Prisma.TransactionClient, "$queryRaw">,
provider: SerializedRefreshProvider,
userId: string,
): Promise<void> {
const key = `provider-token-refresh:${provider}:${userId}`;
await tx.$queryRaw`
SELECT 1 AS locked
FROM pg_advisory_xact_lock(hashtextextended(${key}, 0))
`;
}