From 68d06fed7c1f74181c745f60aaf3aefd97e93256 Mon Sep 17 00:00:00 2001 From: tisachi Date: Sun, 11 Oct 2026 17:56:32 +0200 Subject: [PATCH] Sesje: modyfikacje i zakonczenie pod blokada wiersza (SELECT FOR UPDATE) + straz statusu w makerzu 24h (eliminacja wyscigow) --- api/src/services/scheduler.ts | 4 +- api/src/services/sessions.ts | 147 +++++++++++++++--------- api/test/unit/scheduler.test.ts | 3 +- api/test/unit/services-sessions.test.ts | 18 +++ 4 files changed, 117 insertions(+), 55 deletions(-) diff --git a/api/src/services/scheduler.ts b/api/src/services/scheduler.ts index 3390298..b03ffa0 100644 --- a/api/src/services/scheduler.ts +++ b/api/src/services/scheduler.ts @@ -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 — diff --git a/api/src/services/sessions.ts b/api/src/services/sessions.ts index 29506de..2b27e53 100644 --- a/api/src/services/sessions.ts +++ b/api/src/services/sessions.ts @@ -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( + prisma: PrismaClient, + sessionId: string, + fn: (tx: Prisma.TransactionClient) => Promise, +): Promise { + 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 }, diff --git a/api/test/unit/scheduler.test.ts b/api/test/unit/scheduler.test.ts index d4ebe96..a7ed796 100644 --- a/api/test/unit/scheduler.test.ts +++ b/api/test/unit/scheduler.test.ts @@ -65,7 +65,8 @@ describe('scheduler', () => { select: { id: true, dayId: true }, }); expect(sessionUpdateMany).toHaveBeenCalledWith({ - where: { id: { in: ['s1', 's2'] } }, + // warunek status w where: nie nadpisze sesji zakończonej w międzyczasie + where: { id: { in: ['s1', 's2'] }, status: 'IN_PROGRESS' }, data: { status: 'ABANDONED', endedAt: expect.any(Date) }, }); // dzień porzuconej sesji nie może zostać ponownie wykonany (jak przy ręcznym abandon), diff --git a/api/test/unit/services-sessions.test.ts b/api/test/unit/services-sessions.test.ts index d9b4879..0fb7633 100644 --- a/api/test/unit/services-sessions.test.ts +++ b/api/test/unit/services-sessions.test.ts @@ -48,6 +48,11 @@ function mockPrisma() { return prisma; } +/** Wiersz sesji widoczny dla blokady SELECT ... FOR UPDATE w inSessionTransaction. */ +function mockSessionRow(prisma: any, status: 'IN_PROGRESS' | 'COMPLETED' | 'ABANDONED') { + prisma.trainingSession.findUnique.mockResolvedValue({ id: 's1', status }); +} + const ownedDay = { id: 'd1', status: 'PLANNED', @@ -387,6 +392,7 @@ describe('updateExercise', () => { planExerciseId: null, session: { id: 's1', status: 'IN_PROGRESS', day: { week: { plan: { userId: 'u1' } } } }, }); + mockSessionRow(prisma, 'IN_PROGRESS'); prisma.sessionExercise.update.mockResolvedValue({ id: 'se1' }); await expect(updateExercise(prisma, 'se1', 'u1', { removed: true })).resolves.toEqual({ ok: true, @@ -404,6 +410,7 @@ describe('updateExercise', () => { planExerciseId: 'pe1', session: { id: 's1', status: 'IN_PROGRESS', day: { week: { plan: { userId: 'u1' } } } }, }); + mockSessionRow(prisma, 'IN_PROGRESS'); prisma.sessionExercise.update.mockResolvedValue({ id: 'se1' }); await expect(updateExercise(prisma, 'se1', 'u1', { hidden: true })).resolves.toEqual({ ok: true, @@ -423,6 +430,7 @@ describe('addSet', () => { it('400 when the session is not in progress', async () => { const prisma = mockPrisma(); + mockSessionRow(prisma, 'COMPLETED'); prisma.sessionExercise.findUnique.mockResolvedValue({ ...ownedExercise, session: { id: 's1', status: 'COMPLETED', day: { week: { plan: { userId: 'u1' } } } }, @@ -435,7 +443,9 @@ describe('addSet', () => { it('400 when planned (norm) sets are still pending', async () => { const prisma = mockPrisma(); + mockSessionRow(prisma, 'IN_PROGRESS'); prisma.sessionExercise.findUnique.mockResolvedValue(ownedExercise); + prisma.sessionSet.findMany.mockResolvedValue([ { id: 'st1', planSetId: 'ps1', reps: 10, removed: false }, { id: 'st2', planSetId: 'ps2', reps: null, removed: false }, @@ -448,7 +458,9 @@ describe('addSet', () => { it('400 when an extra set is already in progress', async () => { const prisma = mockPrisma(); + mockSessionRow(prisma, 'IN_PROGRESS'); prisma.sessionExercise.findUnique.mockResolvedValue(ownedExercise); + prisma.sessionSet.findMany.mockResolvedValue([ { id: 'st1', planSetId: 'ps1', reps: 10, removed: false }, { id: 'st2', planSetId: null, reps: null, removed: false }, @@ -461,7 +473,9 @@ describe('addSet', () => { it('adds an extra set when all norm sets are done and no extra is pending', async () => { const prisma = mockPrisma(); + mockSessionRow(prisma, 'IN_PROGRESS'); prisma.sessionExercise.findUnique.mockResolvedValue(ownedExercise); + prisma.sessionSet.findMany.mockResolvedValue([ { id: 'st1', planSetId: 'ps1', reps: 10, removed: false }, { id: 'st2', planSetId: null, reps: 8, removed: false }, @@ -516,6 +530,7 @@ describe('deleteSet', () => { it('400 when the session is not in progress', async () => { const prisma = mockPrisma(); + mockSessionRow(prisma, 'COMPLETED'); prisma.sessionSet.findUnique.mockResolvedValue({ ...ownedSet, exercise: { @@ -530,7 +545,9 @@ describe('deleteSet', () => { it('soft-removes an extra set', async () => { const prisma = mockPrisma(); + mockSessionRow(prisma, 'IN_PROGRESS'); prisma.sessionSet.findUnique.mockResolvedValue(ownedSet); + prisma.sessionSet.update.mockResolvedValue({ id: 'st1', removed: true }); const result = await deleteSet(prisma, 'st1', 'u1'); @@ -546,6 +563,7 @@ describe('deleteSet', () => { describe('addExercise', () => { it('appends after the highest existing order', async () => { const prisma = mockPrisma(); + mockSessionRow(prisma, 'IN_PROGRESS'); prisma.trainingSession.findUnique.mockResolvedValue({ id: 's1', status: 'IN_PROGRESS',