forge
Explore
Log in

Don't you dare go Hollow

Scheduled attempts, live monitor, questions, answers, exam room

Browse files at this commit

ade4fedec165c7ed4be5d83d3956dfc1b438a56eAhmet Kaan GümüşParent: d34ceb3
  • feat
    • scheduled attempts, live monitor, questions, answers, exam room
Show full message
✨ feat(exams): scheduled attempts, live monitor, questions, answers, exam room

- exam scheduling as one validated unit: mode sync|async + window
  (+ per-student duration_ms for async); unscheduled stays offline-graded
- exam_attempt: one row per exam+user by composite id; start = attendance
  signal, finish = submission; status/deadline recomputed from the current
  schedule on every read (mode frozen once attempts exist, times extend live)
- teacher live monitor: GET /exams/{id}/live snapshot + SSE /live/stream
- exam_question: choice|text authored per exam, kind bundle (choices+correct)
  validated as a unit, frozen once attempts start, ULID order
- exam_answer: upsert per question+user via composite id, kind-coherent,
  server-clock stamped; pure auto_score over choice questions as a grading
  suggestion — final mark stays human via /results
- student exam room WebSocket at /exams/{id}/attempt/ws: state ticks,
  autosave acks, finish/expire lifecycle, gates rejected pre-upgrade with
  proper HTTP statuses; shares the REST write path
- PersonRef embeds (id + username + display name) in people-bearing
  responses, plus teacher+ GET /users/search
- cascades: exam/course deletes sweep attempts, questions, answers, results
Cargo.lockmodified+168 -22
@@ -266,6 +266,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
266 checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"266 checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
267 dependencies = [267 dependencies = [
268 "axum-core",268 "axum-core",
269+ "base64",
269 "bytes",270 "bytes",
270 "form_urlencoded",271 "form_urlencoded",
271 "futures-util",272 "futures-util",
@@ -284,8 +285,10 @@ dependencies = [
284 "serde_json",285 "serde_json",
285 "serde_path_to_error",286 "serde_path_to_error",
286 "serde_urlencoded",287 "serde_urlencoded",
288+ "sha1 0.10.6",
287 "sync_wrapper",289 "sync_wrapper",
288 "tokio",290 "tokio",
291+ "tokio-tungstenite 0.29.0",
289 "tower",292 "tower",
290 "tower-layer",293 "tower-layer",
291 "tower-service",294 "tower-service",
@@ -409,7 +412,7 @@ version = "0.10.6"
409 source = "registry+https://github.com/rust-lang/crates.io-index"412 source = "registry+https://github.com/rust-lang/crates.io-index"
410 checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"413 checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
411 dependencies = [414 dependencies = [
412- "digest",415+ "digest 0.10.7",
413 ]416 ]
414 417
415 [[package]]418 [[package]]
@@ -435,6 +438,15 @@ dependencies = [
435 "generic-array 0.14.7",438 "generic-array 0.14.7",
436 ]439 ]
437 440
441+[[package]]
442+name = "block-buffer"
443+version = "0.12.1"
444+source = "registry+https://github.com/rust-lang/crates.io-index"
445+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
446+dependencies = [
447+ "hybrid-array",
448+]
449+
438 [[package]]450 [[package]]
439 name = "blowfish"451 name = "blowfish"
440 version = "0.9.1"452 version = "0.9.1"
@@ -577,6 +589,17 @@ version = "0.2.1"
577 source = "registry+https://github.com/rust-lang/crates.io-index"589 source = "registry+https://github.com/rust-lang/crates.io-index"
578 checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"590 checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
579 591
592+[[package]]
593+name = "chacha20"
594+version = "0.10.1"
595+source = "registry+https://github.com/rust-lang/crates.io-index"
596+checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"
597+dependencies = [
598+ "cfg-if",
599+ "cpufeatures 0.3.0",
600+ "rand_core 0.10.1",
601+]
602+
580 [[package]]603 [[package]]
581 name = "chrono"604 name = "chrono"
582 version = "0.4.45"605 version = "0.4.45"
@@ -624,7 +647,7 @@ version = "0.4.4"
624 source = "registry+https://github.com/rust-lang/crates.io-index"647 source = "registry+https://github.com/rust-lang/crates.io-index"
625 checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"648 checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
626 dependencies = [649 dependencies = [
627- "crypto-common",650+ "crypto-common 0.1.7",
628 "inout",651 "inout",
629 ]652 ]
630 653
@@ -652,6 +675,12 @@ version = "0.9.6"
652 source = "registry+https://github.com/rust-lang/crates.io-index"675 source = "registry+https://github.com/rust-lang/crates.io-index"
653 checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"676 checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
654 677
678+[[package]]
679+name = "const-oid"
680+version = "0.10.2"
681+source = "registry+https://github.com/rust-lang/crates.io-index"
682+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
683+
655 [[package]]684 [[package]]
656 name = "constant_time_eq"685 name = "constant_time_eq"
657 version = "0.4.2"686 version = "0.4.2"
@@ -798,6 +827,15 @@ dependencies = [
798 "typenum",827 "typenum",
799 ]828 ]
800 829
830+[[package]]
831+name = "crypto-common"
832+version = "0.2.2"
833+source = "registry+https://github.com/rust-lang/crates.io-index"
834+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
835+dependencies = [
836+ "hybrid-array",
837+]
838+
801 [[package]]839 [[package]]
802 name = "cssparser"840 name = "cssparser"
803 version = "0.37.0"841 version = "0.37.0"
@@ -818,7 +856,7 @@ dependencies = [
818 "cfg-if",856 "cfg-if",
819 "cpufeatures 0.2.17",857 "cpufeatures 0.2.17",
820 "curve25519-dalek-derive",858 "curve25519-dalek-derive",
821- "digest",859+ "digest 0.10.7",
822 "fiat-crypto",860 "fiat-crypto",
823 "rustc_version",861 "rustc_version",
824 "subtle",862 "subtle",
@@ -862,7 +900,7 @@ version = "0.7.10"
862 source = "registry+https://github.com/rust-lang/crates.io-index"900 source = "registry+https://github.com/rust-lang/crates.io-index"
863 checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"901 checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
864 dependencies = [902 dependencies = [
865- "const-oid",903+ "const-oid 0.9.6",
866 "pem-rfc7468",904 "pem-rfc7468",
867 "zeroize",905 "zeroize",
868 ]906 ]
@@ -896,12 +934,23 @@ version = "0.10.7"
896 source = "registry+https://github.com/rust-lang/crates.io-index"934 source = "registry+https://github.com/rust-lang/crates.io-index"
897 checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"935 checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
898 dependencies = [936 dependencies = [
899- "block-buffer",937+ "block-buffer 0.10.4",
900- "const-oid",938+ "const-oid 0.9.6",
901- "crypto-common",939+ "crypto-common 0.1.7",
902 "subtle",940 "subtle",
903 ]941 ]
904 942
943+[[package]]
944+name = "digest"
945+version = "0.11.3"
946+source = "registry+https://github.com/rust-lang/crates.io-index"
947+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
948+dependencies = [
949+ "block-buffer 0.12.1",
950+ "const-oid 0.10.2",
951+ "crypto-common 0.2.2",
952+]
953+
905 [[package]]954 [[package]]
906 name = "diskann"955 name = "diskann"
907 version = "0.54.0"956 version = "0.54.0"
@@ -1034,7 +1083,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
1034 checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"1083 checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
1035 dependencies = [1084 dependencies = [
1036 "der",1085 "der",
1037- "digest",1086+ "digest 0.10.7",
1038 "elliptic-curve",1087 "elliptic-curve",
1039 "rfc6979",1088 "rfc6979",
1040 "signature",1089 "signature",
@@ -1079,7 +1128,7 @@ checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
1079 dependencies = [1128 dependencies = [
1080 "base16ct",1129 "base16ct",
1081 "crypto-bigint",1130 "crypto-bigint",
1082- "digest",1131+ "digest 0.10.7",
1083 "ff",1132 "ff",
1084 "generic-array 0.14.7",1133 "generic-array 0.14.7",
1085 "group",1134 "group",
@@ -1466,6 +1515,7 @@ dependencies = [
1466 "cfg-if",1515 "cfg-if",
1467 "libc",1516 "libc",
1468 "r-efi 6.0.0",1517 "r-efi 6.0.0",
1518+ "rand_core 0.10.1",
1469 ]1519 ]
1470 1520
1471 [[package]]1521 [[package]]
@@ -1590,7 +1640,7 @@ dependencies = [
1590 "http",1640 "http",
1591 "httpdate",1641 "httpdate",
1592 "mime",1642 "mime",
1593- "sha1",1643+ "sha1 0.10.6",
1594 ]1644 ]
1595 1645
1596 [[package]]1646 [[package]]
@@ -1665,6 +1715,7 @@ dependencies = [
1665 "axum-extra",1715 "axum-extra",
1666 "chrono",1716 "chrono",
1667 "dotenvy",1717 "dotenvy",
1718+ "futures-util",
1668 "getrandom 0.3.4",1719 "getrandom 0.3.4",
1669 "hex",1720 "hex",
1670 "reqwest",1721 "reqwest",
@@ -1675,6 +1726,8 @@ dependencies = [
1675 "thiserror",1726 "thiserror",
1676 "time",1727 "time",
1677 "tokio",1728 "tokio",
1729+ "tokio-stream",
1730+ "tokio-tungstenite 0.30.0",
1678 "tower",1731 "tower",
1679 "tower-http",1732 "tower-http",
1680 "tracing",1733 "tracing",
@@ -1700,7 +1753,7 @@ version = "0.12.1"
1700 source = "registry+https://github.com/rust-lang/crates.io-index"1753 source = "registry+https://github.com/rust-lang/crates.io-index"
1701 checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"1754 checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
1702 dependencies = [1755 dependencies = [
1703- "digest",1756+ "digest 0.10.7",
1704 ]1757 ]
1705 1758
1706 [[package]]1759 [[package]]
@@ -1764,6 +1817,15 @@ version = "2.4.0"
1764 source = "registry+https://github.com/rust-lang/crates.io-index"1817 source = "registry+https://github.com/rust-lang/crates.io-index"
1765 checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15"1818 checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15"
1766 1819
1820+[[package]]
1821+name = "hybrid-array"
1822+version = "0.4.13"
1823+source = "registry+https://github.com/rust-lang/crates.io-index"
1824+checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c"
1825+dependencies = [
1826+ "typenum",
1827+]
1828+
1767 [[package]]1829 [[package]]
1768 name = "hyper"1830 name = "hyper"
1769 version = "1.10.1"1831 version = "1.10.1"
@@ -2244,7 +2306,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
2244 checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"2306 checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
2245 dependencies = [2307 dependencies = [
2246 "cfg-if",2308 "cfg-if",
2247- "digest",2309+ "digest 0.10.7",
2248 ]2310 ]
2249 2311
2250 [[package]]2312 [[package]]
@@ -2577,7 +2639,7 @@ version = "0.12.2"
2577 source = "registry+https://github.com/rust-lang/crates.io-index"2639 source = "registry+https://github.com/rust-lang/crates.io-index"
2578 checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"2640 checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
2579 dependencies = [2641 dependencies = [
2580- "digest",2642+ "digest 0.10.7",
2581 "hmac",2643 "hmac",
2582 "password-hash",2644 "password-hash",
2583 "sha2",2645 "sha2",
@@ -2928,6 +2990,17 @@ dependencies = [
2928 "rand_core 0.9.5",2990 "rand_core 0.9.5",
2929 ]2991 ]
2930 2992
2993+[[package]]
2994+name = "rand"
2995+version = "0.10.2"
2996+source = "registry+https://github.com/rust-lang/crates.io-index"
2997+checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
2998+dependencies = [
2999+ "chacha20",
3000+ "getrandom 0.4.3",
3001+ "rand_core 0.10.1",
3002+]
3003+
2931 [[package]]3004 [[package]]
2932 name = "rand_chacha"3005 name = "rand_chacha"
2933 version = "0.3.1"3006 version = "0.3.1"
@@ -2966,6 +3039,12 @@ dependencies = [
2966 "getrandom 0.3.4",3039 "getrandom 0.3.4",
2967 ]3040 ]
2968 3041
3042+[[package]]
3043+name = "rand_core"
3044+version = "0.10.1"
3045+source = "registry+https://github.com/rust-lang/crates.io-index"
3046+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
3047+
2969 [[package]]3048 [[package]]
2970 name = "rand_distr"3049 name = "rand_distr"
2971 version = "0.5.1"3050 version = "0.5.1"
@@ -3211,8 +3290,8 @@ version = "0.9.10"
3211 source = "registry+https://github.com/rust-lang/crates.io-index"3290 source = "registry+https://github.com/rust-lang/crates.io-index"
3212 checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"3291 checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
3213 dependencies = [3292 dependencies = [
3214- "const-oid",3293+ "const-oid 0.9.6",
3215- "digest",3294+ "digest 0.10.7",
3216 "num-bigint-dig",3295 "num-bigint-dig",
3217 "num-integer",3296 "num-integer",
3218 "num-traits",3297 "num-traits",
@@ -3541,7 +3620,18 @@ checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
3541 dependencies = [3620 dependencies = [
3542 "cfg-if",3621 "cfg-if",
3543 "cpufeatures 0.2.17",3622 "cpufeatures 0.2.17",
3544- "digest",3623+ "digest 0.10.7",
3624+]
3625+
3626+[[package]]
3627+name = "sha1"
3628+version = "0.11.0"
3629+source = "registry+https://github.com/rust-lang/crates.io-index"
3630+checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
3631+dependencies = [
3632+ "cfg-if",
3633+ "cpufeatures 0.3.0",
3634+ "digest 0.11.3",
3545 ]3635 ]
3546 3636
3547 [[package]]3637 [[package]]
@@ -3552,7 +3642,7 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
3552 dependencies = [3642 dependencies = [
3553 "cfg-if",3643 "cfg-if",
3554 "cpufeatures 0.2.17",3644 "cpufeatures 0.2.17",
3555- "digest",3645+ "digest 0.10.7",
3556 ]3646 ]
3557 3647
3558 [[package]]3648 [[package]]
@@ -3592,7 +3682,7 @@ version = "2.2.0"
3592 source = "registry+https://github.com/rust-lang/crates.io-index"3682 source = "registry+https://github.com/rust-lang/crates.io-index"
3593 checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"3683 checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
3594 dependencies = [3684 dependencies = [
3595- "digest",3685+ "digest 0.10.7",
3596 "rand_core 0.6.4",3686 "rand_core 0.6.4",
3597 ]3687 ]
3598 3688
@@ -3867,7 +3957,7 @@ dependencies = [
3867 "semver",3957 "semver",
3868 "serde",3958 "serde",
3869 "serde_json",3959 "serde_json",
3870- "sha1",3960+ "sha1 0.10.6",
3871 "sha2",3961 "sha2",
3872 "storekey",3962 "storekey",
3873 "strsim",3963 "strsim",
@@ -4238,7 +4328,31 @@ dependencies = [
4238 "futures-util",4328 "futures-util",
4239 "log",4329 "log",
4240 "tokio",4330 "tokio",
4241- "tungstenite",4331+ "tungstenite 0.28.0",
4332+]
4333+
4334+[[package]]
4335+name = "tokio-tungstenite"
4336+version = "0.29.0"
4337+source = "registry+https://github.com/rust-lang/crates.io-index"
4338+checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c"
4339+dependencies = [
4340+ "futures-util",
4341+ "log",
4342+ "tokio",
4343+ "tungstenite 0.29.0",
4344+]
4345+
4346+[[package]]
4347+name = "tokio-tungstenite"
4348+version = "0.30.0"
4349+source = "registry+https://github.com/rust-lang/crates.io-index"
4350+checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71"
4351+dependencies = [
4352+ "futures-util",
4353+ "log",
4354+ "tokio",
4355+ "tungstenite 0.30.0",
4242 ]4356 ]
4243 4357
4244 [[package]]4358 [[package]]
@@ -4255,7 +4369,7 @@ dependencies = [
4255 "js-sys",4369 "js-sys",
4256 "thiserror",4370 "thiserror",
4257 "tokio",4371 "tokio",
4258- "tokio-tungstenite",4372+ "tokio-tungstenite 0.28.0",
4259 "wasm-bindgen",4373 "wasm-bindgen",
4260 "web-sys",4374 "web-sys",
4261 ]4375 ]
@@ -4485,11 +4599,43 @@ dependencies = [
4485 "httparse",4599 "httparse",
4486 "log",4600 "log",
4487 "rand 0.9.4",4601 "rand 0.9.4",
4488- "sha1",4602+ "sha1 0.10.6",
4489 "thiserror",4603 "thiserror",
4490 "utf-8",4604 "utf-8",
4491 ]4605 ]
4492 4606
4607+[[package]]
4608+name = "tungstenite"
4609+version = "0.29.0"
4610+source = "registry+https://github.com/rust-lang/crates.io-index"
4611+checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8"
4612+dependencies = [
4613+ "bytes",
4614+ "data-encoding",
4615+ "http",
4616+ "httparse",
4617+ "log",
4618+ "rand 0.9.4",
4619+ "sha1 0.10.6",
4620+ "thiserror",
4621+]
4622+
4623+[[package]]
4624+name = "tungstenite"
4625+version = "0.30.0"
4626+source = "registry+https://github.com/rust-lang/crates.io-index"
4627+checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22"
4628+dependencies = [
4629+ "bytes",
4630+ "data-encoding",
4631+ "http",
4632+ "httparse",
4633+ "log",
4634+ "rand 0.10.2",
4635+ "sha1 0.11.0",
4636+ "thiserror",
4637+]
4638+
4493 [[package]]4639 [[package]]
4494 name = "twox-hash"4640 name = "twox-hash"
4495 version = "2.1.2"4641 version = "2.1.2"
Cargo.tomlmodified+6 -1
@@ -11,7 +11,10 @@ disallowed_types = "deny"
11 11
12 [dependencies]12 [dependencies]
13 tokio = { version = "1", features = ["full"] }13 tokio = { version = "1", features = ["full"] }
14-axum = "0.8"14+# IntervalStream for the live exam-monitor SSE tick.
15+tokio-stream = "0.1"
16+# "ws" backs the live exam room (WebSocket at /exams/{id}/attempt/ws).
17+axum = { version = "0.8", features = ["ws"] }
15 axum-extra = { version = "0.10", features = ["cookie"] }18 axum-extra = { version = "0.10", features = ["cookie"] }
16 tower-http = { version = "0.6", features = ["trace", "cors"] }19 tower-http = { version = "0.6", features = ["trace", "cors"] }
17 surrealdb = { version = "3", default-features = false, features = ["kv-surrealkv", "kv-mem"] }20 surrealdb = { version = "3", default-features = false, features = ["kv-surrealkv", "kv-mem"] }
@@ -38,3 +41,5 @@ tokio = { version = "1", features = ["full", "test-util"] }
38 tower = { version = "0.5", features = ["util"] }41 tower = { version = "0.5", features = ["util"] }
39 reqwest = { version = "0.12", default-features = false, features = ["json", "cookies"] }42 reqwest = { version = "0.12", default-features = false, features = ["json", "cookies"] }
40 tempfile = "3"43 tempfile = "3"
44+tokio-tungstenite = "0.30.0"
45+futures-util = "0.3.32"
src/constant.rsmodified+34 -0
@@ -34,6 +34,40 @@ pub const ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excuse
34 /// the course average.34 /// the course average.
35 pub const EXAM_KINDS: [&str; 6] = ["homework", "quiz", "midterm", "final", "project", "oral"];35 pub const EXAM_KINDS: [&str; 6] = ["homework", "quiz", "midterm", "final", "project", "oral"];
36 36
37+/// The only accepted exam modes. `sync`: everyone sits the exam inside one
38+/// fixed window. `async`: each student starts inside the window and gets their
39+/// own `duration_ms` slice of it.
40+pub const EXAM_MODES: [&str; 2] = ["sync", "async"];
41+
42+/// Inclusive bounds for an async exam's per-student duration, milliseconds
43+/// (1 minute to 24 hours).
44+pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000;
45+pub const MAX_EXAM_DURATION_MS: i64 = 24 * 60 * 60 * 1000;
46+
47+/// Cadence of the live exam-monitor SSE stream (`GET /exams/{id}/live/stream`).
48+pub const EXAM_LIVE_STREAM_INTERVAL_SECS: u64 = 2;
49+
50+/// Cadence of the `state` ticks on the student exam-room WebSocket
51+/// (`GET /exams/{id}/attempt/ws`).
52+pub const EXAM_WS_TICK_SECS: u64 = 2;
53+
54+/// The only accepted question kinds. `choice`: pick one of the listed
55+/// choices, auto-scorable. `text`: free text, judged by the grader.
56+pub const QUESTION_KINDS: [&str; 2] = ["choice", "text"];
57+
58+pub const MAX_QUESTION_TEXT_LEN: usize = 2_000;
59+
60+/// Inclusive bounds for a question's points (its share of the auto-score).
61+pub const MIN_QUESTION_POINTS: i64 = 1;
62+pub const MAX_QUESTION_POINTS: i64 = 100;
63+
64+/// Bounds for a choice question's option list and each option's text.
65+pub const MIN_QUESTION_CHOICES: usize = 2;
66+pub const MAX_QUESTION_CHOICES: usize = 10;
67+pub const MAX_CHOICE_TEXT_LEN: usize = 500;
68+
69+pub const MAX_ANSWER_TEXT_LEN: usize = 10_000;
70+
37 /// Inclusive bounds for an exam mark.71 /// Inclusive bounds for an exam mark.
38 pub const MIN_MARK: i64 = 0;72 pub const MIN_MARK: i64 = 0;
39 pub const MAX_MARK: i64 = 100;73 pub const MAX_MARK: i64 = 100;
src/database.rsmodified+35 -0
@@ -15,6 +15,9 @@ pub const EVENT_TABLE: &str = "event";
15 pub const ATTENDANCE_TABLE: &str = "attendance";15 pub const ATTENDANCE_TABLE: &str = "attendance";
16 pub const EXAM_TABLE: &str = "exam";16 pub const EXAM_TABLE: &str = "exam";
17 pub const EXAM_RESULT_TABLE: &str = "exam_result";17 pub const EXAM_RESULT_TABLE: &str = "exam_result";
18+pub const EXAM_ATTEMPT_TABLE: &str = "exam_attempt";
19+pub const EXAM_QUESTION_TABLE: &str = "exam_question";
20+pub const EXAM_ANSWER_TABLE: &str = "exam_answer";
18 pub const COURSE_TABLE: &str = "course";21 pub const COURSE_TABLE: &str = "course";
19 pub const ENROLLMENT_TABLE: &str = "enrollment";22 pub const ENROLLMENT_TABLE: &str = "enrollment";
20 23
@@ -79,8 +82,40 @@ const MIGRATION: &str = "
79 DEFINE FIELD IF NOT EXISTS description ON exam TYPE string;82 DEFINE FIELD IF NOT EXISTS description ON exam TYPE string;
80 DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string;83 DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string;
81 DEFINE FIELD IF NOT EXISTS weight ON exam TYPE int;84 DEFINE FIELD IF NOT EXISTS weight ON exam TYPE int;
85+ DEFINE FIELD IF NOT EXISTS mode ON exam TYPE option<string>;
86+ DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option<int>;
87+ DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option<int>;
88+ DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option<int>;
82 DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;89 DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;
83 90
91+ DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL;
92+ DEFINE FIELD IF NOT EXISTS exam ON exam_attempt TYPE record<exam>;
93+ DEFINE FIELD IF NOT EXISTS user ON exam_attempt TYPE record<user>;
94+ DEFINE FIELD IF NOT EXISTS started_at ON exam_attempt TYPE int;
95+ DEFINE FIELD IF NOT EXISTS finished_at ON exam_attempt TYPE option<int>;
96+ DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user ON exam_attempt FIELDS exam, user UNIQUE;
97+ DEFINE INDEX IF NOT EXISTS exam_attempt_exam ON exam_attempt FIELDS exam;
98+
99+ DEFINE TABLE IF NOT EXISTS exam_question SCHEMAFULL;
100+ DEFINE FIELD IF NOT EXISTS exam ON exam_question TYPE record<exam>;
101+ DEFINE FIELD IF NOT EXISTS text ON exam_question TYPE string;
102+ DEFINE FIELD IF NOT EXISTS kind ON exam_question TYPE string;
103+ DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int;
104+ DEFINE FIELD IF NOT EXISTS choices ON exam_question TYPE option<array<string>>;
105+ DEFINE FIELD IF NOT EXISTS correct ON exam_question TYPE option<int>;
106+ DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam;
107+
108+ DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL;
109+ DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record<exam>;
110+ DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record<exam_question>;
111+ DEFINE FIELD IF NOT EXISTS user ON exam_answer TYPE record<user>;
112+ DEFINE FIELD IF NOT EXISTS selected ON exam_answer TYPE option<int>;
113+ DEFINE FIELD IF NOT EXISTS text ON exam_answer TYPE option<string>;
114+ DEFINE FIELD IF NOT EXISTS updated_at ON exam_answer TYPE int;
115+ DEFINE INDEX IF NOT EXISTS exam_answer_question_user ON exam_answer FIELDS question, user UNIQUE;
116+ DEFINE INDEX IF NOT EXISTS exam_answer_exam_user ON exam_answer FIELDS exam, user;
117+ DEFINE INDEX IF NOT EXISTS exam_answer_exam ON exam_answer FIELDS exam;
118+
84 DEFINE TABLE IF NOT EXISTS exam_result SCHEMAFULL;119 DEFINE TABLE IF NOT EXISTS exam_result SCHEMAFULL;
85 DEFINE FIELD IF NOT EXISTS exam ON exam_result TYPE record<exam>;120 DEFINE FIELD IF NOT EXISTS exam ON exam_result TYPE record<exam>;
86 DEFINE FIELD IF NOT EXISTS user ON exam_result TYPE record<user>;121 DEFINE FIELD IF NOT EXISTS user ON exam_result TYPE record<user>;
src/domain/course.rsmodified+7 -4
@@ -145,14 +145,17 @@ impl Course {
145 updated.ok_or(AppError::NotFound)145 updated.ok_or(AppError::NotFound)
146 }146 }
147 147
148- /// Delete the course and cascade-remove everything inside it: results of148+ /// Delete the course and cascade-remove everything inside it: results and
149- /// its exams, its enrollments, and the exams themselves. The children go in149+ /// attempts of its exams, its enrollments, and the exams themselves. The
150- /// one transaction so a crash can't leave an exam pointing at a deleted150+ /// children go in one transaction so a crash can't leave an exam pointing
151- /// course.151+ /// at a deleted course.
152 pub async fn delete(self, db: &Database) -> Result<Course, AppError> {152 pub async fn delete(self, db: &Database) -> Result<Course, AppError> {
153 db.query(153 db.query(
154 "BEGIN TRANSACTION;154 "BEGIN TRANSACTION;
155 DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);155 DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
156+ DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
157+ DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
158+ DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
156 DELETE enrollment WHERE course = $course;159 DELETE enrollment WHERE course = $course;
157 DELETE exam WHERE course = $course;160 DELETE exam WHERE course = $course;
158 COMMIT TRANSACTION;",161 COMMIT TRANSACTION;",
src/domain/exam.rsmodified+203 -6
@@ -4,9 +4,13 @@ use ulid::Ulid;
4 use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN};4 use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN};
5 use crate::database::{Database, EXAM_TABLE};5 use crate::database::{Database, EXAM_TABLE};
6 use crate::domain::course::CourseId;6 use crate::domain::course::CourseId;
7+use crate::domain::timestamp::Timestamp;
7 use crate::domain::user::UserId;8 use crate::domain::user::UserId;
8 use crate::error::{AppError, ValidationError};9 use crate::error::{AppError, ValidationError};
9-use crate::validate::{validate_exam_kind, validate_optional, validate_required, validate_weight};10+use crate::validate::{
11+ validate_exam_duration, validate_exam_kind, validate_exam_mode, validate_optional,
12+ validate_required, validate_weight,
13+};
10 14
11 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]15 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
12 pub struct ExamId(RecordId);16 pub struct ExamId(RecordId);
@@ -93,6 +97,107 @@ impl ExamWeight {
93 }97 }
94 }98 }
95 99
100+/// A validated exam mode: `sync` (everyone sits inside one fixed window) or
101+/// `async` (each student starts inside the window and gets `duration_ms`).
102+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
103+pub struct ExamMode(String);
104+
105+impl ExamMode {
106+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
107+ validate_exam_mode(value)?;
108+ Ok(Self(value.to_string()))
109+ }
110+
111+ pub fn as_str(&self) -> &str {
112+ &self.0
113+ }
114+}
115+
116+/// A validated per-student time budget for an `async` exam, milliseconds.
117+#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)]
118+pub struct ExamDuration(i64);
119+
120+impl ExamDuration {
121+ pub fn try_new(value: i64) -> Result<Self, ValidationError> {
122+ validate_exam_duration(value)?;
123+ Ok(Self(value))
124+ }
125+
126+ pub fn as_millis(&self) -> i64 {
127+ self.0
128+ }
129+}
130+
131+/// The scheduling fields of an exam, validated as a unit — they only make
132+/// sense together. `try_new` is the sole constructor, so an `ExamSchedule` in
133+/// hand always satisfies:
134+///
135+/// - no mode → no `starts_at`/`ends_at`/`duration_ms` (an unscheduled exam is
136+/// graded offline; attempts are rejected),
137+/// - `sync` → `starts_at` + `ends_at`, no duration (everyone's deadline is
138+/// `ends_at`),
139+/// - `async` → `starts_at` + `ends_at` + `duration_ms` (a student who starts
140+/// at `t` gets until `min(t + duration_ms, ends_at)`),
141+/// - `ends_at` strictly after `starts_at`.
142+#[derive(Debug, Clone, Default)]
143+pub struct ExamSchedule {
144+ mode: Option<ExamMode>,
145+ starts_at: Option<Timestamp>,
146+ ends_at: Option<Timestamp>,
147+ duration_ms: Option<ExamDuration>,
148+}
149+
150+impl ExamSchedule {
151+ pub fn try_new(
152+ mode: Option<ExamMode>,
153+ starts_at: Option<Timestamp>,
154+ ends_at: Option<Timestamp>,
155+ duration_ms: Option<ExamDuration>,
156+ ) -> Result<Self, ValidationError> {
157+ let invalid = |field, reason| ValidationError::Invalid { field, reason };
158+ match &mode {
159+ None => {
160+ if starts_at.is_some() || ends_at.is_some() || duration_ms.is_some() {
161+ return Err(invalid(
162+ "mode",
163+ "starts_at, ends_at, and duration_ms require a mode (sync or async)",
164+ ));
165+ }
166+ }
167+ Some(m) => {
168+ if starts_at.is_none() {
169+ return Err(invalid("starts_at", "required for a scheduled exam"));
170+ }
171+ if ends_at.is_none() {
172+ return Err(invalid("ends_at", "required for a scheduled exam"));
173+ }
174+ if ends_at <= starts_at {
175+ return Err(invalid("ends_at", "must be after starts_at"));
176+ }
177+ match (m.as_str(), duration_ms.is_some()) {
178+ ("async", false) => {
179+ return Err(invalid("duration_ms", "required for an async exam"));
180+ }
181+ ("sync", true) => {
182+ return Err(invalid("duration_ms", "only async exams take a duration"));
183+ }
184+ _ => {}
185+ }
186+ }
187+ }
188+ Ok(Self {
189+ mode,
190+ starts_at,
191+ ends_at,
192+ duration_ms,
193+ })
194+ }
195+
196+ pub fn get_mode(&self) -> Option<&ExamMode> {
197+ self.mode.as_ref()
198+ }
199+}
200+
96 #[derive(Debug, Clone, SurrealValue)]201 #[derive(Debug, Clone, SurrealValue)]
97 pub struct Exam {202 pub struct Exam {
98 id: ExamId,203 id: ExamId,
@@ -102,6 +207,13 @@ pub struct Exam {
102 description: ExamDescription,207 description: ExamDescription,
103 kind: ExamKind,208 kind: ExamKind,
104 weight: ExamWeight,209 weight: ExamWeight,
210+ // The schedule, flattened into columns (SCHEMAFULL keeps them typed).
211+ // Always written through an `ExamSchedule`, so the invariants above hold
212+ // for every stored row; pre-schedule rows read back as all-`None`.
213+ mode: Option<ExamMode>,
214+ starts_at: Option<Timestamp>,
215+ ends_at: Option<Timestamp>,
216+ duration_ms: Option<ExamDuration>,
105 }217 }
106 218
107 impl Exam {219 impl Exam {
@@ -133,10 +245,42 @@ impl Exam {
133 self.weight245 self.weight
134 }246 }
135 247
248+ pub fn get_mode(&self) -> Option<&ExamMode> {
249+ self.mode.as_ref()
250+ }
251+
252+ pub fn get_starts_at(&self) -> Option<Timestamp> {
253+ self.starts_at
254+ }
255+
256+ pub fn get_ends_at(&self) -> Option<Timestamp> {
257+ self.ends_at
258+ }
259+
260+ pub fn get_duration_ms(&self) -> Option<ExamDuration> {
261+ self.duration_ms
262+ }
263+
264+ /// The stored schedule as the validated bundle (for merge-on-update).
265+ /// Bypasses `try_new`: the fields were written through an `ExamSchedule`,
266+ /// so the invariants already hold.
267+ pub fn schedule(&self) -> ExamSchedule {
268+ ExamSchedule {
269+ mode: self.mode.clone(),
270+ starts_at: self.starts_at,
271+ ends_at: self.ends_at,
272+ duration_ms: self.duration_ms,
273+ }
274+ }
275+
136 pub fn is_creator(&self, user: &UserId) -> bool {276 pub fn is_creator(&self, user: &UserId) -> bool {
137 &self.creator == user277 &self.creator == user
138 }278 }
139 279
280+ #[expect(
281+ clippy::too_many_arguments,
282+ reason = "mirrors the sibling entities' create(field, field, ..) shape"
283+ )]
140 pub async fn create(284 pub async fn create(
141 creator: &UserId,285 creator: &UserId,
142 course: &CourseId,286 course: &CourseId,
@@ -144,6 +288,7 @@ impl Exam {
144 description: ExamDescription,288 description: ExamDescription,
145 kind: ExamKind,289 kind: ExamKind,
146 weight: ExamWeight,290 weight: ExamWeight,
291+ schedule: ExamSchedule,
147 db: &Database,292 db: &Database,
148 ) -> Result<Exam, AppError> {293 ) -> Result<Exam, AppError> {
149 let exam = Exam {294 let exam = Exam {
@@ -154,6 +299,10 @@ impl Exam {
154 description,299 description,
155 kind,300 kind,
156 weight,301 weight,
302+ mode: schedule.mode,
303+ starts_at: schedule.starts_at,
304+ ends_at: schedule.ends_at,
305+ duration_ms: schedule.duration_ms,
157 };306 };
158 let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?;307 let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?;
159 created.ok_or_else(|| AppError::Internal("failed to create exam".into()))308 created.ok_or_else(|| AppError::Internal("failed to create exam".into()))
@@ -188,22 +337,35 @@ impl Exam {
188 description: ExamDescription,337 description: ExamDescription,
189 kind: ExamKind,338 kind: ExamKind,
190 weight: ExamWeight,339 weight: ExamWeight,
340+ schedule: ExamSchedule,
191 db: &Database,341 db: &Database,
192 ) -> Result<Exam, AppError> {342 ) -> Result<Exam, AppError> {
193 self.title = title;343 self.title = title;
194 self.description = description;344 self.description = description;
195 self.kind = kind;345 self.kind = kind;
196 self.weight = weight;346 self.weight = weight;
347+ self.mode = schedule.mode;
348+ self.starts_at = schedule.starts_at;
349+ self.ends_at = schedule.ends_at;
350+ self.duration_ms = schedule.duration_ms;
197 let updated: Option<Exam> = db.update(self.id.record()).content(self).await?;351 let updated: Option<Exam> = db.update(self.id.record()).content(self).await?;
198 updated.ok_or(AppError::NotFound)352 updated.ok_or(AppError::NotFound)
199 }353 }
200 354
201- /// Delete the exam and cascade-remove its result rows.355+ /// Delete the exam and cascade-remove its result, attempt, question, and
356+ /// answer rows.
202 pub async fn delete(self, db: &Database) -> Result<Exam, AppError> {357 pub async fn delete(self, db: &Database) -> Result<Exam, AppError> {
203- db.query("DELETE exam_result WHERE exam = $ex")358+ db.query(
204- .bind(("ex", self.id.record()))359+ "BEGIN TRANSACTION;
205- .await?360+ DELETE exam_result WHERE exam = $ex;
206- .check()?;361+ DELETE exam_attempt WHERE exam = $ex;
362+ DELETE exam_answer WHERE exam = $ex;
363+ DELETE exam_question WHERE exam = $ex;
364+ COMMIT TRANSACTION;",
365+ )
366+ .bind(("ex", self.id.record()))
367+ .await?
368+ .check()?;
207 let deleted: Option<Exam> = db.delete(self.id.record()).await?;369 let deleted: Option<Exam> = db.delete(self.id.record()).await?;
208 deleted.ok_or(AppError::NotFound)370 deleted.ok_or(AppError::NotFound)
209 }371 }
@@ -241,4 +403,39 @@ mod tests {
241 assert!(ExamWeight::try_new(0).is_err());403 assert!(ExamWeight::try_new(0).is_err());
242 assert!(ExamWeight::try_new(101).is_err());404 assert!(ExamWeight::try_new(101).is_err());
243 }405 }
406+
407+ #[tokio::test]
408+ async fn mode_must_be_known() {
409+ for mode in ["sync", "async"] {
410+ assert_eq!(ExamMode::try_new(mode).unwrap().as_str(), mode);
411+ }
412+ assert!(ExamMode::try_new("live").is_err());
413+ }
414+
415+ #[tokio::test]
416+ async fn schedule_invariants_hold() {
417+ let mode = |m| Some(ExamMode::try_new(m).unwrap());
418+ let at = |ms| Some(Timestamp::from_millis(ms));
419+ let dur = Some(ExamDuration::try_new(90 * 60 * 1000).unwrap());
420+
421+ // Unscheduled: nothing set is fine, any time/duration without a mode is not.
422+ assert!(ExamSchedule::try_new(None, None, None, None).is_ok());
423+ assert!(ExamSchedule::try_new(None, at(1), None, None).is_err());
424+ assert!(ExamSchedule::try_new(None, None, at(2), None).is_err());
425+ assert!(ExamSchedule::try_new(None, None, None, dur).is_err());
426+
427+ // Sync: fixed window, no duration.
428+ assert!(ExamSchedule::try_new(mode("sync"), at(1), at(2), None).is_ok());
429+ assert!(ExamSchedule::try_new(mode("sync"), None, at(2), None).is_err());
430+ assert!(ExamSchedule::try_new(mode("sync"), at(1), None, None).is_err());
431+ assert!(ExamSchedule::try_new(mode("sync"), at(1), at(2), dur).is_err());
432+
433+ // Async: window plus a per-student duration.
434+ assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), dur).is_ok());
435+ assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), None).is_err());
436+
437+ // The window must be a real interval, whatever the mode.
438+ assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err());
439+ assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err());
440+ }
244 }441 }
src/domain/exam_answer.rsadded+303 -0
@@ -0,0 +1,303 @@
1+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2+
3+use crate::constant::MAX_ANSWER_TEXT_LEN;
4+use crate::database::{Database, EXAM_ANSWER_TABLE};
5+use crate::domain::exam::ExamId;
6+use crate::domain::exam_question::{ExamQuestion, ExamQuestionId};
7+use crate::domain::timestamp::Timestamp;
8+use crate::domain::user::UserId;
9+use crate::error::{AppError, ValidationError};
10+use crate::validate::validate_optional;
11+
12+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
13+pub struct ExamAnswerId(RecordId);
14+
15+impl ExamAnswerId {
16+ /// A deterministic id for the (question, user) pair — the question key is
17+ /// its own ULID, so the pair key is unambiguous. Saving is a single atomic
18+ /// UPSERT: re-answering overwrites the one row instead of racing the
19+ /// unique index into a 500. ULID keys are alphanumeric, so `_` is an
20+ /// unambiguous joiner.
21+ pub fn composite(question: &ExamQuestionId, user: &UserId) -> Self {
22+ Self(RecordId::new(
23+ EXAM_ANSWER_TABLE,
24+ format!("{}_{}", question.key(), user.key()),
25+ ))
26+ }
27+
28+ pub fn record(&self) -> RecordId {
29+ self.0.clone()
30+ }
31+
32+ pub fn key(&self) -> &str {
33+ match &self.0.key {
34+ RecordIdKey::String(key) => key,
35+ _ => "",
36+ }
37+ }
38+}
39+
40+/// A free-text answer: may be empty (a student clearing their draft is a valid
41+/// save), at most `MAX_ANSWER_TEXT_LEN` characters.
42+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
43+pub struct AnswerText(String);
44+
45+impl AnswerText {
46+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
47+ validate_optional("text", value, MAX_ANSWER_TEXT_LEN)?;
48+ Ok(Self(value.to_string()))
49+ }
50+
51+ pub fn as_str(&self) -> &str {
52+ &self.0
53+ }
54+}
55+
56+/// One student's answer to one question, autosaved as they type or pick.
57+/// `exam` is denormalized from the question so per-exam reads (live monitor,
58+/// cascades) don't fan out through `exam_question`.
59+#[derive(Debug, Clone, SurrealValue)]
60+pub struct ExamAnswer {
61+ id: ExamAnswerId,
62+ exam: ExamId,
63+ question: ExamQuestionId,
64+ user: UserId,
65+ selected: Option<i64>,
66+ text: Option<AnswerText>,
67+ updated_at: Timestamp,
68+}
69+
70+impl ExamAnswer {
71+ pub fn get_id(&self) -> &ExamAnswerId {
72+ &self.id
73+ }
74+
75+ pub fn get_exam(&self) -> &ExamId {
76+ &self.exam
77+ }
78+
79+ pub fn get_question(&self) -> &ExamQuestionId {
80+ &self.question
81+ }
82+
83+ pub fn get_user(&self) -> &UserId {
84+ &self.user
85+ }
86+
87+ pub fn get_selected(&self) -> Option<i64> {
88+ self.selected
89+ }
90+
91+ pub fn get_text(&self) -> Option<&AnswerText> {
92+ self.text.as_ref()
93+ }
94+
95+ pub fn get_updated_at(&self) -> Timestamp {
96+ self.updated_at
97+ }
98+
99+ /// Whether this answer hits the question's correct choice. `None` for a
100+ /// text question — correctness is the grader's call, not the machine's.
101+ pub fn is_correct(&self, question: &ExamQuestion) -> Option<bool> {
102+ let correct = question.get_correct()?;
103+ Some(self.selected == Some(correct))
104+ }
105+
106+ /// Save (or overwrite) `user`'s answer to `question` — the one write path,
107+ /// shared by the REST handler and the WebSocket room. The payload must
108+ /// match the question's kind: a choice question takes `selected` (indexing
109+ /// one of its choices), a text question takes `text`. The caller has
110+ /// already checked that the attempt is in progress.
111+ pub async fn save(
112+ question: &ExamQuestion,
113+ user: &UserId,
114+ selected: Option<i64>,
115+ text: Option<String>,
116+ db: &Database,
117+ ) -> Result<ExamAnswer, AppError> {
118+ let invalid =
119+ |field, reason| AppError::Validation(ValidationError::Invalid { field, reason });
120+ let (selected, text) = match question.get_kind().as_str() {
121+ "choice" => {
122+ if text.is_some() {
123+ return Err(invalid(
124+ "text",
125+ "a choice question takes selected, not text",
126+ ));
127+ }
128+ let Some(selected) = selected else {
129+ return Err(invalid("selected", "required for a choice question"));
130+ };
131+ let count = question.get_choices().map_or(0, <[_]>::len);
132+ if !(0..count as i64).contains(&selected) {
133+ return Err(invalid(
134+ "selected",
135+ "must index one of the question's choices",
136+ ));
137+ }
138+ (Some(selected), None)
139+ }
140+ _ => {
141+ if selected.is_some() {
142+ return Err(invalid(
143+ "selected",
144+ "a text question takes text, not selected",
145+ ));
146+ }
147+ let Some(text) = text else {
148+ return Err(invalid("text", "required for a text question"));
149+ };
150+ (None, Some(AnswerText::try_new(&text)?))
151+ }
152+ };
153+ let answer = ExamAnswer {
154+ id: ExamAnswerId::composite(question.get_id(), user),
155+ exam: question.get_exam().clone(),
156+ question: question.get_id().clone(),
157+ user: user.clone(),
158+ selected,
159+ text,
160+ updated_at: Timestamp::now(),
161+ };
162+ let saved: Option<ExamAnswer> = db.upsert(answer.id.record()).content(answer).await?;
163+ saved.ok_or_else(|| AppError::Internal("failed to save exam answer".into()))
164+ }
165+
166+ /// One student's answers across an exam, in question (ULID) order.
167+ pub async fn list_for_exam_user(
168+ exam: &ExamId,
169+ user: &UserId,
170+ db: &Database,
171+ ) -> Result<Vec<ExamAnswer>, AppError> {
172+ let mut result = db
173+ .query(
174+ "SELECT * FROM exam_answer WHERE exam = $ex AND user = $usr ORDER BY question ASC",
175+ )
176+ .bind(("ex", exam.record()))
177+ .bind(("usr", user.record()))
178+ .await?
179+ .check()?;
180+ Ok(result.take::<Vec<ExamAnswer>>(0)?)
181+ }
182+
183+ /// Every answer of an exam — the live monitor aggregates these per student.
184+ pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamAnswer>, AppError> {
185+ let mut result = db
186+ .query("SELECT * FROM exam_answer WHERE exam = $ex ORDER BY question ASC")
187+ .bind(("ex", exam.record()))
188+ .await?
189+ .check()?;
190+ Ok(result.take::<Vec<ExamAnswer>>(0)?)
191+ }
192+}
193+
194+/// The choice-question score suggested by the machine: `earned` points from
195+/// answers hitting `correct`, out of `possible` points across all choice
196+/// questions. Text questions never count — the final mark stays a human call
197+/// (`POST /exams/{id}/results`).
198+pub fn auto_score(questions: &[ExamQuestion], answers: &[ExamAnswer]) -> (i64, i64) {
199+ let mut earned = 0;
200+ let mut possible = 0;
201+ for question in questions {
202+ let Some(correct) = question.get_correct() else {
203+ continue;
204+ };
205+ possible += question.get_points().as_i64();
206+ if answers
207+ .iter()
208+ .any(|a| a.get_question() == question.get_id() && a.get_selected() == Some(correct))
209+ {
210+ earned += question.get_points().as_i64();
211+ }
212+ }
213+ (earned, possible)
214+}
215+
216+#[cfg(test)]
217+mod tests {
218+ use super::*;
219+ use crate::domain::exam_question::{QuestionKind, QuestionSpec};
220+
221+ fn choice_question(exam: &ExamId, points: i64, correct: i64) -> ExamQuestion {
222+ let spec = QuestionSpec::try_new(
223+ QuestionKind::try_new("choice").unwrap(),
224+ Some(vec!["a".into(), "b".into(), "c".into()]),
225+ Some(correct),
226+ )
227+ .unwrap();
228+ ExamQuestion::test_new(exam, "pick one", points, spec)
229+ }
230+
231+ fn text_question(exam: &ExamId, points: i64) -> ExamQuestion {
232+ let spec =
233+ QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None).unwrap();
234+ ExamQuestion::test_new(exam, "explain", points, spec)
235+ }
236+
237+ fn answer(question: &ExamQuestion, user: &UserId, selected: Option<i64>) -> ExamAnswer {
238+ ExamAnswer {
239+ id: ExamAnswerId::composite(question.get_id(), user),
240+ exam: question.get_exam().clone(),
241+ question: question.get_id().clone(),
242+ user: user.clone(),
243+ selected,
244+ text: selected
245+ .is_none()
246+ .then(|| AnswerText::try_new("essay").unwrap()),
247+ updated_at: Timestamp::from_millis(1),
248+ }
249+ }
250+
251+ fn student() -> UserId {
252+ UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA")
253+ }
254+
255+ #[tokio::test]
256+ async fn answer_text_may_be_empty_but_bounded() {
257+ assert!(AnswerText::try_new("").is_ok());
258+ assert!(AnswerText::try_new(&"x".repeat(10_000)).is_ok());
259+ assert!(AnswerText::try_new(&"x".repeat(10_001)).is_err());
260+ }
261+
262+ #[tokio::test]
263+ async fn auto_score_counts_correct_choices_only() {
264+ let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA");
265+ let user = student();
266+ let q1 = choice_question(&exam, 10, 0); // answered right
267+ let q2 = choice_question(&exam, 20, 1); // answered wrong
268+ let q3 = choice_question(&exam, 30, 2); // unanswered
269+ let q4 = text_question(&exam, 40); // never auto-scored
270+ let questions = vec![q1.clone(), q2.clone(), q3, q4.clone()];
271+ let answers = vec![
272+ answer(&q1, &user, Some(0)),
273+ answer(&q2, &user, Some(0)),
274+ answer(&q4, &user, None),
275+ ];
276+ assert_eq!(auto_score(&questions, &answers), (10, 60));
277+ }
278+
279+ #[tokio::test]
280+ async fn auto_score_of_nothing_is_zero() {
281+ assert_eq!(auto_score(&[], &[]), (0, 0));
282+ let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA");
283+ let questions = vec![text_question(&exam, 50)];
284+ assert_eq!(auto_score(&questions, &[]), (0, 0));
285+ }
286+
287+ #[tokio::test]
288+ async fn is_correct_judges_choice_questions_only() {
289+ let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA");
290+ let user = student();
291+ let choice = choice_question(&exam, 10, 1);
292+ assert_eq!(
293+ answer(&choice, &user, Some(1)).is_correct(&choice),
294+ Some(true)
295+ );
296+ assert_eq!(
297+ answer(&choice, &user, Some(0)).is_correct(&choice),
298+ Some(false)
299+ );
300+ let text = text_question(&exam, 10);
301+ assert_eq!(answer(&text, &user, None).is_correct(&text), None);
302+ }
303+}
src/domain/exam_attempt.rsadded+192 -0
@@ -0,0 +1,192 @@
1+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2+
3+use crate::database::{Database, EXAM_ATTEMPT_TABLE};
4+use crate::domain::exam::Exam;
5+use crate::domain::exam::ExamId;
6+use crate::domain::timestamp::Timestamp;
7+use crate::domain::user::UserId;
8+use crate::error::AppError;
9+
10+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
11+pub struct ExamAttemptId(RecordId);
12+
13+impl ExamAttemptId {
14+ /// A deterministic id for the (exam, user) pair. The same pair always maps
15+ /// to the same record id, so a student gets exactly one attempt per exam by
16+ /// construction — a second "start" cannot mint a fresh clock. ULID keys are
17+ /// alphanumeric, so `_` is an unambiguous joiner.
18+ pub fn composite(exam: &ExamId, user: &UserId) -> Self {
19+ Self(RecordId::new(
20+ EXAM_ATTEMPT_TABLE,
21+ format!("{}_{}", exam.key(), user.key()),
22+ ))
23+ }
24+
25+ pub fn record(&self) -> RecordId {
26+ self.0.clone()
27+ }
28+
29+ pub fn key(&self) -> &str {
30+ match &self.0.key {
31+ RecordIdKey::String(key) => key,
32+ _ => "",
33+ }
34+ }
35+}
36+
37+/// Where an attempt stands right now, judged against the server clock. Derived
38+/// on read — never stored, so it can't go stale.
39+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40+pub enum AttemptStatus {
41+ /// Started, not submitted, deadline not reached.
42+ InProgress,
43+ /// The student declared themselves done before the deadline.
44+ Submitted,
45+ /// The deadline passed without a submission — a valid terminal state
46+ /// (the student used their full time), not an error.
47+ Expired,
48+}
49+
50+impl AttemptStatus {
51+ pub fn as_str(self) -> &'static str {
52+ match self {
53+ AttemptStatus::InProgress => "in_progress",
54+ AttemptStatus::Submitted => "submitted",
55+ AttemptStatus::Expired => "expired",
56+ }
57+ }
58+}
59+
60+/// One student's sitting of a scheduled exam: starting is the live-attendance
61+/// signal, `finished_at` the submission. Grading stays a separate
62+/// `exam_result` row.
63+#[derive(Debug, Clone, SurrealValue)]
64+pub struct ExamAttempt {
65+ id: ExamAttemptId,
66+ exam: ExamId,
67+ user: UserId,
68+ started_at: Timestamp,
69+ finished_at: Option<Timestamp>,
70+}
71+
72+impl ExamAttempt {
73+ pub fn get_id(&self) -> &ExamAttemptId {
74+ &self.id
75+ }
76+
77+ pub fn get_exam(&self) -> &ExamId {
78+ &self.exam
79+ }
80+
81+ pub fn get_user(&self) -> &UserId {
82+ &self.user
83+ }
84+
85+ pub fn get_started_at(&self) -> Timestamp {
86+ self.started_at
87+ }
88+
89+ pub fn get_finished_at(&self) -> Option<Timestamp> {
90+ self.finished_at
91+ }
92+
93+ /// When this attempt closes, computed from the exam's *current* schedule
94+ /// (never stored): `ends_at` for a sync exam, `min(started_at +
95+ /// duration_ms, ends_at)` for an async one. Recomputing on every read means
96+ /// a teacher extending `ends_at` (or an async `duration_ms`) mid-exam moves
97+ /// every deadline live. `None` only if the exam is unscheduled, which
98+ /// starting an attempt forbids.
99+ pub fn deadline(&self, exam: &Exam) -> Option<Timestamp> {
100+ let ends_at = exam.get_ends_at()?;
101+ Some(match exam.get_duration_ms() {
102+ Some(duration) => ends_at.min(Timestamp::from_millis(
103+ self.started_at
104+ .as_millis()
105+ .saturating_add(duration.as_millis()),
106+ )),
107+ None => ends_at,
108+ })
109+ }
110+
111+ /// Status judged at `now` (one clock read per snapshot, shared across rows).
112+ pub fn status(&self, exam: &Exam, now: Timestamp) -> AttemptStatus {
113+ if self.finished_at.is_some() {
114+ return AttemptStatus::Submitted;
115+ }
116+ match self.deadline(exam) {
117+ Some(deadline) if now >= deadline => AttemptStatus::Expired,
118+ _ => AttemptStatus::InProgress,
119+ }
120+ }
121+
122+ /// Start (or resume) `user`'s attempt at `exam`. Returns the attempt plus
123+ /// whether it was newly created: an existing row is returned untouched, so
124+ /// a reconnecting client gets its original clock back instead of a reset —
125+ /// re-"starting" can never buy more time. The composite id makes the
126+ /// create atomic; a concurrent double-start loses to the unique id and
127+ /// reads the winner's row.
128+ pub async fn start(
129+ exam: &ExamId,
130+ user: &UserId,
131+ db: &Database,
132+ ) -> Result<(ExamAttempt, bool), AppError> {
133+ if let Some(existing) = Self::read_for_user(exam, user, db).await? {
134+ return Ok((existing, false));
135+ }
136+ let attempt = ExamAttempt {
137+ id: ExamAttemptId::composite(exam, user),
138+ exam: exam.clone(),
139+ user: user.clone(),
140+ started_at: Timestamp::now(),
141+ finished_at: None,
142+ };
143+ let created: Result<Option<ExamAttempt>, surrealdb::Error> =
144+ db.create(attempt.id.record()).content(attempt).await;
145+ match created {
146+ Ok(Some(created)) => Ok((created, true)),
147+ Ok(None) => Err(AppError::Internal("failed to start exam attempt".into())),
148+ Err(err) => match Self::read_for_user(exam, user, db).await? {
149+ Some(existing) => Ok((existing, false)),
150+ None => Err(err.into()),
151+ },
152+ }
153+ }
154+
155+ /// Stamp the submission time. The caller has already checked the deadline
156+ /// and that the attempt isn't finished.
157+ pub async fn finish(mut self, db: &Database) -> Result<ExamAttempt, AppError> {
158+ self.finished_at = Some(Timestamp::now());
159+ let updated: Option<ExamAttempt> = db.update(self.id.record()).content(self).await?;
160+ updated.ok_or(AppError::NotFound)
161+ }
162+
163+ pub async fn read_for_user(
164+ exam: &ExamId,
165+ user: &UserId,
166+ db: &Database,
167+ ) -> Result<Option<ExamAttempt>, AppError> {
168+ Ok(db
169+ .select(ExamAttemptId::composite(exam, user).record())
170+ .await?)
171+ }
172+
173+ pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamAttempt>, AppError> {
174+ let mut result = db
175+ .query("SELECT * FROM exam_attempt WHERE exam = $ex ORDER BY id DESC")
176+ .bind(("ex", exam.record()))
177+ .await?
178+ .check()?;
179+ Ok(result.take::<Vec<ExamAttempt>>(0)?)
180+ }
181+
182+ /// Whether anyone has started this exam — the gate that freezes `mode`
183+ /// edits once an attempt exists.
184+ pub async fn any_for_exam(exam: &ExamId, db: &Database) -> Result<bool, AppError> {
185+ let mut result = db
186+ .query("SELECT VALUE id FROM exam_attempt WHERE exam = $ex LIMIT 1")
187+ .bind(("ex", exam.record()))
188+ .await?
189+ .check()?;
190+ Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
191+ }
192+}
src/domain/exam_question.rsadded+381 -0
@@ -0,0 +1,381 @@
1+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2+use ulid::Ulid;
3+
4+use crate::constant::{
5+ MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, MIN_QUESTION_CHOICES,
6+};
7+use crate::database::{Database, EXAM_QUESTION_TABLE};
8+use crate::domain::exam::ExamId;
9+use crate::error::{AppError, ValidationError};
10+use crate::validate::{validate_question_kind, validate_question_points, validate_required};
11+
12+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
13+pub struct ExamQuestionId(RecordId);
14+
15+impl ExamQuestionId {
16+ pub fn generate() -> Self {
17+ Self(RecordId::new(EXAM_QUESTION_TABLE, Ulid::new().to_string()))
18+ }
19+
20+ pub fn from_key(key: &str) -> Self {
21+ Self(RecordId::new(EXAM_QUESTION_TABLE, key))
22+ }
23+
24+ pub fn record(&self) -> RecordId {
25+ self.0.clone()
26+ }
27+
28+ pub fn key(&self) -> &str {
29+ match &self.0.key {
30+ RecordIdKey::String(key) => key,
31+ _ => "",
32+ }
33+ }
34+}
35+
36+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
37+pub struct QuestionText(String);
38+
39+impl QuestionText {
40+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
41+ validate_required("text", value, MAX_QUESTION_TEXT_LEN)?;
42+ Ok(Self(value.to_string()))
43+ }
44+
45+ pub fn as_str(&self) -> &str {
46+ &self.0
47+ }
48+}
49+
50+/// A validated question kind: `choice` (pick one option, auto-scorable) or
51+/// `text` (free text, judged by the grader).
52+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
53+pub struct QuestionKind(String);
54+
55+impl QuestionKind {
56+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
57+ validate_question_kind(value)?;
58+ Ok(Self(value.to_string()))
59+ }
60+
61+ pub fn as_str(&self) -> &str {
62+ &self.0
63+ }
64+}
65+
66+/// A validated question weight in the auto-score, held to
67+/// `[MIN_QUESTION_POINTS, MAX_QUESTION_POINTS]`.
68+#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)]
69+pub struct QuestionPoints(i64);
70+
71+impl QuestionPoints {
72+ pub fn try_new(value: i64) -> Result<Self, ValidationError> {
73+ validate_question_points(value)?;
74+ Ok(Self(value))
75+ }
76+
77+ pub fn as_i64(&self) -> i64 {
78+ self.0
79+ }
80+}
81+
82+/// One option of a choice question: non-blank, at most `MAX_CHOICE_TEXT_LEN`
83+/// characters.
84+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
85+pub struct ChoiceText(String);
86+
87+impl ChoiceText {
88+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
89+ validate_required("choice", value, MAX_CHOICE_TEXT_LEN)?;
90+ Ok(Self(value.to_string()))
91+ }
92+
93+ pub fn as_str(&self) -> &str {
94+ &self.0
95+ }
96+}
97+
98+/// The kind-dependent fields of a question, validated as a unit — they only
99+/// make sense together. `try_new` is the sole constructor, so a `QuestionSpec`
100+/// in hand always satisfies:
101+///
102+/// - `text` → no `choices`, no `correct` (the grader judges the answer),
103+/// - `choice` → 2–10 `choices` plus a `correct` index into them.
104+#[derive(Debug, Clone)]
105+pub struct QuestionSpec {
106+ kind: QuestionKind,
107+ choices: Option<Vec<ChoiceText>>,
108+ correct: Option<i64>,
109+}
110+
111+impl QuestionSpec {
112+ pub fn try_new(
113+ kind: QuestionKind,
114+ choices: Option<Vec<String>>,
115+ correct: Option<i64>,
116+ ) -> Result<Self, ValidationError> {
117+ let invalid = |field, reason| ValidationError::Invalid { field, reason };
118+ let choices = match (kind.as_str(), choices) {
119+ ("text", Some(_)) => {
120+ return Err(invalid("choices", "only choice questions take choices"));
121+ }
122+ ("text", None) => {
123+ if correct.is_some() {
124+ return Err(invalid(
125+ "correct",
126+ "only choice questions take a correct index",
127+ ));
128+ }
129+ None
130+ }
131+ (_, None) => return Err(invalid("choices", "required for a choice question")),
132+ (_, Some(choices)) => {
133+ if !(MIN_QUESTION_CHOICES..=MAX_QUESTION_CHOICES).contains(&choices.len()) {
134+ return Err(invalid("choices", "must list 2 to 10 choices"));
135+ }
136+ let Some(correct) = correct else {
137+ return Err(invalid("correct", "required for a choice question"));
138+ };
139+ if !(0..choices.len() as i64).contains(&correct) {
140+ return Err(invalid("correct", "must index one of the choices"));
141+ }
142+ Some(
143+ choices
144+ .iter()
145+ .map(|choice| ChoiceText::try_new(choice))
146+ .collect::<Result<Vec<_>, _>>()?,
147+ )
148+ }
149+ };
150+ Ok(Self {
151+ kind,
152+ choices,
153+ correct,
154+ })
155+ }
156+
157+ pub fn get_kind(&self) -> &QuestionKind {
158+ &self.kind
159+ }
160+}
161+
162+/// One question of an exam. Order within the exam is the id's ULID order
163+/// (creation order); the kind-dependent columns always satisfy the
164+/// [`QuestionSpec`] invariants because every write goes through one.
165+#[derive(Debug, Clone, SurrealValue)]
166+pub struct ExamQuestion {
167+ id: ExamQuestionId,
168+ exam: ExamId,
169+ text: QuestionText,
170+ kind: QuestionKind,
171+ points: QuestionPoints,
172+ choices: Option<Vec<ChoiceText>>,
173+ correct: Option<i64>,
174+}
175+
176+impl ExamQuestion {
177+ pub fn get_id(&self) -> &ExamQuestionId {
178+ &self.id
179+ }
180+
181+ pub fn get_exam(&self) -> &ExamId {
182+ &self.exam
183+ }
184+
185+ pub fn get_text(&self) -> &QuestionText {
186+ &self.text
187+ }
188+
189+ pub fn get_kind(&self) -> &QuestionKind {
190+ &self.kind
191+ }
192+
193+ pub fn get_points(&self) -> QuestionPoints {
194+ self.points
195+ }
196+
197+ pub fn get_choices(&self) -> Option<&[ChoiceText]> {
198+ self.choices.as_deref()
199+ }
200+
201+ pub fn get_correct(&self) -> Option<i64> {
202+ self.correct
203+ }
204+
205+ /// The stored kind-dependent fields as the validated bundle (for
206+ /// merge-on-update). Bypasses `try_new`: the fields were written through a
207+ /// `QuestionSpec`, so the invariants already hold.
208+ pub fn spec(&self) -> QuestionSpec {
209+ QuestionSpec {
210+ kind: self.kind.clone(),
211+ choices: self.choices.clone(),
212+ correct: self.correct,
213+ }
214+ }
215+
216+ pub async fn create(
217+ exam: &ExamId,
218+ text: QuestionText,
219+ points: QuestionPoints,
220+ spec: QuestionSpec,
221+ db: &Database,
222+ ) -> Result<ExamQuestion, AppError> {
223+ let question = ExamQuestion {
224+ id: ExamQuestionId::generate(),
225+ exam: exam.clone(),
226+ text,
227+ points,
228+ kind: spec.kind,
229+ choices: spec.choices,
230+ correct: spec.correct,
231+ };
232+ let created: Option<ExamQuestion> =
233+ db.create(question.id.record()).content(question).await?;
234+ created.ok_or_else(|| AppError::Internal("failed to create exam question".into()))
235+ }
236+
237+ pub async fn read(
238+ id: &ExamQuestionId,
239+ db: &Database,
240+ ) -> Result<Option<ExamQuestion>, AppError> {
241+ Ok(db.select(id.record()).await?)
242+ }
243+
244+ /// The exam's questions in presentation order (ULID ids sort by creation).
245+ pub async fn list_for_exam(
246+ exam: &ExamId,
247+ db: &Database,
248+ ) -> Result<Vec<ExamQuestion>, AppError> {
249+ let mut result = db
250+ .query("SELECT * FROM exam_question WHERE exam = $ex ORDER BY id ASC")
251+ .bind(("ex", exam.record()))
252+ .await?
253+ .check()?;
254+ Ok(result.take::<Vec<ExamQuestion>>(0)?)
255+ }
256+
257+ pub async fn update(
258+ mut self,
259+ text: QuestionText,
260+ points: QuestionPoints,
261+ spec: QuestionSpec,
262+ db: &Database,
263+ ) -> Result<ExamQuestion, AppError> {
264+ self.text = text;
265+ self.points = points;
266+ self.kind = spec.kind;
267+ self.choices = spec.choices;
268+ self.correct = spec.correct;
269+ let updated: Option<ExamQuestion> = db.update(self.id.record()).content(self).await?;
270+ updated.ok_or(AppError::NotFound)
271+ }
272+
273+ /// Delete the question and cascade-remove its answers, so no answer row
274+ /// can point at a missing question.
275+ pub async fn delete(self, db: &Database) -> Result<ExamQuestion, AppError> {
276+ db.query("DELETE exam_answer WHERE question = $q")
277+ .bind(("q", self.id.record()))
278+ .await?
279+ .check()?;
280+ let deleted: Option<ExamQuestion> = db.delete(self.id.record()).await?;
281+ deleted.ok_or(AppError::NotFound)
282+ }
283+
284+ /// A question constructed without a database, for pure-function tests.
285+ #[cfg(test)]
286+ pub fn test_new(exam: &ExamId, text: &str, points: i64, spec: QuestionSpec) -> ExamQuestion {
287+ ExamQuestion {
288+ id: ExamQuestionId::generate(),
289+ exam: exam.clone(),
290+ text: QuestionText::try_new(text).unwrap(),
291+ points: QuestionPoints::try_new(points).unwrap(),
292+ kind: spec.kind,
293+ choices: spec.choices,
294+ correct: spec.correct,
295+ }
296+ }
297+}
298+
299+#[cfg(test)]
300+mod tests {
301+ use super::*;
302+
303+ fn kind(value: &str) -> QuestionKind {
304+ QuestionKind::try_new(value).unwrap()
305+ }
306+
307+ fn two_choices() -> Option<Vec<String>> {
308+ Some(vec!["yes".into(), "no".into()])
309+ }
310+
311+ #[tokio::test]
312+ async fn text_is_required() {
313+ assert!(QuestionText::try_new("What is 2 + 2?").is_ok());
314+ assert!(QuestionText::try_new("").is_err());
315+ assert!(QuestionText::try_new(" ").is_err());
316+ assert!(QuestionText::try_new(&"x".repeat(2_001)).is_err());
317+ }
318+
319+ #[tokio::test]
320+ async fn kind_must_be_known() {
321+ for value in ["choice", "text"] {
322+ assert_eq!(QuestionKind::try_new(value).unwrap().as_str(), value);
323+ }
324+ assert!(QuestionKind::try_new("essay").is_err());
325+ }
326+
327+ #[tokio::test]
328+ async fn points_range_is_enforced() {
329+ assert_eq!(QuestionPoints::try_new(1).unwrap().as_i64(), 1);
330+ assert_eq!(QuestionPoints::try_new(100).unwrap().as_i64(), 100);
331+ assert!(QuestionPoints::try_new(0).is_err());
332+ assert!(QuestionPoints::try_new(101).is_err());
333+ }
334+
335+ #[tokio::test]
336+ async fn choice_text_is_required() {
337+ assert!(ChoiceText::try_new("yes").is_ok());
338+ assert!(ChoiceText::try_new("").is_err());
339+ assert!(ChoiceText::try_new(" ").is_err());
340+ assert!(ChoiceText::try_new(&"x".repeat(501)).is_err());
341+ }
342+
343+ #[tokio::test]
344+ async fn spec_invariants_hold() {
345+ // Text questions carry neither choices nor a correct index.
346+ assert!(QuestionSpec::try_new(kind("text"), None, None).is_ok());
347+ assert!(QuestionSpec::try_new(kind("text"), two_choices(), None).is_err());
348+ assert!(QuestionSpec::try_new(kind("text"), None, Some(0)).is_err());
349+ assert!(QuestionSpec::try_new(kind("text"), two_choices(), Some(0)).is_err());
350+
351+ // Choice questions need both.
352+ assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(0)).is_ok());
353+ assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(1)).is_ok());
354+ assert!(QuestionSpec::try_new(kind("choice"), None, None).is_err());
355+ assert!(QuestionSpec::try_new(kind("choice"), None, Some(0)).is_err());
356+ assert!(QuestionSpec::try_new(kind("choice"), two_choices(), None).is_err());
357+ }
358+
359+ #[tokio::test]
360+ async fn spec_correct_must_index_a_choice() {
361+ assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(-1)).is_err());
362+ assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(2)).is_err());
363+ }
364+
365+ #[tokio::test]
366+ async fn spec_choice_count_is_bounded() {
367+ let n = |count: usize| Some(vec!["option".to_string(); count]);
368+ assert!(QuestionSpec::try_new(kind("choice"), n(1), Some(0)).is_err());
369+ assert!(QuestionSpec::try_new(kind("choice"), n(2), Some(0)).is_ok());
370+ assert!(QuestionSpec::try_new(kind("choice"), n(10), Some(0)).is_ok());
371+ assert!(QuestionSpec::try_new(kind("choice"), n(11), Some(0)).is_err());
372+ }
373+
374+ #[tokio::test]
375+ async fn spec_rejects_blank_or_oversized_choices() {
376+ let blank = Some(vec!["yes".to_string(), " ".to_string()]);
377+ assert!(QuestionSpec::try_new(kind("choice"), blank, Some(0)).is_err());
378+ let oversized = Some(vec!["yes".to_string(), "x".repeat(501)]);
379+ assert!(QuestionSpec::try_new(kind("choice"), oversized, Some(0)).is_err());
380+ }
381+}
src/domain/mod.rsmodified+3 -0
@@ -7,6 +7,9 @@ pub mod course;
7 pub mod enrollment;7 pub mod enrollment;
8 pub mod event;8 pub mod event;
9 pub mod exam;9 pub mod exam;
10+pub mod exam_answer;
11+pub mod exam_attempt;
12+pub mod exam_question;
10 pub mod exam_result;13 pub mod exam_result;
11 pub mod note;14 pub mod note;
12 pub mod profile;15 pub mod profile;
src/domain/user.rsmodified+34 -0
@@ -259,6 +259,40 @@ impl User {
259 Ok(result.take::<Vec<User>>(0)?)259 Ok(result.take::<Vec<User>>(0)?)
260 }260 }
261 261
262+ /// Fetch the users behind `ids` in one query. Ids with no row are simply
263+ /// absent from the result — the caller decides how to degrade.
264+ pub async fn list_by_ids(ids: &[UserId], db: &Database) -> Result<Vec<User>, AppError> {
265+ if ids.is_empty() {
266+ return Ok(Vec::new());
267+ }
268+ let records: Vec<RecordId> = ids.iter().map(UserId::record).collect();
269+ let mut result = db
270+ .query("SELECT * FROM user WHERE id IN $ids")
271+ .bind(("ids", records))
272+ .await?
273+ .check()?;
274+ Ok(result.take::<Vec<User>>(0)?)
275+ }
276+
277+ /// Case-insensitive fragment search over username, name, and surname —
278+ /// backs the user pickers. Capped at 10 rows: pickers show a short list,
279+ /// and the cap keeps an over-broad fragment from hauling the whole table.
280+ pub async fn search(query: &str, db: &Database) -> Result<Vec<User>, AppError> {
281+ let needle = query.trim().to_lowercase();
282+ let mut result = db
283+ .query(
284+ "SELECT * FROM user WHERE \
285+ string::lowercase(username) CONTAINS $q \
286+ OR string::lowercase(name ?? '') CONTAINS $q \
287+ OR string::lowercase(surname ?? '') CONTAINS $q \
288+ ORDER BY username LIMIT 10",
289+ )
290+ .bind(("q", needle))
291+ .await?
292+ .check()?;
293+ Ok(result.take::<Vec<User>>(0)?)
294+ }
295+
262 /// Overwrite this user's role. The caller is responsible for authorizing it.296 /// Overwrite this user's role. The caller is responsible for authorizing it.
263 pub async fn set_role(mut self, role: Role, db: &Database) -> Result<User, AppError> {297 pub async fn set_role(mut self, role: Role, db: &Database) -> Result<User, AppError> {
264 self.role = role;298 self.role = role;
src/lib.rsmodified+1 -1
@@ -42,7 +42,7 @@ use crate::state::AppState;
42 (name = "notes", description = "Per-user notes CRUD"),42 (name = "notes", description = "Per-user notes CRUD"),
43 (name = "events", description = "Events and attendance"),43 (name = "events", description = "Events and attendance"),
44 (name = "courses", description = "Courses, enrollment, and course exams"),44 (name = "courses", description = "Courses, enrollment, and course exams"),
45- (name = "exams", description = "Exams (per course, weighted) and student results"),45+ (name = "exams", description = "Exams (per course, weighted): results, sync/async scheduling, attempts, questions/answers, and live monitoring. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames, see the README's \"Taking an exam\" section for the protocol"),
46 (name = "marks", description = "Weighted mark reports per course and overall"),46 (name = "marks", description = "Weighted mark reports per course and overall"),
47 ),47 ),
48 )]48 )]
src/validate.rsmodified+87 -3
@@ -2,9 +2,10 @@
2 //! the value, so an existing newtype is always valid (parse, don't validate).2 //! the value, so an existing newtype is always valid (parse, don't validate).
3 3
4 use crate::constant::{4 use crate::constant::{
5- ATTENDANCE_STATUSES, EXAM_KINDS, MAX_EMAIL_LEN, MAX_EXAM_WEIGHT, MAX_MARK, MAX_PASSWORD_LEN,5+ ATTENDANCE_STATUSES, EXAM_KINDS, EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_DURATION_MS,
6- MAX_PHONE_DIGITS, MAX_USERNAME_LEN, MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN,6+ MAX_EXAM_WEIGHT, MAX_MARK, MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS,
7- MIN_PHONE_DIGITS, MIN_USERNAME_LEN,7+ MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN,
8+ MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS,
8 };9 };
9 use crate::error::ValidationError;10 use crate::error::ValidationError;
10 11
@@ -179,6 +180,50 @@ pub fn validate_exam_kind(value: &str) -> Result<(), ValidationError> {
179 }180 }
180 }181 }
181 182
183+pub fn validate_exam_mode(value: &str) -> Result<(), ValidationError> {
184+ if EXAM_MODES.contains(&value) {
185+ Ok(())
186+ } else {
187+ Err(ValidationError::Invalid {
188+ field: "mode",
189+ reason: "must be one of: sync, async",
190+ })
191+ }
192+}
193+
194+pub fn validate_exam_duration(value: i64) -> Result<(), ValidationError> {
195+ if (MIN_EXAM_DURATION_MS..=MAX_EXAM_DURATION_MS).contains(&value) {
196+ Ok(())
197+ } else {
198+ Err(ValidationError::Invalid {
199+ field: "duration_ms",
200+ reason: "must be between 60000 (1 minute) and 86400000 (24 hours) milliseconds",
201+ })
202+ }
203+}
204+
205+pub fn validate_question_kind(value: &str) -> Result<(), ValidationError> {
206+ if QUESTION_KINDS.contains(&value) {
207+ Ok(())
208+ } else {
209+ Err(ValidationError::Invalid {
210+ field: "kind",
211+ reason: "must be one of: choice, text",
212+ })
213+ }
214+}
215+
216+pub fn validate_question_points(value: i64) -> Result<(), ValidationError> {
217+ if (MIN_QUESTION_POINTS..=MAX_QUESTION_POINTS).contains(&value) {
218+ Ok(())
219+ } else {
220+ Err(ValidationError::Invalid {
221+ field: "points",
222+ reason: "must be between 1 and 100",
223+ })
224+ }
225+}
226+
182 pub fn validate_mark(value: i64) -> Result<(), ValidationError> {227 pub fn validate_mark(value: i64) -> Result<(), ValidationError> {
183 if (MIN_MARK..=MAX_MARK).contains(&value) {228 if (MIN_MARK..=MAX_MARK).contains(&value) {
184 Ok(())229 Ok(())
@@ -294,6 +339,45 @@ mod tests {
294 assert!(validate_exam_kind("").is_err());339 assert!(validate_exam_kind("").is_err());
295 }340 }
296 341
342+ #[tokio::test]
343+ async fn exam_mode_rules() {
344+ for mode in ["sync", "async"] {
345+ assert!(validate_exam_mode(mode).is_ok());
346+ }
347+ assert!(validate_exam_mode("live").is_err());
348+ assert!(validate_exam_mode("").is_err());
349+ }
350+
351+ #[tokio::test]
352+ async fn exam_duration_rules() {
353+ assert!(validate_exam_duration(MIN_EXAM_DURATION_MS).is_ok());
354+ assert!(validate_exam_duration(90 * 60 * 1000).is_ok());
355+ assert!(validate_exam_duration(MAX_EXAM_DURATION_MS).is_ok());
356+ assert!(validate_exam_duration(MIN_EXAM_DURATION_MS - 1).is_err());
357+ assert!(validate_exam_duration(MAX_EXAM_DURATION_MS + 1).is_err());
358+ assert!(validate_exam_duration(0).is_err());
359+ assert!(validate_exam_duration(-1).is_err());
360+ }
361+
362+ #[tokio::test]
363+ async fn question_kind_rules() {
364+ for kind in ["choice", "text"] {
365+ assert!(validate_question_kind(kind).is_ok());
366+ }
367+ assert!(validate_question_kind("essay").is_err());
368+ assert!(validate_question_kind("").is_err());
369+ }
370+
371+ #[tokio::test]
372+ async fn question_points_rules() {
373+ for points in [1, 50, 100] {
374+ assert!(validate_question_points(points).is_ok());
375+ }
376+ assert!(validate_question_points(0).is_err());
377+ assert!(validate_question_points(-1).is_err());
378+ assert!(validate_question_points(101).is_err());
379+ }
380+
297 #[tokio::test]381 #[tokio::test]
298 async fn mark_rules() {382 async fn mark_rules() {
299 for mark in [0, 1, 50, 99, 100] {383 for mark in [0, 1, 50, 99, 100] {
src/web/courses.rsmodified+50 -11
@@ -1,3 +1,5 @@
1+use std::collections::HashMap;
2+
1 use axum::Json;3 use axum::Json;
2 use axum::extract::{Path, State};4 use axum::extract::{Path, State};
3 use axum::http::StatusCode;5 use axum::http::StatusCode;
@@ -8,13 +10,16 @@ use utoipa_axum::routes;
8 10
9 use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle};11 use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle};
10 use crate::domain::enrollment::Enrollment;12 use crate::domain::enrollment::Enrollment;
11-use crate::domain::exam::{Exam, ExamDescription, ExamKind, ExamTitle, ExamWeight};13+use crate::domain::exam::{
14+ Exam, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, ExamWeight,
15+};
12 use crate::domain::role::Role;16 use crate::domain::role::Role;
17+use crate::domain::timestamp::Timestamp;
13 use crate::domain::user::{User, UserId};18 use crate::domain::user::{User, UserId};
14 use crate::error::{AppError, ErrorResponse, ValidationError};19 use crate::error::{AppError, ErrorResponse, ValidationError};
15 use crate::state::AppState;20 use crate::state::AppState;
16 21
17-use super::{CourseResponse, CurrentUser, ExamResponse, RequireTeacher};22+use super::{CourseResponse, CurrentUser, ExamResponse, PersonRef, RequireTeacher, person_map};
18 23
19 pub fn routes() -> OpenApiRouter<AppState> {24 pub fn routes() -> OpenApiRouter<AppState> {
20 OpenApiRouter::new()25 OpenApiRouter::new()
@@ -58,23 +63,39 @@ struct CreateExamInCourse {
58 /// How many times this exam counts into the course average, `1`–`100`.63 /// How many times this exam counts into the course average, `1`–`100`.
59 #[schema(example = 3)]64 #[schema(example = 3)]
60 weight: i64,65 weight: i64,
66+ /// `sync` (one fixed window for everyone) or `async` (each student starts
67+ /// inside the window and gets `duration_ms`). Omit for an unscheduled,
68+ /// offline-graded exam.
69+ #[schema(example = "sync")]
70+ mode: Option<String>,
71+ /// Window open, UTC unix-milliseconds. Required with `mode`.
72+ #[schema(example = 1_752_275_000_000_i64)]
73+ starts_at: Option<i64>,
74+ /// Window close, UTC unix-milliseconds. Required with `mode`.
75+ ends_at: Option<i64>,
76+ /// Per-student time budget, milliseconds — required for (and exclusive to)
77+ /// `async` exams.
78+ #[schema(example = 5_400_000_i64)]
79+ duration_ms: Option<i64>,
61 }80 }
62 81
63 #[derive(Serialize, ToSchema)]82 #[derive(Serialize, ToSchema)]
64 struct EnrollmentResponse {83 struct EnrollmentResponse {
65 id: String,84 id: String,
66 course: String,85 course: String,
67- user: String,86+ /// The enrolled student.
68- enrolled_by: String,87+ user: PersonRef,
88+ /// Who enrolled them.
89+ enrolled_by: PersonRef,
69 }90 }
70 91
71 impl EnrollmentResponse {92 impl EnrollmentResponse {
72- fn new(enrollment: &Enrollment) -> Self {93+ fn new(enrollment: &Enrollment, people: &HashMap<String, PersonRef>) -> Self {
73 Self {94 Self {
74 id: enrollment.get_id().key().to_string(),95 id: enrollment.get_id().key().to_string(),
75 course: enrollment.get_course().key().to_string(),96 course: enrollment.get_course().key().to_string(),
76- user: enrollment.get_user().key().to_string(),97+ user: PersonRef::resolve(people, enrollment.get_user()),
77- enrolled_by: enrollment.get_enrolled_by().key().to_string(),98+ enrolled_by: PersonRef::resolve(people, enrollment.get_enrolled_by()),
78 }99 }
79 }100 }
80 }101 }
@@ -288,15 +309,16 @@ async fn enroll(
288 }309 }
289 310
290 let target = UserId::from_key(&req.user_id);311 let target = UserId::from_key(&req.user_id);
291- if User::read(&target, &st.db).await?.is_none() {312+ let Some(target_user) = User::read(&target, &st.db).await? else {
292 return Err(AppError::Validation(ValidationError::Invalid {313 return Err(AppError::Validation(ValidationError::Invalid {
293 field: "user_id",314 field: "user_id",
294 reason: "target user does not exist",315 reason: "target user does not exist",
295 }));316 }));
296- }317+ };
297 318
298 let enrollment = Enrollment::enroll(course.get_id(), &target, user.get_id(), &st.db).await?;319 let enrollment = Enrollment::enroll(course.get_id(), &target, user.get_id(), &st.db).await?;
299- Ok(Json(EnrollmentResponse::new(&enrollment)))320+ let people = PersonRef::map_of(&[&target_user, &user]);
321+ Ok(Json(EnrollmentResponse::new(&enrollment, &people)))
300 }322 }
301 323
302 /// List a course's roster. Requires teacher+ — students see their own courses324 /// List a course's roster. Requires teacher+ — students see their own courses
@@ -325,8 +347,18 @@ async fn list_roster(
325 .await?347 .await?
326 .ok_or(AppError::NotFound)?;348 .ok_or(AppError::NotFound)?;
327 let enrollments = Enrollment::list_for_course(&course_id, &st.db).await?;349 let enrollments = Enrollment::list_for_course(&course_id, &st.db).await?;
350+ let people = person_map(
351+ enrollments
352+ .iter()
353+ .flat_map(|e| [e.get_user().clone(), e.get_enrolled_by().clone()]),
354+ &st.db,
355+ )
356+ .await?;
328 Ok(Json(357 Ok(Json(
329- enrollments.iter().map(EnrollmentResponse::new).collect(),358+ enrollments
359+ .iter()
360+ .map(|e| EnrollmentResponse::new(e, &people))
361+ .collect(),
330 ))362 ))
331 }363 }
332 364
@@ -407,6 +439,12 @@ async fn create_exam_in_course(
407 let description = ExamDescription::try_new(&req.description.unwrap_or_default())?;439 let description = ExamDescription::try_new(&req.description.unwrap_or_default())?;
408 let kind = ExamKind::try_new(&req.kind)?;440 let kind = ExamKind::try_new(&req.kind)?;
409 let weight = ExamWeight::try_new(req.weight)?;441 let weight = ExamWeight::try_new(req.weight)?;
442+ let schedule = ExamSchedule::try_new(
443+ req.mode.as_deref().map(ExamMode::try_new).transpose()?,
444+ req.starts_at.map(Timestamp::from_millis),
445+ req.ends_at.map(Timestamp::from_millis),
446+ req.duration_ms.map(ExamDuration::try_new).transpose()?,
447+ )?;
410 let exam = Exam::create(448 let exam = Exam::create(
411 user.get_id(),449 user.get_id(),
412 course.get_id(),450 course.get_id(),
@@ -414,6 +452,7 @@ async fn create_exam_in_course(
414 description,452 description,
415 kind,453 kind,
416 weight,454 weight,
455+ schedule,
417 &st.db,456 &st.db,
418 )457 )
419 .await?;458 .await?;
src/web/dto.rsmodified+87 -2
@@ -1,12 +1,16 @@
1 //! Response DTOs shared across more than one handler module.1 //! Response DTOs shared across more than one handler module.
2 2
3+use std::collections::{HashMap, HashSet};
4+
3 use serde::Serialize;5 use serde::Serialize;
4 use utoipa::ToSchema;6 use utoipa::ToSchema;
5 7
8+use crate::database::Database;
6 use crate::domain::course::Course;9 use crate::domain::course::Course;
7 use crate::domain::exam::Exam;10 use crate::domain::exam::Exam;
8 use crate::domain::role::Role as DomainRole;11 use crate::domain::role::Role as DomainRole;
9-use crate::domain::user::User;12+use crate::domain::user::{User, UserId};
13+use crate::error::AppError;
10 14
11 /// The four access roles, lowest to highest privilege. The web-facing mirror of15 /// The four access roles, lowest to highest privilege. The web-facing mirror of
12 /// [`crate::domain::role::Role`] — it carries the serde + OpenAPI derives (which16 /// [`crate::domain::role::Role`] — it carries the serde + OpenAPI derives (which
@@ -32,6 +36,72 @@ impl From<DomainRole> for Role {
32 }36 }
33 }37 }
34 38
39+/// How another person appears inside a response: enough to say *who* without
40+/// leaking contact details. Rows that reference users (enrollments, attendance,
41+/// exam results) embed this instead of a bare id, so no client ever has to
42+/// show a raw ULID to a human.
43+#[derive(Serialize, Clone, ToSchema)]
44+pub struct PersonRef {
45+ #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
46+ pub id: String,
47+ #[schema(example = "ada")]
48+ pub username: String,
49+ /// `"Name Surname"` when the profile carries either; `null` otherwise.
50+ #[schema(example = "Ada Lovelace")]
51+ pub display_name: Option<String>,
52+}
53+
54+impl PersonRef {
55+ pub fn new(user: &User) -> Self {
56+ let full: Vec<&str> = [user.get_name(), user.get_surname()]
57+ .into_iter()
58+ .flatten()
59+ .map(|part| part.as_str())
60+ .collect();
61+ Self {
62+ id: user.get_id().key().to_string(),
63+ username: user.get_username().as_str().to_string(),
64+ display_name: (!full.is_empty()).then(|| full.join(" ")),
65+ }
66+ }
67+
68+ /// Key already-loaded users by id — for handlers that hold the rows anyway.
69+ pub fn map_of(users: &[&User]) -> HashMap<String, PersonRef> {
70+ users
71+ .iter()
72+ .map(|user| (user.get_id().key().to_string(), PersonRef::new(user)))
73+ .collect()
74+ }
75+
76+ /// Look `id` up in `people`, degrading to the bare id when the row is gone
77+ /// — a stale reference renders oddly instead of failing the request.
78+ pub fn resolve(people: &HashMap<String, PersonRef>, id: &UserId) -> Self {
79+ people.get(id.key()).cloned().unwrap_or_else(|| Self {
80+ id: id.key().to_string(),
81+ username: id.key().to_string(),
82+ display_name: None,
83+ })
84+ }
85+}
86+
87+/// Load every user behind `ids` (duplicates collapsed, one query) and key
88+/// their `PersonRef`s by id — the join half of list endpoints that embed people.
89+pub async fn person_map(
90+ ids: impl IntoIterator<Item = UserId>,
91+ db: &Database,
92+) -> Result<HashMap<String, PersonRef>, AppError> {
93+ let mut seen = HashSet::new();
94+ let unique: Vec<UserId> = ids
95+ .into_iter()
96+ .filter(|id| seen.insert(id.key().to_string()))
97+ .collect();
98+ let users = User::list_by_ids(&unique, db).await?;
99+ Ok(users
100+ .iter()
101+ .map(|user| (user.get_id().key().to_string(), PersonRef::new(user)))
102+ .collect())
103+}
104+
35 /// Public shape of a user: id, username, role, and the optional personal info105 /// Public shape of a user: id, username, role, and the optional personal info
36 /// (`null` until filled in). Never carries the password hash. Shared by `auth`106 /// (`null` until filled in). Never carries the password hash. Shared by `auth`
37 /// (register/login/me) and `users` (listing, role and profile changes).107 /// (register/login/me) and `users` (listing, role and profile changes).
@@ -93,7 +163,9 @@ impl CourseResponse {
93 }163 }
94 164
95 /// Public shape of an exam. Shared by `exams` (CRUD/results) and `courses`165 /// Public shape of an exam. Shared by `exams` (CRUD/results) and `courses`
96-/// (in-course creation and listing).166+/// (in-course creation and listing). The schedule fields are all `null` for an
167+/// unscheduled (offline-graded) exam; see the create/update endpoints for the
168+/// rules tying them together.
97 #[derive(Serialize, ToSchema)]169 #[derive(Serialize, ToSchema)]
98 pub struct ExamResponse {170 pub struct ExamResponse {
99 pub id: String,171 pub id: String,
@@ -103,6 +175,15 @@ pub struct ExamResponse {
103 pub description: String,175 pub description: String,
104 pub kind: String,176 pub kind: String,
105 pub weight: i64,177 pub weight: i64,
178+ /// `sync` or `async`; `null` for an unscheduled exam.
179+ #[schema(example = "sync")]
180+ pub mode: Option<String>,
181+ /// Window open, UTC unix-milliseconds.
182+ pub starts_at: Option<i64>,
183+ /// Window close, UTC unix-milliseconds.
184+ pub ends_at: Option<i64>,
185+ /// Per-student time budget in milliseconds (async exams only).
186+ pub duration_ms: Option<i64>,
106 }187 }
107 188
108 impl ExamResponse {189 impl ExamResponse {
@@ -115,6 +196,10 @@ impl ExamResponse {
115 description: exam.get_description().as_str().to_string(),196 description: exam.get_description().as_str().to_string(),
116 kind: exam.get_kind().as_str().to_string(),197 kind: exam.get_kind().as_str().to_string(),
117 weight: exam.get_weight().as_i64(),198 weight: exam.get_weight().as_i64(),
199+ mode: exam.get_mode().map(|m| m.as_str().to_string()),
200+ starts_at: exam.get_starts_at().map(|t| t.as_millis()),
201+ ends_at: exam.get_ends_at().map(|t| t.as_millis()),
202+ duration_ms: exam.get_duration_ms().map(|d| d.as_millis()),
118 }203 }
119 }204 }
120 }205 }
src/web/events.rsmodified+28 -21
@@ -1,7 +1,9 @@
1+use std::collections::HashMap;
2+
1 use axum::Json;3 use axum::Json;
2 use axum::extract::{Path, State};4 use axum::extract::{Path, State};
3 use axum::http::StatusCode;5 use axum::http::StatusCode;
4-use serde::{Deserialize, Deserializer, Serialize};6+use serde::{Deserialize, Serialize};
5 use utoipa::ToSchema;7 use utoipa::ToSchema;
6 use utoipa_axum::router::OpenApiRouter;8 use utoipa_axum::router::OpenApiRouter;
7 use utoipa_axum::routes;9 use utoipa_axum::routes;
@@ -14,7 +16,7 @@ use crate::domain::user::{User, UserId};
14 use crate::error::{AppError, ErrorResponse, ValidationError};16 use crate::error::{AppError, ErrorResponse, ValidationError};
15 use crate::state::AppState;17 use crate::state::AppState;
16 18
17-use super::{CurrentUser, RequireTeacher};19+use super::{CurrentUser, PersonRef, RequireTeacher, person_map, set_or_clear};
18 20
19 pub fn routes() -> OpenApiRouter<AppState> {21 pub fn routes() -> OpenApiRouter<AppState> {
20 OpenApiRouter::new()22 OpenApiRouter::new()
@@ -35,16 +37,6 @@ struct CreateEvent {
35 ends_at: Option<i64>,37 ends_at: Option<i64>,
36 }38 }
37 39
38-/// Distinguishes an *absent* field from an explicit `null`: absent never
39-/// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the
40-/// stored value); `null` or a number lands here as `Some(inner)` (clear or set).
41-fn set_or_clear<'de, D>(de: D) -> Result<Option<Option<i64>>, D::Error>
42-where
43- D: Deserializer<'de>,
44-{
45- Option::<i64>::deserialize(de).map(Some)
46-}
47-
48 #[derive(Deserialize, ToSchema)]40 #[derive(Deserialize, ToSchema)]
49 struct UpdateEvent {41 struct UpdateEvent {
50 title: Option<String>,42 title: Option<String>,
@@ -120,19 +112,21 @@ fn check_time_range(
120 struct AttendanceResponse {112 struct AttendanceResponse {
121 id: String,113 id: String,
122 event: String,114 event: String,
123- user: String,115+ /// Whose attendance this row records.
116+ user: PersonRef,
124 status: String,117 status: String,
125- marked_by: String,118+ /// Who recorded it.
119+ marked_by: PersonRef,
126 }120 }
127 121
128 impl AttendanceResponse {122 impl AttendanceResponse {
129- fn new(attendance: &Attendance) -> Self {123+ fn new(attendance: &Attendance, people: &HashMap<String, PersonRef>) -> Self {
130 Self {124 Self {
131 id: attendance.get_id().key().to_string(),125 id: attendance.get_id().key().to_string(),
132 event: attendance.get_event().key().to_string(),126 event: attendance.get_event().key().to_string(),
133- user: attendance.get_user().key().to_string(),127+ user: PersonRef::resolve(people, attendance.get_user()),
134 status: attendance.get_status().as_str().to_string(),128 status: attendance.get_status().as_str().to_string(),
135- marked_by: attendance.get_marked_by().key().to_string(),129+ marked_by: PersonRef::resolve(people, attendance.get_marked_by()),
136 }130 }
137 }131 }
138 }132 }
@@ -355,15 +349,16 @@ async fn mark(
355 }349 }
356 350
357 // Target user must exist.351 // Target user must exist.
358- if User::read(&target, &st.db).await?.is_none() {352+ let Some(target_user) = User::read(&target, &st.db).await? else {
359 return Err(AppError::Validation(ValidationError::Invalid {353 return Err(AppError::Validation(ValidationError::Invalid {
360 field: "user_id",354 field: "user_id",
361 reason: "target user does not exist",355 reason: "target user does not exist",
362 }));356 }));
363- }357+ };
364 358
365 let attendance = Attendance::mark(&event_id, &target, status, user.get_id(), &st.db).await?;359 let attendance = Attendance::mark(&event_id, &target, status, user.get_id(), &st.db).await?;
366- Ok(Json(AttendanceResponse::new(&attendance)))360+ let people = PersonRef::map_of(&[&target_user, &user]);
361+ Ok(Json(AttendanceResponse::new(&attendance, &people)))
367 }362 }
368 363
369 /// List the attendance roster for an event.364 /// List the attendance roster for an event.
@@ -390,7 +385,19 @@ async fn list_attendance(
390 .await?385 .await?
391 .ok_or(AppError::NotFound)?;386 .ok_or(AppError::NotFound)?;
392 let roster = Attendance::list_for_event(&event_id, &st.db).await?;387 let roster = Attendance::list_for_event(&event_id, &st.db).await?;
393- Ok(Json(roster.iter().map(AttendanceResponse::new).collect()))388+ let people = person_map(
389+ roster
390+ .iter()
391+ .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]),
392+ &st.db,
393+ )
394+ .await?;
395+ Ok(Json(
396+ roster
397+ .iter()
398+ .map(|a| AttendanceResponse::new(a, &people))
399+ .collect(),
400+ ))
394 }401 }
395 402
396 /// Remove a user's attendance record from an event. Requires teacher+.403 /// Remove a user's attendance record from an event. Requires teacher+.
src/web/exam_ws.rsadded+315 -0
@@ -0,0 +1,315 @@
1+//! The student exam room: a WebSocket at `GET /exams/{id}/attempt/ws`.
2+//!
3+//! REST remains the fallback (`POST /exams/{id}/attempt/answers` etc.); the
4+//! socket exists so a sitting student gets autosave acks and a live,
5+//! server-judged countdown without polling. The teacher monitor deliberately
6+//! stays on SSE (`/exams/{id}/live/stream`) — it only ever flows one way.
7+//!
8+//! Wire protocol (JSON text frames):
9+//!
10+//! server → client
11+//! - `{"type":"state", status, deadline, remaining_ms, now, answered, question_count}`
12+//! on connect, every [`EXAM_WS_TICK_SECS`], and after each save
13+//! - `{"type":"saved", question_id, updated_at}` — an answer landed
14+//! - `{"type":"pong"}`
15+//! - `{"type":"finished", finished_at}` then Close — submitted (here or elsewhere)
16+//! - `{"type":"expired"}` then Close — the deadline passed mid-session
17+//! - `{"type":"error", message}` — bad JSON, unknown type, validation, deadline
18+//!
19+//! client → server
20+//! - `{"type":"answer", question_id, selected? | text?}`
21+//! - `{"type":"finish"}`
22+//! - `{"type":"ping"}`
23+//!
24+//! Every save and every tick re-reads the exam and attempt, so the deadline
25+//! stays server-authoritative: a teacher extending `ends_at` (or `duration_ms`)
26+//! mid-exam moves this room's clock on the next tick, and a stale client can
27+//! never write past its real deadline.
28+
29+use std::time::Duration;
30+
31+use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
32+use axum::extract::{Path, State};
33+use axum::response::Response;
34+use serde::Deserialize;
35+use serde_json::{Value, json};
36+
37+use crate::constant::EXAM_WS_TICK_SECS;
38+use crate::database::Database;
39+use crate::domain::enrollment::Enrollment;
40+use crate::domain::exam::{Exam, ExamId};
41+use crate::domain::exam_answer::ExamAnswer;
42+use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};
43+use crate::domain::exam_question::ExamQuestion;
44+use crate::domain::timestamp::Timestamp;
45+use crate::domain::user::UserId;
46+use crate::error::AppError;
47+use crate::state::AppState;
48+use crate::web::CurrentUser;
49+use crate::web::exams::{save_answer_checked, writable_attempt};
50+
51+/// What the client asked for, tagged by `type`.
52+#[derive(Deserialize)]
53+#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
54+enum ClientMessage {
55+ Answer {
56+ question_id: String,
57+ #[serde(default)]
58+ selected: Option<i64>,
59+ #[serde(default)]
60+ text: Option<String>,
61+ },
62+ Finish,
63+ Ping,
64+}
65+
66+/// Upgrade into the caller's exam room. All gates run *before* the upgrade so
67+/// a rejected client gets a proper HTTP status instead of an instant close:
68+/// unknown exam (404), unscheduled (409), not enrolled (403), no attempt yet
69+/// (404 — `POST /exams/{id}/attempt` first), submitted or expired (409).
70+pub async fn attempt_ws(
71+ State(st): State<AppState>,
72+ CurrentUser(user): CurrentUser,
73+ Path(id): Path<String>,
74+ ws: WebSocketUpgrade,
75+) -> Result<Response, AppError> {
76+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
77+ .await?
78+ .ok_or(AppError::NotFound)?;
79+ if exam.get_starts_at().is_none() {
80+ return Err(AppError::Conflict(
81+ "this exam is not scheduled — there is nothing to sit",
82+ ));
83+ }
84+ if Enrollment::read_for_user(exam.get_course(), user.get_id(), &st.db)
85+ .await?
86+ .is_none()
87+ {
88+ return Err(AppError::Forbidden(
89+ "you are not enrolled in this exam's course",
90+ ));
91+ }
92+ writable_attempt(&exam, user.get_id(), &st.db).await?;
93+
94+ let user_id = user.get_id().clone();
95+ Ok(ws.on_upgrade(move |socket| room(socket, st, exam, user_id)))
96+}
97+
98+/// The room loop: state ticks out, answer/finish/ping in, until the socket
99+/// closes or the attempt reaches a terminal state.
100+async fn room(mut socket: WebSocket, st: AppState, exam: Exam, user: UserId) {
101+ let exam_id = exam.get_id().clone();
102+ let mut tick = tokio::time::interval(Duration::from_secs(EXAM_WS_TICK_SECS));
103+ loop {
104+ tokio::select! {
105+ // First tick fires immediately — the connect-time state frame.
106+ _ = tick.tick() => {
107+ if push_state(&mut socket, &exam_id, &user, &st.db).await.is_err() {
108+ break;
109+ }
110+ }
111+ incoming = socket.recv() => {
112+ let text = match incoming {
113+ Some(Ok(Message::Text(text))) => text,
114+ // Ping/pong frames are answered by axum itself; other
115+ // non-text frames carry nothing for this protocol.
116+ Some(Ok(Message::Close(_))) | Some(Err(_)) | None => break,
117+ Some(Ok(_)) => continue,
118+ };
119+ if handle_message(&mut socket, text.as_str(), &exam_id, &user, &st.db)
120+ .await
121+ .is_err()
122+ {
123+ break;
124+ }
125+ }
126+ }
127+ }
128+ // Best-effort closing handshake — a bare TCP teardown reads as an error
129+ // on the client; a Close frame reads as "the room is over".
130+ let _ = socket.send(Message::Close(None)).await;
131+}
132+
133+/// Errors that end the room: the peer went away, or the attempt reached a
134+/// terminal state and the close frame was sent.
135+struct RoomClosed;
136+
137+async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> {
138+ socket
139+ .send(Message::Text(frame.to_string().into()))
140+ .await
141+ .map_err(|_| RoomClosed)
142+}
143+
144+/// Re-read everything, push a `state` frame, and close the room (after a
145+/// `finished`/`expired` notice) once the attempt is no longer in progress.
146+async fn push_state(
147+ socket: &mut WebSocket,
148+ exam: &ExamId,
149+ user: &UserId,
150+ db: &Database,
151+) -> Result<(), RoomClosed> {
152+ let (frame, status, finished_at) = match state_frame(exam, user, db).await {
153+ Ok(state) => state,
154+ // The exam vanished mid-room (deleted) or the db hiccuped: nothing
155+ // sensible left to serve.
156+ Err(err) => {
157+ tracing::warn!("exam room state failed: {err}");
158+ let _ = send(
159+ socket,
160+ json!({ "type": "error", "message": "state unavailable" }),
161+ )
162+ .await;
163+ return Err(RoomClosed);
164+ }
165+ };
166+ send(socket, frame).await?;
167+ match status {
168+ AttemptStatus::InProgress => Ok(()),
169+ AttemptStatus::Submitted => {
170+ send(
171+ socket,
172+ json!({ "type": "finished", "finished_at": finished_at }),
173+ )
174+ .await?;
175+ Err(RoomClosed)
176+ }
177+ AttemptStatus::Expired => {
178+ send(socket, json!({ "type": "expired" })).await?;
179+ Err(RoomClosed)
180+ }
181+ }
182+}
183+
184+/// One server-judged snapshot of the attempt, shaped like the REST
185+/// `AttemptResponse`'s live fields.
186+async fn state_frame(
187+ exam: &ExamId,
188+ user: &UserId,
189+ db: &Database,
190+) -> Result<(Value, AttemptStatus, Option<i64>), AppError> {
191+ let exam = Exam::read(exam, db).await?.ok_or(AppError::NotFound)?;
192+ let attempt = ExamAttempt::read_for_user(exam.get_id(), user, db)
193+ .await?
194+ .ok_or(AppError::NotFound)?;
195+ let now = Timestamp::now();
196+ let status = attempt.status(&exam, now);
197+ let deadline = attempt.deadline(&exam);
198+ let remaining_ms = (status == AttemptStatus::InProgress)
199+ .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))
200+ .flatten();
201+ let answered = ExamAnswer::list_for_exam_user(exam.get_id(), user, db)
202+ .await?
203+ .len();
204+ let question_count = ExamQuestion::list_for_exam(exam.get_id(), db).await?.len();
205+ let frame = json!({
206+ "type": "state",
207+ "status": status.as_str(),
208+ "deadline": deadline.map(|t| t.as_millis()),
209+ "remaining_ms": remaining_ms,
210+ "now": now.as_millis(),
211+ "answered": answered,
212+ "question_count": question_count,
213+ });
214+ Ok((
215+ frame,
216+ status,
217+ attempt.get_finished_at().map(|t| t.as_millis()),
218+ ))
219+}
220+
221+async fn handle_message(
222+ socket: &mut WebSocket,
223+ text: &str,
224+ exam_id: &ExamId,
225+ user: &UserId,
226+ db: &Database,
227+) -> Result<(), RoomClosed> {
228+ let message = match serde_json::from_str::<ClientMessage>(text) {
229+ Ok(message) => message,
230+ Err(err) => {
231+ return send(
232+ socket,
233+ json!({ "type": "error", "message": format!("unrecognized message: {err}") }),
234+ )
235+ .await;
236+ }
237+ };
238+ match message {
239+ ClientMessage::Ping => send(socket, json!({ "type": "pong" })).await,
240+ ClientMessage::Answer {
241+ question_id,
242+ selected,
243+ text,
244+ } => {
245+ // Re-read the exam so the save is judged against the *current*
246+ // schedule, exactly like the REST path it shares.
247+ let saved = match Exam::read(exam_id, db).await {
248+ Ok(Some(exam)) => {
249+ save_answer_checked(&exam, user, &question_id, selected, text, db).await
250+ }
251+ Ok(None) => Err(AppError::NotFound),
252+ Err(err) => Err(err),
253+ };
254+ match saved {
255+ Ok(answer) => {
256+ send(
257+ socket,
258+ json!({
259+ "type": "saved",
260+ "question_id": answer.get_question().key(),
261+ "updated_at": answer.get_updated_at().as_millis(),
262+ }),
263+ )
264+ .await?;
265+ // Progress changed — refresh the countdown/answered state
266+ // right away rather than waiting out the tick.
267+ push_state(socket, exam_id, user, db).await
268+ }
269+ Err(err) => send(socket, error_frame(&err)).await,
270+ }
271+ }
272+ ClientMessage::Finish => {
273+ let finished = match Exam::read(exam_id, db).await {
274+ Ok(Some(exam)) => match writable_attempt(&exam, user, db).await {
275+ Ok(attempt) => attempt.finish(db).await,
276+ Err(err) => Err(err),
277+ },
278+ Ok(None) => Err(AppError::NotFound),
279+ Err(err) => Err(err),
280+ };
281+ match finished {
282+ Ok(attempt) => {
283+ send(
284+ socket,
285+ json!({
286+ "type": "finished",
287+ "finished_at": attempt.get_finished_at().map(|t| t.as_millis()),
288+ }),
289+ )
290+ .await?;
291+ Err(RoomClosed)
292+ }
293+ Err(err) => send(socket, error_frame(&err)).await,
294+ }
295+ }
296+ }
297+}
298+
299+/// The public words for an error — the same strings the HTTP layer would use,
300+/// with internals logged, never sent.
301+fn error_frame(err: &AppError) -> Value {
302+ let message = match err {
303+ AppError::Validation(err) => err.to_string(),
304+ AppError::NotFound => "not found".to_string(),
305+ AppError::Unauthorized => "unauthorized".to_string(),
306+ AppError::Forbidden(message) => (*message).to_string(),
307+ AppError::Conflict(message) => (*message).to_string(),
308+ AppError::TooManyRequests { .. } => "too many requests".to_string(),
309+ AppError::Db(_) | AppError::Internal(_) => {
310+ tracing::error!("exam room error: {err}");
311+ "internal server error".to_string()
312+ }
313+ };
314+ json!({ "type": "error", "message": message })
315+}
src/web/exams.rsmodified+1166 -17
@@ -1,31 +1,63 @@
1+use std::collections::HashMap;
2+use std::time::Duration;
3+
1 use axum::Json;4 use axum::Json;
2 use axum::extract::{Path, State};5 use axum::extract::{Path, State};
3 use axum::http::StatusCode;6 use axum::http::StatusCode;
7+use axum::response::sse::{Event, KeepAlive, Sse};
4 use serde::{Deserialize, Serialize};8 use serde::{Deserialize, Serialize};
9+use tokio_stream::wrappers::IntervalStream;
10+use tokio_stream::{Stream, StreamExt};
5 use utoipa::ToSchema;11 use utoipa::ToSchema;
6 use utoipa_axum::router::OpenApiRouter;12 use utoipa_axum::router::OpenApiRouter;
7 use utoipa_axum::routes;13 use utoipa_axum::routes;
8 14
15+use crate::constant::EXAM_LIVE_STREAM_INTERVAL_SECS;
9 use crate::database::Database;16 use crate::database::Database;
10 use crate::domain::course::Course;17 use crate::domain::course::Course;
11 use crate::domain::enrollment::Enrollment;18 use crate::domain::enrollment::Enrollment;
12-use crate::domain::exam::{Exam, ExamDescription, ExamId, ExamKind, ExamTitle, ExamWeight};19+use crate::domain::exam::{
20+ Exam, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamSchedule, ExamTitle,
21+ ExamWeight,
22+};
23+use crate::domain::exam_answer::{ExamAnswer, auto_score};
24+use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};
25+use crate::domain::exam_question::{
26+ ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
27+};
13 use crate::domain::exam_result::{ExamResult, Mark};28 use crate::domain::exam_result::{ExamResult, Mark};
29+use crate::domain::timestamp::Timestamp;
14 use crate::domain::user::{User, UserId};30 use crate::domain::user::{User, UserId};
15 use crate::error::{AppError, ErrorResponse, ValidationError};31 use crate::error::{AppError, ErrorResponse, ValidationError};
16 use crate::state::AppState;32 use crate::state::AppState;
17 33
18 use super::courses::can_manage_course;34 use super::courses::can_manage_course;
19-use super::{CurrentUser, ExamResponse, RequireTeacher};35+use super::{CurrentUser, ExamResponse, PersonRef, RequireTeacher, person_map, set_or_clear};
20 36
21 pub fn routes() -> OpenApiRouter<AppState> {37 pub fn routes() -> OpenApiRouter<AppState> {
22 OpenApiRouter::new()38 OpenApiRouter::new()
39+ // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so
40+ // the exam room lives outside the generated spec (see the `exams` tag
41+ // description and README for the protocol).
42+ .route(
43+ "/{id}/attempt/ws",
44+ axum::routing::get(super::exam_ws::attempt_ws),
45+ )
23 .routes(routes!(list_exams))46 .routes(routes!(list_exams))
24 .routes(routes!(get_exam, update_exam, delete_exam))47 .routes(routes!(get_exam, update_exam, delete_exam))
25 .routes(routes!(grade, list_results))48 .routes(routes!(grade, list_results))
26 .routes(routes!(my_result))49 .routes(routes!(my_result))
27 .routes(routes!(remove_result))50 .routes(routes!(remove_result))
28 .routes(routes!(exam_statistics))51 .routes(routes!(exam_statistics))
52+ .routes(routes!(start_attempt, my_attempt))
53+ .routes(routes!(finish_attempt))
54+ .routes(routes!(exam_live))
55+ .routes(routes!(exam_live_stream))
56+ .routes(routes!(create_question, list_questions))
57+ .routes(routes!(update_question, delete_question))
58+ .routes(routes!(attempt_questions))
59+ .routes(routes!(save_answer))
60+ .routes(routes!(attempt_answers))
29 }61 }
30 62
31 #[derive(Deserialize, ToSchema)]63 #[derive(Deserialize, ToSchema)]
@@ -34,6 +66,25 @@ struct UpdateExam {
34 description: Option<String>,66 description: Option<String>,
35 kind: Option<String>,67 kind: Option<String>,
36 weight: Option<i64>,68 weight: Option<i64>,
69+ /// `sync` or `async`. Omit to keep the current mode; send `null` to
70+ /// unschedule the exam. Frozen once anyone has started an attempt.
71+ #[serde(default, deserialize_with = "set_or_clear")]
72+ #[schema(value_type = Option<String>)]
73+ mode: Option<Option<String>>,
74+ /// Window open, UTC unix-milliseconds. Omit to keep; `null` to clear.
75+ #[serde(default, deserialize_with = "set_or_clear")]
76+ #[schema(value_type = Option<i64>)]
77+ starts_at: Option<Option<i64>>,
78+ /// Window close, UTC unix-milliseconds. Omit to keep; `null` to clear.
79+ /// Moving it while a sync exam runs extends (or cuts) everyone's deadline.
80+ #[serde(default, deserialize_with = "set_or_clear")]
81+ #[schema(value_type = Option<i64>)]
82+ ends_at: Option<Option<i64>>,
83+ /// Per-student budget, milliseconds (async only). Omit to keep; `null` to
84+ /// clear. Changing it mid-exam moves every running attempt's deadline.
85+ #[serde(default, deserialize_with = "set_or_clear")]
86+ #[schema(value_type = Option<i64>)]
87+ duration_ms: Option<Option<i64>>,
37 }88 }
38 89
39 #[derive(Deserialize, ToSchema)]90 #[derive(Deserialize, ToSchema)]
@@ -50,19 +101,21 @@ struct GradeResult {
50 struct ExamResultResponse {101 struct ExamResultResponse {
51 id: String,102 id: String,
52 exam: String,103 exam: String,
53- user: String,104+ /// The graded student.
105+ user: PersonRef,
54 mark: i64,106 mark: i64,
55- graded_by: String,107+ /// Who recorded the mark.
108+ graded_by: PersonRef,
56 }109 }
57 110
58 impl ExamResultResponse {111 impl ExamResultResponse {
59- fn new(result: &ExamResult) -> Self {112+ fn new(result: &ExamResult, people: &HashMap<String, PersonRef>) -> Self {
60 Self {113 Self {
61 id: result.get_id().key().to_string(),114 id: result.get_id().key().to_string(),
62 exam: result.get_exam().key().to_string(),115 exam: result.get_exam().key().to_string(),
63- user: result.get_user().key().to_string(),116+ user: PersonRef::resolve(people, result.get_user()),
64 mark: result.get_mark().as_i64(),117 mark: result.get_mark().as_i64(),
65- graded_by: result.get_graded_by().key().to_string(),118+ graded_by: PersonRef::resolve(people, result.get_graded_by()),
66 }119 }
67 }120 }
68 }121 }
@@ -133,8 +186,11 @@ async fn get_exam(
133 }186 }
134 187
135 /// Update an exam. Requires teacher+ and management rights over the exam's188 /// Update an exam. Requires teacher+ and management rights over the exam's
136-/// course (its creator, or manager/admin). Omitted fields keep their value; the189+/// course (its creator, or manager/admin). Omitted fields keep their value; an
137-/// course itself is not updatable.190+/// explicit `null` clears a schedule field; the course itself is not updatable.
191+/// The schedule must stay consistent as a whole (see the create endpoint), and
192+/// `mode` is frozen once anyone has started an attempt — times and duration
193+/// stay editable so a running exam can be extended live.
138 #[utoipa::path(194 #[utoipa::path(
139 patch,195 patch,
140 path = "/{id}",196 path = "/{id}",
@@ -144,10 +200,11 @@ async fn get_exam(
144 request_body = UpdateExam,200 request_body = UpdateExam,
145 responses(201 responses(
146 (status = 200, description = "Updated exam", body = ExamResponse),202 (status = 200, description = "Updated exam", body = ExamResponse),
147- (status = 400, description = "Invalid fields, kind, or weight", body = ErrorResponse),203+ (status = 400, description = "Invalid fields, kind, weight, or schedule", body = ErrorResponse),
148 (status = 401, description = "Not authenticated", body = ErrorResponse),204 (status = 401, description = "Not authenticated", body = ErrorResponse),
149 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),205 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
150 (status = 404, description = "Not found", body = ErrorResponse),206 (status = 404, description = "Not found", body = ErrorResponse),
207+ (status = 409, description = "Mode change after attempts started", body = ErrorResponse),
151 ),208 ),
152 )]209 )]
153 async fn update_exam(210 async fn update_exam(
@@ -183,14 +240,46 @@ async fn update_exam(
183 None => exam.get_weight(),240 None => exam.get_weight(),
184 };241 };
185 242
243+ // Merge the schedule (set / clear / keep per field), then re-validate it
244+ // as a unit — a PATCH can't leave a half-schedule behind.
245+ let mode = match req.mode {
246+ Some(update) => update.as_deref().map(ExamMode::try_new).transpose()?,
247+ None => exam.get_mode().cloned(),
248+ };
249+ let starts_at = match req.starts_at {
250+ Some(update) => update.map(Timestamp::from_millis),
251+ None => exam.get_starts_at(),
252+ };
253+ let ends_at = match req.ends_at {
254+ Some(update) => update.map(Timestamp::from_millis),
255+ None => exam.get_ends_at(),
256+ };
257+ let duration_ms = match req.duration_ms {
258+ Some(update) => update.map(ExamDuration::try_new).transpose()?,
259+ None => exam.get_duration_ms(),
260+ };
261+ let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?;
262+
263+ // Switching sync <-> async (or unscheduling) would silently rewrite the
264+ // deadline rules under students who already sat down; extending times is
265+ // the supported live adjustment instead.
266+ let mode_changed =
267+ schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str);
268+ if mode_changed && ExamAttempt::any_for_exam(exam.get_id(), &st.db).await? {
269+ return Err(AppError::Conflict(
270+ "cannot change the exam mode after attempts have started",
271+ ));
272+ }
273+
186 let updated = exam274 let updated = exam
187- .update(title, description, kind, weight, &st.db)275+ .update(title, description, kind, weight, schedule, &st.db)
188 .await?;276 .await?;
189 Ok(Json(ExamResponse::new(&updated)))277 Ok(Json(ExamResponse::new(&updated)))
190 }278 }
191 279
192 /// Delete an exam. Requires teacher+ and management rights over the exam's280 /// Delete an exam. Requires teacher+ and management rights over the exam's
193-/// course (its creator, or manager/admin). Cascades the exam's result rows.281+/// course (its creator, or manager/admin). Cascades the exam's result and
282+/// attempt rows.
194 #[utoipa::path(283 #[utoipa::path(
195 delete,284 delete,
196 path = "/{id}",285 path = "/{id}",
@@ -270,12 +359,12 @@ async fn grade(
270 }359 }
271 360
272 // Target user must exist.361 // Target user must exist.
273- if User::read(&target, &st.db).await?.is_none() {362+ let Some(target_user) = User::read(&target, &st.db).await? else {
274 return Err(AppError::Validation(ValidationError::Invalid {363 return Err(AppError::Validation(ValidationError::Invalid {
275 field: "user_id",364 field: "user_id",
276 reason: "target user does not exist",365 reason: "target user does not exist",
277 }));366 }));
278- }367+ };
279 368
280 // ... and be enrolled in the exam's course.369 // ... and be enrolled in the exam's course.
281 if Enrollment::read_for_user(exam.get_course(), &target, &st.db)370 if Enrollment::read_for_user(exam.get_course(), &target, &st.db)
@@ -289,7 +378,8 @@ async fn grade(
289 }378 }
290 379
291 let result = ExamResult::grade(&exam_id, &target, mark, teacher.get_id(), &st.db).await?;380 let result = ExamResult::grade(&exam_id, &target, mark, teacher.get_id(), &st.db).await?;
292- Ok(Json(ExamResultResponse::new(&result)))381+ let people = PersonRef::map_of(&[&target_user, &teacher]);
382+ Ok(Json(ExamResultResponse::new(&result, &people)))
293 }383 }
294 384
295 /// List every result for an exam. Requires teacher+ — students read only their385 /// List every result for an exam. Requires teacher+ — students read only their
@@ -318,7 +408,19 @@ async fn list_results(
318 .await?408 .await?
319 .ok_or(AppError::NotFound)?;409 .ok_or(AppError::NotFound)?;
320 let results = ExamResult::list_for_exam(&exam_id, &st.db).await?;410 let results = ExamResult::list_for_exam(&exam_id, &st.db).await?;
321- Ok(Json(results.iter().map(ExamResultResponse::new).collect()))411+ let people = person_map(
412+ results
413+ .iter()
414+ .flat_map(|r| [r.get_user().clone(), r.get_graded_by().clone()]),
415+ &st.db,
416+ )
417+ .await?;
418+ Ok(Json(
419+ results
420+ .iter()
421+ .map(|r| ExamResultResponse::new(r, &people))
422+ .collect(),
423+ ))
322 }424 }
323 425
324 /// The current user's own result for an exam. Any authenticated user may read426 /// The current user's own result for an exam. Any authenticated user may read
@@ -343,7 +445,12 @@ async fn my_result(
343 let result = ExamResult::read_for_user(&ExamId::from_key(&id), user.get_id(), &st.db)445 let result = ExamResult::read_for_user(&ExamId::from_key(&id), user.get_id(), &st.db)
344 .await?446 .await?
345 .ok_or(AppError::NotFound)?;447 .ok_or(AppError::NotFound)?;
346- Ok(Json(ExamResultResponse::new(&result)))448+ let people = person_map(
449+ [result.get_user().clone(), result.get_graded_by().clone()],
450+ &st.db,
451+ )
452+ .await?;
453+ Ok(Json(ExamResultResponse::new(&result, &people)))
347 }454 }
348 455
349 /// Remove a student's result from an exam. Requires teacher+ and management456 /// Remove a student's result from an exam. Requires teacher+ and management
@@ -422,3 +529,1045 @@ async fn exam_statistics(
422 max: marks.iter().max().copied(),529 max: marks.iter().max().copied(),
423 }))530 }))
424 }531 }
532+
533+// ---- attempts -------------------------------------------------------------
534+// A scheduled exam is *sat*: starting an attempt is the live-attendance
535+// signal, finishing is the submission. Deadlines are judged only by the
536+// server clock — clients sync via `GET /time`.
537+
538+/// A student's view of their attempt. `now` is echoed so clients can render
539+/// countdowns without trusting the device clock.
540+#[derive(Serialize, ToSchema)]
541+struct AttemptResponse {
542+ id: String,
543+ exam: String,
544+ user: PersonRef,
545+ /// When the attempt started, UTC unix-milliseconds.
546+ started_at: i64,
547+ /// Submission instant; `null` while running (or expired unsubmitted).
548+ finished_at: Option<i64>,
549+ /// `in_progress` | `submitted` | `expired`.
550+ #[schema(example = "in_progress")]
551+ status: String,
552+ /// When the attempt closes: `ends_at` for sync, `min(started_at +
553+ /// duration_ms, ends_at)` for async. Recomputed live from the exam's
554+ /// current schedule.
555+ deadline: Option<i64>,
556+ /// `deadline - now`, floored at 0; `null` unless in progress.
557+ remaining_ms: Option<i64>,
558+ /// The caller's mark, once graded.
559+ mark: Option<i64>,
560+ /// How many questions the caller has answered so far.
561+ answered: u64,
562+ /// How many questions the exam has.
563+ question_count: u64,
564+ /// Server clock at response time, UTC unix-milliseconds.
565+ now: i64,
566+}
567+
568+impl AttemptResponse {
569+ fn new(
570+ attempt: &ExamAttempt,
571+ exam: &Exam,
572+ mark: Option<Mark>,
573+ people: &HashMap<String, PersonRef>,
574+ answered: u64,
575+ question_count: u64,
576+ now: Timestamp,
577+ ) -> Self {
578+ let status = attempt.status(exam, now);
579+ let deadline = attempt.deadline(exam);
580+ let remaining_ms = (status == AttemptStatus::InProgress)
581+ .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))
582+ .flatten();
583+ Self {
584+ id: attempt.get_id().key().to_string(),
585+ exam: attempt.get_exam().key().to_string(),
586+ user: PersonRef::resolve(people, attempt.get_user()),
587+ started_at: attempt.get_started_at().as_millis(),
588+ finished_at: attempt.get_finished_at().map(|t| t.as_millis()),
589+ status: status.as_str().to_string(),
590+ deadline: deadline.map(|t| t.as_millis()),
591+ remaining_ms,
592+ mark: mark.map(|m| m.as_i64()),
593+ answered,
594+ question_count,
595+ now: now.as_millis(),
596+ }
597+ }
598+}
599+
600+/// The (answered, question_count) pair behind an attempt view — how far one
601+/// student has come through the exam's question list.
602+async fn attempt_progress(
603+ exam: &ExamId,
604+ user: &UserId,
605+ db: &Database,
606+) -> Result<(u64, u64), AppError> {
607+ let answered = ExamAnswer::list_for_exam_user(exam, user, db).await?.len() as u64;
608+ let question_count = ExamQuestion::list_for_exam(exam, db).await?.len() as u64;
609+ Ok((answered, question_count))
610+}
611+
612+/// The exam's window, or a 409 when it isn't scheduled at all. Enrollment and
613+/// window checks for the caller are the caller's own state — hence `Conflict`
614+/// (a state problem), not validation.
615+fn window_of(exam: &Exam) -> Result<(Timestamp, Timestamp), AppError> {
616+ match (exam.get_starts_at(), exam.get_ends_at()) {
617+ (Some(starts), Some(ends)) => Ok((starts, ends)),
618+ _ => Err(AppError::Conflict(
619+ "this exam is not scheduled — there is nothing to sit",
620+ )),
621+ }
622+}
623+
624+/// Start (or resume) the caller's attempt at a scheduled exam. Requires
625+/// enrollment in the exam's course and the window to be open. Idempotent in
626+/// the useful direction: if an attempt already exists it is returned as-is
627+/// (`200` instead of `201`), so a reconnecting client gets its original clock
628+/// back — re-starting never resets the time.
629+#[utoipa::path(
630+ post,
631+ path = "/{id}/attempt",
632+ tag = "exams",
633+ security(("session_cookie" = [])),
634+ params(("id" = String, Path, description = "Exam id")),
635+ responses(
636+ (status = 201, description = "Attempt started", body = AttemptResponse),
637+ (status = 200, description = "Attempt already existed (unchanged)", body = AttemptResponse),
638+ (status = 401, description = "Not authenticated", body = ErrorResponse),
639+ (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse),
640+ (status = 404, description = "Exam not found", body = ErrorResponse),
641+ (status = 409, description = "Unscheduled exam, or outside the window", body = ErrorResponse),
642+ ),
643+)]
644+async fn start_attempt(
645+ State(st): State<AppState>,
646+ CurrentUser(user): CurrentUser,
647+ Path(id): Path<String>,
648+) -> Result<(StatusCode, Json<AttemptResponse>), AppError> {
649+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
650+ .await?
651+ .ok_or(AppError::NotFound)?;
652+ let (starts_at, ends_at) = window_of(&exam)?;
653+ if Enrollment::read_for_user(exam.get_course(), user.get_id(), &st.db)
654+ .await?
655+ .is_none()
656+ {
657+ return Err(AppError::Forbidden(
658+ "you are not enrolled in this exam's course",
659+ ));
660+ }
661+ let now = Timestamp::now();
662+ if now < starts_at {
663+ return Err(AppError::Conflict("the exam has not started yet"));
664+ }
665+ if now >= ends_at {
666+ return Err(AppError::Conflict("the exam has already ended"));
667+ }
668+
669+ let (attempt, created) = ExamAttempt::start(exam.get_id(), user.get_id(), &st.db).await?;
670+ let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
671+ .await?
672+ .map(|r| r.get_mark());
673+ let (answered, question_count) = attempt_progress(exam.get_id(), user.get_id(), &st.db).await?;
674+ let people = PersonRef::map_of(&[&user]);
675+ let status = if created {
676+ StatusCode::CREATED
677+ } else {
678+ StatusCode::OK
679+ };
680+ Ok((
681+ status,
682+ Json(AttemptResponse::new(
683+ &attempt,
684+ &exam,
685+ mark,
686+ &people,
687+ answered,
688+ question_count,
689+ Timestamp::now(),
690+ )),
691+ ))
692+}
693+
694+/// The caller's own attempt: status, deadline, remaining time, and mark once
695+/// graded — everything a student's live exam screen needs, judged by the
696+/// server clock. `404` until the attempt is started.
697+#[utoipa::path(
698+ get,
699+ path = "/{id}/attempt",
700+ tag = "exams",
701+ security(("session_cookie" = [])),
702+ params(("id" = String, Path, description = "Exam id")),
703+ responses(
704+ (status = 200, description = "The caller's attempt", body = AttemptResponse),
705+ (status = 401, description = "Not authenticated", body = ErrorResponse),
706+ (status = 404, description = "No such exam, or no attempt yet", body = ErrorResponse),
707+ ),
708+)]
709+async fn my_attempt(
710+ State(st): State<AppState>,
711+ CurrentUser(user): CurrentUser,
712+ Path(id): Path<String>,
713+) -> Result<Json<AttemptResponse>, AppError> {
714+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
715+ .await?
716+ .ok_or(AppError::NotFound)?;
717+ let attempt = ExamAttempt::read_for_user(exam.get_id(), user.get_id(), &st.db)
718+ .await?
719+ .ok_or(AppError::NotFound)?;
720+ let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
721+ .await?
722+ .map(|r| r.get_mark());
723+ let (answered, question_count) = attempt_progress(exam.get_id(), user.get_id(), &st.db).await?;
724+ let people = PersonRef::map_of(&[&user]);
725+ Ok(Json(AttemptResponse::new(
726+ &attempt,
727+ &exam,
728+ mark,
729+ &people,
730+ answered,
731+ question_count,
732+ Timestamp::now(),
733+ )))
734+}
735+
736+/// Submit the caller's attempt. Allowed while the deadline hasn't passed;
737+/// after it, the attempt is already `expired` (a valid terminal state — the
738+/// student used their full time) and submitting is a `409`.
739+#[utoipa::path(
740+ post,
741+ path = "/{id}/attempt/finish",
742+ tag = "exams",
743+ security(("session_cookie" = [])),
744+ params(("id" = String, Path, description = "Exam id")),
745+ responses(
746+ (status = 200, description = "Attempt submitted", body = AttemptResponse),
747+ (status = 401, description = "Not authenticated", body = ErrorResponse),
748+ (status = 404, description = "No such exam, or no attempt to finish", body = ErrorResponse),
749+ (status = 409, description = "Already submitted, or the deadline passed", body = ErrorResponse),
750+ ),
751+)]
752+async fn finish_attempt(
753+ State(st): State<AppState>,
754+ CurrentUser(user): CurrentUser,
755+ Path(id): Path<String>,
756+) -> Result<Json<AttemptResponse>, AppError> {
757+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
758+ .await?
759+ .ok_or(AppError::NotFound)?;
760+ let attempt = ExamAttempt::read_for_user(exam.get_id(), user.get_id(), &st.db)
761+ .await?
762+ .ok_or(AppError::NotFound)?;
763+ if attempt.get_finished_at().is_some() {
764+ return Err(AppError::Conflict("the attempt is already submitted"));
765+ }
766+ let now = Timestamp::now();
767+ if let Some(deadline) = attempt.deadline(&exam)
768+ && now >= deadline
769+ {
770+ return Err(AppError::Conflict("time is up — the attempt has expired"));
771+ }
772+
773+ let finished = attempt.finish(&st.db).await?;
774+ let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
775+ .await?
776+ .map(|r| r.get_mark());
777+ let (answered, question_count) = attempt_progress(exam.get_id(), user.get_id(), &st.db).await?;
778+ let people = PersonRef::map_of(&[&user]);
779+ Ok(Json(AttemptResponse::new(
780+ &finished,
781+ &exam,
782+ mark,
783+ &people,
784+ answered,
785+ question_count,
786+ Timestamp::now(),
787+ )))
788+}
789+
790+// ---- live monitor ---------------------------------------------------------
791+
792+/// One roster row of the live exam monitor.
793+#[derive(Serialize, ToSchema)]
794+struct LiveStudentResponse {
795+ user: PersonRef,
796+ /// `not_started` | `in_progress` | `submitted` | `expired`.
797+ #[schema(example = "in_progress")]
798+ status: String,
799+ started_at: Option<i64>,
800+ finished_at: Option<i64>,
801+ /// When this student's attempt closes (server-authoritative).
802+ deadline: Option<i64>,
803+ /// Time this student has left, floored at 0; `null` unless in progress.
804+ remaining_ms: Option<i64>,
805+ /// The student's mark, once graded.
806+ mark: Option<i64>,
807+ /// How many questions this student has answered so far.
808+ answered: u64,
809+ /// When this student last saved an answer, UTC unix-milliseconds; `null`
810+ /// before the first save.
811+ last_activity: Option<i64>,
812+}
813+
814+#[derive(Serialize, ToSchema)]
815+struct LiveCountsResponse {
816+ enrolled: u64,
817+ not_started: u64,
818+ in_progress: u64,
819+ submitted: u64,
820+ expired: u64,
821+ graded: u64,
822+}
823+
824+/// A live snapshot of an exam: the enrolled roster with per-student attempt
825+/// state, remaining time, and marks, all judged by one server-clock read.
826+#[derive(Serialize, ToSchema)]
827+struct ExamLiveResponse {
828+ exam: ExamResponse,
829+ /// Server clock the snapshot was judged at, UTC unix-milliseconds.
830+ now: i64,
831+ /// How many questions the exam has.
832+ question_count: u64,
833+ counts: LiveCountsResponse,
834+ students: Vec<LiveStudentResponse>,
835+}
836+
837+/// Build the monitor snapshot: roster ⋈ attempts ⋈ marks at one instant.
838+/// Students unenrolled mid-exam drop off the roster view (their attempt and
839+/// mark rows survive, exactly like the marks report).
840+async fn live_snapshot(exam: &Exam, db: &Database) -> Result<ExamLiveResponse, AppError> {
841+ let now = Timestamp::now();
842+ let roster = Enrollment::list_for_course(exam.get_course(), db).await?;
843+ let attempts: HashMap<String, ExamAttempt> = ExamAttempt::list_for_exam(exam.get_id(), db)
844+ .await?
845+ .into_iter()
846+ .map(|attempt| (attempt.get_user().key().to_string(), attempt))
847+ .collect();
848+ let marks: HashMap<String, i64> = ExamResult::list_for_exam(exam.get_id(), db)
849+ .await?
850+ .iter()
851+ .map(|result| {
852+ (
853+ result.get_user().key().to_string(),
854+ result.get_mark().as_i64(),
855+ )
856+ })
857+ .collect();
858+ let question_count = ExamQuestion::list_for_exam(exam.get_id(), db).await?.len() as u64;
859+ // Per-student progress: answer count and the latest save instant.
860+ let mut progress: HashMap<String, (u64, i64)> = HashMap::new();
861+ for answer in ExamAnswer::list_for_exam(exam.get_id(), db).await? {
862+ let entry = progress
863+ .entry(answer.get_user().key().to_string())
864+ .or_insert((0, i64::MIN));
865+ entry.0 += 1;
866+ entry.1 = entry.1.max(answer.get_updated_at().as_millis());
867+ }
868+ let people = person_map(roster.iter().map(|e| e.get_user().clone()), db).await?;
869+
870+ let mut students: Vec<LiveStudentResponse> = roster
871+ .iter()
872+ .map(|enrollment| {
873+ let key = enrollment.get_user().key();
874+ let attempt = attempts.get(key);
875+ let status = attempt.map(|a| a.status(exam, now));
876+ let deadline = attempt.and_then(|a| a.deadline(exam));
877+ LiveStudentResponse {
878+ user: PersonRef::resolve(&people, enrollment.get_user()),
879+ status: status
880+ .map_or("not_started", AttemptStatus::as_str)
881+ .to_string(),
882+ started_at: attempt.map(|a| a.get_started_at().as_millis()),
883+ finished_at: attempt
884+ .and_then(|a| a.get_finished_at())
885+ .map(|t| t.as_millis()),
886+ deadline: deadline.map(|t| t.as_millis()),
887+ remaining_ms: (status == Some(AttemptStatus::InProgress))
888+ .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))
889+ .flatten(),
890+ mark: marks.get(key).copied(),
891+ answered: progress.get(key).map_or(0, |p| p.0),
892+ last_activity: progress.get(key).map(|p| p.1),
893+ }
894+ })
895+ .collect();
896+ students.sort_by(|a, b| a.user.username.cmp(&b.user.username));
897+
898+ let count = |status: &str| students.iter().filter(|s| s.status == status).count() as u64;
899+ let counts = LiveCountsResponse {
900+ enrolled: students.len() as u64,
901+ not_started: count("not_started"),
902+ in_progress: count("in_progress"),
903+ submitted: count("submitted"),
904+ expired: count("expired"),
905+ graded: students.iter().filter(|s| s.mark.is_some()).count() as u64,
906+ };
907+ Ok(ExamLiveResponse {
908+ exam: ExamResponse::new(exam),
909+ now: now.as_millis(),
910+ question_count,
911+ counts,
912+ students,
913+ })
914+}
915+
916+/// A one-shot live snapshot of the exam: who's in, who's still writing, time
917+/// each student has left, and marks as they land. Requires teacher+. For a
918+/// self-updating feed of the same shape, see `GET /exams/{id}/live/stream`.
919+#[utoipa::path(
920+ get,
921+ path = "/{id}/live",
922+ tag = "exams",
923+ security(("session_cookie" = [])),
924+ params(("id" = String, Path, description = "Exam id")),
925+ responses(
926+ (status = 200, description = "Live snapshot", body = ExamLiveResponse),
927+ (status = 401, description = "Not authenticated", body = ErrorResponse),
928+ (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
929+ (status = 404, description = "Exam not found", body = ErrorResponse),
930+ ),
931+)]
932+async fn exam_live(
933+ State(st): State<AppState>,
934+ _teacher: RequireTeacher,
935+ Path(id): Path<String>,
936+) -> Result<Json<ExamLiveResponse>, AppError> {
937+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
938+ .await?
939+ .ok_or(AppError::NotFound)?;
940+ Ok(Json(live_snapshot(&exam, &st.db).await?))
941+}
942+
943+/// The live snapshot as a Server-Sent-Events stream: one `snapshot` event
944+/// (the `ExamLiveResponse` JSON) immediately on connect and then every couple
945+/// of seconds, so attendance, remaining time, submissions, and marks update
946+/// without polling. Requires teacher+. Consume with `EventSource` (cookies
947+/// ride along on same-site / credentialed requests). If the exam disappears
948+/// mid-stream an `error` event is sent instead.
949+#[utoipa::path(
950+ get,
951+ path = "/{id}/live/stream",
952+ tag = "exams",
953+ security(("session_cookie" = [])),
954+ params(("id" = String, Path, description = "Exam id")),
955+ responses(
956+ (status = 200, description = "SSE feed of `snapshot` events (`ExamLiveResponse` as JSON)", content_type = "text/event-stream"),
957+ (status = 401, description = "Not authenticated", body = ErrorResponse),
958+ (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
959+ (status = 404, description = "Exam not found", body = ErrorResponse),
960+ ),
961+)]
962+async fn exam_live_stream(
963+ State(st): State<AppState>,
964+ _teacher: RequireTeacher,
965+ Path(id): Path<String>,
966+) -> Result<Sse<impl Stream<Item = Result<Event, axum::Error>>>, AppError> {
967+ let exam_id = ExamId::from_key(&id);
968+ // A missing exam is a 404 up front; after this the response is a stream.
969+ Exam::read(&exam_id, &st.db)
970+ .await?
971+ .ok_or(AppError::NotFound)?;
972+
973+ // First tick fires immediately, so the monitor paints on connect. The
974+ // exam is re-read every tick: schedule edits (deadline extensions) show
975+ // up mid-stream.
976+ let interval = tokio::time::interval(Duration::from_secs(EXAM_LIVE_STREAM_INTERVAL_SECS));
977+ let stream = IntervalStream::new(interval).then(move |_| {
978+ let db = st.db.clone();
979+ let exam_id = exam_id.clone();
980+ async move {
981+ let snapshot = match Exam::read(&exam_id, &db).await {
982+ Ok(Some(exam)) => live_snapshot(&exam, &db).await,
983+ Ok(None) => Err(AppError::NotFound),
984+ Err(err) => Err(err),
985+ };
986+ match snapshot {
987+ Ok(snapshot) => Event::default().event("snapshot").json_data(&snapshot),
988+ // Exam deleted mid-stream or a db hiccup: say so without
989+ // leaking internals and keep the stream alive — the client
990+ // decides whether to hang on or close.
991+ Err(err) => {
992+ tracing::warn!("live exam stream snapshot failed: {err}");
993+ Event::default()
994+ .event("error")
995+ .json_data(serde_json::json!({ "error": "live snapshot unavailable" }))
996+ }
997+ }
998+ }
999+ });
1000+ Ok(Sse::new(stream).keep_alive(KeepAlive::default()))
1001+}
1002+
1003+// ---- questions --------------------------------------------------------------
1004+// Teachers author the question list before the exam runs; it freezes the
1005+// moment anyone starts an attempt, so every student sits the same exam.
1006+
1007+#[derive(Deserialize, ToSchema)]
1008+struct CreateQuestion {
1009+ /// The question itself.
1010+ #[schema(example = "What is 2 + 2?")]
1011+ text: String,
1012+ /// `choice` or `text`.
1013+ #[schema(example = "choice")]
1014+ kind: String,
1015+ /// This question's share of the auto-score, `1`–`100`.
1016+ #[schema(example = 10)]
1017+ points: i64,
1018+ /// The options of a `choice` question (2–10 of them); omit for `text`.
1019+ choices: Option<Vec<String>>,
1020+ /// Zero-based index of the right option; required for `choice`, absent
1021+ /// for `text`.
1022+ #[schema(example = 1)]
1023+ correct: Option<i64>,
1024+}
1025+
1026+#[derive(Deserialize, ToSchema)]
1027+struct UpdateQuestion {
1028+ text: Option<String>,
1029+ points: Option<i64>,
1030+ /// `choice` or `text`. Switching kinds needs the other fields to follow:
1031+ /// send `choices` + `correct` when moving to `choice`, explicit `null`s
1032+ /// when moving to `text`.
1033+ kind: Option<String>,
1034+ /// Omit to keep the stored options; send `null` to drop them (text
1035+ /// questions only).
1036+ #[serde(default, deserialize_with = "set_or_clear")]
1037+ #[schema(value_type = Option<Vec<String>>)]
1038+ choices: Option<Option<Vec<String>>>,
1039+ /// Omit to keep; `null` to clear (text questions only).
1040+ #[serde(default, deserialize_with = "set_or_clear")]
1041+ #[schema(value_type = Option<i64>)]
1042+ correct: Option<Option<i64>>,
1043+}
1044+
1045+/// A question as its author sees it — including the `correct` index. Never
1046+/// serialized to students; they get [`AttemptQuestionResponse`].
1047+#[derive(Serialize, ToSchema)]
1048+struct QuestionResponse {
1049+ id: String,
1050+ exam: String,
1051+ text: String,
1052+ /// `choice` or `text`.
1053+ #[schema(example = "choice")]
1054+ kind: String,
1055+ points: i64,
1056+ choices: Option<Vec<String>>,
1057+ /// Zero-based index of the right option (`choice` questions only).
1058+ correct: Option<i64>,
1059+}
1060+
1061+impl QuestionResponse {
1062+ fn new(question: &ExamQuestion) -> Self {
1063+ Self {
1064+ id: question.get_id().key().to_string(),
1065+ exam: question.get_exam().key().to_string(),
1066+ text: question.get_text().as_str().to_string(),
1067+ kind: question.get_kind().as_str().to_string(),
1068+ points: question.get_points().as_i64(),
1069+ choices: question
1070+ .get_choices()
1071+ .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()),
1072+ correct: question.get_correct(),
1073+ }
1074+ }
1075+}
1076+
1077+/// The questions freeze once anyone has started an attempt — editing them
1078+/// under a student mid-exam would fork what "the exam" means.
1079+async fn ensure_questions_editable(exam: &ExamId, db: &Database) -> Result<(), AppError> {
1080+ if ExamAttempt::any_for_exam(exam, db).await? {
1081+ return Err(AppError::Conflict(
1082+ "cannot change questions after attempts have started",
1083+ ));
1084+ }
1085+ Ok(())
1086+}
1087+
1088+/// The question, provided it belongs to `exam` — a qid under someone else's
1089+/// exam is a plain 404, not a leak.
1090+async fn question_of_exam(
1091+ exam: &ExamId,
1092+ qid: &str,
1093+ db: &Database,
1094+) -> Result<ExamQuestion, AppError> {
1095+ let question = ExamQuestion::read(&ExamQuestionId::from_key(qid), db)
1096+ .await?
1097+ .ok_or(AppError::NotFound)?;
1098+ if question.get_exam() != exam {
1099+ return Err(AppError::NotFound);
1100+ }
1101+ Ok(question)
1102+}
1103+
1104+/// Add a question to an exam. Requires teacher+ and management rights over the
1105+/// exam's course. `choice` questions carry 2–10 `choices` plus the `correct`
1106+/// index; `text` questions carry neither. Locked once attempts exist.
1107+#[utoipa::path(
1108+ post,
1109+ path = "/{id}/questions",
1110+ tag = "exams",
1111+ security(("session_cookie" = [])),
1112+ params(("id" = String, Path, description = "Exam id")),
1113+ request_body = CreateQuestion,
1114+ responses(
1115+ (status = 201, description = "Question created", body = QuestionResponse),
1116+ (status = 400, description = "Invalid text, kind, points, choices, or correct", body = ErrorResponse),
1117+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1118+ (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1119+ (status = 404, description = "Exam not found", body = ErrorResponse),
1120+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
1121+ ),
1122+)]
1123+async fn create_question(
1124+ State(st): State<AppState>,
1125+ RequireTeacher(user): RequireTeacher,
1126+ Path(id): Path<String>,
1127+ Json(req): Json<CreateQuestion>,
1128+) -> Result<(StatusCode, Json<QuestionResponse>), AppError> {
1129+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1130+ .await?
1131+ .ok_or(AppError::NotFound)?;
1132+ let course = course_of(&exam, &st.db).await?;
1133+ if !can_manage_course(&course, &user) {
1134+ return Err(AppError::Forbidden(
1135+ "only the course creator or a manager/admin can author questions",
1136+ ));
1137+ }
1138+ ensure_questions_editable(exam.get_id(), &st.db).await?;
1139+
1140+ let text = QuestionText::try_new(&req.text)?;
1141+ let points = QuestionPoints::try_new(req.points)?;
1142+ let spec = QuestionSpec::try_new(QuestionKind::try_new(&req.kind)?, req.choices, req.correct)?;
1143+ let question = ExamQuestion::create(exam.get_id(), text, points, spec, &st.db).await?;
1144+ Ok((StatusCode::CREATED, Json(QuestionResponse::new(&question))))
1145+}
1146+
1147+/// The exam's full question list, `correct` indexes included. Requires
1148+/// teacher+. Students read questions through `GET /exams/{id}/attempt/questions`.
1149+#[utoipa::path(
1150+ get,
1151+ path = "/{id}/questions",
1152+ tag = "exams",
1153+ security(("session_cookie" = [])),
1154+ params(("id" = String, Path, description = "Exam id")),
1155+ responses(
1156+ (status = 200, description = "The exam's questions", body = [QuestionResponse]),
1157+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1158+ (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
1159+ (status = 404, description = "Exam not found", body = ErrorResponse),
1160+ ),
1161+)]
1162+async fn list_questions(
1163+ State(st): State<AppState>,
1164+ _teacher: RequireTeacher,
1165+ Path(id): Path<String>,
1166+) -> Result<Json<Vec<QuestionResponse>>, AppError> {
1167+ let exam_id = ExamId::from_key(&id);
1168+ Exam::read(&exam_id, &st.db)
1169+ .await?
1170+ .ok_or(AppError::NotFound)?;
1171+ let questions = ExamQuestion::list_for_exam(&exam_id, &st.db).await?;
1172+ Ok(Json(questions.iter().map(QuestionResponse::new).collect()))
1173+}
1174+
1175+/// Edit a question. Requires teacher+ and management rights over the exam's
1176+/// course. Omitted fields keep their value; `kind`/`choices`/`correct` are
1177+/// re-validated as a unit, so a kind switch must bring the matching fields
1178+/// along. Locked once attempts exist.
1179+#[utoipa::path(
1180+ patch,
1181+ path = "/{id}/questions/{qid}",
1182+ tag = "exams",
1183+ security(("session_cookie" = [])),
1184+ params(
1185+ ("id" = String, Path, description = "Exam id"),
1186+ ("qid" = String, Path, description = "Question id"),
1187+ ),
1188+ request_body = UpdateQuestion,
1189+ responses(
1190+ (status = 200, description = "Updated question", body = QuestionResponse),
1191+ (status = 400, description = "Invalid text, kind, points, choices, or correct", body = ErrorResponse),
1192+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1193+ (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1194+ (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
1195+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
1196+ ),
1197+)]
1198+async fn update_question(
1199+ State(st): State<AppState>,
1200+ RequireTeacher(user): RequireTeacher,
1201+ Path((id, qid)): Path<(String, String)>,
1202+ Json(req): Json<UpdateQuestion>,
1203+) -> Result<Json<QuestionResponse>, AppError> {
1204+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1205+ .await?
1206+ .ok_or(AppError::NotFound)?;
1207+ let course = course_of(&exam, &st.db).await?;
1208+ if !can_manage_course(&course, &user) {
1209+ return Err(AppError::Forbidden(
1210+ "only the course creator or a manager/admin can edit questions",
1211+ ));
1212+ }
1213+ ensure_questions_editable(exam.get_id(), &st.db).await?;
1214+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
1215+
1216+ let text = match req.text {
1217+ Some(ref text) => QuestionText::try_new(text)?,
1218+ None => question.get_text().clone(),
1219+ };
1220+ let points = match req.points {
1221+ Some(points) => QuestionPoints::try_new(points)?,
1222+ None => question.get_points(),
1223+ };
1224+ // Merge the kind-dependent fields (set / clear / keep per field), then
1225+ // re-validate them as a unit — a PATCH can't leave a half-question behind.
1226+ let kind = match req.kind {
1227+ Some(ref kind) => QuestionKind::try_new(kind)?,
1228+ None => question.get_kind().clone(),
1229+ };
1230+ let choices = match req.choices {
1231+ Some(update) => update,
1232+ None => question
1233+ .get_choices()
1234+ .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()),
1235+ };
1236+ let correct = match req.correct {
1237+ Some(update) => update,
1238+ None => question.get_correct(),
1239+ };
1240+ let spec = QuestionSpec::try_new(kind, choices, correct)?;
1241+
1242+ let updated = question.update(text, points, spec, &st.db).await?;
1243+ Ok(Json(QuestionResponse::new(&updated)))
1244+}
1245+
1246+/// Remove a question (and every answer to it). Requires teacher+ and
1247+/// management rights over the exam's course. Locked once attempts exist.
1248+#[utoipa::path(
1249+ delete,
1250+ path = "/{id}/questions/{qid}",
1251+ tag = "exams",
1252+ security(("session_cookie" = [])),
1253+ params(
1254+ ("id" = String, Path, description = "Exam id"),
1255+ ("qid" = String, Path, description = "Question id"),
1256+ ),
1257+ responses(
1258+ (status = 204, description = "Deleted"),
1259+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1260+ (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1261+ (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
1262+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
1263+ ),
1264+)]
1265+async fn delete_question(
1266+ State(st): State<AppState>,
1267+ RequireTeacher(user): RequireTeacher,
1268+ Path((id, qid)): Path<(String, String)>,
1269+) -> Result<StatusCode, AppError> {
1270+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1271+ .await?
1272+ .ok_or(AppError::NotFound)?;
1273+ let course = course_of(&exam, &st.db).await?;
1274+ if !can_manage_course(&course, &user) {
1275+ return Err(AppError::Forbidden(
1276+ "only the course creator or a manager/admin can delete questions",
1277+ ));
1278+ }
1279+ ensure_questions_editable(exam.get_id(), &st.db).await?;
1280+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
1281+ question.delete(&st.db).await?;
1282+ Ok(StatusCode::NO_CONTENT)
1283+}
1284+
1285+// ---- answers ----------------------------------------------------------------
1286+// Students answer inside their attempt; every save is an upsert stamped with
1287+// the server clock. The WebSocket room (`/exams/{id}/attempt/ws`) drives the
1288+// same paths below.
1289+
1290+/// A student's own saved answer, embedded in their question view.
1291+#[derive(Serialize, ToSchema)]
1292+struct AnswerStateResponse {
1293+ /// The picked option's zero-based index (`choice` questions).
1294+ selected: Option<i64>,
1295+ /// The typed answer (`text` questions).
1296+ text: Option<String>,
1297+ /// When this answer was last saved, UTC unix-milliseconds.
1298+ updated_at: i64,
1299+}
1300+
1301+impl AnswerStateResponse {
1302+ fn new(answer: &ExamAnswer) -> Self {
1303+ Self {
1304+ selected: answer.get_selected(),
1305+ text: answer.get_text().map(|t| t.as_str().to_string()),
1306+ updated_at: answer.get_updated_at().as_millis(),
1307+ }
1308+ }
1309+}
1310+
1311+/// A question as the sitting student sees it: no `correct` index, their own
1312+/// saved answer embedded.
1313+#[derive(Serialize, ToSchema)]
1314+struct AttemptQuestionResponse {
1315+ id: String,
1316+ text: String,
1317+ /// `choice` or `text`.
1318+ #[schema(example = "choice")]
1319+ kind: String,
1320+ points: i64,
1321+ choices: Option<Vec<String>>,
1322+ /// The caller's saved answer; `null` while unanswered.
1323+ answer: Option<AnswerStateResponse>,
1324+}
1325+
1326+#[derive(Deserialize, ToSchema)]
1327+struct SaveAnswer {
1328+ /// The question being answered.
1329+ question_id: String,
1330+ /// The picked option's zero-based index — required for `choice` questions.
1331+ selected: Option<i64>,
1332+ /// The typed answer — required for `text` questions (empty clears the draft).
1333+ text: Option<String>,
1334+}
1335+
1336+#[derive(Serialize, ToSchema)]
1337+struct AnswerSavedResponse {
1338+ question: String,
1339+ selected: Option<i64>,
1340+ text: Option<String>,
1341+ /// Save instant by the server clock, UTC unix-milliseconds.
1342+ updated_at: i64,
1343+}
1344+
1345+/// The caller's attempt provided it is still writable, or the error that says
1346+/// why not: no attempt yet (404 — start it first), already submitted (409),
1347+/// deadline passed (409). One gate shared by REST saves and the WebSocket room.
1348+pub(crate) async fn writable_attempt(
1349+ exam: &Exam,
1350+ user: &UserId,
1351+ db: &Database,
1352+) -> Result<ExamAttempt, AppError> {
1353+ let attempt = ExamAttempt::read_for_user(exam.get_id(), user, db)
1354+ .await?
1355+ .ok_or(AppError::NotFound)?;
1356+ match attempt.status(exam, Timestamp::now()) {
1357+ AttemptStatus::Submitted => Err(AppError::Conflict("the attempt is already submitted")),
1358+ AttemptStatus::Expired => Err(AppError::Conflict("time is up — the attempt has expired")),
1359+ AttemptStatus::InProgress => Ok(attempt),
1360+ }
1361+}
1362+
1363+/// Save one answer inside the caller's in-progress attempt — the whole write
1364+/// path (attempt gate, question lookup, kind check, upsert), shared verbatim
1365+/// by the REST handler and the WebSocket room so the two can never drift.
1366+pub(crate) async fn save_answer_checked(
1367+ exam: &Exam,
1368+ user: &UserId,
1369+ question_id: &str,
1370+ selected: Option<i64>,
1371+ text: Option<String>,
1372+ db: &Database,
1373+) -> Result<ExamAnswer, AppError> {
1374+ writable_attempt(exam, user, db).await?;
1375+ let question = question_of_exam(exam.get_id(), question_id, db).await?;
1376+ ExamAnswer::save(&question, user, selected, text, db).await
1377+}
1378+
1379+/// The exam's questions as the sitting student sees them: `correct` stripped,
1380+/// their own saved answers embedded. Requires an attempt — start one with
1381+/// `POST /exams/{id}/attempt` first (404 until then). Readable in every
1382+/// attempt state, so a submitted student can still review what they wrote.
1383+#[utoipa::path(
1384+ get,
1385+ path = "/{id}/attempt/questions",
1386+ tag = "exams",
1387+ security(("session_cookie" = [])),
1388+ params(("id" = String, Path, description = "Exam id")),
1389+ responses(
1390+ (status = 200, description = "Questions with the caller's answers embedded", body = [AttemptQuestionResponse]),
1391+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1392+ (status = 404, description = "No such exam, or no attempt yet — start the attempt first", body = ErrorResponse),
1393+ ),
1394+)]
1395+async fn attempt_questions(
1396+ State(st): State<AppState>,
1397+ CurrentUser(user): CurrentUser,
1398+ Path(id): Path<String>,
1399+) -> Result<Json<Vec<AttemptQuestionResponse>>, AppError> {
1400+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1401+ .await?
1402+ .ok_or(AppError::NotFound)?;
1403+ // The question list is for sitting students; without an attempt there is
1404+ // nothing to sit behind — and no early peek at the questions.
1405+ ExamAttempt::read_for_user(exam.get_id(), user.get_id(), &st.db)
1406+ .await?
1407+ .ok_or(AppError::NotFound)?;
1408+
1409+ let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?;
1410+ let answers: HashMap<String, ExamAnswer> =
1411+ ExamAnswer::list_for_exam_user(exam.get_id(), user.get_id(), &st.db)
1412+ .await?
1413+ .into_iter()
1414+ .map(|answer| (answer.get_question().key().to_string(), answer))
1415+ .collect();
1416+ Ok(Json(
1417+ questions
1418+ .iter()
1419+ .map(|question| AttemptQuestionResponse {
1420+ id: question.get_id().key().to_string(),
1421+ text: question.get_text().as_str().to_string(),
1422+ kind: question.get_kind().as_str().to_string(),
1423+ points: question.get_points().as_i64(),
1424+ choices: question
1425+ .get_choices()
1426+ .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()),
1427+ answer: answers
1428+ .get(question.get_id().key())
1429+ .map(AnswerStateResponse::new),
1430+ })
1431+ .collect(),
1432+ ))
1433+}
1434+
1435+/// Save (or overwrite) one answer in the caller's in-progress attempt.
1436+/// `choice` questions take `selected`; `text` questions take `text`. Rejected
1437+/// once the attempt is submitted or its deadline has passed — the server
1438+/// clock, not the client's, is the judge.
1439+#[utoipa::path(
1440+ post,
1441+ path = "/{id}/attempt/answers",
1442+ tag = "exams",
1443+ security(("session_cookie" = [])),
1444+ params(("id" = String, Path, description = "Exam id")),
1445+ request_body = SaveAnswer,
1446+ responses(
1447+ (status = 200, description = "Answer saved", body = AnswerSavedResponse),
1448+ (status = 400, description = "Payload doesn't match the question's kind", body = ErrorResponse),
1449+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1450+ (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse),
1451+ (status = 409, description = "Attempt already submitted, or time is up", body = ErrorResponse),
1452+ ),
1453+)]
1454+async fn save_answer(
1455+ State(st): State<AppState>,
1456+ CurrentUser(user): CurrentUser,
1457+ Path(id): Path<String>,
1458+ Json(req): Json<SaveAnswer>,
1459+) -> Result<Json<AnswerSavedResponse>, AppError> {
1460+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1461+ .await?
1462+ .ok_or(AppError::NotFound)?;
1463+ let answer = save_answer_checked(
1464+ &exam,
1465+ user.get_id(),
1466+ &req.question_id,
1467+ req.selected,
1468+ req.text,
1469+ &st.db,
1470+ )
1471+ .await?;
1472+ Ok(Json(AnswerSavedResponse {
1473+ question: answer.get_question().key().to_string(),
1474+ selected: answer.get_selected(),
1475+ text: answer.get_text().map(|t| t.as_str().to_string()),
1476+ updated_at: answer.get_updated_at().as_millis(),
1477+ }))
1478+}
1479+
1480+/// One student's answer sheet with correctness flags. Every row carries the
1481+/// saved answer plus `is_correct` (`null` for text questions — those are the
1482+/// grader's call), and the machine's `auto_score` over the choice questions is
1483+/// attached as a *suggestion*: the final mark stays human, via
1484+/// `POST /exams/{id}/results`. Requires teacher+.
1485+#[utoipa::path(
1486+ get,
1487+ path = "/{id}/attempts/{user}/answers",
1488+ tag = "exams",
1489+ security(("session_cookie" = [])),
1490+ params(
1491+ ("id" = String, Path, description = "Exam id"),
1492+ ("user" = String, Path, description = "User id"),
1493+ ),
1494+ responses(
1495+ (status = 200, description = "The student's answers, judged", body = AttemptAnswersResponse),
1496+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1497+ (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
1498+ (status = 404, description = "No such exam, or the student has no attempt", body = ErrorResponse),
1499+ ),
1500+)]
1501+async fn attempt_answers(
1502+ State(st): State<AppState>,
1503+ _teacher: RequireTeacher,
1504+ Path((id, target)): Path<(String, String)>,
1505+) -> Result<Json<AttemptAnswersResponse>, AppError> {
1506+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1507+ .await?
1508+ .ok_or(AppError::NotFound)?;
1509+ let target = UserId::from_key(&target);
1510+ // No attempt means no answer sheet — a 404, not an empty one.
1511+ ExamAttempt::read_for_user(exam.get_id(), &target, &st.db)
1512+ .await?
1513+ .ok_or(AppError::NotFound)?;
1514+
1515+ let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?;
1516+ let answers = ExamAnswer::list_for_exam_user(exam.get_id(), &target, &st.db).await?;
1517+ let by_question: HashMap<&str, &ExamQuestion> = questions
1518+ .iter()
1519+ .map(|question| (question.get_id().key(), question))
1520+ .collect();
1521+ let (earned, possible) = auto_score(&questions, &answers);
1522+ let people = person_map([target.clone()], &st.db).await?;
1523+ Ok(Json(AttemptAnswersResponse {
1524+ exam: exam.get_id().key().to_string(),
1525+ user: PersonRef::resolve(&people, &target),
1526+ answers: answers
1527+ .iter()
1528+ .map(|answer| StudentAnswerResponse {
1529+ question: answer.get_question().key().to_string(),
1530+ selected: answer.get_selected(),
1531+ text: answer.get_text().map(|t| t.as_str().to_string()),
1532+ updated_at: answer.get_updated_at().as_millis(),
1533+ is_correct: by_question
1534+ .get(answer.get_question().key())
1535+ .and_then(|question| answer.is_correct(question)),
1536+ })
1537+ .collect(),
1538+ auto_score: AutoScoreResponse { earned, possible },
1539+ }))
1540+}
1541+
1542+/// One row of a student's answer sheet, as the grader sees it.
1543+#[derive(Serialize, ToSchema)]
1544+struct StudentAnswerResponse {
1545+ question: String,
1546+ selected: Option<i64>,
1547+ text: Option<String>,
1548+ /// When the answer was last saved, UTC unix-milliseconds.
1549+ updated_at: i64,
1550+ /// Whether `selected` hits the question's `correct`; `null` for text
1551+ /// questions (the grader judges those).
1552+ is_correct: Option<bool>,
1553+}
1554+
1555+/// The machine's scoring suggestion over the choice questions.
1556+#[derive(Serialize, ToSchema)]
1557+struct AutoScoreResponse {
1558+ /// Points earned where `selected == correct`.
1559+ earned: i64,
1560+ /// Total points across the exam's choice questions.
1561+ possible: i64,
1562+}
1563+
1564+/// A student's full answer sheet for grading.
1565+#[derive(Serialize, ToSchema)]
1566+struct AttemptAnswersResponse {
1567+ exam: String,
1568+ /// The student whose sheet this is.
1569+ user: PersonRef,
1570+ answers: Vec<StudentAnswerResponse>,
1571+ /// The suggested score over choice questions — never the final mark.
1572+ auto_score: AutoScoreResponse,
1573+}
src/web/mod.rsmodified+15 -1
@@ -6,6 +6,7 @@
6 pub mod auth;6 pub mod auth;
7 pub mod courses;7 pub mod courses;
8 pub mod events;8 pub mod events;
9+pub mod exam_ws;
9 pub mod exams;10 pub mod exams;
10 pub mod marks;11 pub mod marks;
11 pub mod notes;12 pub mod notes;
@@ -14,5 +15,18 @@ pub mod users;
14 mod dto;15 mod dto;
15 mod extractor;16 mod extractor;
16 17
17-pub use dto::{CourseResponse, ExamResponse, UserResponse};18+pub use dto::{CourseResponse, ExamResponse, PersonRef, UserResponse, person_map};
18 pub use extractor::{CurrentUser, RequireAdmin, RequireTeacher};19 pub use extractor::{CurrentUser, RequireAdmin, RequireTeacher};
20+
21+use serde::{Deserialize, Deserializer};
22+
23+/// Distinguishes an *absent* PATCH field from an explicit `null`: absent never
24+/// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the
25+/// stored value); `null` or a value lands here as `Some(inner)` (clear or set).
26+pub(crate) fn set_or_clear<'de, D, T>(de: D) -> Result<Option<Option<T>>, D::Error>
27+where
28+ D: Deserializer<'de>,
29+ T: Deserialize<'de>,
30+{
31+ Option::<T>::deserialize(de).map(Some)
32+}
src/web/users.rsmodified+41 -3
@@ -1,7 +1,7 @@
1 use axum::Json;1 use axum::Json;
2-use axum::extract::{Path, State};2+use axum::extract::{Path, Query, State};
3 use serde::Deserialize;3 use serde::Deserialize;
4-use utoipa::ToSchema;4+use utoipa::{IntoParams, ToSchema};
5 use utoipa_axum::router::OpenApiRouter;5 use utoipa_axum::router::OpenApiRouter;
6 use utoipa_axum::routes;6 use utoipa_axum::routes;
7 7
@@ -13,12 +13,13 @@ use crate::error::{AppError, ErrorResponse, ValidationError};
13 use crate::state::AppState;13 use crate::state::AppState;
14 14
15 use super::dto::Role as RoleSchema;15 use super::dto::Role as RoleSchema;
16-use super::{CurrentUser, RequireAdmin, UserResponse};16+use super::{CurrentUser, PersonRef, RequireAdmin, RequireTeacher, UserResponse};
17 17
18 pub fn routes() -> OpenApiRouter<AppState> {18 pub fn routes() -> OpenApiRouter<AppState> {
19 OpenApiRouter::new()19 OpenApiRouter::new()
20 .routes(routes!(list_users))20 .routes(routes!(list_users))
21 .routes(routes!(update_my_profile))21 .routes(routes!(update_my_profile))
22+ .routes(routes!(search_users))
22 .routes(routes!(get_user))23 .routes(routes!(get_user))
23 .routes(routes!(set_role))24 .routes(routes!(set_role))
24 .routes(routes!(update_user_profile))25 .routes(routes!(update_user_profile))
@@ -90,6 +91,43 @@ async fn apply_profile(
90 Ok(UserResponse::new(&updated))91 Ok(UserResponse::new(&updated))
91 }92 }
92 93
94+#[derive(Deserialize, IntoParams)]
95+struct SearchUsers {
96+ /// Case-insensitive fragment of a username, name, or surname.
97+ q: String,
98+}
99+
100+/// Find users by username or name — backs the pickers (enroll, grade, mark
101+/// attendance). Requires teacher+. Returns at most 10 matches, and only
102+/// id/username/display name — no contact details.
103+#[utoipa::path(
104+ get,
105+ path = "/search",
106+ tag = "users",
107+ security(("session_cookie" = [])),
108+ params(SearchUsers),
109+ responses(
110+ (status = 200, description = "Matching users, at most 10", body = [PersonRef]),
111+ (status = 400, description = "Empty query", body = ErrorResponse),
112+ (status = 401, description = "Not authenticated", body = ErrorResponse),
113+ (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
114+ ),
115+)]
116+async fn search_users(
117+ State(st): State<AppState>,
118+ _teacher: RequireTeacher,
119+ Query(req): Query<SearchUsers>,
120+) -> Result<Json<Vec<PersonRef>>, AppError> {
121+ if req.q.trim().is_empty() {
122+ return Err(AppError::Validation(ValidationError::Invalid {
123+ field: "q",
124+ reason: "must not be empty",
125+ }));
126+ }
127+ let users = User::search(&req.q, &st.db).await?;
128+ Ok(Json(users.iter().map(PersonRef::new).collect()))
129+}
130+
93 /// List every user with their role. Admin only.131 /// List every user with their role. Admin only.
94 #[utoipa::path(132 #[utoipa::path(
95 get,133 get,