@studious-lms/server 1.4.9 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/dist/index.js +15 -3
  2. package/dist/index.js.map +1 -1
  3. package/dist/lib/config/cors.d.ts.map +1 -1
  4. package/dist/lib/config/cors.js +2 -3
  5. package/dist/lib/config/cors.js.map +1 -1
  6. package/dist/lib/fileUpload.d.ts.map +1 -1
  7. package/dist/lib/fileUpload.js +4 -5
  8. package/dist/lib/fileUpload.js.map +1 -1
  9. package/dist/lib/pusher.d.ts +7 -1
  10. package/dist/lib/pusher.d.ts.map +1 -1
  11. package/dist/lib/pusher.js +9 -3
  12. package/dist/lib/pusher.js.map +1 -1
  13. package/dist/models/attendance.d.ts +16 -7
  14. package/dist/models/attendance.d.ts.map +1 -1
  15. package/dist/models/attendance.js +17 -2
  16. package/dist/models/attendance.js.map +1 -1
  17. package/dist/models/auth.d.ts +1 -0
  18. package/dist/models/auth.d.ts.map +1 -1
  19. package/dist/models/auth.js +3 -2
  20. package/dist/models/auth.js.map +1 -1
  21. package/dist/models/comment.d.ts +0 -5
  22. package/dist/models/comment.d.ts.map +1 -1
  23. package/dist/models/conversation.d.ts +17 -16
  24. package/dist/models/conversation.d.ts.map +1 -1
  25. package/dist/models/labChat.d.ts +2 -1
  26. package/dist/models/labChat.d.ts.map +1 -1
  27. package/dist/models/message.d.ts +6 -3
  28. package/dist/models/message.d.ts.map +1 -1
  29. package/dist/models/school.d.ts +0 -22
  30. package/dist/models/school.d.ts.map +1 -1
  31. package/dist/models/school.js +2 -14
  32. package/dist/models/school.js.map +1 -1
  33. package/dist/models/worksheet.d.ts +76 -19
  34. package/dist/models/worksheet.d.ts.map +1 -1
  35. package/dist/models/worksheet.js +2 -2
  36. package/dist/models/worksheet.js.map +1 -1
  37. package/dist/pipelines/aiLabChat.d.ts +20 -9
  38. package/dist/pipelines/aiLabChat.d.ts.map +1 -1
  39. package/dist/pipelines/aiLabChat.js +63 -75
  40. package/dist/pipelines/aiLabChat.js.map +1 -1
  41. package/dist/pipelines/aiNewtonChat.d.ts +13 -4
  42. package/dist/pipelines/aiNewtonChat.d.ts.map +1 -1
  43. package/dist/pipelines/aiNewtonChat.js +39 -27
  44. package/dist/pipelines/aiNewtonChat.js.map +1 -1
  45. package/dist/pipelines/gradeWorksheet.d.ts +5 -3
  46. package/dist/pipelines/gradeWorksheet.d.ts.map +1 -1
  47. package/dist/pipelines/gradeWorksheet.js +60 -24
  48. package/dist/pipelines/gradeWorksheet.js.map +1 -1
  49. package/dist/pipelines/pdfToWorksheet.d.ts +34 -2
  50. package/dist/pipelines/pdfToWorksheet.d.ts.map +1 -1
  51. package/dist/pipelines/pdfToWorksheet.js +205 -32
  52. package/dist/pipelines/pdfToWorksheet.js.map +1 -1
  53. package/dist/routers/_app.d.ts +106 -48
  54. package/dist/routers/_app.d.ts.map +1 -1
  55. package/dist/routers/announcement.d.ts +0 -4
  56. package/dist/routers/announcement.d.ts.map +1 -1
  57. package/dist/routers/assignment.d.ts +0 -8
  58. package/dist/routers/assignment.d.ts.map +1 -1
  59. package/dist/routers/assignment.js +64 -4
  60. package/dist/routers/assignment.js.map +1 -1
  61. package/dist/routers/auth.d.ts +1 -0
  62. package/dist/routers/auth.d.ts.map +1 -1
  63. package/dist/routers/comment.d.ts +0 -3
  64. package/dist/routers/comment.d.ts.map +1 -1
  65. package/dist/routers/conversation.d.ts +2 -1
  66. package/dist/routers/conversation.d.ts.map +1 -1
  67. package/dist/routers/labChat.d.ts +3 -1
  68. package/dist/routers/labChat.d.ts.map +1 -1
  69. package/dist/routers/message.d.ts +3 -0
  70. package/dist/routers/message.d.ts.map +1 -1
  71. package/dist/routers/newtonChat.d.ts +1 -0
  72. package/dist/routers/newtonChat.d.ts.map +1 -1
  73. package/dist/routers/school.d.ts +6 -0
  74. package/dist/routers/school.d.ts.map +1 -1
  75. package/dist/routers/school.js +7 -2
  76. package/dist/routers/school.js.map +1 -1
  77. package/dist/routers/worksheet.d.ts +37 -7
  78. package/dist/routers/worksheet.d.ts.map +1 -1
  79. package/dist/routers/worksheet.js +16 -6
  80. package/dist/routers/worksheet.js.map +1 -1
  81. package/dist/services/announcement.js +4 -4
  82. package/dist/services/announcement.js.map +1 -1
  83. package/dist/services/assignment.d.ts.map +1 -1
  84. package/dist/services/assignment.js +16 -6
  85. package/dist/services/assignment.js.map +1 -1
  86. package/dist/services/attendance.d.ts.map +1 -1
  87. package/dist/services/attendance.js +68 -4
  88. package/dist/services/attendance.js.map +1 -1
  89. package/dist/services/auth.d.ts +1 -0
  90. package/dist/services/auth.d.ts.map +1 -1
  91. package/dist/services/comment.d.ts +0 -3
  92. package/dist/services/comment.d.ts.map +1 -1
  93. package/dist/services/conversation.d.ts +2 -1
  94. package/dist/services/conversation.d.ts.map +1 -1
  95. package/dist/services/labChat.d.ts +10 -2
  96. package/dist/services/labChat.d.ts.map +1 -1
  97. package/dist/services/labChat.js +103 -44
  98. package/dist/services/labChat.js.map +1 -1
  99. package/dist/services/message.d.ts +3 -0
  100. package/dist/services/message.d.ts.map +1 -1
  101. package/dist/services/message.js +20 -2
  102. package/dist/services/message.js.map +1 -1
  103. package/dist/services/newtonChat.d.ts +1 -0
  104. package/dist/services/newtonChat.d.ts.map +1 -1
  105. package/dist/services/newtonChat.js +40 -17
  106. package/dist/services/newtonChat.js.map +1 -1
  107. package/dist/services/school.d.ts +6 -0
  108. package/dist/services/school.d.ts.map +1 -1
  109. package/dist/services/school.js +71 -6
  110. package/dist/services/school.js.map +1 -1
  111. package/dist/services/worksheet.d.ts +48 -11
  112. package/dist/services/worksheet.d.ts.map +1 -1
  113. package/dist/services/worksheet.js +73 -29
  114. package/dist/services/worksheet.js.map +1 -1
  115. package/dist/utils/generateUsername.d.ts +8 -0
  116. package/dist/utils/generateUsername.d.ts.map +1 -0
  117. package/dist/utils/generateUsername.js +103 -0
  118. package/dist/utils/generateUsername.js.map +1 -0
  119. package/dist/utils/inference.d.ts +50 -1
  120. package/dist/utils/inference.d.ts.map +1 -1
  121. package/dist/utils/inference.js +167 -2
  122. package/dist/utils/inference.js.map +1 -1
  123. package/dist/workers/connection.d.ts +3 -0
  124. package/dist/workers/connection.d.ts.map +1 -0
  125. package/dist/workers/connection.js +33 -0
  126. package/dist/workers/connection.js.map +1 -0
  127. package/dist/workers/index.d.ts +10 -0
  128. package/dist/workers/index.d.ts.map +1 -0
  129. package/dist/workers/index.js +63 -0
  130. package/dist/workers/index.js.map +1 -0
  131. package/dist/workers/processors/aiLabChat.d.ts +7 -0
  132. package/dist/workers/processors/aiLabChat.d.ts.map +1 -0
  133. package/dist/workers/processors/aiLabChat.js +52 -0
  134. package/dist/workers/processors/aiLabChat.js.map +1 -0
  135. package/dist/workers/processors/aiNewtonChat.d.ts +7 -0
  136. package/dist/workers/processors/aiNewtonChat.d.ts.map +1 -0
  137. package/dist/workers/processors/aiNewtonChat.js +57 -0
  138. package/dist/workers/processors/aiNewtonChat.js.map +1 -0
  139. package/dist/workers/processors/createRunJobWorker.d.ts +46 -0
  140. package/dist/workers/processors/createRunJobWorker.d.ts.map +1 -0
  141. package/dist/workers/processors/createRunJobWorker.js +118 -0
  142. package/dist/workers/processors/createRunJobWorker.js.map +1 -0
  143. package/dist/workers/processors/gradeWorksheet.d.ts +6 -0
  144. package/dist/workers/processors/gradeWorksheet.d.ts.map +1 -0
  145. package/dist/workers/processors/gradeWorksheet.js +19 -0
  146. package/dist/workers/processors/gradeWorksheet.js.map +1 -0
  147. package/dist/workers/processors/pdfToWorksheet.d.ts +8 -0
  148. package/dist/workers/processors/pdfToWorksheet.d.ts.map +1 -0
  149. package/dist/workers/processors/pdfToWorksheet.js +20 -0
  150. package/dist/workers/processors/pdfToWorksheet.js.map +1 -0
  151. package/dist/workers/processors/studentProgressChat.d.ts +8 -0
  152. package/dist/workers/processors/studentProgressChat.d.ts.map +1 -0
  153. package/dist/workers/processors/studentProgressChat.js +27 -0
  154. package/dist/workers/processors/studentProgressChat.js.map +1 -0
  155. package/dist/workers/queues.d.ts +85 -0
  156. package/dist/workers/queues.d.ts.map +1 -0
  157. package/dist/workers/queues.js +119 -0
  158. package/dist/workers/queues.js.map +1 -0
  159. package/package.json +6 -3
  160. package/prisma/migrations/20260506162500_consolidate_run_job_and_unify_job_status/migration.sql +166 -0
  161. package/prisma/schema.prisma +465 -387
  162. package/src/index.ts +12 -1
  163. package/src/lib/config/cors.ts +0 -1
  164. package/src/lib/fileUpload.ts +2 -4
  165. package/src/lib/pusher.ts +7 -1
  166. package/src/models/attendance.ts +15 -0
  167. package/src/models/auth.ts +1 -0
  168. package/src/models/school.ts +0 -14
  169. package/src/models/worksheet.ts +2 -2
  170. package/src/pipelines/aiLabChat.ts +71 -79
  171. package/src/pipelines/aiNewtonChat.ts +47 -31
  172. package/src/pipelines/gradeWorksheet.ts +63 -25
  173. package/src/pipelines/pdfToWorksheet.ts +272 -34
  174. package/src/routers/assignment.ts +74 -3
  175. package/src/routers/school.ts +5 -0
  176. package/src/routers/worksheet.ts +25 -4
  177. package/src/services/announcement.ts +2 -2
  178. package/src/services/assignment.ts +18 -4
  179. package/src/services/attendance.ts +87 -2
  180. package/src/services/labChat.ts +108 -48
  181. package/src/services/message.ts +19 -0
  182. package/src/services/newtonChat.ts +46 -25
  183. package/src/services/school.ts +89 -6
  184. package/src/services/worksheet.ts +87 -28
  185. package/src/utils/generateUsername.ts +108 -0
  186. package/src/utils/inference.ts +209 -1
  187. package/src/workers/connection.ts +37 -0
  188. package/src/workers/index.ts +71 -0
  189. package/src/workers/processors/aiLabChat.ts +65 -0
  190. package/src/workers/processors/aiNewtonChat.ts +75 -0
  191. package/src/workers/processors/createRunJobWorker.ts +164 -0
  192. package/src/workers/processors/gradeWorksheet.ts +16 -0
  193. package/src/workers/processors/pdfToWorksheet.ts +17 -0
  194. package/src/workers/processors/studentProgressChat.ts +28 -0
  195. package/src/workers/queues.ts +174 -0
  196. package/tests/{globalSetup.ts → integration/globalSetup.ts} +4 -4
  197. package/tests/{helpers.ts → integration/helpers.ts} +2 -2
  198. package/tests/{pipelines → integration/pipelines}/pdfToWorksheet.test.ts +55 -43
  199. package/tests/{routers → integration/routers}/attendance.test.ts +61 -2
  200. package/tests/{routers → integration/routers}/auth.test.ts +3 -3
  201. package/tests/{routers → integration/routers}/class.test.ts +3 -17
  202. package/tests/{routers → integration/routers}/conversation.test.ts +1 -1
  203. package/tests/{routers → integration/routers}/event.test.ts +1 -1
  204. package/tests/{routers → integration/routers}/message.test.ts +1 -1
  205. package/tests/{routers → integration/routers}/newtonChat.test.ts +1 -1
  206. package/tests/{routers → integration/routers}/studentProgress.test.ts +1 -1
  207. package/tests/{user.test.ts → integration/routers/user.test.ts} +2 -2
  208. package/tests/integration/routers/worksheet.test.ts +448 -0
  209. package/tests/{setup.ts → integration/setup.ts} +4 -4
  210. package/tests/{lib → unit/lib}/cors.test.ts +1 -1
  211. package/tests/{middleware → unit/middleware}/security.test.ts +1 -1
  212. package/tests/{pipelines → unit/pipelines}/aiLabChat.test.ts +1 -1
  213. package/tests/{lib → unit/pipelines}/aiLabChatContract.test.ts +1 -1
  214. package/tests/{utils/aiLabChatPrompt.test.ts → unit/pipelines/labChatPrompt.test.ts} +2 -2
  215. package/tests/{utils → unit/services}/studentProgress.test.ts +5 -5
  216. package/tests/{utils → unit/utils}/aiUser.test.ts +1 -1
  217. package/tests/{utils → unit/utils}/generateInviteCode.test.ts +1 -1
  218. package/tests/{utils → unit/utils}/inference.test.ts +6 -6
  219. package/tests/{utils → unit/utils}/logger.test.ts +1 -1
  220. package/tests/{utils → unit/utils}/prismaErrorHandler.test.ts +1 -1
  221. package/tests/{utils → unit/utils}/prismaWrapper.test.ts +1 -1
  222. package/vitest.config.ts +11 -3
  223. package/vitest.unit.config.ts +10 -10
  224. package/tests/routers/worksheet.test.ts +0 -194
  225. package/tests/startup.test.ts +0 -5
  226. package/tests/worksheet.test.ts +0 -181
  227. /package/tests/{routers → integration/routers}/agenda.test.ts +0 -0
  228. /package/tests/{routers → integration/routers}/announcement.test.ts +0 -0
  229. /package/tests/{routers → integration/routers}/assignment.test.ts +0 -0
  230. /package/tests/{routers → integration/routers}/comment.test.ts +0 -0
  231. /package/tests/{routers → integration/routers}/folder.test.ts +0 -0
  232. /package/tests/{routers → integration/routers}/labChat.test.ts +0 -0
  233. /package/tests/{routers → integration/routers}/marketing.test.ts +0 -0
  234. /package/tests/{routers → integration/routers}/notification.test.ts +0 -0
  235. /package/tests/{routers → integration/routers}/search.test.ts +0 -0
  236. /package/tests/{routers → integration/routers}/section.test.ts +0 -0
  237. /package/tests/{server → unit/middleware}/rateLimit.test.ts +0 -0
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Worker process entrypoint.
3
+ *
4
+ * Run separately from the HTTP server (e.g. `node dist/workers/index.js` on
5
+ * Render/Railway/Fly). Importing this file boots every BullMQ Worker
6
+ * declared under `src/workers/processors/*`. Do NOT import this from the
7
+ * HTTP server — that would spin up workers in your serverless functions.
8
+ */
9
+ import '../instrument.js';
10
+
11
+ import { Worker } from 'bullmq';
12
+ import { prisma } from '../lib/prisma.js';
13
+ import { logger } from '../utils/logger.js';
14
+ import { bullConnection } from './connection.js';
15
+ import { aiLabChatWorker } from './processors/aiLabChat.js';
16
+ import { aiNewtonChatWorker } from './processors/aiNewtonChat.js';
17
+ import { gradeWorksheetWorker } from './processors/gradeWorksheet.js';
18
+ import { pdfToWorksheetWorker } from './processors/pdfToWorksheet.js';
19
+ import { studentProgressChatWorker } from './processors/studentProgressChat.js';
20
+
21
+ const workers: Worker<any>[] = [
22
+ pdfToWorksheetWorker,
23
+ gradeWorksheetWorker,
24
+ aiLabChatWorker,
25
+ aiNewtonChatWorker,
26
+ studentProgressChatWorker,
27
+ ];
28
+
29
+ logger.info('Workers ready', {
30
+ pid: process.pid,
31
+ queues: workers.map((w) => w.name),
32
+ });
33
+
34
+ let shuttingDown = false;
35
+
36
+ async function shutdown(signal: string): Promise<void> {
37
+ if (shuttingDown) return;
38
+ shuttingDown = true;
39
+
40
+ logger.info(`Received ${signal}, draining workers...`);
41
+
42
+ // `worker.close()` waits for in-flight jobs to finish (up to the worker's
43
+ // settings) before resolving. Run them in parallel.
44
+ await Promise.allSettled(workers.map((w) => w.close()));
45
+
46
+ await Promise.allSettled([
47
+ bullConnection.quit(),
48
+ prisma.$disconnect(),
49
+ ]);
50
+
51
+ logger.info('Workers shut down cleanly');
52
+ process.exit(0);
53
+ }
54
+
55
+ process.on('SIGTERM', () => void shutdown('SIGTERM'));
56
+ process.on('SIGINT', () => void shutdown('SIGINT'));
57
+
58
+ process.on('uncaughtException', (error) => {
59
+ logger.error('Uncaught exception in worker process', {
60
+ error: error.message,
61
+ stack: error.stack,
62
+ });
63
+ process.exit(1);
64
+ });
65
+
66
+ process.on('unhandledRejection', (reason) => {
67
+ logger.error('Unhandled rejection in worker process', {
68
+ reason: reason instanceof Error ? reason.message : String(reason),
69
+ });
70
+ process.exit(1);
71
+ });
@@ -0,0 +1,65 @@
1
+ import {
2
+ generateAndSendLabIntroduction,
3
+ generateAndSendLabResponse,
4
+ } from '../../pipelines/aiLabChat.js';
5
+ import { prisma } from '../../lib/prisma.js';
6
+ import { isAIUser } from '../../utils/aiUser.js';
7
+ import { createRunJobWorker } from './createRunJobWorker.js';
8
+
9
+ export const aiLabChatWorker = createRunJobWorker({
10
+ type: 'AI_LAB_CHAT',
11
+ workerOptions: {
12
+ // Lab responses can produce PDFs and large schemas; cap concurrency to
13
+ // keep memory under control and to honour upstream model rate limits.
14
+ concurrency: 1,
15
+ limiter: { max: 5, duration: 60_000 },
16
+ },
17
+ run: async ({ conversationId, aiMessageId }) => {
18
+ const labChat = await prisma.labChat.findFirst({
19
+ where: { conversationId },
20
+ select: {
21
+ id: true,
22
+ classId: true,
23
+ context: true,
24
+ class: { select: { subject: true } },
25
+ },
26
+ });
27
+
28
+ if (!labChat) {
29
+ throw new Error(
30
+ `LabChat for conversationId=${conversationId} not found`,
31
+ );
32
+ }
33
+
34
+ // The AI message is a placeholder we created before enqueue; the
35
+ // pipeline fills it in. Look up the most recent non-AI message in the
36
+ // conversation to feed the response generator. If none exists, this is
37
+ // the introductory message at the top of a brand-new lab chat.
38
+ const triggeringMessage = await prisma.message.findFirst({
39
+ where: {
40
+ conversationId,
41
+ senderId: { not: 'AI_ASSISTANT' },
42
+ },
43
+ orderBy: { createdAt: 'desc' },
44
+ select: { id: true, content: true, senderId: true },
45
+ });
46
+
47
+ if (!triggeringMessage || isAIUser(triggeringMessage.senderId)) {
48
+ await generateAndSendLabIntroduction(
49
+ labChat.id,
50
+ conversationId,
51
+ labChat.context,
52
+ labChat.class?.subject || 'Lab',
53
+ aiMessageId,
54
+ );
55
+ return { labChatId: labChat.id, kind: 'introduction', aiMessageId };
56
+ }
57
+
58
+ await generateAndSendLabResponse(labChat.id, triggeringMessage.content, {
59
+ classId: labChat.classId,
60
+ aiMessageId,
61
+ });
62
+
63
+ return { labChatId: labChat.id, aiMessageId };
64
+ },
65
+ });
@@ -0,0 +1,75 @@
1
+ import {
2
+ generateAndSendNewtonIntroduction,
3
+ generateAndSendNewtonResponse,
4
+ } from '../../pipelines/aiNewtonChat.js';
5
+ import { prisma } from '../../lib/prisma.js';
6
+ import { isAIUser } from '../../utils/aiUser.js';
7
+ import { createRunJobWorker } from './createRunJobWorker.js';
8
+
9
+ export const aiNewtonChatWorker = createRunJobWorker({
10
+ type: 'AI_NEWTON_CHAT',
11
+ workerOptions: {
12
+ concurrency: 2,
13
+ limiter: { max: 10, duration: 60_000 },
14
+ },
15
+ run: async ({ conversationId, aiMessageId }) => {
16
+ const newtonChat = await prisma.newtonChat.findFirst({
17
+ where: { conversationId },
18
+ select: {
19
+ id: true,
20
+ submission: {
21
+ select: {
22
+ id: true,
23
+ assignment: {
24
+ select: {
25
+ id: true,
26
+ title: true,
27
+ instructions: true,
28
+ class: { select: { subject: true } },
29
+ },
30
+ },
31
+ },
32
+ },
33
+ },
34
+ });
35
+
36
+ if (!newtonChat) {
37
+ throw new Error(
38
+ `NewtonChat for conversationId=${conversationId} not found`,
39
+ );
40
+ }
41
+
42
+ // Resolve the triggering student message (if any). On a brand-new
43
+ // tutor session there are no student messages yet, so we run the
44
+ // introduction path; otherwise we run the response path against the
45
+ // most recent non-AI message.
46
+ const triggeringMessage = await prisma.message.findFirst({
47
+ where: {
48
+ conversationId,
49
+ senderId: { not: 'AI_ASSISTANT' },
50
+ },
51
+ orderBy: { createdAt: 'desc' },
52
+ select: { id: true, content: true, senderId: true },
53
+ });
54
+
55
+ if (!triggeringMessage || isAIUser(triggeringMessage.senderId)) {
56
+ await generateAndSendNewtonIntroduction(
57
+ newtonChat.id,
58
+ conversationId,
59
+ newtonChat.submission.id,
60
+ aiMessageId,
61
+ );
62
+ return { newtonChatId: newtonChat.id, kind: 'introduction', aiMessageId };
63
+ }
64
+
65
+ await generateAndSendNewtonResponse(
66
+ newtonChat.id,
67
+ triggeringMessage.content,
68
+ conversationId,
69
+ newtonChat.submission,
70
+ aiMessageId,
71
+ );
72
+
73
+ return { newtonChatId: newtonChat.id, aiMessageId };
74
+ },
75
+ });
@@ -0,0 +1,164 @@
1
+ /**
2
+ * `createRunJobWorker` — shared factory for every BullMQ processor in this app.
3
+ *
4
+ * Wraps the boilerplate that every RunJob-backed worker needs:
5
+ * - Idempotent skip if the RunJob already SUCCEEDED (recovery after a crash
6
+ * that lost the BullMQ ack).
7
+ * - Status transitions: PENDING/RUNNING → RUNNING (with attempts++) → SUCCEEDED.
8
+ * - Failure handling: record latest error every attempt, flip to FAILED only
9
+ * on the final retry.
10
+ * - Standardised structured logging on `error` / `failed` / `completed`.
11
+ *
12
+ * A processor implementation only has to provide its `RunJobType`, optional
13
+ * BullMQ options (concurrency, limiter, etc.), and a `run` callback that does
14
+ * the actual work. The callback receives the typed `JobInputs[type]` payload
15
+ * and a context object with `runJobId`, `bullJobId`, `attempt`, plus the
16
+ * `userId` / `classId` from the original `enqueueRunJob` call.
17
+ */
18
+ import { Worker, type Job, type WorkerOptions } from 'bullmq';
19
+ import { Prisma, type RunJobType } from '@prisma/client';
20
+ import { bullConnection } from '../connection.js';
21
+ import { prisma } from '../../lib/prisma.js';
22
+ import { logger } from '../../utils/logger.js';
23
+ import { QUEUE_NAMES, type JobInputs } from '../queues.js';
24
+
25
+ export interface RunJobContext {
26
+ runJobId: string;
27
+ bullJobId: string | undefined;
28
+ /** 1-indexed attempt number of the current run. */
29
+ attempt: number;
30
+ /** From `EnqueueOptions.userId` on the producer side. */
31
+ userId: string | null;
32
+ /** From `EnqueueOptions.classId` on the producer side. */
33
+ classId: string | null;
34
+ }
35
+
36
+ export interface CreateRunJobWorkerOptions<T extends RunJobType> {
37
+ type: T;
38
+ /** BullMQ `WorkerOptions` minus `connection`, which is supplied by the helper. */
39
+ workerOptions?: Omit<WorkerOptions, 'connection'>;
40
+ /**
41
+ * The actual work. Return any JSON-serialisable value (or `null`) — it gets
42
+ * persisted to `RunJob.result` for the client to read back.
43
+ */
44
+ run: (
45
+ input: JobInputs[T],
46
+ ctx: RunJobContext,
47
+ ) => Promise<Prisma.InputJsonValue | null>;
48
+ }
49
+
50
+ type WorkerData<T extends RunJobType> = JobInputs[T] & { runJobId: string };
51
+
52
+ export function createRunJobWorker<T extends RunJobType>({
53
+ type,
54
+ workerOptions,
55
+ run,
56
+ }: CreateRunJobWorkerOptions<T>): Worker<WorkerData<T>> {
57
+ const name = QUEUE_NAMES[type];
58
+
59
+ const worker = new Worker<WorkerData<T>>(
60
+ name,
61
+ async (job: Job<WorkerData<T>>) => {
62
+ const { runJobId, ...rest } = job.data;
63
+ // The destructured rest is `Omit<JobInputs[T] & { runJobId }, 'runJobId'>`,
64
+ // which TS can't simplify back to `JobInputs[T]` while `T` is generic.
65
+ const input = rest as unknown as JobInputs[T];
66
+
67
+ const existing = await prisma.runJob.findUnique({
68
+ where: { id: runJobId },
69
+ select: { status: true, result: true, userId: true, classId: true },
70
+ });
71
+
72
+ if (existing?.status === 'SUCCEEDED') {
73
+ logger.info(`${name} RunJob already succeeded; skipping re-run`, {
74
+ runJobId,
75
+ bullJobId: job.id,
76
+ });
77
+ return existing.result;
78
+ }
79
+
80
+ await prisma.runJob.update({
81
+ where: { id: runJobId },
82
+ data: {
83
+ status: 'RUNNING',
84
+ startedAt: existing?.status === 'RUNNING' ? undefined : new Date(),
85
+ attempts: { increment: 1 },
86
+ },
87
+ });
88
+
89
+ const result = await run(input, {
90
+ runJobId,
91
+ bullJobId: job.id,
92
+ attempt: job.attemptsMade + 1,
93
+ userId: existing?.userId ?? null,
94
+ classId: existing?.classId ?? null,
95
+ });
96
+
97
+ await prisma.runJob.update({
98
+ where: { id: runJobId },
99
+ data: {
100
+ status: 'SUCCEEDED',
101
+ finishedAt: new Date(),
102
+ error: null,
103
+ result: result === null ? Prisma.JsonNull : result,
104
+ },
105
+ });
106
+
107
+ return result;
108
+ },
109
+ { connection: bullConnection, ...workerOptions },
110
+ );
111
+
112
+ worker.on('error', (err) => {
113
+ logger.error(`${name} worker error`, {
114
+ error: err.message,
115
+ stack: err.stack,
116
+ });
117
+ });
118
+
119
+ worker.on('failed', async (job, err) => {
120
+ if (!job) return;
121
+
122
+ const runJobId = job.data?.runJobId;
123
+ const isFinalAttempt = job.attemptsMade >= (job.opts.attempts ?? 1);
124
+
125
+ logger.error(`${name} job failed`, {
126
+ bullJobId: job.id,
127
+ runJobId,
128
+ attempt: job.attemptsMade,
129
+ finalAttempt: isFinalAttempt,
130
+ error: err.message,
131
+ });
132
+
133
+ if (!runJobId) return;
134
+
135
+ await prisma.runJob
136
+ .update({
137
+ where: { id: runJobId },
138
+ data: {
139
+ error: err.message,
140
+ ...(isFinalAttempt
141
+ ? { status: 'FAILED', finishedAt: new Date() }
142
+ : {}),
143
+ },
144
+ })
145
+ .catch((updateError) => {
146
+ logger.error(`Failed to record ${name} failure on RunJob`, {
147
+ runJobId,
148
+ error:
149
+ updateError instanceof Error
150
+ ? updateError.message
151
+ : String(updateError),
152
+ });
153
+ });
154
+ });
155
+
156
+ worker.on('completed', (job) => {
157
+ logger.info(`${name} job completed`, {
158
+ bullJobId: job.id,
159
+ runJobId: job.data?.runJobId,
160
+ });
161
+ });
162
+
163
+ return worker;
164
+ }
@@ -0,0 +1,16 @@
1
+ import { gradeWorksheetPipeline } from '../../pipelines/gradeWorksheet.js';
2
+ import { createRunJobWorker } from './createRunJobWorker.js';
3
+
4
+ export const gradeWorksheetWorker = createRunJobWorker({
5
+ type: 'GRADE_WORKSHEET',
6
+ workerOptions: {
7
+ concurrency: 2,
8
+ // Each pipeline run can fan out to many per-question inferences; keep
9
+ // throughput modest until we measure real-world usage.
10
+ limiter: { max: 5, duration: 60_000 },
11
+ },
12
+ run: async ({ worksheetResponseId }) => {
13
+ await gradeWorksheetPipeline(worksheetResponseId);
14
+ return { worksheetResponseId };
15
+ },
16
+ });
@@ -0,0 +1,17 @@
1
+ import { pdfToWorksheet } from '../../pipelines/pdfToWorksheet.js';
2
+ import { createRunJobWorker } from './createRunJobWorker.js';
3
+
4
+ export const pdfToWorksheetWorker = createRunJobWorker({
5
+ type: 'PDF_TO_WORKSHEET',
6
+ workerOptions: {
7
+ concurrency: 2,
8
+ // 5 jobs / minute, e.g. to stay under OpenAI rate limits.
9
+ limiter: { max: 5, duration: 60_000 },
10
+ },
11
+ run: async ({ gcsUrl, classId, worksheetId }) => {
12
+ const worksheet = await pdfToWorksheet(gcsUrl, classId, { worksheetId });
13
+ return worksheet
14
+ ? { worksheetId: worksheet.id, name: worksheet.name }
15
+ : null;
16
+ },
17
+ });
@@ -0,0 +1,28 @@
1
+ import { chatAboutStudentProgress } from '../../services/studentProgress.js';
2
+ import { createRunJobWorker } from './createRunJobWorker.js';
3
+
4
+ export const studentProgressChatWorker = createRunJobWorker({
5
+ type: 'STUDENT_PROGRESS_CHAT',
6
+ workerOptions: {
7
+ concurrency: 4,
8
+ limiter: { max: 20, duration: 60_000 },
9
+ },
10
+ run: async ({ classId, studentId, message }, ctx) => {
11
+ // `chatAboutStudentProgress` runs an authorization check using the viewer
12
+ // id, so callers MUST pass `userId` via `enqueueRunJob` options for the
13
+ // service to receive it here.
14
+ if (!ctx.userId) {
15
+ throw new Error(
16
+ 'STUDENT_PROGRESS_CHAT requires `userId` on the RunJob (set via enqueueRunJob options)',
17
+ );
18
+ }
19
+
20
+ const response = await chatAboutStudentProgress(ctx.userId, {
21
+ classId,
22
+ studentId,
23
+ message,
24
+ });
25
+
26
+ return response;
27
+ },
28
+ });
@@ -0,0 +1,174 @@
1
+ /**
2
+ * BullMQ queue producers and the `enqueueRunJob` helper.
3
+ *
4
+ * Producer side only — safe to import from HTTP routes / services running on
5
+ * Vercel. Importing this file does NOT start any workers; workers live in
6
+ * `src/workers/processors/*` and are wired up by `src/workers/index.ts`,
7
+ * which is the entrypoint of the separate long-running worker process.
8
+ */
9
+ import { Queue, type JobsOptions } from 'bullmq';
10
+ import { Prisma, type RunJobType } from '@prisma/client';
11
+ import { bullConnection } from './connection.js';
12
+ import { prisma } from '../lib/prisma.js';
13
+ import { logger } from '../utils/logger.js';
14
+
15
+ const DEFAULT_JOB_OPTIONS: JobsOptions = {
16
+ attempts: 3,
17
+ backoff: { type: 'exponential', delay: 5_000 },
18
+ removeOnComplete: { age: 60 * 60 }, // keep completed jobs in Redis for 1h, then drop
19
+ removeOnFail: { age: 24 * 60 * 60 }, // keep failed jobs for 24h for inspection
20
+ };
21
+
22
+ /**
23
+ * Map RunJobType → (queue name, input payload shape).
24
+ *
25
+ * Add a new entry here whenever you introduce a new background job type.
26
+ * The queue name string must match what the corresponding processor passes
27
+ * to `new Worker(<name>, ...)`.
28
+ */
29
+ export type JobInputs = {
30
+ /**
31
+ * `worksheetId` is the placeholder Worksheet row created synchronously by
32
+ * the producer (so the client has an id to navigate to). The pipeline fills
33
+ * that row in asynchronously and broadcasts progress on the per-worksheet
34
+ * job channel.
35
+ */
36
+ PDF_TO_WORKSHEET: { gcsUrl: string; classId: string; worksheetId: string };
37
+ GRADE_WORKSHEET: { worksheetResponseId: string };
38
+ /**
39
+ * `aiMessageId` is the placeholder AI Message row created synchronously by
40
+ * the producer before enqueue (so the client renders a PENDING bubble in
41
+ * the timeline). The pipeline fills in the content and flips the row to
42
+ * COMPLETED / FAILED. Used for both intros and replies — single shape.
43
+ */
44
+ AI_LAB_CHAT: { conversationId: string; aiMessageId: string };
45
+ /**
46
+ * `aiMessageId` placeholder pattern, same as AI_LAB_CHAT — see above.
47
+ */
48
+ AI_NEWTON_CHAT: { conversationId: string; aiMessageId: string };
49
+ STUDENT_PROGRESS_CHAT: { classId: string; studentId: string; message: string };
50
+ };
51
+
52
+ export const QUEUE_NAMES: Record<RunJobType, string> = {
53
+ PDF_TO_WORKSHEET: 'pdfToWorksheet',
54
+ GRADE_WORKSHEET: 'gradeWorksheet',
55
+ AI_LAB_CHAT: 'aiLabChat',
56
+ AI_NEWTON_CHAT: 'aiNewtonChat',
57
+ STUDENT_PROGRESS_CHAT: 'studentProgressChat',
58
+ };
59
+
60
+ /**
61
+ * One Queue instance per type. Created lazily so that importing this module
62
+ * does not eagerly open queues you may never use in a given runtime.
63
+ */
64
+ const queueCache = new Map<RunJobType, Queue>();
65
+
66
+ function getQueue(type: RunJobType): Queue {
67
+ let queue = queueCache.get(type);
68
+ if (!queue) {
69
+ queue = new Queue(QUEUE_NAMES[type], {
70
+ connection: bullConnection,
71
+ defaultJobOptions: DEFAULT_JOB_OPTIONS,
72
+ });
73
+ queueCache.set(type, queue);
74
+ }
75
+ return queue;
76
+ }
77
+
78
+ export interface EnqueueOptions {
79
+ classId?: string | null;
80
+ userId?: string | null;
81
+ /** Override BullMQ job options (attempts, delay, priority, etc.). */
82
+ jobOptions?: JobsOptions;
83
+ }
84
+
85
+ export interface EnqueueResult {
86
+ runJobId: string;
87
+ bullJobId: string | null;
88
+ }
89
+
90
+ /**
91
+ * Create a `RunJob` audit row, enqueue the BullMQ job, and link the two.
92
+ *
93
+ * Returns immediately — the actual work happens on the worker process. The
94
+ * caller can return `runJobId` to the client and have them poll `getRunJob`
95
+ * (or subscribe over Pusher) to track progress.
96
+ *
97
+ * IMPORTANT: do not call this inside a Prisma `$transaction`. If the outer
98
+ * transaction rolls back after the BullMQ job is added, the worker will pick
99
+ * up an orphaned job pointing at a non-existent RunJob row. Enqueue *after*
100
+ * the transaction commits.
101
+ */
102
+ export async function enqueueRunJob<T extends RunJobType>(
103
+ type: T,
104
+ input: JobInputs[T],
105
+ options: EnqueueOptions = {},
106
+ ): Promise<EnqueueResult> {
107
+ const runJob = await prisma.runJob.create({
108
+ data: {
109
+ type,
110
+ status: 'PENDING',
111
+ classId: options.classId ?? null,
112
+ userId: options.userId ?? null,
113
+ input: input as unknown as Prisma.InputJsonValue,
114
+ },
115
+ });
116
+
117
+ try {
118
+ const queue = getQueue(type);
119
+ const job = await queue.add(
120
+ QUEUE_NAMES[type],
121
+ { runJobId: runJob.id, ...input },
122
+ options.jobOptions,
123
+ );
124
+
125
+ try {
126
+ await prisma.runJob.update({
127
+ where: { id: runJob.id },
128
+ data: { bullJobId: job.id ?? null },
129
+ });
130
+ } catch (linkError) {
131
+ logger.error('RunJob enqueued but bullJobId linkage failed', {
132
+ runJobId: runJob.id,
133
+ bullJobId: job.id ?? null,
134
+ type,
135
+ error: linkError instanceof Error ? linkError.message : String(linkError),
136
+ });
137
+ }
138
+
139
+ return { runJobId: runJob.id, bullJobId: job.id ?? null };
140
+ } catch (error) {
141
+ logger.error('Failed to enqueue RunJob; marking FAILED', {
142
+ runJobId: runJob.id,
143
+ type,
144
+ error: error instanceof Error ? error.message : String(error),
145
+ });
146
+
147
+ try {
148
+ await prisma.runJob.update({
149
+ where: { id: runJob.id },
150
+ data: {
151
+ status: 'FAILED',
152
+ error: error instanceof Error ? error.message : String(error),
153
+ finishedAt: new Date(),
154
+ },
155
+ });
156
+ } catch (updateError) {
157
+ logger.error('Failed to mark RunJob as FAILED after enqueue error', {
158
+ runJobId: runJob.id,
159
+ error: updateError instanceof Error ? updateError.message : String(updateError),
160
+ });
161
+ }
162
+
163
+ throw error;
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Close every cached queue. Call from the HTTP server's shutdown handler so
169
+ * the producer side disconnects from Redis cleanly.
170
+ */
171
+ export async function closeAllQueues(): Promise<void> {
172
+ await Promise.all(Array.from(queueCache.values()).map((q) => q.close()));
173
+ queueCache.clear();
174
+ }
@@ -4,10 +4,10 @@ import type { TestProject } from 'vitest/node';
4
4
 
5
5
  config({ path: resolve(process.cwd(), '.env.test'), override: true });
6
6
 
7
- import { prisma } from '../src/lib/prisma';
8
- import { appRouter } from '../src/routers/_app';
9
- import { createTRPCContext } from '../src/trpc';
10
- import { clearDatabase } from '../src/seedDatabase';
7
+ import { prisma } from '../../src/lib/prisma';
8
+ import { appRouter } from '../../src/routers/_app';
9
+ import { createTRPCContext } from '../../src/trpc';
10
+ import { clearDatabase } from '../../src/seedDatabase';
11
11
  import { execSync } from 'child_process';
12
12
  import { SessionType } from '@prisma/client';
13
13
 
@@ -1,5 +1,5 @@
1
- import { createTRPCContext } from '../src/trpc';
2
- import { appRouter } from '../src/routers/_app';
1
+ import { createTRPCContext } from '../../src/trpc';
2
+ import { appRouter } from '../../src/routers/_app';
3
3
 
4
4
  export async function createUnauthCaller() {
5
5
  const ctx = await createTRPCContext({