Sesje: modyfikacje i zakonczenie pod blokada wiersza (SELECT FOR UPDATE) + straz statusu w makerzu 24h (eliminacja wyscigow)
This commit is contained in:
@@ -37,8 +37,10 @@ export function startScheduler(prisma: PrismaClient): void {
|
||||
select: { id: true, dayId: true },
|
||||
});
|
||||
if (stale.length > 0) {
|
||||
// status w warunku: sesja mogła zostać ukończona między findMany a
|
||||
// updateMany — COMPLETED/ABANDONED nie może zostać nadpisane.
|
||||
await prisma.trainingSession.updateMany({
|
||||
where: { id: { in: stale.map((s) => s.id) } },
|
||||
where: { id: { in: stale.map((s) => s.id) }, status: 'IN_PROGRESS' },
|
||||
data: { status: 'ABANDONED', endedAt: now },
|
||||
});
|
||||
// Porzucona sesja nie może pozwalać na ponowne wykonanie dnia —
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
import type { Prisma, PrismaClient } from '@prisma/client';
|
||||
import { badRequest, conflict, notFound } from '../lib/errors.js';
|
||||
|
||||
export interface UpdateExerciseInput {
|
||||
@@ -32,6 +32,30 @@ async function getExerciseOwned(prisma: PrismaClient, exerciseId: string, userId
|
||||
return exercise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wszystkie modyfikacje i zakończenie sesji serializujemy na wierszu sesji
|
||||
* (SELECT ... FOR UPDATE), więc sprawdzenie statusu IN_PROGRESS i kontrola
|
||||
* „wszystkie serie planowe zapisane" przy ukończeniu są wolne od wyścigu —
|
||||
* równoległe nadpisanie serii przez klienta nie może przejść między kontrolę
|
||||
* a zapis COMPLETED.
|
||||
*/
|
||||
async function inSessionTransaction<T>(
|
||||
prisma: PrismaClient,
|
||||
sessionId: string,
|
||||
fn: (tx: Prisma.TransactionClient) => Promise<T>,
|
||||
): Promise<T> {
|
||||
return prisma.$transaction(async (tx) => {
|
||||
await tx.$executeRaw`SELECT id FROM "TrainingSession" WHERE id = ${sessionId} FOR UPDATE`;
|
||||
const s = await tx.trainingSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
select: { status: true },
|
||||
});
|
||||
if (!s) throw notFound('Session not found');
|
||||
if (s.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
|
||||
return fn(tx);
|
||||
});
|
||||
}
|
||||
|
||||
export async function startSession(prisma: PrismaClient, dayId: string, userId: string) {
|
||||
const day = await prisma.planDay.findUnique({
|
||||
where: { id: dayId },
|
||||
@@ -178,16 +202,20 @@ export async function addExercise(
|
||||
if (session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
|
||||
const template = await prisma.exercise.findUnique({ where: { id: exerciseId } });
|
||||
if (!template) throw notFound('Exercise not found');
|
||||
const maxOrder = await prisma.sessionExercise.aggregate({
|
||||
where: { sessionId: session.id },
|
||||
_max: { order: true },
|
||||
});
|
||||
const exercise = await prisma.sessionExercise.create({
|
||||
data: {
|
||||
sessionId: session.id,
|
||||
exerciseId: template.id,
|
||||
order: (maxOrder._max.order ?? -1) + 1,
|
||||
},
|
||||
// Kolejność i kontrola statusu pod blokadą sesji — dwa równoległe dodania
|
||||
// nie mogą trafić na ten sam `order` (unikalny indeks w bazie dałby 500).
|
||||
const exercise = await inSessionTransaction(prisma, sessionId, async (tx) => {
|
||||
const maxOrder = await tx.sessionExercise.aggregate({
|
||||
where: { sessionId },
|
||||
_max: { order: true },
|
||||
});
|
||||
return tx.sessionExercise.create({
|
||||
data: {
|
||||
sessionId,
|
||||
exerciseId: template.id,
|
||||
order: (maxOrder._max.order ?? -1) + 1,
|
||||
},
|
||||
});
|
||||
});
|
||||
return { exerciseId: exercise.id, order: exercise.order };
|
||||
}
|
||||
@@ -199,16 +227,14 @@ export async function updateExercise(
|
||||
data: UpdateExerciseInput,
|
||||
) {
|
||||
const exercise = await getExerciseOwned(prisma, exerciseId, userId);
|
||||
if (exercise.session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
|
||||
// Ćwiczenie z planu można ukryć, ale nie usunąć — usuwanie nie może „wybaczać"
|
||||
// nieodpisanych serii planowych; kasować wolno tylko ćwiczenia dodane do sesji.
|
||||
if (data.removed === true && exercise.planExerciseId != null) {
|
||||
throw badRequest('Only exercises added to the session can be removed');
|
||||
}
|
||||
await prisma.sessionExercise.update({
|
||||
where: { id: exercise.id },
|
||||
data,
|
||||
});
|
||||
await inSessionTransaction(prisma, exercise.sessionId, (tx) =>
|
||||
tx.sessionExercise.update({ where: { id: exercise.id }, data }),
|
||||
);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
@@ -219,21 +245,24 @@ export async function updateExercise(
|
||||
*/
|
||||
export async function addSet(prisma: PrismaClient, exerciseId: string, userId: string) {
|
||||
const exercise = await getExerciseOwned(prisma, exerciseId, userId);
|
||||
if (exercise.session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
|
||||
const sets = await prisma.sessionSet.findMany({
|
||||
where: { exercise: { sessionId: exercise.session.id }, removed: false },
|
||||
});
|
||||
const pendingNorm = sets.filter((s) => s.planSetId != null && s.reps == null).length;
|
||||
if (pendingNorm > 0)
|
||||
throw badRequest('All planned sets must be recorded before adding an extra set');
|
||||
const pendingExtra = sets.filter((s) => s.planSetId == null && s.reps == null).length;
|
||||
if (pendingExtra > 0) throw badRequest('An extra set is already in progress');
|
||||
const maxIndex = await prisma.sessionSet.aggregate({
|
||||
where: { exerciseId: exercise.id },
|
||||
_max: { index: true },
|
||||
});
|
||||
const set = await prisma.sessionSet.create({
|
||||
data: { exerciseId: exercise.id, index: (maxIndex._max.index ?? -1) + 1 },
|
||||
// Cała kontrola + wstawienie pod blokadą sesji: dwa równoległe żądania nie mogą
|
||||
// przejść obiecyjnie warunku „brak serii dodatkowej w toku".
|
||||
const set = await inSessionTransaction(prisma, exercise.sessionId, async (tx) => {
|
||||
const sets = await tx.sessionSet.findMany({
|
||||
where: { exercise: { sessionId: exercise.sessionId }, removed: false },
|
||||
});
|
||||
const pendingNorm = sets.filter((s) => s.planSetId != null && s.reps == null).length;
|
||||
if (pendingNorm > 0)
|
||||
throw badRequest('All planned sets must be recorded before adding an extra set');
|
||||
const pendingExtra = sets.filter((s) => s.planSetId == null && s.reps == null).length;
|
||||
if (pendingExtra > 0) throw badRequest('An extra set is already in progress');
|
||||
const maxIndex = await tx.sessionSet.aggregate({
|
||||
where: { exerciseId: exercise.id },
|
||||
_max: { index: true },
|
||||
});
|
||||
return tx.sessionSet.create({
|
||||
data: { exerciseId: exercise.id, index: (maxIndex._max.index ?? -1) + 1 },
|
||||
});
|
||||
});
|
||||
return { setId: set.id, index: set.index };
|
||||
}
|
||||
@@ -255,11 +284,10 @@ export async function updateSet(
|
||||
},
|
||||
});
|
||||
if (!set || set.exercise.session.day.week.plan.userId !== userId) throw notFound('Set not found');
|
||||
if (set.exercise.session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
|
||||
const updated = await prisma.sessionSet.update({
|
||||
where: { id: set.id },
|
||||
data,
|
||||
});
|
||||
// status + zapis pod blokadą sesji (patrz inSessionTransaction)
|
||||
const updated = await inSessionTransaction(prisma, set.exercise.sessionId, (tx) =>
|
||||
tx.sessionSet.update({ where: { id: set.id }, data }),
|
||||
);
|
||||
return { set: updated };
|
||||
}
|
||||
|
||||
@@ -280,31 +308,43 @@ export async function deleteSet(prisma: PrismaClient, setId: string, userId: str
|
||||
});
|
||||
if (!set || set.exercise.session.day.week.plan.userId !== userId) throw notFound('Set not found');
|
||||
if (set.planSetId != null) throw badRequest('Only extra sets can be removed');
|
||||
if (set.exercise.session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
|
||||
await prisma.sessionSet.update({ where: { id: set.id }, data: { removed: true } });
|
||||
await inSessionTransaction(prisma, set.exercise.sessionId, (tx) =>
|
||||
tx.sessionSet.update({ where: { id: set.id }, data: { removed: true } }),
|
||||
);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export async function completeSession(prisma: PrismaClient, sessionId: string, userId: string) {
|
||||
const session = await getSessionOwned(prisma, sessionId, userId);
|
||||
// Szybka ścieżka dla czytelnego 400; rozstrzygnięcie pod blokadą w transakcji.
|
||||
if (session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
|
||||
const exercises = await prisma.sessionExercise.findMany({
|
||||
where: { sessionId: session.id, removed: false },
|
||||
include: { sets: true },
|
||||
});
|
||||
// Only planned (norm) sets must be recorded; extra sets are a bonus and don't block.
|
||||
const pending = exercises.reduce(
|
||||
(n, e) => n + e.sets.filter((s) => !s.removed && s.planSetId != null && s.reps == null).length,
|
||||
0,
|
||||
);
|
||||
if (pending > 0)
|
||||
throw badRequest(
|
||||
`All planned sets must be recorded before completing the session (${pending} remaining)`,
|
||||
);
|
||||
const now = new Date();
|
||||
// Atomowe zamknięcie sesji i dnia: dzień można oznaczyć jako wykonany tylko gdy
|
||||
// wciąż jest zaplanowany — wygasły (SKIPPED) nie może „ożyć" jako COMPLETED.
|
||||
// Atomowe zamknięcie sesji i dnia: kontrola „wszystkie serie planowe zapisane"
|
||||
// musi nastąpić PO zablokowaniu wiersza sesji — inaczej równoległe
|
||||
// wyczyszczenie serii (updateSet) weszłoby między kontrolę a COMPLETED.
|
||||
// Dzień można oznaczyć jako wykonany tylko gdy wciąż jest zaplanowany —
|
||||
// wygasły (SKIPPED) nie może „ożyć" jako COMPLETED.
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.$executeRaw`SELECT id FROM "TrainingSession" WHERE id = ${session.id} FOR UPDATE`;
|
||||
const s0 = await tx.trainingSession.findUnique({
|
||||
where: { id: session.id },
|
||||
select: { status: true },
|
||||
});
|
||||
if (!s0 || s0.status !== 'IN_PROGRESS') throw conflict('Session is no longer in progress');
|
||||
const exercises = await tx.sessionExercise.findMany({
|
||||
where: { sessionId: session.id, removed: false },
|
||||
include: { sets: true },
|
||||
});
|
||||
// Only planned (norm) sets must be recorded; extra sets are a bonus and don't block.
|
||||
const pending = exercises.reduce(
|
||||
(n, e) =>
|
||||
n + e.sets.filter((s) => !s.removed && s.planSetId != null && s.reps == null).length,
|
||||
0,
|
||||
);
|
||||
if (pending > 0)
|
||||
throw badRequest(
|
||||
`All planned sets must be recorded before completing the session (${pending} remaining)`,
|
||||
);
|
||||
const s = await tx.trainingSession.updateMany({
|
||||
where: { id: session.id, status: 'IN_PROGRESS' },
|
||||
data: { status: 'COMPLETED', endedAt: now },
|
||||
@@ -331,6 +371,7 @@ export async function abandonSession(prisma: PrismaClient, sessionId: string, us
|
||||
// PLANNED i da się go wykonać normalnie; SKIPPED tylko dla dni, które nadszedł czas.
|
||||
const startOfTomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.$executeRaw`SELECT id FROM "TrainingSession" WHERE id = ${session.id} FOR UPDATE`;
|
||||
const s = await tx.trainingSession.updateMany({
|
||||
where: { id: session.id, status: 'IN_PROGRESS' },
|
||||
data: { status: 'ABANDONED', endedAt: now },
|
||||
|
||||
Reference in New Issue
Block a user