CognxSafeTrack Claude Sonnet 4.6 commited on
Commit Β·
2859b85
1
Parent(s): ec9b5da
fix: batch scheduler updates, typed JWT user, log catch blocks, move script
Browse files- scheduler.ts: collect completed enrollment IDs in loop, single updateMany
after β eliminates N queries per day for completions
- ContentHandler.ts: log Redis cache failures instead of swallowing silently
- index.ts: remove (request as any).user cast β now safe via FastifyJWT
augmentation in types/fastify.d.ts
- types/fastify.d.ts: augment @fastify/jwt FastifyJWT interface so request.user
resolves to {id, role, organizationId} after jwtVerify(), not string|object|Buffer
- delete-user.ts: moved from apps/api root to apps/api/scripts/
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Files changed (5)
79 unmodified lines8081828384858679 unmodified lines}// Multi-Tenant Enforcementconst user = request.user as any;const requestedOrgId = request.headers['x-organization-id'] as string;if (user && user.role !== 'SUPER_ADMIN') {79 unmodified lines8081828384858679 unmodified lines}// Multi-Tenant Enforcementconst user = request.user;const requestedOrgId = request.headers['x-organization-id'] as string;if (user && user.role !== 'SUPER_ADMIN') {
123456789101112131415import { PrismaClient } from '@repo/database';declare module 'fastify' {interface FastifyInstance {prisma: PrismaClient;}interface FastifyRequest {user: {id: string;role: string;organizationId: string;};organizationId?: string;rawBody?: Buffer;}1234567891011121314151617181920import { PrismaClient } from '@repo/database';import '@fastify/multipart';// Tell @fastify/jwt what shape our JWT payload has.// This makes request.user properly typed after jwtVerify().declare module '@fastify/jwt' {interface FastifyJWT {payload: { id: string; role: string; organizationId: string };user: { id: string; role: string; organizationId: string };}}declare module 'fastify' {interface FastifyInstance {prisma: PrismaClient;}interface FastifyRequest {organizationId?: string;rawBody?: Buffer;}
16 unmodified lines1718192021222316 unmodified linestry {const cached = await connection.get(cacheKey);if (cached) return JSON.parse(cached);} catch (err) {}const org = await prisma.organization.findUnique({where: { id: organizationId },16 unmodified lines17181920212223242516 unmodified linestry {const cached = await connection.get(cacheKey);if (cached) return JSON.parse(cached);} catch (err) {logger.warn({ err, organizationId }, '[ContentHandler] Redis cache lookup failed');}const org = await prisma.organization.findUnique({where: { id: organizationId },
40 unmodified lines414243444546474849505152536 unmodified lines6061626364656667686970717273747576777879802 unmodified lines83848586878840 unmodified lines}});for (const enrollment of activeEnrollments) {// Find progress for this specific trackconst progress = enrollment.user.progress.find(p => p.trackId === enrollment.trackId);if (progress?.exerciseStatus === 'PENDING') {const lastInteraction = progress.lastInteraction;const hoursSinceLast = (Date.now() - new Date(lastInteraction).getTime()) / (1000 * 60 * 60);if (hoursSinceLast >= 72) {logger.info(`[SCHEDULER] Queuing RESURRECTION nudge for User ${enrollment.userId}`);6 unmodified lines}const nextDay = enrollment.currentDay + 1;// ββ Check the next day content exists in memory ββββββββββββββββββββββββββconst nextDayContent = enrollment.track.days.find(d => d.dayNumber === nextDay);if (!nextDayContent) {// No more content β mark enrollment COMPLETEDlogger.info(`[SCHEDULER] No Day ${nextDay} for Track ${enrollment.trackId} β marking COMPLETED`);await prisma.enrollment.update({where: { id: enrollment.id },data: { status: 'COMPLETED', completedAt: new Date() }});continue;}// ββ Queue the next lesson βββββββββββββββββββββββββββββββββββββawait whatsappQueue.add('send-content', {userId: enrollment.userId,trackId: enrollment.trackId,2 unmodified lineslogger.info(`[SCHEDULER] Queued Day ${nextDay} for User ${enrollment.userId}`);}} catch (error) {logger.error('[SCHEDULER] Error:', error);}40 unmodified lines41424344454647484950515253546 unmodified lines6162636465666768697071727374752 unmodified lines78798081828384858687888990919240 unmodified lines}});const completedIds: string[] = [];for (const enrollment of activeEnrollments) {// Find progress for this specific track (in-memory, no extra query)const progress = enrollment.user.progress.find(p => p.trackId === enrollment.trackId);if (progress?.exerciseStatus === 'PENDING') {const hoursSinceLast = (Date.now() - new Date(progress.lastInteraction).getTime()) / (1000 * 60 * 60);if (hoursSinceLast >= 72) {logger.info(`[SCHEDULER] Queuing RESURRECTION nudge for User ${enrollment.userId}`);6 unmodified lines}const nextDay = enrollment.currentDay + 1;const nextDayContent = enrollment.track.days.find(d => d.dayNumber === nextDay);if (!nextDayContent) {// Collect for batch update instead of N individual querieslogger.info(`[SCHEDULER] No Day ${nextDay} for Track ${enrollment.trackId} β marking COMPLETED`);completedIds.push(enrollment.id);continue;}await whatsappQueue.add('send-content', {userId: enrollment.userId,trackId: enrollment.trackId,2 unmodified lineslogger.info(`[SCHEDULER] Queued Day ${nextDay} for User ${enrollment.userId}`);}// Single batch update instead of one query per completed enrollmentif (completedIds.length > 0) {await prisma.enrollment.updateMany({where: { id: { in: completedIds } },data: { status: 'COMPLETED', completedAt: new Date() }});logger.info(`[SCHEDULER] Marked ${completedIds.length} enrollment(s) as COMPLETED`);}} catch (error) {logger.error('[SCHEDULER] Error:', error);}
apps/api/delete-user.ts β apps/api/scripts/delete-user.tsRenamed
apps/api/src/index.ts+1-1
apps/api/src/types/fastify.d.ts+10-5
apps/whatsapp-worker/src/handlers/ContentHandler.ts+3-1
apps/whatsapp-worker/src/scheduler.ts+15-11