diff --git a/api/src/index.ts b/api/src/index.ts index 4a4bfbc..ebbb8c3 100644 --- a/api/src/index.ts +++ b/api/src/index.ts @@ -2,6 +2,7 @@ import { createApp } from './app.js'; import { config } from './config.js'; import { logger } from './lib/logger.js'; import { prisma } from './lib/prisma.js'; +import { startTmpSweeper } from './lib/uploads.js'; import { startScheduler } from './services/scheduler.js'; const app = createApp({ prisma }); @@ -9,6 +10,7 @@ const app = createApp({ prisma }); const server = app.listen(config.port, () => { logger.info({ port: config.port }, 'FitOS API started'); startScheduler(prisma); + startTmpSweeper(); }); export default app; diff --git a/api/src/lib/uploads.ts b/api/src/lib/uploads.ts index 5105c90..b70f161 100644 --- a/api/src/lib/uploads.ts +++ b/api/src/lib/uploads.ts @@ -130,3 +130,35 @@ export function removeTmpFiles(files: { path: string }[]): void { } } } + +/** Pliki młodsze niż stąd mogą być w trakcie żądania — nie sprzątamy ich. */ +const TMP_FILE_MAX_AGE_MS = 60 * 60 * 1000; + +/** + * Okresowe porządki w UPLOAD_DIR/tmp:osieroccone pliki (crash procesu w połowie + * żądania, ścieżki błędów poza obsłużonymi) nie powinny zalegać bezterminowo. + */ +export function startTmpSweeper(intervalMs = 10 * 60 * 1000): NodeJS.Timeout { + const sweep = () => { + let names: string[]; + try { + names = fs.readdirSync(tmpDir); + } catch { + return; // katalog jeszcze nie istnieje — nie ma czego sprzątać + } + const cutoff = Date.now() - TMP_FILE_MAX_AGE_MS; + for (const name of names) { + const file = path.join(tmpDir, name); + try { + const st = fs.statSync(file); + if (st.isFile() && st.mtimeMs < cutoff) fs.rmSync(file, { force: true }); + } catch (e) { + logger.warn({ err: e, path: file }, 'Failed to sweep temp upload file'); + } + } + }; + const timer = setInterval(sweep, intervalMs); + timer.unref(); + void sweep(); + return timer; +} diff --git a/api/src/routes/gyms/claims.ts b/api/src/routes/gyms/claims.ts index 5fc8920..c6e96ee 100644 --- a/api/src/routes/gyms/claims.ts +++ b/api/src/routes/gyms/claims.ts @@ -26,12 +26,16 @@ export function createGymClaimRoutes({ prisma }: AppDeps) { * 400: { description: Validation failed (fields or files) } * 404: { description: Gym not found } * 409: { description: Gym is not virtual / pending claim already exists } - */ + */ router.post( '/', (req, res, next) => claimUpload.array('files', MAX_CLAIM_FILES)(req, res, (err) => { if (err) { + // część plików mogła już trafić do tmp (np. LIMIT_FILE_SIZE w połowie) + removeTmpFiles( + ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })), + ); const message = err.code === 'LIMIT_FILE_SIZE' ? 'File too large (max 5 MB)' @@ -42,7 +46,16 @@ export function createGymClaimRoutes({ prisma }: AppDeps) { } next(); }), - validate(gymClaimSchema), + // walidacja padnie po zapisaniu plików — bez sprzątania zostałyby w tmp + (req, res, next) => + validate(gymClaimSchema)(req, res, (err) => { + if (err) { + removeTmpFiles( + ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })), + ); + } + next(err); + }), asyncHandler(async (req, res) => { try { const body = req.body as z.infer; @@ -87,7 +100,9 @@ export function createGymClaimRoutes({ prisma }: AppDeps) { }); res.status(201).json(result); } catch (e) { - removeTmpFiles(((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path }))); + removeTmpFiles( + ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })), + ); throw e; } }), @@ -101,7 +116,7 @@ export function createGymClaimRoutes({ prisma }: AppDeps) { * tags: [Gyms] * responses: * 200: { description: OK } - */ + */ router.get( '/', asyncHandler(async (req, res) => { @@ -120,7 +135,7 @@ export function createGymClaimRoutes({ prisma }: AppDeps) { * 204: { description: Withdrawn } * 403: { description: Not the claim author } * 409: { description: Claim is not pending } - */ + */ router.delete( '/:claimId', asyncHandler(async (req, res) => { diff --git a/api/src/routes/gyms/photos.ts b/api/src/routes/gyms/photos.ts index 2421e8f..c635bf3 100644 --- a/api/src/routes/gyms/photos.ts +++ b/api/src/routes/gyms/photos.ts @@ -9,7 +9,12 @@ import { setGymPhotoCover, } from '../../services/gyms.js'; import { logActivity } from '../../services/audit.js'; -import { MAX_PHOTO_FILES, gymPhotoUpload, photoUploadDir, removeTmpFiles } from '../../lib/uploads.js'; +import { + MAX_PHOTO_FILES, + gymPhotoUpload, + photoUploadDir, + removeTmpFiles, +} from '../../lib/uploads.js'; import { badRequest, forbidden, notFound } from '../../lib/errors.js'; import { asyncHandler } from '../../lib/asyncHandler.js'; @@ -31,12 +36,16 @@ export function createGymPhotoRoutes({ prisma }: AppDeps) { * 403: { description: Not the gym owner and not an admin } * 404: { description: Gym not found } * 409: { description: Gym is not REAL } - */ + */ router.post( '/', (req, res, next) => gymPhotoUpload.array('photos', MAX_PHOTO_FILES)(req, res, (err) => { if (err) { + // część zdjęć mogła już trafić do tmp (np. LIMIT_FILE_SIZE w połowie) + removeTmpFiles( + ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })), + ); const message = err.code === 'LIMIT_FILE_SIZE' ? 'File too large (max 5 MB)' @@ -55,13 +64,7 @@ export function createGymPhotoRoutes({ prisma }: AppDeps) { sizeBytes: f.size, path: f.path, })); - const result = await addGymPhotos( - prisma, - req.user!.id, - req.user!.isAdmin, - gymId, - files, - ); + const result = await addGymPhotos(prisma, req.user!.id, req.user!.isAdmin, gymId, files); await logActivity(prisma, { actorId: req.user!.id, action: 'gym.photos.added', @@ -71,7 +74,9 @@ export function createGymPhotoRoutes({ prisma }: AppDeps) { }); res.json(result); } catch (e) { - removeTmpFiles(((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path }))); + removeTmpFiles( + ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })), + ); throw e; } }), @@ -87,18 +92,12 @@ export function createGymPhotoRoutes({ prisma }: AppDeps) { * 200: { description: OK, returns { gym } } * 403: { description: Not the gym owner and not an admin } * 404: { description: Photo not found } - */ + */ router.delete( '/:photoId', asyncHandler(async (req, res) => { const { gymId, photoId } = req.params as GymParams & { photoId: string }; - const result = await deleteGymPhoto( - prisma, - req.user!.id, - req.user!.isAdmin, - gymId, - photoId, - ); + const result = await deleteGymPhoto(prisma, req.user!.id, req.user!.isAdmin, gymId, photoId); await logActivity(prisma, { actorId: req.user!.id, action: 'gym.photo.deleted', @@ -120,7 +119,7 @@ export function createGymPhotoRoutes({ prisma }: AppDeps) { * 200: { description: OK, returns { gym } } * 403: { description: Not the gym owner and not an admin } * 404: { description: Photo not found } - */ + */ router.patch( '/:photoId/cover', asyncHandler(async (req, res) => { @@ -153,7 +152,7 @@ export function createGymPhotoRoutes({ prisma }: AppDeps) { * 200: { description: Image bytes with the stored Content-Type } * 403: { description: VIRTUAL gym and the caller is not a manager } * 404: { description: Photo not found or file missing } - */ + */ router.get( '/:photoId', asyncHandler(async (req, res) => { @@ -162,7 +161,10 @@ export function createGymPhotoRoutes({ prisma }: AppDeps) { if (!photo || photo.gymId !== gymId) throw notFound('Photo not found'); const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { kind: true } }); if (!gym) throw notFound('Gym not found'); - if (gym.kind !== 'REAL' && !(await canManageGym(prisma, gymId, req.user!.id, req.user!.isAdmin))) + if ( + gym.kind !== 'REAL' && + !(await canManageGym(prisma, gymId, req.user!.id, req.user!.isAdmin)) + ) throw forbidden('You do not have access to this gym'); const filePath = path.join(photoUploadDir(gymId), photo.storedName); if (!fs.existsSync(filePath)) throw notFound('Photo file not found');