fix: fix deadlock

This commit is contained in:
Steve Korshakov 2025-07-24 22:21:18 -07:00
parent e07e79ae2f
commit 2f853017ee

View File

@ -918,6 +918,15 @@ export async function startApi(): Promise<{ app: FastifyInstance; io: Server }>
// Start transaction to ensure consistency
const result = await db.$transaction(async (tx) => {
// Get user for update (lock account first to prevent deadlocks)
const user = await tx.account.findUnique({
where: { id: userId }
});
if (!user) {
throw new Error('User not found');
}
// Verify session belongs to user and lock it
const session = await tx.session.findFirst({
where: {
@ -930,15 +939,6 @@ export async function startApi(): Promise<{ app: FastifyInstance; io: Server }>
throw new Error('Session not found');
}
// Get user for update
const user = await tx.account.findUnique({
where: { id: userId }
});
if (!user) {
throw new Error('User not found');
}
// Get next sequence numbers
const msgSeq = session.seq + 1;
const updSeq = user.seq + 1;
@ -1038,6 +1038,15 @@ export async function startApi(): Promise<{ app: FastifyInstance; io: Server }>
// Start transaction to ensure consistency
const result = await db.$transaction(async (tx) => {
// Get user for update (lock account first to prevent deadlocks)
const user = await tx.account.findUnique({
where: { id: userId }
});
if (!user) {
callback({ result: 'error' });
return null;
}
// Verify session belongs to user and lock it
const session = await tx.session.findFirst({
where: {
@ -1045,10 +1054,7 @@ export async function startApi(): Promise<{ app: FastifyInstance; io: Server }>
accountId: userId
}
});
const user = await tx.account.findUnique({
where: { id: userId }
});
if (!user || !session) {
if (!session) {
callback({ result: 'error' });
return null;
}
@ -1128,6 +1134,15 @@ export async function startApi(): Promise<{ app: FastifyInstance; io: Server }>
// Start transaction to ensure consistency
const result = await db.$transaction(async (tx) => {
// Get user for update (lock account first to prevent deadlocks)
const user = await tx.account.findUnique({
where: { id: userId }
});
if (!user) {
callback({ result: 'error' });
return null;
}
// Verify session belongs to user and lock it
const session = await tx.session.findFirst({
where: {
@ -1135,10 +1150,7 @@ export async function startApi(): Promise<{ app: FastifyInstance; io: Server }>
accountId: userId
}
});
const user = await tx.account.findUnique({
where: { id: userId }
});
if (!user || !session) {
if (!session) {
callback({ result: 'error' });
return null;
}