-
Notifications
You must be signed in to change notification settings - Fork 212
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6960369
commit 68ee779
Showing
3 changed files
with
138 additions
and
128 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,32 +1,43 @@ | ||
import prisma, { getPGInstance } from '@briefer/database' | ||
import { logger } from './logger.js' | ||
import { z } from 'zod' | ||
|
||
export async function acquireLock<T>( | ||
name: string, | ||
cb: () => Promise<T> | ||
): Promise<T> { | ||
const { pool } = await getPGInstance() | ||
|
||
const lock = await prisma().lock2.upsert({ | ||
where: { | ||
name, | ||
}, | ||
update: {}, | ||
create: { name }, | ||
}) | ||
let lockId = BigInt(-1) | ||
while (true) { | ||
try { | ||
const lock = await prisma().lock2.upsert({ | ||
where: { | ||
name, | ||
}, | ||
update: {}, | ||
create: { name }, | ||
}) | ||
lockId = lock.id | ||
|
||
try { | ||
// acquire lock | ||
logger().trace({ name, id: lock.id }, 'Acquiring lock') | ||
await pool.query('SELECT pg_advisory_lock($1)', [lock.id]) | ||
logger().trace({ name, id: lock.id }, 'Lock acquired') | ||
// acquire lock | ||
logger().trace({ name, id: lock.id }, 'Acquiring lock') | ||
await pool.query('SELECT pg_advisory_lock($1)', [lock.id]) | ||
logger().trace({ name, id: lock.id }, 'Lock acquired') | ||
|
||
// run callback | ||
return await cb() | ||
} finally { | ||
// release lock | ||
logger().trace({ name, id: lock.id }, 'Releasing lock') | ||
await pool.query('SELECT pg_advisory_unlock($1)', [lock.id]) | ||
logger().trace({ name, id: lock.id }, 'Lock released') | ||
// run callback | ||
return await cb() | ||
} catch (err) { | ||
if (z.object({ code: z.literal('P2002') }).safeParse(err).success) { | ||
continue | ||
} | ||
|
||
throw err | ||
} finally { | ||
// release lock | ||
logger().trace({ name, id: lockId }, 'Releasing lock') | ||
await pool.query('SELECT pg_advisory_unlock($1)', [lockId]) | ||
logger().trace({ name, id: lockId }, 'Lock released') | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters