Migrate persistence core from SurrealDB to PostgreSQL/sqlx
Browse files at this commitddc470a06ccf0775afe60d29a10e1e4db3383334Parent: ea35e58- feat
- migrate persistence core from SurrealDB to PostgreSQL/sqlx
93 changed files +5094 -10453
- .env.example +8 -9
- .sqlx/.gitkeep +0 -0
- Cargo.lock +327 -2692
- Cargo.toml +2 -3
- Containerfile +7 -3
- compose.yaml +14 -25
- migrations/control/20260912000001_control.sql +60 -0
- migrations/school/20260912000001_identity.sql +275 -0
- migrations/school/20260912000002_courses.sql +208 -0
- migrations/school/20260912000003_exams.sql +242 -0
- migrations/school/20260912000004_food_appointments_fees.sql +205 -0
- scripts/prepare_db.sh +44 -0
- src/ai/server.rs +9 -31
- src/config.rs +7 -15
- src/database.rs +338 -1256
- src/db/cap.rs +201 -1215
- src/db/field_update.rs +319 -362
- src/db/page.rs +178 -175
- src/domain/answer_image.rs +30 -31
- src/domain/appointment.rs +47 -86
- src/domain/appointment_slot.rs +34 -35
- src/domain/attendance.rs +23 -27
- src/domain/badge.rs +11 -9
- src/domain/bank_question.rs +27 -50
- src/domain/bank_question_image.rs +35 -37
- src/domain/board.rs +37 -43
- src/domain/board_stroke.rs +25 -28
- src/domain/builder.rs +16 -18
- src/domain/chatbot_message.rs +47 -82
- src/domain/chatbot_thread.rs +18 -22
- src/domain/class_blueprint.rs +24 -30
- src/domain/class_course.rs +25 -27
- src/domain/class_group.rs +17 -22
- src/domain/class_member.rs +24 -25
- src/domain/course.rs +23 -82
- src/domain/course_note.rs +18 -22
- src/domain/course_note_file.rs +18 -27
- src/domain/course_session.rs +17 -22
- src/domain/dietary_profile.rs +26 -25
- src/domain/enrollment.rs +24 -62
- src/domain/event.rs +109 -120
- src/domain/exam.rs +36 -47
- src/domain/exam_answer.rs +32 -32
- src/domain/exam_attempt.rs +25 -27
- src/domain/exam_question.rs +53 -49
- src/domain/exam_result.rs +63 -41
- src/domain/fee_plan.rs +38 -25
- src/domain/fee_plan_assignment.rs +61 -29
- src/domain/homework.rs +34 -34
- src/domain/homework_file.rs +25 -32
- src/domain/homework_result.rs +28 -37
- src/domain/homework_submission.rs +24 -30
- src/domain/key.rs +32 -27
- src/domain/meal_attendance.rs +45 -29
- src/domain/meal_booking.rs +105 -90
- src/domain/meal_ledger.rs +92 -95
- src/domain/menu.rs +40 -59
- src/domain/menu_dish.rs +32 -38
- src/domain/message.rs +51 -36
- src/domain/mod.rs +53 -2
- src/domain/monotonic_id.rs +30 -25
- src/domain/note.rs +24 -20
- src/domain/note_file.rs +26 -23
- src/domain/parent_link.rs +35 -26
- src/domain/payment_ledger.rs +96 -104
- src/domain/pomodoro.rs +40 -43
- src/domain/pool_question.rs +26 -24
- src/domain/preferences.rs +25 -24
- src/domain/profile.rs +13 -9
- src/domain/question_image.rs +62 -37
- src/domain/rag_output.rs +25 -23
- src/domain/registration.rs +38 -27
- src/domain/role.rs +19 -16
- src/domain/session.rs +16 -17
- src/domain/session_attendance.rs +37 -27
- src/domain/settings.rs +34 -27
- src/domain/solution.rs +24 -32
- src/domain/subject.rs +28 -24
- src/domain/term.rs +28 -37
- src/domain/text_fold.rs +33 -30
- src/domain/timestamp.rs +22 -7
- src/domain/user.rs +35 -33
- src/domain/work_entry.rs +25 -43
- src/error.rs +51 -59
- src/lib.rs +35 -43
- src/main.rs +1 -77
- src/migration_sql.rs +0 -1524
- src/rate_limit.rs +59 -122
- src/state.rs +0 -42
- src/tenant.rs +217 -427
- src/web/auth.rs +1 -1
- src/web/builder.rs +1 -1
- src/web/tenant_state.rs +0 -2
.env.examplemodified+8 -9
| @@ -2,15 +2,14 @@ | |||
| 2 | HOST=127.0.0.1 | 2 | HOST=127.0.0.1 |
| 3 | PORT=8080 | 3 | PORT=8080 |
| 4 | 4 | ||
| 5 | -# SurrealDB server endpoint + root credentials. For local dev start one with: | 5 | +# PostgreSQL connection string. Also read by sqlx's compile-time query macros, |
| 6 | -# surreal start --user root --pass root surrealkv:./data/hezarfen.db | 6 | +# so `cargo check` prepares every query against this database. For local dev: |
| 7 | -DB_URL=ws://127.0.0.1:8000 | 7 | +# podman compose up -d postgres |
| 8 | -DB_USER=root | 8 | +DATABASE_URL=postgres://hezarfen:hezarfen@127.0.0.1:5432/hezarfen_control |
| 9 | -DB_PASS=root | 9 | + |
| 10 | -DB_NAMESPACE=hezarfen | 10 | +# The maintenance database tests clone scratch databases from (see |
| 11 | -# The CONTROL database: the school registry and the builder accounts. Each | 11 | +# tests/common). Uncomment to override the default. |
| 12 | -# school gets a database of its own inside DB_NAMESPACE, named by its slug. | 12 | +# HEZARFEN_TEST_DATABASE_URL=postgres://hezarfen:hezarfen@127.0.0.1:5432/postgres |
| 13 | -DB_DATABASE=control | ||
| 14 | 13 | ||
| 15 | # Directory for uploaded note-file blobs (created at startup). Each school | 14 | # Directory for uploaded note-file blobs (created at startup). Each school |
| 16 | # writes into a subdirectory of it named by its slug. | 15 | # writes into a subdirectory of it named by its slug. |
.sqlx/.gitkeepadded+0 -0
Cargo.lockmodified+327 -2692
Diff too large; view file
| @@ -2,62 +2,12 @@ | |||
| 2 | # It is not intended for manual editing. | 2 | # It is not intended for manual editing. |
| 3 | version = 4 | 3 | version = 4 |
| 4 | 4 | ||
| 5 | -[[package]] | ||
| 6 | -name = "addr" | ||
| 7 | -version = "0.15.6" | ||
| 8 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 9 | -checksum = "a93b8a41dbe230ad5087cc721f8d41611de654542180586b315d9f4cf6b72bef" | ||
| 10 | -dependencies = [ | ||
| 11 | - "psl-types", | ||
| 12 | -] | ||
| 13 | - | ||
| 14 | [[package]] | 5 | [[package]] |
| 15 | name = "adler2" | 6 | name = "adler2" |
| 16 | version = "2.0.1" | 7 | version = "2.0.1" |
| 17 | source = "registry+https://github.com/rust-lang/crates.io-index" | 8 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 18 | checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" | 9 | checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" |
| 19 | 10 | ||
| 20 | -[[package]] | ||
| 21 | -name = "affinitypool" | ||
| 22 | -version = "0.7.0" | ||
| 23 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 24 | -checksum = "c4a46f56d354df11b6bcd8ca4f84fa03ac816cc41c72568a1b337d8f7e5af90e" | ||
| 25 | -dependencies = [ | ||
| 26 | - "arc-swap", | ||
| 27 | - "async-task", | ||
| 28 | - "crossbeam-deque", | ||
| 29 | - "crossbeam-utils", | ||
| 30 | - "libc", | ||
| 31 | - "num_cpus", | ||
| 32 | - "parking_lot", | ||
| 33 | - "thiserror", | ||
| 34 | - "winapi", | ||
| 35 | -] | ||
| 36 | - | ||
| 37 | -[[package]] | ||
| 38 | -name = "ahash" | ||
| 39 | -version = "0.7.8" | ||
| 40 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 41 | -checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" | ||
| 42 | -dependencies = [ | ||
| 43 | - "getrandom 0.2.17", | ||
| 44 | - "once_cell", | ||
| 45 | - "version_check", | ||
| 46 | -] | ||
| 47 | - | ||
| 48 | -[[package]] | ||
| 49 | -name = "ahash" | ||
| 50 | -version = "0.8.12" | ||
| 51 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 52 | -checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" | ||
| 53 | -dependencies = [ | ||
| 54 | - "cfg-if", | ||
| 55 | - "getrandom 0.3.4", | ||
| 56 | - "once_cell", | ||
| 57 | - "version_check", | ||
| 58 | - "zerocopy", | ||
| 59 | -] | ||
| 60 | - | ||
| 61 | [[package]] | 11 | [[package]] |
| 62 | name = "aho-corasick" | 12 | name = "aho-corasick" |
| 63 | version = "1.1.4" | 13 | version = "1.1.4" |
| @@ -73,18 +23,6 @@ version = "0.2.21" | |||
| 73 | source = "registry+https://github.com/rust-lang/crates.io-index" | 23 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 74 | checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" | 24 | checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" |
| 75 | 25 | ||
| 76 | -[[package]] | ||
| 77 | -name = "ammonia" | ||
| 78 | -version = "4.1.4" | ||
| 79 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 80 | -checksum = "dc6d763210e2eb7670d1a5183a08bebefa3f97db2a738a684f2ce00bd49f681d" | ||
| 81 | -dependencies = [ | ||
| 82 | - "cssparser", | ||
| 83 | - "html5ever", | ||
| 84 | - "maplit", | ||
| 85 | - "url", | ||
| 86 | -] | ||
| 87 | - | ||
| 88 | [[package]] | 26 | [[package]] |
| 89 | name = "android_system_properties" | 27 | name = "android_system_properties" |
| 90 | version = "0.1.5" | 28 | version = "0.1.5" |
| @@ -100,15 +38,6 @@ version = "1.0.104" | |||
| 100 | source = "registry+https://github.com/rust-lang/crates.io-index" | 38 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 101 | checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" | 39 | checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" |
| 102 | 40 | ||
| 103 | -[[package]] | ||
| 104 | -name = "approx" | ||
| 105 | -version = "0.5.1" | ||
| 106 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 107 | -checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" | ||
| 108 | -dependencies = [ | ||
| 109 | - "num-traits", | ||
| 110 | -] | ||
| 111 | - | ||
| 112 | [[package]] | 41 | [[package]] |
| 113 | name = "arbitrary" | 42 | name = "arbitrary" |
| 114 | version = "1.4.2" | 43 | version = "1.4.2" |
| @@ -118,27 +47,6 @@ dependencies = [ | |||
| 118 | "derive_arbitrary", | 47 | "derive_arbitrary", |
| 119 | ] | 48 | ] |
| 120 | 49 | ||
| 121 | -[[package]] | ||
| 122 | -name = "arc-swap" | ||
| 123 | -version = "1.9.2" | ||
| 124 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 125 | -checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" | ||
| 126 | -dependencies = [ | ||
| 127 | - "rustversion", | ||
| 128 | -] | ||
| 129 | - | ||
| 130 | -[[package]] | ||
| 131 | -name = "argon2" | ||
| 132 | -version = "0.5.3" | ||
| 133 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 134 | -checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" | ||
| 135 | -dependencies = [ | ||
| 136 | - "base64ct", | ||
| 137 | - "blake2 0.10.6", | ||
| 138 | - "cpufeatures 0.2.17", | ||
| 139 | - "password-hash 0.5.0", | ||
| 140 | -] | ||
| 141 | - | ||
| 142 | [[package]] | 50 | [[package]] |
| 143 | name = "argon2" | 51 | name = "argon2" |
| 144 | version = "0.6.0" | 52 | version = "0.6.0" |
| @@ -146,33 +54,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 146 | checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c" | 54 | checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c" |
| 147 | dependencies = [ | 55 | dependencies = [ |
| 148 | "base64ct", | 56 | "base64ct", |
| 149 | - "blake2 0.11.0", | 57 | + "blake2", |
| 150 | "cpufeatures 0.3.1", | 58 | "cpufeatures 0.3.1", |
| 151 | - "password-hash 0.6.1", | 59 | + "password-hash", |
| 152 | -] | ||
| 153 | - | ||
| 154 | -[[package]] | ||
| 155 | -name = "arrayref" | ||
| 156 | -version = "0.3.9" | ||
| 157 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 158 | -checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" | ||
| 159 | - | ||
| 160 | -[[package]] | ||
| 161 | -name = "arrayvec" | ||
| 162 | -version = "0.7.8" | ||
| 163 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 164 | -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" | ||
| 165 | - | ||
| 166 | -[[package]] | ||
| 167 | -name = "as-slice" | ||
| 168 | -version = "0.1.5" | ||
| 169 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 170 | -checksum = "45403b49e3954a4b8428a0ac21a4b7afadccf92bfd96273f1a58cd4812496ae0" | ||
| 171 | -dependencies = [ | ||
| 172 | - "generic-array 0.12.4", | ||
| 173 | - "generic-array 0.13.3", | ||
| 174 | - "generic-array 0.14.7", | ||
| 175 | - "stable_deref_trait", | ||
| 176 | ] | 60 | ] |
| 177 | 61 | ||
| 178 | [[package]] | 62 | [[package]] |
| @@ -214,46 +98,6 @@ dependencies = [ | |||
| 214 | "syn 2.0.119", | 98 | "syn 2.0.119", |
| 215 | ] | 99 | ] |
| 216 | 100 | ||
| 217 | -[[package]] | ||
| 218 | -name = "async-channel" | ||
| 219 | -version = "2.5.0" | ||
| 220 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 221 | -checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" | ||
| 222 | -dependencies = [ | ||
| 223 | - "concurrent-queue", | ||
| 224 | - "event-listener-strategy", | ||
| 225 | - "futures-core", | ||
| 226 | - "pin-project-lite", | ||
| 227 | -] | ||
| 228 | - | ||
| 229 | -[[package]] | ||
| 230 | -name = "async-stream" | ||
| 231 | -version = "0.3.6" | ||
| 232 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 233 | -checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" | ||
| 234 | -dependencies = [ | ||
| 235 | - "async-stream-impl", | ||
| 236 | - "futures-core", | ||
| 237 | - "pin-project-lite", | ||
| 238 | -] | ||
| 239 | - | ||
| 240 | -[[package]] | ||
| 241 | -name = "async-stream-impl" | ||
| 242 | -version = "0.3.6" | ||
| 243 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 244 | -checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" | ||
| 245 | -dependencies = [ | ||
| 246 | - "proc-macro2", | ||
| 247 | - "quote", | ||
| 248 | - "syn 2.0.119", | ||
| 249 | -] | ||
| 250 | - | ||
| 251 | -[[package]] | ||
| 252 | -name = "async-task" | ||
| 253 | -version = "4.7.1" | ||
| 254 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 255 | -checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" | ||
| 256 | - | ||
| 257 | [[package]] | 101 | [[package]] |
| 258 | name = "async-trait" | 102 | name = "async-trait" |
| 259 | version = "0.1.91" | 103 | version = "0.1.91" |
| @@ -266,12 +110,12 @@ dependencies = [ | |||
| 266 | ] | 110 | ] |
| 267 | 111 | ||
| 268 | [[package]] | 112 | [[package]] |
| 269 | -name = "atomic-polyfill" | 113 | +name = "atoi" |
| 270 | -version = "1.0.3" | 114 | +version = "2.0.0" |
| 271 | source = "registry+https://github.com/rust-lang/crates.io-index" | 115 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 272 | -checksum = "8cf2bce30dfe09ef0bfaef228b9d414faaf7e563035494d7fe092dba54b300f4" | 116 | +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" |
| 273 | dependencies = [ | 117 | dependencies = [ |
| 274 | - "critical-section", | 118 | + "num-traits", |
| 275 | ] | 119 | ] |
| 276 | 120 | ||
| 277 | [[package]] | 121 | [[package]] |
| @@ -286,30 +130,6 @@ version = "1.5.1" | |||
| 286 | source = "registry+https://github.com/rust-lang/crates.io-index" | 130 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 287 | checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" | 131 | checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" |
| 288 | 132 | ||
| 289 | -[[package]] | ||
| 290 | -name = "aws-lc-rs" | ||
| 291 | -version = "1.17.3" | ||
| 292 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 293 | -checksum = "00bdb5da18dac48ca2cc7cd4a98e533e8635a58e2361d13a1a4ee3888e0d72f1" | ||
| 294 | -dependencies = [ | ||
| 295 | - "aws-lc-sys", | ||
| 296 | - "untrusted 0.7.1", | ||
| 297 | - "zeroize", | ||
| 298 | -] | ||
| 299 | - | ||
| 300 | -[[package]] | ||
| 301 | -name = "aws-lc-sys" | ||
| 302 | -version = "0.43.0" | ||
| 303 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 304 | -checksum = "43103168cc76fe62678a375e722fc9cb3a0146159ac5828bc4f0dfd755c2224c" | ||
| 305 | -dependencies = [ | ||
| 306 | - "cc", | ||
| 307 | - "cmake", | ||
| 308 | - "dunce", | ||
| 309 | - "fs_extra", | ||
| 310 | - "pkg-config", | ||
| 311 | -] | ||
| 312 | - | ||
| 313 | [[package]] | 133 | [[package]] |
| 314 | name = "axum" | 134 | name = "axum" |
| 315 | version = "0.8.9" | 135 | version = "0.8.9" |
| @@ -388,12 +208,6 @@ dependencies = [ | |||
| 388 | "tracing", | 208 | "tracing", |
| 389 | ] | 209 | ] |
| 390 | 210 | ||
| 391 | -[[package]] | ||
| 392 | -name = "base16ct" | ||
| 393 | -version = "0.2.0" | ||
| 394 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 395 | -checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" | ||
| 396 | - | ||
| 397 | [[package]] | 211 | [[package]] |
| 398 | name = "base64" | 212 | name = "base64" |
| 399 | version = "0.22.1" | 213 | version = "0.22.1" |
| @@ -412,39 +226,6 @@ version = "1.8.3" | |||
| 412 | source = "registry+https://github.com/rust-lang/crates.io-index" | 226 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 413 | checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" | 227 | checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" |
| 414 | 228 | ||
| 415 | -[[package]] | ||
| 416 | -name = "bcrypt" | ||
| 417 | -version = "0.18.0" | ||
| 418 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 419 | -checksum = "9a0f5948f30df5f43ac29d310b7476793be97c50787e6ef4a63d960a0d0be827" | ||
| 420 | -dependencies = [ | ||
| 421 | - "base64 0.22.1", | ||
| 422 | - "blowfish", | ||
| 423 | - "getrandom 0.3.4", | ||
| 424 | - "subtle", | ||
| 425 | - "zeroize", | ||
| 426 | -] | ||
| 427 | - | ||
| 428 | -[[package]] | ||
| 429 | -name = "bincode" | ||
| 430 | -version = "2.0.1" | ||
| 431 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 432 | -checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740" | ||
| 433 | -dependencies = [ | ||
| 434 | - "bincode_derive", | ||
| 435 | - "serde", | ||
| 436 | - "unty", | ||
| 437 | -] | ||
| 438 | - | ||
| 439 | -[[package]] | ||
| 440 | -name = "bincode_derive" | ||
| 441 | -version = "2.0.1" | ||
| 442 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 443 | -checksum = "bf95709a440f45e986983918d0e8a1f30a9b1df04918fc828670606804ac3c09" | ||
| 444 | -dependencies = [ | ||
| 445 | - "virtue", | ||
| 446 | -] | ||
| 447 | - | ||
| 448 | [[package]] | 229 | [[package]] |
| 449 | name = "bit-set" | 230 | name = "bit-set" |
| 450 | version = "0.8.0" | 231 | version = "0.8.0" |
| @@ -474,26 +255,8 @@ name = "bitflags" | |||
| 474 | version = "2.13.1" | 255 | version = "2.13.1" |
| 475 | source = "registry+https://github.com/rust-lang/crates.io-index" | 256 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 476 | checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" | 257 | checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" |
| 477 | - | ||
| 478 | -[[package]] | ||
| 479 | -name = "bitvec" | ||
| 480 | -version = "1.1.1" | ||
| 481 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 482 | -checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" | ||
| 483 | -dependencies = [ | ||
| 484 | - "funty", | ||
| 485 | - "radium", | ||
| 486 | - "tap", | ||
| 487 | - "wyz", | ||
| 488 | -] | ||
| 489 | - | ||
| 490 | -[[package]] | ||
| 491 | -name = "blake2" | ||
| 492 | -version = "0.10.6" | ||
| 493 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 494 | -checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" | ||
| 495 | dependencies = [ | 258 | dependencies = [ |
| 496 | - "digest 0.10.7", | 259 | + "serde_core", |
| 497 | ] | 260 | ] |
| 498 | 261 | ||
| 499 | [[package]] | 262 | [[package]] |
| @@ -505,27 +268,13 @@ dependencies = [ | |||
| 505 | "digest 0.11.3", | 268 | "digest 0.11.3", |
| 506 | ] | 269 | ] |
| 507 | 270 | ||
| 508 | -[[package]] | ||
| 509 | -name = "blake3" | ||
| 510 | -version = "1.8.5" | ||
| 511 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 512 | -checksum = "0aa83c34e62843d924f905e0f5c866eb1dd6545fc4d719e803d9ba6030371fce" | ||
| 513 | -dependencies = [ | ||
| 514 | - "arrayref", | ||
| 515 | - "arrayvec", | ||
| 516 | - "cc", | ||
| 517 | - "cfg-if", | ||
| 518 | - "constant_time_eq", | ||
| 519 | - "cpufeatures 0.3.1", | ||
| 520 | -] | ||
| 521 | - | ||
| 522 | [[package]] | 271 | [[package]] |
| 523 | name = "block-buffer" | 272 | name = "block-buffer" |
| 524 | version = "0.10.4" | 273 | version = "0.10.4" |
| 525 | source = "registry+https://github.com/rust-lang/crates.io-index" | 274 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 526 | checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" | 275 | checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" |
| 527 | dependencies = [ | 276 | dependencies = [ |
| 528 | - "generic-array 0.14.7", | 277 | + "generic-array", |
| 529 | ] | 278 | ] |
| 530 | 279 | ||
| 531 | [[package]] | 280 | [[package]] |
| @@ -537,100 +286,12 @@ dependencies = [ | |||
| 537 | "hybrid-array", | 286 | "hybrid-array", |
| 538 | ] | 287 | ] |
| 539 | 288 | ||
| 540 | -[[package]] | ||
| 541 | -name = "blowfish" | ||
| 542 | -version = "0.9.1" | ||
| 543 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 544 | -checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7" | ||
| 545 | -dependencies = [ | ||
| 546 | - "byteorder", | ||
| 547 | - "cipher", | ||
| 548 | -] | ||
| 549 | - | ||
| 550 | -[[package]] | ||
| 551 | -name = "bnum" | ||
| 552 | -version = "0.12.1" | ||
| 553 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 554 | -checksum = "f781dba93de3a5ef6dc5b17c9958b208f6f3f021623b360fb605ea51ce443f10" | ||
| 555 | - | ||
| 556 | -[[package]] | ||
| 557 | -name = "borsh" | ||
| 558 | -version = "1.8.0" | ||
| 559 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 560 | -checksum = "a88b7ea17d208c4193f2c1e6de3c35fe71f98c96982d5ced308bdcc749ff6e1f" | ||
| 561 | -dependencies = [ | ||
| 562 | - "borsh-derive", | ||
| 563 | - "bytes", | ||
| 564 | - "cfg_aliases", | ||
| 565 | -] | ||
| 566 | - | ||
| 567 | -[[package]] | ||
| 568 | -name = "borsh-derive" | ||
| 569 | -version = "1.8.0" | ||
| 570 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 571 | -checksum = "d8f347189c62a579b8cd5f80714efa178f52e461dc2e6d701d264f5ff22e566c" | ||
| 572 | -dependencies = [ | ||
| 573 | - "once_cell", | ||
| 574 | - "proc-macro-crate", | ||
| 575 | - "proc-macro2", | ||
| 576 | - "quote", | ||
| 577 | - "syn 2.0.119", | ||
| 578 | -] | ||
| 579 | - | ||
| 580 | -[[package]] | ||
| 581 | -name = "boxcar" | ||
| 582 | -version = "0.2.14" | ||
| 583 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 584 | -checksum = "36f64beae40a84da1b4b26ff2761a5b895c12adc41dc25aaee1c4f2bbfe97a6e" | ||
| 585 | - | ||
| 586 | [[package]] | 289 | [[package]] |
| 587 | name = "bumpalo" | 290 | name = "bumpalo" |
| 588 | version = "3.20.3" | 291 | version = "3.20.3" |
| 589 | source = "registry+https://github.com/rust-lang/crates.io-index" | 292 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 590 | checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" | 293 | checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" |
| 591 | 294 | ||
| 592 | -[[package]] | ||
| 593 | -name = "bytecheck" | ||
| 594 | -version = "0.6.12" | ||
| 595 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 596 | -checksum = "23cdc57ce23ac53c931e88a43d06d070a6fd142f2617be5855eb75efc9beb1c2" | ||
| 597 | -dependencies = [ | ||
| 598 | - "bytecheck_derive", | ||
| 599 | - "ptr_meta", | ||
| 600 | - "simdutf8", | ||
| 601 | -] | ||
| 602 | - | ||
| 603 | -[[package]] | ||
| 604 | -name = "bytecheck_derive" | ||
| 605 | -version = "0.6.12" | ||
| 606 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 607 | -checksum = "3db406d29fbcd95542e92559bed4d8ad92636d1ca8b3b72ede10b4bcc010e659" | ||
| 608 | -dependencies = [ | ||
| 609 | - "proc-macro2", | ||
| 610 | - "quote", | ||
| 611 | - "syn 1.0.109", | ||
| 612 | -] | ||
| 613 | - | ||
| 614 | -[[package]] | ||
| 615 | -name = "bytemuck" | ||
| 616 | -version = "1.25.2" | ||
| 617 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 618 | -checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" | ||
| 619 | -dependencies = [ | ||
| 620 | - "bytemuck_derive", | ||
| 621 | -] | ||
| 622 | - | ||
| 623 | -[[package]] | ||
| 624 | -name = "bytemuck_derive" | ||
| 625 | -version = "1.11.0" | ||
| 626 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 627 | -checksum = "f65693059b6b9c588b9f62fed1cedbf0a8b805631457ea162d68f0de186f3de5" | ||
| 628 | -dependencies = [ | ||
| 629 | - "proc-macro2", | ||
| 630 | - "quote", | ||
| 631 | - "syn 2.0.119", | ||
| 632 | -] | ||
| 633 | - | ||
| 634 | [[package]] | 295 | [[package]] |
| 635 | name = "byteorder" | 296 | name = "byteorder" |
| 636 | version = "1.5.0" | 297 | version = "1.5.0" |
| @@ -642,18 +303,6 @@ name = "bytes" | |||
| 642 | version = "1.12.1" | 303 | version = "1.12.1" |
| 643 | source = "registry+https://github.com/rust-lang/crates.io-index" | 304 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 644 | checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" | 305 | checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" |
| 645 | -dependencies = [ | ||
| 646 | - "serde", | ||
| 647 | -] | ||
| 648 | - | ||
| 649 | -[[package]] | ||
| 650 | -name = "castaway" | ||
| 651 | -version = "0.2.4" | ||
| 652 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 653 | -checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" | ||
| 654 | -dependencies = [ | ||
| 655 | - "rustversion", | ||
| 656 | -] | ||
| 657 | 306 | ||
| 658 | [[package]] | 307 | [[package]] |
| 659 | name = "cc" | 308 | name = "cc" |
| @@ -662,8 +311,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 662 | checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80" | 311 | checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80" |
| 663 | dependencies = [ | 312 | dependencies = [ |
| 664 | "find-msvc-tools", | 313 | "find-msvc-tools", |
| 665 | - "jobserver", | ||
| 666 | - "libc", | ||
| 667 | "shlex", | 314 | "shlex", |
| 668 | ] | 315 | ] |
| 669 | 316 | ||
| @@ -699,106 +346,38 @@ dependencies = [ | |||
| 699 | "iana-time-zone", | 346 | "iana-time-zone", |
| 700 | "js-sys", | 347 | "js-sys", |
| 701 | "num-traits", | 348 | "num-traits", |
| 702 | - "serde", | ||
| 703 | "wasm-bindgen", | 349 | "wasm-bindgen", |
| 704 | - "windows-link 0.2.1", | 350 | + "windows-link", |
| 705 | ] | 351 | ] |
| 706 | 352 | ||
| 707 | [[package]] | 353 | [[package]] |
| 708 | -name = "ciborium" | 354 | +name = "cmov" |
| 709 | -version = "0.2.2" | 355 | +version = "0.5.4" |
| 710 | source = "registry+https://github.com/rust-lang/crates.io-index" | 356 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 711 | -checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" | 357 | +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" |
| 712 | -dependencies = [ | ||
| 713 | - "ciborium-io", | ||
| 714 | - "ciborium-ll", | ||
| 715 | - "serde", | ||
| 716 | -] | ||
| 717 | 358 | ||
| 718 | [[package]] | 359 | [[package]] |
| 719 | -name = "ciborium-io" | 360 | +name = "const-oid" |
| 720 | -version = "0.2.2" | 361 | +version = "0.10.2" |
| 721 | source = "registry+https://github.com/rust-lang/crates.io-index" | 362 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 722 | -checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" | 363 | +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" |
| 723 | 364 | ||
| 724 | [[package]] | 365 | [[package]] |
| 725 | -name = "ciborium-ll" | 366 | +name = "cookie" |
| 726 | -version = "0.2.2" | 367 | +version = "0.18.1" |
| 727 | source = "registry+https://github.com/rust-lang/crates.io-index" | 368 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 728 | -checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" | 369 | +checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" |
| 729 | dependencies = [ | 370 | dependencies = [ |
| 730 | - "ciborium-io", | 371 | + "percent-encoding", |
| 731 | - "half", | 372 | + "time", |
| 373 | + "version_check", | ||
| 732 | ] | 374 | ] |
| 733 | 375 | ||
| 734 | [[package]] | 376 | [[package]] |
| 735 | -name = "cipher" | 377 | +name = "cookie_store" |
| 736 | -version = "0.4.4" | 378 | +version = "0.22.1" |
| 737 | source = "registry+https://github.com/rust-lang/crates.io-index" | 379 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 738 | -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" | 380 | +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" |
| 739 | -dependencies = [ | ||
| 740 | - "crypto-common 0.1.7", | ||
| 741 | - "inout", | ||
| 742 | -] | ||
| 743 | - | ||
| 744 | -[[package]] | ||
| 745 | -name = "cmake" | ||
| 746 | -version = "0.1.58" | ||
| 747 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 748 | -checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" | ||
| 749 | -dependencies = [ | ||
| 750 | - "cc", | ||
| 751 | -] | ||
| 752 | - | ||
| 753 | -[[package]] | ||
| 754 | -name = "cmov" | ||
| 755 | -version = "0.5.4" | ||
| 756 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 757 | -checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" | ||
| 758 | - | ||
| 759 | -[[package]] | ||
| 760 | -name = "concurrent-queue" | ||
| 761 | -version = "2.5.0" | ||
| 762 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 763 | -checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" | ||
| 764 | -dependencies = [ | ||
| 765 | - "crossbeam-utils", | ||
| 766 | -] | ||
| 767 | - | ||
| 768 | -[[package]] | ||
| 769 | -name = "const-oid" | ||
| 770 | -version = "0.9.6" | ||
| 771 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 772 | -checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" | ||
| 773 | - | ||
| 774 | -[[package]] | ||
| 775 | -name = "const-oid" | ||
| 776 | -version = "0.10.2" | ||
| 777 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 778 | -checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" | ||
| 779 | - | ||
| 780 | -[[package]] | ||
| 781 | -name = "constant_time_eq" | ||
| 782 | -version = "0.4.2" | ||
| 783 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 784 | -checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" | ||
| 785 | - | ||
| 786 | -[[package]] | ||
| 787 | -name = "cookie" | ||
| 788 | -version = "0.18.1" | ||
| 789 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 790 | -checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" | ||
| 791 | -dependencies = [ | ||
| 792 | - "percent-encoding", | ||
| 793 | - "time", | ||
| 794 | - "version_check", | ||
| 795 | -] | ||
| 796 | - | ||
| 797 | -[[package]] | ||
| 798 | -name = "cookie_store" | ||
| 799 | -version = "0.22.1" | ||
| 800 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 801 | -checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" | ||
| 802 | dependencies = [ | 381 | dependencies = [ |
| 803 | "cookie", | 382 | "cookie", |
| 804 | "document-features", | 383 | "document-features", |
| @@ -837,81 +416,43 @@ dependencies = [ | |||
| 837 | ] | 416 | ] |
| 838 | 417 | ||
| 839 | [[package]] | 418 | [[package]] |
| 840 | -name = "crc32fast" | 419 | +name = "crc" |
| 841 | -version = "1.5.0" | 420 | +version = "3.4.0" |
| 842 | source = "registry+https://github.com/rust-lang/crates.io-index" | 421 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 843 | -checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" | 422 | +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" |
| 844 | dependencies = [ | 423 | dependencies = [ |
| 845 | - "cfg-if", | 424 | + "crc-catalog", |
| 846 | ] | 425 | ] |
| 847 | 426 | ||
| 848 | [[package]] | 427 | [[package]] |
| 849 | -name = "critical-section" | 428 | +name = "crc-catalog" |
| 850 | -version = "1.2.0" | 429 | +version = "2.5.0" |
| 851 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 852 | -checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" | ||
| 853 | - | ||
| 854 | -[[package]] | ||
| 855 | -name = "crossbeam-deque" | ||
| 856 | -version = "0.8.7" | ||
| 857 | source = "registry+https://github.com/rust-lang/crates.io-index" | 430 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 858 | -checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" | 431 | +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" |
| 859 | -dependencies = [ | ||
| 860 | - "crossbeam-epoch", | ||
| 861 | - "crossbeam-utils", | ||
| 862 | -] | ||
| 863 | 432 | ||
| 864 | [[package]] | 433 | [[package]] |
| 865 | -name = "crossbeam-epoch" | 434 | +name = "crc32fast" |
| 866 | -version = "0.9.20" | 435 | +version = "1.5.0" |
| 867 | source = "registry+https://github.com/rust-lang/crates.io-index" | 436 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 868 | -checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" | 437 | +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" |
| 869 | dependencies = [ | 438 | dependencies = [ |
| 870 | - "crossbeam-utils", | 439 | + "cfg-if", |
| 871 | ] | 440 | ] |
| 872 | 441 | ||
| 873 | [[package]] | 442 | [[package]] |
| 874 | name = "crossbeam-queue" | 443 | name = "crossbeam-queue" |
| 875 | -version = "0.3.13" | 444 | +version = "0.3.14" |
| 876 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 877 | -checksum = "803d13fb3b09d88be9f4dbc29062c66b19bf7170867ceb746d2a8689bf6c7a26" | ||
| 878 | -dependencies = [ | ||
| 879 | - "crossbeam-utils", | ||
| 880 | -] | ||
| 881 | - | ||
| 882 | -[[package]] | ||
| 883 | -name = "crossbeam-skiplist" | ||
| 884 | -version = "0.1.3" | ||
| 885 | source = "registry+https://github.com/rust-lang/crates.io-index" | 445 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 886 | -checksum = "df29de440c58ca2cc6e587ec3d22347551a32435fbde9d2bff64e78a9ffa151b" | 446 | +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" |
| 887 | dependencies = [ | 447 | dependencies = [ |
| 888 | - "crossbeam-epoch", | ||
| 889 | "crossbeam-utils", | 448 | "crossbeam-utils", |
| 890 | ] | 449 | ] |
| 891 | 450 | ||
| 892 | [[package]] | 451 | [[package]] |
| 893 | name = "crossbeam-utils" | 452 | name = "crossbeam-utils" |
| 894 | -version = "0.8.22" | 453 | +version = "0.8.23" |
| 895 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 896 | -checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" | ||
| 897 | - | ||
| 898 | -[[package]] | ||
| 899 | -name = "crunchy" | ||
| 900 | -version = "0.2.4" | ||
| 901 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 902 | -checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" | ||
| 903 | - | ||
| 904 | -[[package]] | ||
| 905 | -name = "crypto-bigint" | ||
| 906 | -version = "0.5.5" | ||
| 907 | source = "registry+https://github.com/rust-lang/crates.io-index" | 454 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 908 | -checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" | 455 | +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" |
| 909 | -dependencies = [ | ||
| 910 | - "generic-array 0.14.7", | ||
| 911 | - "rand_core 0.6.4", | ||
| 912 | - "subtle", | ||
| 913 | - "zeroize", | ||
| 914 | -] | ||
| 915 | 456 | ||
| 916 | [[package]] | 457 | [[package]] |
| 917 | name = "crypto-common" | 458 | name = "crypto-common" |
| @@ -919,7 +460,7 @@ version = "0.1.7" | |||
| 919 | source = "registry+https://github.com/rust-lang/crates.io-index" | 460 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 920 | checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" | 461 | checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" |
| 921 | dependencies = [ | 462 | dependencies = [ |
| 922 | - "generic-array 0.14.7", | 463 | + "generic-array", |
| 923 | "typenum", | 464 | "typenum", |
| 924 | ] | 465 | ] |
| 925 | 466 | ||
| @@ -932,17 +473,6 @@ dependencies = [ | |||
| 932 | "hybrid-array", | 473 | "hybrid-array", |
| 933 | ] | 474 | ] |
| 934 | 475 | ||
| 935 | -[[package]] | ||
| 936 | -name = "cssparser" | ||
| 937 | -version = "0.37.0" | ||
| 938 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 939 | -checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98" | ||
| 940 | -dependencies = [ | ||
| 941 | - "dtoa-short", | ||
| 942 | - "itoa", | ||
| 943 | - "smallvec", | ||
| 944 | -] | ||
| 945 | - | ||
| 946 | [[package]] | 476 | [[package]] |
| 947 | name = "ctutils" | 477 | name = "ctutils" |
| 948 | version = "0.4.2" | 478 | version = "0.4.2" |
| @@ -952,64 +482,12 @@ dependencies = [ | |||
| 952 | "cmov", | 482 | "cmov", |
| 953 | ] | 483 | ] |
| 954 | 484 | ||
| 955 | -[[package]] | ||
| 956 | -name = "curve25519-dalek" | ||
| 957 | -version = "4.1.3" | ||
| 958 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 959 | -checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" | ||
| 960 | -dependencies = [ | ||
| 961 | - "cfg-if", | ||
| 962 | - "cpufeatures 0.2.17", | ||
| 963 | - "curve25519-dalek-derive", | ||
| 964 | - "digest 0.10.7", | ||
| 965 | - "fiat-crypto", | ||
| 966 | - "rustc_version", | ||
| 967 | - "subtle", | ||
| 968 | - "zeroize", | ||
| 969 | -] | ||
| 970 | - | ||
| 971 | -[[package]] | ||
| 972 | -name = "curve25519-dalek-derive" | ||
| 973 | -version = "0.1.1" | ||
| 974 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 975 | -checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" | ||
| 976 | -dependencies = [ | ||
| 977 | - "proc-macro2", | ||
| 978 | - "quote", | ||
| 979 | - "syn 2.0.119", | ||
| 980 | -] | ||
| 981 | - | ||
| 982 | -[[package]] | ||
| 983 | -name = "dashmap" | ||
| 984 | -version = "6.2.1" | ||
| 985 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 986 | -checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" | ||
| 987 | -dependencies = [ | ||
| 988 | - "cfg-if", | ||
| 989 | - "crossbeam-utils", | ||
| 990 | - "hashbrown 0.14.5", | ||
| 991 | - "lock_api", | ||
| 992 | - "once_cell", | ||
| 993 | - "parking_lot_core", | ||
| 994 | -] | ||
| 995 | - | ||
| 996 | [[package]] | 485 | [[package]] |
| 997 | name = "data-encoding" | 486 | name = "data-encoding" |
| 998 | version = "2.11.1" | 487 | version = "2.11.1" |
| 999 | source = "registry+https://github.com/rust-lang/crates.io-index" | 488 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1000 | checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" | 489 | checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" |
| 1001 | 490 | ||
| 1002 | -[[package]] | ||
| 1003 | -name = "der" | ||
| 1004 | -version = "0.7.10" | ||
| 1005 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1006 | -checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" | ||
| 1007 | -dependencies = [ | ||
| 1008 | - "const-oid 0.9.6", | ||
| 1009 | - "pem-rfc7468", | ||
| 1010 | - "zeroize", | ||
| 1011 | -] | ||
| 1012 | - | ||
| 1013 | [[package]] | 491 | [[package]] |
| 1014 | name = "der-parser" | 492 | name = "der-parser" |
| 1015 | version = "10.0.0" | 493 | version = "10.0.0" |
| @@ -1041,12 +519,6 @@ dependencies = [ | |||
| 1041 | "syn 2.0.119", | 519 | "syn 2.0.119", |
| 1042 | ] | 520 | ] |
| 1043 | 521 | ||
| 1044 | -[[package]] | ||
| 1045 | -name = "deunicode" | ||
| 1046 | -version = "1.6.2" | ||
| 1047 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1048 | -checksum = "abd57806937c9cc163efc8ea3910e00a62e2aeb0b8119f1793a978088f8f6b04" | ||
| 1049 | - | ||
| 1050 | [[package]] | 522 | [[package]] |
| 1051 | name = "digest" | 523 | name = "digest" |
| 1052 | version = "0.10.7" | 524 | version = "0.10.7" |
| @@ -1054,9 +526,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 1054 | checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" | 526 | checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" |
| 1055 | dependencies = [ | 527 | dependencies = [ |
| 1056 | "block-buffer 0.10.4", | 528 | "block-buffer 0.10.4", |
| 1057 | - "const-oid 0.9.6", | ||
| 1058 | "crypto-common 0.1.7", | 529 | "crypto-common 0.1.7", |
| 1059 | - "subtle", | ||
| 1060 | ] | 530 | ] |
| 1061 | 531 | ||
| 1062 | [[package]] | 532 | [[package]] |
| @@ -1066,69 +536,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 1066 | checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" | 536 | checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" |
| 1067 | dependencies = [ | 537 | dependencies = [ |
| 1068 | "block-buffer 0.12.1", | 538 | "block-buffer 0.12.1", |
| 1069 | - "const-oid 0.10.2", | 539 | + "const-oid", |
| 1070 | "crypto-common 0.2.2", | 540 | "crypto-common 0.2.2", |
| 1071 | "ctutils", | 541 | "ctutils", |
| 1072 | ] | 542 | ] |
| 1073 | 543 | ||
| 1074 | -[[package]] | ||
| 1075 | -name = "diskann" | ||
| 1076 | -version = "0.54.0" | ||
| 1077 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1078 | -checksum = "421c6cf955c6cb1451d36c8a3740ab2a22880265d0fa93d8ea22cbc425c90479" | ||
| 1079 | -dependencies = [ | ||
| 1080 | - "anyhow", | ||
| 1081 | - "bytemuck", | ||
| 1082 | - "diskann-utils", | ||
| 1083 | - "diskann-vector", | ||
| 1084 | - "diskann-wide", | ||
| 1085 | - "futures-util", | ||
| 1086 | - "half", | ||
| 1087 | - "hashbrown 0.16.1", | ||
| 1088 | - "num-traits", | ||
| 1089 | - "rand 0.9.5", | ||
| 1090 | - "thiserror", | ||
| 1091 | - "tokio", | ||
| 1092 | -] | ||
| 1093 | - | ||
| 1094 | -[[package]] | ||
| 1095 | -name = "diskann-utils" | ||
| 1096 | -version = "0.54.0" | ||
| 1097 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1098 | -checksum = "7cdf7d491910fbff13338e07460c9197a3c172268cfd4d8f8e69e5cec5a256d9" | ||
| 1099 | -dependencies = [ | ||
| 1100 | - "bytemuck", | ||
| 1101 | - "cfg-if", | ||
| 1102 | - "diskann-vector", | ||
| 1103 | - "diskann-wide", | ||
| 1104 | - "half", | ||
| 1105 | - "rand 0.9.5", | ||
| 1106 | - "rand_distr", | ||
| 1107 | - "rayon", | ||
| 1108 | - "thiserror", | ||
| 1109 | -] | ||
| 1110 | - | ||
| 1111 | -[[package]] | ||
| 1112 | -name = "diskann-vector" | ||
| 1113 | -version = "0.54.0" | ||
| 1114 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1115 | -checksum = "de1643bbece645f03527ef120bc7dd5e4e40557980dbe52ee51129adfb58a851" | ||
| 1116 | -dependencies = [ | ||
| 1117 | - "cfg-if", | ||
| 1118 | - "diskann-wide", | ||
| 1119 | - "half", | ||
| 1120 | -] | ||
| 1121 | - | ||
| 1122 | -[[package]] | ||
| 1123 | -name = "diskann-wide" | ||
| 1124 | -version = "0.54.0" | ||
| 1125 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1126 | -checksum = "421f02c42e57a2153dc65b66b4b95fe2be56e14bf9f95253b663abcac8521166" | ||
| 1127 | -dependencies = [ | ||
| 1128 | - "cfg-if", | ||
| 1129 | - "half", | ||
| 1130 | -] | ||
| 1131 | - | ||
| 1132 | [[package]] | 544 | [[package]] |
| 1133 | name = "displaydoc" | 545 | name = "displaydoc" |
| 1134 | version = "0.2.7" | 546 | version = "0.2.7" |
| @@ -1140,16 +552,6 @@ dependencies = [ | |||
| 1140 | "syn 3.0.5", | 552 | "syn 3.0.5", |
| 1141 | ] | 553 | ] |
| 1142 | 554 | ||
| 1143 | -[[package]] | ||
| 1144 | -name = "dmp" | ||
| 1145 | -version = "0.2.3" | ||
| 1146 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1147 | -checksum = "bb2dfc7a18dffd3ef60a442b72a827126f1557d914620f8fc4d1049916da43c1" | ||
| 1148 | -dependencies = [ | ||
| 1149 | - "trice", | ||
| 1150 | - "urlencoding", | ||
| 1151 | -] | ||
| 1152 | - | ||
| 1153 | [[package]] | 555 | [[package]] |
| 1154 | name = "document-features" | 556 | name = "document-features" |
| 1155 | version = "0.2.12" | 557 | version = "0.2.12" |
| @@ -1165,100 +567,13 @@ version = "0.15.7" | |||
| 1165 | source = "registry+https://github.com/rust-lang/crates.io-index" | 567 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1166 | checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" | 568 | checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" |
| 1167 | 569 | ||
| 1168 | -[[package]] | ||
| 1169 | -name = "dtoa" | ||
| 1170 | -version = "1.0.11" | ||
| 1171 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1172 | -checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" | ||
| 1173 | - | ||
| 1174 | -[[package]] | ||
| 1175 | -name = "dtoa-short" | ||
| 1176 | -version = "0.3.5" | ||
| 1177 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1178 | -checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" | ||
| 1179 | -dependencies = [ | ||
| 1180 | - "dtoa", | ||
| 1181 | -] | ||
| 1182 | - | ||
| 1183 | -[[package]] | ||
| 1184 | -name = "dunce" | ||
| 1185 | -version = "1.0.5" | ||
| 1186 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1187 | -checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" | ||
| 1188 | - | ||
| 1189 | -[[package]] | ||
| 1190 | -name = "earcutr" | ||
| 1191 | -version = "0.4.3" | ||
| 1192 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1193 | -checksum = "79127ed59a85d7687c409e9978547cffb7dc79675355ed22da6b66fd5f6ead01" | ||
| 1194 | -dependencies = [ | ||
| 1195 | - "itertools 0.11.0", | ||
| 1196 | - "num-traits", | ||
| 1197 | -] | ||
| 1198 | - | ||
| 1199 | -[[package]] | ||
| 1200 | -name = "ecdsa" | ||
| 1201 | -version = "0.16.9" | ||
| 1202 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1203 | -checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" | ||
| 1204 | -dependencies = [ | ||
| 1205 | - "der", | ||
| 1206 | - "digest 0.10.7", | ||
| 1207 | - "elliptic-curve", | ||
| 1208 | - "rfc6979", | ||
| 1209 | - "signature", | ||
| 1210 | - "spki", | ||
| 1211 | -] | ||
| 1212 | - | ||
| 1213 | -[[package]] | ||
| 1214 | -name = "ed25519" | ||
| 1215 | -version = "2.2.3" | ||
| 1216 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1217 | -checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" | ||
| 1218 | -dependencies = [ | ||
| 1219 | - "pkcs8", | ||
| 1220 | - "signature", | ||
| 1221 | -] | ||
| 1222 | - | ||
| 1223 | -[[package]] | ||
| 1224 | -name = "ed25519-dalek" | ||
| 1225 | -version = "2.2.0" | ||
| 1226 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1227 | -checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" | ||
| 1228 | -dependencies = [ | ||
| 1229 | - "curve25519-dalek", | ||
| 1230 | - "ed25519", | ||
| 1231 | - "serde", | ||
| 1232 | - "sha2 0.10.9", | ||
| 1233 | - "subtle", | ||
| 1234 | - "zeroize", | ||
| 1235 | -] | ||
| 1236 | - | ||
| 1237 | [[package]] | 570 | [[package]] |
| 1238 | name = "either" | 571 | name = "either" |
| 1239 | version = "1.16.0" | 572 | version = "1.16.0" |
| 1240 | source = "registry+https://github.com/rust-lang/crates.io-index" | 573 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1241 | checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" | 574 | checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" |
| 1242 | - | ||
| 1243 | -[[package]] | ||
| 1244 | -name = "elliptic-curve" | ||
| 1245 | -version = "0.13.8" | ||
| 1246 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1247 | -checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" | ||
| 1248 | dependencies = [ | 575 | dependencies = [ |
| 1249 | - "base16ct", | 576 | + "serde", |
| 1250 | - "crypto-bigint", | ||
| 1251 | - "digest 0.10.7", | ||
| 1252 | - "ff", | ||
| 1253 | - "generic-array 0.14.7", | ||
| 1254 | - "group", | ||
| 1255 | - "hkdf", | ||
| 1256 | - "pem-rfc7468", | ||
| 1257 | - "pkcs8", | ||
| 1258 | - "rand_core 0.6.4", | ||
| 1259 | - "sec1", | ||
| 1260 | - "subtle", | ||
| 1261 | - "zeroize", | ||
| 1262 | ] | 577 | ] |
| 1263 | 578 | ||
| 1264 | [[package]] | 579 | [[package]] |
| @@ -1287,89 +602,37 @@ dependencies = [ | |||
| 1287 | ] | 602 | ] |
| 1288 | 603 | ||
| 1289 | [[package]] | 604 | [[package]] |
| 1290 | -name = "event-listener" | 605 | +name = "etcetera" |
| 1291 | -version = "5.4.1" | 606 | +version = "0.11.0" |
| 1292 | source = "registry+https://github.com/rust-lang/crates.io-index" | 607 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1293 | -checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" | 608 | +checksum = "de48cc4d1c1d97a20fd819def54b890cadde72ed3ad0c614822a0a433361be96" |
| 1294 | dependencies = [ | 609 | dependencies = [ |
| 1295 | - "concurrent-queue", | 610 | + "cfg-if", |
| 1296 | - "parking", | 611 | + "windows-sys 0.61.2", |
| 1297 | - "pin-project-lite", | ||
| 1298 | ] | 612 | ] |
| 1299 | 613 | ||
| 1300 | [[package]] | 614 | [[package]] |
| 1301 | -name = "event-listener-strategy" | 615 | +name = "event-listener" |
| 1302 | -version = "0.5.4" | 616 | +version = "5.4.2" |
| 1303 | source = "registry+https://github.com/rust-lang/crates.io-index" | 617 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1304 | -checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" | 618 | +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" |
| 1305 | dependencies = [ | 619 | dependencies = [ |
| 1306 | - "event-listener", | 620 | + "parking", |
| 1307 | "pin-project-lite", | 621 | "pin-project-lite", |
| 1308 | ] | 622 | ] |
| 1309 | 623 | ||
| 1310 | -[[package]] | ||
| 1311 | -name = "ext-sort" | ||
| 1312 | -version = "0.1.5" | ||
| 1313 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1314 | -checksum = "cf5d3b056bcc471d38082b8c453acb6670f7327fd44219b3c411e40834883569" | ||
| 1315 | -dependencies = [ | ||
| 1316 | - "log", | ||
| 1317 | - "rayon", | ||
| 1318 | - "rmp-serde", | ||
| 1319 | - "serde", | ||
| 1320 | - "tempfile", | ||
| 1321 | -] | ||
| 1322 | - | ||
| 1323 | -[[package]] | ||
| 1324 | -name = "fastnum" | ||
| 1325 | -version = "0.7.5" | ||
| 1326 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1327 | -checksum = "020d1b59a944bc239d79903fbac2eda2365138b44890c27979562f6592059dcd" | ||
| 1328 | -dependencies = [ | ||
| 1329 | - "bnum", | ||
| 1330 | - "num-integer", | ||
| 1331 | - "num-traits", | ||
| 1332 | -] | ||
| 1333 | - | ||
| 1334 | [[package]] | 624 | [[package]] |
| 1335 | name = "fastrand" | 625 | name = "fastrand" |
| 1336 | version = "2.5.0" | 626 | version = "2.5.0" |
| 1337 | source = "registry+https://github.com/rust-lang/crates.io-index" | 627 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1338 | checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" | 628 | checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" |
| 1339 | 629 | ||
| 1340 | -[[package]] | ||
| 1341 | -name = "ff" | ||
| 1342 | -version = "0.13.1" | ||
| 1343 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1344 | -checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" | ||
| 1345 | -dependencies = [ | ||
| 1346 | - "rand_core 0.6.4", | ||
| 1347 | - "subtle", | ||
| 1348 | -] | ||
| 1349 | - | ||
| 1350 | -[[package]] | ||
| 1351 | -name = "fiat-crypto" | ||
| 1352 | -version = "0.2.9" | ||
| 1353 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1354 | -checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" | ||
| 1355 | - | ||
| 1356 | [[package]] | 630 | [[package]] |
| 1357 | name = "find-msvc-tools" | 631 | name = "find-msvc-tools" |
| 1358 | version = "0.1.12" | 632 | version = "0.1.12" |
| 1359 | source = "registry+https://github.com/rust-lang/crates.io-index" | 633 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1360 | checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" | 634 | checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" |
| 1361 | 635 | ||
| 1362 | -[[package]] | ||
| 1363 | -name = "flatbuffers" | ||
| 1364 | -version = "25.12.19" | ||
| 1365 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1366 | -checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3" | ||
| 1367 | -dependencies = [ | ||
| 1368 | - "bitflags", | ||
| 1369 | - "rustc_version", | ||
| 1370 | - "serde", | ||
| 1371 | -] | ||
| 1372 | - | ||
| 1373 | [[package]] | 636 | [[package]] |
| 1374 | name = "flate2" | 637 | name = "flate2" |
| 1375 | version = "1.1.9" | 638 | version = "1.1.9" |
| @@ -1381,10 +644,15 @@ dependencies = [ | |||
| 1381 | ] | 644 | ] |
| 1382 | 645 | ||
| 1383 | [[package]] | 646 | [[package]] |
| 1384 | -name = "float_next_after" | 647 | +name = "flume" |
| 1385 | -version = "1.0.0" | 648 | +version = "0.12.0" |
| 1386 | source = "registry+https://github.com/rust-lang/crates.io-index" | 649 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1387 | -checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8" | 650 | +checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" |
| 651 | +dependencies = [ | ||
| 652 | + "futures-core", | ||
| 653 | + "futures-sink", | ||
| 654 | + "spin", | ||
| 655 | +] | ||
| 1388 | 656 | ||
| 1389 | [[package]] | 657 | [[package]] |
| 1390 | name = "fnv" | 658 | name = "fnv" |
| @@ -1407,39 +675,6 @@ dependencies = [ | |||
| 1407 | "percent-encoding", | 675 | "percent-encoding", |
| 1408 | ] | 676 | ] |
| 1409 | 677 | ||
| 1410 | -[[package]] | ||
| 1411 | -name = "fs_extra" | ||
| 1412 | -version = "1.3.0" | ||
| 1413 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1414 | -checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" | ||
| 1415 | - | ||
| 1416 | -[[package]] | ||
| 1417 | -name = "fst" | ||
| 1418 | -version = "0.4.7" | ||
| 1419 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1420 | -checksum = "7ab85b9b05e3978cc9a9cf8fea7f01b494e1a09ed3037e16ba39edc7a29eb61a" | ||
| 1421 | - | ||
| 1422 | -[[package]] | ||
| 1423 | -name = "funty" | ||
| 1424 | -version = "2.0.0" | ||
| 1425 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1426 | -checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" | ||
| 1427 | - | ||
| 1428 | -[[package]] | ||
| 1429 | -name = "futures" | ||
| 1430 | -version = "0.3.33" | ||
| 1431 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1432 | -checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218" | ||
| 1433 | -dependencies = [ | ||
| 1434 | - "futures-channel", | ||
| 1435 | - "futures-core", | ||
| 1436 | - "futures-executor", | ||
| 1437 | - "futures-io", | ||
| 1438 | - "futures-sink", | ||
| 1439 | - "futures-task", | ||
| 1440 | - "futures-util", | ||
| 1441 | -] | ||
| 1442 | - | ||
| 1443 | [[package]] | 678 | [[package]] |
| 1444 | name = "futures-channel" | 679 | name = "futures-channel" |
| 1445 | version = "0.3.34" | 680 | version = "0.3.34" |
| @@ -1467,6 +702,17 @@ dependencies = [ | |||
| 1467 | "futures-util", | 702 | "futures-util", |
| 1468 | ] | 703 | ] |
| 1469 | 704 | ||
| 705 | +[[package]] | ||
| 706 | +name = "futures-intrusive" | ||
| 707 | +version = "0.5.0" | ||
| 708 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 709 | +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" | ||
| 710 | +dependencies = [ | ||
| 711 | + "futures-core", | ||
| 712 | + "lock_api", | ||
| 713 | + "parking_lot", | ||
| 714 | +] | ||
| 715 | + | ||
| 1470 | [[package]] | 716 | [[package]] |
| 1471 | name = "futures-io" | 717 | name = "futures-io" |
| 1472 | version = "0.3.34" | 718 | version = "0.3.34" |
| @@ -1502,7 +748,6 @@ version = "0.3.34" | |||
| 1502 | source = "registry+https://github.com/rust-lang/crates.io-index" | 748 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1503 | checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" | 749 | checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" |
| 1504 | dependencies = [ | 750 | dependencies = [ |
| 1505 | - "futures-channel", | ||
| 1506 | "futures-core", | 751 | "futures-core", |
| 1507 | "futures-io", | 752 | "futures-io", |
| 1508 | "futures-macro", | 753 | "futures-macro", |
| @@ -1513,33 +758,6 @@ dependencies = [ | |||
| 1513 | "slab", | 758 | "slab", |
| 1514 | ] | 759 | ] |
| 1515 | 760 | ||
| 1516 | -[[package]] | ||
| 1517 | -name = "fuzzy-matcher" | ||
| 1518 | -version = "0.3.7" | ||
| 1519 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1520 | -checksum = "54614a3312934d066701a80f20f15fa3b56d67ac7722b39eea5b4c9dd1d66c94" | ||
| 1521 | -dependencies = [ | ||
| 1522 | - "thread_local", | ||
| 1523 | -] | ||
| 1524 | - | ||
| 1525 | -[[package]] | ||
| 1526 | -name = "generic-array" | ||
| 1527 | -version = "0.12.4" | ||
| 1528 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1529 | -checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" | ||
| 1530 | -dependencies = [ | ||
| 1531 | - "typenum", | ||
| 1532 | -] | ||
| 1533 | - | ||
| 1534 | -[[package]] | ||
| 1535 | -name = "generic-array" | ||
| 1536 | -version = "0.13.3" | ||
| 1537 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1538 | -checksum = "f797e67af32588215eaaab8327027ee8e71b9dd0b2b26996aedf20c030fce309" | ||
| 1539 | -dependencies = [ | ||
| 1540 | - "typenum", | ||
| 1541 | -] | ||
| 1542 | - | ||
| 1543 | [[package]] | 761 | [[package]] |
| 1544 | name = "generic-array" | 762 | name = "generic-array" |
| 1545 | version = "0.14.7" | 763 | version = "0.14.7" |
| @@ -1548,54 +766,6 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" | |||
| 1548 | dependencies = [ | 766 | dependencies = [ |
| 1549 | "typenum", | 767 | "typenum", |
| 1550 | "version_check", | 768 | "version_check", |
| 1551 | - "zeroize", | ||
| 1552 | -] | ||
| 1553 | - | ||
| 1554 | -[[package]] | ||
| 1555 | -name = "geo" | ||
| 1556 | -version = "0.32.0" | ||
| 1557 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1558 | -checksum = "3f3901269ec6d4f6068d3f09e5f02f995bd076398dcd1dfec407cd230b02d11b" | ||
| 1559 | -dependencies = [ | ||
| 1560 | - "earcutr", | ||
| 1561 | - "float_next_after", | ||
| 1562 | - "geo-types", | ||
| 1563 | - "geographiclib-rs", | ||
| 1564 | - "i_overlay", | ||
| 1565 | - "log", | ||
| 1566 | - "num-traits", | ||
| 1567 | - "rand 0.8.7", | ||
| 1568 | - "robust", | ||
| 1569 | - "rstar 0.12.2", | ||
| 1570 | - "serde", | ||
| 1571 | - "sif-itree", | ||
| 1572 | - "spade", | ||
| 1573 | -] | ||
| 1574 | - | ||
| 1575 | -[[package]] | ||
| 1576 | -name = "geo-types" | ||
| 1577 | -version = "0.7.19" | ||
| 1578 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1579 | -checksum = "94776032c45f950d30a13af6113c2ad5625316c9abfbccee4dd5a6695f8fe0f5" | ||
| 1580 | -dependencies = [ | ||
| 1581 | - "approx", | ||
| 1582 | - "num-traits", | ||
| 1583 | - "rayon", | ||
| 1584 | - "rstar 0.10.0", | ||
| 1585 | - "rstar 0.11.0", | ||
| 1586 | - "rstar 0.12.2", | ||
| 1587 | - "rstar 0.8.4", | ||
| 1588 | - "rstar 0.9.3", | ||
| 1589 | - "serde", | ||
| 1590 | -] | ||
| 1591 | - | ||
| 1592 | -[[package]] | ||
| 1593 | -name = "geographiclib-rs" | ||
| 1594 | -version = "0.2.7" | ||
| 1595 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1596 | -checksum = "c5a7f08910fd98737a6eda7568e7c5e645093e073328eeef49758cfe8b0489c7" | ||
| 1597 | -dependencies = [ | ||
| 1598 | - "libm", | ||
| 1599 | ] | 769 | ] |
| 1600 | 770 | ||
| 1601 | [[package]] | 771 | [[package]] |
| @@ -1618,11 +788,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 1618 | checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" | 788 | checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" |
| 1619 | dependencies = [ | 789 | dependencies = [ |
| 1620 | "cfg-if", | 790 | "cfg-if", |
| 1621 | - "js-sys", | ||
| 1622 | "libc", | 791 | "libc", |
| 1623 | "r-efi 5.3.0", | 792 | "r-efi 5.3.0", |
| 1624 | "wasip2", | 793 | "wasip2", |
| 1625 | - "wasm-bindgen", | ||
| 1626 | ] | 794 | ] |
| 1627 | 795 | ||
| 1628 | [[package]] | 796 | [[package]] |
| @@ -1632,22 +800,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 1632 | checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" | 800 | checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" |
| 1633 | dependencies = [ | 801 | dependencies = [ |
| 1634 | "cfg-if", | 802 | "cfg-if", |
| 1635 | - "js-sys", | 803 | + "js-sys", |
| 1636 | - "libc", | 804 | + "libc", |
| 1637 | - "r-efi 6.0.0", | 805 | + "r-efi 6.0.0", |
| 1638 | - "rand_core 0.10.1", | 806 | + "rand_core 0.10.1", |
| 1639 | - "wasm-bindgen", | 807 | + "wasm-bindgen", |
| 1640 | -] | ||
| 1641 | - | ||
| 1642 | -[[package]] | ||
| 1643 | -name = "group" | ||
| 1644 | -version = "0.13.0" | ||
| 1645 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1646 | -checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" | ||
| 1647 | -dependencies = [ | ||
| 1648 | - "ff", | ||
| 1649 | - "rand_core 0.6.4", | ||
| 1650 | - "subtle", | ||
| 1651 | ] | 808 | ] |
| 1652 | 809 | ||
| 1653 | [[package]] | 810 | [[package]] |
| @@ -1669,63 +826,6 @@ dependencies = [ | |||
| 1669 | "tracing", | 826 | "tracing", |
| 1670 | ] | 827 | ] |
| 1671 | 828 | ||
| 1672 | -[[package]] | ||
| 1673 | -name = "half" | ||
| 1674 | -version = "2.7.1" | ||
| 1675 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1676 | -checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" | ||
| 1677 | -dependencies = [ | ||
| 1678 | - "bytemuck", | ||
| 1679 | - "cfg-if", | ||
| 1680 | - "crunchy", | ||
| 1681 | - "num-traits", | ||
| 1682 | - "rand 0.9.5", | ||
| 1683 | - "rand_distr", | ||
| 1684 | - "zerocopy", | ||
| 1685 | -] | ||
| 1686 | - | ||
| 1687 | -[[package]] | ||
| 1688 | -name = "hash32" | ||
| 1689 | -version = "0.1.1" | ||
| 1690 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1691 | -checksum = "d4041af86e63ac4298ce40e5cca669066e75b6f1aa3390fe2561ffa5e1d9f4cc" | ||
| 1692 | -dependencies = [ | ||
| 1693 | - "byteorder", | ||
| 1694 | -] | ||
| 1695 | - | ||
| 1696 | -[[package]] | ||
| 1697 | -name = "hash32" | ||
| 1698 | -version = "0.2.1" | ||
| 1699 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1700 | -checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67" | ||
| 1701 | -dependencies = [ | ||
| 1702 | - "byteorder", | ||
| 1703 | -] | ||
| 1704 | - | ||
| 1705 | -[[package]] | ||
| 1706 | -name = "hash32" | ||
| 1707 | -version = "0.3.1" | ||
| 1708 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1709 | -checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" | ||
| 1710 | -dependencies = [ | ||
| 1711 | - "byteorder", | ||
| 1712 | -] | ||
| 1713 | - | ||
| 1714 | -[[package]] | ||
| 1715 | -name = "hashbrown" | ||
| 1716 | -version = "0.12.3" | ||
| 1717 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1718 | -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" | ||
| 1719 | -dependencies = [ | ||
| 1720 | - "ahash 0.7.8", | ||
| 1721 | -] | ||
| 1722 | - | ||
| 1723 | -[[package]] | ||
| 1724 | -name = "hashbrown" | ||
| 1725 | -version = "0.14.5" | ||
| 1726 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1727 | -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" | ||
| 1728 | - | ||
| 1729 | [[package]] | 829 | [[package]] |
| 1730 | name = "hashbrown" | 830 | name = "hashbrown" |
| 1731 | version = "0.16.1" | 831 | version = "0.16.1" |
| @@ -1744,75 +844,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 1744 | checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" | 844 | checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" |
| 1745 | 845 | ||
| 1746 | [[package]] | 846 | [[package]] |
| 1747 | -name = "headers" | 847 | +name = "hashlink" |
| 1748 | -version = "0.4.1" | 848 | +version = "0.11.1" |
| 1749 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1750 | -checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb" | ||
| 1751 | -dependencies = [ | ||
| 1752 | - "base64 0.22.1", | ||
| 1753 | - "bytes", | ||
| 1754 | - "headers-core", | ||
| 1755 | - "http", | ||
| 1756 | - "httpdate", | ||
| 1757 | - "mime", | ||
| 1758 | - "sha1 0.10.7", | ||
| 1759 | -] | ||
| 1760 | - | ||
| 1761 | -[[package]] | ||
| 1762 | -name = "headers-core" | ||
| 1763 | -version = "0.3.0" | ||
| 1764 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1765 | -checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" | ||
| 1766 | -dependencies = [ | ||
| 1767 | - "http", | ||
| 1768 | -] | ||
| 1769 | - | ||
| 1770 | -[[package]] | ||
| 1771 | -name = "heapless" | ||
| 1772 | -version = "0.6.1" | ||
| 1773 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1774 | -checksum = "634bd4d29cbf24424d0a4bfcbf80c6960129dc24424752a7d1d1390607023422" | ||
| 1775 | -dependencies = [ | ||
| 1776 | - "as-slice", | ||
| 1777 | - "generic-array 0.14.7", | ||
| 1778 | - "hash32 0.1.1", | ||
| 1779 | - "stable_deref_trait", | ||
| 1780 | -] | ||
| 1781 | - | ||
| 1782 | -[[package]] | ||
| 1783 | -name = "heapless" | ||
| 1784 | -version = "0.7.17" | ||
| 1785 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1786 | -checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f" | ||
| 1787 | -dependencies = [ | ||
| 1788 | - "atomic-polyfill", | ||
| 1789 | - "hash32 0.2.1", | ||
| 1790 | - "rustc_version", | ||
| 1791 | - "spin", | ||
| 1792 | - "stable_deref_trait", | ||
| 1793 | -] | ||
| 1794 | - | ||
| 1795 | -[[package]] | ||
| 1796 | -name = "heapless" | ||
| 1797 | -version = "0.8.0" | ||
| 1798 | source = "registry+https://github.com/rust-lang/crates.io-index" | 849 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1799 | -checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" | 850 | +checksum = "824e001ac4f3012dd16a264bec811403a67ca9deb6c102fc5049b32c4574b35f" |
| 1800 | dependencies = [ | 851 | dependencies = [ |
| 1801 | - "hash32 0.3.1", | 852 | + "hashbrown 0.16.1", |
| 1802 | - "stable_deref_trait", | ||
| 1803 | ] | 853 | ] |
| 1804 | 854 | ||
| 1805 | [[package]] | 855 | [[package]] |
| 1806 | name = "heck" | 856 | name = "heck" |
| 1807 | -version = "0.4.1" | 857 | +version = "0.5.0" |
| 1808 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1809 | -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" | ||
| 1810 | - | ||
| 1811 | -[[package]] | ||
| 1812 | -name = "hermit-abi" | ||
| 1813 | -version = "0.5.2" | ||
| 1814 | source = "registry+https://github.com/rust-lang/crates.io-index" | 858 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1815 | -checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" | 859 | +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" |
| 1816 | 860 | ||
| 1817 | [[package]] | 861 | [[package]] |
| 1818 | name = "hex" | 862 | name = "hex" |
| @@ -1825,7 +869,7 @@ name = "hezarfen_backend" | |||
| 1825 | version = "0.1.0" | 869 | version = "0.1.0" |
| 1826 | dependencies = [ | 870 | dependencies = [ |
| 1827 | "anyhow", | 871 | "anyhow", |
| 1828 | - "argon2 0.6.0", | 872 | + "argon2", |
| 1829 | "axum", | 873 | "axum", |
| 1830 | "axum-extra", | 874 | "axum-extra", |
| 1831 | "base64 0.23.1", | 875 | "base64 0.23.1", |
| @@ -1849,7 +893,7 @@ dependencies = [ | |||
| 1849 | "serde", | 893 | "serde", |
| 1850 | "serde_json", | 894 | "serde_json", |
| 1851 | "sha2 0.11.0", | 895 | "sha2 0.11.0", |
| 1852 | - "surrealdb", | 896 | + "sqlx", |
| 1853 | "tempfile", | 897 | "tempfile", |
| 1854 | "thiserror", | 898 | "thiserror", |
| 1855 | "time", | 899 | "time", |
| @@ -1861,7 +905,6 @@ dependencies = [ | |||
| 1861 | "tracing", | 905 | "tracing", |
| 1862 | "tracing-opentelemetry", | 906 | "tracing-opentelemetry", |
| 1863 | "tracing-subscriber", | 907 | "tracing-subscriber", |
| 1864 | - "ulid 3.0.0", | ||
| 1865 | "utoipa", | 908 | "utoipa", |
| 1866 | "utoipa-axum", | 909 | "utoipa-axum", |
| 1867 | "utoipa-swagger-ui", | 910 | "utoipa-swagger-ui", |
| @@ -1870,30 +913,20 @@ dependencies = [ | |||
| 1870 | 913 | ||
| 1871 | [[package]] | 914 | [[package]] |
| 1872 | name = "hkdf" | 915 | name = "hkdf" |
| 1873 | -version = "0.12.4" | 916 | +version = "0.13.0" |
| 1874 | source = "registry+https://github.com/rust-lang/crates.io-index" | 917 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1875 | -checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" | 918 | +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" |
| 1876 | dependencies = [ | 919 | dependencies = [ |
| 1877 | "hmac", | 920 | "hmac", |
| 1878 | ] | 921 | ] |
| 1879 | 922 | ||
| 1880 | [[package]] | 923 | [[package]] |
| 1881 | name = "hmac" | 924 | name = "hmac" |
| 1882 | -version = "0.12.1" | 925 | +version = "0.13.0" |
| 1883 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1884 | -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" | ||
| 1885 | -dependencies = [ | ||
| 1886 | - "digest 0.10.7", | ||
| 1887 | -] | ||
| 1888 | - | ||
| 1889 | -[[package]] | ||
| 1890 | -name = "html5ever" | ||
| 1891 | -version = "0.39.0" | ||
| 1892 | source = "registry+https://github.com/rust-lang/crates.io-index" | 926 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1893 | -checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" | 927 | +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" |
| 1894 | dependencies = [ | 928 | dependencies = [ |
| 1895 | - "log", | 929 | + "digest 0.11.3", |
| 1896 | - "markup5ever", | ||
| 1897 | ] | 930 | ] |
| 1898 | 931 | ||
| 1899 | [[package]] | 932 | [[package]] |
| @@ -1941,12 +974,6 @@ version = "1.0.3" | |||
| 1941 | source = "registry+https://github.com/rust-lang/crates.io-index" | 974 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1942 | checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" | 975 | checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" |
| 1943 | 976 | ||
| 1944 | -[[package]] | ||
| 1945 | -name = "humantime" | ||
| 1946 | -version = "2.4.0" | ||
| 1947 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1948 | -checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" | ||
| 1949 | - | ||
| 1950 | [[package]] | 977 | [[package]] |
| 1951 | name = "hybrid-array" | 978 | name = "hybrid-array" |
| 1952 | version = "0.4.15" | 979 | version = "0.4.15" |
| @@ -2014,49 +1041,6 @@ dependencies = [ | |||
| 2014 | "tracing", | 1041 | "tracing", |
| 2015 | ] | 1042 | ] |
| 2016 | 1043 | ||
| 2017 | -[[package]] | ||
| 2018 | -name = "i_float" | ||
| 2019 | -version = "1.15.0" | ||
| 2020 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2021 | -checksum = "010025c2c532c8d82e42d0b8bb5184afa449fa6f06c709ea9adcb16c49ae405b" | ||
| 2022 | -dependencies = [ | ||
| 2023 | - "libm", | ||
| 2024 | -] | ||
| 2025 | - | ||
| 2026 | -[[package]] | ||
| 2027 | -name = "i_key_sort" | ||
| 2028 | -version = "0.6.0" | ||
| 2029 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2030 | -checksum = "9190f86706ca38ac8add223b2aed8b1330002b5cdbbce28fb58b10914d38fc27" | ||
| 2031 | - | ||
| 2032 | -[[package]] | ||
| 2033 | -name = "i_overlay" | ||
| 2034 | -version = "4.0.7" | ||
| 2035 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2036 | -checksum = "413183068e6e0289e18d7d0a1f661b81546e6918d5453a44570b9ab30cbed1b3" | ||
| 2037 | -dependencies = [ | ||
| 2038 | - "i_float", | ||
| 2039 | - "i_key_sort", | ||
| 2040 | - "i_shape", | ||
| 2041 | - "i_tree", | ||
| 2042 | - "rayon", | ||
| 2043 | -] | ||
| 2044 | - | ||
| 2045 | -[[package]] | ||
| 2046 | -name = "i_shape" | ||
| 2047 | -version = "1.14.0" | ||
| 2048 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2049 | -checksum = "1ea154b742f7d43dae2897fcd5ead86bc7b5eefcedd305a7ebf9f69d44d61082" | ||
| 2050 | -dependencies = [ | ||
| 2051 | - "i_float", | ||
| 2052 | -] | ||
| 2053 | - | ||
| 2054 | -[[package]] | ||
| 2055 | -name = "i_tree" | ||
| 2056 | -version = "0.16.0" | ||
| 2057 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2058 | -checksum = "35e6d558e6d4c7b82bc51d9c771e7a927862a161a7d87bf2b0541450e0e20915" | ||
| 2059 | - | ||
| 2060 | [[package]] | 1044 | [[package]] |
| 2061 | name = "iana-time-zone" | 1045 | name = "iana-time-zone" |
| 2062 | version = "0.1.65" | 1046 | version = "0.1.65" |
| @@ -2069,7 +1053,7 @@ dependencies = [ | |||
| 2069 | "js-sys", | 1053 | "js-sys", |
| 2070 | "log", | 1054 | "log", |
| 2071 | "wasm-bindgen", | 1055 | "wasm-bindgen", |
| 2072 | - "windows-core 0.62.2", | 1056 | + "windows-core", |
| 2073 | ] | 1057 | ] |
| 2074 | 1058 | ||
| 2075 | [[package]] | 1059 | [[package]] |
| @@ -2196,39 +1180,12 @@ dependencies = [ | |||
| 2196 | "serde_core", | 1180 | "serde_core", |
| 2197 | ] | 1181 | ] |
| 2198 | 1182 | ||
| 2199 | -[[package]] | ||
| 2200 | -name = "inout" | ||
| 2201 | -version = "0.1.4" | ||
| 2202 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2203 | -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" | ||
| 2204 | -dependencies = [ | ||
| 2205 | - "generic-array 0.14.7", | ||
| 2206 | -] | ||
| 2207 | - | ||
| 2208 | [[package]] | 1183 | [[package]] |
| 2209 | name = "ipnet" | 1184 | name = "ipnet" |
| 2210 | version = "2.12.0" | 1185 | version = "2.12.0" |
| 2211 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1186 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2212 | checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" | 1187 | checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" |
| 2213 | 1188 | ||
| 2214 | -[[package]] | ||
| 2215 | -name = "itertools" | ||
| 2216 | -version = "0.11.0" | ||
| 2217 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2218 | -checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" | ||
| 2219 | -dependencies = [ | ||
| 2220 | - "either", | ||
| 2221 | -] | ||
| 2222 | - | ||
| 2223 | -[[package]] | ||
| 2224 | -name = "itertools" | ||
| 2225 | -version = "0.13.0" | ||
| 2226 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2227 | -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" | ||
| 2228 | -dependencies = [ | ||
| 2229 | - "either", | ||
| 2230 | -] | ||
| 2231 | - | ||
| 2232 | [[package]] | 1189 | [[package]] |
| 2233 | name = "itertools" | 1190 | name = "itertools" |
| 2234 | version = "0.14.0" | 1191 | version = "0.14.0" |
| @@ -2244,16 +1201,6 @@ version = "1.0.18" | |||
| 2244 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1201 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2245 | checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" | 1202 | checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" |
| 2246 | 1203 | ||
| 2247 | -[[package]] | ||
| 2248 | -name = "jobserver" | ||
| 2249 | -version = "0.1.35" | ||
| 2250 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2251 | -checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" | ||
| 2252 | -dependencies = [ | ||
| 2253 | - "getrandom 0.4.3", | ||
| 2254 | - "libc", | ||
| 2255 | -] | ||
| 2256 | - | ||
| 2257 | [[package]] | 1204 | [[package]] |
| 2258 | name = "js-sys" | 1205 | name = "js-sys" |
| 2259 | version = "0.3.103" | 1206 | version = "0.3.103" |
| @@ -2265,48 +1212,11 @@ dependencies = [ | |||
| 2265 | "wasm-bindgen", | 1212 | "wasm-bindgen", |
| 2266 | ] | 1213 | ] |
| 2267 | 1214 | ||
| 2268 | -[[package]] | ||
| 2269 | -name = "jsonwebtoken" | ||
| 2270 | -version = "10.4.0" | ||
| 2271 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2272 | -checksum = "eba32bfb4ffdeaca3e34431072faf01745c9b26d25504aa7a6cf5684334fc4fc" | ||
| 2273 | -dependencies = [ | ||
| 2274 | - "aws-lc-rs", | ||
| 2275 | - "base64 0.22.1", | ||
| 2276 | - "ed25519-dalek", | ||
| 2277 | - "getrandom 0.2.17", | ||
| 2278 | - "hmac", | ||
| 2279 | - "js-sys", | ||
| 2280 | - "p256", | ||
| 2281 | - "p384", | ||
| 2282 | - "pem 3.0.6", | ||
| 2283 | - "rand 0.8.7", | ||
| 2284 | - "rsa", | ||
| 2285 | - "serde", | ||
| 2286 | - "serde_json", | ||
| 2287 | - "sha2 0.10.9", | ||
| 2288 | - "signature", | ||
| 2289 | - "simple_asn1", | ||
| 2290 | - "zeroize", | ||
| 2291 | -] | ||
| 2292 | - | ||
| 2293 | [[package]] | 1215 | [[package]] |
| 2294 | name = "lazy_static" | 1216 | name = "lazy_static" |
| 2295 | version = "1.5.0" | 1217 | version = "1.5.0" |
| 2296 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1218 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2297 | checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" | 1219 | checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" |
| 2298 | -dependencies = [ | ||
| 2299 | - "spin", | ||
| 2300 | -] | ||
| 2301 | - | ||
| 2302 | -[[package]] | ||
| 2303 | -name = "lexicmp" | ||
| 2304 | -version = "0.2.0" | ||
| 2305 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2306 | -checksum = "0e8f89da8fd95c4eb6274e914694bea90c7826523b26f2a2fd863d44b9d42c43" | ||
| 2307 | -dependencies = [ | ||
| 2308 | - "deunicode", | ||
| 2309 | -] | ||
| 2310 | 1220 | ||
| 2311 | [[package]] | 1221 | [[package]] |
| 2312 | name = "libc" | 1222 | name = "libc" |
| @@ -2315,10 +1225,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 2315 | checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" | 1225 | checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" |
| 2316 | 1226 | ||
| 2317 | [[package]] | 1227 | [[package]] |
| 2318 | -name = "libm" | 1228 | +name = "libsqlite3-sys" |
| 2319 | -version = "0.2.16" | 1229 | +version = "0.37.0" |
| 2320 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1230 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2321 | -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" | 1231 | +checksum = "b1f111c8c41e7c61a49cd34e44c7619462967221a6443b0ec299e0ac30cfb9b1" |
| 1232 | +dependencies = [ | ||
| 1233 | + "pkg-config", | ||
| 1234 | + "vcpkg", | ||
| 1235 | +] | ||
| 2322 | 1236 | ||
| 2323 | [[package]] | 1237 | [[package]] |
| 2324 | name = "linux-raw-sys" | 1238 | name = "linux-raw-sys" |
| @@ -2359,42 +1273,6 @@ version = "0.1.2" | |||
| 2359 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1273 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2360 | checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" | 1274 | checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" |
| 2361 | 1275 | ||
| 2362 | -[[package]] | ||
| 2363 | -name = "lz4" | ||
| 2364 | -version = "1.28.1" | ||
| 2365 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2366 | -checksum = "a20b523e860d03443e98350ceaac5e71c6ba89aea7d960769ec3ce37f4de5af4" | ||
| 2367 | -dependencies = [ | ||
| 2368 | - "lz4-sys", | ||
| 2369 | -] | ||
| 2370 | - | ||
| 2371 | -[[package]] | ||
| 2372 | -name = "lz4-sys" | ||
| 2373 | -version = "1.11.1+lz4-1.10.0" | ||
| 2374 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2375 | -checksum = "6bd8c0d6c6ed0cd30b3652886bb8711dc4bb01d637a68105a3d5158039b418e6" | ||
| 2376 | -dependencies = [ | ||
| 2377 | - "cc", | ||
| 2378 | - "libc", | ||
| 2379 | -] | ||
| 2380 | - | ||
| 2381 | -[[package]] | ||
| 2382 | -name = "maplit" | ||
| 2383 | -version = "1.0.2" | ||
| 2384 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2385 | -checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" | ||
| 2386 | - | ||
| 2387 | -[[package]] | ||
| 2388 | -name = "markup5ever" | ||
| 2389 | -version = "0.39.0" | ||
| 2390 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2391 | -checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" | ||
| 2392 | -dependencies = [ | ||
| 2393 | - "log", | ||
| 2394 | - "tendril", | ||
| 2395 | - "web_atoms", | ||
| 2396 | -] | ||
| 2397 | - | ||
| 2398 | [[package]] | 1276 | [[package]] |
| 2399 | name = "matchers" | 1277 | name = "matchers" |
| 2400 | version = "0.2.0" | 1278 | version = "0.2.0" |
| @@ -2410,24 +1288,14 @@ version = "0.8.4" | |||
| 2410 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1288 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2411 | checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" | 1289 | checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" |
| 2412 | 1290 | ||
| 2413 | -[[package]] | ||
| 2414 | -name = "matrixmultiply" | ||
| 2415 | -version = "0.3.11" | ||
| 2416 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2417 | -checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7" | ||
| 2418 | -dependencies = [ | ||
| 2419 | - "autocfg", | ||
| 2420 | - "rawpointer", | ||
| 2421 | -] | ||
| 2422 | - | ||
| 2423 | [[package]] | 1291 | [[package]] |
| 2424 | name = "md-5" | 1292 | name = "md-5" |
| 2425 | -version = "0.10.6" | 1293 | +version = "0.11.0" |
| 2426 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1294 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2427 | -checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" | 1295 | +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" |
| 2428 | dependencies = [ | 1296 | dependencies = [ |
| 2429 | "cfg-if", | 1297 | "cfg-if", |
| 2430 | - "digest 0.10.7", | 1298 | + "digest 0.11.3", |
| 2431 | ] | 1299 | ] |
| 2432 | 1300 | ||
| 2433 | [[package]] | 1301 | [[package]] |
| @@ -2469,76 +1337,31 @@ dependencies = [ | |||
| 2469 | ] | 1337 | ] |
| 2470 | 1338 | ||
| 2471 | [[package]] | 1339 | [[package]] |
| 2472 | -name = "mio" | 1340 | +name = "mio" |
| 2473 | -version = "1.2.2" | 1341 | +version = "1.2.2" |
| 2474 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2475 | -checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" | ||
| 2476 | -dependencies = [ | ||
| 2477 | - "libc", | ||
| 2478 | - "wasi", | ||
| 2479 | - "windows-sys 0.61.2", | ||
| 2480 | -] | ||
| 2481 | - | ||
| 2482 | -[[package]] | ||
| 2483 | -name = "multer" | ||
| 2484 | -version = "3.1.0" | ||
| 2485 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2486 | -checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" | ||
| 2487 | -dependencies = [ | ||
| 2488 | - "bytes", | ||
| 2489 | - "encoding_rs", | ||
| 2490 | - "futures-util", | ||
| 2491 | - "http", | ||
| 2492 | - "httparse", | ||
| 2493 | - "memchr", | ||
| 2494 | - "mime", | ||
| 2495 | - "spin", | ||
| 2496 | - "version_check", | ||
| 2497 | -] | ||
| 2498 | - | ||
| 2499 | -[[package]] | ||
| 2500 | -name = "ndarray" | ||
| 2501 | -version = "0.17.2" | ||
| 2502 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2503 | -checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d" | ||
| 2504 | -dependencies = [ | ||
| 2505 | - "matrixmultiply", | ||
| 2506 | - "num-complex", | ||
| 2507 | - "num-integer", | ||
| 2508 | - "num-traits", | ||
| 2509 | - "portable-atomic", | ||
| 2510 | - "portable-atomic-util", | ||
| 2511 | - "rawpointer", | ||
| 2512 | -] | ||
| 2513 | - | ||
| 2514 | -[[package]] | ||
| 2515 | -name = "ndarray-stats" | ||
| 2516 | -version = "0.7.0" | ||
| 2517 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2518 | -checksum = "9b6e54a8b65764f71827a90ca1d56965ec0c67f069f996477bd493402a901d1f" | ||
| 2519 | -dependencies = [ | ||
| 2520 | - "indexmap", | ||
| 2521 | - "itertools 0.13.0", | ||
| 2522 | - "ndarray", | ||
| 2523 | - "noisy_float", | ||
| 2524 | - "num-integer", | ||
| 2525 | - "num-traits", | ||
| 2526 | - "rand 0.8.7", | ||
| 2527 | -] | ||
| 2528 | - | ||
| 2529 | -[[package]] | ||
| 2530 | -name = "new_debug_unreachable" | ||
| 2531 | -version = "1.0.6" | ||
| 2532 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1342 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2533 | -checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" | 1343 | +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" |
| 1344 | +dependencies = [ | ||
| 1345 | + "libc", | ||
| 1346 | + "wasi", | ||
| 1347 | + "windows-sys 0.61.2", | ||
| 1348 | +] | ||
| 2534 | 1349 | ||
| 2535 | [[package]] | 1350 | [[package]] |
| 2536 | -name = "noisy_float" | 1351 | +name = "multer" |
| 2537 | -version = "0.2.1" | 1352 | +version = "3.1.0" |
| 2538 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1353 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2539 | -checksum = "c16843be85dd410c6a12251c4eca0dd1d3ee8c5725f746c4d5e0fdcec0a864b2" | 1354 | +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" |
| 2540 | dependencies = [ | 1355 | dependencies = [ |
| 2541 | - "num-traits", | 1356 | + "bytes", |
| 1357 | + "encoding_rs", | ||
| 1358 | + "futures-util", | ||
| 1359 | + "http", | ||
| 1360 | + "httparse", | ||
| 1361 | + "memchr", | ||
| 1362 | + "mime", | ||
| 1363 | + "spin", | ||
| 1364 | + "version_check", | ||
| 2542 | ] | 1365 | ] |
| 2543 | 1366 | ||
| 2544 | [[package]] | 1367 | [[package]] |
| @@ -2551,15 +1374,6 @@ dependencies = [ | |||
| 2551 | "minimal-lexical", | 1374 | "minimal-lexical", |
| 2552 | ] | 1375 | ] |
| 2553 | 1376 | ||
| 2554 | -[[package]] | ||
| 2555 | -name = "ntapi" | ||
| 2556 | -version = "0.4.3" | ||
| 2557 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2558 | -checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" | ||
| 2559 | -dependencies = [ | ||
| 2560 | - "winapi", | ||
| 2561 | -] | ||
| 2562 | - | ||
| 2563 | [[package]] | 1377 | [[package]] |
| 2564 | name = "nu-ansi-term" | 1378 | name = "nu-ansi-term" |
| 2565 | version = "0.50.3" | 1379 | version = "0.50.3" |
| @@ -2579,31 +1393,6 @@ dependencies = [ | |||
| 2579 | "num-traits", | 1393 | "num-traits", |
| 2580 | ] | 1394 | ] |
| 2581 | 1395 | ||
| 2582 | -[[package]] | ||
| 2583 | -name = "num-bigint-dig" | ||
| 2584 | -version = "0.8.6" | ||
| 2585 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2586 | -checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" | ||
| 2587 | -dependencies = [ | ||
| 2588 | - "lazy_static", | ||
| 2589 | - "libm", | ||
| 2590 | - "num-integer", | ||
| 2591 | - "num-iter", | ||
| 2592 | - "num-traits", | ||
| 2593 | - "rand 0.8.7", | ||
| 2594 | - "smallvec", | ||
| 2595 | - "zeroize", | ||
| 2596 | -] | ||
| 2597 | - | ||
| 2598 | -[[package]] | ||
| 2599 | -name = "num-complex" | ||
| 2600 | -version = "0.4.6" | ||
| 2601 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2602 | -checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" | ||
| 2603 | -dependencies = [ | ||
| 2604 | - "num-traits", | ||
| 2605 | -] | ||
| 2606 | - | ||
| 2607 | [[package]] | 1396 | [[package]] |
| 2608 | name = "num-conv" | 1397 | name = "num-conv" |
| 2609 | version = "0.2.2" | 1398 | version = "0.2.2" |
| @@ -2619,16 +1408,6 @@ dependencies = [ | |||
| 2619 | "num-traits", | 1408 | "num-traits", |
| 2620 | ] | 1409 | ] |
| 2621 | 1410 | ||
| 2622 | -[[package]] | ||
| 2623 | -name = "num-iter" | ||
| 2624 | -version = "0.1.46" | ||
| 2625 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2626 | -checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" | ||
| 2627 | -dependencies = [ | ||
| 2628 | - "num-integer", | ||
| 2629 | - "num-traits", | ||
| 2630 | -] | ||
| 2631 | - | ||
| 2632 | [[package]] | 1411 | [[package]] |
| 2633 | name = "num-traits" | 1412 | name = "num-traits" |
| 2634 | version = "0.2.19" | 1413 | version = "0.2.19" |
| @@ -2636,62 +1415,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 2636 | checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" | 1415 | checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" |
| 2637 | dependencies = [ | 1416 | dependencies = [ |
| 2638 | "autocfg", | 1417 | "autocfg", |
| 2639 | - "libm", | ||
| 2640 | -] | ||
| 2641 | - | ||
| 2642 | -[[package]] | ||
| 2643 | -name = "num_cpus" | ||
| 2644 | -version = "1.17.0" | ||
| 2645 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2646 | -checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" | ||
| 2647 | -dependencies = [ | ||
| 2648 | - "hermit-abi", | ||
| 2649 | - "libc", | ||
| 2650 | -] | ||
| 2651 | - | ||
| 2652 | -[[package]] | ||
| 2653 | -name = "objc2-core-foundation" | ||
| 2654 | -version = "0.3.2" | ||
| 2655 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2656 | -checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" | ||
| 2657 | -dependencies = [ | ||
| 2658 | - "bitflags", | ||
| 2659 | -] | ||
| 2660 | - | ||
| 2661 | -[[package]] | ||
| 2662 | -name = "objc2-io-kit" | ||
| 2663 | -version = "0.3.2" | ||
| 2664 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2665 | -checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" | ||
| 2666 | -dependencies = [ | ||
| 2667 | - "libc", | ||
| 2668 | - "objc2-core-foundation", | ||
| 2669 | -] | ||
| 2670 | - | ||
| 2671 | -[[package]] | ||
| 2672 | -name = "object_store" | ||
| 2673 | -version = "0.13.2" | ||
| 2674 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2675 | -checksum = "622acbc9100d3c10e2ee15804b0caa40e55c933d5aa53814cd520805b7958a49" | ||
| 2676 | -dependencies = [ | ||
| 2677 | - "async-trait", | ||
| 2678 | - "bytes", | ||
| 2679 | - "chrono", | ||
| 2680 | - "futures-channel", | ||
| 2681 | - "futures-core", | ||
| 2682 | - "futures-util", | ||
| 2683 | - "http", | ||
| 2684 | - "humantime", | ||
| 2685 | - "itertools 0.14.0", | ||
| 2686 | - "parking_lot", | ||
| 2687 | - "percent-encoding", | ||
| 2688 | - "thiserror", | ||
| 2689 | - "tokio", | ||
| 2690 | - "tracing", | ||
| 2691 | - "url", | ||
| 2692 | - "walkdir", | ||
| 2693 | - "wasm-bindgen-futures", | ||
| 2694 | - "web-time", | ||
| 2695 | ] | 1418 | ] |
| 2696 | 1419 | ||
| 2697 | [[package]] | 1420 | [[package]] |
| @@ -2804,40 +1527,6 @@ dependencies = [ | |||
| 2804 | "tokio-stream", | 1527 | "tokio-stream", |
| 2805 | ] | 1528 | ] |
| 2806 | 1529 | ||
| 2807 | -[[package]] | ||
| 2808 | -name = "p256" | ||
| 2809 | -version = "0.13.2" | ||
| 2810 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2811 | -checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" | ||
| 2812 | -dependencies = [ | ||
| 2813 | - "ecdsa", | ||
| 2814 | - "elliptic-curve", | ||
| 2815 | - "primeorder", | ||
| 2816 | - "sha2 0.10.9", | ||
| 2817 | -] | ||
| 2818 | - | ||
| 2819 | -[[package]] | ||
| 2820 | -name = "p384" | ||
| 2821 | -version = "0.13.1" | ||
| 2822 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2823 | -checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" | ||
Cargo.tomlmodified+2 -3
| @@ -19,14 +19,12 @@ tokio-stream = { version = "0.1", features = ["sync"] } | |||
| 19 | axum = { version = "0.8.9", features = ["ws", "multipart"] } | 19 | axum = { version = "0.8.9", features = ["ws", "multipart"] } |
| 20 | axum-extra = { version = "0.12", features = ["cookie"] } | 20 | axum-extra = { version = "0.12", features = ["cookie"] } |
| 21 | tower-http = { version = "0.7", features = ["trace", "cors", "request-id", "catch-panic"] } | 21 | tower-http = { version = "0.7", features = ["trace", "cors", "request-id", "catch-panic"] } |
| 22 | -surrealdb = { version = "3.2", default-features = false, features = ["protocol-ws", "kv-mem"] } | ||
| 23 | serde = { version = "1", features = ["derive"] } | 22 | serde = { version = "1", features = ["derive"] } |
| 24 | serde_json = "1" | 23 | serde_json = "1" |
| 25 | chrono = "0.4" | 24 | chrono = "0.4" |
| 26 | argon2 = "0.6" | 25 | argon2 = "0.6" |
| 27 | getrandom = "0.4" | 26 | getrandom = "0.4" |
| 28 | hex = "0.4" | 27 | hex = "0.4" |
| 29 | -ulid = "3" | ||
| 30 | thiserror = "2" | 28 | thiserror = "2" |
| 31 | anyhow = "1" | 29 | anyhow = "1" |
| 32 | tracing = "0.1" | 30 | tracing = "0.1" |
| @@ -49,10 +47,11 @@ tower = { version = "0.5", features = ["util"] } | |||
| 49 | opentelemetry = "0.32.0" | 47 | opentelemetry = "0.32.0" |
| 50 | tracing-opentelemetry = "0.33.0" | 48 | tracing-opentelemetry = "0.33.0" |
| 51 | opentelemetry-semantic-conventions = "0.32.1" | 49 | opentelemetry-semantic-conventions = "0.32.1" |
| 52 | -uuid = { version = "1.26.1", features = ["v4"] } | 50 | +uuid = { version = "1.26.1", features = ["v4", "v7"] } |
| 53 | opentelemetry_sdk = { version = "0.32.1", features = ["rt-tokio"] } | 51 | opentelemetry_sdk = { version = "0.32.1", features = ["rt-tokio"] } |
| 54 | opentelemetry-otlp = { version = "0.32.0", default-features = false, features = ["trace", "metrics", "logs", "grpc-tonic", "http-proto", "reqwest-blocking-client", "internal-logs"] } | 52 | opentelemetry-otlp = { version = "0.32.0", default-features = false, features = ["trace", "metrics", "logs", "grpc-tonic", "http-proto", "reqwest-blocking-client", "internal-logs"] } |
| 55 | opentelemetry-appender-tracing = "0.32.0" | 53 | opentelemetry-appender-tracing = "0.32.0" |
| 54 | +sqlx = { version = "0.9.0", default-features = false, features = ["postgres", "runtime-tokio", "tls-rustls-ring", "migrate", "macros", "uuid", "json"] } | ||
| 56 | 55 | ||
| 57 | [dev-dependencies] | 56 | [dev-dependencies] |
| 58 | # test-util enables tokio::time::pause/advance for the rate limiter tests. | 57 | # test-util enables tokio::time::pause/advance for the rate limiter tests. |
Containerfilemodified+7 -3
| @@ -9,6 +9,10 @@ RUN apt-get update && \ | |||
| 9 | WORKDIR /app | 9 | WORKDIR /app |
| 10 | COPY Cargo.toml Cargo.lock ./ | 10 | COPY Cargo.toml Cargo.lock ./ |
| 11 | COPY src ./src | 11 | COPY src ./src |
| 12 | +# sqlx's compile-time macros verify every query against this committed cache, | ||
| 13 | +# so the build must never reach for a live database. | ||
| 14 | +ENV SQLX_OFFLINE=true | ||
| 15 | +COPY .sqlx ./.sqlx | ||
| 12 | 16 | ||
| 13 | # Cache mounts keep the registry and incremental build artifacts between | 17 | # Cache mounts keep the registry and incremental build artifacts between |
| 14 | # builds. The binary must be copied out of /app/target inside the same RUN, | 18 | # builds. The binary must be copied out of /app/target inside the same RUN, |
| @@ -31,11 +35,11 @@ COPY --from=builder /usr/local/bin/hezarfen_backend /usr/local/bin/hezarfen_back | |||
| 31 | 35 | ||
| 32 | USER hezarfen | 36 | USER hezarfen |
| 33 | 37 | ||
| 34 | -# HOST must be 0.0.0.0 so the port mapping can reach the listener. DB_URL | 38 | +# HOST must be 0.0.0.0 so the port mapping can reach the listener. DATABASE_URL |
| 35 | -# points at the SurrealDB server (the compose service); /data holds uploads. | 39 | +# points at the compose Postgres (the control database); /data holds uploads. |
| 36 | ENV HOST=0.0.0.0 \ | 40 | ENV HOST=0.0.0.0 \ |
| 37 | PORT=8080 \ | 41 | PORT=8080 \ |
| 38 | - DB_URL=ws://surrealdb:8000 | 42 | + DATABASE_URL=postgres://hezarfen:hezarfen@postgres:5432/hezarfen_control |
| 39 | 43 | ||
| 40 | EXPOSE 8080 | 44 | EXPOSE 8080 |
| 41 | 45 | ||
compose.yamlmodified+14 -25
| @@ -1,25 +1,18 @@ | |||
| 1 | services: | 1 | services: |
| 2 | - surrealdb: | 2 | + postgres: |
| 3 | - image: docker.io/surrealdb/surrealdb:v3 | 3 | + image: docker.io/library/postgres:18-alpine |
| 4 | - container_name: hezarfen-surrealdb | 4 | + container_name: hezarfen-postgres |
| 5 | - # Distroless image; its default `nonroot` user can't write a fresh named | 5 | + environment: |
| 6 | - # volume (created root-owned). Run as root — only this service touches | 6 | + POSTGRES_USER: hezarfen |
| 7 | - # surreal-data, the backend never mounts it. | 7 | + POSTGRES_PASSWORD: hezarfen |
| 8 | - user: "0" | 8 | + POSTGRES_DB: hezarfen_control |
| 9 | - command: | ||
| 10 | - [ | ||
| 11 | - "start", | ||
| 12 | - "--user", "root", | ||
| 13 | - "--pass", "root", | ||
| 14 | - "surrealkv:/data/hezarfen.db", | ||
| 15 | - ] | ||
| 16 | ports: | 9 | ports: |
| 17 | - - "127.0.0.1:8000:8000" | 10 | + - "127.0.0.1:5432:5432" |
| 18 | volumes: | 11 | volumes: |
| 19 | - - surreal-data:/data | 12 | + - pgdata:/data |
| 20 | restart: unless-stopped | 13 | restart: unless-stopped |
| 21 | healthcheck: | 14 | healthcheck: |
| 22 | - test: ["CMD", "/surreal", "isready"] | 15 | + test: ["CMD-SHELL", "pg_isready -U hezarfen -d hezarfen_control"] |
| 23 | interval: 10s | 16 | interval: 10s |
| 24 | timeout: 5s | 17 | timeout: 5s |
| 25 | retries: 5 | 18 | retries: 5 |
| @@ -38,13 +31,9 @@ services: | |||
| 38 | environment: | 31 | environment: |
| 39 | HOST: 0.0.0.0 | 32 | HOST: 0.0.0.0 |
| 40 | PORT: "8080" | 33 | PORT: "8080" |
| 41 | - DB_URL: ws://surrealdb:8000 | ||
| 42 | - DB_USER: root | ||
| 43 | - DB_PASS: root | ||
| 44 | - DB_NAMESPACE: hezarfen | ||
| 45 | # The control database: the school registry + the builder accounts. Each | 34 | # The control database: the school registry + the builder accounts. Each |
| 46 | - # school lives in a database of its own, named by its slug. | 35 | + # school lives in a Postgres database of its own, named from its slug. |
| 47 | - DB_DATABASE: control | 36 | + DATABASE_URL: postgres://hezarfen:hezarfen@postgres:5432/hezarfen_control |
| 48 | FILES_PATH: /data/files | 37 | FILES_PATH: /data/files |
| 49 | RUST_LOG: info,hezarfen_backend=debug | 38 | RUST_LOG: info,hezarfen_backend=debug |
| 50 | # First-boot builder seed: the operator who creates and suspends schools, | 39 | # First-boot builder seed: the operator who creates and suspends schools, |
| @@ -82,7 +71,7 @@ services: | |||
| 82 | volumes: | 71 | volumes: |
| 83 | - hezarfen-data:/data | 72 | - hezarfen-data:/data |
| 84 | depends_on: | 73 | depends_on: |
| 85 | - surrealdb: | 74 | + postgres: |
| 86 | condition: service_healthy | 75 | condition: service_healthy |
| 87 | restart: unless-stopped | 76 | restart: unless-stopped |
| 88 | healthcheck: | 77 | healthcheck: |
| @@ -133,5 +122,5 @@ services: | |||
| 133 | 122 | ||
| 134 | volumes: | 123 | volumes: |
| 135 | hezarfen-data: | 124 | hezarfen-data: |
| 136 | - surreal-data: | 125 | + pgdata: |
| 137 | openobserve-data: | 126 | openobserve-data: |
migrations/control/20260912000001_control.sqladded+60 -0
| @@ -0,0 +1,60 @@ | |||
| 1 | +-- Control-database schema (Postgres). | ||
| 2 | +-- | ||
| 3 | +-- DISJOINTNESS INVARIANT: the tables here (school, builder, builder_session, | ||
| 4 | +-- rate_limit) and every table in migrations/school/*.sql together form ONE | ||
| 5 | +-- union schema, applied to a single prepare database by | ||
| 6 | +-- scripts/prepare_db.sh for sqlx's compile-time query macros. The two sets | ||
| 7 | +-- must never collide on a table name; the prepare script fails loudly if they | ||
| 8 | +-- do. | ||
| 9 | +-- | ||
| 10 | +-- Translated from src/migration_sql.rs CONTROL_MIGRATION (SurrealDB), per the | ||
| 11 | +-- plan's schema translation rules. Entity ids are app-minted UUID v7 (no DB | ||
| 12 | +-- default); timestamps stay BIGINT unix-ms. All FKs are ON DELETE NO ACTION — | ||
| 13 | +-- cascades stay explicit application transactions. | ||
| 14 | +-- | ||
| 15 | +-- Renames (reserved words, never quoted): table `school` keeps its name (its | ||
| 16 | +-- Surreal record id WAS the slug, so slug is the PRIMARY KEY, constraint | ||
| 17 | +-- carrying the old index name school_slug). | ||
| 18 | +-- | ||
| 19 | +-- `rate_limit` exists ONLY here, not in the school schema: rate limiting is | ||
| 20 | +-- billed against the control handle before any cookie names a school (see the | ||
| 21 | +-- CONTROL_MIGRATION doc), and the school-side `rate_limit` DEFINE in the old | ||
| 22 | +-- Surreal migration had no school-side reader. Its id is the derived | ||
| 23 | +-- `tier:client:window` key, so the PK is TEXT. | ||
| 24 | + | ||
| 25 | +CREATE TABLE school ( | ||
| 26 | + slug TEXT NOT NULL, | ||
| 27 | + name TEXT NOT NULL, | ||
| 28 | + status TEXT NOT NULL CHECK (status IN ('active', 'suspended')), | ||
| 29 | + created_at BIGINT NOT NULL, | ||
| 30 | + -- Which product modules this school has bought; names bound from | ||
| 31 | + -- Module::ALL at write time, never spelled here. | ||
| 32 | + modules TEXT[] NOT NULL DEFAULT '{}', | ||
| 33 | + CONSTRAINT school_slug PRIMARY KEY (slug) | ||
| 34 | +); | ||
| 35 | + | ||
| 36 | +CREATE TABLE builder ( | ||
| 37 | + id uuid PRIMARY KEY, | ||
| 38 | + username TEXT NOT NULL, | ||
| 39 | + password_hash TEXT NOT NULL, | ||
| 40 | + CONSTRAINT builder_username UNIQUE (username) | ||
| 41 | +); | ||
| 42 | + | ||
| 43 | +CREATE TABLE builder_session ( | ||
| 44 | + id uuid PRIMARY KEY, | ||
| 45 | + builder uuid NOT NULL REFERENCES builder(id) ON DELETE NO ACTION, | ||
| 46 | + token TEXT NOT NULL, | ||
| 47 | + created_at BIGINT NOT NULL, | ||
| 48 | + expires_at BIGINT NOT NULL, | ||
| 49 | + CONSTRAINT builder_session_token UNIQUE (token) | ||
| 50 | +); | ||
| 51 | + | ||
| 52 | +CREATE INDEX builder_session_expires ON builder_session (expires_at); | ||
| 53 | + | ||
| 54 | +-- One row per tier+client+window; the durable fold target of the in-memory | ||
| 55 | +-- bucket (see src/rate_limit.rs). | ||
| 56 | +CREATE TABLE rate_limit ( | ||
| 57 | + id TEXT PRIMARY KEY, | ||
| 58 | + hits BIGINT NOT NULL DEFAULT 0, | ||
| 59 | + window_start BIGINT NOT NULL | ||
| 60 | +); | ||
migrations/school/20260912000001_identity.sqladded+275 -0
| @@ -0,0 +1,275 @@ | |||
| 1 | +-- School-database schema, part 1: identity, sessions, notes, messages, | ||
| 2 | +-- parent links, work, pomodoro, badges, boards, chatbot, settings, refcounts | ||
| 3 | +-- (Postgres). | ||
| 4 | +-- | ||
| 5 | +-- DISJOINTNESS INVARIANT: the tables in migrations/school/*.sql and the ones | ||
| 6 | +-- in migrations/control/*.sql together form ONE union schema, applied to a | ||
| 7 | +-- single prepare database by scripts/prepare_db.sh for sqlx's compile-time | ||
| 8 | +-- query macros. The two sets must never collide on a table name. | ||
| 9 | +-- | ||
| 10 | +-- Translated from src/migration_sql.rs MIGRATION (SurrealDB), per the plan's | ||
| 11 | +-- schema translation rules. Binding renames (reserved words, never quoted): | ||
| 12 | +-- table `user` -> app_user | ||
| 13 | +-- table `session` -> user_session | ||
| 14 | +-- every column named `user` -> `app_user` (PostgreSQL rejects the bare | ||
| 15 | +-- word as a column name; the plan's fallback prefixes the domain noun) | ||
| 16 | +-- `session` as a COLUMN name (session_attendance.session) is legal in | ||
| 17 | +-- PostgreSQL (non-reserved) and stays. Entity ids are app-minted UUID v7 (no | ||
| 18 | +-- DB default); timestamps stay BIGINT unix-ms; counter columns | ||
| 19 | +-- (absent-reads-as-zero in Surreal) are BIGINT NOT NULL DEFAULT 0 and stay | ||
| 20 | +-- out of the Rust structs. All FKs ON DELETE NO ACTION. | ||
| 21 | +-- | ||
| 22 | +-- Deliberately NOT translated from the Surreal source: `rate_limit` (control | ||
| 23 | +-- only — see migrations/control), `migration_mark` + every `REMOVE ...` | ||
| 24 | +-- retirement line, PRE_REPAIR, BACKFILL, migration_mark machinery (all dead, | ||
| 25 | +-- preproduction). | ||
| 26 | +-- | ||
| 27 | +-- CHECK constraints carry exactly the `#[surreal(untagged, | ||
| 28 | +-- rename_all = "lowercase")]` enums (role, folder, chatbot role/status, | ||
| 29 | +-- ledger kinds, audience tags, school status). Validated-String newtypes | ||
| 30 | +-- (course kind, exam kind/mode, homework status, attendance statuses, pool | ||
| 31 | +-- status, board_stroke kind, bank visibility) keep NO CHECK — the repo | ||
| 32 | +-- convention is that those enums live in Rust newtypes, and attendance | ||
| 33 | +-- statuses / exam kinds are school-configurable at runtime, which a DDL | ||
| 34 | +-- CHECK could not survive. | ||
| 35 | + | ||
| 36 | +CREATE TABLE app_user ( | ||
| 37 | + id uuid PRIMARY KEY, | ||
| 38 | + username TEXT NOT NULL, | ||
| 39 | + password_hash TEXT NOT NULL, | ||
| 40 | + role TEXT NOT NULL DEFAULT 'student' | ||
| 41 | + CHECK (role IN ('ai', 'parent', 'student', 'teacher', 'manager', 'admin')), | ||
| 42 | + name TEXT NULL, | ||
| 43 | + surname TEXT NULL, | ||
| 44 | + email TEXT NULL, | ||
| 45 | + phone TEXT NULL, | ||
| 46 | + birth_date TEXT NULL, | ||
| 47 | + theme TEXT NULL CHECK (theme IN ('light', 'dark')), | ||
| 48 | + language TEXT NULL CHECK (language IN ('tr', 'en')), | ||
| 49 | + palette_color TEXT NULL, | ||
| 50 | + display_name TEXT NULL, | ||
| 51 | + bio TEXT NULL, | ||
| 52 | + avatar_file TEXT NULL, | ||
| 53 | + avatar_content_type TEXT NULL, | ||
| 54 | + avatar_size BIGINT NULL, | ||
| 55 | + -- Lifetime/claim counters: absent-reads-as-zero in Surreal, DEFAULT 0 | ||
| 56 | + -- here, and (as today) carried by no Rust struct. | ||
| 57 | + chatbot_thread_count BIGINT NOT NULL DEFAULT 0, | ||
| 58 | + board_count BIGINT NOT NULL DEFAULT 0, | ||
| 59 | + homework_submitted_total BIGINT NOT NULL DEFAULT 0, | ||
| 60 | + homework_on_time_total BIGINT NOT NULL DEFAULT 0, | ||
| 61 | + exam_sat_total BIGINT NOT NULL DEFAULT 0, | ||
| 62 | + pomodoro_finished_total BIGINT NOT NULL DEFAULT 0, | ||
| 63 | + pomodoro_focus_ms_total BIGINT NOT NULL DEFAULT 0, | ||
| 64 | + marks_given_total BIGINT NOT NULL DEFAULT 0, | ||
| 65 | + lessons_held_total BIGINT NOT NULL DEFAULT 0, | ||
| 66 | + pool_approved_total BIGINT NOT NULL DEFAULT 0, | ||
| 67 | + pool_published_total BIGINT NOT NULL DEFAULT 0, | ||
| 68 | + lessons_attended_total BIGINT NOT NULL DEFAULT 0, | ||
| 69 | + high_mark_total BIGINT NOT NULL DEFAULT 0, | ||
| 70 | + study_streak_longest BIGINT NOT NULL DEFAULT 0, | ||
| 71 | + study_streak_current BIGINT NOT NULL DEFAULT 0, | ||
| 72 | + -- Day markers, not counts: absent means "no day yet", which NULL keeps | ||
| 73 | + -- (DEFAULT 0 would mean the epoch day). | ||
| 74 | + study_streak_last_day BIGINT NULL, | ||
| 75 | + pomodoro_counted_today BIGINT NOT NULL DEFAULT 0, | ||
| 76 | + pomodoro_counted_day BIGINT NULL, | ||
| 77 | + CONSTRAINT app_user_username UNIQUE (username) | ||
| 78 | +); | ||
| 79 | + | ||
| 80 | +CREATE TABLE user_session ( | ||
| 81 | + id uuid PRIMARY KEY, | ||
| 82 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 83 | + token TEXT NOT NULL, | ||
| 84 | + expires_at BIGINT NOT NULL, | ||
| 85 | + CONSTRAINT session_token UNIQUE (token) | ||
| 86 | +); | ||
| 87 | + | ||
| 88 | +CREATE INDEX session_expires ON user_session (expires_at); | ||
| 89 | + | ||
| 90 | +CREATE TABLE note ( | ||
| 91 | + id uuid PRIMARY KEY, | ||
| 92 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 93 | + title TEXT NOT NULL, | ||
| 94 | + content TEXT NOT NULL, | ||
| 95 | + file_count BIGINT NOT NULL DEFAULT 0 | ||
| 96 | +); | ||
| 97 | + | ||
| 98 | +CREATE INDEX note_user ON note (app_user); | ||
| 99 | + | ||
| 100 | +CREATE TABLE note_file ( | ||
| 101 | + id uuid PRIMARY KEY, | ||
| 102 | + note uuid NOT NULL REFERENCES note(id) ON DELETE NO ACTION, | ||
| 103 | + name TEXT NOT NULL, | ||
| 104 | + content_type TEXT NOT NULL, | ||
| 105 | + size BIGINT NOT NULL | ||
| 106 | +); | ||
| 107 | + | ||
| 108 | +CREATE INDEX note_file_note ON note_file (note); | ||
| 109 | + | ||
| 110 | +CREATE TABLE message ( | ||
| 111 | + id uuid PRIMARY KEY, | ||
| 112 | + sender uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 113 | + recipient uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 114 | + subject TEXT NOT NULL, | ||
| 115 | + body TEXT NOT NULL, | ||
| 116 | + label TEXT NULL, | ||
| 117 | + sent_at BIGINT NOT NULL, | ||
| 118 | + read BOOLEAN NOT NULL DEFAULT false, | ||
| 119 | + sender_folder TEXT NOT NULL DEFAULT 'sent' | ||
| 120 | + CHECK (sender_folder IN ('inbox', 'sent', 'archive', 'trash', 'deleted')), | ||
| 121 | + recipient_folder TEXT NOT NULL DEFAULT 'inbox' | ||
| 122 | + CHECK (recipient_folder IN ('inbox', 'sent', 'archive', 'trash', 'deleted')), | ||
| 123 | + -- Where each side's copy sat before it was filed into archive/trash; | ||
| 124 | + -- NULL while the copy is in its home folder. | ||
| 125 | + sender_origin TEXT NULL, | ||
| 126 | + recipient_origin TEXT NULL | ||
| 127 | +); | ||
| 128 | + | ||
| 129 | +CREATE INDEX message_sender ON message (sender); | ||
| 130 | +CREATE INDEX message_recipient ON message (recipient); | ||
| 131 | + | ||
| 132 | +CREATE TABLE parent_link ( | ||
| 133 | + parent uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 134 | + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 135 | + linked_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 136 | + CONSTRAINT parent_link_parent_student PRIMARY KEY (parent, student) | ||
| 137 | +); | ||
| 138 | + | ||
| 139 | +CREATE INDEX parent_link_parent ON parent_link (parent); | ||
| 140 | +CREATE INDEX parent_link_student ON parent_link (student); | ||
| 141 | + | ||
| 142 | +CREATE TABLE work_entry ( | ||
| 143 | + id uuid PRIMARY KEY, | ||
| 144 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 145 | + check_in BIGINT NOT NULL, | ||
| 146 | + check_out BIGINT NULL | ||
| 147 | +); | ||
| 148 | + | ||
| 149 | +CREATE INDEX work_entry_user ON work_entry (app_user); | ||
| 150 | +-- At most one open stint per user: the deterministic `open_{user}` key of | ||
| 151 | +-- `WorkEntryId::open_for`, now DB-enforced (closed entries keep minted ids). | ||
| 152 | +CREATE UNIQUE INDEX work_entry_open ON work_entry (app_user) WHERE check_out IS NULL; | ||
| 153 | + | ||
| 154 | +CREATE TABLE pomodoro_session ( | ||
| 155 | + id uuid PRIMARY KEY, | ||
| 156 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 157 | + started_at BIGINT NOT NULL, | ||
| 158 | + finished_at BIGINT NULL, | ||
| 159 | + -- The verdict `finish` reached for this stint, stamped at close; NULL on | ||
| 160 | + -- a running stint, and on a stint closed before the rule existed. | ||
| 161 | + counted BOOLEAN NULL, | ||
| 162 | + -- The student's own name for what the stint is for ('math', 'TYT | ||
| 163 | + -- denemesi') — free text given at start, not a subject link. | ||
| 164 | + label TEXT NULL | ||
| 165 | +); | ||
| 166 | + | ||
| 167 | +CREATE INDEX pomodoro_session_user ON pomodoro_session (app_user); | ||
| 168 | +-- One open stint per user: the deterministic open-stint row of | ||
| 169 | +-- `PomodoroSession::open_for`, now DB-enforced. | ||
| 170 | +CREATE UNIQUE INDEX pomodoro_session_open_stint | ||
| 171 | + ON pomodoro_session (app_user) WHERE finished_at IS NULL; | ||
| 172 | + | ||
| 173 | +-- One row per badge a user has earned; the deterministic {user}_{badge} | ||
| 174 | +-- pair. Awards are permanent — nothing deletes a row here. | ||
| 175 | +CREATE TABLE badge_award ( | ||
| 176 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 177 | + badge TEXT NOT NULL, | ||
| 178 | + earned_at BIGINT NULL, | ||
| 179 | + CONSTRAINT badge_award_user_badge PRIMARY KEY (app_user, badge) | ||
| 180 | +); | ||
| 181 | + | ||
| 182 | +CREATE INDEX badge_award_user ON badge_award (app_user); | ||
| 183 | + | ||
| 184 | +CREATE TABLE board ( | ||
| 185 | + id uuid PRIMARY KEY, | ||
| 186 | + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 187 | + title TEXT NOT NULL, | ||
| 188 | + participants uuid[] NOT NULL DEFAULT '{}', | ||
| 189 | + locked BOOLEAN NOT NULL DEFAULT false, | ||
| 190 | + locked_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 191 | + locked_at BIGINT NULL, | ||
| 192 | + epoch BIGINT NOT NULL DEFAULT 0, | ||
| 193 | + epoch_stroke_count BIGINT NOT NULL DEFAULT 0, | ||
| 194 | + total_stroke_count BIGINT NOT NULL DEFAULT 0, | ||
| 195 | + closed_at BIGINT NULL, | ||
| 196 | + created_at BIGINT NOT NULL | ||
| 197 | +); | ||
| 198 | + | ||
| 199 | +CREATE INDEX board_creator ON board (creator); | ||
| 200 | +-- The board list asks `creator = $u OR participants CONTAINS $u`; the GIN | ||
| 201 | +-- index covers the membership half ($1 = ANY(participants) at query sites). | ||
| 202 | +CREATE INDEX board_participants ON board USING GIN (participants); | ||
| 203 | + | ||
| 204 | +CREATE TABLE board_stroke ( | ||
| 205 | + id uuid PRIMARY KEY, | ||
| 206 | + board uuid NOT NULL REFERENCES board(id) ON DELETE NO ACTION, | ||
| 207 | + author uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 208 | + -- 'stroke' or 'clear'; payload NULL on a clear marker, count populated | ||
| 209 | + -- only on a clear marker — the final stroke count of the epoch that | ||
| 210 | + -- marker closed. | ||
| 211 | + kind TEXT NOT NULL, | ||
| 212 | + payload TEXT NULL, | ||
| 213 | + count BIGINT NULL, | ||
| 214 | + epoch BIGINT NOT NULL, | ||
| 215 | + created_at BIGINT NOT NULL | ||
| 216 | +); | ||
| 217 | + | ||
| 218 | +CREATE INDEX board_stroke_board_epoch ON board_stroke (board, epoch); | ||
| 219 | +CREATE INDEX board_stroke_board_kind ON board_stroke (board, kind); | ||
| 220 | + | ||
| 221 | +CREATE TABLE chatbot_thread ( | ||
| 222 | + id uuid PRIMARY KEY, | ||
| 223 | + user_id uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 224 | + title TEXT NULL, | ||
| 225 | + created_at BIGINT NOT NULL, | ||
| 226 | + updated_at BIGINT NOT NULL | ||
| 227 | +); | ||
| 228 | + | ||
| 229 | +CREATE INDEX chatbot_thread_user_updated ON chatbot_thread (user_id, updated_at); | ||
| 230 | + | ||
| 231 | +CREATE TABLE chatbot_message ( | ||
| 232 | + id uuid PRIMARY KEY, | ||
| 233 | + thread_id uuid NOT NULL REFERENCES chatbot_thread(id) ON DELETE NO ACTION, | ||
| 234 | + user_id uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 235 | + role TEXT NOT NULL CHECK (role IN ('user', 'assistant')), | ||
| 236 | + content TEXT NOT NULL, | ||
| 237 | + status TEXT NOT NULL CHECK (status IN ('pending', 'complete', 'failed')), | ||
| 238 | + truncated BOOLEAN NOT NULL DEFAULT false, | ||
| 239 | + error_code TEXT NULL, | ||
| 240 | + created_at BIGINT NOT NULL, | ||
| 241 | + completed_at BIGINT NULL | ||
| 242 | +); | ||
| 243 | + | ||
| 244 | +CREATE INDEX chatbot_message_thread_created ON chatbot_message (thread_id, created_at); | ||
| 245 | +CREATE INDEX chatbot_message_user ON chatbot_message (user_id); | ||
| 246 | +CREATE INDEX chatbot_message_status_created ON chatbot_message (status, created_at); | ||
| 247 | + | ||
| 248 | +CREATE TABLE settings ( | ||
| 249 | + -- Singleton row: id = 'school'. | ||
| 250 | + id TEXT PRIMARY KEY, | ||
| 251 | + exam_kinds JSONB NOT NULL, | ||
| 252 | + attendance_statuses TEXT[] NOT NULL, | ||
| 253 | + grade_bands JSONB NOT NULL, | ||
| 254 | + max_file_bytes BIGINT NULL, | ||
| 255 | + chatbot_history_turns BIGINT NULL, | ||
| 256 | + max_chatbot_message_len BIGINT NULL, | ||
| 257 | + max_chatbot_threads BIGINT NULL, | ||
| 258 | + meal_slots JSONB NULL, | ||
| 259 | + dietary_tags TEXT[] NULL, | ||
| 260 | + meal_cancel_cutoff_minutes BIGINT NULL | ||
| 261 | +); | ||
| 262 | + | ||
| 263 | +-- Reference counters, one row per *name* the settings offer. Created by the | ||
| 264 | +-- first claim; an absent row reads as zero references, in service. | ||
| 265 | +CREATE TABLE kind_ref ( | ||
| 266 | + name TEXT PRIMARY KEY, | ||
| 267 | + count BIGINT NOT NULL DEFAULT 0, | ||
| 268 | + retired BOOLEAN NOT NULL DEFAULT false | ||
| 269 | +); | ||
| 270 | + | ||
| 271 | +CREATE TABLE slot_ref ( | ||
| 272 | + name TEXT PRIMARY KEY, | ||
| 273 | + count BIGINT NOT NULL DEFAULT 0, | ||
| 274 | + retired BOOLEAN NOT NULL DEFAULT false | ||
| 275 | +); | ||
migrations/school/20260912000002_courses.sqladded+208 -0
| @@ -0,0 +1,208 @@ | |||
| 1 | +-- School-database schema, part 2: courses, terms, classes, enrollment, | ||
| 2 | +-- events, attendance (Postgres). | ||
| 3 | +-- | ||
| 4 | +-- DISJOINTNESS INVARIANT: the tables in migrations/school/*.sql and the ones | ||
| 5 | +-- in migrations/control/*.sql together form ONE union schema, applied to a | ||
| 6 | +-- single prepare database by scripts/prepare_db.sh for sqlx's compile-time | ||
| 7 | +-- query macros. The two sets must never collide on a table name. | ||
| 8 | +-- | ||
| 9 | +-- Same translation rules as part 1: table `user` -> app_user (and every | ||
| 10 | +-- column named `user`), record refs -> uuid FKs ON DELETE NO ACTION, natural | ||
| 11 | +-- composite PKs replace the old `{a}_{b}` text record keys (the PK constraint | ||
| 12 | +-- carries the old unique-index name — it is what surfaces in SQLSTATE 23505), | ||
| 13 | +-- counters are BIGINT NOT NULL DEFAULT 0 and stay out of the Rust structs. | ||
| 14 | + | ||
| 15 | +CREATE TABLE term ( | ||
| 16 | + id uuid PRIMARY KEY, | ||
| 17 | + name TEXT NOT NULL, | ||
| 18 | + starts_at BIGINT NOT NULL, | ||
| 19 | + ends_at BIGINT NOT NULL, | ||
| 20 | + -- When the term was archived; NULL = open. | ||
| 21 | + archived_at BIGINT NULL, | ||
| 22 | + course_count BIGINT NOT NULL DEFAULT 0, | ||
| 23 | + class_count BIGINT NOT NULL DEFAULT 0 | ||
| 24 | +); | ||
| 25 | + | ||
| 26 | +CREATE TABLE course ( | ||
| 27 | + id uuid PRIMARY KEY, | ||
| 28 | + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 29 | + teachers uuid[] NOT NULL DEFAULT '{}', | ||
| 30 | + title TEXT NOT NULL, | ||
| 31 | + description TEXT NOT NULL, | ||
| 32 | + kind TEXT NOT NULL DEFAULT 'course', | ||
| 33 | + term uuid NULL REFERENCES term(id) ON DELETE NO ACTION, | ||
| 34 | + capacity BIGINT NULL, | ||
| 35 | + enrollment_count BIGINT NOT NULL DEFAULT 0 | ||
| 36 | +); | ||
| 37 | +-- No GIN on teachers, faithful to the Surreal schema: the teachers-membership | ||
| 38 | +-- read stays a scan, exactly as today (see src/db/course.rs — the Surreal | ||
| 39 | +-- per-element index form returned zero rows and was never defined). | ||
| 40 | + | ||
| 41 | +CREATE TABLE subject ( | ||
| 42 | + id uuid PRIMARY KEY, | ||
| 43 | + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, | ||
| 44 | + name TEXT NOT NULL, | ||
| 45 | + description TEXT NOT NULL, | ||
| 46 | + exam_question_count BIGINT NOT NULL DEFAULT 0, | ||
| 47 | + homework_count BIGINT NOT NULL DEFAULT 0 | ||
| 48 | +); | ||
| 49 | + | ||
| 50 | +CREATE INDEX subject_course ON subject (course); | ||
| 51 | + | ||
| 52 | +CREATE TABLE course_note ( | ||
| 53 | + id uuid PRIMARY KEY, | ||
| 54 | + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, | ||
| 55 | + author uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 56 | + title TEXT NOT NULL, | ||
| 57 | + content TEXT NOT NULL, | ||
| 58 | + file_count BIGINT NOT NULL DEFAULT 0 | ||
| 59 | +); | ||
| 60 | + | ||
| 61 | +CREATE INDEX course_note_course ON course_note (course); | ||
| 62 | + | ||
| 63 | +CREATE TABLE course_note_file ( | ||
| 64 | + id uuid PRIMARY KEY, | ||
| 65 | + course_note uuid NOT NULL REFERENCES course_note(id) ON DELETE NO ACTION, | ||
| 66 | + name TEXT NOT NULL, | ||
| 67 | + content_type TEXT NOT NULL, | ||
| 68 | + size BIGINT NOT NULL | ||
| 69 | +); | ||
| 70 | + | ||
| 71 | +CREATE INDEX course_note_file_note ON course_note_file (course_note); | ||
| 72 | + | ||
| 73 | +-- What an AI service produced for a course note. Derived and disposable; | ||
| 74 | +-- payload is JSONB because its shape belongs to the service, not this schema. | ||
| 75 | +CREATE TABLE rag_output ( | ||
| 76 | + id uuid PRIMARY KEY, | ||
| 77 | + course_note uuid NOT NULL REFERENCES course_note(id) ON DELETE NO ACTION, | ||
| 78 | + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, | ||
| 79 | + sources uuid[] NOT NULL DEFAULT '{}', | ||
| 80 | + payload JSONB NOT NULL, | ||
| 81 | + generated_at BIGINT NOT NULL | ||
| 82 | +); | ||
| 83 | + | ||
| 84 | +CREATE INDEX rag_output_note ON rag_output (course_note); | ||
| 85 | +-- The source cascade asks `sources CONTAINS $file`; the GIN index makes it a | ||
| 86 | +-- lookup instead of a scan. | ||
| 87 | +CREATE INDEX rag_output_source ON rag_output USING GIN (sources); | ||
| 88 | + | ||
| 89 | +CREATE TABLE course_session ( | ||
| 90 | + id uuid PRIMARY KEY, | ||
| 91 | + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, | ||
| 92 | + teacher uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 93 | + topic TEXT NOT NULL, | ||
| 94 | + starts_at BIGINT NOT NULL, | ||
| 95 | + ends_at BIGINT NULL, | ||
| 96 | + -- The once-per-session guard behind lessons_held_total: stamped by the | ||
| 97 | + -- first roll call taken for the lesson. | ||
| 98 | + held_counted_at BIGINT NULL | ||
| 99 | +); | ||
| 100 | + | ||
| 101 | +CREATE INDEX course_session_course ON course_session (course); | ||
| 102 | + | ||
| 103 | +CREATE TABLE session_attendance ( | ||
| 104 | + session uuid NOT NULL REFERENCES course_session(id) ON DELETE NO ACTION, | ||
| 105 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 106 | + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, | ||
| 107 | + status TEXT NOT NULL, | ||
| 108 | + marked_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 109 | + CONSTRAINT session_attendance_session_user PRIMARY KEY (session, app_user) | ||
| 110 | +); | ||
| 111 | + | ||
| 112 | +CREATE INDEX session_attendance_session ON session_attendance (session); | ||
| 113 | +CREATE INDEX session_attendance_user ON session_attendance (app_user); | ||
| 114 | +CREATE INDEX session_attendance_course ON session_attendance (course); | ||
| 115 | + | ||
| 116 | +CREATE TABLE class_group ( | ||
| 117 | + id uuid PRIMARY KEY, | ||
| 118 | + name TEXT NOT NULL, | ||
| 119 | + grade TEXT NULL, | ||
| 120 | + term uuid NULL REFERENCES term(id) ON DELETE NO ACTION, | ||
| 121 | + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 122 | + teacher uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 123 | + class_member_count BIGINT NOT NULL DEFAULT 0, | ||
| 124 | + class_course_count BIGINT NOT NULL DEFAULT 0 | ||
| 125 | +); | ||
| 126 | + | ||
| 127 | +CREATE INDEX class_group_grade ON class_group (grade); | ||
| 128 | + | ||
| 129 | +-- A grade's course template. The grade label IS the record key in Surreal, so | ||
| 130 | +-- the PK here is TEXT on grade itself (no id column, no uuid). | ||
| 131 | +CREATE TABLE class_blueprint ( | ||
| 132 | + grade TEXT PRIMARY KEY, | ||
| 133 | + courses uuid[] NOT NULL DEFAULT '{}', | ||
| 134 | + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION | ||
| 135 | +); | ||
| 136 | + | ||
| 137 | +CREATE TABLE class_member ( | ||
| 138 | + class uuid NOT NULL REFERENCES class_group(id) ON DELETE NO ACTION, | ||
| 139 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 140 | + added_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 141 | + -- When the student was put in; NULL on rows of unknown age. | ||
| 142 | + added_at BIGINT NULL, | ||
| 143 | + CONSTRAINT class_member_class_user PRIMARY KEY (class, app_user) | ||
| 144 | +); | ||
| 145 | + | ||
| 146 | +CREATE INDEX class_member_class ON class_member (class); | ||
| 147 | +CREATE INDEX class_member_user ON class_member (app_user); | ||
| 148 | + | ||
| 149 | +CREATE TABLE class_course ( | ||
| 150 | + class uuid NOT NULL REFERENCES class_group(id) ON DELETE NO ACTION, | ||
| 151 | + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, | ||
| 152 | + attached_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 153 | + attached_at BIGINT NULL, | ||
| 154 | + -- The blueprint that attached this course; NULL = attached by hand, which | ||
| 155 | + -- keeps a hand-attached course unreachable by every blueprint sweep. | ||
| 156 | + source TEXT NULL REFERENCES class_blueprint(grade) ON DELETE NO ACTION, | ||
| 157 | + CONSTRAINT class_course_class_course PRIMARY KEY (class, course) | ||
| 158 | +); | ||
| 159 | + | ||
| 160 | +CREATE INDEX class_course_class ON class_course (class); | ||
| 161 | +CREATE INDEX class_course_course ON class_course (course); | ||
| 162 | + | ||
| 163 | +CREATE TABLE enrollment ( | ||
| 164 | + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, | ||
| 165 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 166 | + enrolled_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 167 | + -- The class that pumped this row; NULL when a human placed the student. | ||
| 168 | + source uuid NULL REFERENCES class_group(id) ON DELETE NO ACTION, | ||
| 169 | + CONSTRAINT enrollment_course_user PRIMARY KEY (course, app_user) | ||
| 170 | +); | ||
| 171 | + | ||
| 172 | +CREATE INDEX enrollment_user ON enrollment (app_user); | ||
| 173 | + | ||
| 174 | +CREATE TABLE event ( | ||
| 175 | + id uuid PRIMARY KEY, | ||
| 176 | + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 177 | + title TEXT NOT NULL, | ||
| 178 | + description TEXT NOT NULL, | ||
| 179 | + -- The EventAudience enum flattened into columns (tag + per-variant data). | ||
| 180 | + audience_kind TEXT NOT NULL | ||
| 181 | + CHECK (audience_kind IN ('school', 'role', 'course', 'class', 'registration')), | ||
| 182 | + audience_role TEXT NULL, | ||
| 183 | + audience_course uuid NULL REFERENCES course(id) ON DELETE NO ACTION, | ||
| 184 | + audience_class uuid NULL REFERENCES class_group(id) ON DELETE NO ACTION, | ||
| 185 | + audience_capacity BIGINT NULL, | ||
| 186 | + registration_count BIGINT NOT NULL DEFAULT 0, | ||
| 187 | + starts_at BIGINT NULL, | ||
| 188 | + ends_at BIGINT NULL | ||
| 189 | +); | ||
| 190 | + | ||
| 191 | +CREATE TABLE attendance ( | ||
| 192 | + event uuid NOT NULL REFERENCES event(id) ON DELETE NO ACTION, | ||
| 193 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 194 | + status TEXT NOT NULL, | ||
| 195 | + marked_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 196 | + CONSTRAINT attendance_event_user PRIMARY KEY (event, app_user) | ||
| 197 | +); | ||
| 198 | + | ||
| 199 | +CREATE INDEX attendance_user ON attendance (app_user); | ||
| 200 | + | ||
| 201 | +CREATE TABLE registration ( | ||
| 202 | + event uuid NOT NULL REFERENCES event(id) ON DELETE NO ACTION, | ||
| 203 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 204 | + registered_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 205 | + CONSTRAINT registration_event_user PRIMARY KEY (event, app_user) | ||
| 206 | +); | ||
| 207 | + | ||
| 208 | +CREATE INDEX registration_event ON registration (event); | ||
migrations/school/20260912000003_exams.sqladded+242 -0
| @@ -0,0 +1,242 @@ | |||
| 1 | +-- School-database schema, part 3: exams, question bank, pool, homework | ||
| 2 | +-- (Postgres). | ||
| 3 | +-- | ||
| 4 | +-- DISJOINTNESS INVARIANT: the tables in migrations/school/*.sql and the ones | ||
| 5 | +-- in migrations/control/*.sql together form ONE union schema, applied to a | ||
| 6 | +-- single prepare database by scripts/prepare_db.sh for sqlx's compile-time | ||
| 7 | +-- query macros. The two sets must never collide on a table name. | ||
| 8 | +-- | ||
| 9 | +-- Same translation rules as parts 1-2. Sitting-scoped tables | ||
| 10 | +-- (exam_attempt / exam_answer / answer_image / exam_result) key on their | ||
| 11 | +-- natural composite (…, app_user, seq); a retake's row is a new row, never an | ||
| 12 | +-- overwrite of the prior sitting. `choices` is JSONB (array of {id, text} | ||
| 13 | +-- objects); exam.kind / exam.mode / homework_result.status / | ||
| 14 | +-- pool_question.status / bank_question.visibility carry NO CHECK — validated | ||
| 15 | +-- String newtypes in Rust, and exam kinds are school-configurable at runtime. | ||
| 16 | + | ||
| 17 | +CREATE TABLE exam ( | ||
| 18 | + id uuid PRIMARY KEY, | ||
| 19 | + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 20 | + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, | ||
| 21 | + title TEXT NOT NULL, | ||
| 22 | + description TEXT NOT NULL, | ||
| 23 | + kind TEXT NOT NULL, | ||
| 24 | + mode TEXT NULL, | ||
| 25 | + starts_at BIGINT NULL, | ||
| 26 | + ends_at BIGINT NULL, | ||
| 27 | + duration_ms BIGINT NULL, | ||
| 28 | + max_attempts BIGINT NOT NULL DEFAULT 1, | ||
| 29 | + allow_rejoin BOOLEAN NOT NULL DEFAULT true, | ||
| 30 | + allow_review BOOLEAN NOT NULL DEFAULT false, | ||
| 31 | + draft BOOLEAN NOT NULL DEFAULT false, | ||
| 32 | + result_count BIGINT NOT NULL DEFAULT 0 | ||
| 33 | +); | ||
| 34 | + | ||
| 35 | +CREATE INDEX exam_course ON exam (course); | ||
| 36 | + | ||
| 37 | +-- Created before exam_question: source_exam points back at exam. | ||
| 38 | +CREATE TABLE bank_question ( | ||
| 39 | + id uuid PRIMARY KEY, | ||
| 40 | + owner uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 41 | + subject uuid NULL REFERENCES subject(id) ON DELETE NO ACTION, | ||
| 42 | + text TEXT NOT NULL, | ||
| 43 | + kind TEXT NOT NULL, | ||
| 44 | + points BIGINT NOT NULL, | ||
| 45 | + choices JSONB NULL, | ||
| 46 | + correct TEXT NULL, | ||
| 47 | + source_exam uuid NULL REFERENCES exam(id) ON DELETE NO ACTION, | ||
| 48 | + -- 'private' | 'school'; DEFAULT so a partial write can never come out | ||
| 49 | + -- published. | ||
| 50 | + visibility TEXT NOT NULL DEFAULT 'private', | ||
| 51 | + created_at BIGINT NOT NULL | ||
| 52 | +); | ||
| 53 | + | ||
| 54 | +CREATE INDEX bank_question_owner ON bank_question (owner); | ||
| 55 | +CREATE INDEX bank_question_subject ON bank_question (subject); | ||
| 56 | + | ||
| 57 | +CREATE TABLE exam_question ( | ||
| 58 | + id uuid PRIMARY KEY, | ||
| 59 | + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, | ||
| 60 | + text TEXT NOT NULL, | ||
| 61 | + kind TEXT NOT NULL, | ||
| 62 | + points BIGINT NOT NULL, | ||
| 63 | + choices JSONB NULL, | ||
| 64 | + correct TEXT NULL, | ||
| 65 | + subject uuid NOT NULL REFERENCES subject(id) ON DELETE NO ACTION, | ||
| 66 | + -- Provenance, one column per direction: from_bank = the template this | ||
| 67 | + -- question was inserted from, banked_as = the template most recently | ||
| 68 | + -- minted by saving it into the bank. | ||
| 69 | + from_bank uuid NULL REFERENCES bank_question(id) ON DELETE NO ACTION, | ||
| 70 | + banked_as uuid NULL REFERENCES bank_question(id) ON DELETE NO ACTION | ||
| 71 | +); | ||
| 72 | + | ||
| 73 | +CREATE INDEX exam_question_exam ON exam_question (exam); | ||
| 74 | +CREATE INDEX exam_question_subject ON exam_question (subject); | ||
| 75 | + | ||
| 76 | +CREATE TABLE bank_question_image ( | ||
| 77 | + bank_question uuid NOT NULL REFERENCES bank_question(id) ON DELETE NO ACTION, | ||
| 78 | + -- NULL = the question's own illustration; otherwise the choice's id. A | ||
| 79 | + -- (question, slot) pair holds at most one picture, and a question holds | ||
| 80 | + -- at most one illustration — NULLS NOT DISTINCT is what makes the NULL | ||
| 81 | + -- case count as taken. | ||
| 82 | + slot TEXT NULL, | ||
| 83 | + file TEXT NOT NULL, | ||
| 84 | + content_type TEXT NOT NULL, | ||
| 85 | + size BIGINT NOT NULL, | ||
| 86 | + CONSTRAINT bank_question_image_question_slot UNIQUE NULLS NOT DISTINCT (bank_question, slot) | ||
| 87 | +); | ||
| 88 | + | ||
| 89 | +CREATE TABLE question_image ( | ||
| 90 | + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, | ||
| 91 | + question uuid NOT NULL REFERENCES exam_question(id) ON DELETE NO ACTION, | ||
| 92 | + -- NULL = the question's own illustration; otherwise the choice's id. A | ||
| 93 | + -- (question, slot) pair holds at most one picture, and a question holds | ||
| 94 | + -- at most one illustration — NULLS NOT DISTINCT is what makes the NULL | ||
| 95 | + -- case count as taken. | ||
| 96 | + slot TEXT NULL, | ||
| 97 | + file TEXT NOT NULL, | ||
| 98 | + content_type TEXT NOT NULL, | ||
| 99 | + size BIGINT NOT NULL, | ||
| 100 | + CONSTRAINT question_image_question_slot UNIQUE NULLS NOT DISTINCT (question, slot) | ||
| 101 | +); | ||
| 102 | + | ||
| 103 | +CREATE INDEX question_image_exam ON question_image (exam); | ||
| 104 | +CREATE INDEX question_image_question ON question_image (question); | ||
| 105 | + | ||
| 106 | +CREATE TABLE exam_attempt ( | ||
| 107 | + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, | ||
| 108 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 109 | + seq BIGINT NOT NULL DEFAULT 1, | ||
| 110 | + started_at BIGINT NOT NULL, | ||
| 111 | + finished_at BIGINT NULL, | ||
| 112 | + left_at BIGINT NULL, | ||
| 113 | + CONSTRAINT exam_attempt_exam_user_seq PRIMARY KEY (exam, app_user, seq) | ||
| 114 | +); | ||
| 115 | + | ||
| 116 | +CREATE INDEX exam_attempt_exam ON exam_attempt (exam); | ||
| 117 | + | ||
| 118 | +CREATE TABLE exam_answer ( | ||
| 119 | + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, | ||
| 120 | + question uuid NOT NULL REFERENCES exam_question(id) ON DELETE NO ACTION, | ||
| 121 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 122 | + selected TEXT NULL, | ||
| 123 | + text TEXT NULL, | ||
| 124 | + updated_at BIGINT NOT NULL, | ||
| 125 | + seq BIGINT NOT NULL DEFAULT 1, | ||
| 126 | + CONSTRAINT exam_answer_question_user_seq PRIMARY KEY (question, app_user, seq) | ||
| 127 | +); | ||
| 128 | + | ||
| 129 | +CREATE INDEX exam_answer_exam_user ON exam_answer (exam, app_user); | ||
| 130 | +CREATE INDEX exam_answer_exam ON exam_answer (exam); | ||
| 131 | + | ||
| 132 | +CREATE TABLE answer_image ( | ||
| 133 | + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, | ||
| 134 | + question uuid NOT NULL REFERENCES exam_question(id) ON DELETE NO ACTION, | ||
| 135 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 136 | + file TEXT NOT NULL, | ||
| 137 | + content_type TEXT NOT NULL, | ||
| 138 | + size BIGINT NOT NULL, | ||
| 139 | + seq BIGINT NOT NULL DEFAULT 1, | ||
| 140 | + CONSTRAINT answer_image_question_user_seq PRIMARY KEY (question, app_user, seq) | ||
| 141 | +); | ||
| 142 | + | ||
| 143 | +CREATE INDEX answer_image_exam ON answer_image (exam); | ||
| 144 | +CREATE INDEX answer_image_user ON answer_image (app_user); | ||
| 145 | + | ||
| 146 | +CREATE TABLE exam_result ( | ||
| 147 | + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, | ||
| 148 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 149 | + mark BIGINT NOT NULL, | ||
| 150 | + graded_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 151 | + seq BIGINT NOT NULL DEFAULT 1, | ||
| 152 | + CONSTRAINT exam_result_exam_user_seq PRIMARY KEY (exam, app_user, seq) | ||
| 153 | +); | ||
| 154 | + | ||
| 155 | +CREATE TABLE pool_question ( | ||
| 156 | + id uuid PRIMARY KEY, | ||
| 157 | + asker uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 158 | + title TEXT NOT NULL, | ||
| 159 | + body TEXT NOT NULL, | ||
| 160 | + status TEXT NOT NULL DEFAULT 'pending', | ||
| 161 | + asked_at BIGINT NOT NULL, | ||
| 162 | + approved_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 163 | + image_file TEXT NULL, | ||
| 164 | + image_content_type TEXT NULL, | ||
| 165 | + image_size BIGINT NULL | ||
| 166 | +); | ||
| 167 | + | ||
| 168 | +CREATE INDEX pool_question_status ON pool_question (status); | ||
| 169 | +CREATE INDEX pool_question_asker ON pool_question (asker); | ||
| 170 | + | ||
| 171 | +CREATE TABLE solution ( | ||
| 172 | + id uuid PRIMARY KEY, | ||
| 173 | + question uuid NOT NULL REFERENCES pool_question(id) ON DELETE NO ACTION, | ||
| 174 | + author uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 175 | + body TEXT NOT NULL, | ||
| 176 | + offered_at BIGINT NOT NULL, | ||
| 177 | + image_file TEXT NULL, | ||
| 178 | + image_content_type TEXT NULL, | ||
| 179 | + image_size BIGINT NULL | ||
| 180 | +); | ||
| 181 | + | ||
| 182 | +CREATE INDEX solution_question ON solution (question); | ||
| 183 | + | ||
| 184 | +CREATE TABLE homework ( | ||
| 185 | + id uuid PRIMARY KEY, | ||
| 186 | + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, | ||
| 187 | + subject uuid NOT NULL REFERENCES subject(id) ON DELETE NO ACTION, | ||
| 188 | + title TEXT NOT NULL, | ||
| 189 | + description TEXT NULL, | ||
| 190 | + due_at BIGINT NOT NULL, | ||
| 191 | + -- NULL/empty means the whole course. | ||
| 192 | + assigned uuid[] NOT NULL DEFAULT '{}', | ||
| 193 | + created_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 194 | + created_at BIGINT NOT NULL | ||
| 195 | +); | ||
| 196 | + | ||
| 197 | +CREATE INDEX homework_course ON homework (course); | ||
| 198 | + | ||
| 199 | +CREATE TABLE homework_result ( | ||
| 200 | + id uuid PRIMARY KEY, | ||
| 201 | + homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION, | ||
| 202 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 203 | + status TEXT NOT NULL, | ||
| 204 | + mark BIGINT NULL, | ||
| 205 | + graded_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 206 | + created_at BIGINT NOT NULL, | ||
| 207 | + -- The deterministic {homework}_{user} pair: one grade per pair by | ||
| 208 | + -- construction (grading is one atomic upsert against this constraint). | ||
| 209 | + CONSTRAINT homework_result_homework_user UNIQUE (homework, app_user) | ||
| 210 | +); | ||
| 211 | + | ||
| 212 | +CREATE INDEX homework_result_homework ON homework_result (homework); | ||
| 213 | + | ||
| 214 | +CREATE TABLE homework_submission ( | ||
| 215 | + id uuid PRIMARY KEY, | ||
| 216 | + homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION, | ||
| 217 | + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 218 | + text TEXT NULL, | ||
| 219 | + submitted_at BIGINT NOT NULL, | ||
| 220 | + updated_at BIGINT NOT NULL, | ||
| 221 | + file_count BIGINT NOT NULL DEFAULT 0, | ||
| 222 | + -- The on-time verdict credited at the first hand-in, never re-judged. | ||
| 223 | + counted_on_time BOOLEAN NULL, | ||
| 224 | + -- The grade that froze this submission; NULL while it is still open. | ||
| 225 | + graded_by_result uuid NULL REFERENCES homework_result(id) ON DELETE NO ACTION, | ||
| 226 | + -- Same deterministic pair as homework_result: one submission per | ||
| 227 | + -- (homework, user) by construction. | ||
| 228 | + CONSTRAINT homework_submission_homework_user UNIQUE (homework, app_user) | ||
| 229 | +); | ||
| 230 | + | ||
| 231 | +CREATE INDEX homework_submission_homework ON homework_submission (homework); | ||
| 232 | + | ||
| 233 | +CREATE TABLE homework_file ( | ||
| 234 | + id uuid PRIMARY KEY, | ||
| 235 | + submission uuid NOT NULL REFERENCES homework_submission(id) ON DELETE NO ACTION, | ||
| 236 | + name TEXT NOT NULL, | ||
| 237 | + content_type TEXT NOT NULL, | ||
| 238 | + size BIGINT NOT NULL, | ||
| 239 | + created_at BIGINT NOT NULL | ||
| 240 | +); | ||
| 241 | + | ||
| 242 | +CREATE INDEX homework_file_submission ON homework_file (submission); | ||
migrations/school/20260912000004_food_appointments_fees.sqladded+205 -0
| @@ -0,0 +1,205 @@ | |||
| 1 | +-- School-database schema, part 4: appointments, food program, fees, payments | ||
| 2 | +-- (Postgres). | ||
| 3 | +-- | ||
| 4 | +-- DISJOINTNESS INVARIANT: the tables in migrations/school/*.sql and the ones | ||
| 5 | +-- in migrations/control/*.sql together form ONE union schema, applied to a | ||
| 6 | +-- single prepare database by scripts/prepare_db.sh for sqlx's compile-time | ||
| 7 | +-- query macros. The two sets must never collide on a table name. | ||
| 8 | +-- | ||
| 9 | +-- Same translation rules as parts 1-3. New DDL with no Surreal source: | ||
| 10 | +-- the btree_gist extension and the appointment_slot EXCLUDE constraint — | ||
| 11 | +-- the publish-overlap guard that replaces the old APPOINTMENT_LOCK publish | ||
| 12 | +-- path (SQLSTATE 23505 maps to the overlap 409 at the call site). | ||
| 13 | +-- | ||
| 14 | +-- `menu` carries an app-minted uuid id plus the natural UNIQUE (date, slot): | ||
| 15 | +-- its children (menu_dish, meal_booking, meal_attendance) reference it by a | ||
| 16 | +-- single column, which a composite (date, slot) PK could not serve. The | ||
| 17 | +-- publish upsert keys on the natural pair exactly as before. | ||
| 18 | + | ||
| 19 | +CREATE EXTENSION IF NOT EXISTS btree_gist; | ||
| 20 | + | ||
| 21 | +CREATE TABLE appointment_slot ( | ||
| 22 | + id uuid PRIMARY KEY, | ||
| 23 | + teacher uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 24 | + starts_at BIGINT NOT NULL, | ||
| 25 | + ends_at BIGINT NOT NULL, | ||
| 26 | + occupied BIGINT NOT NULL DEFAULT 0, | ||
| 27 | + note TEXT NULL, | ||
| 28 | + -- Groups the occurrences a weekly repeat expanded into; NULL on a | ||
| 29 | + -- one-off slot. | ||
| 30 | + series TEXT NULL, | ||
| 31 | + created_at BIGINT NOT NULL, | ||
| 32 | + -- Derived window for the exclusion constraint below. | ||
| 33 | + span int8range GENERATED ALWAYS AS (int8range(starts_at, ends_at)) STORED, | ||
| 34 | + -- A teacher cannot publish two overlapping windows: the old | ||
| 35 | + -- APPOINTMENT_LOCK publish path, now a database guarantee (23505). | ||
| 36 | + CONSTRAINT appointment_slot_teacher_span EXCLUDE USING gist (teacher WITH =, span WITH &&) | ||
| 37 | +); | ||
| 38 | + | ||
| 39 | +CREATE INDEX appointment_slot_teacher_starts ON appointment_slot (teacher, starts_at); | ||
| 40 | +CREATE INDEX appointment_slot_series ON appointment_slot (series); | ||
| 41 | + | ||
| 42 | +CREATE TABLE appointment ( | ||
| 43 | + id uuid PRIMARY KEY, | ||
| 44 | + slot uuid NOT NULL REFERENCES appointment_slot(id) ON DELETE NO ACTION, | ||
| 45 | + requester uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 46 | + status TEXT NOT NULL DEFAULT 'pending' | ||
| 47 | + CHECK (status IN ('pending', 'approved', 'rejected', 'cancelled')), | ||
| 48 | + reason TEXT NOT NULL, | ||
| 49 | + -- A teacher's counter-proposal on the same row, until the requester | ||
| 50 | + -- accepts. | ||
| 51 | + proposed_starts_at BIGINT NULL, | ||
| 52 | + proposed_ends_at BIGINT NULL, | ||
| 53 | + proposed_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 54 | + decided_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 55 | + cancelled_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 56 | + cancel_reason TEXT NULL, | ||
| 57 | + reject_reason TEXT NULL, | ||
| 58 | + created_at BIGINT NOT NULL | ||
| 59 | +); | ||
| 60 | + | ||
| 61 | +CREATE INDEX appointment_slot_ref ON appointment (slot); | ||
| 62 | +CREATE INDEX appointment_requester ON appointment (requester); | ||
| 63 | +CREATE INDEX appointment_status ON appointment (status); | ||
| 64 | + | ||
| 65 | +-- A published menu per day+slot. `date` is a calendar day as YYYY-MM-DD | ||
| 66 | +-- text (an equality key, not a timestamp); `slot` is snapshotted text, so | ||
| 67 | +-- retiring a slot in settings never rewrites a past menu. | ||
| 68 | +CREATE TABLE menu ( | ||
| 69 | + -- The {date}_{slot} derived key — it IS the URL segment — with the two | ||
| 70 | + -- components kept as their own columns (the unique pair keeps the old | ||
| 71 | + -- index name, which is what surfaces in SQLSTATE 23505). | ||
| 72 | + id TEXT PRIMARY KEY, | ||
| 73 | + date TEXT NOT NULL, | ||
| 74 | + slot TEXT NOT NULL, | ||
| 75 | + capacity BIGINT NULL, | ||
| 76 | + seats_booked BIGINT NOT NULL DEFAULT 0, | ||
| 77 | + -- The menu's revision: a booking claims its seat only while the menu | ||
| 78 | + -- still stands at the revision it read the price at. A stamp, not a | ||
| 79 | + -- counter: NULL reads as revision zero at the Rust boundary. | ||
| 80 | + version BIGINT NULL, | ||
| 81 | + created_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 82 | + created_at BIGINT NOT NULL, | ||
| 83 | + CONSTRAINT menu_date_slot UNIQUE (date, slot) | ||
| 84 | +); | ||
| 85 | + | ||
| 86 | +CREATE TABLE menu_dish ( | ||
| 87 | + id uuid PRIMARY KEY, | ||
| 88 | + menu TEXT NOT NULL REFERENCES menu(id) ON DELETE NO ACTION, | ||
| 89 | + name TEXT NOT NULL, | ||
| 90 | + description TEXT NULL, | ||
| 91 | + -- Money is minor units (kuruş) as an integer, everywhere. Never decimal. | ||
| 92 | + price_minor BIGINT NOT NULL, | ||
| 93 | + tags TEXT[] NOT NULL DEFAULT '{}', | ||
| 94 | + created_at BIGINT NOT NULL | ||
| 95 | +); | ||
| 96 | + | ||
| 97 | +CREATE INDEX menu_dish_menu ON menu_dish (menu); | ||
| 98 | + | ||
| 99 | +CREATE TABLE dietary_profile ( | ||
| 100 | + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 101 | + tags TEXT[] NOT NULL DEFAULT '{}', | ||
| 102 | + note TEXT NULL, | ||
| 103 | + updated_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 104 | + updated_at BIGINT NOT NULL, | ||
| 105 | + CONSTRAINT dietary_profile_student PRIMARY KEY (student) | ||
| 106 | +); | ||
| 107 | + | ||
| 108 | +-- A cancel flips `status` and stamps `cancelled_at`; the row stays so the | ||
| 109 | +-- freed seat is still auditable against the ledger line it charged. | ||
| 110 | +CREATE TABLE meal_booking ( | ||
| 111 | + menu TEXT NOT NULL REFERENCES menu(id) ON DELETE NO ACTION, | ||
| 112 | + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 113 | + booked_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 114 | + status TEXT NOT NULL DEFAULT 'booked' | ||
| 115 | + CHECK (status IN ('booked', 'cancelled')), | ||
| 116 | + -- How many times this seat has been taken, and what it cost when the | ||
| 117 | + -- current attempt took it (NULL = the menu was free then). | ||
| 118 | + attempt BIGINT NOT NULL DEFAULT 1, | ||
| 119 | + price_minor BIGINT NULL, | ||
| 120 | + cancelled_at BIGINT NULL, | ||
| 121 | + created_at BIGINT NOT NULL, | ||
| 122 | + -- One row per (menu, student); a re-booking re-uses the row and bumps | ||
| 123 | + -- `attempt`. | ||
| 124 | + CONSTRAINT meal_booking_menu_student PRIMARY KEY (menu, student) | ||
| 125 | +); | ||
| 126 | + | ||
| 127 | +CREATE INDEX meal_booking_menu ON meal_booking (menu); | ||
| 128 | +CREATE INDEX meal_booking_student ON meal_booking (student); | ||
| 129 | + | ||
| 130 | +CREATE TABLE meal_attendance ( | ||
| 131 | + menu TEXT NOT NULL REFERENCES menu(id) ON DELETE NO ACTION, | ||
| 132 | + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 133 | + status TEXT NOT NULL, | ||
| 134 | + marked_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 135 | + marked_at BIGINT NOT NULL, | ||
| 136 | + CONSTRAINT meal_attendance_menu_student PRIMARY KEY (menu, student) | ||
| 137 | +); | ||
| 138 | + | ||
| 139 | +-- APPEND-ONLY by design: a mistake is corrected with an opposing reversal | ||
| 140 | +-- line, never by editing or deleting one. `source` is deliberately FK-less — | ||
| 141 | +-- a charge points at the booking that caused it, a reversal at the line it | ||
| 142 | +-- undoes (polymorphic, so no single REFERENCES target exists). | ||
| 143 | +CREATE TABLE meal_ledger ( | ||
| 144 | + -- The {menu}_{student}_c{attempt} derived key: billing idempotence by | ||
| 145 | + -- identity, not by scanning for an outstanding charge. | ||
| 146 | + id TEXT PRIMARY KEY, | ||
| 147 | + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 148 | + kind TEXT NOT NULL CHECK (kind IN ('charge', 'credit', 'reversal')), | ||
| 149 | + amount_minor BIGINT NOT NULL, | ||
| 150 | + -- Polymorphic pointer (booking row, or the line it undoes) — TEXT | ||
| 151 | + -- because it can name a uuid-keyed or a derived-key row; no FK. | ||
| 152 | + source TEXT NULL, | ||
| 153 | + method TEXT NULL, | ||
| 154 | + note TEXT NULL, | ||
| 155 | + recorded_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 156 | + created_at BIGINT NOT NULL | ||
| 157 | +); | ||
| 158 | + | ||
| 159 | +CREATE INDEX meal_ledger_student ON meal_ledger (student); | ||
| 160 | + | ||
| 161 | +-- A school fee plan: a name and its installments (embedded JSONB — a charge | ||
| 162 | +-- line copies the amount it was assigned at, so child rows would buy | ||
| 163 | +-- nothing). | ||
| 164 | +CREATE TABLE fee_plan ( | ||
| 165 | + id uuid PRIMARY KEY, | ||
| 166 | + name TEXT NOT NULL, | ||
| 167 | + installments JSONB NOT NULL, | ||
| 168 | + created_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 169 | + created_at BIGINT NOT NULL, | ||
| 170 | + assignment_count BIGINT NOT NULL DEFAULT 0 | ||
| 171 | +); | ||
| 172 | + | ||
| 173 | +-- One plan on one student; the deterministic {plan}_{student} pair. | ||
| 174 | +CREATE TABLE fee_plan_assignment ( | ||
| 175 | + plan uuid NOT NULL REFERENCES fee_plan(id) ON DELETE NO ACTION, | ||
| 176 | + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 177 | + assigned_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 178 | + created_at BIGINT NOT NULL, | ||
| 179 | + CONSTRAINT fee_plan_assignment_plan PRIMARY KEY (plan, student) | ||
| 180 | +); | ||
| 181 | + | ||
| 182 | +CREATE INDEX fee_plan_assignment_student ON fee_plan_assignment (student); | ||
| 183 | + | ||
| 184 | +-- School fees, APPEND-ONLY exactly like meal_ledger. `source` is FK-less for | ||
| 185 | +-- the same polymorphic reason (charge -> assignment, credit -> charge, | ||
| 186 | +-- refund -> credit, reversal -> line); `due_at` is set on charges alone. | ||
| 187 | +CREATE TABLE payment_ledger ( | ||
| 188 | + -- The {plan}_{student}_c{n} / {line}_r / {target}_k_{request_key} | ||
| 189 | + -- derived key: append-only rows addressed by identity. | ||
| 190 | + id TEXT PRIMARY KEY, | ||
| 191 | + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 192 | + kind TEXT NOT NULL CHECK (kind IN ('charge', 'credit', 'reversal', 'refund')), | ||
| 193 | + amount_minor BIGINT NOT NULL, | ||
| 194 | + -- Polymorphic pointer (assignment, charge, credit, or line it undoes); | ||
| 195 | + -- TEXT for the same reason as meal_ledger.source. No FK. | ||
| 196 | + source TEXT NULL, | ||
| 197 | + due_at BIGINT NULL, | ||
| 198 | + method TEXT NULL, | ||
| 199 | + note TEXT NULL, | ||
| 200 | + recorded_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | ||
| 201 | + created_at BIGINT NOT NULL | ||
| 202 | +); | ||
| 203 | + | ||
| 204 | +CREATE INDEX payment_ledger_student ON payment_ledger (student); | ||
| 205 | +CREATE INDEX payment_ledger_source ON payment_ledger (source); | ||
scripts/prepare_db.shadded+44 -0
| @@ -0,0 +1,44 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# Refresh the sqlx "prepare" database: the ONE database whose schema is the | ||
| 3 | +# union of migrations/control/*.sql + migrations/school/*.sql, against which | ||
| 4 | +# sqlx's compile-time query macros check every query (`cargo sqlx prepare`, | ||
| 5 | +# and plain `cargo check` with DATABASE_URL set — see .env.example). | ||
| 6 | +# | ||
| 7 | +# DISJOINTNESS INVARIANT: control tables (school, builder, builder_session, | ||
| 8 | +# rate_limit) and school tables must never collide on a name — the union is | ||
| 9 | +# applied to this single database. The loop below fails loudly (psql | ||
| 10 | +# ON_ERROR_STOP=1) if a name ever collides. | ||
| 11 | +# | ||
| 12 | +# Raw apply, on purpose: no `sqlx migrate run`, so no `_sqlx_migrations` | ||
| 13 | +# tracking rows exist and the control and school file sets never share a | ||
| 14 | +# tracking table. The database is dropped and recreated on every run, so the | ||
| 15 | +# result is deterministic. | ||
| 16 | +# | ||
| 17 | +# Requires the compose Postgres: `podman compose up -d postgres`. | ||
| 18 | +set -euo pipefail | ||
| 19 | + | ||
| 20 | +CONTAINER="${HEZARFEN_PG_CONTAINER:-hezarfen-postgres}" | ||
| 21 | +PREPARE_DB="${HEZARFEN_PREPARE_DB:-hezarfen_sqlx_prepare}" | ||
| 22 | +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" | ||
| 23 | + | ||
| 24 | +psql() { | ||
| 25 | + podman exec -i "$CONTAINER" psql -U hezarfen -v ON_ERROR_STOP=1 "$@" | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +echo "== refreshing $PREPARE_DB on $CONTAINER" | ||
| 29 | +psql -d postgres -q <<SQL | ||
| 30 | +DROP DATABASE IF EXISTS $PREPARE_DB; | ||
| 31 | +CREATE DATABASE $PREPARE_DB; | ||
| 32 | +SQL | ||
| 33 | + | ||
| 34 | +applied=0 | ||
| 35 | +for dir in control school; do | ||
| 36 | + for file in "$HERE"/migrations/"$dir"/*.sql; do | ||
| 37 | + echo "== applying migrations/$dir/$(basename "$file")" | ||
| 38 | + psql -d "$PREPARE_DB" -q -f - < "$file" | ||
| 39 | + applied=$((applied + 1)) | ||
| 40 | + done | ||
| 41 | +done | ||
| 42 | + | ||
| 43 | +echo "== applied $applied migration files; tables now in $PREPARE_DB:" | ||
| 44 | +psql -d "$PREPARE_DB" -c '\dt' | ||
src/ai/server.rsmodified+9 -31
| @@ -12,7 +12,6 @@ use opentelemetry::KeyValue; | |||
| 12 | use serde_json::Value; | 12 | use serde_json::Value; |
| 13 | use tower::ServiceExt; | 13 | use tower::ServiceExt; |
| 14 | use tracing::Instrument; | 14 | use tracing::Instrument; |
| 15 | -use ulid::Ulid; | ||
| 16 | 15 | ||
| 17 | use crate::ai::error::AiError; | 16 | use crate::ai::error::AiError; |
| 18 | use crate::ai::protocol::{ | 17 | use crate::ai::protocol::{ |
| @@ -28,10 +27,10 @@ use crate::constant::{ | |||
| 28 | use crate::database::Database; | 27 | use crate::database::Database; |
| 29 | 28 | ||
| 30 | use crate::domain::course_note_file::CourseNoteFileId; | 29 | use crate::domain::course_note_file::CourseNoteFileId; |
| 30 | +use crate::domain::monotonic_id::next_uuid; | ||
| 31 | use crate::domain::user::{User, UserId}; | 31 | use crate::domain::user::{User, UserId}; |
| 32 | use crate::error::AppError; | 32 | use crate::error::AppError; |
| 33 | use crate::module::Module; | 33 | use crate::module::Module; |
| 34 | -use crate::state::DbHealth; | ||
| 35 | use crate::telemetry::Metrics; | 34 | use crate::telemetry::Metrics; |
| 36 | use crate::tenant::{Slug, Tenants}; | 35 | use crate::tenant::{Slug, Tenants}; |
| 37 | use crate::web::blob_path; | 36 | use crate::web::blob_path; |
| @@ -53,16 +52,14 @@ pub struct BridgeConfig { | |||
| 53 | pub request_timeout: Duration, | 52 | pub request_timeout: Duration, |
| 54 | } | 53 | } |
| 55 | 54 | ||
| 56 | -/// What an api read needs to be answered: the router to dispatch into, the | 55 | +/// What an api read needs to be answered: the router to dispatch into and |
| 57 | -/// registry every school is resolved through, and the liveness flag that | 56 | +/// the registry every school is resolved through. |
| 58 | -/// stands in for the HTTP db guard this path bypasses. | ||
| 59 | /// | 57 | /// |
| 60 | /// Deployment-wide, not per-school: `hab/2` frames name their own school, so | 58 | /// Deployment-wide, not per-school: `hab/2` frames name their own school, so |
| 61 | /// one bridge (and one AI fleet) serves every school here. | 59 | /// one bridge (and one AI fleet) serves every school here. |
| 62 | struct ApiHandle { | 60 | struct ApiHandle { |
| 63 | router: axum::Router, | 61 | router: axum::Router, |
| 64 | tenants: Tenants, | 62 | tenants: Tenants, |
| 65 | - db_up: DbHealth, | ||
| 66 | /// Where uploaded blobs live — the deployment root; a school's own | 63 | /// Where uploaded blobs live — the deployment root; a school's own |
| 67 | /// directory is [`school_files_path`] of it. | 64 | /// directory is [`school_files_path`] of it. |
| 68 | files_path: std::path::PathBuf, | 65 | files_path: std::path::PathBuf, |
| @@ -260,7 +257,7 @@ impl AiBridge { | |||
| 260 | // function returns by any path, so an abandoned request frees the | 257 | // function returns by any path, so an abandoned request frees the |
| 261 | // worker's slot rather than leaking it. | 258 | // worker's slot rather than leaking it. |
| 262 | let lease = self.inner.registry.pick(capability)?; | 259 | let lease = self.inner.registry.pick(capability)?; |
| 263 | - let id = Ulid::generate().to_string(); | 260 | + let id = next_uuid().to_string(); |
| 264 | let deadline_ms = timeout.as_millis().min(u64::MAX as u128) as u64; | 261 | let deadline_ms = timeout.as_millis().min(u64::MAX as u128) as u64; |
| 265 | let request = Request { | 262 | let request = Request { |
| 266 | id: id.clone(), | 263 | id: id.clone(), |
| @@ -357,7 +354,6 @@ impl AiBridge { | |||
| 357 | &self, | 354 | &self, |
| 358 | router: axum::Router, | 355 | router: axum::Router, |
| 359 | tenants: Tenants, | 356 | tenants: Tenants, |
| 360 | - db_up: DbHealth, | ||
| 361 | files_path: std::path::PathBuf, | 357 | files_path: std::path::PathBuf, |
| 362 | metrics: Metrics, | 358 | metrics: Metrics, |
| 363 | ) { | 359 | ) { |
| @@ -370,7 +366,6 @@ impl AiBridge { | |||
| 370 | .set(ApiHandle { | 366 | .set(ApiHandle { |
| 371 | router, | 367 | router, |
| 372 | tenants, | 368 | tenants, |
| 373 | - db_up, | ||
| 374 | files_path, | 369 | files_path, |
| 375 | }) | 370 | }) |
| 376 | .is_err() | 371 | .is_err() |
| @@ -601,12 +596,6 @@ async fn open_blob( | |||
| 601 | "unavailable", | 596 | "unavailable", |
| 602 | "the api is not serving yet — retry".to_string(), | 597 | "the api is not serving yet — retry".to_string(), |
| 603 | ))?; | 598 | ))?; |
| 604 | - if !api.db_up.is_up() { | ||
| 605 | - return Err(( | ||
| 606 | - "unavailable", | ||
| 607 | - "the database socket is down — retry".to_string(), | ||
| 608 | - )); | ||
| 609 | - } | ||
| 610 | let tenant = api.school(&request.school).await?; | 599 | let tenant = api.school(&request.school).await?; |
| 611 | let (slug, db) = (tenant.slug, tenant.db); | 600 | let (slug, db) = (tenant.slug, tenant.db); |
| 612 | // This stream bypasses the router, so it also bypasses the route_layer the | 601 | // This stream bypasses the router, so it also bypasses the route_layer the |
| @@ -754,10 +743,10 @@ async fn read_api( | |||
| 754 | dispatch_api(api, inner.metrics(), request).await | 743 | dispatch_api(api, inner.metrics(), request).await |
| 755 | } | 744 | } |
| 756 | 745 | ||
| 757 | -/// The half of [`read_api`] that needs only the armed handle: liveness, | 746 | +/// The half of [`read_api`] that needs only the armed handle: principal, |
| 758 | -/// principal, dispatch, and framing the router's answer. Split out from the | 747 | +/// dispatch, and framing the router's answer. Split out from the listener so |
| 759 | -/// listener so the refusal codes it owns can be exercised without a QUIC | 748 | +/// the refusal codes it owns can be exercised without a QUIC endpoint (see |
| 760 | -/// endpoint (see this module's tests). | 749 | +/// this module's tests). |
| 761 | async fn dispatch_api( | 750 | async fn dispatch_api( |
| 762 | api: &ApiHandle, | 751 | api: &ApiHandle, |
| 763 | metrics: &Metrics, | 752 | metrics: &Metrics, |
| @@ -772,16 +761,6 @@ async fn dispatch_api( | |||
| 772 | .. | 761 | .. |
| 773 | } = request; | 762 | } = request; |
| 774 | 763 | ||
| 775 | - // The outer db guard is one of the layers this path deliberately skips, so | ||
| 776 | - // the same liveness check happens here instead: a query issued against a | ||
| 777 | - // dead socket hangs rather than failing (see [`DbHealth`]). | ||
| 778 | - if !api.db_up.is_up() { | ||
| 779 | - return Err(( | ||
| 780 | - "unavailable", | ||
| 781 | - "the database socket is down — retry".to_string(), | ||
| 782 | - )); | ||
| 783 | - } | ||
| 784 | - | ||
| 785 | // The school comes off the frame, so this is where a service naming a | 764 | // The school comes off the frame, so this is where a service naming a |
| 786 | // stranger's slug (or a suspended school's) is stopped — before a row of | 765 | // stranger's slug (or a suspended school's) is stopped — before a row of |
| 787 | // anyone's data is read. | 766 | // anyone's data is read. |
| @@ -995,7 +974,7 @@ async fn register( | |||
| 995 | return Err(()); | 974 | return Err(()); |
| 996 | } | 975 | } |
| 997 | 976 | ||
| 998 | - let worker_id = Ulid::generate().to_string(); | 977 | + let worker_id = next_uuid().to_string(); |
| 999 | let max_concurrent = clamp_concurrency(hello.max_concurrent); | 978 | let max_concurrent = clamp_concurrency(hello.max_concurrent); |
| 1000 | let greeting = Greeting::Welcome { | 979 | let greeting = Greeting::Welcome { |
| 1001 | worker_id: worker_id.clone(), | 980 | worker_id: worker_id.clone(), |
| @@ -1101,7 +1080,6 @@ mod tests { | |||
| 1101 | tenants: crate::database::init_mem_tenants() | 1080 | tenants: crate::database::init_mem_tenants() |
| 1102 | .await | 1081 | .await |
| 1103 | .expect("in-memory deployment"), | 1082 | .expect("in-memory deployment"), |
| 1104 | - db_up: Default::default(), | ||
| 1105 | files_path: std::env::temp_dir(), | 1083 | files_path: std::env::temp_dir(), |
| 1106 | } | 1084 | } |
| 1107 | } | 1085 | } |
src/config.rsmodified+7 -15
| @@ -12,16 +12,11 @@ use crate::telemetry::{LogFormat, TelemetryConfig, TelemetryError}; | |||
| 12 | pub struct Config { | 12 | pub struct Config { |
| 13 | pub host: String, | 13 | pub host: String, |
| 14 | pub port: u16, | 14 | pub port: u16, |
| 15 | - /// SurrealDB server endpoint (`DB_URL`), e.g. `ws://127.0.0.1:8000`. | 15 | + /// PostgreSQL connection string (`DATABASE_URL`), e.g. |
| 16 | - pub db_url: String, | 16 | + /// `postgres://hezarfen:hezarfen@127.0.0.1:5432/hezarfen_control`. Also |
| 17 | - /// Root credentials for the SurrealDB server (`DB_USER` / `DB_PASS`). | 17 | + /// read by sqlx's compile-time query macros, which prepare against the |
| 18 | - pub db_user: String, | 18 | + /// union-schema prepare database (see `scripts/prepare_db.sh`). |
| 19 | - pub db_pass: String, | 19 | + pub database_url: String, |
| 20 | - pub db_ns: String, | ||
| 21 | - /// The **control** database inside `db_ns` (`DB_DATABASE`): the school | ||
| 22 | - /// registry and the builder accounts. Every school gets a database of its | ||
| 23 | - /// own, named by its slug. | ||
| 24 | - pub db_name: String, | ||
| 25 | /// Directory for uploaded note-file blobs (`FILES_PATH`). | 20 | /// Directory for uploaded note-file blobs (`FILES_PATH`). |
| 26 | pub files_path: String, | 21 | pub files_path: String, |
| 27 | /// Add the `Secure` attribute to the session cookie (HTTPS-only). Off by | 22 | /// Add the `Secure` attribute to the session cookie (HTTPS-only). Off by |
| @@ -64,11 +59,8 @@ impl Config { | |||
| 64 | Self { | 59 | Self { |
| 65 | host: env::var("HOST").unwrap_or_else(|_| "127.0.0.1".into()), | 60 | host: env::var("HOST").unwrap_or_else(|_| "127.0.0.1".into()), |
| 66 | port: parse_port(env::var("PORT").ok()), | 61 | port: parse_port(env::var("PORT").ok()), |
| 67 | - db_url: env::var("DB_URL").unwrap_or_else(|_| "ws://127.0.0.1:8000".into()), | 62 | + database_url: env::var("DATABASE_URL") |
| 68 | - db_user: env::var("DB_USER").unwrap_or_else(|_| "root".into()), | 63 | + .unwrap_or_else(|_| "postgres://hezarfen:hezarfen@127.0.0.1:5432/hezarfen_control".into()), |
| 69 | - db_pass: env::var("DB_PASS").unwrap_or_else(|_| "root".into()), | ||
| 70 | - db_ns: env::var("DB_NAMESPACE").unwrap_or_else(|_| "hezarfen".into()), | ||
| 71 | - db_name: env::var("DB_DATABASE").unwrap_or_else(|_| "control".into()), | ||
| 72 | files_path: env::var("FILES_PATH").unwrap_or_else(|_| "./data/files".into()), | 64 | files_path: env::var("FILES_PATH").unwrap_or_else(|_| "./data/files".into()), |
| 73 | cookie_secure: parse_flag(env::var("COOKIE_SECURE").ok()), | 65 | cookie_secure: parse_flag(env::var("COOKIE_SECURE").ok()), |
| 74 | rate_limit: RateLimitConfig { | 66 | rate_limit: RateLimitConfig { |
src/database.rsmodified+338 -1256
| @@ -1,220 +1,364 @@ | |||
| 1 | -//! SurrealDB connection (WebSocket to a server; in-memory for tests) + schema. | 1 | +//! PostgreSQL connections (sqlx) + the two migration sets + the |
| 2 | - | 2 | +//! guarded-transaction retry loop. |
| 3 | -use surrealdb::Surreal; | 3 | +//! |
| 4 | -use surrealdb::engine::any::Any; | 4 | +//! Two sets of migrations live side by side and never share a tracking table: |
| 5 | -use surrealdb::opt::auth::Root; | 5 | +//! `migrations/control` for the control database (schools, builders, the |
| 6 | +//! shared rate-limit window) and `migrations/school` for every school | ||
| 7 | +//! database. They are applied by two separate [`sqlx::migrate::Migrator`]s — | ||
| 8 | +//! the compile-time `migrate!` macro cannot be aimed at two directories, so | ||
| 9 | +//! each is constructed at runtime from its path under `CARGO_MANIFEST_DIR`. | ||
| 10 | +//! Their table names are disjoint by design, which is what lets one prepare | ||
| 11 | +//! database carry the union for the compile-time `query!` checks. | ||
| 12 | + | ||
| 13 | +use std::path::Path; | ||
| 14 | +use std::time::Duration; | ||
| 15 | + | ||
| 16 | +use sqlx::migrate::{MigrateError, Migrator}; | ||
| 17 | +use sqlx::postgres::{PgConnectOptions, PgConnection, PgPoolOptions}; | ||
| 18 | +use sqlx::PgPool; | ||
| 6 | 19 | ||
| 7 | use crate::config::Config; | 20 | use crate::config::Config; |
| 8 | use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS}; | 21 | use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS}; |
| 9 | use crate::domain::timestamp::Timestamp; | 22 | use crate::domain::timestamp::Timestamp; |
| 10 | use crate::domain::user::{Password, Username}; | 23 | use crate::domain::user::{Password, Username}; |
| 11 | use crate::error::AppError; | 24 | use crate::error::AppError; |
| 12 | -use crate::migration_sql::{BACKFILL, CONTROL_MIGRATION_BATCHES, MIGRATION_BATCHES}; | ||
| 13 | use crate::tenant::Tenants; | 25 | use crate::tenant::Tenants; |
| 14 | 26 | ||
| 15 | /// The shared database handle. | 27 | /// The shared database handle. |
| 16 | /// | 28 | /// |
| 17 | -/// `Arc` is load-bearing, not decoration. `Surreal`'s own `Clone` mints a | 29 | +/// `PgPool` is an `Arc` around its internals, so cloning shares the one pool — |
| 18 | -/// fresh server-side session per clone (`Uuid::new_v4()` + a fire-and-forget | 30 | +/// axum cloning the application state per request costs an atomic increment, |
| 19 | -/// `SessionId::Clone` to the router, SDK `lib.rs:340`), and axum clones the | 31 | +/// nothing more. |
| 20 | -/// application state on every request — so a bare `Surreal<Any>` here means a | 32 | +pub type Database = sqlx::PgPool; |
| 21 | -/// new session, and a matching `SessionId::Drop`, for each request served. | 33 | + |
| 22 | -/// Under concurrency those lifecycle events race the queries riding on them: | 34 | +/// Connect to the **control** database, apply the control schema, seed the |
| 23 | -/// sessions disappear ("Session not found"), and a session whose signin has | 35 | +/// builder account and ensure the school-template database. School databases |
| 24 | -/// not been replayed answers "Anonymous access not allowed" / "Specify a | 36 | +/// are brought up separately, one per school, by [`crate::tenant::Tenants`]. |
| 25 | -/// namespace" — the same strings [`crate::error::is_session_replay_error`] | ||
| 26 | -/// treats as a transient reconnect, so the failures masquerade as one. | ||
| 27 | /// | 37 | /// |
| 28 | -/// Cloning the `Arc` shares the single session established at boot instead. | 38 | +/// The dial is retried forever (one-second cadence): the database is normally |
| 29 | -pub type Database = std::sync::Arc<Surreal<Any>>; | 39 | +/// a sibling container booting in parallel, and a process that exits on the |
| 30 | - | 40 | +/// first refusal gets restarted by the runtime, fails again in ~100ms, and |
| 31 | -/// Connect to the **control** database, sign in as root, apply the control | 41 | +/// burns its whole restart budget inside a second — leaving the backend |
| 32 | -/// schema and seed the builder account. School databases are brought up | 42 | +/// permanently down over a startup skew that would have cleared on its own. |
| 33 | -/// separately, one per school, by [`crate::tenant::Tenants`]. | 43 | +/// Only the *connection* is retried. Bad credentials or a broken migration |
| 44 | +/// still fail hard, since no amount of waiting fixes those. | ||
| 34 | pub async fn init(cfg: &Config) -> Result<Tenants, AppError> { | 45 | pub async fn init(cfg: &Config) -> Result<Tenants, AppError> { |
| 35 | // Validated before the connection, not after: half a credential pair is a | 46 | // Validated before the connection, not after: half a credential pair is a |
| 36 | // deployment mistake, and reporting it only after a successful dial buries | 47 | // deployment mistake, and reporting it only after a successful dial buries |
| 37 | // it under an outage that isn't one. | 48 | // it under an outage that isn't one. |
| 38 | let builder = builder_credentials(cfg)?; | 49 | let builder = builder_credentials(cfg)?; |
| 39 | - let db = connect_with_retry(cfg).await; | 50 | + |
| 40 | - db.signin(Root { | 51 | + let (base, control_db) = parse_base(cfg)?; |
| 41 | - username: cfg.db_user.clone(), | 52 | + |
| 42 | - password: cfg.db_pass.clone(), | 53 | + let control = loop { |
| 43 | - }) | 54 | + match boot_control(&base).await { |
| 44 | - .await?; | 55 | + Ok(pool) => break pool, |
| 45 | - db.use_ns(cfg.db_ns.clone()) | 56 | + Err(err) if boot_failure_retryable(&err) => { |
| 46 | - .use_db(cfg.db_name.clone()) | 57 | + tracing::warn!( |
| 47 | - .await?; | 58 | + "database at postgres://{}:{} unreachable ({err}) — retrying in 1s", |
| 48 | - let db = std::sync::Arc::new(db); | 59 | + base.get_host(), |
| 49 | - migrate_control(&db).await?; | 60 | + base.get_port(), |
| 61 | + ); | ||
| 62 | + tokio::time::sleep(Duration::from_secs(1)).await; | ||
| 63 | + } | ||
| 64 | + Err(err) => return Err(err.into()), | ||
| 65 | + } | ||
| 66 | + }; | ||
| 67 | + | ||
| 50 | if let Some((username, password)) = builder { | 68 | if let Some((username, password)) = builder { |
| 51 | - crate::service::builder::ensure(&db, username, password).await?; | 69 | + crate::service::builder::ensure(&control, username, password).await?; |
| 52 | } | 70 | } |
| 53 | - Ok(Tenants::new_remote(db, cfg)) | 71 | + |
| 72 | + // The template every school schema is validated against at boot: created | ||
| 73 | + // outside any transaction (`CREATE DATABASE` cannot run inside one — | ||
| 74 | + // `Pool::execute` runs bare autocommit statements), migrated once, then | ||
| 75 | + // closed. A first boot lost to a concurrent boot of the same deployment | ||
| 76 | + // adopts the winner's template via the duplicate-database swallow. | ||
| 77 | + let template = format!("{control_db}_school_template"); | ||
| 78 | + ensure_template(&control, &base, &template).await?; | ||
| 79 | + | ||
| 80 | + Ok(Tenants::new(control, base, control_db)) | ||
| 54 | } | 81 | } |
| 55 | 82 | ||
| 56 | -/// The `BUILDER_USERNAME` / `BUILDER_PASSWORD` bootstrap pair, if configured. | 83 | +/// Parse `DATABASE_URL` into dial options plus the control database's name — |
| 57 | -/// Both-or-neither: half a pair aborts startup rather than silently running | 84 | +/// the name every school database hangs off (`{control}_school_{slug}`). |
| 58 | -/// without the seed — and without a builder, a fresh deployment has nobody who | 85 | +pub(crate) fn parse_base(cfg: &Config) -> Result<(PgConnectOptions, String), AppError> { |
| 59 | -/// can create the first school. | 86 | + let opts: PgConnectOptions = cfg.database_url.parse().map_err(|err| { |
| 60 | -fn builder_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, AppError> { | 87 | + AppError::Internal(format!("invalid DATABASE_URL ({}): {err}", cfg.database_url)) |
| 61 | - match (&cfg.builder_username, &cfg.builder_password) { | 88 | + })?; |
| 62 | - (Some(username), Some(password)) => Ok(Some(( | 89 | + let db = opts |
| 63 | - Username::try_new(username) | 90 | + .get_database() |
| 64 | - .map_err(|err| AppError::Internal(format!("invalid BUILDER_USERNAME: {err}")))?, | 91 | + .ok_or_else(|| { |
| 65 | - Password::try_new(password) | 92 | + AppError::Internal( |
| 66 | - .map_err(|err| AppError::Internal(format!("invalid BUILDER_PASSWORD: {err}")))?, | 93 | + "DATABASE_URL names no database — the school databases are named after it".into(), |
| 67 | - ))), | 94 | + ) |
| 68 | - (None, None) => Ok(None), | 95 | + })? |
| 69 | - _ => Err(AppError::Internal( | 96 | + .to_string(); |
| 70 | - "BUILDER_USERNAME and BUILDER_PASSWORD must be set together".into(), | 97 | + Ok((opts, db)) |
| 71 | - )), | 98 | +} |
| 99 | + | ||
| 100 | +/// The pool knobs. The control pool holds 10 connections; each school pool | ||
| 101 | +/// holds 4 (a school's traffic is one building's worth, and every school pool | ||
| 102 | +/// draws from the same server's connection budget). | ||
| 103 | +fn pool_options(max_connections: u32) -> PgPoolOptions { | ||
| 104 | + PgPoolOptions::new() | ||
| 105 | + .max_connections(max_connections) | ||
| 106 | + .min_connections(0) | ||
| 107 | + .acquire_timeout(Duration::from_secs(10)) | ||
| 108 | + .idle_timeout(Duration::from_secs(300)) | ||
| 109 | + .max_lifetime(Duration::from_secs(1800)) | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +/// A pool over one school database with the school pool sizing. The schema is | ||
| 113 | +/// the caller's business — [`migrate_school`] for a mint, nothing for a | ||
| 114 | +/// re-dial of an existing school. | ||
| 115 | +pub(crate) async fn school_pool(base: &PgConnectOptions, db_name: &str) -> Result<PgPool, AppError> { | ||
| 116 | + pool_options(4) | ||
| 117 | + .connect_with(base.clone().database(db_name)) | ||
| 118 | + .await | ||
| 119 | + .map_err(Into::into) | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +/// A `CREATE DATABASE` / `DROP DATABASE` statement for a quoted identifier. | ||
| 123 | +/// The names passed here are the control database's name (from | ||
| 124 | +/// `DATABASE_URL`), the template's (`{control}_school_template`) or | ||
| 125 | +/// [`crate::tenant::school_db_name`]'s output — never user input: the slug | ||
| 126 | +/// charset is `[a-z0-9-]` and an embedded quote is doubled, so the statement | ||
| 127 | +/// cannot be escaped from. That manual audit is what licenses the | ||
| 128 | +/// `AssertSqlSafe` wrapper every caller applies (sqlx refuses non-literal | ||
| 129 | +/// query strings without it). | ||
| 130 | +pub(crate) fn create_database_sql(statement: &str, name: &str) -> String { | ||
| 131 | + format!("{statement} \"{}\"", name.replace('"', "\"\"")) | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +async fn boot_control(base: &PgConnectOptions) -> Result<PgPool, sqlx::Error> { | ||
| 135 | + let pool = pool_options(10).connect_with(base.clone()).await?; | ||
| 136 | + // The migrator is built here rather than in [`migrator`]: its resolution | ||
| 137 | + // failure must classify as a boot error (retry or abort), not skip | ||
| 138 | + // straight to `AppError`. | ||
| 139 | + let migrator = Migrator::new(migrations_path("control").as_path()) | ||
| 140 | + .await | ||
| 141 | + .map_err(sqlx::Error::from)?; | ||
| 142 | + migrator.run(&pool).await?; | ||
| 143 | + Ok(pool) | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +/// Is this boot failure the database not being *there* yet — the only thing | ||
| 147 | +/// a second of patience can fix? Everything else (a bad migration, a bad | ||
| 148 | +/// credential, a missing migrations directory) aborts startup immediately. | ||
| 149 | +fn boot_failure_retryable(err: &sqlx::Error) -> bool { | ||
| 150 | + match err { | ||
| 151 | + sqlx::Error::Migrate(migrate) => match migrate.as_ref() { | ||
| 152 | + MigrateError::Execute(e) | MigrateError::ExecuteMigration(e, _) => is_dial_error(e), | ||
| 153 | + _ => false, | ||
| 154 | + }, | ||
| 155 | + e => is_dial_error(e), | ||
| 72 | } | 156 | } |
| 73 | } | 157 | } |
| 74 | 158 | ||
| 75 | -/// The two ways a rival's claim shows up as an error on ours: our `CREATE` hit | 159 | +/// Connection-class errors: the server was unreachable or the pool could not |
| 76 | -/// their row, or the key-value layer aborted our transaction because theirs | 160 | +/// hand out a connection. A migrations statement that *failed* is not here — |
| 77 | -/// touched the same key first. | 161 | +/// its error is `Error::Database`, and no sleep rewrites SQL. |
| 78 | -/// | 162 | +fn is_dial_error(err: &sqlx::Error) -> bool { |
| 79 | -/// Read from the *typed* error surface, not the message. Every conflict wording | 163 | + matches!( |
| 80 | -/// the storage engines produce — surrealkv's "Transaction conflict: Write | 164 | + err, |
| 81 | -/// conflict, retry the transaction. This transaction can be retried", | 165 | + sqlx::Error::Io(_) |
| 82 | -/// surrealmx's read-conflict variant, RocksDB's `Busy`/`TryAgain` — funnels | 166 | + | sqlx::Error::Tls(_) |
| 83 | -/// through one `KvsError::TransactionConflict` into | 167 | + | sqlx::Error::PoolTimedOut |
| 84 | -/// `QueryError::TransactionConflict` (surrealdb-core 3.2.3 | 168 | + | sqlx::Error::PoolClosed |
| 85 | -/// `err/to_types.rs:295`, `kvs/err.rs:64-179`), and a duplicate record id into | 169 | + // A connection that died mid-handshake can present as protocol |
| 86 | -/// `AlreadyExistsError::Record` (`to_types.rs:206`). So the two checks below | 170 | + // breakage; a fresh dial either works or reports something else. |
| 87 | -/// cover all of them, where matching substrings covered only whichever wording | 171 | + | sqlx::Error::Protocol(_) |
| 88 | -/// the engine of the day happened to use. | 172 | + ) |
| 89 | -/// | 173 | +} |
| 90 | -/// The message fallback stays for one reason: these errors also travel over the | 174 | + |
| 91 | -/// WebSocket, where the SDK rebuilds them from the wire (`Error::from_parts`), | 175 | +/// The `migrations/<set>` directory under `CARGO_MANIFEST_DIR`. Two sets |
| 92 | -/// and a server that omitted the typed details would otherwise turn a lost race | 176 | +/// cannot both feed the compile-time `migrate!` macro, so both are resolved |
| 93 | -/// into a failed boot. Widest known wordings, cheap, and belt-and-braces. | 177 | +/// from their paths at runtime. |
| 94 | -pub(crate) fn lost_the_race(err: &surrealdb::Error) -> bool { | 178 | +fn migrations_path(set: &str) -> std::path::PathBuf { |
| 95 | - use surrealdb::types::{ErrorDetails, QueryError}; | 179 | + Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/migrations")).join(set) |
| 96 | - if err.is_already_exists() | 180 | +} |
| 97 | - || matches!( | 181 | + |
| 98 | - err.details(), | 182 | +async fn migrator(set: &str) -> Result<Migrator, AppError> { |
| 99 | - ErrorDetails::Query(Some(QueryError::TransactionConflict)) | 183 | + Migrator::new(migrations_path(set).as_path()) |
| 100 | - ) | 184 | + .await |
| 185 | + .map_err(|err| AppError::Internal(format!("cannot read the {set} migrations: {err}"))) | ||
| 186 | +} | ||
| 187 | + | ||
| 188 | +/// Apply the school schema to a school database — the template at boot, every | ||
| 189 | +/// newly minted school at create — then sweep the chatbot turns the previous | ||
| 190 | +/// process owed an answer. Idempotent: an already-migrated database runs only | ||
| 191 | +/// the sweep. | ||
| 192 | +pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> { | ||
| 193 | + migrator("school") | ||
| 194 | + .await? | ||
| 195 | + .run(pool) | ||
| 196 | + .await | ||
| 197 | + .map_err(|err| AppError::from(sqlx::Error::from(err)))?; | ||
| 198 | + | ||
| 199 | + // An assistant turn is answered by a task in this process, so a restart | ||
| 200 | + // can leave its row `pending` with nobody left to complete it. Only rows | ||
| 201 | + // past the stale horizon (`CHATBOT_PENDING_STALE_SECS`) are certainly | ||
| 202 | + // abandoned though: a young one may still be being answered on the other | ||
| 203 | + // side of the AI bridge, and a deploy must not shoot down a turn | ||
| 204 | + // dispatched seconds ago. Nothing is lost by waiting — a reader already | ||
| 205 | + // presents an over-age `pending` row as failed, and the next boot sweeps | ||
| 206 | + // for real whatever crossed the horizon in the meantime. | ||
| 207 | + let now = Timestamp::now().as_millis(); | ||
| 208 | + sqlx::query( | ||
| 209 | + "UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted', | ||
| 210 | + completed_at = $1 | ||
| 211 | + WHERE status = 'pending' AND created_at < $2", | ||
| 212 | + ) | ||
| 213 | + .bind(now) | ||
| 214 | + .bind(now - CHATBOT_PENDING_STALE_SECS * 1_000) | ||
| 215 | + .execute(pool) | ||
| 216 | + .await?; | ||
| 217 | + Ok(()) | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +/// Ensure the school-template database exists and carries the current school | ||
| 221 | +/// schema. `CREATE DATABASE` runs on the control pool outside any | ||
| 222 | +/// transaction; the loser of a race adopts the winner's database. | ||
| 223 | +async fn ensure_template( | ||
| 224 | + control: &PgPool, | ||
| 225 | + base: &PgConnectOptions, | ||
| 226 | + name: &str, | ||
| 227 | +) -> Result<(), AppError> { | ||
| 228 | + if let Err(err) = | ||
| 229 | + sqlx::query(sqlx::AssertSqlSafe(create_database_sql("CREATE DATABASE", name))) | ||
| 230 | + .execute(control) | ||
| 231 | + .await | ||
| 101 | { | 232 | { |
| 102 | - return true; | 233 | + if !is_duplicate_database(&err) { |
| 234 | + return Err(err.into()); | ||
| 235 | + } | ||
| 103 | } | 236 | } |
| 104 | - let message = err.to_string(); | 237 | + // One migrator connection, made and closed: the template is never served. |
| 105 | - message.contains("already exists") || message.contains("can be retried") | 238 | + let pool = pool_options(1).connect_with(base.clone().database(name)).await?; |
| 239 | + let migrated = migrate_school(&pool).await; | ||
| 240 | + pool.close().await; | ||
| 241 | + migrated | ||
| 106 | } | 242 | } |
| 107 | 243 | ||
| 108 | -/// Send one guarded single-statement write, re-sending it while the store | 244 | +/// `42P04` — the database already exists. The other side of every |
| 109 | -/// answers "conflict, retry", and hand back the rows it returned. | 245 | +/// "create it unless a rival got there first" move. |
| 110 | -/// | 246 | +pub(crate) fn is_duplicate_database(err: &sqlx::Error) -> bool { |
| 111 | -/// The guard on such a statement reads a column a rival writes, so the two | 247 | + err.as_database_error() |
| 112 | -/// contend on one record *by design* — that contention is what makes the guard | 248 | + .is_some_and(|db| db.code().as_deref() == Some("42P04")) |
| 113 | -/// atomic. Losing a round writes nothing at all, which makes re-sending the | 249 | +} |
| 114 | -/// whole of the recovery; without it an ordinary raced `PATCH` or `DELETE` | 250 | + |
| 115 | -/// answers 500 instead of the 404 or 409 it owes. Only for statements that | 251 | +/// The violated `UNIQUE` constraint's name, when `err` is a unique violation |
| 116 | -/// cannot produce "already exists" (the other thing [`lost_the_race`] matches), | 252 | +/// (`23505`). The constraint name is the stable handle call sites map |
| 117 | -/// so `UPDATE` and `DELETE` and not `CREATE`. | 253 | +/// refusals onto — `unique_violation(&e) == Some("school_pkey")` — and it is |
| 118 | -pub(crate) async fn write_with_retry<T: surrealdb::types::SurrealValue>( | 254 | +/// borrowed from the error, not `'static`: the server owns the text. |
| 119 | - db: &Database, | 255 | +pub fn unique_violation(err: &sqlx::Error) -> Option<&str> { |
| 120 | - sql: &str, | 256 | + let db = err.as_database_error()?; |
| 121 | - bindings: &[(String, surrealdb::types::Value)], | 257 | + if db.code().as_deref() == Some("23505") { |
| 122 | -) -> Result<Vec<T>, AppError> { | 258 | + db.constraint() |
| 123 | - let mut last = None; | 259 | + } else { |
| 124 | - for attempt in 0..CAP_WRITE_TRIES { | 260 | + None |
| 125 | - backoff(attempt).await; | ||
| 126 | - let mut query = db.query(sql); | ||
| 127 | - for (name, value) in bindings { | ||
| 128 | - query = query.bind((name.clone(), value.clone())); | ||
| 129 | - } | ||
| 130 | - match async { query.await?.check()?.take::<Vec<T>>(0) }.await { | ||
| 131 | - Ok(rows) => return Ok(rows), | ||
| 132 | - Err(err) if lost_the_race(&err) => last = Some(err), | ||
| 133 | - Err(err) => return Err(err.into()), | ||
| 134 | - } | ||
| 135 | } | 261 | } |
| 136 | - Err(last | ||
| 137 | - .map(AppError::from) | ||
| 138 | - .unwrap_or_else(|| AppError::Internal("a guarded write never ran".into()))) | ||
| 139 | } | 262 | } |
| 140 | 263 | ||
| 141 | -/// Send one guarded `BEGIN…COMMIT` cascade, re-sending it while the store | 264 | +/// A foreign-key violation (`23503`): a parent row a statement names is gone. |
| 142 | -/// answers "conflict, retry", and hand back both the response and the errors | 265 | +pub fn foreign_key_violation(err: &sqlx::Error) -> bool { |
| 143 | -/// drained off it. | 266 | + err.as_database_error() |
| 267 | + .is_some_and(|db| db.code().as_deref() == Some("23503")) | ||
| 268 | +} | ||
| 269 | + | ||
| 270 | +/// Is this error the transaction *contended*, rather than decided? `40001` | ||
| 271 | +/// (serialization failure) and `40P01` (deadlock) are Postgres telling two | ||
| 272 | +/// writers to take turns — the whole reason the retry loop below exists. | ||
| 273 | +pub fn is_retryable_tx(err: &sqlx::Error) -> bool { | ||
| 274 | + err.as_database_error().is_some_and(|db| { | ||
| 275 | + let code = db.code(); | ||
| 276 | + code.as_deref() == Some("40001") || code.as_deref() == Some("40P01") | ||
| 277 | + }) | ||
| 278 | +} | ||
| 279 | + | ||
| 280 | +/// [`is_retryable_tx`] plus the foreign-key violation. For **cascade** | ||
| 281 | +/// transactions only: a child insert whose parent vanished mid-cascade means | ||
| 282 | +/// a racing cascade is still in flight and a re-run sees the settled state — | ||
| 283 | +/// but to a plain insert a `23503` is a real refusal (the parent is simply | ||
| 284 | +/// gone), and retrying it would only burn the budget before returning the | ||
| 285 | +/// same verdict. | ||
| 286 | +pub fn is_retryable_cascade(err: &sqlx::Error) -> bool { | ||
| 287 | + is_retryable_tx(err) || foreign_key_violation(err) | ||
| 288 | +} | ||
| 289 | + | ||
| 290 | +/// Send one guarded `BEGIN…COMMIT` transaction, re-running it while Postgres | ||
| 291 | +/// answers "contended, retry", and hand back the closure's value. | ||
| 144 | /// | 292 | /// |
| 145 | -/// [`write_with_retry`]'s story, for the cascades that cannot be one statement: | 293 | +/// The closure writes through the transaction's connection (`&mut |
| 146 | -/// the guard reads a column a rival writes, so the two contend on one record by | 294 | +/// PgConnection`), returns its value, and reports refusals as ordinary `Err`s |
| 147 | -/// design, and a lost round aborts the transaction having written *nothing* — | 295 | +/// carrying exactly the `AppError` the web layer owes the caller. A refusal |
| 148 | -/// which is what makes re-sending the whole of the recovery. | 296 | +/// is a *decision*, so it outranks the retry loop — only `AppError::Db` |
| 297 | +/// errors that [`is_retryable_tx`] (or, when `cascade`, [`is_retryable_cascade`]) | ||
| 298 | +/// recognise are re-sent; everything else comes straight back. | ||
| 149 | /// | 299 | /// |
| 150 | -/// Both halves come back because the caller needs both and `take_errors` | 300 | +/// Isolation is Postgres's default **READ COMMITTED** everywhere. Invariants |
| 151 | -/// consumes: the response carries the result slots, and only the error map can | 301 | +/// that span rows are enforced by single-statement CTEs or row locks |
| 152 | -/// tell a deliberate `THROW` from a lost round. `refusals` are the caller's | 302 | +/// (`FOR UPDATE` / `FOR NO KEY UPDATE`) inside the closure, not by stronger |
| 153 | -/// `THROW` markers and they are matched *first* — a `THROW` is a decision, and | 303 | +/// isolation. |
| 154 | -/// it outranks a conflict. Everything after that ordering is why this exists: | 304 | +/// The closure is an [`AsyncFnMut`] (edition-2024 async closure, or a plain |
| 155 | -/// an aborted transaction errors *every* slot, and all but the failing one say | 305 | +/// closure whose async block the compiler infers as such) because every real |
| 156 | -/// a generic "not executed", which is the consequence of the abort and never a | 306 | +/// call site's future borrows the connection — a named `Fut` generic cannot |
| 157 | -/// reason of its own. Picking one of those out of the unordered `HashMap` — or | 307 | +/// express that lifetime relationship. |
| 158 | -/// taking the first via `check()` — retired a retryable round as a 500, measured | ||
| 159 | -/// on `Course::delete` at 1-3 of 20 raced rounds. | ||
| 160 | /// | 308 | /// |
| 161 | -/// [`write_with_retry`]'s restriction carries over, and a cascade makes it | 309 | +/// Isolation is Postgres's default **READ COMMITTED** everywhere. Invariants |
| 162 | -/// easier to trip: no statement inside may be able to answer "already exists", | 310 | +/// that span rows are enforced by single-statement CTEs or row locks |
| 163 | -/// because that is the other thing [`lost_the_race`] matches and re-sending it | 311 | +/// (`FOR UPDATE` / `FOR NO KEY UPDATE`) inside the closure, not by stronger |
| 164 | -/// would just fail the same way until the tries run out — turning a 409 into a | 312 | +/// isolation; if a transaction genuinely cannot be row-locked, escalate that |
| 165 | -/// 500, which is the exact defect this exists to prevent. The test to apply to | 313 | +/// one to `SERIALIZABLE` (the retry loop already covers the `40001` it can |
| 166 | -/// every statement in the batch is not which verb it uses but whether the store | 314 | +/// then raise) and record the reason in its own call site's comment. |
| 167 | -/// could *legitimately* answer "already exists" to it — that answer is a | 315 | +/// |
| 168 | -/// decision, and this loop cannot tell one from a conflict, so it would burn all | 316 | +/// The budget and backoff are the guard layer's usual: `CAP_WRITE_TRIES` |
| 169 | -/// the tries re-asking a question already settled. `UPDATE` and `DELETE` never | 317 | +/// rounds, `backoff`'s exponential-with-jitter wait, attempt zero waiting |
| 170 | -/// can. A `CREATE` can, unless the id is unreachable by any rival: a freshly | 318 | +/// not at all. |
| 171 | -/// generated ULID on a table with no `UNIQUE` index is such an id. An `UPSERT` | 319 | +pub async fn tx_with_retry<T, F>(pool: &PgPool, cascade: bool, mut f: F) -> Result<T, AppError> |
| 172 | -/// can, unless its id is *bijective* with every unique tuple its table indexes — | 320 | +where |
| 173 | -/// then the index entry can only ever point at the row the id already names, and | 321 | + F: AsyncFnMut(&mut PgConnection) -> Result<T, AppError>, |
| 174 | -/// the write resolves onto it instead of colliding with it | 322 | +{ |
| 175 | -/// ([`crate::domain::exam_result::ExamResult`]'s composite id is that shape). | 323 | + let mut last: Option<sqlx::Error> = None; |
| 176 | -/// A statement that fails this test belongs in front of the cascade, where its | ||
| 177 | -/// 409 can be read as the answer it is. | ||
| 178 | -pub(crate) async fn transaction_with_retry( | ||
| 179 | - db: &Database, | ||
| 180 | - sql: &str, | ||
| 181 | - bindings: &[(String, surrealdb::types::Value)], | ||
| 182 | - refusals: &[&str], | ||
| 183 | -) -> Result< | ||
| 184 | - ( | ||
| 185 | - surrealdb::IndexedResults, | ||
| 186 | - std::collections::HashMap<usize, surrealdb::Error>, | ||
| 187 | - ), | ||
| 188 | - AppError, | ||
| 189 | -> { | ||
| 190 | - let mut last = None; | ||
| 191 | for attempt in 0..CAP_WRITE_TRIES { | 324 | for attempt in 0..CAP_WRITE_TRIES { |
| 192 | backoff(attempt).await; | 325 | backoff(attempt).await; |
| 193 | - let mut query = db.query(sql); | 326 | + let mut tx = pool.begin().await?; |
| 194 | - for (name, value) in bindings { | 327 | + match f(&mut tx).await { |
| 195 | - query = query.bind((name.clone(), value.clone())); | 328 | + Ok(value) => { |
| 196 | - } | 329 | + // A commit can itself lose the race — `40001` fires at COMMIT |
| 197 | - let mut result = match query.await { | 330 | + // in Postgres — so the commit sits inside the classification. |
| 198 | - Ok(result) => result, | 331 | + match tx.commit().await { |
| 199 | - Err(err) if lost_the_race(&err) => { | 332 | + Ok(()) => return Ok(value), |
| 333 | + Err(err) if is_retryable(&err, cascade) => last = Some(err), | ||
| 334 | + Err(err) => return Err(err.into()), | ||
| 335 | + } | ||
| 336 | + } | ||
| 337 | + Err(AppError::Db(err)) if is_retryable(&err, cascade) => { | ||
| 338 | + // The losing round wrote nothing durable, which is what makes | ||
| 339 | + // re-sending the whole of the recovery. Settle the abort | ||
| 340 | + // before the wait, so a connection is not left | ||
| 341 | + // idle-in-transaction across the backoff. | ||
| 342 | + let _ = tx.rollback().await; | ||
| 200 | last = Some(err); | 343 | last = Some(err); |
| 201 | - continue; | ||
| 202 | } | 344 | } |
| 203 | - Err(err) => return Err(err.into()), | 345 | + // A refusal is a decision. Same shape for a `Db` error the |
| 204 | - }; | 346 | + // classifier does not recognise: it failed for a reason waiting |
| 205 | - let mut errors = result.take_errors(); | 347 | + // cannot fix. |
| 206 | - let refused = |error: &surrealdb::Error| { | 348 | + Err(err) => return Err(err), |
| 207 | - let message = error.to_string(); | ||
| 208 | - refusals.iter().any(|marker| message.contains(marker)) | ||
| 209 | - }; | ||
| 210 | - if errors.values().any(refused) || !errors.values().any(lost_the_race) { | ||
| 211 | - return Ok((result, errors)); | ||
| 212 | } | 349 | } |
| 213 | - last = errors.drain().map(|(_, error)| error).find(lost_the_race); | ||
| 214 | } | 350 | } |
| 215 | - Err(last | 351 | + Err(last.map(AppError::Db).unwrap_or_else(|| { |
| 216 | - .map(AppError::from) | 352 | + AppError::Internal("a guarded transaction never ran".into()) |
| 217 | - .unwrap_or_else(|| AppError::Internal("a guarded cascade never ran".into()))) | 353 | + })) |
| 354 | +} | ||
| 355 | + | ||
| 356 | +fn is_retryable(err: &sqlx::Error, cascade: bool) -> bool { | ||
| 357 | + if cascade { | ||
| 358 | + is_retryable_cascade(err) | ||
| 359 | + } else { | ||
| 360 | + is_retryable_tx(err) | ||
| 361 | + } | ||
| 218 | } | 362 | } |
| 219 | 363 | ||
| 220 | /// Wait out one lost round. Exponential with jitter, because racers arrive in | 364 | /// Wait out one lost round. Exponential with jitter, because racers arrive in |
| @@ -229,75 +373,25 @@ pub(crate) async fn backoff(attempt: usize) { | |||
| 229 | tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await; | 373 | tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await; |
| 230 | } | 374 | } |
| 231 | 375 | ||
| 232 | -/// Dial the database, retrying until it answers. | 376 | +/// The `BUILDER_USERNAME` / `BUILDER_PASSWORD` bootstrap pair, if configured. |
| 233 | -/// | 377 | +/// Both-or-neither: half a pair aborts startup rather than silently running |
| 234 | -/// Never gives up, because giving up is worse than waiting: the database is | 378 | +/// without the seed — and without a builder, a fresh deployment has nobody who |
| 235 | -/// normally a sibling container booting in parallel, and a process that exits | 379 | +/// can create the first school. |
| 236 | -/// on the first refusal gets restarted by the runtime, fails again in ~100ms, | 380 | +fn builder_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, AppError> { |
| 237 | -/// and burns its whole restart budget inside a second — leaving the backend | 381 | + match (&cfg.builder_username, &cfg.builder_password) { |
| 238 | -/// permanently down over a startup skew that would have cleared on its own. | 382 | + (Some(username), Some(password)) => Ok(Some(( |
| 239 | -/// | 383 | + Username::try_new(username) |
| 240 | -/// Only the dial is retried. Bad credentials or a broken migration still fail | 384 | + .map_err(|err| AppError::Internal(format!("invalid BUILDER_USERNAME: {err}")))?, |
| 241 | -/// hard, since no amount of waiting fixes those. | 385 | + Password::try_new(password) |
| 242 | -async fn connect_with_retry(cfg: &Config) -> Surreal<Any> { | 386 | + .map_err(|err| AppError::Internal(format!("invalid BUILDER_PASSWORD: {err}")))?, |
| 243 | - let mut backoff = 1; | 387 | + ))), |
| 244 | - loop { | 388 | + (None, None) => Ok(None), |
| 245 | - match surrealdb::engine::any::connect(cfg.db_url.clone()).await { | 389 | + _ => Err(AppError::Internal( |
| 246 | - Ok(db) => return db, | 390 | + "BUILDER_USERNAME and BUILDER_PASSWORD must be set together".into(), |
| 247 | - Err(err) => { | 391 | + )), |
| 248 | - tracing::warn!( | ||
| 249 | - "database at {} unreachable ({err}) — retrying in {backoff}s", | ||
| 250 | - cfg.db_url | ||
| 251 | - ); | ||
| 252 | - tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; | ||
| 253 | - backoff = (backoff * 2).min(crate::constant::DB_CONNECT_BACKOFF_MAX_SECS); | ||
| 254 | - } | ||
| 255 | - } | ||
| 256 | } | 392 | } |
| 257 | } | 393 | } |
| 258 | 394 | ||
| 259 | -/// A fresh in-memory **school** database with the school schema applied. For | ||
| 260 | -/// the unit tests whose subject is one school's own rows; a test that needs the | ||
| 261 | -/// whole app (control database included) wants [`init_mem_tenants`]. | ||
| 262 | -pub async fn init_mem() -> Result<Database, AppError> { | ||
| 263 | - let db = surrealdb::engine::any::connect("memory").await?; | ||
| 264 | - db.use_ns("hezarfen").use_db("hezarfen").await?; | ||
| 265 | - migrate(&db).await?; | ||
| 266 | - Ok(std::sync::Arc::new(db)) | ||
| 267 | -} | ||
| 268 | - | ||
| 269 | -/// A fresh in-memory deployment: an empty control database plus one school, | ||
| 270 | -/// [`crate::tenant::DEMO_SLUG`]. The bootstrap every router-level test uses. | ||
| 271 | -pub async fn init_mem_tenants() -> Result<Tenants, AppError> { | ||
| 272 | - let tenants = Tenants::new_mem().await?; | ||
| 273 | - let demo = crate::tenant::Slug::try_new(crate::tenant::DEMO_SLUG) | ||
| 274 | - .map_err(|err| AppError::Internal(format!("the demo slug is a slug: {err}")))?; | ||
| 275 | - tenants | ||
| 276 | - .create(&demo, "Demo School", crate::module::ModuleSet::all()) | ||
| 277 | - .await?; | ||
| 278 | - Ok(tenants) | ||
| 279 | -} | ||
| 280 | - | ||
| 281 | -/// A handle on a **real** SurrealDB server, in a scratch namespace of its own | ||
| 282 | -/// that is dropped and re-made on every call. For the tests whose subject is | ||
| 283 | -/// the store's own conflict detection, which [`init_mem`]'s embedded engine | ||
| 284 | -/// does not have: it drops one of two concurrent writes to a record and answers | ||
| 285 | -/// `Ok` to both (see [`crate::db::cap`]), which *forges* the very | ||
| 286 | -/// integrity failure those tests exist to catch — measured 2026-07-30 at 2 | ||
| 287 | -/// failed runs in 36 on `memory`, against 0 in 10 000 rounds here. | ||
| 288 | -/// | ||
| 289 | -/// Every caller is `#[ignore]`d, so a machine with no server prints them as | ||
| 290 | -/// `ignored` rather than passing: this is not a test that may quietly skip. | ||
| 291 | -/// `HEZARFEN_TEST_DB` overrides the address; the credentials are `compose.yaml`'s. | ||
| 292 | -/// | ||
| 293 | -/// The guard handed back with the handle serializes these tests against each | ||
| 294 | -/// other and must be held for the whole test — hence the tuple, which cannot be | ||
| 295 | -/// forgotten the way a separate `lock()` line can. `cargo test -- --ignored` | ||
| 296 | -/// runs them in parallel, and while each has a namespace to itself they all | ||
| 297 | -/// burst against the *one* server: their beats are sub-millisecond, so a | ||
| 298 | -/// sibling's burst pushes a delete clean out of the window it is meant to land | ||
| 299 | -/// in (measured 4 runs in 4 at 3 of 6 failing their own "the race was reached" | ||
| 300 | -/// guard). Serialized, the plain documented command works. | ||
| 301 | #[cfg(test)] | 395 | #[cfg(test)] |
| 302 | mod builder_seed_tests { | 396 | mod builder_seed_tests { |
| 303 | use super::builder_credentials; | 397 | use super::builder_credentials; |
| @@ -330,1015 +424,3 @@ mod builder_seed_tests { | |||
| 330 | } | 424 | } |
| 331 | } | 425 | } |
| 332 | 426 | ||
| 333 | -#[cfg(test)] | ||
| 334 | -pub(crate) static RACE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); | ||
| 335 | - | ||
| 336 | -#[cfg(test)] | ||
| 337 | -pub(crate) async fn init_test_server( | ||
| 338 | - scratch: &str, | ||
| 339 | -) -> (Database, tokio::sync::MutexGuard<'static, ()>) { | ||
| 340 | - let serialized = RACE_LOCK.lock().await; | ||
| 341 | - let url = | ||
| 342 | - std::env::var("HEZARFEN_TEST_DB").unwrap_or_else(|_| "ws://127.0.0.1:8000".to_string()); | ||
| 343 | - let db = surrealdb::engine::any::connect(url.clone()) | ||
| 344 | - .await | ||
| 345 | - .unwrap_or_else(|err| panic!("no SurrealDB server at {url} ({err})")); | ||
| 346 | - db.signin(Root { | ||
| 347 | - username: "root".into(), | ||
| 348 | - password: "root".into(), | ||
| 349 | - }) | ||
| 350 | - .await | ||
| 351 | - .expect("sign in to the test server"); | ||
| 352 | - let ns = format!("test_{scratch}"); | ||
| 353 | - db.query(format!("REMOVE NAMESPACE IF EXISTS {ns}")) | ||
| 354 | - .await | ||
| 355 | - .expect("clear the scratch namespace") | ||
| 356 | - .check() | ||
| 357 | - .expect("clear the scratch namespace"); | ||
| 358 | - db.use_ns(ns.clone()).use_db(ns).await.expect("scratch ns"); | ||
| 359 | - let db = std::sync::Arc::new(db); | ||
| 360 | - migrate(&db).await.expect("migrate the scratch namespace"); | ||
| 361 | - (db, serialized) | ||
| 362 | -} | ||
| 363 | - | ||
| 364 | -/// Apply the schema + backfills. Idempotent — `init` runs it on every boot, | ||
| 365 | -/// and tests re-run it on a live handle to simulate a second boot. | ||
| 366 | -pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> { | ||
| 367 | - for sql in MIGRATION_BATCHES { | ||
| 368 | - let mut query = db.query(sql); | ||
| 369 | - for (name, value) in migration_binds() { | ||
| 370 | - query = query.bind((name, value)); | ||
| 371 | - } | ||
| 372 | - query.await?.check()?; | ||
| 373 | - } | ||
| 374 | - Ok(()) | ||
| 375 | -} | ||
| 376 | - | ||
| 377 | -/// Apply the **control** schema (schools, builders, the shared rate-limit | ||
| 378 | -/// window). Idempotent, like [`migrate`]. | ||
| 379 | -pub async fn migrate_control(db: &Surreal<Any>) -> Result<(), AppError> { | ||
| 380 | - // The one data-driven parameter in this batch: the module list a school | ||
| 381 | - // written before entitlements existed is backfilled to. | ||
| 382 | - let all_modules = crate::module::ModuleSet::all().names(); | ||
| 383 | - for sql in CONTROL_MIGRATION_BATCHES { | ||
| 384 | - db.query(sql) | ||
| 385 | - .bind(("all_modules", all_modules.clone())) | ||
| 386 | - .await? | ||
| 387 | - .check()?; | ||
| 388 | - } | ||
| 389 | - Ok(()) | ||
| 390 | -} | ||
| 391 | - | ||
| 392 | -/// Parameters the batches are executed with. Bound, not baked into the SQL | ||
| 393 | -/// string: a `const` cannot be interpolated into another `const`, and a | ||
| 394 | -/// hand-copied 300000 would drift silently. The one-time blocks' fingerprints | ||
| 395 | -/// ride along — see [`marked_blocks`]. Bound to all three batches, which is | ||
| 396 | -/// free: an unused parameter is not an error. | ||
| 397 | -fn migration_binds() -> Vec<(String, i64)> { | ||
| 398 | - let mut binds = vec![("stale_ms".to_string(), CHATBOT_PENDING_STALE_SECS * 1_000)]; | ||
| 399 | - binds.extend(marked_blocks()); | ||
| 400 | - binds | ||
| 401 | -} | ||
| 402 | - | ||
| 403 | -/// The line every one-time block in [`BACKFILL`] opens with. The name straight | ||
| 404 | -/// after it is the block's `migration_mark` key, and `fp_<name>` is the | ||
| 405 | -/// parameter its fingerprint is bound to — so a block written in this idiom is | ||
| 406 | -/// found, hashed and bound with nothing to keep by hand. A block written any | ||
| 407 | -/// other way silently gets no fingerprint, which is what | ||
| 408 | -/// `every_one_time_block_is_fingerprinted` exists to catch. | ||
| 409 | -const MARK_GATE: &str = "IF array::len((SELECT VALUE id FROM migration_mark:"; | ||
| 410 | - | ||
| 411 | -/// Every one-time block in [`BACKFILL`], as (`fp_<name>`, hash of its own SQL). | ||
| 412 | -/// | ||
| 413 | -/// A `migration_mark` used to say only *that* a block had run, which made a | ||
| 414 | -/// marked block's content permanently uncorrectable: an edit to it never ran on | ||
| 415 | -/// any volume that had booted once. The mark now stores this number and the | ||
| 416 | -/// gate compares it against the number this binary computes, so an edited block | ||
| 417 | -/// runs one more time and re-stamps. There is nothing to remember to bump — the | ||
| 418 | -/// hash comes from the very string the server executes, which is the whole | ||
| 419 | -/// point: a hand-kept version is the same discipline failure in a new place. | ||
| 420 | -/// | ||
| 421 | -/// Hashed from the gate through the stamp with comments and indentation | ||
| 422 | -/// dropped: every re-run costs something (the `profile_counters` block says | ||
| 423 | -/// what, in its own comment), so re-wording a comment must not trigger one. | ||
| 424 | -fn marked_blocks() -> Vec<(String, i64)> { | ||
| 425 | - let mut blocks = Vec::new(); | ||
| 426 | - let mut rest = BACKFILL; | ||
| 427 | - while let Some(at) = rest.find(MARK_GATE) { | ||
| 428 | - let block = &rest[at..]; | ||
| 429 | - let name: String = block[MARK_GATE.len()..] | ||
| 430 | - .chars() | ||
| 431 | - .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') | ||
| 432 | - .collect(); | ||
| 433 | - let stamp = format!("UPSERT migration_mark:{name}"); | ||
| 434 | - let end = block | ||
| 435 | - .find(&stamp) | ||
| 436 | - .and_then(|from| block[from..].find(';').map(|to| from + to + 1)) | ||
| 437 | - .unwrap_or_else(|| panic!("the `{name}` block never stamps its own mark")); | ||
| 438 | - blocks.push((format!("fp_{name}"), block_fingerprint(&block[..end]))); | ||
| 439 | - rest = &block[end..]; | ||
| 440 | - } | ||
| 441 | - blocks | ||
| 442 | -} | ||
| 443 | - | ||
| 444 | -/// FNV-1a over a block's statements, comments and layout dropped. | ||
| 445 | -/// | ||
| 446 | -/// Hand-rolled rather than [`std::hash`]: this number is *stored*, so it has to | ||
| 447 | -/// mean the same thing after a compiler upgrade, and `DefaultHasher` promises | ||
| 448 | -/// nothing across versions — a hash that drifted on its own would re-run every | ||
| 449 | -/// one-time block on every volume. | ||
| 450 | -fn block_fingerprint(block: &str) -> i64 { | ||
| 451 | - let mut hash: u64 = 0xcbf2_9ce4_8422_2325; | ||
| 452 | - for line in block | ||
| 453 | - .lines() | ||
| 454 | - .map(str::trim) | ||
| 455 | - .filter(|line| !line.is_empty() && !line.starts_with("--")) | ||
| 456 | - { | ||
| 457 | - for byte in line.bytes().chain(std::iter::once(b'\n')) { | ||
| 458 | - hash = (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3); | ||
| 459 | - } | ||
| 460 | - } | ||
| 461 | - hash as i64 | ||
| 462 | -} | ||
| 463 | - | ||
| 464 | -#[cfg(test)] | ||
| 465 | -mod tests { | ||
| 466 | - | ||
| 467 | - /// The fingerprint has to move when a *statement* moves and stay put when | ||
| 468 | - /// prose does: a re-run is never free (see the `profile_counters` comment), | ||
| 469 | - /// and a fingerprint that ignored an edit would put us back where this | ||
| 470 | - /// mechanism started — a marked block nobody can correct. | ||
| 471 | - #[test] | ||
| 472 | - fn a_block_fingerprint_tracks_statements_not_prose() { | ||
| 473 | - let block = "IF x = 0 {\n -- why this runs\n UPDATE t SET a = 1;\n};"; | ||
| 474 | - let reworded = "IF x = 0 {\n -- why this runs, at length\n UPDATE t SET a = 1;\n};"; | ||
| 475 | - let edited = "IF x = 0 {\n -- why this runs\n UPDATE t SET a = 2;\n};"; | ||
| 476 | - assert_eq!( | ||
| 477 | - super::block_fingerprint(block), | ||
| 478 | - super::block_fingerprint(reworded), | ||
| 479 | - "a re-worded comment or a re-indent must not re-run a one-time block" | ||
| 480 | - ); | ||
| 481 | - assert_ne!( | ||
| 482 | - super::block_fingerprint(block), | ||
| 483 | - super::block_fingerprint(edited), | ||
| 484 | - "an edited statement must re-run its block" | ||
| 485 | - ); | ||
| 486 | - } | ||
| 487 | - | ||
| 488 | - /// The forcing function: a one-time block written outside the gate idiom | ||
| 489 | - /// gets no fingerprint parameter, and its `$fp_…` would bind to nothing — a | ||
| 490 | - /// gate that then matches every mark and skips forever. Nothing about the | ||
| 491 | - /// compiler notices, so this does. | ||
| 492 | - #[test] | ||
| 493 | - fn every_one_time_block_is_fingerprinted() { | ||
| 494 | - let blocks = super::marked_blocks(); | ||
| 495 | - let names: Vec<&str> = blocks.iter().map(|(name, _)| name.as_str()).collect(); | ||
| 496 | - assert_eq!( | ||
| 497 | - names, | ||
| 498 | - ["fp_board_roster", "fp_profile_counters"], | ||
| 499 | - "{names:?}" | ||
| 500 | - ); | ||
| 501 | - assert_ne!(blocks[0].1, blocks[1].1, "two blocks, two fingerprints"); | ||
| 502 | - // Two mentions of the mark table per block — its gate and its stamp. A | ||
| 503 | - // third, or a block gated some other way, means a block the binder | ||
| 504 | - // never saw. | ||
| 505 | - assert_eq!( | ||
| 506 | - super::BACKFILL.matches("migration_mark:").count(), | ||
| 507 | - blocks.len() * 2, | ||
| 508 | - "a one-time block outside the `{}…` idiom is invisible to the binder", | ||
| 509 | - super::MARK_GATE | ||
| 510 | - ); | ||
| 511 | - for (param, _) in &blocks { | ||
| 512 | - assert!( | ||
| 513 | - super::BACKFILL.contains(&format!("${param}")), | ||
| 514 | - "nothing reads ${param}" | ||
| 515 | - ); | ||
| 516 | - } | ||
| 517 | - } | ||
| 518 | - | ||
| 519 | - /// The fingerprint the mark for `name` must carry once its block has run. | ||
| 520 | - fn expected_fingerprint(name: &str) -> i64 { | ||
| 521 | - super::marked_blocks() | ||
| 522 | - .into_iter() | ||
| 523 | - .find(|(param, _)| *param == format!("fp_{name}")) | ||
| 524 | - .unwrap_or_else(|| panic!("no one-time block named {name}")) | ||
| 525 | - .1 | ||
| 526 | - } | ||
| 527 | - | ||
| 528 | - async fn stamped_fingerprint(db: &super::Database, name: &str) -> Vec<Option<i64>> { | ||
| 529 | - let mut rows = db | ||
| 530 | - .query(format!( | ||
| 531 | - "SELECT VALUE fingerprint FROM migration_mark:{name}" | ||
| 532 | - )) | ||
| 533 | - .await | ||
| 534 | - .unwrap(); | ||
| 535 | - rows.take(0).unwrap() | ||
| 536 | - } | ||
| 537 | - | ||
| 538 | - /// The admin seed must not be interruptible into a state no later boot can | ||
| 539 | - /// repair. `create` + `set_role` was: killed between the two writes it | ||
| 540 | - /// leaves a *student* row holding ADMIN_USERNAME, which `ensure_admin` then | ||
| 541 | - /// refuses to promote on every subsequent boot (rightly — it cannot tell | ||
| 542 | - /// that row from a stranger who registered the name first). The row is | ||
| 543 | - /// therefore minted with its role in one statement, and this pins that. | ||
| 544 | - #[test] | ||
| 545 | - fn the_admin_seed_mints_the_role_with_the_row() { | ||
| 546 | - let source = | ||
| 547 | - std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/service/user.rs")) | ||
| 548 | - .expect("read service/user.rs"); | ||
| 549 | - let start = source | ||
| 550 | - .find("pub async fn ensure_admin") | ||
| 551 | - .expect("ensure_admin is declared"); | ||
| 552 | - let body = &source[start..start + source[start..].find("\n }\n").expect("body ends")]; | ||
| 553 | - assert!( | ||
| 554 | - !body.contains("set_role"), | ||
| 555 | - "ensure_admin promotes after creating; an interruption between those two writes \ | ||
| 556 | - leaves a student account on ADMIN_USERNAME that no boot can heal:\n{body}" | ||
| 557 | - ); | ||
| 558 | - assert!( | ||
| 559 | - body.contains("create_with_role"), | ||
| 560 | - "the seed must mint the row with Role::Admin in one statement" | ||
| 561 | - ); | ||
| 562 | - } | ||
| 563 | - | ||
| 564 | - #[tokio::test] | ||
| 565 | - async fn boot_fails_chatbot_messages_left_pending() { | ||
| 566 | - let db = super::init_mem().await.unwrap(); | ||
| 567 | - db.query( | ||
| 568 | - "CREATE user:u SET username = 'u', password_hash = 'x'; | ||
| 569 | - CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1; | ||
| 570 | - CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u, | ||
| 571 | - role = 'assistant', content = '', status = 'pending', created_at = 1; | ||
| 572 | - CREATE chatbot_message:done SET thread_id = chatbot_thread:c, user_id = user:u, | ||
| 573 | - role = 'assistant', content = 'hi', status = 'complete', created_at = 1;", | ||
| 574 | - ) | ||
| 575 | - .await | ||
| 576 | - .unwrap() | ||
| 577 | - .check() | ||
| 578 | - .unwrap(); | ||
| 579 | - | ||
| 580 | - // A second boot: the task that would have answered `m` died with the | ||
| 581 | - // previous process, so the row is failed rather than left waiting. | ||
| 582 | - super::migrate(&db).await.unwrap(); | ||
| 583 | - | ||
| 584 | - let mut rows = db | ||
| 585 | - .query("SELECT id, status, error_code, completed_at FROM chatbot_message ORDER BY id") | ||
| 586 | - .await | ||
| 587 | - .unwrap(); | ||
| 588 | - let rows: Vec<serde_json::Value> = rows.take(0).unwrap(); | ||
| 589 | - // An already-answered turn is untouched; the pending one is failed. | ||
| 590 | - let done = &rows[0]; | ||
| 591 | - let interrupted = &rows[1]; | ||
| 592 | - assert_eq!(done["status"], "complete"); | ||
| 593 | - assert_eq!(done["error_code"], serde_json::Value::Null); | ||
| 594 | - assert_eq!(interrupted["status"], "failed"); | ||
| 595 | - assert_eq!(interrupted["error_code"], "interrupted"); | ||
| 596 | - assert!(interrupted["completed_at"].as_i64().unwrap() > 0); | ||
| 597 | - } | ||
| 598 | - | ||
| 599 | - /// Stale-data path for the 2026-07-30 fee-plan refcount. A dev volume | ||
| 600 | - /// carries plans and assignments written before the counter column existed, | ||
| 601 | - /// and an absent counter reads as **zero** — which is exactly the value | ||
| 602 | - /// that licenses an edit and a delete. Unseeded, every already-assigned | ||
| 603 | - /// plan on every existing volume would go editable and deletable again, so | ||
| 604 | - /// the backfill is the whole of the stale-data story, not a nicety. | ||
| 605 | - #[tokio::test] | ||
| 606 | - async fn a_plan_assigned_before_the_counter_existed_is_still_refused() { | ||
| 607 | - use crate::db::fee_plan; | ||
| 608 | - use crate::domain::fee_plan::{FeePlanId, FeePlanName}; | ||
| 609 | - use crate::error::AppError; | ||
| 610 | - | ||
| 611 | - let db = super::init_mem().await.unwrap(); | ||
| 612 | - // The old shape: rows stating every column the older binary knew, and | ||
| 613 | - // no `assignment_count` at all. `used` carries an assignment, `free` | ||
| 614 | - // does not — a plan nobody is on must stay editable. | ||
| 615 | - db.query( | ||
| 616 | - "CREATE user:m SET username = 'm', password_hash = 'x'; | ||
| 617 | - CREATE user:s SET username = 's', password_hash = 'x'; | ||
| 618 | - CREATE fee_plan:used SET name = 'Yearly', | ||
| 619 | - installments = [{ amount_minor: 100, due_at: 1 }], | ||
| 620 | - created_by = user:m, created_at = 1; | ||
| 621 | - CREATE fee_plan:free SET name = 'Unused', | ||
| 622 | - installments = [{ amount_minor: 100, due_at: 1 }], | ||
| 623 | - created_by = user:m, created_at = 1; | ||
| 624 | - CREATE fee_plan_assignment:used_s SET plan = fee_plan:used, | ||
| 625 | - student = user:s, assigned_by = user:m, created_at = 1;", | ||
| 626 | - ) | ||
| 627 | - .await | ||
| 628 | - .unwrap() | ||
| 629 | - .check() | ||
| 630 | - .unwrap(); | ||
| 631 | - | ||
| 632 | - // Twice: every boot runs the backfill, and a second pass must not | ||
| 633 | - // double a counter it already seeded. | ||
| 634 | - super::migrate(&db).await.unwrap(); | ||
| 635 | - super::migrate(&db).await.unwrap(); | ||
| 636 | - | ||
| 637 | - let mut counts = db | ||
| 638 | - .query("SELECT VALUE assignment_count FROM fee_plan ORDER BY id") | ||
| 639 | - .await | ||
| 640 | - .unwrap(); | ||
| 641 | - let counts: Vec<Option<i64>> = counts.take(0).unwrap(); | ||
| 642 | - // `free` before `used` by id; the unused plan is deliberately left | ||
| 643 | - // absent, which already reads as zero in the guard. | ||
| 644 | - assert_eq!(counts, vec![None, Some(1)]); | ||
| 645 | - | ||
| 646 | - // The load-bearing half: the seeded plan is frozen, and the untouched | ||
| 647 | - // one is not. | ||
| 648 | - let used = fee_plan::read(&db, &FeePlanId::from_key("used")) | ||
| 649 | - .await | ||
| 650 | - .unwrap() | ||
| 651 | - .unwrap(); | ||
| 652 | - assert!(matches!( | ||
| 653 | - fee_plan::update( | ||
| 654 | - &db, | ||
| 655 | - used.clone(), | ||
| 656 | - Some(FeePlanName::try_new("Edited").unwrap()), | ||
| 657 | - None | ||
| 658 | - ) | ||
| 659 | - .await, | ||
| 660 | - Err(AppError::Conflict(_)) | ||
| 661 | - )); | ||
| 662 | - assert!(!fee_plan::delete(&db, used).await.unwrap()); | ||
| 663 | - let free = fee_plan::read(&db, &FeePlanId::from_key("free")) | ||
| 664 | - .await | ||
| 665 | - .unwrap() | ||
| 666 | - .unwrap(); | ||
| 667 | - assert!( | ||
| 668 | - fee_plan::update( | ||
| 669 | - &db, | ||
| 670 | - free.clone(), | ||
| 671 | - Some(FeePlanName::try_new("Edited").unwrap()), | ||
| 672 | - None | ||
| 673 | - ) | ||
| 674 | - .await | ||
| 675 | - .is_ok() | ||
| 676 | - ); | ||
| 677 | - assert!(fee_plan::delete(&db, free).await.unwrap()); | ||
| 678 | - } | ||
| 679 | - | ||
| 680 | - /// Stale-data path for the 2026-08-02 board-roster repair. `set_role` | ||
| 681 | - /// sweeps a demoted user off every board going forward, but an existing | ||
| 682 | - /// volume still names parents on rosters — and ids of users deleted before | ||
| 683 | - /// any sweep existed. Both freeze the creator's roster `PATCH` at a 400 | ||
| 684 | - /// (see `web::boards::resolve_participants`), so boot has to clean them. | ||
| 685 | - #[tokio::test] | ||
| 686 | - async fn a_board_roster_written_before_the_sweep_is_repaired_at_boot() { | ||
| 687 | - let db = super::init_mem().await.unwrap(); | ||
| 688 | - db.query( | ||
| 689 | - "CREATE user:s SET username = 's', password_hash = 'x', role = 'student'; | ||
| 690 | - CREATE user:p SET username = 'p', password_hash = 'x', role = 'parent'; | ||
| 691 | - CREATE board:keep SET creator = user:s, title = 'B', | ||
| 692 | - participants = [user:s, user:p, user:ghost], created_at = 1; | ||
| 693 | - CREATE board:gone SET creator = user:s, title = 'C', | ||
| 694 | - participants = [user:p], created_at = 1; | ||
| 695 | - CREATE board:clean SET creator = user:s, title = 'D', | ||
| 696 | - participants = [user:s], created_at = 1; | ||
| 697 | - DELETE migration_mark:board_roster;", | ||
| 698 | - ) | ||
| 699 | - .await | ||
| 700 | - .unwrap() | ||
| 701 | - .check() | ||
| 702 | - .unwrap(); | ||
| 703 | - // `init_mem` boots a *migrated* database, so it has already marked the | ||
| 704 | - // repair done on an empty store — which is right, and is exactly why the | ||
| 705 | - // mark is dropped here: a volume written before the mark existed carries | ||
| 706 | - // stale rosters and no mark at all, and that is the state under test. | ||
| 707 | - // A write probe on the table under repair: the event fires *inside* the | ||
| 708 | - // UPDATE, so it counts real writes rather than trusting a re-read. | ||
| 709 | - db.query( | ||
| 710 | - "DEFINE TABLE board_write_probe SCHEMALESS; | ||
| 711 | - DEFINE EVENT board_write ON board WHEN $event = 'UPDATE' THEN { | ||
| 712 | - UPSERT type::record('board_write_probe', 'n') SET n = (n ?? 0) + 1; | ||
| 713 | - };", | ||
| 714 | - ) | ||
| 715 | - .await | ||
| 716 | - .unwrap() | ||
| 717 | - .check() | ||
| 718 | - .unwrap(); | ||
| 719 | - | ||
| 720 | - super::migrate(&db).await.unwrap(); | ||
| 721 | - | ||
| 722 | - async fn rosters(db: &super::Database) -> Vec<Vec<surrealdb::types::RecordId>> { | ||
| 723 | - let mut rows = db | ||
| 724 | - .query("SELECT VALUE participants FROM board ORDER BY id") | ||
| 725 | - .await | ||
| 726 | - .unwrap(); | ||
| 727 | - rows.take(0).unwrap() | ||
| 728 | - } | ||
| 729 | - let after_first = rosters(&db).await; | ||
| 730 | - let s = surrealdb::types::RecordId::new("user", "s"); | ||
| 731 | - // `clean`, `gone`, `keep` by id. The parent and the vanished user are | ||
| 732 | - // both gone; a board whose whole roster was stale ends empty, which is | ||
| 733 | - // the same shape a board opened without invites carries. | ||
| 734 | - assert_eq!( | ||
| 735 | - after_first, | ||
| 736 | - vec![vec![s.clone()], vec![], vec![s.clone()]], | ||
| 737 | - "{after_first:?}" | ||
| 738 | - ); | ||
| 739 | - | ||
| 740 | - async fn writes(db: &super::Database) -> Vec<i64> { | ||
| 741 | - let mut rows = db | ||
| 742 | - .query("SELECT VALUE n FROM board_write_probe:n") | ||
| 743 | - .await | ||
| 744 | - .unwrap(); | ||
| 745 | - rows.take(0).unwrap() | ||
| 746 | - } | ||
| 747 | - assert_eq!( | ||
| 748 | - writes(&db).await, | ||
| 749 | - vec![2], | ||
| 750 | - "only the two stale rows repaired" | ||
| 751 | - ); | ||
| 752 | - | ||
| 753 | - // The second boot: every boot runs the backfill, and a converged row | ||
| 754 | - // must not be written again. | ||
| 755 | - super::migrate(&db).await.unwrap(); | ||
| 756 | - assert_eq!(rosters(&db).await, after_first); | ||
| 757 | - assert_eq!(writes(&db).await, vec![2], "the second pass wrote nothing"); | ||
| 758 | - | ||
| 759 | - // …and it did not *look*, either, which is the whole point of the mark: | ||
| 760 | - // the repair's cost is a `user` table scan per board, and writing | ||
| 761 | - // nothing is not the same as scanning nothing. A roster made stale after | ||
| 762 | - // the mark landed is the probe — it survives the next boot untouched, | ||
| 763 | - // which no converging `WHERE` could produce. | ||
| 764 | - let mut mark = db | ||
| 765 | - .query("SELECT VALUE done_at FROM migration_mark:board_roster") | ||
| 766 | - .await | ||
| 767 | - .unwrap(); | ||
| 768 | - assert_eq!( | ||
| 769 | - mark.take::<Vec<i64>>(0).unwrap().len(), | ||
| 770 | - 1, | ||
| 771 | - "the repair marks itself finished" | ||
| 772 | - ); | ||
| 773 | - // …with the fingerprint of the text it ran, which is what a later edit | ||
| 774 | - // to this block is compared against. | ||
| 775 | - assert_eq!( | ||
| 776 | - stamped_fingerprint(&db, "board_roster").await, | ||
| 777 | - vec![Some(expected_fingerprint("board_roster"))] | ||
| 778 | - ); | ||
| 779 | - db.query("CREATE board:late SET creator = user:s, title = 'E', participants = [user:p], created_at = 1") | ||
| 780 | - .await | ||
| 781 | - .unwrap() | ||
| 782 | - .check() | ||
| 783 | - .unwrap(); | ||
| 784 | - super::migrate(&db).await.unwrap(); | ||
| 785 | - assert_eq!( | ||
| 786 | - rosters(&db).await, | ||
| 787 | - vec![ | ||
| 788 | - vec![s.clone()], | ||
| 789 | - vec![], | ||
| 790 | - vec![s.clone()], | ||
| 791 | - vec![surrealdb::types::RecordId::new("user", "p")] | ||
| 792 | - ], | ||
| 793 | - "a marked database skips the scan entirely" | ||
| 794 | - ); | ||
| 795 | - assert_eq!(writes(&db).await, vec![2]); | ||
| 796 | - } | ||
| 797 | - | ||
| 798 | - /// Stale-data path for the 2026-08-04 badge counters. Every account on an | ||
| 799 | - /// existing volume predates the columns, and a badge is decided off the | ||
| 800 | - /// stored total — so a zero start would not lose a number, it would | ||
| 801 | - /// permanently mis-award the student who really did the work. Boot seeds the | ||
| 802 | - /// counters from the rows that exist, exactly once. | ||
| 803 | - #[tokio::test] | ||
| 804 | - async fn the_badge_counters_are_seeded_from_history_exactly_once() { | ||
| 805 | - let db = super::init_mem().await.unwrap(); | ||
| 806 | - db.query( | ||
| 807 | - "CREATE user:a SET username = 'a', password_hash = 'x', role = 'student'; | ||
| 808 | - CREATE user:b SET username = 'b', password_hash = 'x', role = 'student'; | ||
| 809 | - CREATE user:c SET username = 'c', password_hash = 'x', role = 'student'; | ||
| 810 | - CREATE homework:h SET course = course:c, subject = subject:s, title = 'H', | ||
| 811 | - due_at = 100, created_by = user:a, created_at = 1; | ||
| 812 | - -- Three on time (the equal case counts as on time) and one whose | ||
| 813 | - -- homework was deleted out from under it: that last one is | ||
| 814 | - -- submitted but not on time, because the traversal yields nothing. | ||
| 815 | - CREATE homework_submission:s1 SET homework = homework:h, user = user:a, | ||
| 816 | - submitted_at = 50, updated_at = 50; | ||
| 817 | - CREATE homework_submission:s2 SET homework = homework:h, user = user:a, | ||
| 818 | - submitted_at = 60, updated_at = 100; | ||
| 819 | - -- Handed in before the deadline, then edited well after it — a | ||
| 820 | - -- `touch()` from a single file add does this. On time, because the | ||
| 821 | - -- live path credits the hand-in and debits by `submitted_at`; if | ||
| 822 | - -- the seed judged this one by `updated_at` a later withdrawal | ||
| 823 | - -- would decrement a credit that was never given. | ||
| 824 | - CREATE homework_submission:s3 SET homework = homework:h, user = user:a, | ||
| 825 | - submitted_at = 70, updated_at = 200; | ||
| 826 | - CREATE homework_submission:s4 SET homework = homework:gone, user = user:a, | ||
| 827 | - submitted_at = 80, updated_at = 1; | ||
| 828 | - CREATE exam_attempt:e1 SET exam = exam:x, user = user:a, seq = 1, started_at = 1; | ||
| 829 | - CREATE exam_attempt:e2 SET exam = exam:y, user = user:a, seq = 1, started_at = 2; | ||
| 830 | - -- Two finished stints and one still open, which counts for neither. | ||
| 831 | - CREATE pomodoro_session:p1 SET user = user:a, started_at = 1000, finished_at = 2000; | ||
| 832 | - CREATE pomodoro_session:p2 SET user = user:a, started_at = 5000, finished_at = 7500; | ||
| 833 | - CREATE pomodoro_session:p3 SET user = user:a, started_at = 9000; | ||
| 834 | - -- One real stint beside one written with a backwards clock. The | ||
| 835 | - -- floor is per row, like the live close, so the negative one | ||
| 836 | - -- contributes zero and the real 1000ms survives; flooring the | ||
| 837 | - -- per-user sum instead would seed 0 and lose the real stint. | ||
| 838 | - CREATE pomodoro_session:p4 SET user = user:c, started_at = 0, finished_at = 1000; | ||
| 839 | - CREATE pomodoro_session:p5 SET user = user:c, started_at = 9000, finished_at = 3000; | ||
| 840 | - DELETE migration_mark:profile_counters;", | ||
| 841 | - ) | ||
| 842 | - .await | ||
| 843 | - .unwrap() | ||
| 844 | - .check() | ||
| 845 | - .unwrap(); | ||
| 846 | - // `init_mem` boots a *migrated* database, so the seed is already marked | ||
| 847 | - // done on an empty store — which is right, and is exactly why the mark is | ||
| 848 | - // dropped here: a volume written before the columns existed carries | ||
| 849 | - // history and no mark at all, and that is the state under test. | ||
| 850 | - // A write probe on the table being seeded: the event fires *inside* the | ||
| 851 | - // UPDATE, so it counts real writes rather than trusting a re-read. | ||
| 852 | - db.query( | ||
| 853 | - "DEFINE TABLE user_write_probe SCHEMALESS; | ||
| 854 | - DEFINE EVENT user_write ON user WHEN $event = 'UPDATE' THEN { | ||
| 855 | - UPSERT type::record('user_write_probe', 'n') SET n = (n ?? 0) + 1; | ||
| 856 | - };", | ||
| 857 | - ) | ||
| 858 | - .await | ||
| 859 | - .unwrap() | ||
| 860 | - .check() | ||
| 861 | - .unwrap(); | ||
| 862 | - | ||
| 863 | - super::migrate(&db).await.unwrap(); | ||
| 864 | - | ||
| 865 | - async fn counters(db: &super::Database) -> Vec<(i64, i64, i64, i64, i64)> { | ||
| 866 | - let mut rows = db | ||
| 867 | - .query( | ||
| 868 | - "SELECT VALUE [homework_submitted_total, homework_on_time_total, | ||
| 869 | - exam_sat_total, pomodoro_finished_total, | ||
| 870 | - pomodoro_focus_ms_total] | ||
| 871 | - FROM user ORDER BY id", | ||
| 872 | - ) | ||
| 873 | - .await | ||
| 874 | - .unwrap(); | ||
| 875 | - rows.take::<Vec<Vec<i64>>>(0) | ||
| 876 | - .unwrap() | ||
| 877 | - .into_iter() | ||
| 878 | - .map(|row| (row[0], row[1], row[2], row[3], row[4])) | ||
| 879 | - .collect() | ||
| 880 | - } | ||
| 881 | - let after_first = counters(&db).await; | ||
| 882 | - // `a`, `b`, `c` by id. `b` has no history at all and reads as a fresh | ||
| 883 | - // account; `c` keeps the 1000ms real stint the -6000ms one sits beside. | ||
| 884 | - assert_eq!( | ||
| 885 | - after_first, | ||
| 886 | - vec![(4, 3, 2, 2, 3500), (0, 0, 0, 0, 0), (0, 0, 0, 2, 1000)], | ||
| 887 | - "{after_first:?}" | ||
| 888 | - ); | ||
| 889 | - | ||
| 890 | - // The seed also stamps each submission with the verdict it was counted | ||
| 891 | - // under, because `due_at` is mutable: a withdrawal after the teacher | ||
| 892 | - // moves the deadline must debit what was credited, not what the | ||
| 893 | - // deadline says by then. Asserted through `WHERE` rather than read back | ||
| 894 | - // as a column, so an unstamped row would show up as belonging to | ||
| 895 | - // neither set instead of deserializing as some default. | ||
| 896 | - async fn stamped(db: &super::Database, cond: &str) -> Vec<String> { | ||
| 897 | - let mut rows = db | ||
| 898 | - .query(format!( | ||
| 899 | - "SELECT VALUE record::id(id) FROM homework_submission | ||
| 900 | - WHERE {cond} ORDER BY id" | ||
| 901 | - )) | ||
| 902 | - .await | ||
| 903 | - .unwrap(); | ||
| 904 | - rows.take(0).unwrap() | ||
| 905 | - } | ||
| 906 | - // s1/s2/s3 beat the deadline (50, 60, 70 vs 100). s4 hangs off a | ||
| 907 | - // deleted homework, so `submitted_at <= homework.due_at` compares | ||
| 908 | - // against NONE and lands on `false` — which is exactly what the count | ||
| 909 | - // above credited it as, so the stamp agrees with the counter rather | ||
| 910 | - // than leaving the row to a fallback that could later disagree. | ||
| 911 | - assert_eq!( | ||
| 912 | - stamped(&db, "counted_on_time = true").await, | ||
| 913 | - ["s1", "s2", "s3"] | ||
| 914 | - ); | ||
| 915 | - assert_eq!(stamped(&db, "counted_on_time = false").await, ["s4"]); | ||
| 916 | - | ||
| 917 | - async fn writes(db: &super::Database) -> Vec<i64> { | ||
| 918 | - let mut rows = db | ||
| 919 | - .query("SELECT VALUE n FROM user_write_probe:n") | ||
| 920 | - .await | ||
| 921 | - .unwrap(); | ||
| 922 | - rows.take(0).unwrap() | ||
| 923 | - } | ||
| 924 | - let first_writes = writes(&db).await; | ||
| 925 | - // Pinned non-zero, not just compared: "the second pass wrote nothing" | ||
| 926 | - // would hold vacuously if the probe itself stopped firing, and then the | ||
| 927 | - // test would pass on a seed that never ran. | ||
| 928 | - assert!( | ||
| 929 | - matches!(first_writes.as_slice(), [n] if *n > 0), | ||
| 930 | - "{first_writes:?}" | ||
| 931 | - ); | ||
| 932 | - | ||
| 933 | - // The second boot: every boot runs the backfill, and a recount here | ||
| 934 | - // would not converge the way the counters above it do — these columns | ||
| 935 | - // are maintained by the request path from now on, so a second pass would | ||
| 936 | - // overwrite everything earned since. It must not write at all… | ||
| 937 | - super::migrate(&db).await.unwrap(); | ||
| 938 | - assert_eq!(counters(&db).await, after_first); | ||
| 939 | - assert_eq!( | ||
| 940 | - writes(&db).await, | ||
| 941 | - first_writes, | ||
| 942 | - "the second pass wrote nothing" | ||
| 943 | - ); | ||
| 944 | - | ||
| 945 | - // …and it must not *look*, either, which is the whole point of the mark: | ||
| 946 | - // writing nothing is not the same as scanning nothing. A submission that | ||
| 947 | - // lands after the mark is the probe — its counter stays where the request | ||
| 948 | - // path left it, which no recomputing backfill could produce. | ||
| 949 | - let mut mark = db | ||
| 950 | - .query("SELECT VALUE done_at FROM migration_mark:profile_counters") | ||
| 951 | - .await | ||
| 952 | - .unwrap(); | ||
| 953 | - assert_eq!( | ||
| 954 | - mark.take::<Vec<i64>>(0).unwrap().len(), | ||
| 955 | - 1, | ||
| 956 | - "the seed marks itself finished" | ||
| 957 | - ); | ||
| 958 | - assert_eq!( | ||
| 959 | - stamped_fingerprint(&db, "profile_counters").await, | ||
| 960 | - vec![Some(expected_fingerprint("profile_counters"))] | ||
| 961 | - ); | ||
| 962 | - db.query( | ||
| 963 | - "CREATE homework_submission:late SET homework = homework:h, user = user:b, | ||
| 964 | - submitted_at = 90, updated_at = 90;", | ||
| 965 | - ) | ||
| 966 | - .await | ||
| 967 | - .unwrap() | ||
| 968 | - .check() | ||
| 969 | - .unwrap(); | ||
| 970 | - super::migrate(&db).await.unwrap(); | ||
| 971 | - assert_eq!( | ||
| 972 | - counters(&db).await, | ||
| 973 | - after_first, | ||
| 974 | - "a mark carrying this binary's fingerprint skips the seed entirely" | ||
| 975 | - ); | ||
| 976 | - assert_eq!(writes(&db).await, first_writes); | ||
| 977 | - } | ||
| 978 | - | ||
| 979 | - /// A marked block's *content* has to be correctable (2026-08-05). The mark | ||
| 980 | - /// used to record only that the block had run, so an edit to a marked block | ||
| 981 | - /// silently never ran on any volume that had booted once — which is how the | ||
| 982 | - /// `exam_sat_total` seed below (fixed to count sittings, not attempts) | ||
| 983 | - /// would have reached exactly nobody. The mark carries the fingerprint of | ||
| 984 | - /// the text it ran, and a different fingerprint runs the block once more. | ||
| 985 | - #[tokio::test] | ||
| 986 | - async fn an_edited_one_time_block_runs_once_more_and_restamps() { | ||
| 987 | - let db = super::init_mem().await.unwrap(); | ||
| 988 | - // `init_mem` migrates an empty store, so the seed is already marked | ||
| 989 | - // done — the state every booted volume is in. History written *after* | ||
| 990 | - // that mark is the probe: a skip has to leave it uncounted, and a | ||
| 991 | - // re-run has to pick it up. | ||
| 992 | - db.query( | ||
| 993 | - "CREATE user:a SET username = 'a', password_hash = 'x', role = 'student'; | ||
| 994 | - -- One sitting, taken twice. The corrected seed counts the exam, | ||
| 995 | - -- not the attempts, exactly as the request path credits it. | ||
| 996 | - CREATE exam_attempt:e1 SET exam = exam:x, user = user:a, seq = 1, started_at = 1; | ||
| 997 | - CREATE exam_attempt:e2 SET exam = exam:x, user = user:a, seq = 2, started_at = 2; | ||
| 998 | - CREATE pomodoro_session:p1 SET user = user:a, started_at = 1000, finished_at = 2000;", | ||
| 999 | - ) | ||
| 1000 | - .await | ||
| 1001 | - .unwrap() | ||
| 1002 | - .check() | ||
| 1003 | - .unwrap(); | ||
| 1004 | - | ||
| 1005 | - async fn counters(db: &super::Database) -> Vec<(i64, i64)> { | ||
| 1006 | - let mut rows = db | ||
| 1007 | - .query( | ||
| 1008 | - // `?? 0`, parenthesized: the columns are `option<int>` and | ||
| 1009 | - // a row the seed has not touched holds neither. | ||
| 1010 | - "SELECT VALUE [(exam_sat_total ?? 0), (pomodoro_finished_total ?? 0)] | ||
| 1011 | - FROM user ORDER BY id", | ||
| 1012 | - ) | ||
| 1013 | - .await | ||
| 1014 | - .unwrap(); | ||
| 1015 | - rows.take::<Vec<Vec<i64>>>(0) | ||
| 1016 | - .unwrap() | ||
| 1017 | - .into_iter() | ||
| 1018 | - .map(|row| (row[0], row[1])) | ||
| 1019 | - .collect() | ||
| 1020 | - } | ||
| 1021 | - let fp = expected_fingerprint("profile_counters"); | ||
| 1022 | - | ||
| 1023 | - // Same binary, same fingerprint: the block does not run, and the | ||
| 1024 | - // history above stays uncounted. That is the mark still doing its job. | ||
| 1025 | - super::migrate(&db).await.unwrap(); | ||
| 1026 | - assert_eq!(counters(&db).await, vec![(0, 0)]); | ||
| 1027 | - assert_eq!( | ||
| 1028 | - stamped_fingerprint(&db, "profile_counters").await, | ||
| 1029 | - vec![Some(fp)] | ||
| 1030 | - ); | ||
| 1031 | - | ||
| 1032 | - // A write probe on the seeded table, defined now so it counts only the | ||
| 1033 | - // runs under test: the event fires *inside* the UPDATE, so "exactly | ||
| 1034 | - // once" is measured rather than inferred from the numbers. | ||
| 1035 | - db.query( | ||
| 1036 | - "DEFINE TABLE user_write_probe SCHEMALESS; | ||
| 1037 | - DEFINE EVENT user_write ON user WHEN $event = 'UPDATE' THEN { | ||
| 1038 | - UPSERT type::record('user_write_probe', 'n') SET n = (n ?? 0) + 1; | ||
| 1039 | - }; | ||
| 1040 | - -- A mark written by the binary before fingerprints existed: the | ||
| 1041 | - -- row is there, the column is not. This is the live volumes' | ||
| 1042 | - -- state, and it must run the corrected block exactly once. | ||
| 1043 | - UPDATE migration_mark:profile_counters UNSET fingerprint;", | ||
| 1044 | - ) | ||
| 1045 | - .await | ||
| 1046 | - .unwrap() | ||
| 1047 | - .check() | ||
| 1048 | - .unwrap(); | ||
| 1049 | - assert_eq!( | ||
| 1050 | - stamped_fingerprint(&db, "profile_counters").await, | ||
| 1051 | - vec![None] | ||
| 1052 | - ); | ||
| 1053 | - | ||
| 1054 | - super::migrate(&db).await.unwrap(); | ||
| 1055 | - // Two attempt rows, one exam: the corrected seed says one sitting, the | ||
| 1056 | - // number the request path would have given. The old text said two. | ||
| 1057 | - assert_eq!(counters(&db).await, vec![(1, 1)]); | ||
| 1058 | - assert_eq!( | ||
| 1059 | - stamped_fingerprint(&db, "profile_counters").await, | ||
| 1060 | - vec![Some(fp)] | ||
| 1061 | - ); | ||
| 1062 | - | ||
| 1063 | - async fn writes(db: &super::Database) -> Vec<i64> { | ||
| 1064 | - let mut rows = db | ||
| 1065 | - .query("SELECT VALUE n FROM user_write_probe:n") | ||
| 1066 | - .await | ||
| 1067 | - .unwrap(); | ||
| 1068 | - rows.take(0).unwrap() | ||
| 1069 | - } | ||
| 1070 | - let one_run = writes(&db).await; | ||
| 1071 | - // Pinned non-zero, not merely compared: "it did not run twice" holds | ||
| 1072 | - // vacuously if the probe stopped firing, and the test would then pass | ||
| 1073 | - // on a mechanism that never runs anything at all. | ||
| 1074 | - assert!(matches!(one_run.as_slice(), [n] if *n > 0), "{one_run:?}"); | ||
| 1075 | - | ||
| 1076 | - // Once more, not on every boot: the re-run re-stamped, so the next boot | ||
| 1077 | - // is a plain skip again. | ||
| 1078 | - super::migrate(&db).await.unwrap(); | ||
| 1079 | - assert_eq!(counters(&db).await, vec![(1, 1)]); | ||
| 1080 | - assert_eq!(writes(&db).await, one_run, "the re-run happened once"); | ||
| 1081 | - | ||
| 1082 | - // And now the edit this whole mechanism exists for: a mark whose stored | ||
| 1083 | - // fingerprint is some *other* text's. The block runs again and lands on | ||
| 1084 | - // the same numbers — every SET is absolute, so a re-run converges | ||
| 1085 | - // instead of doubling what the first pass wrote. | ||
| 1086 | - db.query("UPDATE migration_mark:profile_counters SET fingerprint = 1") | ||
| 1087 | - .await | ||
| 1088 | - .unwrap() | ||
| 1089 | - .check() | ||
| 1090 | - .unwrap(); | ||
| 1091 | - super::migrate(&db).await.unwrap(); | ||
| 1092 | - assert_eq!( | ||
| 1093 | - counters(&db).await, | ||
| 1094 | - vec![(1, 1)], | ||
| 1095 | - "a re-run recomputes, it does not add to what is there" | ||
| 1096 | - ); | ||
| 1097 | - assert_eq!( | ||
| 1098 | - writes(&db).await, | ||
| 1099 | - vec![one_run[0] * 2], | ||
| 1100 | - "the edited block did the same work a second time, and no more" | ||
| 1101 | - ); | ||
| 1102 | - assert_eq!( | ||
| 1103 | - stamped_fingerprint(&db, "profile_counters").await, | ||
| 1104 | - vec![Some(fp)] | ||
| 1105 | - ); | ||
| 1106 | - super::migrate(&db).await.unwrap(); | ||
| 1107 | - assert_eq!(writes(&db).await, vec![one_run[0] * 2], "and stopped again"); | ||
| 1108 | - } | ||
| 1109 | - | ||
| 1110 | - #[tokio::test] | ||
| 1111 | - async fn the_retired_claim_columns_are_dropped_off_a_live_row() { | ||
| 1112 | - // Stale-data path for the 2026-07-30 removal of the chat claim queue. | ||
| 1113 | - // A dev volume carries `chatbot_message` rows *with* claim values and an | ||
| 1114 | - // `ai_worker` table, so the boot has to clear the values while their | ||
| 1115 | - // definitions still stand (PRE_REPAIR) and only then retire the columns | ||
| 1116 | - // — SCHEMAFULL rejects every write to a row storing a column that no | ||
| 1117 | - // longer exists, which would make the row unanswerable forever. | ||
| 1118 | - let db = super::init_mem().await.unwrap(); | ||
| 1119 | - db.query( | ||
| 1120 | - "DEFINE FIELD claimed_by ON chatbot_message TYPE option<string>; | ||
| 1121 | - DEFINE FIELD claimed_at ON chatbot_message TYPE option<int>; | ||
| 1122 | - DEFINE TABLE ai_worker SCHEMAFULL; | ||
| 1123 | - DEFINE FIELD seen_at ON ai_worker TYPE int; | ||
| 1124 | - DEFINE TABLE migration_lock SCHEMALESS;", | ||
| 1125 | - ) | ||
| 1126 | - .await | ||
| 1127 | - .unwrap() | ||
| 1128 | - .check() | ||
| 1129 | - .unwrap(); | ||
| 1130 | - db.query( | ||
| 1131 | - "CREATE user:u SET username = 'u', password_hash = 'x'; | ||
| 1132 | - CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1; | ||
| 1133 | - CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u, | ||
| 1134 | - role = 'assistant', content = '', status = 'pending', | ||
| 1135 | - created_at = time::unix(time::now()) * 1000, | ||
| 1136 | - claimed_by = 'a-dead-replica', claimed_at = 1; | ||
| 1137 | - CREATE ai_worker:w SET seen_at = 1; | ||
| 1138 | - CREATE migration_lock:the_lock SET holder = 'a-dead-replica', expires_at = 1;", | ||
| 1139 | - ) | ||
| 1140 | - .await | ||
| 1141 | - .unwrap() | ||
| 1142 | - .check() | ||
| 1143 | - .unwrap(); | ||
| 1144 | - | ||
| 1145 | - // Twice: the repair and both removals have to be idempotent, since | ||
| 1146 | - // every boot runs them. | ||
| 1147 | - super::migrate(&db).await.unwrap(); | ||
| 1148 | - super::migrate(&db).await.unwrap(); | ||
| 1149 | - | ||
| 1150 | - let mut info = db.query("INFO FOR TABLE chatbot_message").await.unwrap(); | ||
| 1151 | - let table: serde_json::Value = info.take::<Option<serde_json::Value>>(0).unwrap().unwrap(); | ||
| 1152 | - let fields = table["fields"].as_object().expect("fields"); | ||
| 1153 | - assert!(!fields.contains_key("claimed_by"), "{table}"); | ||
| 1154 | - assert!(!fields.contains_key("claimed_at"), "{table}"); | ||
| 1155 | - let mut tables = db.query("INFO FOR DB").await.unwrap(); | ||
| 1156 | - let dbinfo: serde_json::Value = tables | ||
| 1157 | - .take::<Option<serde_json::Value>>(0) | ||
| 1158 | - .unwrap() | ||
| 1159 | - .unwrap(); | ||
| 1160 | - let tables = dbinfo["tables"].as_object().expect("tables"); | ||
| 1161 | - assert!(!tables.contains_key("ai_worker"), "{dbinfo}"); | ||
| 1162 | - // Same story one table over: the elected-boot lease, stale leader row | ||
| 1163 | - // and all. | ||
| 1164 | - assert!(!tables.contains_key("migration_lock"), "{dbinfo}"); | ||
| 1165 | - | ||
| 1166 | - // The load-bearing half: the row that carried a claim is still | ||
| 1167 | - // writable. A leftover value under no definition fails here. | ||
| 1168 | - db.query("UPDATE chatbot_message:m SET status = 'complete', content = 'ok'") | ||
| 1169 | - .await | ||
| 1170 | - .unwrap() | ||
| 1171 | - .check() | ||
| 1172 | - .unwrap(); | ||
| 1173 | - let mut row = db | ||
| 1174 | - .query("SELECT * FROM ONLY chatbot_message:m") | ||
| 1175 | - .await | ||
| 1176 | - .unwrap(); | ||
| 1177 | - let row: serde_json::Value = row.take::<Option<serde_json::Value>>(0).unwrap().unwrap(); | ||
| 1178 | - assert_eq!(row["status"], "complete", "{row}"); | ||
| 1179 | - assert!(row.get("claimed_by").is_none(), "{row}"); | ||
| 1180 | - } | ||
| 1181 | - | ||
| 1182 | - /// The other half of the sweep: a restart seconds after a dispatch must not | ||
| 1183 | - /// kill the turn — the answering task may still be alive on the other side | ||
| 1184 | - /// of the bridge, and the row is not yet past the stale horizon. | ||
| 1185 | - #[tokio::test] | ||
| 1186 | - async fn boot_spares_a_chatbot_message_pending_since_just_now() { | ||
| 1187 | - let db = super::init_mem().await.unwrap(); | ||
| 1188 | - db.query( | ||
| 1189 | - "CREATE user:u SET username = 'u', password_hash = 'x'; | ||
| 1190 | - CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1; | ||
| 1191 | - CREATE chatbot_message:fresh SET thread_id = chatbot_thread:c, user_id = user:u, | ||
| 1192 | - role = 'assistant', content = '', status = 'pending', | ||
| 1193 | - created_at = time::unix(time::now()) * 1000 - 2000; | ||
| 1194 | - CREATE chatbot_message:old SET thread_id = chatbot_thread:c, user_id = user:u, | ||
| 1195 | - role = 'assistant', content = '', status = 'pending', | ||
| 1196 | - created_at = time::unix(time::now()) * 1000 | ||
| 1197 | - - ($stale + 1) * 1000;", | ||
| 1198 | - ) | ||
| 1199 | - .bind(("stale", crate::constant::CHATBOT_PENDING_STALE_SECS)) | ||
| 1200 | - .await | ||
| 1201 | - .unwrap() | ||
| 1202 | - .check() | ||
| 1203 | - .unwrap(); | ||
| 1204 | - | ||
| 1205 | - super::migrate(&db).await.unwrap(); | ||
| 1206 | - | ||
| 1207 | - let mut res = db | ||
| 1208 | - .query( | ||
| 1209 | - "SELECT status, error_code FROM ONLY chatbot_message:fresh; | ||
| 1210 | - SELECT VALUE status FROM ONLY chatbot_message:old;", | ||
| 1211 | - ) | ||
| 1212 | - .await | ||
| 1213 | - .unwrap(); | ||
| 1214 | - let fresh: Option<serde_json::Value> = res.take(0).unwrap(); | ||
| 1215 | - let fresh = fresh.unwrap(); | ||
| 1216 | - let old: Option<String> = res.take(1).unwrap(); | ||
| 1217 | - assert_eq!( | ||
| 1218 | - fresh["status"], "pending", | ||
| 1219 | - "a two-second-old turn is still being answered" | ||
| 1220 | - ); | ||
| 1221 | - assert_eq!(fresh["error_code"], serde_json::Value::Null); | ||
| 1222 | - assert_eq!(old.as_deref(), Some("failed"), "past the horizon it goes"); | ||
| 1223 | - } | ||
| 1224 | - | ||
| 1225 | - /// A row written before choices had ids survives the retyped columns: it is | ||
| 1226 | - /// converted, it is writable again, and its stored *position* still names | ||
| 1227 | - /// the same option — a wrong remap here silently regrades exams. | ||
| 1228 | - #[tokio::test] | ||
| 1229 | - async fn boot_converts_positional_choices_and_keeps_the_same_option() { | ||
| 1230 | - let db = super::init_mem().await.unwrap(); | ||
| 1231 | - // Roll the columns back to their pre-2026-07-24 shapes and write the | ||
| 1232 | - // kind of row an older binary left behind, `source_bank` included. | ||
| 1233 | - db.query( | ||
| 1234 | - "REMOVE FIELD IF EXISTS choices[*].id ON TABLE exam_question; | ||
| 1235 | - REMOVE FIELD IF EXISTS choices[*].text ON TABLE exam_question; | ||
| 1236 | - REMOVE FIELD IF EXISTS choices[*].id ON TABLE bank_question; | ||
| 1237 | - REMOVE FIELD IF EXISTS choices[*].text ON TABLE bank_question; | ||
| 1238 | - DEFINE FIELD OVERWRITE choices ON exam_question TYPE option<array<string>>; | ||
| 1239 | - DEFINE FIELD OVERWRITE correct ON exam_question TYPE option<int>; | ||
| 1240 | - DEFINE FIELD OVERWRITE source_bank ON exam_question TYPE option<string>; | ||
| 1241 | - DEFINE FIELD OVERWRITE slot ON question_image TYPE option<int>; | ||
| 1242 | - DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option<int>; | ||
| 1243 | - DEFINE FIELD OVERWRITE choices ON bank_question TYPE option<array<string>>; | ||
| 1244 | - DEFINE FIELD OVERWRITE correct ON bank_question TYPE option<int>; | ||
| 1245 | - DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option<int>;", | ||
| 1246 | - ) | ||
| 1247 | - .await | ||
| 1248 | - .unwrap() | ||
| 1249 | - .check() | ||
| 1250 | - .unwrap(); | ||
| 1251 | - db.query( | ||
| 1252 | - "CREATE user:u SET username = 'u', password_hash = 'x'; | ||
| 1253 | - CREATE exam_question:q SET exam = exam:e, text = 'q', kind = 'multiple', | ||
| 1254 | - points = 5, subject = subject:s, choices = ['3', '4', '5'], correct = 1, | ||
| 1255 | - source_bank = 'bank_question:b'; | ||
| 1256 | - CREATE question_image:i SET exam = exam:e, question = exam_question:q, slot = 2, | ||
| 1257 | - file = 'f', content_type = 'image/png', size = 1; | ||
| 1258 | - CREATE question_image:whole SET exam = exam:e, question = exam_question:q, | ||
| 1259 | - file = 'w', content_type = 'image/png', size = 1; | ||
| 1260 | - CREATE exam_answer:a SET exam = exam:e, question = exam_question:q, user = user:u, | ||
| 1261 | - selected = 2, updated_at = 1; | ||
| 1262 | - CREATE bank_question:b SET owner = user:u, text = 'b', kind = 'multiple', | ||
| 1263 | - points = 3, choices = ['a', 'b'], correct = 0, created_at = 1; | ||
| 1264 | - CREATE bank_question_image:bi SET bank_question = bank_question:b, slot = 1, | ||
| 1265 | - file = 'bf', content_type = 'image/png', size = 1;", | ||
| 1266 | - ) | ||
| 1267 | - .await | ||
| 1268 | - .unwrap() | ||
| 1269 | - .check() | ||
| 1270 | - .unwrap(); | ||
| 1271 | - | ||
| 1272 | - super::migrate(&db).await.unwrap(); | ||
| 1273 | - | ||
| 1274 | - let mut res = db | ||
| 1275 | - .query( | ||
| 1276 | - "SELECT choices, correct FROM ONLY exam_question:q; | ||
| 1277 | - SELECT VALUE slot FROM ONLY question_image:i; | ||
| 1278 | - SELECT VALUE slot FROM ONLY question_image:whole; | ||
| 1279 | - SELECT VALUE selected FROM ONLY exam_answer:a; | ||
| 1280 | - SELECT choices, correct FROM ONLY bank_question:b; | ||
| 1281 | - SELECT VALUE slot FROM ONLY bank_question_image:bi;", | ||
| 1282 | - ) | ||
| 1283 | - .await | ||
| 1284 | - .unwrap(); | ||
| 1285 | - let q: Option<serde_json::Value> = res.take(0).unwrap(); | ||
| 1286 | - let q = q.unwrap(); | ||
| 1287 | - let img_slot: Option<String> = res.take(1).unwrap(); | ||
| 1288 | - let whole_slot: Option<String> = res.take(2).unwrap(); | ||
| 1289 | - let selected: Option<String> = res.take(3).unwrap(); | ||
| 1290 | - let bank: Option<serde_json::Value> = res.take(4).unwrap(); | ||
| 1291 | - let bank = bank.unwrap(); | ||
| 1292 | - let bank_slot: Option<String> = res.take(5).unwrap(); | ||
| 1293 | - | ||
| 1294 | - let ids: Vec<&str> = q["choices"] | ||
| 1295 | - .as_array() | ||
| 1296 | - .unwrap() | ||
| 1297 | - .iter() | ||
| 1298 | - .map(|c| c["id"].as_str().unwrap()) | ||
| 1299 | - .collect(); | ||
| 1300 | - assert_eq!( | ||
| 1301 | - q["choices"][0]["text"], "3", | ||
| 1302 | - "option order (and so the meaning of every stored index) is preserved" | ||
| 1303 | - ); | ||
| 1304 | - assert_eq!(q["correct"], ids[1], "correct was index 1"); | ||
| 1305 | - assert_eq!( | ||
| 1306 | - img_slot.as_deref(), | ||
| 1307 | - Some(ids[2]), | ||
| 1308 | - "option picture was slot 2" | ||
| 1309 | - ); | ||
| 1310 | - assert_eq!(selected.as_deref(), Some(ids[2]), "the answer was index 2"); | ||
| 1311 | - assert_eq!(whole_slot, None, "a question-level picture has no index"); | ||
| 1312 | - let bank_ids: Vec<&str> = bank["choices"] | ||
| 1313 | - .as_array() | ||
| 1314 | - .unwrap() | ||
| 1315 | - .iter() | ||
| 1316 | - .map(|c| c["id"].as_str().unwrap()) | ||
| 1317 | - .collect(); | ||
| 1318 | - assert_eq!(bank["correct"], bank_ids[0]); | ||
| 1319 | - assert_eq!(bank_slot.as_deref(), Some(bank_ids[1])); | ||
| 1320 | - | ||
| 1321 | - // Writable again — every one of these failed coercion before the | ||
| 1322 | - // backfill existed, and `source_bank` outlived its own column. | ||
| 1323 | - db.query( | ||
| 1324 | - "UPDATE exam_question:q SET points = 7; | ||
| 1325 | - UPDATE question_image:i SET size = 2; | ||
| 1326 | - UPDATE exam_answer:a SET updated_at = 2; | ||
| 1327 | - UPDATE bank_question:b SET points = 4; | ||
| 1328 | - UPDATE bank_question_image:bi SET size = 2;", | ||
| 1329 | - ) | ||
| 1330 | - .await | ||
| 1331 | - .unwrap() | ||
| 1332 | - .check() | ||
| 1333 | - .unwrap(); | ||
| 1334 | - | ||
| 1335 | - // A second boot re-mints nothing. | ||
| 1336 | - super::migrate(&db).await.unwrap(); | ||
| 1337 | - let mut res = db | ||
| 1338 | - .query("SELECT VALUE choices.map(|$c| $c.id) FROM ONLY exam_question:q") | ||
| 1339 | - .await | ||
| 1340 | - .unwrap(); | ||
| 1341 | - let again: Vec<String> = res.take(0).unwrap(); | ||
| 1342 | - assert_eq!(again, ids, "conversion is idempotent"); | ||
| 1343 | - } | ||
| 1344 | -} | ||
src/db/cap.rsmodified+201 -1215
| @@ -1,132 +1,165 @@ | |||
| 1 | //! Count caps the database enforces, not the process. | 1 | //! Count caps the database enforces, not the process. |
| 2 | //! | 2 | //! |
| 3 | //! Every "at most N children per parent" rule used to be a count-then-write | 3 | //! Every "at most N children per parent" rule used to be a count-then-write |
| 4 | -//! under a process-wide `Mutex`, because a `BEGIN…COMMIT` cannot enforce it: | 4 | +//! under a process-wide `Mutex`, because the old store did not conflict-check |
| 5 | -//! SurrealDB does not conflict-check a cross-record `count()` against a | 5 | +//! a cross-record `count()` against a concurrent insert (write-skew): two |
| 6 | -//! concurrent insert (write-skew), so two racing writers both saw a free slot. | 6 | +//! racing writers both saw a free slot. A mutex serialized the writers, but |
| 7 | -//! A mutex serializes the writers, but only around whatever it wraps: every | 7 | +//! only around whatever it wrapped — every one of those caps held a lock |
| 8 | -//! one of those caps held a lock across a database round trip, and the count it | 8 | +//! across a database round trip, and the count it was protecting was already |
| 9 | -//! was protecting was already a guess by the time the insert landed. | 9 | +//! a guess by the time the insert landed. |
| 10 | //! | 10 | //! |
| 11 | -//! The guard that does survive is a single-record conditional write: an | 11 | +//! The guard that survives is a single-record conditional write: an |
| 12 | -//! `UPDATE … SET n += 1 WHERE n < cap` on the *parent* row is atomic, so of N | 12 | +//! `UPDATE … SET n = n + 1 WHERE n < cap` on the *parent* row is atomic, so |
| 13 | -//! concurrent claimers exactly `cap` get a non-empty result and the rest are | 13 | +//! of N concurrent claimers exactly `cap` get a non-empty result and the rest |
| 14 | -//! refused, with no lock and no window. The counter is therefore the | 14 | +//! are refused, with no lock and no window. The counter is therefore the |
| 15 | //! authority on how many slots are taken, and the child rows follow it: the | 15 | //! authority on how many slots are taken, and the child rows follow it: the |
| 16 | -//! claim and the child's insert land in one transaction ([`claim_and_create`] | 16 | +//! claim and the child's insert land in one statement (the CTE recipes |
| 17 | -//! and its variants), and a decrement rides the *same transaction* as every | 17 | +//! below), and a decrement rides the *same transaction* as every delete of a |
| 18 | -//! delete of a child row. | 18 | +//! child row. |
| 19 | //! | 19 | //! |
| 20 | -//! The counters are `option<int>` columns on the parent table, absent meaning | 20 | +//! Postgres takes over the rest of what the old builders hand-rolled: |
| 21 | -//! zero, so no Rust struct carries them and no whole-row save can clobber one | 21 | +//! |
| 22 | -//! (every parent's `.content()` write is a create of a fresh row). | 22 | +//! * **Existence proof** — a real `FOREIGN KEY` refuses a child whose parent |
| 23 | -// | 23 | +//! is gone (SQLSTATE 23503), so the old bump-and-restore "touch" trick is |
| 24 | -// corner-cut: a counter can only drift if a future delete path forgets its | 24 | +//! deleted. A gated variant ("parent must still be open") is |
| 25 | -// decrement, and the boot backfill seeds most counters once rather than | 25 | +//! `INSERT … SELECT … WHERE EXISTS (SELECT 1 FROM parent WHERE id = $n AND <gate>)`. |
| 26 | -// recomputing them. `enrollment_count` is the one that already drifted (the boot | 26 | +//! * **Duplicate detection** — the child's primary key answers "another |
| 27 | -// sweep of promoted users' rows kept their seats), so it is recomputed on every | 27 | +//! writer placed this very row first" as SQLSTATE 23505 |
| 28 | -// boot instead — see the repair in `migration_sql::BACKFILL`. That is the shape | 28 | +//! (`crate::database::unique_violation`). |
| 29 | -// to copy for any other counter drift observed: a counter whose meaning is | 29 | +//! * **Retry** — `crate::database::tx_with_retry` owns the retry loop; a |
| 30 | -// exactly "the live child rows" converges on a recompute, a lifetime tally does | 30 | +//! refusal is an `Err` from the closure and is never retried, because a |
| 31 | -// not and must stay seeded once. | 31 | +//! refusal is a decision. |
| 32 | - | 32 | +//! |
| 33 | -use surrealdb::types::{RecordId, SurrealValue}; | 33 | +//! ## The per-call-site recipes |
| 34 | -use tokio::sync::Mutex; | 34 | +//! |
| 35 | - | 35 | +//! Table, column and cap names are crate constants, so every call site writes |
| 36 | -use crate::constant::{CAP_WRITE_TRIES, REF_COUNT_FIELD, REF_RETIRED_FIELD, USER_ROLE_CLAIM_FIELD}; | 36 | +//! its own static, macro-checkable statement (`sqlx::query!`). This module |
| 37 | -use crate::database::{Database, backoff, lost_the_race, transaction_with_retry}; | 37 | +//! keeps only the result types the call sites answer with, plus the one |
| 38 | -use crate::error::AppError; | 38 | +//! genuinely shared mapping ([`full_kind`]). The shapes: |
| 39 | - | 39 | +//! |
| 40 | -/// One counter writer at a time, over every counter. | 40 | +//! ### Claim a seat and create the child (`claim_and_create` and its variants) |
| 41 | -/// | 41 | +//! |
| 42 | -/// Not the cap — the `WHERE` clause is the cap, and it holds with or without | 42 | +//! ```sql |
| 43 | -/// this. What the lock buys is that the process sends its counter writes one at | 43 | +//! WITH seat AS ( |
| 44 | -/// a time, so the database never sees a parent row contended by every in-flight | 44 | +//! UPDATE <parent> |
| 45 | -/// request at once. That keeps the optimistic retry loop below to a beat or two | 45 | +//! SET <cnt> = <cnt> + <bump> -- bump 0 for the uncounted create |
| 46 | -/// rather than a storm. | 46 | +//! WHERE id = $1 |
| 47 | -/// | 47 | +//! AND <cnt> < $2 -- or: < (SELECT <cap_expr> …) (live cap) |
| 48 | -/// It is also what keeps the test suite deterministic. The embedded in-memory | 48 | +//! -- AND (<guard>) -- the guarded variant: one predicate decides cap and precondition |
| 49 | -/// engine the tests run on does *not* have the real server's conflict | 49 | +//! RETURNING 1) |
| 50 | -/// detection: under two concurrent writes to one record it can drop one and | 50 | +//! INSERT INTO <child> (id, <cols>) |
| 51 | -/// still answer `Ok` (probed — the stored counter stays correct, but ~13% of a | 51 | +//! SELECT $3, $4, … WHERE EXISTS (SELECT 1 FROM seat) |
| 52 | -/// 16-racer round had one more caller told it had won than the counter agreed | 52 | +//! RETURNING <cols>; |
| 53 | -/// to). The real ws server never did this in 150 rounds of the same probe. | 53 | +//! ``` |
| 54 | -// | 54 | +//! |
| 55 | -// corner-cut: one lock for every cap. Per-parent locks (a keyed map) if unrelated | 55 | +//! One statement is atomic: a refused insert takes its own seat bump back. |
| 56 | -// caps ever contend measurably — the counters are already independent, this is | 56 | +//! The verdict maps: one row → [`Claimed::Made`]; 23505 on the child key → |
| 57 | -// only about how many writes a process has in flight. | 57 | +//! [`Claimed::Duplicate`] (read before the row count); zero rows → |
| 58 | -static CLAIM_LOCK: Mutex<()> = Mutex::const_new(()); | 58 | +//! [`Claimed::Full`] — deliberately still one marker for "full, guard failed, |
| 59 | +//! parent gone", as before: the caller re-reads the parent to pick the | ||
| 60 | +//! message, and only on that path. A live cap reads its capacity as a | ||
| 61 | +//! subselect inside the same `WHERE`, so the write that lowers the cap and | ||
| 62 | +//! the write that reads it still contend on one record; a lowered cap refuses | ||
| 63 | +//! the very next claimer instead of admitting everyone whose snapshot predates | ||
| 64 | +//! the edit. The uncounted create (`bump = 0`) still writes the seat | ||
| 65 | +//! statement, so a missing parent row is refused as [`Claimed::Full`] on both | ||
| 66 | +//! paths rather than silently writing a child of nobody. | ||
| 67 | +//! | ||
| 68 | +//! ### Two counters, one verdict (`claim_two_when_and_create`) | ||
| 69 | +//! | ||
| 70 | +//! ```sql | ||
| 71 | +//! WITH bump AS ( | ||
| 72 | +//! UPDATE board | ||
| 73 | +//! SET total_stroke_count = total_stroke_count + 1, -- hard (lifetime) cap first | ||
| 74 | +//! epoch_stroke_count = epoch_stroke_count + 1 -- soft (resettable) counter with it | ||
| 75 | +//! WHERE id = $1 | ||
| 76 | +//! AND total_stroke_count < $2 -- the hard cap carries the guard | ||
| 77 | +//! AND epoch = $3 | ||
| 78 | +//! AND epoch_stroke_count < $4 | ||
| 79 | +//! RETURNING 1) | ||
| 80 | +//! INSERT INTO board_stroke (id, <cols>) | ||
| 81 | +//! SELECT $5, … WHERE EXISTS (SELECT 1 FROM bump) | ||
| 82 | +//! RETURNING <cols>; | ||
| 83 | +//! ``` | ||
| 84 | +//! | ||
| 85 | +//! One `UPDATE` moves both counters, so the row is written once and the | ||
| 86 | +//! two-statement interleave the old process lock existed for cannot happen. | ||
| 87 | +//! Zero rows means "hard full, guard failed, board gone, or soft full": the | ||
| 88 | +//! caller re-reads both counters and maps them with [`full_kind`] — the | ||
| 89 | +//! terminal cap outranks the recoverable one, as [`ClaimedTwo`] documents. | ||
| 90 | +//! The child id is freshly minted, so no rival can aim at it and no 23505 | ||
| 91 | +//! verdict exists on this path. | ||
| 92 | +//! | ||
| 93 | +//! ### Claim a reference on a name (`claim_ref_and_create`) | ||
| 94 | +//! | ||
| 95 | +//! In the caller's transaction, the duplicate gate stays *ahead* of the | ||
| 96 | +//! retired check, so "you already have it" still outranks "the name is | ||
| 97 | +//! retired": | ||
| 98 | +//! | ||
| 99 | +//! ```sql | ||
| 100 | +//! SELECT 1 FROM <child> WHERE <its primary key>; -- found → ClaimedRef::Duplicate, stop | ||
| 101 | +//! WITH ref AS ( | ||
| 102 | +//! INSERT INTO <ref_table> (name, count) | ||
| 103 | +//! VALUES ($1, $2) | ||
| 104 | +//! ON CONFLICT (name) DO UPDATE | ||
| 105 | +//! SET count = <ref_table>.count + EXCLUDED.count | ||
| 106 | +//! WHERE <ref_table>.retired = false -- zero rows → ClaimedRef::Retired | ||
| 107 | +//! RETURNING 1) | ||
| 108 | +//! INSERT INTO <child> (…) | ||
| 109 | +//! SELECT … WHERE EXISTS (SELECT 1 FROM ref) | ||
| 110 | +//! RETURNING …; -- 23505 on the child key → ClaimedRef::Duplicate | ||
| 111 | +//! ``` | ||
| 112 | +//! | ||
| 113 | +//! The 23505 backstop covers the rival that passed the same gate a moment | ||
| 114 | +//! ago (referential integrity keeps "row exists ∧ name retired" unreachable: | ||
| 115 | +//! retiring requires count = 0, and a live row holds a count). The counted | ||
| 116 | +//! row and the count still commit together or not at all — a name counted for | ||
| 117 | +//! a row that does not exist is a name nobody can ever retire. | ||
| 118 | +//! | ||
| 119 | +//! ### Retire / un-retire a name (produces a [`Switched`]) | ||
| 120 | +//! | ||
| 121 | +//! Two statements in the caller's transaction; the row lock makes the read | ||
| 122 | +//! and the write one switch, which is why the old process lock is gone: | ||
| 123 | +//! | ||
| 124 | +//! ```sql | ||
| 125 | +//! SELECT retired FROM <ref_table> WHERE name = $1 FOR UPDATE; -- absent → treated as false | ||
| 126 | +//! INSERT INTO <ref_table> (name, count, retired) | ||
| 127 | +//! VALUES ($1, 0, $2) | ||
| 128 | +//! ON CONFLICT (name) DO UPDATE | ||
| 129 | +//! SET retired = $2 | ||
| 130 | +//! WHERE <ref_table>.count = 0 -- retire only | ||
| 131 | +//! AND <ref_table>.retired IS DISTINCT FROM $2 -- idempotence | ||
| 132 | +//! RETURNING 1; -- empty result → the write did not land | ||
| 133 | +//! ``` | ||
| 134 | +//! | ||
| 135 | +//! `(landed, was.unwrap_or(false))` maps exactly as [`Switched`] documents. | ||
| 136 | +//! Retiring a never-claimed name still creates its ref row retired (the | ||
| 137 | +//! `INSERT` arm), as before. | ||
| 138 | +//! | ||
| 139 | +//! ### Role-gated grants (the old `role_claim` handshake) | ||
| 140 | +//! | ||
| 141 | +//! The grant-survives-demotion handshake is now two statements in the | ||
| 142 | +//! caller's transaction — the old counter bump-and-restore dance is dead: | ||
| 143 | +//! | ||
| 144 | +//! ```sql | ||
| 145 | +//! SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE; | ||
| 146 | +//! -- Rust checks the role it found; unfit → the call-site refusal (no retry). | ||
| 147 | +//! INSERT INTO <grant> …; | ||
| 148 | +//! ``` | ||
| 149 | +//! | ||
| 150 | +//! The demotion cascade's transaction `UPDATE`s that same user row before its | ||
| 151 | +//! sweeps, so grant and demotion serialize on the row lock in both | ||
| 152 | +//! directions: either the sweep sees the grant row, or the grant saw the new | ||
| 153 | +//! role. | ||
| 59 | 154 | ||
| 60 | -/// [`CLAIM_LOCK`], for a counter write that rides someone else's transaction | 155 | +#![allow(dead_code)] // the types below are the wave-2 lanes' verdict vocabulary |
| 61 | -/// instead of [`write`]'s — [`crate::db::field_update::FieldUpdate`]'s term | ||
| 62 | -/// move claims and releases inside the very `UPDATE`'s transaction, and still | ||
| 63 | -/// owes the process one counter write at a time. | ||
| 64 | -/// | ||
| 65 | -/// **Is it load-bearing?** For the caps themselves, no — every one of them is a | ||
| 66 | -/// single conditional write the store decides, and it decides it the same way | ||
| 67 | -/// with a dozen writers in flight. So a counter write that skips this lock is | ||
| 68 | -/// not a hole in a cap, and "every other site takes it" is not a correctness | ||
| 69 | -/// argument. What the lock *is* load-bearing for is (a) the test suite, whose | ||
| 70 | -/// in-memory engine forges wins under concurrency, and (b) any guard built out | ||
| 71 | -/// of **two** statements that must not interleave with a rival's pair — | ||
| 72 | -/// [`retire_name`] is exactly that, and it is why a skipped lock there would be | ||
| 73 | -/// a real bug while a skipped lock around a lone `UPDATE … WHERE` is only | ||
| 74 | -/// contention. | ||
| 75 | -pub(crate) async fn counter_lock() -> tokio::sync::MutexGuard<'static, ()> { | ||
| 76 | - CLAIM_LOCK.lock().await | ||
| 77 | -} | ||
| 78 | 156 | ||
| 79 | /// "No cap" as a number, so the guard stays one comparison instead of a | 157 | /// "No cap" as a number, so the guard stays one comparison instead of a |
| 80 | -/// nullable branch: `NONE`/`NULL` bind ambiguity is a worse trade than a | 158 | +/// nullable branch: `NULL` bind ambiguity is a worse trade than a sentinel no |
| 81 | -/// sentinel no roster will ever reach. | 159 | +/// roster will ever reach. |
| 82 | pub(crate) const UNLIMITED: i64 = i64::MAX; | 160 | pub(crate) const UNLIMITED: i64 = i64::MAX; |
| 83 | 161 | ||
| 84 | -/// Take one slot on `parent`'s `field` counter, and nothing else. `false` means | 162 | +/// What the claim-and-create recipe (module docs) settled. |
| 85 | -/// the cap is full (or the parent row is gone) and the caller must refuse — | ||
| 86 | -/// nothing was written. `field` is always an in-crate constant, never user | ||
| 87 | -/// input. | ||
| 88 | -/// | ||
| 89 | -/// **Test-only.** Every production claim now lands its child row in the same | ||
| 90 | -/// transaction ([`claim_and_create`] and its variants); a bare claim followed by | ||
| 91 | -/// a separate insert is the leak those exist to close. What survives is the | ||
| 92 | -/// probe: the appointment tests put the double-book question to this `WHERE` | ||
| 93 | -/// directly (a `join!` would ask the in-memory engine instead, which forges | ||
| 94 | -/// wins), and staging a taken seat with *no* child row — exactly what a booking | ||
| 95 | -/// mid-flight looks like — is a state no `*_and_create` can produce. | ||
| 96 | -#[cfg(test)] | ||
| 97 | -pub(crate) async fn claim( | ||
| 98 | - parent: &RecordId, | ||
| 99 | - field: &str, | ||
| 100 | - cap: i64, | ||
| 101 | - db: &Database, | ||
| 102 | -) -> Result<bool, AppError> { | ||
| 103 | - let sql = format!( | ||
| 104 | - "UPDATE $parent SET {field} = ({field} ?? 0) + 1 \ | ||
| 105 | - WHERE ({field} ?? 0) < $num RETURN VALUE id" | ||
| 106 | - ); | ||
| 107 | - Ok(!write(&sql, parent, cap, db).await?.is_empty()) | ||
| 108 | -} | ||
| 109 | - | ||
| 110 | -/// The `THROW` markers the in-transaction gates below abort with: no room, and | ||
| 111 | -/// this pair already holds its row. | ||
| 112 | -const FULL_MARK: &str = "cap_full"; | ||
| 113 | -const HELD_MARK: &str = "cap_held"; | ||
| 114 | - | ||
| 115 | -/// [`claim_ref_and_create`]'s third answer: the *name* is retired, which is not | ||
| 116 | -/// a count being full — nothing empties it, and only putting the name back in | ||
| 117 | -/// service lets a claim through. | ||
| 118 | -const RETIRED_MARK: &str = "cap_retired"; | ||
| 119 | - | ||
| 120 | -/// The two markers [`claim_two_when_and_create`] aborts with, one per counter, | ||
| 121 | -/// deliberately *not* shared: its two caps mean opposite things to the person | ||
| 122 | -/// who hit one. The soft cap is a resettable working set (a whiteboard's live | ||
| 123 | -/// canvas, emptied by a clear and drawn on again); the hard cap is the parent's | ||
| 124 | -/// lifetime budget, and hitting it is terminal. One marker for both would tell | ||
| 125 | -/// a caller a recoverable state is a permanent one. | ||
| 126 | -const SOFT_FULL_MARK: &str = "cap_full_soft"; | ||
| 127 | -const HARD_FULL_MARK: &str = "cap_full_hard"; | ||
| 128 | - | ||
| 129 | -/// What [`claim_and_create`] settled. | ||
| 130 | pub(crate) enum Claimed<T> { | 163 | pub(crate) enum Claimed<T> { |
| 131 | /// The seat and the row committed together. | 164 | /// The seat and the row committed together. |
| 132 | Made(T), | 165 | Made(T), |
| @@ -137,607 +170,32 @@ pub(crate) enum Claimed<T> { | |||
| 137 | Duplicate, | 170 | Duplicate, |
| 138 | } | 171 | } |
| 139 | 172 | ||
| 140 | -/// Take a slot on `parent`'s `field` counter *and* write the child that fills | 173 | +/// What the two-counter recipe (module docs) settled. |
| 141 | -/// it, in one transaction. | ||
| 142 | -/// | ||
| 143 | -/// A bare claim followed by a separate insert cannot promise this. Where the child | ||
| 144 | -/// carries a deterministic id (one row per pair), two writers placing the *same* | ||
| 145 | -/// pair both pass the claim — neither row exists yet — so on a tight cap the | ||
| 146 | -/// second is told "full" for a seat it was never going to need, and a release | ||
| 147 | -/// afterwards is too late to unsay it. A process-wide mutex could not hide that | ||
| 148 | -/// either: it is released around the very round trip the two writes race in. | ||
| 149 | -/// Here the duplicate `CREATE` aborts the transaction, which takes its own | ||
| 150 | -/// increment with it, and the caller reads the winner's row back — so the | ||
| 151 | -/// counter never counts a row that does not exist. | ||
| 152 | -/// | ||
| 153 | -/// The row is looked for *before* the seat is claimed, in that same | ||
| 154 | -/// transaction, because on a tight cap the claim is the first thing to fail: a | ||
| 155 | -/// member whose row a rival placed a moment ago would be told "full" about a | ||
| 156 | -/// seat they already hold. The order makes "you are already in" outrank "there | ||
| 157 | -/// is no room", which is what every caller's early return promises anyway. | ||
| 158 | -pub(crate) async fn claim_and_create<T: SurrealValue + Clone>( | ||
| 159 | - parent: &RecordId, | ||
| 160 | - field: &str, | ||
| 161 | - cap: i64, | ||
| 162 | - id: &RecordId, | ||
| 163 | - content: &T, | ||
| 164 | - db: &Database, | ||
| 165 | -) -> Result<Claimed<T>, AppError> { | ||
| 166 | - claim_at_and_create(parent, field, "$num", cap, "", 1, None, id, content, db).await | ||
| 167 | -} | ||
| 168 | - | ||
| 169 | -/// [`claim_and_create`] for a counter only *some* of a parent's children move: | ||
| 170 | -/// the row lands either way, and `counts` decides whether the tally follows it. | ||
| 171 | -/// | ||
| 172 | -/// The one live user is `exam_sat_total`, which counts exams sat rather than | ||
| 173 | -/// sittings — a retake writes a row and moves nothing. Splitting that into | ||
| 174 | -/// "count and create" versus a bare create outside this module would put the | ||
| 175 | -/// uncounted write on a different statement to the counted one, and a | ||
| 176 | -/// deterministic child id needs the duplicate abort either way: whichever | ||
| 177 | -/// branch runs, exactly one writer's `CREATE` commits, and only that one's | ||
| 178 | -/// increment survives with it. `counts` false still writes the seat statement | ||
| 179 | -/// (`+ 0`), so a missing parent row is refused as [`Claimed::Full`] on both | ||
| 180 | -/// paths rather than silently writing a child of nobody. | ||
| 181 | -pub(crate) async fn create_counting<T: SurrealValue + Clone>( | ||
| 182 | - parent: &RecordId, | ||
| 183 | - field: &str, | ||
| 184 | - counts: bool, | ||
| 185 | - id: &RecordId, | ||
| 186 | - content: &T, | ||
| 187 | - db: &Database, | ||
| 188 | -) -> Result<Claimed<T>, AppError> { | ||
| 189 | - let bump = i64::from(counts); | ||
| 190 | - claim_at_and_create( | ||
| 191 | - parent, field, "$num", UNLIMITED, "", bump, None, id, content, db, | ||
| 192 | - ) | ||
| 193 | - .await | ||
| 194 | -} | ||
| 195 | - | ||
| 196 | -/// [`claim_and_create`] against a cap the *statement* reads rather than one the | ||
| 197 | -/// caller snapshotted: `cap_expr` is SQL evaluated on the parent row at write | ||
| 198 | -/// time (`audience.capacity ?? $num`, a subquery onto the settings singleton), | ||
| 199 | -/// and `fallback` is the `$num` it coalesces to when the column is unset. | ||
| 200 | -/// | ||
| 201 | -/// A snapshotted cap is only ever a claim about the past. Bound as an integer, | ||
| 202 | -/// a `PATCH` that *lowers* the cap while N requests are in flight admits all N | ||
| 203 | -/// anyway — each one is measured against the number its own read saw, and the | ||
| 204 | -/// single-record guard that makes concurrent claimers safe against each other | ||
| 205 | -/// says nothing about the writer of the cap itself. Read inside the same | ||
| 206 | -/// conditional write, the lowered cap refuses the very next claimer, because | ||
| 207 | -/// the write that lowered it and the write that reads it contend on one record. | ||
| 208 | -/// | ||
| 209 | -/// `cap_expr` is always an in-crate SQL literal, never text from a client. | ||
| 210 | -/// | ||
| 211 | -/// `holder` is the child's *other* parent when that parent is a user whose live | ||
| 212 | -/// role decides whether the row may exist at all: `(the user record, the role | ||
| 213 | -/// it may not carry)`, claimed by [`role_claim`] in this same transaction. A | ||
| 214 | -/// refusal from it arrives as [`Claimed::Full`], which already means "full, or | ||
| 215 | -/// the guard failed, or the parent is gone" — the caller re-reads to pick the | ||
| 216 | -/// message, and only on that path. | ||
| 217 | -pub(crate) async fn claim_live_and_create<T: SurrealValue + Clone>( | ||
| 218 | - parent: &RecordId, | ||
| 219 | - field: &str, | ||
| 220 | - cap_expr: &str, | ||
| 221 | - fallback: i64, | ||
| 222 | - holder: Option<(&RecordId, &str)>, | ||
| 223 | - new: (&RecordId, &T), | ||
| 224 | - db: &Database, | ||
| 225 | -) -> Result<Claimed<T>, AppError> { | ||
| 226 | - let (id, content) = new; | ||
| 227 | - claim_at_and_create( | ||
| 228 | - parent, field, cap_expr, fallback, "", 1, holder, id, content, db, | ||
| 229 | - ) | ||
| 230 | - .await | ||
| 231 | -} | ||
| 232 | - | ||
| 233 | -/// [`claim_and_create`], but only while `guard` — an extra predicate on that | ||
| 234 | -/// same parent row — also holds: one conditional write decides the cap *and* | ||
| 235 | -/// the caller's second precondition (a homework submission's file add is | ||
| 236 | -/// refused once the work is graded), so no read a concurrent write can outrun | ||
| 237 | -/// sits between them. | ||
| 238 | -/// | ||
| 239 | -/// The contract that costs the caller something: [`Claimed::Full`] means "full | ||
| 240 | -/// **or** the guard failed **or** the parent row is gone" — one marker for all | ||
| 241 | -/// three, because the seat `UPDATE` matching nothing cannot say which clause | ||
| 242 | -/// refused it. A caller that needs to tell them apart re-reads the parent, and | ||
| 243 | -/// only to pick the message: none of the three is retryable into a success. | ||
| 244 | -/// | ||
| 245 | -/// `guard` is always an in-crate SQL literal or built in-crate out of numbers | ||
| 246 | -/// this crate read back itself — never text from a client. | ||
| 247 | -pub(crate) async fn claim_when_and_create<T: SurrealValue + Clone>( | ||
| 248 | - parent: &RecordId, | ||
| 249 | - field: &str, | ||
| 250 | - cap: i64, | ||
| 251 | - guard: &str, | ||
| 252 | - id: &RecordId, | ||
| 253 | - content: &T, | ||
| 254 | - db: &Database, | ||
| 255 | -) -> Result<Claimed<T>, AppError> { | ||
| 256 | - claim_at_and_create(parent, field, "$num", cap, guard, 1, None, id, content, db).await | ||
| 257 | -} | ||
| 258 | - | ||
| 259 | -#[allow(clippy::too_many_arguments)] | ||
| 260 | -async fn claim_at_and_create<T: SurrealValue + Clone>( | ||
| 261 | - parent: &RecordId, | ||
| 262 | - field: &str, | ||
| 263 | - cap_expr: &str, | ||
| 264 | - cap: i64, | ||
| 265 | - extra: &str, | ||
| 266 | - bump: i64, | ||
| 267 | - holder: Option<(&RecordId, &str)>, | ||
| 268 | - id: &RecordId, | ||
| 269 | - content: &T, | ||
| 270 | - db: &Database, | ||
| 271 | -) -> Result<Claimed<T>, AppError> { | ||
| 272 | - let extra = if extra.is_empty() { | ||
| 273 | - String::new() | ||
| 274 | - } else { | ||
| 275 | - format!(" AND ({extra})") | ||
| 276 | - }; | ||
| 277 | - // The holder's claim rides between the duplicate gate and the seat, so a | ||
| 278 | - // caller whose row a rival placed is still told "you already have it", and | ||
| 279 | - // a demotion outranks a full cap: `Full` on a list with room left sends | ||
| 280 | - // nobody looking for a seat that is not the problem. | ||
| 281 | - let held_by = holder.map_or_else(Vec::new, |(_, unfit)| { | ||
| 282 | - role_claim("holder", unfit, FULL_MARK) | ||
| 283 | - }); | ||
| 284 | - let hold = if held_by.is_empty() { | ||
| 285 | - String::new() | ||
| 286 | - } else { | ||
| 287 | - format!("{};\n", held_by.join(";\n")) | ||
| 288 | - }; | ||
| 289 | - let sql = format!( | ||
| 290 | - "BEGIN TRANSACTION; | ||
| 291 | - LET $held = (SELECT VALUE id FROM $id); | ||
| 292 | - IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; | ||
| 293 | - {hold}LET $seat = (UPDATE $parent SET {field} = ({field} ?? 0) + $bump \ | ||
| 294 | - WHERE ({field} ?? 0) < ({cap_expr}){extra} RETURN VALUE id); | ||
| 295 | - IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }}; | ||
| 296 | - CREATE $id CONTENT $row; | ||
| 297 | - COMMIT TRANSACTION;" | ||
| 298 | - ); | ||
| 299 | - let _guard = CLAIM_LOCK.lock().await; | ||
| 300 | - let mut last = None; | ||
| 301 | - for attempt in 0..CAP_WRITE_TRIES { | ||
| 302 | - backoff(attempt).await; | ||
| 303 | - let mut query = db | ||
| 304 | - .query(sql.as_str()) | ||
| 305 | - .bind(("parent", parent.clone())) | ||
| 306 | - .bind(("num", cap)) | ||
| 307 | - .bind(("bump", bump)) | ||
| 308 | - .bind(("id", id.clone())) | ||
| 309 | - .bind(("row", content.clone())); | ||
| 310 | - if let Some((record, _)) = holder { | ||
| 311 | - query = query.bind(("holder", record.clone())); | ||
| 312 | - } | ||
| 313 | - let attempted = query.await; | ||
| 314 | - let mut result = match attempted { | ||
| 315 | - Ok(result) => result, | ||
| 316 | - Err(err) if lost_the_race(&err) => { | ||
| 317 | - last = Some(err); | ||
| 318 | - continue; | ||
| 319 | - } | ||
| 320 | - Err(err) => return Err(err.into()), | ||
| 321 | - }; | ||
| 322 | - // An aborted transaction errors *every* slot, most with a generic "not | ||
| 323 | - // executed" — only the failing slot says why. | ||
| 324 | - let mut errors = result.take_errors(); | ||
| 325 | - // "Already a member" is read first: it outranks a full cap, and the two | ||
| 326 | - // never both fire (the gate aborts before the seat is touched). | ||
| 327 | - if errors | ||
| 328 | - .values() | ||
| 329 | - .any(|error| error.to_string().contains(HELD_MARK) || error.is_already_exists()) | ||
| 330 | - { | ||
| 331 | - return Ok(Claimed::Duplicate); | ||
| 332 | - } | ||
| 333 | - if errors | ||
| 334 | - .values() | ||
| 335 | - .any(|error| error.to_string().contains(FULL_MARK)) | ||
| 336 | - { | ||
| 337 | - return Ok(Claimed::Full); | ||
| 338 | - } | ||
| 339 | - // A conflict in *any* slot is the whole batch's verdict, and it is read | ||
| 340 | - // before the arbitrary pick below: the siblings say only "not executed", | ||
| 341 | - // which is the *consequence* of this abort and never a reason of its | ||
| 342 | - // own. Picking one of those out of a `HashMap` — unordered, so it wins | ||
| 343 | - // most rounds — retired a retryable round as a 500. | ||
| 344 | - if errors.values().any(lost_the_race) { | ||
| 345 | - last = errors.drain().map(|(_, error)| error).find(lost_the_race); | ||
| 346 | - continue; | ||
| 347 | - } | ||
| 348 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 349 | - return Err(error.into()); | ||
| 350 | - } | ||
| 351 | - // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5, plus | ||
| 352 | - // the holder claim's own statements when one is carried — counted, not | ||
| 353 | - // tallied by hand, so a statement added there cannot read back the | ||
| 354 | - // wrong result. | ||
| 355 | - let slot = 5 + held_by.len(); | ||
| 356 | - return result | ||
| 357 | - .take::<Vec<T>>(slot)? | ||
| 358 | - .into_iter() | ||
| 359 | - .next() | ||
| 360 | - .map(Claimed::Made) | ||
| 361 | - .ok_or_else(|| AppError::Internal("cap claim wrote no row".into())); | ||
| 362 | - } | ||
| 363 | - Err(last | ||
| 364 | - .map(AppError::from) | ||
| 365 | - .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) | ||
| 366 | -} | ||
| 367 | - | ||
| 368 | -/// The marker [`touch_and_create`] aborts with: the parent row is gone. | ||
| 369 | -const GONE_MARK: &str = "cap_gone"; | ||
| 370 | - | ||
| 371 | -/// Write a child of `parent` while *colliding* with anything that removes the | ||
| 372 | -/// parent — no seat spent, only the proof. `Ok(None)` = the parent is gone and | ||
| 373 | -/// nothing was written. | ||
| 374 | -/// | ||
| 375 | -/// Reading the parent first and then inserting cannot promise this, and neither | ||
| 376 | -/// can a `SELECT` inside the transaction: SurrealDB 3.2.3 conflict-checks write | ||
| 377 | -/// sets, not read sets, so a create landing inside a parent delete's window | ||
| 378 | -/// reads a row that is still there (removed, uncommitted) while the delete's | ||
| 379 | -/// `DELETE <child> WHERE parent = $parent` sweep already ran on a snapshot | ||
| 380 | -/// without this row — both commit, and the child outlives its parent | ||
| 381 | -/// unreachably, because every route to it goes through the parent. | ||
| 382 | -/// | ||
| 383 | -/// So the proof is a *write* on the parent's own record, which is the key the | ||
| 384 | -/// delete writes. `field` is moved — bumped and put back by captured value, | ||
| 385 | -/// `NONE` included, so the row is byte-identical afterwards — because an | ||
| 386 | -/// `UPDATE` that leaves the document unchanged is elided and never enters the | ||
| 387 | -/// write set: `SET x = x` sits on no key at all and collides with nothing | ||
| 388 | -/// (measured on 3.2.3, and the reason | ||
| 389 | -/// [`crate::db::class_pump::Axis::pivot_claim`] and | ||
| 390 | -/// [`crate::db::exam_answer::save`] have the same shape). Both | ||
| 391 | -/// statements are inside the transaction, so an abort between them cannot leave | ||
| 392 | -/// the counter up. | ||
| 393 | -/// | ||
| 394 | -/// It lives here because it is [`claim_and_create`] with the cap removed: the | ||
| 395 | -/// same single-record conditional write on the parent, asked "are you still | ||
| 396 | -/// there?" instead of "is there room?". No [`CLAIM_LOCK`] either — the counter | ||
| 397 | -/// nets zero, so no cap depends on the order these arrive in. | ||
| 398 | -/// | ||
| 399 | -/// Admissible for [`crate::database::transaction_with_retry`]: `UPDATE`s and a | ||
| 400 | -/// `CREATE` whose id is a freshly minted ULID no rival can aim at, so no | ||
| 401 | -/// statement can legitimately answer "already exists" and a lost round wrote | ||
| 402 | -/// nothing. | ||
| 403 | -pub(crate) async fn touch_and_create<T: SurrealValue + Clone>( | ||
| 404 | - parent: &RecordId, | ||
| 405 | - field: &str, | ||
| 406 | - id: &RecordId, | ||
| 407 | - content: &T, | ||
| 408 | - db: &Database, | ||
| 409 | -) -> Result<Option<T>, AppError> { | ||
| 410 | - let sql = format!( | ||
| 411 | - "BEGIN TRANSACTION; | ||
| 412 | - LET $was = (SELECT VALUE {field} FROM ONLY $parent); | ||
| 413 | - LET $alive = (UPDATE $parent SET {field} = ({field} ?? 0) + 1 RETURN VALUE id); | ||
| 414 | - IF array::len($alive) = 0 {{ THROW '{GONE_MARK}' }}; | ||
| 415 | - UPDATE $parent SET {field} = $was; | ||
| 416 | - LET $made = (CREATE $id CONTENT $row RETURN AFTER); | ||
| 417 | - RETURN $made[0]; | ||
| 418 | - COMMIT TRANSACTION;" | ||
| 419 | - ); | ||
| 420 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 421 | - db, | ||
| 422 | - &sql, | ||
| 423 | - &[ | ||
| 424 | - ("parent".into(), parent.clone().into_value()), | ||
| 425 | - ("id".into(), id.clone().into_value()), | ||
| 426 | - ("row".into(), content.clone().into_value()), | ||
| 427 | - ], | ||
| 428 | - &[GONE_MARK], | ||
| 429 | - ) | ||
| 430 | - .await?; | ||
| 431 | - // An aborted transaction errors *every* slot, most with a generic "not | ||
| 432 | - // executed" — only the THROW's own slot names the marker. | ||
| 433 | - if errors | ||
| 434 | - .values() | ||
| 435 | - .any(|error| error.to_string().contains(GONE_MARK)) | ||
| 436 | - { | ||
| 437 | - return Ok(None); | ||
| 438 | - } | ||
| 439 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 440 | - return Err(error.into()); | ||
| 441 | - } | ||
| 442 | - // The trailing `RETURN` is the last statement before `COMMIT`, so its slot | ||
| 443 | - // follows the statement count rather than a hand-kept number; | ||
| 444 | - // `num_statements` counts BEGIN and COMMIT. | ||
| 445 | - let slot = result.num_statements().saturating_sub(2); | ||
| 446 | - result | ||
| 447 | - .take::<Vec<T>>(slot)? | ||
| 448 | - .into_iter() | ||
| 449 | - .next() | ||
| 450 | - .map(Some) | ||
| 451 | - .ok_or_else(|| AppError::Internal("the parent touch wrote no row".into())) | ||
| 452 | -} | ||
| 453 | - | ||
| 454 | -/// The statements that put a transaction's write on a **user's own record** | ||
| 455 | -/// while the role that row still carries may hold the grant being written — | ||
| 456 | -/// [`touch_and_create`]'s trick pointed at the one key | ||
| 457 | -/// [`crate::service::user::set_role`] writes. | ||
| 458 | -/// | ||
| 459 | -/// WHY: a demotion sheds every grant the old role implied, and it does that in | ||
| 460 | -/// the role write's own transaction — but its sweeps are *snapshots* | ||
| 461 | -/// (`DELETE <child> WHERE user = $usr`), and SurrealDB 3.2.3 conflict-checks | ||
| 462 | -/// write sets, not read sets. A seat, an enrollment or a class membership | ||
| 463 | -/// created after that snapshot therefore survives the sweep, and nothing ever | ||
| 464 | -/// re-sweeps: the grant stands forever under a role that may not hold it. Every | ||
| 465 | -/// one of those creates writes its *other* parent (the event, the course, the | ||
| 466 | -/// class), so it shares no key with the demotion and the store has nothing to | ||
| 467 | -/// settle. | ||
| 468 | -/// | ||
| 469 | -/// So the counter named by [`USER_ROLE_CLAIM_FIELD`] is **moved** — bumped and | ||
| 470 | -/// put back by captured value, `NONE` included, so the row is byte-identical | ||
| 471 | -/// afterwards — because re-stating a value claims nothing: an `UPDATE` that | ||
| 472 | -/// leaves the document unchanged is elided and enters no write set. The same | ||
| 473 | -/// `UPDATE` hands back the role it found, so one statement is both the write | ||
| 474 | -/// that collides and the read that decides. Either the sweep sees this row, or | ||
| 475 | -/// this statement sees the demotion; and the caller that *loses* the conflict | ||
| 476 | -/// re-sends into a fresh transaction that reads the new role, which is what | ||
| 477 | -/// keeps the retry from turning a refusal into a success. | ||
| 478 | -/// | ||
| 479 | -/// A user row that is not there claims nothing and refuses nothing: the | ||
| 480 | -/// `UPDATE` matches no key, and every caller has already answered a missing | ||
| 481 | -/// target its own way. `holder` names the binding the user record is bound to, | ||
| 482 | -/// and `unfit` is an in-crate comparison against the role that may *not* hold | ||
| 483 | -/// this grant — never text from a client. | ||
| 484 | -pub(crate) fn role_claim(holder: &str, unfit: &str, mark: &str) -> Vec<String> { | ||
| 485 | - vec![ | ||
| 486 | - format!("LET $role_was = (SELECT VALUE {USER_ROLE_CLAIM_FIELD} FROM ONLY ${holder})"), | ||
| 487 | - format!( | ||
| 488 | - "LET $role_now = (UPDATE ${holder} SET {USER_ROLE_CLAIM_FIELD} = \ | ||
| 489 | - ({USER_ROLE_CLAIM_FIELD} ?? 0) + 1 RETURN VALUE role)" | ||
| 490 | - ), | ||
| 491 | - format!("IF array::len($role_now) > 0 AND $role_now[0] {unfit} {{ THROW '{mark}' }}"), | ||
| 492 | - format!("UPDATE ${holder} SET {USER_ROLE_CLAIM_FIELD} = $role_was"), | ||
| 493 | - ] | ||
| 494 | -} | ||
| 495 | - | ||
| 496 | -/// What [`claim_two_when_and_create`] settled. | ||
| 497 | pub(crate) enum ClaimedTwo<T> { | 174 | pub(crate) enum ClaimedTwo<T> { |
| 498 | /// Both seats and the row committed together. | 175 | /// Both seats and the row committed together. |
| 499 | Made(T), | 176 | Made(T), |
| 500 | - /// The *resettable* counter (`fields[0]`) is full — nothing was written, | 177 | + /// The *resettable* counter (the soft, epoch-scoped one) is full — |
| 501 | - /// and whatever empties it lets the caller through again. | 178 | + /// nothing was written, and whatever empties it lets the caller through |
| 179 | + /// again. | ||
| 502 | FullSoft, | 180 | FullSoft, |
| 503 | - /// The *lifetime* counter (`fields[1]`) is full, the guard failed, or the | 181 | + /// The *lifetime* counter is full, the guard failed, or the parent row is |
| 504 | - /// parent row is gone — nothing was written. The caller re-reads the parent | 182 | + /// gone — nothing was written. The caller re-reads the parent to tell |
| 505 | - /// to tell those apart, and only to pick the message: both are refusals the | 183 | + /// those apart, and only to pick the message: both are refusals the |
| 506 | /// caller cannot retry into a success. | 184 | /// caller cannot retry into a success. |
| 507 | FullHard, | 185 | FullHard, |
| 508 | } | 186 | } |
| 509 | 187 | ||
| 510 | -/// Take a slot on *two* of `parent`'s counters, while `guard` holds, and write | 188 | +/// What the reference-counter recipe (module docs) settled. |
| 511 | -/// the child that fills them — one transaction, one verdict. | ||
| 512 | -/// | ||
| 513 | -/// Two separate guarded claims cannot promise this. A parent whose children are | ||
| 514 | -/// counted twice — once against a resettable working set, once against a | ||
| 515 | -/// lifetime budget — has the two counters describing the same rows, so a writer | ||
| 516 | -/// that lands one increment and loses the other leaves them disagreeing | ||
| 517 | -/// forever, and the lifetime cap stops bounding anything. Here either both | ||
| 518 | -/// increments and the row commit, or the transaction aborts having written | ||
| 519 | -/// nothing. | ||
| 520 | -/// | ||
| 521 | -/// The hard cap is claimed *first*, carrying the guard, so a terminal refusal | ||
| 522 | -/// outranks a recoverable one: a parent that has spent its lifetime budget is | ||
| 523 | -/// not helped by being told its resettable counter is also full. | ||
| 524 | -/// | ||
| 525 | -/// There is no `$held` gate — [`claim_and_create`]'s exists because its child | ||
| 526 | -/// carries a deterministic id two writers can both aim at. This one's caller | ||
| 527 | -/// mints a fresh monotonic ULID on a table with no `UNIQUE` index, so no rival | ||
| 528 | -/// can target that id, and its absence is also what keeps the batch retryable: | ||
| 529 | -/// no statement in it can legitimately answer "already exists" (see | ||
| 530 | -/// [`crate::database::transaction_with_retry`]). | ||
| 531 | -/// | ||
| 532 | -/// The two counters are named one by one rather than passed as a pair of | ||
| 533 | -/// arrays: which slot is the resettable one and which is terminal decides | ||
| 534 | -/// whether a refusal is phrased "clear it and carry on" or "this is over", and | ||
| 535 | -/// two `[i64; 2]` positions swapped by mistake compile, pass every test — both | ||
| 536 | -/// slots are the same type — and misreport that forever. The names are the | ||
| 537 | -/// guard against it. | ||
| 538 | -/// | ||
| 539 | -/// The fields are always in-crate constants, and `guard` is either one or | ||
| 540 | -/// built in-crate out of numbers this crate read back itself | ||
| 541 | -/// (`board_stroke::append` appends an `epoch` it took off the board row) — | ||
| 542 | -/// never text from a client. | ||
| 543 | -pub(crate) async fn claim_two_when_and_create<T: SurrealValue + Clone>( | ||
| 544 | - parent: &RecordId, | ||
| 545 | - soft: (&str, i64), | ||
| 546 | - hard: (&str, i64), | ||
| 547 | - guard: &str, | ||
| 548 | - id: &RecordId, | ||
| 549 | - content: &T, | ||
| 550 | - db: &Database, | ||
| 551 | -) -> Result<ClaimedTwo<T>, AppError> { | ||
| 552 | - let (soft_field, soft_cap) = soft; | ||
| 553 | - let (hard_field, hard_cap) = hard; | ||
| 554 | - // Parenthesized `??` throughout: `n ?? 0 < $cap` parses as `n ?? (0 < $cap)`, | ||
| 555 | - // which is truthy for every row and would claim past the cap. | ||
| 556 | - let sql = format!( | ||
| 557 | - "BEGIN TRANSACTION; | ||
| 558 | - LET $lifetime = (UPDATE $parent SET {hard_field} = ({hard_field} ?? 0) + 1 \ | ||
| 559 | - WHERE ({hard_field} ?? 0) < $hard AND ({guard}) RETURN VALUE id); | ||
| 560 | - IF array::len($lifetime) = 0 {{ THROW '{HARD_FULL_MARK}' }}; | ||
| 561 | - LET $seat = (UPDATE $parent SET {soft_field} = ({soft_field} ?? 0) + 1 \ | ||
| 562 | - WHERE ({soft_field} ?? 0) < $soft RETURN VALUE id); | ||
| 563 | - IF array::len($seat) = 0 {{ THROW '{SOFT_FULL_MARK}' }}; | ||
| 564 | - CREATE $id CONTENT $row; | ||
| 565 | - COMMIT TRANSACTION;" | ||
| 566 | - ); | ||
| 567 | - let _guard = CLAIM_LOCK.lock().await; | ||
| 568 | - let mut last = None; | ||
| 569 | - for attempt in 0..CAP_WRITE_TRIES { | ||
| 570 | - backoff(attempt).await; | ||
| 571 | - let attempted = db | ||
| 572 | - .query(sql.as_str()) | ||
| 573 | - .bind(("parent", parent.clone())) | ||
| 574 | - .bind(("soft", soft_cap)) | ||
| 575 | - .bind(("hard", hard_cap)) | ||
| 576 | - .bind(("id", id.clone())) | ||
| 577 | - .bind(("row", content.clone())) | ||
| 578 | - .await; | ||
| 579 | - let mut result = match attempted { | ||
| 580 | - Ok(result) => result, | ||
| 581 | - Err(err) if lost_the_race(&err) => { | ||
| 582 | - last = Some(err); | ||
| 583 | - continue; | ||
| 584 | - } | ||
| 585 | - Err(err) => return Err(err.into()), | ||
| 586 | - }; | ||
| 587 | - // An aborted transaction errors *every* slot, most with a generic "not | ||
| 588 | - // executed" — only the failing slot says why. The two markers are read | ||
| 589 | - // before the conflict check, because a `THROW` is a decision. | ||
| 590 | - let mut errors = result.take_errors(); | ||
| 591 | - if errors | ||
| 592 | - .values() | ||
| 593 | - .any(|error| error.to_string().contains(HARD_FULL_MARK)) | ||
| 594 | - { | ||
| 595 | - return Ok(ClaimedTwo::FullHard); | ||
| 596 | - } | ||
| 597 | - if errors | ||
| 598 | - .values() | ||
| 599 | - .any(|error| error.to_string().contains(SOFT_FULL_MARK)) | ||
| 600 | - { | ||
| 601 | - return Ok(ClaimedTwo::FullSoft); | ||
| 602 | - } | ||
| 603 | - if errors.values().any(lost_the_race) { | ||
| 604 | - last = errors.drain().map(|(_, error)| error).find(lost_the_race); | ||
| 605 | - continue; | ||
| 606 | - } | ||
| 607 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 608 | - return Err(error.into()); | ||
| 609 | - } | ||
| 610 | - // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. | ||
| 611 | - return result | ||
| 612 | - .take::<Vec<T>>(5)? | ||
| 613 | - .into_iter() | ||
| 614 | - .next() | ||
| 615 | - .map(ClaimedTwo::Made) | ||
| 616 | - .ok_or_else(|| AppError::Internal("cap claim wrote no row".into())); | ||
| 617 | - } | ||
| 618 | - Err(last | ||
| 619 | - .map(AppError::from) | ||
| 620 | - .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) | ||
| 621 | -} | ||
| 622 | - | ||
| 623 | -// --- reference counters -------------------------------------------------- | ||
| 624 | -// | ||
| 625 | -// The same single-record guard, pointed the other way. A cap asks "is there | ||
| 626 | -// room for one more child?"; a reference counter asks "may this *name* still be | ||
| 627 | -// used, and does anything still use it?" — the shape behind "an exam kind | ||
| 628 | -// nothing is graded under may leave the school's settings". Both questions are | ||
| 629 | -// answered by one row per name (`kind_ref:<name>`, `slot_ref:<name>`), created | ||
| 630 | -// on first use, so the removal and the last claim contend on a record rather | ||
| 631 | -// than on a cross-table count no transaction serializes. | ||
| 632 | -// | ||
| 633 | -// The two writes are exact mirrors: a claim lands only while the name is not | ||
| 634 | -// retired, a retirement lands only while the count is zero. Whichever reaches | ||
| 635 | -// the record first, the other is refused — in any process. | ||
| 636 | - | ||
| 637 | -/// What [`claim_ref_and_create`] settled. | ||
| 638 | pub(crate) enum ClaimedRef<T> { | 189 | pub(crate) enum ClaimedRef<T> { |
| 639 | /// The reference and the row committed together. | 190 | /// The reference and the row committed together. |
| 640 | Made(T), | 191 | Made(T), |
| 641 | - /// The name is retired — nothing was written, and no retry helps until the | 192 | + /// The name is retired — nothing was written, and no retry helps until |
| 642 | - /// name is put back in service. | 193 | + /// the name is put back in service. |
| 643 | Retired, | 194 | Retired, |
| 644 | /// Another writer placed this very row first, so this caller never owed a | 195 | /// Another writer placed this very row first, so this caller never owed a |
| 645 | /// reference: nothing was written, and the winner's row is the answer. | 196 | /// reference: nothing was written, and the winner's row is the answer. |
| 646 | Duplicate, | 197 | Duplicate, |
| 647 | } | 198 | } |
| 648 | -// | ||
| 649 | -// A separate enum rather than a `Retired` variant on [`Claimed`]: that enum is | ||
| 650 | -// matched exhaustively by a dozen callers in files this change does not touch, | ||
| 651 | -// and a cap has no retired state to answer for anyway. | ||
| 652 | - | ||
| 653 | -/// Take one reference on `counter` *and* write the row that holds it, in one | ||
| 654 | -/// transaction — [`claim_and_create`] pointed at a name instead of a cap. | ||
| 655 | -/// | ||
| 656 | -/// A bare reference claim followed by a separate insert cannot promise this: it | ||
| 657 | -/// lands, the insert then fails or the process dies, and the name is counted as | ||
| 658 | -/// used by a row that does not exist — which is a name nobody can ever retire. | ||
| 659 | -/// Here the abort takes the increment with it. | ||
| 660 | -/// | ||
| 661 | -/// The `$held` gate comes first for [`claim_and_create`]'s reason: where the | ||
| 662 | -/// child carries a deterministic id, a rival can place the very row this caller | ||
| 663 | -/// is placing, and "you already have it" is the honest answer — one that must | ||
| 664 | -/// not cost a reference. Which is also why this carries its own retry loop | ||
| 665 | -/// rather than [`crate::database::transaction_with_retry`]'s: the `CREATE` can | ||
| 666 | -/// legitimately answer "already exists", and that loop cannot tell that answer | ||
| 667 | -/// from a lost round. The `UPSERT` cannot answer it — `kind_ref`/`slot_ref` | ||
| 668 | -/// carry no `UNIQUE` index, so a write keyed by id resolves onto the row the id | ||
| 669 | -/// names. | ||
| 670 | -pub(crate) async fn claim_ref_and_create<T: SurrealValue + Clone>( | ||
| 671 | - counter: &RecordId, | ||
| 672 | - n: i64, | ||
| 673 | - id: &RecordId, | ||
| 674 | - content: &T, | ||
| 675 | - db: &Database, | ||
| 676 | -) -> Result<ClaimedRef<T>, AppError> { | ||
| 677 | - let sql = format!( | ||
| 678 | - "BEGIN TRANSACTION; | ||
| 679 | - LET $held = (SELECT VALUE id FROM $id); | ||
| 680 | - IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; | ||
| 681 | - LET $ref = (UPSERT $parent SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + $num \ | ||
| 682 | - WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id); | ||
| 683 | - IF array::len($ref) = 0 {{ THROW '{RETIRED_MARK}' }}; | ||
| 684 | - CREATE $id CONTENT $row; | ||
| 685 | - COMMIT TRANSACTION;" | ||
| 686 | - ); | ||
| 687 | - let _guard = CLAIM_LOCK.lock().await; | ||
| 688 | - let mut last = None; | ||
| 689 | - for attempt in 0..CAP_WRITE_TRIES { | ||
| 690 | - backoff(attempt).await; | ||
| 691 | - let attempted = db | ||
| 692 | - .query(sql.as_str()) | ||
| 693 | - .bind(("parent", counter.clone())) | ||
| 694 | - .bind(("num", n)) | ||
| 695 | - .bind(("id", id.clone())) | ||
| 696 | - .bind(("row", content.clone())) | ||
| 697 | - .await; | ||
| 698 | - let mut result = match attempted { | ||
| 699 | - Ok(result) => result, | ||
| 700 | - Err(err) if lost_the_race(&err) => { | ||
| 701 | - last = Some(err); | ||
| 702 | - continue; | ||
| 703 | - } | ||
| 704 | - Err(err) => return Err(err.into()), | ||
| 705 | - }; | ||
| 706 | - // An aborted transaction errors *every* slot, most with a generic "not | ||
| 707 | - // executed" — only the failing slot says why. The markers are read | ||
| 708 | - // before the conflict check, because a `THROW` is a decision. | ||
| 709 | - let mut errors = result.take_errors(); | ||
| 710 | - if errors | ||
| 711 | - .values() | ||
| 712 | - .any(|error| error.to_string().contains(HELD_MARK) || error.is_already_exists()) | ||
| 713 | - { | ||
| 714 | - return Ok(ClaimedRef::Duplicate); | ||
| 715 | - } | ||
| 716 | - if errors | ||
| 717 | - .values() | ||
| 718 | - .any(|error| error.to_string().contains(RETIRED_MARK)) | ||
| 719 | - { | ||
| 720 | - return Ok(ClaimedRef::Retired); | ||
| 721 | - } | ||
| 722 | - if errors.values().any(lost_the_race) { | ||
| 723 | - last = errors.drain().map(|(_, error)| error).find(lost_the_race); | ||
| 724 | - continue; | ||
| 725 | - } | ||
| 726 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 727 | - return Err(error.into()); | ||
| 728 | - } | ||
| 729 | - // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. | ||
| 730 | - return result | ||
| 731 | - .take::<Vec<T>>(5)? | ||
| 732 | - .into_iter() | ||
| 733 | - .next() | ||
| 734 | - .map(ClaimedRef::Made) | ||
| 735 | - .ok_or_else(|| AppError::Internal("cap claim wrote no row".into())); | ||
| 736 | - } | ||
| 737 | - Err(last | ||
| 738 | - .map(AppError::from) | ||
| 739 | - .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) | ||
| 740 | -} | ||
| 741 | 199 | ||
| 742 | /// What a retire / un-retire write did to the name's bit. | 200 | /// What a retire / un-retire write did to the name's bit. |
| 743 | /// | 201 | /// |
| @@ -753,530 +211,58 @@ pub(crate) enum Switched { | |||
| 753 | /// The bit already stood that way — this call wrote nothing, so there is | 211 | /// The bit already stood that way — this call wrote nothing, so there is |
| 754 | /// nothing to take back, and taking it back would undo somebody else. | 212 | /// nothing to take back, and taking it back would undo somebody else. |
| 755 | Unchanged, | 213 | Unchanged, |
| 756 | - /// Retirement only: something still references the name and the caller must | 214 | + /// Retirement only: something still references the name and the caller |
| 757 | - /// refuse. Nothing was written. | 215 | + /// must refuse. Nothing was written. |
| 758 | InUse, | 216 | InUse, |
| 759 | } | 217 | } |
| 760 | 218 | ||
| 761 | -/// Retire the name behind `id`: no further claim succeeds. Idempotent — a | 219 | +/// Which of [`ClaimedTwo`]'s caps refused a zero-row dual claim. |
| 762 | -/// retirement of an already-retired unused name lands again, and says so | 220 | +pub(crate) enum FullKind { |
| 763 | -/// ([`Switched::Unchanged`]) so the caller does not roll back a bit it never | 221 | + /// The resettable counter is full — recoverable by whatever empties it. |
| 764 | -/// set. | 222 | + Soft, |
| 765 | -pub(crate) async fn retire_name(id: &RecordId, db: &Database) -> Result<Switched, AppError> { | 223 | + /// The lifetime counter is full, the guard failed, or the parent row is |
| 766 | - // Parenthesized `??`: `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which | 224 | + /// gone — terminal. |
| 767 | - // is truthy for *every* row and would retire a name still in use. | 225 | + Hard, |
| 768 | - // | ||
| 769 | - // The bit as it stood is read in the *same round trip* as the write, so the | ||
| 770 | - // pair is one hold of `CLAIM_LOCK` (see [`switch`]) and no rival in this | ||
| 771 | - // process can retire the name between them and be undone by this caller. | ||
| 772 | - let sql = format!( | ||
| 773 | - "SELECT VALUE ({REF_RETIRED_FIELD} ?? false) FROM $parent; | ||
| 774 | - UPSERT $parent SET {REF_RETIRED_FIELD} = true \ | ||
| 775 | - WHERE ({REF_COUNT_FIELD} ?? 0) = 0 RETURN VALUE id" | ||
| 776 | - ); | ||
| 777 | - let (was, landed) = switch(&sql, id, db).await?; | ||
| 778 | - Ok(match (landed, was) { | ||
| 779 | - (false, _) => Switched::InUse, | ||
| 780 | - (true, true) => Switched::Unchanged, | ||
| 781 | - (true, false) => Switched::Flipped, | ||
| 782 | - }) | ||
| 783 | -} | ||
| 784 | - | ||
| 785 | -/// Put a name back in service — it re-entered the list it was retired from, or | ||
| 786 | -/// the edit that retired it never landed. [`Switched::Flipped`] only when the | ||
| 787 | -/// name really was retired, for [`retire_name`]'s reason pointed the other way. | ||
| 788 | -pub(crate) async fn unretire_name(id: &RecordId, db: &Database) -> Result<Switched, AppError> { | ||
| 789 | - let sql = format!( | ||
| 790 | - "SELECT VALUE ({REF_RETIRED_FIELD} ?? false) FROM $parent; | ||
| 791 | - UPSERT $parent SET {REF_RETIRED_FIELD} = false RETURN VALUE id" | ||
| 792 | - ); | ||
| 793 | - let (was, _) = switch(&sql, id, db).await?; | ||
| 794 | - Ok(if was { | ||
| 795 | - Switched::Flipped | ||
| 796 | - } else { | ||
| 797 | - Switched::Unchanged | ||
| 798 | - }) | ||
| 799 | -} | ||
| 800 | - | ||
| 801 | -/// [`retire_name`] as the yes/no the domain probes ask — did the name end up | ||
| 802 | -/// retired? **Test-only**: production callers roll their edit back and need to | ||
| 803 | -/// know which of the two "yes" answers they got. | ||
| 804 | -#[cfg(test)] | ||
| 805 | -pub(crate) async fn retire(id: &RecordId, db: &Database) -> Result<bool, AppError> { | ||
| 806 | - Ok(!matches!(retire_name(id, db).await?, Switched::InUse)) | ||
| 807 | } | 226 | } |
| 808 | 227 | ||
| 809 | -/// The read of the `retired` bit and the write that moves it, one round trip | 228 | +/// Map a zero-row dual-counter claim, re-read off the parent row, onto |
| 810 | -/// under one [`CLAIM_LOCK`] hold: `(bit as it stood, did the write match)`. | 229 | +/// [`ClaimedTwo`]'s two full states. |
| 811 | -async fn switch(sql: &str, parent: &RecordId, db: &Database) -> Result<(bool, bool), AppError> { | ||
| 812 | - let _guard = CLAIM_LOCK.lock().await; | ||
| 813 | - let mut last = None; | ||
| 814 | - for attempt in 0..CAP_WRITE_TRIES { | ||
| 815 | - backoff(attempt).await; | ||
| 816 | - let attempted = async { | ||
| 817 | - let mut result = db | ||
| 818 | - .query(sql) | ||
| 819 | - .bind(("parent", parent.clone())) | ||
| 820 | - .await? | ||
| 821 | - .check()?; | ||
| 822 | - let was = result | ||
| 823 | - .take::<Vec<bool>>(0)? | ||
| 824 | - .first() | ||
| 825 | - .copied() | ||
| 826 | - .unwrap_or(false); | ||
| 827 | - let landed = !result.take::<Vec<RecordId>>(1)?.is_empty(); | ||
| 828 | - Ok::<_, surrealdb::Error>((was, landed)) | ||
| 829 | - } | ||
| 830 | - .await; | ||
| 831 | - match attempted { | ||
| 832 | - Ok(answer) => return Ok(answer), | ||
| 833 | - Err(err) if lost_the_race(&err) => last = Some(err), | ||
| 834 | - Err(err) => return Err(err.into()), | ||
| 835 | - } | ||
| 836 | - } | ||
| 837 | - Err(last | ||
| 838 | - .map(AppError::from) | ||
| 839 | - .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) | ||
| 840 | -} | ||
| 841 | - | ||
| 842 | -/// Run one conditional counter write, retrying while the store reports a write | ||
| 843 | -/// conflict. | ||
| 844 | -/// | ||
| 845 | -/// Claimers contend on a single record by design — that contention *is* the | ||
| 846 | -/// guard — and SurrealDB resolves it optimistically: the loser's transaction is | ||
| 847 | -/// aborted with "can be retried" rather than queued, which the old mutex hid by | ||
| 848 | -/// never letting two writers reach the database at once. So the queueing has to | ||
| 849 | -/// happen here. Backoff is exponential with jitter, because racers arrive in | ||
| 850 | -/// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them. | ||
| 851 | -/// `num` is the statement's one number, bound as `$num` — the cap. | ||
| 852 | /// | 230 | /// |
| 853 | -/// **Test-only**, like its one caller [`claim`]: every production counter write | 231 | +/// The recipe bumps both counters in one `UPDATE` with the hard cap's |
| 854 | -/// now rides its child row's transaction and carries its own loop. | 232 | +/// conditions first, so zero rows means "hard full, guard failed, parent |
| 855 | -#[cfg(test)] | 233 | +/// gone, or soft full". The terminal cap outranks the recoverable one |
| 856 | -async fn write( | 234 | +/// everywhere: [`FullKind::Soft`] only when the soft counter is full *while* |
| 857 | - sql: &str, | 235 | +/// the hard one still has room — every other answer, including the ambiguous |
| 858 | - parent: &RecordId, | 236 | +/// guard/gone case, folds into [`FullKind::Hard`], whose contract already |
| 859 | - num: i64, | 237 | +/// covers it. This is the old claim order (hard claim, guard attached, before |
| 860 | - db: &Database, | 238 | +/// the soft one) expressed as a re-read. |
| 861 | -) -> Result<Vec<RecordId>, AppError> { | 239 | +pub(crate) fn full_kind(soft_count: i64, soft_cap: i64, hard_count: i64, hard_cap: i64) -> FullKind { |
| 862 | - let _guard = CLAIM_LOCK.lock().await; | 240 | + if soft_count >= soft_cap && hard_count < hard_cap { |
| 863 | - let mut last = None; | 241 | + FullKind::Soft |
| 864 | - for attempt in 0..CAP_WRITE_TRIES { | 242 | + } else { |
| 865 | - backoff(attempt).await; | 243 | + FullKind::Hard |
| 866 | - let attempted = async { | ||
| 867 | - let mut result = db | ||
| 868 | - .query(sql) | ||
| 869 | - .bind(("parent", parent.clone())) | ||
| 870 | - .bind(("num", num)) | ||
| 871 | - .await? | ||
| 872 | - .check()?; | ||
| 873 | - result.take::<Vec<RecordId>>(0) | ||
| 874 | - } | ||
| 875 | - .await; | ||
| 876 | - match attempted { | ||
| 877 | - Ok(hit) => return Ok(hit), | ||
| 878 | - // `lost_the_race` also matches "already exists", which an UPDATE | ||
| 879 | - // cannot produce — what is being reused here is its transaction | ||
| 880 | - // conflict detection, typed details first and wording second. | ||
| 881 | - Err(err) if lost_the_race(&err) => last = Some(err), | ||
| 882 | - Err(err) => return Err(err.into()), | ||
| 883 | - } | ||
| 884 | } | 244 | } |
| 885 | - Err(last | ||
| 886 | - .map(AppError::from) | ||
| 887 | - .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) | ||
| 888 | } | 245 | } |
| 889 | 246 | ||
| 890 | #[cfg(test)] | 247 | #[cfg(test)] |
| 891 | mod tests { | 248 | mod tests { |
| 892 | use super::*; | 249 | use super::*; |
| 893 | - use crate::constant::{ | ||
| 894 | - BOARD_EPOCH_STROKE_COUNT_FIELD, BOARD_OPEN_GUARD, BOARD_TOTAL_STROKE_COUNT_FIELD, | ||
| 895 | - }; | ||
| 896 | - | ||
| 897 | - #[derive(Debug, Clone, SurrealValue)] | ||
| 898 | - struct Stroke { | ||
| 899 | - board: RecordId, | ||
| 900 | - author: RecordId, | ||
| 901 | - kind: String, | ||
| 902 | - epoch: i64, | ||
| 903 | - created_at: i64, | ||
| 904 | - } | ||
| 905 | - | ||
| 906 | - /// The pair of counters, re-read out of the store — never off a return | ||
| 907 | - /// value, which the in-memory engine forges wins on (see `CLAIM_LOCK`). | ||
| 908 | - async fn stored(db: &Database) -> (i64, i64) { | ||
| 909 | - let mut result = db | ||
| 910 | - .query("SELECT VALUE [epoch_stroke_count ?? 0, total_stroke_count ?? 0] FROM board:b") | ||
| 911 | - .await | ||
| 912 | - .unwrap() | ||
| 913 | - .check() | ||
| 914 | - .unwrap(); | ||
| 915 | - let rows: Vec<Vec<i64>> = result.take(0).unwrap(); | ||
| 916 | - (rows[0][0], rows[0][1]) | ||
| 917 | - } | ||
| 918 | - | ||
| 919 | - async fn strokes(db: &Database) -> usize { | ||
| 920 | - let mut result = db | ||
| 921 | - .query("SELECT VALUE id FROM board_stroke") | ||
| 922 | - .await | ||
| 923 | - .unwrap() | ||
| 924 | - .check() | ||
| 925 | - .unwrap(); | ||
| 926 | - result.take::<Vec<RecordId>>(0).unwrap().len() | ||
| 927 | - } | ||
| 928 | - | ||
| 929 | - async fn a_board(epoch: i64, total: i64, locked: bool) -> Database { | ||
| 930 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 931 | - db.query( | ||
| 932 | - "CREATE user:u SET username = 'u', password_hash = 'x'; | ||
| 933 | - CREATE board:b SET creator = user:u, title = 't', participants = [user:u], | ||
| 934 | - locked = $locked, epoch = 0, epoch_stroke_count = $epoch, | ||
| 935 | - total_stroke_count = $total, created_at = 1;", | ||
| 936 | - ) | ||
| 937 | - .bind(("locked", locked)) | ||
| 938 | - .bind(("epoch", epoch)) | ||
| 939 | - .bind(("total", total)) | ||
| 940 | - .await | ||
| 941 | - .unwrap() | ||
| 942 | - .check() | ||
| 943 | - .unwrap(); | ||
| 944 | - db | ||
| 945 | - } | ||
| 946 | - | ||
| 947 | - fn a_stroke() -> Stroke { | ||
| 948 | - Stroke { | ||
| 949 | - board: RecordId::new("board", "b"), | ||
| 950 | - author: RecordId::new("user", "u"), | ||
| 951 | - kind: "stroke".into(), | ||
| 952 | - epoch: 0, | ||
| 953 | - created_at: 2, | ||
| 954 | - } | ||
| 955 | - } | ||
| 956 | - | ||
| 957 | - async fn claim(db: &Database, caps: [i64; 2], key: &str) -> ClaimedTwo<Stroke> { | ||
| 958 | - claim_two_when_and_create( | ||
| 959 | - &RecordId::new("board", "b"), | ||
| 960 | - (BOARD_EPOCH_STROKE_COUNT_FIELD, caps[0]), | ||
| 961 | - (BOARD_TOTAL_STROKE_COUNT_FIELD, caps[1]), | ||
| 962 | - BOARD_OPEN_GUARD, | ||
| 963 | - &RecordId::new("board_stroke", key), | ||
| 964 | - &a_stroke(), | ||
| 965 | - db, | ||
| 966 | - ) | ||
| 967 | - .await | ||
| 968 | - .unwrap() | ||
| 969 | - } | ||
| 970 | - | ||
| 971 | - #[tokio::test] | ||
| 972 | - async fn both_counters_move_together_or_not_at_all() { | ||
| 973 | - let db = a_board(0, 0, false).await; | ||
| 974 | - assert!(matches!( | ||
| 975 | - claim(&db, [2, 2], "s1").await, | ||
| 976 | - ClaimedTwo::Made(_) | ||
| 977 | - )); | ||
| 978 | - assert_eq!(stored(&db).await, (1, 1)); | ||
| 979 | - assert_eq!(strokes(&db).await, 1); | ||
| 980 | - } | ||
| 981 | - | ||
| 982 | - /// One cap refuses; the *other* counter must not have advanced, asserted by | ||
| 983 | - /// re-reading the row. A drift here would let the lifetime cap be passed. | ||
| 984 | - #[tokio::test] | ||
| 985 | - async fn a_refused_claim_advances_neither_counter() { | ||
| 986 | - // Soft (epoch) full, hard (lifetime) with room to spare. | ||
| 987 | - let db = a_board(5, 5, false).await; | ||
| 988 | - assert!(matches!( | ||
| 989 | - claim(&db, [5, 99], "s1").await, | ||
| 990 | - ClaimedTwo::FullSoft | ||
| 991 | - )); | ||
| 992 | - assert_eq!(stored(&db).await, (5, 5)); | ||
| 993 | - assert_eq!(strokes(&db).await, 0); | ||
| 994 | - | ||
| 995 | - // Hard full, soft with room to spare. | ||
| 996 | - let db = a_board(5, 5, false).await; | ||
| 997 | - assert!(matches!( | ||
| 998 | - claim(&db, [99, 5], "s1").await, | ||
| 999 | - ClaimedTwo::FullHard | ||
| 1000 | - )); | ||
| 1001 | - assert_eq!(stored(&db).await, (5, 5)); | ||
| 1002 | - assert_eq!(strokes(&db).await, 0); | ||
| 1003 | - } | ||
| 1004 | - | ||
| 1005 | - /// The two `THROW` markers must reach the caller as *different* answers: | ||
| 1006 | - /// one board is recoverable by a clear, the other is read-only for good. | ||
| 1007 | - #[tokio::test] | ||
| 1008 | - async fn the_two_caps_refuse_distinguishably() { | ||
| 1009 | - let db = a_board(5, 5, false).await; | ||
| 1010 | - let soft = claim(&db, [5, 99], "s1").await; | ||
| 1011 | - let hard = claim(&db, [99, 5], "s2").await; | ||
| 1012 | - assert!(matches!(soft, ClaimedTwo::FullSoft)); | ||
| 1013 | - assert!(matches!(hard, ClaimedTwo::FullHard)); | ||
| 1014 | - assert_eq!(stored(&db).await, (5, 5)); | ||
| 1015 | - } | ||
| 1016 | - | ||
| 1017 | - #[tokio::test] | ||
| 1018 | - async fn the_guard_refuses_a_locked_board() { | ||
| 1019 | - let db = a_board(0, 0, true).await; | ||
| 1020 | - assert!(matches!( | ||
| 1021 | - claim(&db, [9, 9], "s1").await, | ||
| 1022 | - ClaimedTwo::FullHard | ||
| 1023 | - )); | ||
| 1024 | - assert_eq!(stored(&db).await, (0, 0)); | ||
| 1025 | - assert_eq!(strokes(&db).await, 0); | ||
| 1026 | - } | ||
| 1027 | - | ||
| 1028 | - // --- claim_when_and_create ------------------------------------------ | ||
| 1029 | - | ||
| 1030 | - async fn claim_one(db: &Database, cap: i64, key: &str) -> Claimed<Stroke> { | ||
| 1031 | - claim_when_and_create( | ||
| 1032 | - &RecordId::new("board", "b"), | ||
| 1033 | - BOARD_EPOCH_STROKE_COUNT_FIELD, | ||
| 1034 | - cap, | ||
| 1035 | - BOARD_OPEN_GUARD, | ||
| 1036 | - &RecordId::new("board_stroke", key), | ||
| 1037 | - &a_stroke(), | ||
| 1038 | - db, | ||
| 1039 | - ) | ||
| 1040 | - .await | ||
| 1041 | - .unwrap() | ||
| 1042 | - } | ||
| 1043 | - | ||
| 1044 | - #[tokio::test] | ||
| 1045 | - async fn a_guarded_claim_advances_its_counter_exactly_once() { | ||
| 1046 | - let db = a_board(0, 0, false).await; | ||
| 1047 | - assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Made(_))); | ||
| 1048 | - assert_eq!(stored(&db).await, (1, 0)); | ||
| 1049 | - assert_eq!(strokes(&db).await, 1); | ||
| 1050 | - } | ||
| 1051 | - | ||
| 1052 | - /// A failed guard is refused as `Full` (the one marker covers full, guard | ||
| 1053 | - /// and missing parent), and must leave the counter and the table alone. | ||
| 1054 | - #[tokio::test] | ||
| 1055 | - async fn a_guard_refusal_advances_neither_counter_nor_row() { | ||
| 1056 | - let db = a_board(0, 0, true).await; | ||
| 1057 | - assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Full)); | ||
| 1058 | - assert_eq!(stored(&db).await, (0, 0)); | ||
| 1059 | - assert_eq!(strokes(&db).await, 0); | ||
| 1060 | - } | ||
| 1061 | - | ||
| 1062 | - /// The second writer at the same id owes no seat: the row is already there, | ||
| 1063 | - /// so the counter must not move a second time for it. | ||
| 1064 | - #[tokio::test] | ||
| 1065 | - async fn a_duplicate_row_claims_no_seat() { | ||
| 1066 | - let db = a_board(0, 0, false).await; | ||
| 1067 | - assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Made(_))); | ||
| 1068 | - assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Duplicate)); | ||
| 1069 | - assert_eq!(stored(&db).await, (1, 0)); | ||
| 1070 | - assert_eq!(strokes(&db).await, 1); | ||
| 1071 | - } | ||
| 1072 | - | ||
| 1073 | - // --- claim_ref_and_create ------------------------------------------- | ||
| 1074 | - | ||
| 1075 | - #[derive(Debug, Clone, SurrealValue)] | ||
| 1076 | - struct Menu { | ||
| 1077 | - date: String, | ||
| 1078 | - slot: String, | ||
| 1079 | - created_by: RecordId, | ||
| 1080 | - created_at: i64, | ||
| 1081 | - } | ||
| 1082 | - | ||
| 1083 | - async fn a_slot(count: i64, retired: bool) -> Database { | ||
| 1084 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 1085 | - db.query( | ||
| 1086 | - "CREATE user:u SET username = 'u', password_hash = 'x'; | ||
| 1087 | - UPSERT slot_ref:lunch SET count = $count, retired = $retired;", | ||
| 1088 | - ) | ||
| 1089 | - .bind(("count", count)) | ||
| 1090 | - .bind(("retired", retired)) | ||
| 1091 | - .await | ||
| 1092 | - .unwrap() | ||
| 1093 | - .check() | ||
| 1094 | - .unwrap(); | ||
| 1095 | - db | ||
| 1096 | - } | ||
| 1097 | - | ||
| 1098 | - /// The reference count, re-read out of the store — never off a return | ||
| 1099 | - /// value, which the in-memory engine forges wins on (see `CLAIM_LOCK`). | ||
| 1100 | - async fn refs(db: &Database) -> i64 { | ||
| 1101 | - let mut result = db | ||
| 1102 | - .query("SELECT VALUE (count ?? 0) FROM slot_ref:lunch") | ||
| 1103 | - .await | ||
| 1104 | - .unwrap() | ||
| 1105 | - .check() | ||
| 1106 | - .unwrap(); | ||
| 1107 | - result.take::<Vec<i64>>(0).unwrap()[0] | ||
| 1108 | - } | ||
| 1109 | - | ||
| 1110 | - async fn menus(db: &Database) -> usize { | ||
| 1111 | - let mut result = db | ||
| 1112 | - .query("SELECT VALUE id FROM menu") | ||
| 1113 | - .await | ||
| 1114 | - .unwrap() | ||
| 1115 | - .check() | ||
| 1116 | - .unwrap(); | ||
| 1117 | - result.take::<Vec<RecordId>>(0).unwrap().len() | ||
| 1118 | - } | ||
| 1119 | - | ||
| 1120 | - async fn claim_slot(db: &Database, key: &str) -> ClaimedRef<Menu> { | ||
| 1121 | - claim_ref_and_create( | ||
| 1122 | - &RecordId::new(crate::constant::SLOT_REF_TABLE, "lunch"), | ||
| 1123 | - 1, | ||
| 1124 | - &RecordId::new("menu", key), | ||
| 1125 | - &Menu { | ||
| 1126 | - date: "2026-08-02".into(), | ||
| 1127 | - slot: "lunch".into(), | ||
| 1128 | - created_by: RecordId::new("user", "u"), | ||
| 1129 | - created_at: 1, | ||
| 1130 | - }, | ||
| 1131 | - db, | ||
| 1132 | - ) | ||
| 1133 | - .await | ||
| 1134 | - .unwrap() | ||
| 1135 | - } | ||
| 1136 | - | ||
| 1137 | - #[tokio::test] | ||
| 1138 | - async fn a_reference_and_its_row_land_together() { | ||
| 1139 | - let db = a_slot(0, false).await; | ||
| 1140 | - assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Made(_))); | ||
| 1141 | - assert_eq!(refs(&db).await, 1); | ||
| 1142 | - assert_eq!(menus(&db).await, 1); | ||
| 1143 | - } | ||
| 1144 | - | ||
| 1145 | - /// A retired name refuses, and the refusal must cost nothing: no row, no | ||
| 1146 | - /// count — a counted row on a retired name is a name nobody can retire. | ||
| 1147 | - #[tokio::test] | ||
| 1148 | - async fn a_retired_name_refuses_with_no_row_and_no_count() { | ||
| 1149 | - let db = a_slot(0, true).await; | ||
| 1150 | - assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Retired)); | ||
| 1151 | - assert_eq!(refs(&db).await, 0); | ||
| 1152 | - assert_eq!(menus(&db).await, 0); | ||
| 1153 | - } | ||
| 1154 | - | ||
| 1155 | - /// The `retired` bit as the store holds it, `None` when the row is absent. | ||
| 1156 | - async fn bit(db: &Database) -> Option<bool> { | ||
| 1157 | - let mut result = db | ||
| 1158 | - .query("SELECT VALUE retired FROM slot_ref:lunch") | ||
| 1159 | - .await | ||
| 1160 | - .unwrap() | ||
| 1161 | - .check() | ||
| 1162 | - .unwrap(); | ||
| 1163 | - result.take::<Vec<bool>>(0).unwrap().first().copied() | ||
| 1164 | - } | ||
| 1165 | - | ||
| 1166 | - fn lunch() -> RecordId { | ||
| 1167 | - RecordId::new(crate::constant::SLOT_REF_TABLE, "lunch") | ||
| 1168 | - } | ||
| 1169 | - | ||
| 1170 | - /// Retirement is idempotent, so "it is retired now" is *not* "I retired | ||
| 1171 | - /// it" — and a caller that rolls back on the second answer un-retires a | ||
| 1172 | - /// name somebody else legitimately took out of service. That is the whole | ||
| 1173 | - /// settings-CAS wedge: the list drops the name, the counter says in | ||
| 1174 | - /// service, the name grades again and can then never be removed. | ||
| 1175 | - #[tokio::test] | ||
| 1176 | - async fn a_second_retirement_says_it_changed_nothing() { | ||
| 1177 | - let db = a_slot(0, false).await; | ||
| 1178 | - assert!(matches!( | ||
| 1179 | - retire_name(&lunch(), &db).await.unwrap(), | ||
| 1180 | - Switched::Flipped | ||
| 1181 | - )); | ||
| 1182 | - assert!(matches!( | ||
| 1183 | - retire_name(&lunch(), &db).await.unwrap(), | ||
| 1184 | - Switched::Unchanged | ||
| 1185 | - )); | ||
| 1186 | - assert_eq!(bit(&db).await, Some(true), "the winner's bit still stands"); | ||
| 1187 | - } | ||
| 1188 | - | ||
| 1189 | - /// The mirror: only the un-retire that really put a name back in service | ||
| 1190 | - /// owes a re-retirement, so a re-add that never lands cannot be undone | ||
| 1191 | - /// twice. | ||
| 1192 | - #[tokio::test] | ||
| 1193 | - async fn a_second_un_retirement_says_it_changed_nothing() { | ||
| 1194 | - let db = a_slot(0, true).await; | ||
| 1195 | - assert!(matches!( | ||
| 1196 | - unretire_name(&lunch(), &db).await.unwrap(), | ||
| 1197 | - Switched::Flipped | ||
| 1198 | - )); | ||
| 1199 | - assert!(matches!( | ||
| 1200 | - unretire_name(&lunch(), &db).await.unwrap(), | ||
| 1201 | - Switched::Unchanged | ||
| 1202 | - )); | ||
| 1203 | - assert_eq!(bit(&db).await, Some(false)); | ||
| 1204 | - } | ||
| 1205 | - | ||
| 1206 | - /// A referenced name is refused, and the refusal writes nothing — the | ||
| 1207 | - /// caller must not record an undo for it either. | ||
| 1208 | - #[tokio::test] | ||
| 1209 | - async fn a_referenced_name_refuses_and_leaves_the_bit_alone() { | ||
| 1210 | - let db = a_slot(1, false).await; | ||
| 1211 | - assert!(matches!( | ||
| 1212 | - retire_name(&lunch(), &db).await.unwrap(), | ||
| 1213 | - Switched::InUse | ||
| 1214 | - )); | ||
| 1215 | - assert_eq!(bit(&db).await, Some(false)); | ||
| 1216 | - } | ||
| 1217 | - | ||
| 1218 | - // --- claim_live_and_create ------------------------------------------ | ||
| 1219 | - | ||
| 1220 | - /// The cap the statement reads and the cap the caller remembers are | ||
| 1221 | - /// different numbers the moment anyone edits the cap. `epoch` stands in for | ||
| 1222 | - /// a capacity column here — any int on the parent row does. | ||
| 1223 | - #[tokio::test] | ||
| 1224 | - async fn a_live_cap_refuses_where_the_caller_s_snapshot_admits() { | ||
| 1225 | - let db = a_board(1, 0, false).await; | ||
| 1226 | - db.query("UPDATE board:b SET epoch = 1") | ||
| 1227 | - .await | ||
| 1228 | - .unwrap() | ||
| 1229 | - .check() | ||
| 1230 | - .unwrap(); | ||
| 1231 | - | ||
| 1232 | - // Live: one seat, one taken — full, and nothing written. | ||
| 1233 | - let live = claim_live_and_create( | ||
| 1234 | - &RecordId::new("board", "b"), | ||
| 1235 | - BOARD_EPOCH_STROKE_COUNT_FIELD, | ||
| 1236 | - "epoch ?? $num", | ||
| 1237 | - UNLIMITED, | ||
| 1238 | - None, | ||
| 1239 | - (&RecordId::new("board_stroke", "s1"), &a_stroke()), | ||
| 1240 | - &db, | ||
| 1241 | - ) | ||
| 1242 | - .await | ||
| 1243 | - .unwrap(); | ||
| 1244 | - assert!(matches!(live, Claimed::Full)); | ||
| 1245 | - assert_eq!(stored(&db).await, (1, 0)); | ||
| 1246 | - assert_eq!(strokes(&db).await, 0); | ||
| 1247 | - | ||
| 1248 | - // The same row, the same instant, against a cap of 5 the caller read | ||
| 1249 | - // before it was lowered: admitted. That gap is the over-admission. | ||
| 1250 | - assert!(matches!(claim_one(&db, 5, "s2").await, Claimed::Made(_))); | ||
| 1251 | - assert_eq!(stored(&db).await, (2, 0)); | ||
| 1252 | - } | ||
| 1253 | - | ||
| 1254 | - /// An unset capacity column means "no cap", which is the bound `$num` | ||
| 1255 | - /// fallback — not a cap of zero that refuses everything. | ||
| 1256 | - #[tokio::test] | ||
| 1257 | - async fn an_absent_live_cap_falls_back_to_the_bound_number() { | ||
| 1258 | - let db = a_board(0, 0, false).await; | ||
| 1259 | - let made = claim_live_and_create( | ||
| 1260 | - &RecordId::new("board", "b"), | ||
| 1261 | - BOARD_EPOCH_STROKE_COUNT_FIELD, | ||
| 1262 | - "capacity ?? $num", | ||
| 1263 | - UNLIMITED, | ||
| 1264 | - None, | ||
| 1265 | - (&RecordId::new("board_stroke", "s1"), &a_stroke()), | ||
| 1266 | - &db, | ||
| 1267 | - ) | ||
| 1268 | - .await | ||
| 1269 | - .unwrap(); | ||
| 1270 | - assert!(matches!(made, Claimed::Made(_))); | ||
| 1271 | - assert_eq!(stored(&db).await, (1, 0)); | ||
| 1272 | - } | ||
| 1273 | 250 | ||
| 1274 | - #[tokio::test] | 251 | + /// The terminal cap outranks the recoverable one: only a soft-full-with- |
| 1275 | - async fn a_duplicate_row_claims_no_reference() { | 252 | + /// hard-room claim is recoverable, everything else answers Hard — the old |
| 1276 | - let db = a_slot(0, false).await; | 253 | + /// claim order (hard first, guard attached), preserved as a re-read. |
| 1277 | - assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Made(_))); | 254 | + #[test] |
| 1278 | - assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Duplicate)); | 255 | + fn the_terminal_cap_outranks_the_recoverable_one() { |
| 1279 | - assert_eq!(refs(&db).await, 1); | 256 | + // Soft full, hard with room: the one recoverable answer. |
| 1280 | - assert_eq!(menus(&db).await, 1); | 257 | + assert!(matches!(full_kind(5, 5, 9, 10), FullKind::Soft)); |
| 258 | + // Both full: terminal. | ||
| 259 | + assert!(matches!(full_kind(5, 5, 9, 9), FullKind::Hard)); | ||
| 260 | + // Hard full alone. | ||
| 261 | + assert!(matches!(full_kind(4, 5, 9, 9), FullKind::Hard)); | ||
| 262 | + // Neither full — the guard failed or the parent is gone, and both fold | ||
| 263 | + // into the terminal answer, whose contract already covers them. | ||
| 264 | + assert!(matches!(full_kind(4, 5, 8, 9), FullKind::Hard)); | ||
| 265 | + // Boundaries: exactly-at-cap is full. | ||
| 266 | + assert!(matches!(full_kind(5, 5, 10, 10), FullKind::Hard)); | ||
| 1281 | } | 267 | } |
| 1282 | } | 268 | } |
src/db/field_update.rsmodified+319 -362
| @@ -1,106 +1,131 @@ | |||
| 1 | -//! One `UPDATE $id SET ... RETURN AFTER` built from *only* the fields a PATCH | 1 | +//! One `UPDATE <table> … WHERE id = $n RETURNING *` built from *only* the |
| 2 | -//! actually carried. | 2 | +//! fields a PATCH actually carried. |
| 3 | //! | 3 | //! |
| 4 | //! WHY: a handler reads the row, then writes. Filling a field the request | 4 | //! WHY: a handler reads the row, then writes. Filling a field the request |
| 5 | //! omitted from that snapshot re-sends a value the client never gave, so a | 5 | //! omitted from that snapshot re-sends a value the client never gave, so a |
| 6 | //! concurrent PATCH of the *other* field that landed in between is silently | 6 | //! concurrent PATCH of the *other* field that landed in between is silently |
| 7 | -//! reverted — the same lost update a whole-row `.content(self)` save causes, | 7 | +//! reverted — the lost update a whole-row save causes, just spelled field by |
| 8 | -//! just spelled field by field. Scoping the `SET` is not enough; the *values* must come | 8 | +//! field. Scoping the `SET` is not enough; the *values* must come from the |
| 9 | -//! from the request, so an absent field is never written at all. | 9 | +//! request, so an absent field is never written at all. |
| 10 | //! | 10 | //! |
| 11 | -//! Callers therefore take `Option<T>` per field (`None` = absent, keep) and | 11 | +//! Callers take `Option<T>` per field (`None` = absent, keep) and hand them |
| 12 | -//! hand them straight here: | 12 | +//! straight here: |
| 13 | //! | 13 | //! |
| 14 | //! ```ignore | 14 | //! ```ignore |
| 15 | -//! FieldUpdate::new(self.id.record()) | 15 | +//! FieldUpdate::new("note", note.id.0) |
| 16 | //! .set("title", title) | 16 | //! .set("title", title) |
| 17 | //! .set("content", content) | 17 | //! .set("content", content) |
| 18 | //! .run::<Note>(db) | 18 | //! .run::<Note>(db) |
| 19 | //! .await | 19 | //! .await |
| 20 | //! ``` | 20 | //! ``` |
| 21 | //! | 21 | //! |
| 22 | -//! Clearing a nullable column is `Some(None)` on a `Option<Option<T>>` field | 22 | +//! Clearing a nullable column is `Some(None)` on an `Option<Option<T>>` |
| 23 | -//! — pass it as `Some(value_or_none)` so `NONE` is written explicitly. | 23 | +//! field — pass it as `Some(value_or_none)` so `NULL` is written explicitly |
| 24 | +//! (for a link column, `Param::OptUuid(None)`). | ||
| 25 | +//! | ||
| 26 | +//! Runtime-checked SQL by design (this module is the named exemption from the | ||
| 27 | +//! compile-time `query!` rule): the `SET` list is the request's shape. All | ||
| 28 | +//! emitted statements are plain Postgres — positional `$n` placeholders, the | ||
| 29 | +//! row read back with `RETURNING *` (the old store's return-updated-document | ||
| 30 | +//! spelling), and an explicit clear written as a bound `NULL`; there is no | ||
| 31 | +//! remove-a-key statement a row needs a counterpart for. | ||
| 32 | +//! | ||
| 33 | +//! The dynamic parts of every statement here are table/column names (in-crate | ||
| 34 | +//! `&'static str` constants, never client text) and the `$n` numbers this | ||
| 35 | +//! builder prints itself; every value binds — which is the audit the | ||
| 36 | +//! [`AssertSqlSafe`] wraps stand on. | ||
| 24 | 37 | ||
| 25 | -use surrealdb::types::{RecordId, SurrealValue, Value}; | 38 | +use sqlx::postgres::{PgArguments, PgRow}; |
| 39 | +use sqlx::{AssertSqlSafe, FromRow}; | ||
| 40 | +use uuid::Uuid; | ||
| 26 | 41 | ||
| 27 | -use crate::database::{Database, transaction_with_retry, write_with_retry}; | 42 | +use crate::database::{Database, tx_with_retry}; |
| 28 | -use crate::db::cap; | 43 | +use crate::db::page::Param; |
| 29 | use crate::error::AppError; | 44 | use crate::error::AppError; |
| 30 | 45 | ||
| 31 | -/// The `THROW` markers [`FieldUpdate::refcount`]'s transaction aborts with: the | 46 | +/// The statement-shaped markers [`run_with_refcount`]'s transaction aborts |
| 32 | -/// row the reference was to be claimed on is gone, the row being patched is | 47 | +/// with, mapped to their answers right after [`tx_with_retry`] returns. They |
| 33 | -/// gone (or its guard bit), and the link this move started from is no longer | 48 | +/// never reach the wire: a refusal is a decision, never a retry, and the |
| 34 | -/// the one the handler read. | 49 | +/// marker `Internal` error is replaced before it can escape. |
| 35 | -const CLAIM_MARK: &str = "ref_claim_gone"; | 50 | +const REFUSAL_MARK: &str = "ref_claim_gone"; |
| 36 | -const ROW_MARK: &str = "ref_row_gone"; | ||
| 37 | const STALE_MARK: &str = "ref_stale_move"; | 51 | const STALE_MARK: &str = "ref_stale_move"; |
| 52 | +const GONE_MARK: &str = "ref_row_gone"; | ||
| 38 | 53 | ||
| 39 | -/// `(counter field, link column, expected link, claim, release, refusal)`. | 54 | +/// The answer a moved link has always carried. |
| 55 | +const STALE_MOVE: &str = "the link this update moves changed since it was read; re-read and retry"; | ||
| 56 | + | ||
| 57 | +/// An abort marker packed as the one error arm no caller ever observes. | ||
| 58 | +fn mark(kind: &'static str) -> AppError { | ||
| 59 | + AppError::Internal(kind.to_owned()) | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +/// `(counter table, counter field, link column, expected link, claim, release, | ||
| 63 | +/// refusal)`. | ||
| 40 | type Refcount = ( | 64 | type Refcount = ( |
| 41 | &'static str, | 65 | &'static str, |
| 42 | &'static str, | 66 | &'static str, |
| 43 | - Option<RecordId>, | 67 | + &'static str, |
| 44 | - Option<RecordId>, | 68 | + Option<Uuid>, |
| 45 | - Option<RecordId>, | 69 | + Option<Uuid>, |
| 70 | + Option<Uuid>, | ||
| 46 | AppError, | 71 | AppError, |
| 47 | ); | 72 | ); |
| 48 | 73 | ||
| 49 | -pub struct FieldUpdate { | 74 | +pub(crate) struct FieldUpdate { |
| 50 | - id: RecordId, | 75 | + /// The row's own table — an in-crate constant, never user input. |
| 51 | - /// `field = $field` fragments, in the order they were set. | 76 | + table: &'static str, |
| 52 | - assignments: Vec<String>, | 77 | + id: Uuid, |
| 53 | - bindings: Vec<(String, Value)>, | 78 | + /// `(field, value)` fragments, in the order they were set; a value's |
| 79 | + /// placeholder number is its position here plus one. | ||
| 80 | + sets: Vec<(&'static str, Param)>, | ||
| 54 | /// `(low, high, refusal)` for [`FieldUpdate::ordered`]. | 81 | /// `(low, high, refusal)` for [`FieldUpdate::ordered`]. |
| 55 | ordered: Option<(&'static str, &'static str, AppError)>, | 82 | ordered: Option<(&'static str, &'static str, AppError)>, |
| 56 | /// `(condition, refusal)` for [`FieldUpdate::guard`]. | 83 | /// `(condition, refusal)` for [`FieldUpdate::guard`]. |
| 57 | guard: Option<(&'static str, AppError)>, | 84 | guard: Option<(&'static str, AppError)>, |
| 58 | - /// `(counter field, link column, expected link, claim, release, refusal)` | 85 | + /// `(counter table, counter field, link column, expected link, claim, |
| 59 | - /// for [`FieldUpdate::refcount`]. | 86 | + /// release, refusal)` for [`FieldUpdate::refcount`]. |
| 60 | refcount: Option<Refcount>, | 87 | refcount: Option<Refcount>, |
| 61 | } | 88 | } |
| 62 | 89 | ||
| 63 | impl FieldUpdate { | 90 | impl FieldUpdate { |
| 64 | - pub fn new(id: RecordId) -> Self { | 91 | + /// `table` names the row's table; `id` is its uuid primary key. |
| 92 | + pub(crate) fn new(table: &'static str, id: Uuid) -> Self { | ||
| 65 | Self { | 93 | Self { |
| 94 | + table, | ||
| 66 | id, | 95 | id, |
| 67 | - assignments: Vec::new(), | 96 | + sets: Vec::new(), |
| 68 | - bindings: Vec::new(), | ||
| 69 | ordered: None, | 97 | ordered: None, |
| 70 | guard: None, | 98 | guard: None, |
| 71 | refcount: None, | 99 | refcount: None, |
| 72 | } | 100 | } |
| 73 | } | 101 | } |
| 74 | 102 | ||
| 75 | - /// Write `field` only when the request carried it. The bind variable is | 103 | + /// Write `field` only when the request carried it. The value binds as the |
| 76 | - /// named after the field, so `id` — and `ref_claim`/`ref_release`/ | 104 | + /// `SET` list's next positional parameter, in call order. |
| 77 | - /// `ref_expected`, which [`FieldUpdate::refcount`] binds — are the names a | ||
| 78 | - /// caller must not use. | ||
| 79 | #[must_use] | 105 | #[must_use] |
| 80 | - pub fn set<T: SurrealValue>(mut self, field: &'static str, value: Option<T>) -> Self { | 106 | + pub(crate) fn set<T: Into<Param>>(mut self, field: &'static str, value: Option<T>) -> Self { |
| 81 | if let Some(value) = value { | 107 | if let Some(value) = value { |
| 82 | - self.assignments.push(format!("{field} = ${field}")); | 108 | + self.sets.push((field, value.into())); |
| 83 | - self.bindings.push((field.to_string(), value.into_value())); | ||
| 84 | } | 109 | } |
| 85 | self | 110 | self |
| 86 | } | 111 | } |
| 87 | 112 | ||
| 88 | /// Refuse the write unless `low <= high` still holds on the *merged* row — | 113 | /// Refuse the write unless `low <= high` still holds on the *merged* row — |
| 89 | - /// the new value for an end this PATCH carries, the stored column for one it | 114 | + /// the new value for an end this PATCH carries, the stored column for one |
| 90 | - /// omits. Emitted as a `WHERE` on the same `UPDATE`, so the comparison the | 115 | + /// it omits. Emitted as a `WHERE` on the same `UPDATE`, so the comparison |
| 91 | - /// handler made against its snapshot is re-made by the database at write | 116 | + /// the handler made against its snapshot is re-made by the database at |
| 92 | - /// time, against the row as it is *then*: two PATCHes each moving one end, | 117 | + /// write time, against the row as it is *then*: two PATCHes each moving |
| 93 | - /// each fine on its own, cannot commit an inverted range between them. That | 118 | + /// one end, each fine on its own, cannot commit an inverted range between |
| 94 | - /// is what an in-process `Mutex` used to buy, without a window between the | 119 | + /// them. That is what an in-process `Mutex` used to buy, without a window |
| 95 | - /// snapshot and the write for a concurrent request to slip into. | 120 | + /// between the snapshot and the write for a concurrent request to slip |
| 121 | + /// into. | ||
| 96 | /// | 122 | /// |
| 97 | /// Call it after the `.set()`s of both fields. A PATCH that moves neither | 123 | /// Call it after the `.set()`s of both fields. A PATCH that moves neither |
| 98 | - /// end emits no guard at all (nothing to race), matching the lock window it | 124 | + /// end emits no guard at all (nothing to race), so a pre-existing inverted |
| 99 | - /// replaces — so a pre-existing inverted row stays editable field by field. | 125 | + /// row stays editable field by field. `NULL` on either side passes, |
| 100 | - /// `NONE` on either side passes, exactly like | 126 | + /// exactly like [`crate::web::check_time_range`] skipping an absent end. |
| 101 | - /// [`crate::web::check_time_range`] skipping an absent end. | ||
| 102 | #[must_use] | 127 | #[must_use] |
| 103 | - pub fn ordered(mut self, low: &'static str, high: &'static str, refused: AppError) -> Self { | 128 | + pub(crate) fn ordered(mut self, low: &'static str, high: &'static str, refused: AppError) -> Self { |
| 104 | self.ordered = Some((low, high, refused)); | 129 | self.ordered = Some((low, high, refused)); |
| 105 | self | 130 | self |
| 106 | } | 131 | } |
| @@ -108,122 +133,158 @@ impl FieldUpdate { | |||
| 108 | /// Refuse the write unless `condition` — a predicate on this same row — | 133 | /// Refuse the write unless `condition` — a predicate on this same row — |
| 109 | /// still holds at write time. The [`FieldUpdate::ordered`] guard for a | 134 | /// still holds at write time. The [`FieldUpdate::ordered`] guard for a |
| 110 | /// precondition that is not about a range: a handler that read "nothing | 135 | /// precondition that is not about a range: a handler that read "nothing |
| 111 | - /// references this yet" re-asks the database at the instant it writes, so a | 136 | + /// references this yet" re-asks the database at the instant it writes, so |
| 112 | - /// reference landing in between refuses the edit instead of being edited | 137 | + /// a reference landing in between refuses the edit instead of being |
| 113 | - /// out from under. `condition` is always an in-crate SQL literal, never | 138 | + /// edited out from under. `condition` is always an in-crate SQL literal, |
| 114 | - /// user input. | 139 | + /// never user input. |
| 115 | /// | 140 | /// |
| 116 | /// A request that carries no field at all emits no `UPDATE`, so it is not | 141 | /// A request that carries no field at all emits no `UPDATE`, so it is not |
| 117 | /// refused: it writes nothing, and reading the row back is a truthful | 142 | /// refused: it writes nothing, and reading the row back is a truthful |
| 118 | /// answer to a PATCH that asked for no change. | 143 | /// answer to a PATCH that asked for no change. |
| 119 | #[must_use] | 144 | #[must_use] |
| 120 | - pub fn guard(mut self, condition: &'static str, refused: AppError) -> Self { | 145 | + pub(crate) fn guard(mut self, condition: &'static str, refused: AppError) -> Self { |
| 121 | self.guard = Some((condition, refused)); | 146 | self.guard = Some((condition, refused)); |
| 122 | self | 147 | self |
| 123 | } | 148 | } |
| 124 | 149 | ||
| 125 | - /// Move a reference counter *with* this write: `claim` takes one on the row | 150 | + /// Move a reference counter *with* this write: `claim` takes one on the |
| 126 | - /// the link moves to, `release` gives one back on the row it moves off, and | 151 | + /// row the link moves to (in `counter_table`), `release` gives one back |
| 127 | - /// both ride the same `BEGIN…COMMIT` as the `UPDATE` that moves the link. | 152 | + /// on the row it moves off, and both ride the same transaction as the |
| 153 | + /// `UPDATE` that moves the link. | ||
| 128 | /// | 154 | /// |
| 129 | - /// That is the whole point. A claim sent as its own query leaves a window | 155 | + /// That is the whole point. A claim sent as its own statement leaves a |
| 130 | - /// where a crash strands a count on a row nothing links any more — and a | 156 | + /// window where a crash strands a count on a row nothing links any more — |
| 131 | - /// count is what a delete guard reads, so the stranded one makes its parent | 157 | + /// and a count is what a delete guard reads, so the stranded one makes |
| 132 | - /// undeletable forever. `refused` is the answer when the claimed row is gone | 158 | + /// its parent undeletable forever. `refused` is the answer when the |
| 133 | - /// (the conditional write doubles as the existence check, as in | 159 | + /// claimed row is gone (the conditional claim doubles as the existence |
| 134 | - /// [`crate::db::cap`]); the transaction then aborts, so the release and | 160 | + /// check); the transaction then aborts, so the release and the row write |
| 135 | - /// the row write never happened either. | 161 | + /// never happened either. |
| 136 | /// | 162 | /// |
| 137 | - /// Only ever called alongside a `.set()` of the very column that carries the | 163 | + /// Only ever called alongside a `.set()` of the very column that carries |
| 138 | - /// link, so the empty-request short-circuit below cannot swallow a move. | 164 | + /// the link, so the empty-request short-circuit below cannot swallow a |
| 165 | + /// move. | ||
| 139 | /// | 166 | /// |
| 140 | - /// `link` is that column (never `field`: the counter lives on the *other* | 167 | + /// `link` is that column (never a `.set()` field on this row: the counter |
| 141 | - /// row, `course_count` on the term against a `term` link) and `expected` is | 168 | + /// lives on the *other* table — `course_count` on the term against a |
| 142 | - /// what the handler's snapshot said it held — `None` for a link that was | 169 | + /// `term` link) and `expected` is what the handler's snapshot said it |
| 143 | - /// absent. The pair becomes a CAS on the row write, because claim and | 170 | + /// held — `None` for a link that was absent. The pair becomes a CAS on |
| 144 | - /// release are computed from that snapshot: two PATCHes moving the same link | 171 | + /// the row write, because claim and release are computed from that |
| 145 | - /// A→B both read A, and both would claim B, leaving B counted twice for one | 172 | + /// snapshot: two PATCHes moving the same link A→B both read A, and both |
| 146 | - /// link — a count with no link is exactly what makes a term undeletable | 173 | + /// would claim B, leaving B counted twice for one link — a count with no |
| 147 | - /// forever. The loser's row write matches nothing and the whole transaction | 174 | + /// link is exactly what makes a term undeletable forever. The loser's row |
| 148 | - /// aborts, so it claims nothing and answers 409. | 175 | + /// write matches nothing and the whole transaction aborts, so it claims |
| 176 | + /// nothing and answers 409. | ||
| 149 | /// | 177 | /// |
| 150 | - /// **Carrying the link and shifting a counter are separate questions**, and | 178 | + /// **Carrying the link and shifting a counter are separate questions**, |
| 151 | - /// the CAS keys off the first one — `run` arms it for any request that | 179 | + /// and the CAS keys off the first one — `run` arms it for any request |
| 152 | - /// `.set()` this column, `claim`/`release` both `None` included. A PATCH | 180 | + /// that `.set()`s this column, `claim`/`release` both `None` included. A |
| 153 | - /// *re-stating* the link its snapshot showed shifts no counter, but it is | 181 | + /// PATCH *re-stating* the link its snapshot showed shifts no counter, but |
| 154 | - /// the same stale read: run it against a row someone else has since moved | 182 | + /// it is the same stale read: run it against a row someone else has since |
| 155 | - /// and the unguarded write silently drags the link back, stranding the | 183 | + /// moved and the unguarded write silently drags the link back, stranding |
| 156 | - /// winner's claim on a term nothing points at (undeletable forever) and | 184 | + /// the winner's claim on a term nothing points at (undeletable forever) |
| 157 | - /// leaving the reverted-to term linked at zero (deletable while linked). | 185 | + /// and leaving the reverted-to term linked at zero (deletable while |
| 158 | - /// Gating the CAS on the counters is what let that through. | 186 | + /// linked). Gating the CAS on the counters is what let that through. |
| 159 | #[must_use] | 187 | #[must_use] |
| 160 | - pub fn refcount( | 188 | + pub(crate) fn refcount( |
| 161 | mut self, | 189 | mut self, |
| 162 | - field: &'static str, | 190 | + counter_table: &'static str, |
| 191 | + counter_field: &'static str, | ||
| 163 | link: &'static str, | 192 | link: &'static str, |
| 164 | - expected: Option<RecordId>, | 193 | + expected: Option<Uuid>, |
| 165 | - claim: Option<RecordId>, | 194 | + claim: Option<Uuid>, |
| 166 | - release: Option<RecordId>, | 195 | + release: Option<Uuid>, |
| 167 | refused: AppError, | 196 | refused: AppError, |
| 168 | ) -> Self { | 197 | ) -> Self { |
| 169 | - self.refcount = Some((field, link, expected, claim, release, refused)); | 198 | + self.refcount = Some(( |
| 199 | + counter_table, | ||
| 200 | + counter_field, | ||
| 201 | + link, | ||
| 202 | + expected, | ||
| 203 | + claim, | ||
| 204 | + release, | ||
| 205 | + refused, | ||
| 206 | + )); | ||
| 170 | self | 207 | self |
| 171 | } | 208 | } |
| 172 | 209 | ||
| 173 | /// Run the update and return the stored row. An empty request writes | 210 | /// Run the update and return the stored row. An empty request writes |
| 174 | /// nothing at all and reads the row back unchanged. | 211 | /// nothing at all and reads the row back unchanged. |
| 175 | - pub async fn run<T: SurrealValue>(mut self, db: &Database) -> Result<T, AppError> { | 212 | + pub(crate) async fn run<T>(mut self, db: &Database) -> Result<T, AppError> |
| 176 | - // Armed by the *request*, not by the counters: a PATCH that carries the | 213 | + where |
| 177 | - // link column gets the CAS even when it re-states the value it read and | 214 | + T: for<'r> FromRow<'r, PgRow> + Send + Unpin, |
| 178 | - // so shifts nothing. Decided here rather than in `refcount` so the | 215 | + { |
| 179 | - // builder's call order cannot silently disarm it — `run` is always last. | 216 | + // Armed by the *request*, not by the counters: a PATCH that carries |
| 180 | - let moved = self.refcount.take(); | 217 | + // the link column gets the CAS even when it re-states the value it |
| 181 | - let moved = moved.filter(|(_, link, ..)| self.is_set(link)); | 218 | + // read and so shifts nothing. Decided here rather than in `refcount` |
| 182 | - if self.assignments.is_empty() { | 219 | + // so the builder's call order cannot silently disarm it — `run` is |
| 183 | - let row: Option<T> = db.select(self.id).await?; | 220 | + // always last. |
| 221 | + let moved = self.refcount.take().filter(|rc| self.is_set(rc.2)); | ||
| 222 | + if self.sets.is_empty() { | ||
| 223 | + let row: Option<T> = sqlx::query_as(AssertSqlSafe(format!( | ||
| 224 | + "SELECT * FROM {} WHERE id = $1", | ||
| 225 | + self.table | ||
| 226 | + ))) | ||
| 227 | + .bind(self.id) | ||
| 228 | + .fetch_optional(db) | ||
| 229 | + .await?; | ||
| 184 | return row.ok_or(AppError::NotFound); | 230 | return row.ok_or(AppError::NotFound); |
| 185 | } | 231 | } |
| 232 | + // The `SET` list, each value binding as the next positional | ||
| 233 | + // parameter. | ||
| 234 | + let mut binds: Vec<Param> = Vec::new(); | ||
| 235 | + let mut set_sql = String::new(); | ||
| 236 | + for (index, (field, value)) in self.sets.iter().enumerate() { | ||
| 237 | + if index > 0 { | ||
| 238 | + set_sql.push_str(", "); | ||
| 239 | + } | ||
| 240 | + set_sql.push_str(field); | ||
| 241 | + set_sql.push_str(&format!(" = ${}", binds.len() + 1)); | ||
| 242 | + binds.push(value.clone()); | ||
| 243 | + } | ||
| 244 | + // Both ends stored: name the placeholder for an end this request set, | ||
| 245 | + // the column for one it left alone. | ||
| 186 | let (ordered, mut refused) = match self.ordered.take() { | 246 | let (ordered, mut refused) = match self.ordered.take() { |
| 187 | - // Both ends stored: name the bound variable for an end this request | ||
| 188 | - // set, the column for one it left alone. | ||
| 189 | Some((low, high, err)) if self.is_set(low) || self.is_set(high) => { | 247 | Some((low, high, err)) if self.is_set(low) || self.is_set(high) => { |
| 190 | - let side = |field: &str, set| { | 248 | + let side = |field: &str, set: bool| { |
| 191 | if set { | 249 | if set { |
| 192 | - format!("${field}") | 250 | + format!("${}", self.number_of(field)) |
| 193 | } else { | 251 | } else { |
| 194 | - field.into() | 252 | + field.to_owned() |
| 195 | } | 253 | } |
| 196 | }; | 254 | }; |
| 197 | - let low = side(low, self.is_set(low)); | ||
| 198 | - let high = side(high, self.is_set(high)); | ||
| 199 | ( | 255 | ( |
| 200 | Some(format!( | 256 | Some(format!( |
| 201 | - "({low} = NONE OR {high} = NONE OR {low} <= {high})" | 257 | + "({} IS NULL OR {} IS NULL OR {} <= {})", |
| 258 | + side(low, self.is_set(low)), | ||
| 259 | + side(high, self.is_set(high)), | ||
| 260 | + side(low, self.is_set(low)), | ||
| 261 | + side(high, self.is_set(high)), | ||
| 202 | )), | 262 | )), |
| 203 | Some(err), | 263 | Some(err), |
| 204 | ) | 264 | ) |
| 205 | } | 265 | } |
| 206 | _ => (None, None), | 266 | _ => (None, None), |
| 207 | }; | 267 | }; |
| 208 | - // Both guards land on the one `UPDATE`, ANDed. No caller sets both, so | ||
| 209 | - // the refusal is whichever one is there. | ||
| 210 | let (extra, extra_refused) = match self.guard.take() { | 268 | let (extra, extra_refused) = match self.guard.take() { |
| 211 | - Some((condition, err)) => (Some(condition.to_string()), Some(err)), | 269 | + Some((condition, err)) => (Some(condition.to_owned()), Some(err)), |
| 212 | None => (None, None), | 270 | None => (None, None), |
| 213 | }; | 271 | }; |
| 272 | + // No caller sets both, so the refusal is whichever one is there. | ||
| 214 | refused = refused.or(extra_refused); | 273 | refused = refused.or(extra_refused); |
| 215 | - // A PATCH that does not carry the link at all writes the same unguarded | 274 | + // A PATCH that does not carry the link at all writes the same |
| 216 | - // `UPDATE` it always did — it re-states nothing and races nobody. Probed | 275 | + // unguarded `UPDATE` it always did — it re-states nothing and races |
| 217 | - // on the mem engine: | 276 | + // nobody. The CAS is `IS NOT DISTINCT FROM`, so an absent link |
| 218 | - // a bound `None` comes through as `NONE` and `link = NONE` matches a row | 277 | + // (bound `None`) still compares truthfully. |
| 219 | - // whose option column was never set, while failing one that holds a | 278 | + let mut expected_at: Option<usize> = None; |
| 220 | - // record, so the absent-link shape needs no `??`. | 279 | + let cas = moved.as_ref().map(|rc| { |
| 221 | - let cas = moved | 280 | + binds.push(Param::OptUuid(rc.3)); |
| 222 | - .as_ref() | 281 | + expected_at = Some(binds.len()); |
| 223 | - .map(|(_, link, ..)| format!("{link} = $ref_expected")); | 282 | + format!("{} IS NOT DISTINCT FROM ${}", rc.2, binds.len()) |
| 224 | - // The caller's own guards, kept apart from the CAS: the split below has | 283 | + }); |
| 225 | - // to ask "did *only* the link move?", and a probe that ignores them | 284 | + // The caller's own guards, kept apart from the CAS: the probe below |
| 226 | - // answers "the link moved" to a write its `.guard()` refused outright. | 285 | + // has to ask "did *only* the link move?", and a probe that ignores |
| 286 | + // them answers "the link moved" to a write its `.guard()` refused | ||
| 287 | + // outright. | ||
| 227 | let own = ordered | 288 | let own = ordered |
| 228 | .iter() | 289 | .iter() |
| 229 | .chain(extra.iter()) | 290 | .chain(extra.iter()) |
| @@ -231,262 +292,158 @@ impl FieldUpdate { | |||
| 231 | .collect::<Vec<_>>() | 292 | .collect::<Vec<_>>() |
| 232 | .join(" AND "); | 293 | .join(" AND "); |
| 233 | let conditions: Vec<String> = ordered.into_iter().chain(extra).chain(cas).collect(); | 294 | let conditions: Vec<String> = ordered.into_iter().chain(extra).chain(cas).collect(); |
| 234 | - let guard = if conditions.is_empty() { | 295 | + let guard_sql = if conditions.is_empty() { |
| 235 | String::new() | 296 | String::new() |
| 236 | } else { | 297 | } else { |
| 237 | format!(" WHERE {}", conditions.join(" AND ")) | 298 | format!(" WHERE {}", conditions.join(" AND ")) |
| 238 | }; | 299 | }; |
| 239 | - let sets = self.assignments.join(", "); | 300 | + // The row id binds last, after the CAS value. |
| 240 | - let sql = format!("UPDATE $id SET {sets}{guard} RETURN AFTER"); | 301 | + binds.push(Param::Uuid(self.id)); |
| 241 | - self.bindings.push(("id".into(), self.id.into_value())); | 302 | + let id_at = binds.len(); |
| 242 | - // Retried on a write conflict: a guarded PATCH contends on the very row | 303 | + let update = format!( |
| 243 | - // its guard reads, and the loser wrote nothing, so re-sending it is the | 304 | + "UPDATE {} SET {}{} WHERE id = ${id_at} RETURNING *", |
| 244 | - // recovery — see [`write_with_retry`]. | 305 | + self.table, set_sql, guard_sql |
| 306 | + ); | ||
| 245 | let rows: Vec<T> = match moved { | 307 | let rows: Vec<T> = match moved { |
| 246 | - Some(moved) => run_with_refcount(db, &sql, &own, self.bindings, moved).await?, | 308 | + Some(rc) => { |
| 247 | - None => write_with_retry(db, &sql, &self.bindings).await?, | 309 | + let still_mine = if own.is_empty() { |
| 310 | + String::new() | ||
| 311 | + } else { | ||
| 312 | + format!("({own}) AND ") | ||
| 313 | + }; | ||
| 314 | + let probe = format!( | ||
| 315 | + "SELECT 1 FROM {} WHERE id = ${id_at} AND {still_mine}{} \ | ||
| 316 | + IS DISTINCT FROM ${} LIMIT 1", | ||
| 317 | + self.table, | ||
| 318 | + rc.2, | ||
| 319 | + expected_at.expect("the CAS arms with its link"), | ||
| 320 | + ); | ||
| 321 | + run_with_refcount::<T>(db, update, probe, binds, rc).await? | ||
| 322 | + } | ||
| 323 | + None => { | ||
| 324 | + let mut args = PgArguments::default(); | ||
| 325 | + for bind in binds { | ||
| 326 | + bind.add_to(&mut args); | ||
| 327 | + } | ||
| 328 | + sqlx::query_as_with(AssertSqlSafe(update), args) | ||
| 329 | + .fetch_all(db) | ||
| 330 | + .await? | ||
| 331 | + } | ||
| 248 | }; | 332 | }; |
| 249 | - // No row back means the guard bit (or, in the window after the handler's | 333 | + // No row back means the guard bit failed (or, in the window after the |
| 250 | - // read, the row was deleted — the guard cannot tell the two apart, and | 334 | + // handler's read, the row was deleted — the guard cannot tell the two |
| 251 | - // reports the refusal it was given). | 335 | + // apart, and reports the refusal it was given). |
| 252 | rows.into_iter() | 336 | rows.into_iter() |
| 253 | .next() | 337 | .next() |
| 254 | .ok_or_else(|| refused.take().unwrap_or(AppError::NotFound)) | 338 | .ok_or_else(|| refused.take().unwrap_or(AppError::NotFound)) |
| 255 | } | 339 | } |
| 256 | 340 | ||
| 341 | + /// The `$n` the field's value bound as (set order is bind order). | ||
| 342 | + fn number_of(&self, field: &str) -> usize { | ||
| 343 | + self.sets | ||
| 344 | + .iter() | ||
| 345 | + .position(|(name, _)| *name == field) | ||
| 346 | + .expect("ordered() sides are .set() fields") | ||
| 347 | + + 1 | ||
| 348 | + } | ||
| 349 | + | ||
| 257 | fn is_set(&self, field: &str) -> bool { | 350 | fn is_set(&self, field: &str) -> bool { |
| 258 | - self.bindings.iter().any(|(name, _)| name == field) | 351 | + self.sets.iter().any(|(name, _)| *name == field) |
| 259 | } | 352 | } |
| 260 | } | 353 | } |
| 261 | 354 | ||
| 262 | -/// Send `update` with its counter move, as one transaction. An empty `Vec` back | 355 | +/// Send the update with its counter move, as one transaction. |
| 263 | -/// means the row write matched nothing, exactly as [`write_with_retry`] would | ||
| 264 | -/// have reported it, so the caller's refusal is unchanged. | ||
| 265 | /// | 356 | /// |
| 266 | /// A re-statement shifts no counter, so `claim` and `release` are both `None` | 357 | /// A re-statement shifts no counter, so `claim` and `release` are both `None` |
| 267 | -/// and the transaction is the CAS'd row write and its split alone — still a | 358 | +/// and the transaction is the CAS'd row write and its probe alone — still a |
| 268 | -/// transaction, because the split's probe must see the same snapshot the write | 359 | +/// transaction, because the probe must see the same snapshot the write was |
| 269 | -/// was refused against. | 360 | +/// refused against. |
| 270 | /// | 361 | /// |
| 271 | -/// Admissible for [`transaction_with_retry`]: every statement is an `UPDATE`, | 362 | +/// Statement order is the old one, for the old reason: the release goes |
| 272 | -/// an `IF`/`THROW` or a `RETURN`, and none of those can answer "already | 363 | +/// first, so a move to a counter row that is gone decrements before the claim |
| 273 | -/// exists" — a lost round writes nothing and re-sending it is the recovery. | 364 | +/// refuses — and the rolled-back transaction demonstrably undid it. Every |
| 274 | -async fn run_with_refcount<T: SurrealValue>( | 365 | +/// abort takes the whole move back with it: nothing is committed unless the |
| 366 | +/// row write landed. | ||
| 367 | +async fn run_with_refcount<T>( | ||
| 275 | db: &Database, | 368 | db: &Database, |
| 276 | - update: &str, | 369 | + update: String, |
| 277 | - own_guards: &str, | 370 | + probe: String, |
| 278 | - mut bindings: Vec<(String, Value)>, | 371 | + binds: Vec<Param>, |
| 279 | - (field, link, expected, claim, release, refused): Refcount, | 372 | + (counter_table, counter_field, _link, _expected, claim, release, refused): Refcount, |
| 280 | -) -> Result<Vec<T>, AppError> { | 373 | +) -> Result<Vec<T>, AppError> |
| 281 | - // Parenthesized `??` throughout: `n ?? 0 + 1` parses as `n ?? (0 + 1)`. | 374 | +where |
| 282 | - // Both counter writes commit with the row write or neither does, so their | 375 | + T: for<'r> FromRow<'r, PgRow> + Send + Unpin, |
| 283 | - // order is free — the release goes first because that is what makes the | 376 | +{ |
| 284 | - // rollback observable: a move to a term that is gone decrements before the | 377 | + let mut slot: Option<AppError> = Some(refused); |
| 285 | - // claim throws, and the old count still being there proves the abort undid | 378 | + let outcome = tx_with_retry(db, false, async |tx| { |
| 286 | - // it (`a_term_move_to_a_dead_term_leaves_everything_untouched`). | 379 | + let binds = binds.clone(); |
| 287 | - let mut statements: Vec<String> = Vec::new(); | 380 | + if let Some(release) = release { |
| 288 | - if let Some(release) = release { | 381 | + sqlx::query(AssertSqlSafe(format!( |
| 289 | - statements.push(format!( | 382 | + "UPDATE {counter_table} \ |
| 290 | - "UPDATE $ref_release SET {field} = math::max([({field} ?? 0) - 1, 0])" | 383 | + SET {counter_field} = GREATEST({counter_field} - 1, 0) WHERE id = $1" |
| 291 | - )); | 384 | + ))) |
| 292 | - bindings.push(("ref_release".into(), release.into_value())); | 385 | + .bind(release) |
| 293 | - } | 386 | + .execute(&mut *tx) |
| 294 | - if let Some(claim) = claim { | 387 | + .await?; |
| 295 | - statements.push(format!( | 388 | + } |
| 296 | - "LET $seat = (UPDATE $ref_claim SET {field} = ({field} ?? 0) + 1 RETURN VALUE id)" | 389 | + // The conditional claim doubles as the existence check: zero rows |
| 297 | - )); | 390 | + // is the claimed row being gone, the caller's own refusal. |
| 298 | - statements.push(format!( | 391 | + if let Some(claim) = claim { |
| 299 | - "IF array::len($seat) = 0 {{ THROW '{CLAIM_MARK}' }}" | 392 | + let seat: Option<i32> = sqlx::query_scalar(AssertSqlSafe(format!( |
| 300 | - )); | 393 | + "UPDATE {counter_table} SET {counter_field} = {counter_field} + 1 \ |
| 301 | - bindings.push(("ref_claim".into(), claim.into_value())); | 394 | + WHERE id = $1 RETURNING 1" |
| 302 | - } | 395 | + ))) |
| 303 | - bindings.push(("ref_expected".into(), expected.into_value())); | 396 | + .bind(claim) |
| 304 | - statements.push(format!("LET $row = ({update})")); | 397 | + .fetch_optional(&mut *tx) |
| 305 | - // Without this the claim would outlive a row write that matched nothing — | 398 | + .await?; |
| 306 | - // the very leak the transaction exists to close. Nothing was written yet | 399 | + if seat.is_none() { |
| 307 | - // either way, so the probe that tells the two empty cases apart is free to | 400 | + return Err(slot.take().unwrap_or_else(|| mark(REFUSAL_MARK))); |
| 308 | - // be another `UPDATE`: it matches only a row that is *there*, whose *own* | 401 | + } |
| 309 | - // guards still hold, and whose link has moved off what the handler read — | 402 | + } |
| 310 | - // which is the CAS, and nothing else, having bitten. A deleted row and a | 403 | + let mut args = PgArguments::default(); |
| 311 | - // plain guard refusal both miss it and keep the answer they have always | 404 | + for bind in binds.iter().cloned() { |
| 312 | - // got. Carrying the caller's guards is what keeps that true when a write is | 405 | + bind.add_to(&mut args); |
| 313 | - // refused for *both* reasons at once: a `.guard()`/`.ordered()` refusal is | 406 | + } |
| 314 | - // the caller's own answer to give, and reporting it as "the link moved" | 407 | + let rows: Vec<T> = sqlx::query_as_with(AssertSqlSafe(update.as_str()), args) |
| 315 | - // would send the client to re-read a link that was never its problem. | 408 | + .fetch_all(&mut *tx) |
| 316 | - let still_mine = if own_guards.is_empty() { | 409 | + .await?; |
| 317 | - String::new() | 410 | + if !rows.is_empty() { |
| 318 | - } else { | 411 | + return Ok(rows); |
| 319 | - format!("({own_guards}) AND ") | 412 | + } |
| 320 | - }; | 413 | + // Zero rows: the caller's own guard bit, the row deleted in the |
| 321 | - statements.push(format!( | 414 | + // window after the handler's read, or — the CAS only — the link |
| 322 | - "IF array::len($row) = 0 {{ \ | 415 | + // moved since the handler read it. Nothing was written yet either |
| 323 | - LET $live = (UPDATE $id WHERE {still_mine}{link} != $ref_expected RETURN VALUE id); \ | 416 | + // way, so the probe that tells the cases apart is free: it matches |
| 324 | - IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} ELSE {{ THROW '{STALE_MARK}' }} }}" | 417 | + // only a row that is *there*, whose *own* guards still hold, and |
| 325 | - )); | 418 | + // whose link has moved off what the handler read — which is the |
| 326 | - statements.push("RETURN $row".into()); | 419 | + // CAS, and nothing else, having bitten. Carrying the caller's |
| 327 | - let sql = format!( | 420 | + // guards is what keeps that true when a write is refused for |
| 328 | - "BEGIN TRANSACTION; {}; COMMIT TRANSACTION;", | 421 | + // *both* reasons at once: a `.guard()`/`.ordered()` refusal is the |
| 329 | - statements.join("; ") | 422 | + // caller's own answer to give, and reporting it as "the link |
| 330 | - ); | 423 | + // moved" would send the client to re-read a link that was never |
| 331 | - // BEGIN is slot 0, so the trailing RETURN sits at `statements.len()`. | 424 | + // its problem. |
| 332 | - let slot = statements.len(); | 425 | + let mut args = PgArguments::default(); |
| 333 | - | 426 | + for bind in binds { |
| 334 | - // One counter write in flight at a time, like every other counter write. | 427 | + bind.add_to(&mut args); |
| 335 | - let _guard = cap::counter_lock().await; | 428 | + } |
| 336 | - let (mut result, mut errors) = | 429 | + let live: Option<i32> = sqlx::query_scalar_with(AssertSqlSafe(probe.as_str()), args) |
| 337 | - transaction_with_retry(db, &sql, &bindings, &[CLAIM_MARK, ROW_MARK, STALE_MARK]).await?; | 430 | + .fetch_optional(&mut *tx) |
| 338 | - if errors | 431 | + .await?; |
| 339 | - .values() | 432 | + match live { |
| 340 | - .any(|error| error.to_string().contains(CLAIM_MARK)) | 433 | + Some(_) => Err(mark(STALE_MARK)), |
| 341 | - { | 434 | + None => Err(mark(GONE_MARK)), |
| 342 | - return Err(refused); | 435 | + } |
| 343 | - } | 436 | + }) |
| 344 | - if errors | 437 | + .await; |
| 345 | - .values() | 438 | + match outcome { |
| 346 | - .any(|error| error.to_string().contains(STALE_MARK)) | 439 | + Err(AppError::Internal(m)) if m == REFUSAL_MARK => { |
| 347 | - { | 440 | + Err(slot.take().unwrap_or_else(|| mark(REFUSAL_MARK))) |
| 348 | - return Err(AppError::Conflict( | 441 | + } |
| 349 | - "the link this update moves changed since it was read; re-read and retry", | 442 | + Err(AppError::Internal(m)) if m == STALE_MARK => Err(AppError::Conflict(STALE_MOVE)), |
| 350 | - )); | 443 | + // The row is gone: exactly the "wrote nothing" answer the plain path |
| 351 | - } | 444 | + // reports, so the caller's refusal is unchanged. |
| 352 | - if errors | 445 | + Err(AppError::Internal(m)) if m == GONE_MARK => Ok(Vec::new()), |
| 353 | - .values() | 446 | + other => other, |
| 354 | - .any(|error| error.to_string().contains(ROW_MARK)) | ||
| 355 | - { | ||
| 356 | - return Ok(Vec::new()); | ||
| 357 | - } | ||
| 358 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 359 | - return Err(error.into()); | ||
| 360 | } | 447 | } |
| 361 | - // Sound only because the error map came back empty: `take_errors` swap- | ||
| 362 | - // removes errored slots, which would renumber the rest. | ||
| 363 | - Ok(result.take::<Vec<T>>(slot)?) | ||
| 364 | } | 448 | } |
| 365 | 449 | ||
| 366 | -#[cfg(test)] | ||
| 367 | -mod tests { | ||
| 368 | - use super::*; | ||
| 369 | - use crate::constant::SUBJECT_HOMEWORK_COUNT_FIELD; | ||
| 370 | - use crate::database::init_mem; | ||
| 371 | - | ||
| 372 | - /// Two subjects and one homework tagged with the first. The `course` and | ||
| 373 | - /// `created_by` links point at rows that do not exist — a `record<…>` type | ||
| 374 | - /// constrains the table, not the existence, and nothing here reads them. | ||
| 375 | - async fn seeded() -> Database { | ||
| 376 | - let db = init_mem().await.unwrap(); | ||
| 377 | - db.query( | ||
| 378 | - "CREATE subject:s1 SET course = course:c, name = 'a', description = ''; | ||
| 379 | - CREATE subject:s2 SET course = course:c, name = 'b', description = ''; | ||
| 380 | - CREATE homework:h1 SET course = course:c, subject = subject:s1, | ||
| 381 | - title = 't', due_at = 1, created_by = user:u, created_at = 1;", | ||
| 382 | - ) | ||
| 383 | - .await | ||
| 384 | - .unwrap() | ||
| 385 | - .check() | ||
| 386 | - .unwrap(); | ||
| 387 | - db | ||
| 388 | - } | ||
| 389 | - | ||
| 390 | - /// The two subjects' homework counters, re-read out of the store. | ||
| 391 | - async fn counts(db: &Database) -> Vec<i64> { | ||
| 392 | - let mut result = db | ||
| 393 | - .query(format!( | ||
| 394 | - "SELECT VALUE ({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) FROM subject ORDER BY id" | ||
| 395 | - )) | ||
| 396 | - .await | ||
| 397 | - .unwrap() | ||
| 398 | - .check() | ||
| 399 | - .unwrap(); | ||
| 400 | - result.take::<Vec<i64>>(0).unwrap() | ||
| 401 | - } | ||
| 402 | - | ||
| 403 | - fn homework() -> RecordId { | ||
| 404 | - RecordId::new("homework", "h1") | ||
| 405 | - } | ||
| 406 | - | ||
| 407 | - fn subject(key: &str) -> RecordId { | ||
| 408 | - RecordId::new("subject", key) | ||
| 409 | - } | ||
| 410 | - | ||
| 411 | - /// A write refused by the caller's *own* guard must answer with the | ||
| 412 | - /// caller's own refusal, even when the link it carries has also moved since | ||
| 413 | - /// the handler read it. Both are true; only one is the client's problem, | ||
| 414 | - /// and "re-read the link and retry" sends them chasing a `409` that a retry | ||
| 415 | - /// cannot clear — the guard will refuse the next attempt exactly the same. | ||
| 416 | - #[tokio::test] | ||
| 417 | - async fn a_guard_refusal_outranks_a_link_that_also_moved() { | ||
| 418 | - let db = seeded().await; | ||
| 419 | - let refused = FieldUpdate::new(homework()) | ||
| 420 | - .set("subject", Some(subject("s2"))) | ||
| 421 | - .guard("title = 'never'", AppError::Conflict("the caller's own no")) | ||
| 422 | - .refcount( | ||
| 423 | - SUBJECT_HOMEWORK_COUNT_FIELD, | ||
| 424 | - "subject", | ||
| 425 | - // Stale: the row says `s1`, so the CAS bites too. | ||
| 426 | - Some(subject("s9")), | ||
| 427 | - Some(subject("s2")), | ||
| 428 | - Some(subject("s9")), | ||
| 429 | - AppError::Conflict("the subject is gone"), | ||
| 430 | - ) | ||
| 431 | - .run::<Value>(&db) | ||
| 432 | - .await | ||
| 433 | - .unwrap_err(); | ||
| 434 | - assert_eq!(refused.to_string(), "conflict: the caller's own no"); | ||
| 435 | - // The abort took the claim with it, and the link never moved. | ||
| 436 | - assert_eq!(counts(&db).await, vec![0, 0]); | ||
| 437 | - } | ||
| 438 | - | ||
| 439 | - /// ...and with the guard satisfied, a moved link is still reported as a | ||
| 440 | - /// moved link — the answer every current caller relies on. | ||
| 441 | - #[tokio::test] | ||
| 442 | - async fn a_moved_link_alone_is_still_the_stale_move_409() { | ||
| 443 | - let db = seeded().await; | ||
| 444 | - let refused = FieldUpdate::new(homework()) | ||
| 445 | - .set("subject", Some(subject("s2"))) | ||
| 446 | - .guard("title = 't'", AppError::Conflict("the caller's own no")) | ||
| 447 | - .refcount( | ||
| 448 | - SUBJECT_HOMEWORK_COUNT_FIELD, | ||
| 449 | - "subject", | ||
| 450 | - Some(subject("s9")), | ||
| 451 | - Some(subject("s2")), | ||
| 452 | - Some(subject("s9")), | ||
| 453 | - AppError::Conflict("the subject is gone"), | ||
| 454 | - ) | ||
| 455 | - .run::<Value>(&db) | ||
| 456 | - .await | ||
| 457 | - .unwrap_err(); | ||
| 458 | - assert!( | ||
| 459 | - refused | ||
| 460 | - .to_string() | ||
| 461 | - .contains("the link this update moves changed"), | ||
| 462 | - "{refused}" | ||
| 463 | - ); | ||
| 464 | - assert_eq!(counts(&db).await, vec![0, 0]); | ||
| 465 | - } | ||
| 466 | - | ||
| 467 | - /// The unguarded shape every production caller uses today: the link moves, | ||
| 468 | - /// the counters move with it, in one transaction. | ||
| 469 | - #[tokio::test] | ||
| 470 | - async fn an_unguarded_move_still_lands_with_both_counters() { | ||
| 471 | - let db = seeded().await; | ||
| 472 | - db.query("UPDATE subject:s1 SET homework_count = 1") | ||
| 473 | - .await | ||
| 474 | - .unwrap() | ||
| 475 | - .check() | ||
| 476 | - .unwrap(); | ||
| 477 | - FieldUpdate::new(homework()) | ||
| 478 | - .set("subject", Some(subject("s2"))) | ||
| 479 | - .refcount( | ||
| 480 | - SUBJECT_HOMEWORK_COUNT_FIELD, | ||
| 481 | - "subject", | ||
| 482 | - Some(subject("s1")), | ||
| 483 | - Some(subject("s2")), | ||
| 484 | - Some(subject("s1")), | ||
| 485 | - AppError::Conflict("the subject is gone"), | ||
| 486 | - ) | ||
| 487 | - .run::<Value>(&db) | ||
| 488 | - .await | ||
| 489 | - .unwrap(); | ||
| 490 | - assert_eq!(counts(&db).await, vec![0, 1]); | ||
| 491 | - } | ||
| 492 | -} | ||
src/db/page.rsmodified+178 -175
| @@ -4,250 +4,253 @@ | |||
| 4 | //! WHY: `?limit=10` used to run an unbounded `SELECT *`, hand the whole table | 4 | //! WHY: `?limit=10` used to run an unbounded `SELECT *`, hand the whole table |
| 5 | //! to the web layer and slice ten rows off it. The scan (and the decode of | 5 | //! to the web layer and slice ten rows off it. The scan (and the decode of |
| 6 | //! every row) grew with the table no matter how small the page was. Here the | 6 | //! every row) grew with the table no matter how small the page was. Here the |
| 7 | -//! window is `LIMIT/START` in SQL, and `total` is a `count()` over the *same* | 7 | +//! window is `LIMIT/OFFSET` in SQL, and `total` is a `count(*)` over the |
| 8 | -//! `WHERE`, so a page can never disagree with the count that pages it. | 8 | +//! *same* `WHERE` as a second statement, so a page can never disagree with |
| 9 | +//! the count that pages it. | ||
| 9 | //! | 10 | //! |
| 10 | //! ```ignore | 11 | //! ```ignore |
| 11 | -//! PagedList::new("note WHERE user = $usr", "ORDER BY id DESC") | 12 | +//! PagedList::new("note WHERE user_id = $1", "ORDER BY id DESC") |
| 12 | -//! .bind("usr", owner.record()) | 13 | +//! .bind(owner.0) |
| 13 | //! .run::<Note>(limit, offset, db) | 14 | //! .run::<Note>(limit, offset, db) |
| 14 | //! .await | 15 | //! .await |
| 15 | //! ``` | 16 | //! ``` |
| 16 | //! | 17 | //! |
| 17 | -//! Paging stays opt-in: `limit = None, offset = 0` is the unpaged read, and it | 18 | +//! Paging stays opt-in: `limit = None, offset = 0` is the unpaged read, and |
| 18 | -//! emits exactly one statement (no count — the rows in hand *are* the total), | 19 | +//! it runs exactly one statement (no count — the rows in hand *are* the |
| 19 | -//! so internal callers that just want the list pay nothing. | 20 | +//! total), so internal callers that just want the list pay nothing. |
| 20 | //! | 21 | //! |
| 21 | -//! The count's result shape is the planner's to choose (see [`total_of`]) — | 22 | +//! Runtime-checked SQL by design: `from_where` is assembled per call site, |
| 22 | -//! both shapes decode to the same `total`. | 23 | +//! which is this module's named exemption from the compile-time `query!` |
| 24 | +//! rule. Placeholders are positional (`$1, $2, …`) in [`.bind`] order, and | ||
| 25 | +//! the window's own placeholders continue the numbering. The count is a plain | ||
| 26 | +//! `count(*)`, which always answers one `NOT NULL` row — no planner-shape | ||
| 27 | +//! decoding to preserve. | ||
| 28 | +//! | ||
| 29 | +//! The dynamic parts of every statement here are table/column names (in-crate | ||
| 30 | +//! constants and literals, never client text) and the `$n` numbers this | ||
| 31 | +//! builder prints itself; every value binds — which is the audit the | ||
| 32 | +//! [`AssertSqlSafe`] wraps stand on. | ||
| 23 | //! | 33 | //! |
| 24 | //! Only for lists the database can express whole. A handler that filters rows | 34 | //! Only for lists the database can express whole. A handler that filters rows |
| 25 | -//! in Rust after the read (visibility, audience resolution, a schedule window) | 35 | +//! in Rust after the read (visibility, audience resolution, a schedule |
| 26 | -//! must keep slicing in the web layer: a DB `LIMIT` in front of a Rust filter | 36 | +//! window) must keep slicing in the web layer: a DB `LIMIT` in front of a |
| 27 | -//! silently returns a short page. | 37 | +//! Rust filter silently returns a short page. |
| 28 | 38 | ||
| 29 | -use surrealdb::types::{SurrealValue, Value}; | 39 | +use sqlx::postgres::{PgArguments, PgRow}; |
| 40 | +use sqlx::{Arguments, AssertSqlSafe, FromRow}; | ||
| 41 | +use uuid::Uuid; | ||
| 30 | 42 | ||
| 31 | use crate::database::Database; | 43 | use crate::database::Database; |
| 32 | use crate::error::AppError; | 44 | use crate::error::AppError; |
| 33 | 45 | ||
| 34 | -pub struct PagedList { | 46 | +/// One bound parameter of a runtime-checked builder's statement, in |
| 35 | - /// Everything after `FROM`, e.g. `note WHERE user = $usr`. Shared verbatim | 47 | +/// `$1, $2, …` order. |
| 36 | - /// by the page and the count. | 48 | +/// |
| 49 | +/// [`PagedList`] and [`crate::db::field_update::FieldUpdate`] are the named | ||
| 50 | +/// exemptions from the compile-time `query!` rule: their SQL is assembled at | ||
| 51 | +/// run time, so their parameters ride this closed enum — owned values, no | ||
| 52 | +/// borrow to tie a builder's lifetime to, [`Clone`] because one builder run | ||
| 53 | +/// can need the same `WHERE` bound twice (page, then count). A caller that | ||
| 54 | +/// needs a type the enum lacks adds a variant here; sqlx's borrow-tied | ||
| 55 | +/// dynamic binding does not survive being stored in a builder. | ||
| 56 | +#[derive(Clone, Debug)] | ||
| 57 | +pub(crate) enum Param { | ||
| 58 | + I64(i64), | ||
| 59 | + Text(String), | ||
| 60 | + Uuid(Uuid), | ||
| 61 | + /// A nullable column value: `None` binds SQL `NULL` with the uuid type | ||
| 62 | + /// still named, so `IS NOT DISTINCT FROM $n` compares an absent link | ||
| 63 | + /// truthfully. | ||
| 64 | + OptUuid(Option<Uuid>), | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +impl Param { | ||
| 68 | + /// Push onto runtime-checked arguments. sqlx defers encode failures to | ||
| 69 | + /// execution, so there is nothing to check here. | ||
| 70 | + pub(crate) fn add_to(self, args: &mut PgArguments) { | ||
| 71 | + let _ = match self { | ||
| 72 | + Param::I64(value) => args.add(value), | ||
| 73 | + Param::Text(value) => args.add(value), | ||
| 74 | + Param::Uuid(value) => args.add(value), | ||
| 75 | + Param::OptUuid(value) => args.add(value), | ||
| 76 | + }; | ||
| 77 | + } | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +impl From<i64> for Param { | ||
| 81 | + fn from(value: i64) -> Self { | ||
| 82 | + Self::I64(value) | ||
| 83 | + } | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +impl From<String> for Param { | ||
| 87 | + fn from(value: String) -> Self { | ||
| 88 | + Self::Text(value) | ||
| 89 | + } | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +impl From<Uuid> for Param { | ||
| 93 | + fn from(value: Uuid) -> Self { | ||
| 94 | + Self::Uuid(value) | ||
| 95 | + } | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +impl From<Option<Uuid>> for Param { | ||
| 99 | + fn from(value: Option<Uuid>) -> Self { | ||
| 100 | + Self::OptUuid(value) | ||
| 101 | + } | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +pub(crate) struct PagedList { | ||
| 105 | + /// Everything after `FROM`, e.g. `note WHERE user_id = $1`. Placeholders | ||
| 106 | + /// are positional in [`PagedList::bind`] order; shared verbatim by the | ||
| 107 | + /// page and the count. | ||
| 37 | from_where: String, | 108 | from_where: String, |
| 38 | /// The full `ORDER BY ...`, applied to the page only. | 109 | /// The full `ORDER BY ...`, applied to the page only. |
| 39 | order: &'static str, | 110 | order: &'static str, |
| 40 | - bindings: Vec<(String, Value)>, | 111 | + binds: Vec<Param>, |
| 41 | } | 112 | } |
| 42 | 113 | ||
| 43 | impl PagedList { | 114 | impl PagedList { |
| 44 | /// `from_where` is a whole-table read (`"term"`) or a filtered one | 115 | /// `from_where` is a whole-table read (`"term"`) or a filtered one |
| 45 | - /// (`"note WHERE user = $usr"`). | 116 | + /// (`"note WHERE user_id = $1"`). |
| 46 | - pub fn new(from_where: impl Into<String>, order: &'static str) -> Self { | 117 | + pub(crate) fn new(from_where: impl Into<String>, order: &'static str) -> Self { |
| 47 | Self { | 118 | Self { |
| 48 | from_where: from_where.into(), | 119 | from_where: from_where.into(), |
| 49 | order, | 120 | order, |
| 50 | - bindings: Vec::new(), | 121 | + binds: Vec::new(), |
| 51 | } | 122 | } |
| 52 | } | 123 | } |
| 53 | 124 | ||
| 54 | - /// Bind one variable of the `WHERE`. `limit` and `offset` are the two names | 125 | + /// Bind the next positional parameter: the first call fills `$1`, the |
| 55 | - /// a caller must not use. | 126 | + /// second `$2`, … — `from_where` must carry the placeholders in the same |
| 127 | + /// order. | ||
| 56 | #[must_use] | 128 | #[must_use] |
| 57 | - pub fn bind<T: SurrealValue>(mut self, name: &'static str, value: T) -> Self { | 129 | + pub(crate) fn bind<T: Into<Param>>(mut self, value: T) -> Self { |
| 58 | - self.bindings.push((name.to_string(), value.into_value())); | 130 | + self.binds.push(value.into()); |
| 59 | self | 131 | self |
| 60 | } | 132 | } |
| 61 | 133 | ||
| 62 | - /// The statements to run, and whether the second one (the count) is among | 134 | + /// The page statement and, when the window can hide rows, the count |
| 63 | - /// them. Split out so a test can read the SQL: the whole point of this type | 135 | + /// statement. Split out so a test can read the SQL: the whole point of |
| 64 | - /// is that `LIMIT`/`START` reach the database instead of a `Vec` slice. | 136 | + /// this type is that `LIMIT/OFFSET` reach the database instead of a |
| 65 | - fn statements(&self, limit: Option<i64>, offset: i64) -> (String, bool) { | 137 | + /// `Vec` slice. |
| 66 | - let from_where = &self.from_where; | 138 | + fn statements(&self, limit: Option<i64>, offset: i64) -> (String, Option<String>) { |
| 67 | - let window = match limit { | 139 | + let mut next = self.binds.len(); |
| 68 | - Some(_) => "LIMIT $limit START $offset", | 140 | + let mut sql = format!("SELECT * FROM {} {}", self.from_where, self.order); |
| 69 | - None => "START $offset", | 141 | + if limit.is_some() { |
| 70 | - }; | 142 | + next += 1; |
| 71 | - let mut sql = format!("SELECT * FROM {from_where} {} {window};", self.order); | 143 | + sql.push_str(&format!(" LIMIT ${next}")); |
| 72 | - // A window that can hide rows needs the count; an unpaged read from row | 144 | + } |
| 73 | - // zero already holds every row, so it stays a single statement. | 145 | + // A window that can hide rows needs the count; an unpaged read from |
| 146 | + // row zero already holds every row, so it stays a single statement. | ||
| 74 | let counted = limit.is_some() || offset > 0; | 147 | let counted = limit.is_some() || offset > 0; |
| 75 | if counted { | 148 | if counted { |
| 76 | - sql.push_str(&format!( | 149 | + next += 1; |
| 77 | - "SELECT VALUE count() FROM {from_where} GROUP ALL;" | 150 | + sql.push_str(&format!(" OFFSET ${next}")); |
| 78 | - )); | ||
| 79 | } | 151 | } |
| 80 | - (sql, counted) | 152 | + let count = counted.then(|| format!("SELECT count(*) FROM {}", self.from_where)); |
| 153 | + (sql, count) | ||
| 81 | } | 154 | } |
| 82 | 155 | ||
| 83 | /// The page plus the full row count. `limit = None` runs from `offset` to | 156 | /// The page plus the full row count. `limit = None` runs from `offset` to |
| 84 | /// the end, matching the unpaged envelope. | 157 | /// the end, matching the unpaged envelope. |
| 85 | - pub async fn run<T: SurrealValue>( | 158 | + pub(crate) async fn run<T>( |
| 86 | self, | 159 | self, |
| 87 | limit: Option<i64>, | 160 | limit: Option<i64>, |
| 88 | offset: i64, | 161 | offset: i64, |
| 89 | db: &Database, | 162 | db: &Database, |
| 90 | - ) -> Result<(Vec<T>, i64), AppError> { | 163 | + ) -> Result<(Vec<T>, i64), AppError> |
| 91 | - let (sql, counted) = self.statements(limit, offset); | 164 | + where |
| 92 | - let mut query = db | 165 | + T: for<'r> FromRow<'r, PgRow> + Send + Unpin, |
| 93 | - .query(sql) | 166 | + { |
| 94 | - .bind(("offset", offset)) | 167 | + let (page_sql, count_sql) = self.statements(limit, offset); |
| 95 | - .bind(("limit", limit.unwrap_or(0))); | 168 | + let mut args = PgArguments::default(); |
| 96 | - for (name, value) in self.bindings { | 169 | + for bind in self.binds.iter().cloned() { |
| 97 | - query = query.bind((name, value)); | 170 | + bind.add_to(&mut args); |
| 98 | } | 171 | } |
| 99 | - let mut result = query.await?.check()?; | 172 | + if let Some(limit) = limit { |
| 100 | - let rows = result.take::<Vec<T>>(0)?; | 173 | + Param::from(limit).add_to(&mut args); |
| 101 | - let total = match counted { | 174 | + } |
| 102 | - true => total_of(result.take::<Value>(1)?)?, | 175 | + if count_sql.is_some() { |
| 103 | - false => rows.len() as i64, | 176 | + Param::from(offset).add_to(&mut args); |
| 177 | + } | ||
| 178 | + let rows: Vec<T> = | ||
| 179 | + sqlx::query_as_with(AssertSqlSafe(page_sql), args).fetch_all(db).await?; | ||
| 180 | + let total = match count_sql { | ||
| 181 | + Some(count_sql) => { | ||
| 182 | + let mut args = PgArguments::default(); | ||
| 183 | + for bind in self.binds { | ||
| 184 | + bind.add_to(&mut args); | ||
| 185 | + } | ||
| 186 | + let scalar: i64 = | ||
| 187 | + sqlx::query_scalar_with(AssertSqlSafe(count_sql), args).fetch_one(db).await?; | ||
| 188 | + scalar | ||
| 189 | + } | ||
| 190 | + None => rows.len() as i64, | ||
| 104 | }; | 191 | }; |
| 105 | Ok((rows, total)) | 192 | Ok((rows, total)) |
| 106 | } | 193 | } |
| 107 | } | 194 | } |
| 108 | 195 | ||
| 109 | -/// The count statement's slot, in either shape the planner answers in. | ||
| 110 | -/// | ||
| 111 | -/// `SELECT VALUE count() ... GROUP ALL` normally yields the projected int, but | ||
| 112 | -/// whenever the planner can answer the count straight out of an index or the | ||
| 113 | -/// table count (`IndexCountScan` — an indexed field compared to a value known | ||
| 114 | -/// at plan time, `grade IS NONE` or a *literal*, and any bare table read) it | ||
| 115 | -/// returns `{ count: N }` and drops the `SELECT VALUE` projection. Decoding | ||
| 116 | -/// only the int is where "Expected int, got object" came from; the number is | ||
| 117 | -/// the same either way. The in-memory engine never rewrites the plan, so only | ||
| 118 | -/// a real server ever produces the object. | ||
| 119 | -fn total_of(count: Value) -> Result<i64, AppError> { | ||
| 120 | - // `GROUP ALL` yields no row at all when nothing matched. | ||
| 121 | - let row = match count { | ||
| 122 | - Value::Array(rows) => rows.into_iter().next().unwrap_or_default(), | ||
| 123 | - other => other, | ||
| 124 | - }; | ||
| 125 | - let row = match row { | ||
| 126 | - Value::Object(mut object) => object.remove("count").unwrap_or_default(), | ||
| 127 | - other => other, | ||
| 128 | - }; | ||
| 129 | - match row.is_nullish() { | ||
| 130 | - true => Ok(0), | ||
| 131 | - false => row | ||
| 132 | - .into_t::<i64>() | ||
| 133 | - .map_err(|e| AppError::Internal(format!("count decode: {e}"))), | ||
| 134 | - } | ||
| 135 | -} | ||
| 136 | - | ||
| 137 | #[cfg(test)] | 196 | #[cfg(test)] |
| 138 | mod tests { | 197 | mod tests { |
| 139 | use super::*; | 198 | use super::*; |
| 140 | - use crate::database; | ||
| 141 | - use crate::db::note; | ||
| 142 | - use crate::domain::note::{NoteContent, NoteTitle}; | ||
| 143 | - use crate::domain::user::UserId; | ||
| 144 | - use ulid::Ulid; | ||
| 145 | 199 | ||
| 146 | fn list() -> PagedList { | 200 | fn list() -> PagedList { |
| 147 | - PagedList::new("note WHERE user = $usr", "ORDER BY id DESC") | 201 | + PagedList::new("note WHERE user_id = $1", "ORDER BY id DESC").bind(Uuid::nil()) |
| 148 | } | 202 | } |
| 149 | 203 | ||
| 150 | - /// The window has to be SQL — a `Vec` slice would leave the scan unbounded, | 204 | + /// The window has to be SQL — a `Vec` slice would leave the scan |
| 151 | - /// which is the whole reason this type exists. | 205 | + /// unbounded, which is the whole reason this type exists. |
| 152 | #[test] | 206 | #[test] |
| 153 | fn a_paged_read_windows_and_counts_in_sql() { | 207 | fn a_paged_read_windows_and_counts_in_sql() { |
| 154 | - let (sql, counted) = list().statements(Some(10), 20); | 208 | + let (sql, count) = list().statements(Some(10), 20); |
| 155 | - assert!(sql.contains("ORDER BY id DESC LIMIT $limit START $offset;")); | 209 | + assert!(sql.contains("ORDER BY id DESC LIMIT $2 OFFSET $3")); |
| 156 | - assert!(sql.contains("SELECT VALUE count() FROM note WHERE user = $usr GROUP ALL;")); | 210 | + assert_eq!( |
| 157 | - assert!(counted); | 211 | + count.as_deref(), |
| 212 | + Some("SELECT count(*) FROM note WHERE user_id = $1") | ||
| 213 | + ); | ||
| 158 | } | 214 | } |
| 159 | 215 | ||
| 160 | - /// A whole-table read counts the table as it stands — no `WHERE true` to | 216 | + /// A whole-table read counts the bare table. |
| 161 | - /// force a scan, because [`total_of`] now takes the count-from-index shape | ||
| 162 | - /// that hack existed to avoid. | ||
| 163 | #[test] | 217 | #[test] |
| 164 | fn an_unfiltered_list_counts_the_bare_table() { | 218 | fn an_unfiltered_list_counts_the_bare_table() { |
| 165 | - let (sql, _) = PagedList::new("term", "ORDER BY starts_at DESC").statements(Some(5), 0); | 219 | + let (sql, count) = |
| 166 | - assert!(sql.contains("SELECT VALUE count() FROM term GROUP ALL;")); | 220 | + PagedList::new("term", "ORDER BY starts_at DESC").statements(Some(5), 0); |
| 221 | + assert!(sql.contains("LIMIT $1 OFFSET $2")); | ||
| 222 | + assert_eq!(count.as_deref(), Some("SELECT count(*) FROM term")); | ||
| 167 | } | 223 | } |
| 168 | 224 | ||
| 169 | - /// Both shapes of the count slot mean the same number. The object is what | 225 | + /// Unpaged from row zero: the rows in hand are the total, so no count |
| 170 | - /// a real server returns whenever it answers `count()` from an index or the | 226 | + /// runs. |
| 171 | - /// table count; the in-memory engine only ever produces the int, so this is | ||
| 172 | - /// the only place the object arm can be pinned. Drop that arm and the | ||
| 173 | - /// second assert fails with "count decode: Expected int, got object" — | ||
| 174 | - /// which is the 500 `GET /classes?grade=&limit=1` served. | ||
| 175 | - #[test] | ||
| 176 | - fn a_count_decodes_from_either_shape() { | ||
| 177 | - let projected = Value::Array([Value::from_t(7i64)].into_iter().collect()); | ||
| 178 | - let from_index = Value::Array( | ||
| 179 | - [Value::Object( | ||
| 180 | - [("count".to_string(), Value::from_t(7i64))] | ||
| 181 | - .into_iter() | ||
| 182 | - .collect(), | ||
| 183 | - )] | ||
| 184 | - .into_iter() | ||
| 185 | - .collect(), | ||
| 186 | - ); | ||
| 187 | - assert_eq!(total_of(projected).unwrap(), 7); | ||
| 188 | - assert_eq!(total_of(from_index).unwrap(), 7); | ||
| 189 | - // `GROUP ALL` yields no row at all when nothing matched. | ||
| 190 | - assert_eq!(total_of(Value::Array(Default::default())).unwrap(), 0); | ||
| 191 | - // Any other shape is an error, never a silently wrong `total`. | ||
| 192 | - assert!(total_of(Value::Array([Value::from_t("7")].into_iter().collect())).is_err()); | ||
| 193 | - } | ||
| 194 | - | ||
| 195 | - /// Unpaged from row zero: the rows in hand are the total, so no count runs. | ||
| 196 | #[test] | 227 | #[test] |
| 197 | fn an_unpaged_read_stays_one_statement() { | 228 | fn an_unpaged_read_stays_one_statement() { |
| 198 | - let (sql, counted) = list().statements(None, 0); | 229 | + let (sql, count) = list().statements(None, 0); |
| 199 | - assert!(sql.ends_with("ORDER BY id DESC START $offset;")); | 230 | + assert_eq!( |
| 200 | - assert!(!sql.contains("count()")); | 231 | + sql, |
| 201 | - assert!(!counted); | 232 | + "SELECT * FROM note WHERE user_id = $1 ORDER BY id DESC" |
| 233 | + ); | ||
| 234 | + assert_eq!(count, None); | ||
| 202 | // An offset without a limit still hides rows, so it needs the count. | 235 | // An offset without a limit still hides rows, so it needs the count. |
| 203 | - assert!(list().statements(None, 3).1); | 236 | + let (sql, count) = list().statements(None, 3); |
| 237 | + assert!(sql.contains("OFFSET $2")); | ||
| 238 | + assert!(!sql.contains("LIMIT")); | ||
| 239 | + assert!(count.is_some()); | ||
| 204 | } | 240 | } |
| 205 | 241 | ||
| 206 | - #[tokio::test] | 242 | + /// The window's placeholders continue the caller's numbering, in emission |
| 207 | - async fn the_window_walks_the_rows_and_total_stays_the_whole_list() { | 243 | + /// order. |
| 208 | - let db = database::init_mem().await.unwrap(); | 244 | + #[test] |
| 209 | - let user = UserId::from_key(&Ulid::generate().to_string()); | 245 | + fn window_placeholders_continue_the_where_numbering() { |
| 210 | - for i in 0..5 { | 246 | + let (sql, count) = |
| 211 | - note::create( | 247 | + PagedList::new("note WHERE user_id = $1 AND archived_at IS NULL", "ORDER BY id") |
| 212 | - &db, | 248 | + .bind(Uuid::nil()) |
| 213 | - &user, | 249 | + .statements(Some(2), 4); |
| 214 | - NoteTitle::try_new(&format!("n{i}")).unwrap(), | 250 | + assert!(sql.contains("LIMIT $2 OFFSET $3")); |
| 215 | - NoteContent::try_new("x").unwrap(), | ||
| 216 | - ) | ||
| 217 | - .await | ||
| 218 | - .unwrap(); | ||
| 219 | - } | ||
| 220 | - | ||
| 221 | - // Every page is `limit` long and `total` ignores the window. | ||
| 222 | - let (page, total) = note::list_for(&db, &user, Some(2), 0).await.unwrap(); | ||
| 223 | - assert_eq!((page.len(), total), (2, 5)); | ||
| 224 | - let (tail, total) = note::list_for(&db, &user, Some(2), 4).await.unwrap(); | ||
| 225 | - assert_eq!((tail.len(), total), (1, 5)); | ||
| 226 | - // Offset past the end is an empty page, not an error. | ||
| 227 | - assert_eq!( | ||
| 228 | - note::list_for(&db, &user, Some(2), 9) | ||
| 229 | - .await | ||
| 230 | - .unwrap() | ||
| 231 | - .0 | ||
| 232 | - .len(), | ||
| 233 | - 0 | ||
| 234 | - ); | ||
| 235 | - // Unpaged, and unpaged-from-an-offset: the count still covers everything. | ||
| 236 | - let (all, total) = note::list_for(&db, &user, None, 0).await.unwrap(); | ||
| 237 | - assert_eq!((all.len(), total), (5, 5)); | ||
| 238 | - let (rest, total) = note::list_for(&db, &user, None, 3).await.unwrap(); | ||
| 239 | - assert_eq!((rest.len(), total), (2, 5)); | ||
| 240 | - | ||
| 241 | - // The pages are consecutive slices of the unpaged list — page | ||
| 242 | - // boundaries match the order the ORDER BY already produced. | ||
| 243 | - let keys: Vec<&str> = all.iter().map(|note| note.get_id().key()).collect(); | ||
| 244 | - assert_eq!( | ||
| 245 | - page.iter().map(|n| n.get_id().key()).collect::<Vec<_>>(), | ||
| 246 | - keys[..2] | ||
| 247 | - ); | ||
| 248 | assert_eq!( | 251 | assert_eq!( |
| 249 | - tail.iter().map(|n| n.get_id().key()).collect::<Vec<_>>(), | 252 | + count.as_deref(), |
| 250 | - keys[4..] | 253 | + Some("SELECT count(*) FROM note WHERE user_id = $1 AND archived_at IS NULL") |
| 251 | ); | 254 | ); |
| 252 | } | 255 | } |
| 253 | } | 256 | } |
src/domain/answer_image.rsmodified+30 -31
| @@ -2,48 +2,49 @@ | |||
| 2 | //! one (exam, user, question), mirroring [`crate::domain::question_image`] but | 2 | //! one (exam, user, question), mirroring [`crate::domain::question_image`] but |
| 3 | //! keyed by the answering student instead of a choice slot. The row carries | 3 | //! keyed by the answering student instead of a choice slot. The row carries |
| 4 | //! metadata; the bytes live on disk under [`crate::config::Config::files_path`] | 4 | //! metadata; the bytes live on disk under [`crate::config::Config::files_path`] |
| 5 | -//! in a file named by `file` — a fresh server-generated ULID per upload, so no | 5 | +//! in a file named by `file` — a fresh server-generated UUID per upload, so no |
| 6 | //! user input ever shapes a disk path and a replace never overwrites bytes in | 6 | //! user input ever shapes a disk path and a replace never overwrites bytes in |
| 7 | -//! place. The row id is *deterministic* per (question, user, seq) — the same | 7 | +//! place. The row is keyed by (question, user, seq) — the same shape as |
| 8 | -//! shape as [`crate::domain::exam_attempt::ExamAttemptId::composite`] — so "one | 8 | +//! [`crate::domain::exam_attempt::ExamAttemptId`] — so "one |
| 9 | //! drawing per student per question per sitting" holds by construction and a | 9 | //! drawing per student per question per sitting" holds by construction and a |
| 10 | -//! replace within a sitting is a plain UPSERT, while a retake (`seq + 1`) | 10 | +//! replace within a sitting is a plain UPSERT on the composite primary key, |
| 11 | -//! accumulates its own rows instead of overwriting. The queries and | 11 | +//! while a retake (`seq + 1`) accumulates its own rows instead of |
| 12 | -//! transactions over these rows live in [`crate::db::answer_image`]; the web | 12 | +//! overwriting. The queries and transactions over these rows live in |
| 13 | -//! layer owns the blob I/O and its ordering (new blob before row, row before | 13 | +//! [`crate::db::answer_image`]; the web layer owns the blob I/O and its |
| 14 | -//! old blob). | 14 | +//! ordering (new blob before row, row before old blob). |
| 15 | 15 | ||
| 16 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 17 | -use ulid::Ulid; | ||
| 18 | - | ||
| 19 | -use crate::constant::ANSWER_IMAGE_TABLE; | ||
| 20 | use crate::domain::exam::ExamId; | 16 | use crate::domain::exam::ExamId; |
| 21 | use crate::domain::exam_question::ExamQuestionId; | 17 | use crate::domain::exam_question::ExamQuestionId; |
| 22 | use crate::domain::key; | 18 | use crate::domain::key; |
| 23 | use crate::domain::note_file::FileContentType; | 19 | use crate::domain::note_file::FileContentType; |
| 24 | use crate::domain::user::UserId; | 20 | use crate::domain::user::UserId; |
| 25 | 21 | ||
| 26 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 22 | +/// The identity of one (question, user, seq) triple — a sitting's drawing. |
| 27 | -pub struct AnswerImageId(RecordId); | 23 | +/// Not a row column: the table's primary key *is* the (question, user, seq) |
| 24 | +/// triple, and this struct's job is the underscore-joined wire form at the | ||
| 25 | +/// HTTP edge. | ||
| 26 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 27 | +pub struct AnswerImageId { | ||
| 28 | + pub(crate) question: ExamQuestionId, | ||
| 29 | + pub(crate) user: UserId, | ||
| 30 | + pub(crate) seq: i64, | ||
| 31 | +} | ||
| 28 | 32 | ||
| 29 | impl AnswerImageId { | 33 | impl AnswerImageId { |
| 30 | /// The one id a (question, user, seq) triple can have, so "one drawing per | 34 | /// The one id a (question, user, seq) triple can have, so "one drawing per |
| 31 | /// student per question per sitting" needs no index. See [`key::sitting`] | 35 | /// student per question per sitting" needs no index. See [`key::sitting`] |
| 32 | - /// for the key shape and why the first sitting stays bare. | 36 | + /// for the wire shape and why the first sitting stays bare. |
| 33 | pub fn composite(question: &ExamQuestionId, user: &UserId, seq: i64) -> Self { | 37 | pub fn composite(question: &ExamQuestionId, user: &UserId, seq: i64) -> Self { |
| 34 | - let key = key::sitting(question.key(), user.key(), seq); | 38 | + Self { |
| 35 | - Self(RecordId::new(ANSWER_IMAGE_TABLE, key)) | 39 | + question: question.clone(), |
| 36 | - } | 40 | + user: user.clone(), |
| 37 | - | 41 | + seq, |
| 38 | - pub fn record(&self) -> RecordId { | 42 | + } |
| 39 | - self.0.clone() | ||
| 40 | } | 43 | } |
| 41 | 44 | ||
| 42 | - pub fn key(&self) -> &str { | 45 | + /// The underscore-joined wire form (`{question}_{user}[_{seq}]`). |
| 43 | - match &self.0.key { | 46 | + pub fn key(&self) -> String { |
| 44 | - RecordIdKey::String(key) => key, | 47 | + key::sitting(self.question.key().as_str(), self.user.key().as_str(), self.seq) |
| 45 | - _ => "", | ||
| 46 | - } | ||
| 47 | } | 48 | } |
| 48 | } | 49 | } |
| 49 | 50 | ||
| @@ -51,16 +52,15 @@ impl AnswerImageId { | |||
| 51 | /// [`crate::domain::exam_answer::ExamAnswer`]) so per-exam reads (cascade) and | 52 | /// [`crate::domain::exam_answer::ExamAnswer`]) so per-exam reads (cascade) and |
| 52 | /// per-(exam, user) reads (sitting/grading views, retake blob-GC) don't fan out | 53 | /// per-(exam, user) reads (sitting/grading views, retake blob-GC) don't fan out |
| 53 | /// through `exam_question`. | 54 | /// through `exam_question`. |
| 54 | -#[derive(Debug, Clone, SurrealValue)] | 55 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 55 | pub struct AnswerImage { | 56 | pub struct AnswerImage { |
| 56 | - pub(crate) id: AnswerImageId, | ||
| 57 | pub(crate) exam: ExamId, | 57 | pub(crate) exam: ExamId, |
| 58 | pub(crate) question: ExamQuestionId, | 58 | pub(crate) question: ExamQuestionId, |
| 59 | pub(crate) user: UserId, | 59 | pub(crate) user: UserId, |
| 60 | /// Which sitting this drawing belongs to — 1 for the first attempt, | 60 | /// Which sitting this drawing belongs to — 1 for the first attempt, |
| 61 | /// counting up, so retakes accumulate instead of overwriting. | 61 | /// counting up, so retakes accumulate instead of overwriting. |
| 62 | pub(crate) seq: i64, | 62 | pub(crate) seq: i64, |
| 63 | - /// The blob's on-disk name — a fresh ULID every upload. | 63 | + /// The blob's on-disk name — a fresh UUID every upload. |
| 64 | pub(crate) file: String, | 64 | pub(crate) file: String, |
| 65 | pub(crate) content_type: FileContentType, | 65 | pub(crate) content_type: FileContentType, |
| 66 | pub(crate) size: i64, | 66 | pub(crate) size: i64, |
| @@ -80,12 +80,11 @@ impl AnswerImage { | |||
| 80 | size: i64, | 80 | size: i64, |
| 81 | ) -> Self { | 81 | ) -> Self { |
| 82 | Self { | 82 | Self { |
| 83 | - id: AnswerImageId::composite(question, user, seq), | ||
| 84 | exam: exam.clone(), | 83 | exam: exam.clone(), |
| 85 | question: question.clone(), | 84 | question: question.clone(), |
| 86 | user: user.clone(), | 85 | user: user.clone(), |
| 87 | seq, | 86 | seq, |
| 88 | - file: Ulid::generate().to_string(), | 87 | + file: uuid::Uuid::new_v4().to_string(), |
| 89 | content_type, | 88 | content_type, |
| 90 | size, | 89 | size, |
| 91 | } | 90 | } |
src/domain/appointment.rsmodified+47 -86
| @@ -9,90 +9,59 @@ | |||
| 9 | //! | 9 | //! |
| 10 | //! The *cross-record* invariants live one layer down: | 10 | //! The *cross-record* invariants live one layer down: |
| 11 | //! | 11 | //! |
| 12 | -//! - **One live booking per slot** — the `occupied` counter on the slot row, a | 12 | +//! - **One live booking per slot** — the `occupied` counter on the slot row, |
| 13 | -//! [`cap`](crate::db::cap) of one. [`crate::service::appointment::book`] | 13 | +//! a [`cap`](crate::db::cap) of one. [`crate::service::appointment::book`] |
| 14 | -//! claims it *with* the booking row | 14 | +//! claims it *with* the booking row; rejecting or cancelling gives it back |
| 15 | -//! ([`cap::claim_and_create`](crate::db::cap::claim_and_create)); rejecting | 15 | +//! in the *same transaction* as the status flip |
| 16 | -//! or cancelling gives it back in the *same transaction* as the status flip | ||
| 17 | //! ([`crate::db::appointment::save_if_unchanged`]), so the slot frees itself | 16 | //! ([`crate::db::appointment::save_if_unchanged`]), so the slot frees itself |
| 18 | -//! with nothing to sweep. Both are single-record conditional writes, so the | 17 | +//! with nothing to sweep. |
| 19 | -//! store decides it, not a lock. | 18 | +//! - **No double-booked teacher window.** Two overlapping published windows |
| 20 | -//! - **No double-booked person.** An approved meeting may not overlap another | 19 | +//! cannot both exist — the `appointment_slot` exclusion constraint refuses |
| 21 | -//! approved meeting of the same teacher *or* of the same requester. That is a | 20 | +//! the second insert at the store, which is what replaced the |
| 22 | -//! count-then-write over *many* rows, which a `BEGIN…COMMIT` does not | 21 | +//! [`crate::service::appointment::APPOINTMENT_LOCK`] serialization. |
| 23 | -//! serialize in SurrealDB (write-skew), so booking and approval hold | ||
| 24 | -//! [`crate::service::appointment::APPOINTMENT_LOCK`], which is the whole | ||
| 25 | -//! guarantee behind it. | ||
| 26 | //! | 22 | //! |
| 27 | //! The *single-row* invariant — a decision must be written onto the state it | 23 | //! The *single-row* invariant — a decision must be written onto the state it |
| 28 | -//! was validated against — is **not** the lock's job, and never was: a | 24 | +//! was validated against — is a compare-and-set |
| 29 | -//! whole-row save built on a snapshot read before the lock was taken would | 25 | +//! ([`crate::db::appointment::save_if_unchanged`]), decided by a conditional |
| 30 | -//! silently drop whatever landed in between. That one is a compare-and-set | 26 | +//! `UPDATE`. |
| 31 | -//! ([`crate::db::appointment::save_if_unchanged`]), decided by the store. | ||
| 32 | -//! | ||
| 33 | -//! Overlap therefore rests on the lock alone — it is a predicate over *other* | ||
| 34 | -//! rows, with no single row to key a counter or a CAS on. That holds while | ||
| 35 | -//! every approving write takes the lock; one that skips it puts two | ||
| 36 | -//! meetings in one half-hour, so the rule is stated at the lock rather than | ||
| 37 | -//! left to be noticed. The damage if it ever happens is one double-booked | ||
| 38 | -//! half-hour, visible to both parties and fixable by cancelling either | ||
| 39 | -//! side — no money, no grade, no data loss. | ||
| 40 | - | ||
| 41 | -use std::sync::LazyLock; | ||
| 42 | 27 | ||
| 43 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 28 | +use crate::constant::{MAX_APPOINTMENT_REASON_LEN}; |
| 44 | -use ulid::Generator; | ||
| 45 | - | ||
| 46 | -use crate::constant::{APPOINTMENT_TABLE, MAX_APPOINTMENT_REASON_LEN}; | ||
| 47 | use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId}; | 29 | use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId}; |
| 30 | +use crate::domain::monotonic_id::next_uuid; | ||
| 48 | use crate::domain::timestamp::Timestamp; | 31 | use crate::domain::timestamp::Timestamp; |
| 49 | use crate::domain::user::UserId; | 32 | use crate::domain::user::UserId; |
| 50 | use crate::error::ValidationError; | 33 | use crate::error::ValidationError; |
| 51 | use crate::validate::validate_required; | 34 | use crate::validate::validate_required; |
| 52 | 35 | ||
| 53 | -/// Mints booking ids in write order — `Ulid::generate()`'s random low bits sort | 36 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 54 | -/// arbitrarily within one millisecond, which would scramble the `id` tie-break | 37 | +#[sqlx(transparent)] |
| 55 | -/// of the newest-first listings ([`crate::db::appointment::list_for_requester`]). | 38 | +pub struct AppointmentId(uuid::Uuid); |
| 56 | -static IDS: LazyLock<std::sync::Mutex<Generator>> = | ||
| 57 | - LazyLock::new(|| std::sync::Mutex::new(Generator::new())); | ||
| 58 | - | ||
| 59 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 60 | -pub struct AppointmentId(RecordId); | ||
| 61 | 39 | ||
| 62 | impl AppointmentId { | 40 | impl AppointmentId { |
| 41 | + /// Mints in write order — the `id` tie-break of the newest-first listings | ||
| 42 | + /// ([`crate::db::appointment::list_for_requester`]) must not scramble rows | ||
| 43 | + /// minted inside one millisecond. | ||
| 63 | pub fn generate() -> Self { | 44 | pub fn generate() -> Self { |
| 64 | - let mut ids = IDS.lock().expect("appointment id generator poisoned"); | 45 | + Self(next_uuid()) |
| 65 | - // The only error is exhausting the random bits within one millisecond | ||
| 66 | - // (2^80 ids deep); it clears itself as the clock ticks, so retry. | ||
| 67 | - let ulid = loop { | ||
| 68 | - if let Ok(ulid) = ids.generate() { | ||
| 69 | - break ulid; | ||
| 70 | - } | ||
| 71 | - }; | ||
| 72 | - Self(RecordId::new(APPOINTMENT_TABLE, ulid.to_string())) | ||
| 73 | } | 46 | } |
| 74 | 47 | ||
| 48 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 49 | + /// which matches no row — a malformed path param stays a 404, exactly | ||
| 50 | + /// like a well-formed one that names nothing. | ||
| 75 | pub fn from_key(key: &str) -> Self { | 51 | pub fn from_key(key: &str) -> Self { |
| 76 | - Self(RecordId::new(APPOINTMENT_TABLE, key)) | 52 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 77 | } | 53 | } |
| 78 | 54 | ||
| 79 | - pub fn record(&self) -> RecordId { | 55 | + pub fn key(&self) -> String { |
| 80 | - self.0.clone() | 56 | + self.0.to_string() |
| 81 | - } | ||
| 82 | - | ||
| 83 | - pub fn key(&self) -> &str { | ||
| 84 | - match &self.0.key { | ||
| 85 | - RecordIdKey::String(key) => key, | ||
| 86 | - _ => "", | ||
| 87 | - } | ||
| 88 | } | 57 | } |
| 89 | } | 58 | } |
| 90 | 59 | ||
| 91 | -/// Where a booking stands. `untagged` + `rename_all` store it as the bare | 60 | +/// Where a booking stands. Stored as the bare lowercase string the `status` |
| 92 | -/// lowercase string the `status` column types as; an unknown value comes back | 61 | +/// column's CHECK allows; an unknown value comes back as a decode error, |
| 93 | -/// as a deserialization error, never a panic. | 62 | +/// never a panic. |
| 94 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | 63 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] |
| 95 | -#[surreal(untagged, rename_all = "lowercase")] | 64 | +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] |
| 96 | pub enum AppointmentStatus { | 65 | pub enum AppointmentStatus { |
| 97 | Pending, | 66 | Pending, |
| 98 | Approved, | 67 | Approved, |
| @@ -123,7 +92,8 @@ impl AppointmentStatus { | |||
| 123 | 92 | ||
| 124 | /// Why the requester wants the meeting. Required: a teacher approving a | 93 | /// Why the requester wants the meeting. Required: a teacher approving a |
| 125 | /// parent-teacher conference needs to know what it is about. | 94 | /// parent-teacher conference needs to know what it is about. |
| 126 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 95 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 96 | +#[sqlx(transparent)] | ||
| 127 | pub struct AppointmentReason(String); | 97 | pub struct AppointmentReason(String); |
| 128 | 98 | ||
| 129 | impl AppointmentReason { | 99 | impl AppointmentReason { |
| @@ -140,7 +110,7 @@ impl AppointmentReason { | |||
| 140 | /// Fields are crate-visible: [`crate::db::appointment`] reads the columns its | 110 | /// Fields are crate-visible: [`crate::db::appointment`] reads the columns its |
| 141 | /// compare-and-set discriminates on, and [`crate::service::appointment`] | 111 | /// compare-and-set discriminates on, and [`crate::service::appointment`] |
| 142 | /// clones a fresh read and mutates the decision onto it. | 112 | /// clones a fresh read and mutates the decision onto it. |
| 143 | -#[derive(Debug, Clone, SurrealValue)] | 113 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 144 | pub struct Appointment { | 114 | pub struct Appointment { |
| 145 | pub(crate) id: AppointmentId, | 115 | pub(crate) id: AppointmentId, |
| 146 | pub(crate) slot: AppointmentSlotId, | 116 | pub(crate) slot: AppointmentSlotId, |
| @@ -154,15 +124,10 @@ pub struct Appointment { | |||
| 154 | pub(crate) proposed_ends_at: Option<Timestamp>, | 124 | pub(crate) proposed_ends_at: Option<Timestamp>, |
| 155 | pub(crate) proposed_by: Option<UserId>, | 125 | pub(crate) proposed_by: Option<UserId>, |
| 156 | pub(crate) decided_by: Option<UserId>, | 126 | pub(crate) decided_by: Option<UserId>, |
| 157 | - /// Who called the meeting off, and why, once it is `cancelled`. Both | 127 | + /// Who called the meeting off, and why, once it is `cancelled`. |
| 158 | - /// `#[surreal(default)]` so bookings written before cancellation records | ||
| 159 | - /// existed still read back (they resolve to `None`). | ||
| 160 | - #[surreal(default)] | ||
| 161 | pub(crate) cancelled_by: Option<UserId>, | 128 | pub(crate) cancelled_by: Option<UserId>, |
| 162 | - #[surreal(default)] | ||
| 163 | pub(crate) cancel_reason: Option<AppointmentReason>, | 129 | pub(crate) cancel_reason: Option<AppointmentReason>, |
| 164 | /// Why the request was turned down; the rejecter is already on `decided_by`. | 130 | /// Why the request was turned down; the rejecter is already on `decided_by`. |
| 165 | - #[surreal(default)] | ||
| 166 | pub(crate) reject_reason: Option<AppointmentReason>, | 131 | pub(crate) reject_reason: Option<AppointmentReason>, |
| 167 | pub(crate) created_at: Timestamp, | 132 | pub(crate) created_at: Timestamp, |
| 168 | } | 133 | } |
| @@ -259,7 +224,6 @@ impl Appointment { | |||
| 259 | #[cfg(test)] | 224 | #[cfg(test)] |
| 260 | mod tests { | 225 | mod tests { |
| 261 | use super::*; | 226 | use super::*; |
| 262 | - use surrealdb::types::Value; | ||
| 263 | 227 | ||
| 264 | fn at(millis: i64) -> Timestamp { | 228 | fn at(millis: i64) -> Timestamp { |
| 265 | Timestamp::from_millis(millis) | 229 | Timestamp::from_millis(millis) |
| @@ -273,22 +237,19 @@ mod tests { | |||
| 273 | assert!(AppointmentReason::try_new(&"x".repeat(MAX_APPOINTMENT_REASON_LEN + 1)).is_err()); | 237 | assert!(AppointmentReason::try_new(&"x".repeat(MAX_APPOINTMENT_REASON_LEN + 1)).is_err()); |
| 274 | } | 238 | } |
| 275 | 239 | ||
| 276 | - /// The `status` column is `TYPE string`: an object-wrapped enum would be | 240 | + /// The `status` column is `TEXT` with a CHECK listing exactly these |
| 277 | - /// rejected on write, and the `status IN ['pending','approved']` occupancy | 241 | + /// spellings: the occupancy query is written against them, so the storage |
| 278 | - /// query is written against exactly these spellings. | 242 | + /// form may not drift from `as_str`. |
| 279 | - #[tokio::test] | 243 | + #[test] |
| 280 | - async fn status_stores_as_a_bare_string() { | 244 | + fn status_stores_as_a_bare_string() { |
| 281 | - for status in [ | 245 | + for (status, spelling) in [ |
| 282 | - AppointmentStatus::Pending, | 246 | + (AppointmentStatus::Pending, "pending"), |
| 283 | - AppointmentStatus::Approved, | 247 | + (AppointmentStatus::Approved, "approved"), |
| 284 | - AppointmentStatus::Rejected, | 248 | + (AppointmentStatus::Rejected, "rejected"), |
| 285 | - AppointmentStatus::Cancelled, | 249 | + (AppointmentStatus::Cancelled, "cancelled"), |
| 286 | ] { | 250 | ] { |
| 287 | - let value = status.into_value(); | 251 | + assert_eq!(status.as_str(), spelling); |
| 288 | - assert_eq!(value, Value::String(status.as_str().to_string())); | ||
| 289 | - assert_eq!(AppointmentStatus::from_value(value).unwrap(), status); | ||
| 290 | } | 252 | } |
| 291 | - assert!(AppointmentStatus::from_value(Value::String("declined".into())).is_err()); | ||
| 292 | assert!(AppointmentStatus::Pending.is_live()); | 253 | assert!(AppointmentStatus::Pending.is_live()); |
| 293 | assert!(AppointmentStatus::Approved.is_live()); | 254 | assert!(AppointmentStatus::Approved.is_live()); |
| 294 | assert!(!AppointmentStatus::Rejected.is_live()); | 255 | assert!(!AppointmentStatus::Rejected.is_live()); |
src/domain/appointment_slot.rsmodified+34 -35
| @@ -5,69 +5,65 @@ | |||
| 5 | //! `series` id, so no recurrence rule is ever evaluated at read time and | 5 | //! `series` id, so no recurrence rule is ever evaluated at read time and |
| 6 | //! cancelling one week is a plain row delete. | 6 | //! cancelling one week is a plain row delete. |
| 7 | //! | 7 | //! |
| 8 | -//! The one piece of booking state a slot carries is the `occupied` counter (a | 8 | +//! The one piece of booking state a slot carries is the `occupied` counter, a |
| 9 | -//! [`cap`](crate::db::cap) of one), taken when a booking is made and given | 9 | +//! [`cap`](crate::db::cap) of one, taken when a booking is made and given |
| 10 | //! back in the same transaction as the reject or cancel that settles it — so | 10 | //! back in the same transaction as the reject or cancel that settles it — so |
| 11 | //! the slot frees itself again, and unlike a UNIQUE index it does not keep a | 11 | //! the slot frees itself again, and unlike a UNIQUE index it does not keep a |
| 12 | //! dead booking's seat. Stored rather than counted from the | 12 | //! dead booking's seat. Stored rather than counted from the |
| 13 | //! [appointment](crate::domain::appointment::Appointment) rows because a | 13 | //! [appointment](crate::domain::appointment::Appointment) rows because a |
| 14 | //! conditional write on one row is the only guard a concurrent booking cannot | 14 | //! conditional write on one row is the only guard a concurrent booking cannot |
| 15 | -//! outrun. The reads and writes behind it live in | 15 | +//! outrun. Two overlapping windows of one teacher cannot both be published: |
| 16 | -//! [`crate::db::appointment_slot`]; the publish and delete workflows under | 16 | +//! the `appointment_slot` span exclusion constraint refuses the second |
| 17 | -//! [`crate::service::appointment::APPOINTMENT_LOCK`] live in | 17 | +//! insert, which is what replaced the |
| 18 | -//! [`crate::service::appointment_slot`]. | 18 | +//! [`crate::service::appointment::APPOINTMENT_LOCK`]. The reads and writes |
| 19 | - | 19 | +//! live in [`crate::db::appointment_slot`]; the publish and delete workflows |
| 20 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 20 | +//! in [`crate::service::appointment_slot`]. |
| 21 | 21 | ||
| 22 | use crate::constant::{ | 22 | use crate::constant::{ |
| 23 | - APPOINTMENT_SLOT_TABLE, MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, | 23 | + MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, |
| 24 | }; | 24 | }; |
| 25 | -use crate::domain::monotonic_id::next_ulid; | 25 | +use crate::domain::monotonic_id::next_uuid; |
| 26 | use crate::domain::timestamp::Timestamp; | 26 | use crate::domain::timestamp::Timestamp; |
| 27 | use crate::domain::user::UserId; | 27 | use crate::domain::user::UserId; |
| 28 | use crate::error::{AppError, ValidationError}; | 28 | use crate::error::{AppError, ValidationError}; |
| 29 | use crate::validate::validate_optional; | 29 | use crate::validate::validate_optional; |
| 30 | 30 | ||
| 31 | // Slot ids come from [`crate::domain::monotonic_id`]: a recurring publish | 31 | // Slot ids come from [`crate::domain::monotonic_id`]: a recurring publish |
| 32 | -// writes its whole expansion inside one millisecond, which random ULID low | 32 | +// writes its whole expansion inside one millisecond, which random UUID |
| 33 | -// bits would scramble against the `id` tie-break of the `ORDER BY starts_at, | 33 | +// low bits would scramble against the `id` tie-break of the |
| 34 | -// id` listings. | 34 | +// `ORDER BY starts_at, id` listings. |
| 35 | 35 | ||
| 36 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 36 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 37 | -pub struct AppointmentSlotId(RecordId); | 37 | +#[sqlx(transparent)] |
| 38 | +pub struct AppointmentSlotId(uuid::Uuid); | ||
| 38 | 39 | ||
| 39 | impl AppointmentSlotId { | 40 | impl AppointmentSlotId { |
| 40 | pub fn generate() -> Self { | 41 | pub fn generate() -> Self { |
| 41 | - Self(RecordId::new( | 42 | + Self(next_uuid()) |
| 42 | - APPOINTMENT_SLOT_TABLE, | ||
| 43 | - next_ulid().to_string(), | ||
| 44 | - )) | ||
| 45 | } | 43 | } |
| 46 | 44 | ||
| 45 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 46 | + /// which matches no row — a malformed path param stays a 404, exactly | ||
| 47 | + /// like a well-formed one that names nothing. | ||
| 47 | pub fn from_key(key: &str) -> Self { | 48 | pub fn from_key(key: &str) -> Self { |
| 48 | - Self(RecordId::new(APPOINTMENT_SLOT_TABLE, key)) | 49 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 49 | - } | ||
| 50 | - | ||
| 51 | - pub fn record(&self) -> RecordId { | ||
| 52 | - self.0.clone() | ||
| 53 | } | 50 | } |
| 54 | 51 | ||
| 55 | - pub fn key(&self) -> &str { | 52 | + pub fn key(&self) -> String { |
| 56 | - match &self.0.key { | 53 | + self.0.to_string() |
| 57 | - RecordIdKey::String(key) => key, | ||
| 58 | - _ => "", | ||
| 59 | - } | ||
| 60 | } | 54 | } |
| 61 | } | 55 | } |
| 62 | 56 | ||
| 63 | /// The id shared by every occurrence one recurring publish created. A plain | 57 | /// The id shared by every occurrence one recurring publish created. A plain |
| 64 | -/// ULID string (not a record id): it names a group, never a row. | 58 | +/// UUID string (not a row id): it names a group, never a row — the column |
| 65 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 59 | +/// stays `TEXT`, so cancelling one week is still `DELETE … WHERE series = $1`. |
| 60 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] | ||
| 61 | +#[sqlx(transparent)] | ||
| 66 | pub struct SlotSeries(String); | 62 | pub struct SlotSeries(String); |
| 67 | 63 | ||
| 68 | impl SlotSeries { | 64 | impl SlotSeries { |
| 69 | pub fn generate() -> Self { | 65 | pub fn generate() -> Self { |
| 70 | - Self(next_ulid().to_string()) | 66 | + Self(next_uuid().to_string()) |
| 71 | } | 67 | } |
| 72 | 68 | ||
| 73 | pub fn from_key(key: &str) -> Self { | 69 | pub fn from_key(key: &str) -> Self { |
| @@ -79,7 +75,8 @@ impl SlotSeries { | |||
| 79 | } | 75 | } |
| 80 | } | 76 | } |
| 81 | 77 | ||
| 82 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 78 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 79 | +#[sqlx(transparent)] | ||
| 83 | pub struct SlotNote(String); | 80 | pub struct SlotNote(String); |
| 84 | 81 | ||
| 85 | impl SlotNote { | 82 | impl SlotNote { |
| @@ -95,8 +92,10 @@ impl SlotNote { | |||
| 95 | 92 | ||
| 96 | /// The half-open window `[starts_at, ends_at)` a slot offers. Half-open is the | 93 | /// The half-open window `[starts_at, ends_at)` a slot offers. Half-open is the |
| 97 | /// whole point: back-to-back slots (10:00–10:30, 10:30–11:00) touch without | 94 | /// whole point: back-to-back slots (10:00–10:30, 10:30–11:00) touch without |
| 98 | -/// overlapping, which is exactly how a teacher's hour is carved up. | 95 | +/// overlapping, which is exactly how a teacher's hour is carved up. The same |
| 99 | -#[derive(Debug, Clone, SurrealValue)] | 96 | +/// half-open semantics are what the stored `span` range and its exclusion |
| 97 | +/// constraint enforce at publish time. | ||
| 98 | +#[derive(Debug, Clone, sqlx::FromRow)] | ||
| 100 | pub struct AppointmentSlot { | 99 | pub struct AppointmentSlot { |
| 101 | pub(crate) id: AppointmentSlotId, | 100 | pub(crate) id: AppointmentSlotId, |
| 102 | pub(crate) teacher: UserId, | 101 | pub(crate) teacher: UserId, |
src/domain/attendance.rsmodified+23 -27
| @@ -1,34 +1,29 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | - | ||
| 3 | -use crate::constant::ATTENDANCE_TABLE; | ||
| 4 | use crate::domain::event::EventId; | 1 | use crate::domain::event::EventId; |
| 5 | use crate::domain::user::UserId; | 2 | use crate::domain::user::UserId; |
| 6 | use crate::error::ValidationError; | 3 | use crate::error::ValidationError; |
| 7 | 4 | ||
| 8 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 5 | +/// The identity of one (event, user) pair. Not a row column: the table's |
| 9 | -pub struct AttendanceId(RecordId); | 6 | +/// primary key *is* the pair, which is what makes marking a single atomic |
| 7 | +/// UPSERT (`ON CONFLICT (event, app_user)`) with no find-then-insert race, | ||
| 8 | +/// one-row-per-pair by construction. This struct's job is the | ||
| 9 | +/// underscore-joined wire form at the HTTP edge. | ||
| 10 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 11 | +pub struct AttendanceId { | ||
| 12 | + pub(crate) event: EventId, | ||
| 13 | + pub(crate) user: UserId, | ||
| 14 | +} | ||
| 10 | 15 | ||
| 11 | impl AttendanceId { | 16 | impl AttendanceId { |
| 12 | - /// A deterministic id for the (event, user) pair. Because the same pair | ||
| 13 | - /// always maps to the same record id, marking is a single atomic UPSERT with | ||
| 14 | - /// no find-then-insert race, and one-row-per-pair holds by construction. | ||
| 15 | - /// ULID keys are alphanumeric, so `_` is an unambiguous joiner. | ||
| 16 | pub fn composite(event: &EventId, user: &UserId) -> Self { | 17 | pub fn composite(event: &EventId, user: &UserId) -> Self { |
| 17 | - Self(RecordId::new( | 18 | + Self { |
| 18 | - ATTENDANCE_TABLE, | 19 | + event: event.clone(), |
| 19 | - format!("{}_{}", event.key(), user.key()), | 20 | + user: user.clone(), |
| 20 | - )) | 21 | + } |
| 21 | - } | ||
| 22 | - | ||
| 23 | - pub fn record(&self) -> RecordId { | ||
| 24 | - self.0.clone() | ||
| 25 | } | 22 | } |
| 26 | 23 | ||
| 27 | - pub fn key(&self) -> &str { | 24 | + /// The underscore-joined wire form (`{event}_{user}`). |
| 28 | - match &self.0.key { | 25 | + pub fn key(&self) -> String { |
| 29 | - RecordIdKey::String(key) => key, | 26 | + format!("{}_{}", self.event.key(), self.user.key()) |
| 30 | - _ => "", | ||
| 31 | - } | ||
| 32 | } | 27 | } |
| 33 | } | 28 | } |
| 34 | 29 | ||
| @@ -36,7 +31,8 @@ impl AttendanceId { | |||
| 36 | /// ([`crate::domain::settings::Settings::get_attendance_statuses`]): the core | 31 | /// ([`crate::domain::settings::Settings::get_attendance_statuses`]): the core |
| 37 | /// `present | absent | late | excused` plus any the school added. Stored rows | 32 | /// `present | absent | late | excused` plus any the school added. Stored rows |
| 38 | /// keep their status even if the school later edits the list. | 33 | /// keep their status even if the school later edits the list. |
| 39 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 34 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 35 | +#[sqlx(transparent)] | ||
| 40 | pub struct AttendanceStatus(String); | 36 | pub struct AttendanceStatus(String); |
| 41 | 37 | ||
| 42 | impl AttendanceStatus { | 38 | impl AttendanceStatus { |
| @@ -55,9 +51,8 @@ impl AttendanceStatus { | |||
| 55 | } | 51 | } |
| 56 | } | 52 | } |
| 57 | 53 | ||
| 58 | -#[derive(Debug, Clone, SurrealValue)] | 54 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 59 | pub struct Attendance { | 55 | pub struct Attendance { |
| 60 | - pub(crate) id: AttendanceId, | ||
| 61 | pub(crate) event: EventId, | 56 | pub(crate) event: EventId, |
| 62 | pub(crate) user: UserId, | 57 | pub(crate) user: UserId, |
| 63 | pub(crate) status: AttendanceStatus, | 58 | pub(crate) status: AttendanceStatus, |
| @@ -65,8 +60,9 @@ pub struct Attendance { | |||
| 65 | } | 60 | } |
| 66 | 61 | ||
| 67 | impl Attendance { | 62 | impl Attendance { |
| 68 | - pub fn get_id(&self) -> &AttendanceId { | 63 | + /// The row's identity, built back from its primary-key columns. |
| 69 | - &self.id | 64 | + pub fn get_id(&self) -> AttendanceId { |
| 65 | + AttendanceId::composite(&self.event, &self.user) | ||
| 70 | } | 66 | } |
| 71 | 67 | ||
| 72 | pub fn get_event(&self) -> &EventId { | 68 | pub fn get_event(&self) -> &EventId { |
src/domain/badge.rsmodified+11 -9
| @@ -14,8 +14,6 @@ | |||
| 14 | //! table, so [`earned`] is a total function of [`BadgeStats`] with no I/O | 14 | //! table, so [`earned`] is a total function of [`BadgeStats`] with no I/O |
| 15 | //! and no configuration behind it. | 15 | //! and no configuration behind it. |
| 16 | 16 | ||
| 17 | -use surrealdb::types::SurrealValue; | ||
| 18 | - | ||
| 19 | use crate::constant::{ | 17 | use crate::constant::{ |
| 20 | BADGES, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD, HOMEWORK_ON_TIME_TOTAL_FIELD, | 18 | BADGES, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD, HOMEWORK_ON_TIME_TOTAL_FIELD, |
| 21 | HOMEWORK_SUBMITTED_TOTAL_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD, | 19 | HOMEWORK_SUBMITTED_TOTAL_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD, |
| @@ -95,9 +93,11 @@ impl BadgeStat { | |||
| 95 | } | 93 | } |
| 96 | 94 | ||
| 97 | /// The lifetime counters one user has accumulated, as the badge rules see | 95 | /// The lifetime counters one user has accumulated, as the badge rules see |
| 98 | -/// them. Every field is a count and never an `Option`: no rows is a true zero, | 96 | +/// them. Every field is a count and never an `Option`: the columns are |
| 99 | -/// and an account that predates the columns reads like a fresh one. | 97 | +/// `BIGINT NOT NULL DEFAULT 0`, so no rows is a true zero. |
| 100 | -#[derive(Debug, Clone, Default, SurrealValue)] | 98 | +/// Not a row shape of its own — it is a projection the user-row queries |
| 99 | +/// select into (`SELECT homework_submitted, … FROM app_user WHERE id = $1`). | ||
| 100 | +#[derive(Debug, Clone, Default, sqlx::FromRow)] | ||
| 101 | pub struct BadgeStats { | 101 | pub struct BadgeStats { |
| 102 | homework_submitted: i64, | 102 | homework_submitted: i64, |
| 103 | homework_on_time: i64, | 103 | homework_on_time: i64, |
| @@ -195,8 +195,10 @@ pub fn earned(stats: &BadgeStats) -> Vec<&'static str> { | |||
| 195 | .collect() | 195 | .collect() |
| 196 | } | 196 | } |
| 197 | 197 | ||
| 198 | -/// One badge one user has earned, and when. | 198 | +/// One badge one user has earned, and when — a projection of the `badge_award` |
| 199 | -#[derive(Debug, Clone, SurrealValue)] | 199 | +/// row (whose identity is the (user, badge) pair) down to the two served |
| 200 | +/// columns. | ||
| 201 | +#[derive(Debug, Clone, sqlx::FromRow)] | ||
| 200 | pub struct BadgeAward { | 202 | pub struct BadgeAward { |
| 201 | badge: String, | 203 | badge: String, |
| 202 | earned_at: Timestamp, | 204 | earned_at: Timestamp, |
| @@ -240,8 +242,8 @@ mod tests { | |||
| 240 | } | 242 | } |
| 241 | } | 243 | } |
| 242 | 244 | ||
| 243 | - #[tokio::test] | 245 | + #[test] |
| 244 | - async fn the_rule_takes_every_threshold_at_or_below_the_count() { | 246 | + fn the_rule_takes_every_threshold_at_or_below_the_count() { |
| 245 | let stats = BadgeStats { | 247 | let stats = BadgeStats { |
| 246 | homework_submitted: 10, | 248 | homework_submitted: 10, |
| 247 | homework_on_time: 9, | 249 | homework_on_time: 9, |
src/domain/bank_question.rsmodified+27 -50
| @@ -10,14 +10,14 @@ | |||
| 10 | //! Pure types only: the queries live in [`crate::db::bank_question`], the | 10 | //! Pure types only: the queries live in [`crate::db::bank_question`], the |
| 11 | //! PATCH re-derive in [`crate::service::bank_question`]. | 11 | //! PATCH re-derive in [`crate::service::bank_question`]. |
| 12 | 12 | ||
| 13 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 13 | +use sqlx::types::Json; |
| 14 | 14 | ||
| 15 | -use crate::constant::{BANK_QUESTION_TABLE, BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL}; | 15 | +use crate::constant::{BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL}; |
| 16 | use crate::domain::exam::ExamId; | 16 | use crate::domain::exam::ExamId; |
| 17 | use crate::domain::exam_question::{ | 17 | use crate::domain::exam_question::{ |
| 18 | Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, | 18 | Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 19 | }; | 19 | }; |
| 20 | -use crate::domain::monotonic_id::next_ulid; | 20 | +use crate::domain::monotonic_id::next_uuid; |
| 21 | use crate::domain::subject::SubjectId; | 21 | use crate::domain::subject::SubjectId; |
| 22 | use crate::domain::timestamp::Timestamp; | 22 | use crate::domain::timestamp::Timestamp; |
| 23 | use crate::domain::user::UserId; | 23 | use crate::domain::user::UserId; |
| @@ -28,10 +28,11 @@ use crate::error::ValidationError; | |||
| 28 | /// | 28 | /// |
| 29 | /// **The default is `private`, deliberately.** A template carries `correct`, the | 29 | /// **The default is `private`, deliberately.** A template carries `correct`, the |
| 30 | /// answer key, and its images: publishing one is an explicit act, never a side | 30 | /// answer key, and its images: publishing one is an explicit act, never a side |
| 31 | -/// effect of saving a question to the bank. `#[surreal(default)]` on the field | 31 | +/// effect of saving a question to the bank. A new row defaults to `private` |
| 32 | -/// means rows written before this existed decode as `private` too, so the bank | 32 | +/// (the column is `TEXT NOT NULL DEFAULT 'private'`), so the bank can't |
| 33 | -/// can't retroactively broadcast anyone's answer keys. | 33 | +/// retroactively broadcast anyone's answer keys. |
| 34 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 34 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 35 | +#[sqlx(transparent)] | ||
| 35 | pub struct BankVisibility(String); | 36 | pub struct BankVisibility(String); |
| 36 | 37 | ||
| 37 | impl Default for BankVisibility { | 38 | impl Default for BankVisibility { |
| @@ -61,31 +62,28 @@ impl BankVisibility { | |||
| 61 | } | 62 | } |
| 62 | } | 63 | } |
| 63 | 64 | ||
| 64 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 65 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 65 | -pub struct BankQuestionId(RecordId); | 66 | +#[sqlx(transparent)] |
| 67 | +pub struct BankQuestionId(uuid::Uuid); | ||
| 66 | 68 | ||
| 67 | impl BankQuestionId { | 69 | impl BankQuestionId { |
| 68 | /// A write-ordered id. `list` sorts `id DESC` to mean "newest first", and | 70 | /// A write-ordered id. `list` sorts `id DESC` to mean "newest first", and |
| 69 | - /// a random ULID is only millisecond-accurate — templates saved inside one | 71 | + /// a plain random UUID is only millisecond-accurate — templates saved |
| 70 | - /// tick (a to-bank burst, a test loop) would come back shuffled, so the id | 72 | + /// inside one tick (a to-bank burst, a test loop) would come back |
| 71 | - /// comes from [`crate::domain::monotonic_id`] instead. | 73 | + /// shuffled, so the id comes from [`crate::domain::monotonic_id`] instead. |
| 72 | pub fn generate() -> Self { | 74 | pub fn generate() -> Self { |
| 73 | - Self(RecordId::new(BANK_QUESTION_TABLE, next_ulid().to_string())) | 75 | + Self(next_uuid()) |
| 74 | } | 76 | } |
| 75 | 77 | ||
| 78 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 79 | + /// which matches no row — a malformed path param stays a 404, exactly | ||
| 80 | + /// like a well-formed one that names nothing. | ||
| 76 | pub fn from_key(key: &str) -> Self { | 81 | pub fn from_key(key: &str) -> Self { |
| 77 | - Self(RecordId::new(BANK_QUESTION_TABLE, key)) | 82 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 78 | } | 83 | } |
| 79 | 84 | ||
| 80 | - pub fn record(&self) -> RecordId { | 85 | + pub fn key(&self) -> String { |
| 81 | - self.0.clone() | 86 | + self.0.to_string() |
| 82 | - } | ||
| 83 | - | ||
| 84 | - pub fn key(&self) -> &str { | ||
| 85 | - match &self.0.key { | ||
| 86 | - RecordIdKey::String(key) => key, | ||
| 87 | - _ => "", | ||
| 88 | - } | ||
| 89 | } | 87 | } |
| 90 | } | 88 | } |
| 91 | 89 | ||
| @@ -95,30 +93,25 @@ impl BankQuestionId { | |||
| 95 | /// subject when a template is copied into an exam, not here. | 93 | /// subject when a template is copied into an exam, not here. |
| 96 | /// | 94 | /// |
| 97 | /// `subject` is optional because it is *only* metadata: deleting a subject | 95 | /// `subject` is optional because it is *only* metadata: deleting a subject |
| 98 | -/// clears it school-wide (see [`crate::db::subject::delete`]) | 96 | +/// nulls it school-wide (see [`crate::db::subject::delete`]) |
| 99 | /// rather than being blocked by the bank. Blocking would have been a dead end | 97 | /// rather than being blocked by the bank. Blocking would have been a dead end |
| 100 | /// — the bank is owner-or-admin editable, so a manager could not resolve their | 98 | /// — the bank is owner-or-admin editable, so a manager could not resolve their |
| 101 | /// own 409 — and an existence oracle, since another teacher's *private* | 99 | /// own 409 — and an existence oracle, since another teacher's *private* |
| 102 | /// template would have raised it. | 100 | /// template would have raised it. |
| 103 | -#[derive(Debug, Clone, SurrealValue)] | 101 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 104 | pub struct BankQuestion { | 102 | pub struct BankQuestion { |
| 105 | pub(crate) id: BankQuestionId, | 103 | pub(crate) id: BankQuestionId, |
| 106 | pub(crate) owner: UserId, | 104 | pub(crate) owner: UserId, |
| 107 | /// The origin subject, or `None` once that subject was deleted. | 105 | /// The origin subject, or `None` once that subject was deleted. |
| 108 | - /// `#[surreal(default)]` for the same reason `visibility` has one: rows | ||
| 109 | - /// written before the field went optional still decode. | ||
| 110 | - #[surreal(default)] | ||
| 111 | pub(crate) subject: Option<SubjectId>, | 106 | pub(crate) subject: Option<SubjectId>, |
| 112 | pub(crate) text: QuestionText, | 107 | pub(crate) text: QuestionText, |
| 113 | pub(crate) kind: QuestionKind, | 108 | pub(crate) kind: QuestionKind, |
| 114 | pub(crate) points: QuestionPoints, | 109 | pub(crate) points: QuestionPoints, |
| 115 | - pub(crate) choices: Option<Vec<Choice>>, | 110 | + pub(crate) choices: Option<Json<Vec<Choice>>>, |
| 116 | pub(crate) correct: Option<ChoiceId>, | 111 | pub(crate) correct: Option<ChoiceId>, |
| 117 | /// The exam question this template was saved from, if any. | 112 | /// The exam question this template was saved from, if any. |
| 118 | pub(crate) source_exam: Option<ExamId>, | 113 | pub(crate) source_exam: Option<ExamId>, |
| 119 | - /// Who may read it. `#[surreal(default)]` (not serde — that doesn't compile | 114 | + /// Who may read it; defaults to `private` at the column. |
| 120 | - /// here): rows written before the field existed decode as `private`. | ||
| 121 | - #[surreal(default)] | ||
| 122 | pub(crate) visibility: BankVisibility, | 115 | pub(crate) visibility: BankVisibility, |
| 123 | pub(crate) created_at: Timestamp, | 116 | pub(crate) created_at: Timestamp, |
| 124 | } | 117 | } |
| @@ -148,10 +141,6 @@ impl BankQuestion { | |||
| 148 | self.points | 141 | self.points |
| 149 | } | 142 | } |
| 150 | 143 | ||
| 151 | - pub fn get_choices(&self) -> Option<&[Choice]> { | ||
| 152 | - self.choices.as_deref() | ||
| 153 | - } | ||
| 154 | - | ||
| 155 | pub fn get_correct(&self) -> Option<&ChoiceId> { | 144 | pub fn get_correct(&self) -> Option<&ChoiceId> { |
| 156 | self.correct.as_ref() | 145 | self.correct.as_ref() |
| 157 | } | 146 | } |
| @@ -176,7 +165,7 @@ impl BankQuestion { | |||
| 176 | pub fn spec(&self) -> QuestionSpec { | 165 | pub fn spec(&self) -> QuestionSpec { |
| 177 | QuestionSpec::from_stored( | 166 | QuestionSpec::from_stored( |
| 178 | self.kind.clone(), | 167 | self.kind.clone(), |
| 179 | - self.choices.clone(), | 168 | + self.choices.as_ref().map(|json| json.0.clone()), |
| 180 | self.correct.clone(), | 169 | self.correct.clone(), |
| 181 | ) | 170 | ) |
| 182 | } | 171 | } |
| @@ -201,7 +190,7 @@ impl BankQuestion { | |||
| 201 | text, | 190 | text, |
| 202 | kind, | 191 | kind, |
| 203 | points, | 192 | points, |
| 204 | - choices, | 193 | + choices: choices.map(Json), |
| 205 | correct, | 194 | correct, |
| 206 | source_exam, | 195 | source_exam, |
| 207 | visibility, | 196 | visibility, |
| @@ -209,15 +198,3 @@ impl BankQuestion { | |||
| 209 | } | 198 | } |
| 210 | } | 199 | } |
| 211 | } | 200 | } |
| 212 | - | ||
| 213 | -#[cfg(test)] | ||
| 214 | -mod tests { | ||
| 215 | - use super::*; | ||
| 216 | - | ||
| 217 | - #[test] | ||
| 218 | - fn visibility_rejects_anything_else() { | ||
| 219 | - assert!(BankVisibility::try_new("public").is_err()); | ||
| 220 | - assert!(BankVisibility::try_new("").is_err()); | ||
| 221 | - assert!(BankVisibility::try_new("school").unwrap().is_school()); | ||
| 222 | - } | ||
| 223 | -} | ||
src/domain/bank_question_image.rsmodified+35 -37
| @@ -1,58 +1,56 @@ | |||
| 1 | //! An image pinned to a bank question — the question's own illustration | 1 | //! An image pinned to a bank question — the question's own illustration |
| 2 | -//! (`slot = NONE`) or one choice's picture (`slot` = that choice's stable id, | 2 | +//! (`slot = NULL`) or one choice's picture (`slot` = that choice's stable id, |
| 3 | //! choice questions only). | 3 | //! choice questions only). |
| 4 | //! A structural copy of [`crate::domain::question_image`] with the exam FK | 4 | //! A structural copy of [`crate::domain::question_image`] with the exam FK |
| 5 | //! dropped: a bank template belongs to no exam, and its owner is reachable | 5 | //! dropped: a bank template belongs to no exam, and its owner is reachable |
| 6 | //! through the `bank_question` row. The row carries metadata; the bytes live | 6 | //! through the `bank_question` row. The row carries metadata; the bytes live |
| 7 | //! on disk under [`crate::config::Config::files_path`] in a file named by | 7 | //! on disk under [`crate::config::Config::files_path`] in a file named by |
| 8 | -//! `file` — a fresh server-generated ULID per upload. The row id is | 8 | +//! `file` — a fresh server-generated UUID per upload. The row is keyed by |
| 9 | -//! *deterministic* per (question, slot), so "one image per slot" holds by | 9 | +//! (question, slot) under a `NULLS NOT DISTINCT` unique constraint, so "one |
| 10 | -//! construction and a replace is a plain UPSERT. The web layer owns the blob | 10 | +//! image per slot" holds by construction and a replace is a plain UPSERT. The |
| 11 | -//! I/O and its ordering; the queries live in | 11 | +//! web layer owns the blob I/O and its ordering; the queries live in |
| 12 | //! [`crate::db::bank_question_image`]. | 12 | //! [`crate::db::bank_question_image`]. |
| 13 | 13 | ||
| 14 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 15 | -use ulid::Ulid; | ||
| 16 | - | ||
| 17 | -use crate::constant::BANK_QUESTION_IMAGE_TABLE; | ||
| 18 | use crate::domain::bank_question::BankQuestionId; | 14 | use crate::domain::bank_question::BankQuestionId; |
| 19 | use crate::domain::exam_question::ChoiceId; | 15 | use crate::domain::exam_question::ChoiceId; |
| 20 | use crate::domain::key; | 16 | use crate::domain::key; |
| 21 | use crate::domain::note_file::FileContentType; | 17 | use crate::domain::note_file::FileContentType; |
| 22 | 18 | ||
| 23 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 19 | +/// The identity of one (question, slot) pair. Not a row column: the table's |
| 24 | -pub struct BankQuestionImageId(RecordId); | 20 | +/// unique constraint *is* the pair, and this struct's job is the |
| 21 | +/// underscore-joined wire form at the HTTP edge. | ||
| 22 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 23 | +pub struct BankQuestionImageId { | ||
| 24 | + pub(crate) question: BankQuestionId, | ||
| 25 | + pub(crate) slot: Option<ChoiceId>, | ||
| 26 | +} | ||
| 25 | 27 | ||
| 26 | impl BankQuestionImageId { | 28 | impl BankQuestionImageId { |
| 27 | - /// The one id a (question, slot) pair can have — see [`key::slot`] for the | 29 | + /// The one id a (question, slot) pair can have — see [`key::slot`] for |
| 28 | - /// key shape and why the two forms can never collide. | 30 | + /// the wire shape and why the two forms can never collide. |
| 29 | pub fn for_slot(question: &BankQuestionId, slot: Option<&ChoiceId>) -> Self { | 31 | pub fn for_slot(question: &BankQuestionId, slot: Option<&ChoiceId>) -> Self { |
| 30 | - Self(RecordId::new( | 32 | + Self { |
| 31 | - BANK_QUESTION_IMAGE_TABLE, | 33 | + question: question.clone(), |
| 32 | - key::slot(question.key(), slot.map(|id| id.as_str())), | 34 | + slot: slot.cloned(), |
| 33 | - )) | 35 | + } |
| 34 | - } | ||
| 35 | - | ||
| 36 | - pub fn record(&self) -> RecordId { | ||
| 37 | - self.0.clone() | ||
| 38 | } | 36 | } |
| 39 | 37 | ||
| 40 | - pub fn key(&self) -> &str { | 38 | + /// The underscore-joined wire form (`{question}_{slot|q}`). |
| 41 | - match &self.0.key { | 39 | + pub fn key(&self) -> String { |
| 42 | - RecordIdKey::String(key) => key, | 40 | + key::slot( |
| 43 | - _ => "", | 41 | + self.question.key().as_str(), |
| 44 | - } | 42 | + self.slot.as_ref().map(|id| id.as_str()), |
| 43 | + ) | ||
| 45 | } | 44 | } |
| 46 | } | 45 | } |
| 47 | 46 | ||
| 48 | -#[derive(Debug, Clone, SurrealValue)] | 47 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 49 | pub struct BankQuestionImage { | 48 | pub struct BankQuestionImage { |
| 50 | - pub(crate) id: BankQuestionImageId, | ||
| 51 | pub(crate) bank_question: BankQuestionId, | 49 | pub(crate) bank_question: BankQuestionId, |
| 52 | - /// `NONE` = the question's illustration; otherwise the id of the option | 50 | + /// `NULL` = the question's illustration; otherwise the id of the option |
| 53 | /// this picture belongs to. | 51 | /// this picture belongs to. |
| 54 | pub(crate) slot: Option<ChoiceId>, | 52 | pub(crate) slot: Option<ChoiceId>, |
| 55 | - /// The blob's on-disk name — a fresh ULID every upload. | 53 | + /// The blob's on-disk name — a fresh UUID every upload. |
| 56 | pub(crate) file: String, | 54 | pub(crate) file: String, |
| 57 | pub(crate) content_type: FileContentType, | 55 | pub(crate) content_type: FileContentType, |
| 58 | pub(crate) size: i64, | 56 | pub(crate) size: i64, |
| @@ -70,17 +68,17 @@ impl BankQuestionImage { | |||
| 70 | size: i64, | 68 | size: i64, |
| 71 | ) -> Self { | 69 | ) -> Self { |
| 72 | Self { | 70 | Self { |
| 73 | - id: BankQuestionImageId::for_slot(question, slot), | ||
| 74 | bank_question: question.clone(), | 71 | bank_question: question.clone(), |
| 75 | slot: slot.cloned(), | 72 | slot: slot.cloned(), |
| 76 | - file: Ulid::generate().to_string(), | 73 | + file: uuid::Uuid::new_v4().to_string(), |
| 77 | content_type, | 74 | content_type, |
| 78 | size, | 75 | size, |
| 79 | } | 76 | } |
| 80 | } | 77 | } |
| 81 | 78 | ||
| 82 | - pub fn get_id(&self) -> &BankQuestionImageId { | 79 | + /// The row's identity, built back from its unique-key columns. |
| 83 | - &self.id | 80 | + pub fn get_id(&self) -> BankQuestionImageId { |
| 81 | + BankQuestionImageId::for_slot(&self.bank_question, self.slot.as_ref()) | ||
| 84 | } | 82 | } |
| 85 | 83 | ||
| 86 | pub fn get_bank_question(&self) -> &BankQuestionId { | 84 | pub fn get_bank_question(&self) -> &BankQuestionId { |
| @@ -135,15 +133,15 @@ mod tests { | |||
| 135 | 133 | ||
| 136 | #[test] | 134 | #[test] |
| 137 | fn for_slot_keys_by_question_and_choice_id() { | 135 | fn for_slot_keys_by_question_and_choice_id() { |
| 138 | - let question = BankQuestionId::from_key("abc"); | 136 | + let question = BankQuestionId::from_key("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"); |
| 139 | let ids = choice_ids(); | 137 | let ids = choice_ids(); |
| 140 | assert_eq!( | 138 | assert_eq!( |
| 141 | BankQuestionImageId::for_slot(&question, None).key(), | 139 | BankQuestionImageId::for_slot(&question, None).key(), |
| 142 | - "abc_q" | 140 | + format!("{}_q", question.key()) |
| 143 | ); | 141 | ); |
| 144 | assert_eq!( | 142 | assert_eq!( |
| 145 | BankQuestionImageId::for_slot(&question, Some(&ids[0])).key(), | 143 | BankQuestionImageId::for_slot(&question, Some(&ids[0])).key(), |
| 146 | - format!("abc_{}", ids[0].as_str()) | 144 | + format!("{}_{}", question.key(), ids[0].as_str()) |
| 147 | ); | 145 | ); |
| 148 | // Distinct options never share a row. | 146 | // Distinct options never share a row. |
| 149 | assert_ne!( | 147 | assert_ne!( |
src/domain/board.rsmodified+37 -43
| @@ -7,48 +7,44 @@ | |||
| 7 | //! The marks themselves live in `board_stroke`, appended and never deleted: a | 7 | //! The marks themselves live in `board_stroke`, appended and never deleted: a |
| 8 | //! clear bumps `epoch` so the canvas empties while the history stays | 8 | //! clear bumps `epoch` so the canvas empties while the history stays |
| 9 | //! replayable. The two stroke counters (`epoch_stroke_count`, | 9 | //! replayable. The two stroke counters (`epoch_stroke_count`, |
| 10 | -//! `total_stroke_count`) are `option<int>` columns this struct deliberately | 10 | +//! `total_stroke_count`) are counter columns this struct deliberately does |
| 11 | -//! does NOT carry — they are written only by the stroke path's conditional | 11 | +//! NOT carry — they are written only by the stroke path's conditional claim, |
| 12 | -//! claim, so every mutation here is field-scoped `UPDATE … SET`. A whole-row | 12 | +//! so every mutation here is a field-scoped `UPDATE … SET`. A whole-row |
| 13 | -//! `CONTENT` save would silently wipe both (src/constant.rs:717-722). | 13 | +//! rewrite would silently wipe both. |
| 14 | 14 | ||
| 15 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 15 | +use crate::constant::{MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN}; |
| 16 | - | 16 | +use crate::domain::monotonic_id::next_uuid; |
| 17 | -use crate::constant::{BOARD_TABLE, MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN}; | ||
| 18 | -use crate::domain::monotonic_id::next_ulid; | ||
| 19 | use crate::domain::timestamp::Timestamp; | 17 | use crate::domain::timestamp::Timestamp; |
| 20 | use crate::domain::user::UserId; | 18 | use crate::domain::user::UserId; |
| 21 | use crate::error::ValidationError; | 19 | use crate::error::ValidationError; |
| 22 | use crate::validate::validate_required; | 20 | use crate::validate::validate_required; |
| 23 | 21 | ||
| 24 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 22 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 25 | -pub struct BoardId(RecordId); | 23 | +#[sqlx(transparent)] |
| 24 | +pub struct BoardId(uuid::Uuid); | ||
| 26 | 25 | ||
| 27 | impl BoardId { | 26 | impl BoardId { |
| 28 | - /// Monotonic, not `Ulid::generate()`: boards list newest-first by id, and a | 27 | + /// Monotonic, not a plain random UUID: boards list newest-first by id, and |
| 29 | - /// random low half scrambles rows minted in the same millisecond. | 28 | + /// a random low half scrambles rows minted in the same millisecond. |
| 30 | pub fn generate() -> Self { | 29 | pub fn generate() -> Self { |
| 31 | - Self(RecordId::new(BOARD_TABLE, next_ulid().to_string())) | 30 | + Self(next_uuid()) |
| 32 | } | 31 | } |
| 33 | 32 | ||
| 33 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 34 | + /// which matches no row — a malformed path param stays a 404, exactly | ||
| 35 | + /// like a well-formed one that names nothing. | ||
| 34 | pub fn from_key(key: &str) -> Self { | 36 | pub fn from_key(key: &str) -> Self { |
| 35 | - Self(RecordId::new(BOARD_TABLE, key)) | 37 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 36 | - } | ||
| 37 | - | ||
| 38 | - pub fn record(&self) -> RecordId { | ||
| 39 | - self.0.clone() | ||
| 40 | } | 38 | } |
| 41 | 39 | ||
| 42 | - pub fn key(&self) -> &str { | 40 | + pub fn key(&self) -> String { |
| 43 | - match &self.0.key { | 41 | + self.0.to_string() |
| 44 | - RecordIdKey::String(key) => key, | ||
| 45 | - _ => "", | ||
| 46 | - } | ||
| 47 | } | 42 | } |
| 48 | } | 43 | } |
| 49 | 44 | ||
| 50 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 45 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 51 | -pub struct BoardTitle(pub(crate) String); | 46 | +#[sqlx(transparent)] |
| 47 | +pub struct BoardTitle(String); | ||
| 52 | 48 | ||
| 53 | impl BoardTitle { | 49 | impl BoardTitle { |
| 54 | pub fn try_new(value: &str) -> Result<Self, ValidationError> { | 50 | pub fn try_new(value: &str) -> Result<Self, ValidationError> { |
| @@ -83,7 +79,7 @@ pub(crate) fn checked_participants( | |||
| 83 | Ok(unique) | 79 | Ok(unique) |
| 84 | } | 80 | } |
| 85 | 81 | ||
| 86 | -#[derive(Debug, Clone, SurrealValue)] | 82 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 87 | pub struct Board { | 83 | pub struct Board { |
| 88 | pub(crate) id: BoardId, | 84 | pub(crate) id: BoardId, |
| 89 | pub(crate) creator: UserId, | 85 | pub(crate) creator: UserId, |
| @@ -162,10 +158,10 @@ mod tests { | |||
| 162 | /// so no store is involved. | 158 | /// so no store is involved. |
| 163 | fn a_board() -> Board { | 159 | fn a_board() -> Board { |
| 164 | Board { | 160 | Board { |
| 165 | - id: BoardId::from_key("b"), | 161 | + id: BoardId::from_key("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"), |
| 166 | - creator: user("c"), | 162 | + creator: user("0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e"), |
| 167 | title: BoardTitle::try_new("Geometri").unwrap(), | 163 | title: BoardTitle::try_new("Geometri").unwrap(), |
| 168 | - participants: vec![user("p")], | 164 | + participants: vec![user("0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f")], |
| 169 | locked: false, | 165 | locked: false, |
| 170 | locked_by: None, | 166 | locked_by: None, |
| 171 | locked_at: None, | 167 | locked_at: None, |
| @@ -179,14 +175,14 @@ mod tests { | |||
| 179 | fn the_two_predicates_are_the_permission_model() { | 175 | fn the_two_predicates_are_the_permission_model() { |
| 180 | let board = a_board(); | 176 | let board = a_board(); |
| 181 | // Creator: draws AND commands. | 177 | // Creator: draws AND commands. |
| 182 | - assert!(board.is_participant(&user("c"))); | 178 | + assert!(board.is_participant(&user("0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e"))); |
| 183 | - assert!(board.is_creator(&user("c"))); | 179 | + assert!(board.is_creator(&user("0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e"))); |
| 184 | // Invited: draws only. | 180 | // Invited: draws only. |
| 185 | - assert!(board.is_participant(&user("p"))); | 181 | + assert!(board.is_participant(&user("0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f"))); |
| 186 | - assert!(!board.is_creator(&user("p"))); | 182 | + assert!(!board.is_creator(&user("0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f"))); |
| 187 | // Stranger: neither. | 183 | // Stranger: neither. |
| 188 | - assert!(!board.is_participant(&user("s"))); | 184 | + assert!(!board.is_participant(&user("0198f1a2-3b4c-7d5e-8f90-cccc4d5e6f7a"))); |
| 189 | - assert!(!board.is_creator(&user("s"))); | 185 | + assert!(!board.is_creator(&user("0198f1a2-3b4c-7d5e-8f90-cccc4d5e6f7a"))); |
| 190 | } | 186 | } |
| 191 | 187 | ||
| 192 | #[test] | 188 | #[test] |
| @@ -198,14 +194,12 @@ mod tests { | |||
| 198 | 194 | ||
| 199 | #[test] | 195 | #[test] |
| 200 | fn participants_are_deduplicated_and_bounded() { | 196 | fn participants_are_deduplicated_and_bounded() { |
| 201 | - assert_eq!( | 197 | + let one = user("0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f"); |
| 202 | - checked_participants(vec![user("p"), user("p")]) | 198 | + assert_eq!(checked_participants(vec![one.clone(), one]).unwrap().len(), 1); |
| 203 | - .unwrap() | 199 | + // One over the ceiling is refused; each key must be a distinct |
| 204 | - .len(), | 200 | + // *parseable* UUID, or the parser would collapse them all to nil. |
| 205 | - 1 | 201 | + let many = (0..=MAX_BOARD_PARTICIPANTS) |
| 206 | - ); | 202 | + .map(|n| user(&format!("0198f1a2-3b4c-7d5e-8f90-{n:012x}"))) |
| 207 | - let many = (0..MAX_BOARD_PARTICIPANTS + 1) | ||
| 208 | - .map(|n| UserId::from_key(&format!("u{n}"))) | ||
| 209 | .collect(); | 203 | .collect(); |
| 210 | assert!(checked_participants(many).is_err()); | 204 | assert!(checked_participants(many).is_err()); |
| 211 | } | 205 | } |
src/domain/board_stroke.rsmodified+25 -28
| @@ -8,21 +8,18 @@ | |||
| 8 | //! transaction as the board's own delete. | 8 | //! transaction as the board's own delete. |
| 9 | //! | 9 | //! |
| 10 | //! The `clear` marker row IS the epoch index: it carries the epoch it closed, | 10 | //! The `clear` marker row IS the epoch index: it carries the epoch it closed, |
| 11 | -//! that epoch's final stroke count, who cleared and when — so replaying a whole | 11 | +//! that epoch's final stroke count, who cleared and when — so replaying a |
| 12 | -//! session needs no second table and no `GROUP BY` over the history. | 12 | +//! whole session needs no second table and no `GROUP BY` over the history. |
| 13 | //! | 13 | //! |
| 14 | -//! Writes funnel through [`crate::db::board_stroke`], and so do the board's | 14 | +//! two stroke counters. Nothing else may write either, because the invariant |
| 15 | -//! two stroke counters. Nothing else may write either, because two invariants | 15 | +//! the schema cannot state depends on it: `count` is populated *only* on a |
| 16 | -//! the schema cannot state depend on it: `count` is populated *only* on a | 16 | +//! `clear` row, and the two counters must move together with the row they |
| 17 | -//! `clear` row (SCHEMAFULL types both kinds the same), and the two counters | 17 | +//! count (the stroke claim's dual-counter CTE is what makes that one |
| 18 | -//! must move together with the row they count (`cap::claim_two_when_and_create` | 18 | +//! transaction). |
| 19 | -//! is what makes that one transaction). | ||
| 20 | 19 | ||
| 21 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 20 | +use crate::constant::BOARD_STROKE_KINDS; |
| 22 | - | ||
| 23 | -use crate::constant::{BOARD_STROKE_KINDS, BOARD_STROKE_TABLE}; | ||
| 24 | use crate::domain::board::Board; | 21 | use crate::domain::board::Board; |
| 25 | -use crate::domain::monotonic_id::next_ulid; | 22 | +use crate::domain::monotonic_id::next_uuid; |
| 26 | use crate::domain::timestamp::Timestamp; | 23 | use crate::domain::timestamp::Timestamp; |
| 27 | use crate::domain::user::UserId; | 24 | use crate::domain::user::UserId; |
| 28 | 25 | ||
| @@ -30,9 +27,9 @@ use crate::domain::user::UserId; | |||
| 30 | pub(crate) const KIND_STROKE: &str = BOARD_STROKE_KINDS[0]; | 27 | pub(crate) const KIND_STROKE: &str = BOARD_STROKE_KINDS[0]; |
| 31 | pub(crate) const KIND_CLEAR: &str = BOARD_STROKE_KINDS[1]; | 28 | pub(crate) const KIND_CLEAR: &str = BOARD_STROKE_KINDS[1]; |
| 32 | 29 | ||
| 33 | -/// The `THROW` the clear transaction refuses with: a blank canvas, not the | 30 | +/// The refusal the clear transaction refuses with: a blank canvas, not the |
| 34 | /// creator, or the board is locked or already closed. A decision, so it | 31 | /// creator, or the board is locked or already closed. A decision, so it |
| 35 | -/// outranks a lost round. | 32 | +/// outranks a retryable failure. |
| 36 | pub(crate) const CLEAR_REFUSED: &str = "board_clear_refused"; | 33 | pub(crate) const CLEAR_REFUSED: &str = "board_clear_refused"; |
| 37 | 34 | ||
| 38 | /// The public words of every refusal this module raises. `pub` because | 35 | /// The public words of every refusal this module raises. `pub` because |
| @@ -58,30 +55,30 @@ pub const REFUSALS: [&str; 5] = [ | |||
| 58 | CANVAS_BLANK, | 55 | CANVAS_BLANK, |
| 59 | ]; | 56 | ]; |
| 60 | 57 | ||
| 61 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 58 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 62 | -pub struct BoardStrokeId(RecordId); | 59 | +#[sqlx(transparent)] |
| 60 | +pub struct BoardStrokeId(uuid::Uuid); | ||
| 63 | 61 | ||
| 64 | impl BoardStrokeId { | 62 | impl BoardStrokeId { |
| 65 | - /// Monotonic, not `Ulid::generate()`: this id *is* the board's total order, and | 63 | + /// Monotonic, not a plain random UUID: this id *is* the board's total |
| 66 | - /// a random low half scrambles every stroke drawn in the same millisecond — | 64 | + /// order, and a random low half scrambles every stroke drawn in the same |
| 67 | - /// which is what a burst of drawing looks like. | 65 | + /// millisecond — which is what a burst of drawing looks like. |
| 68 | pub fn generate() -> Self { | 66 | pub fn generate() -> Self { |
| 69 | - Self(RecordId::new(BOARD_STROKE_TABLE, next_ulid().to_string())) | 67 | + Self(next_uuid()) |
| 70 | } | 68 | } |
| 71 | 69 | ||
| 72 | - pub fn record(&self) -> RecordId { | 70 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, |
| 73 | - self.0.clone() | 71 | + /// which matches no row. |
| 72 | + pub fn from_key(key: &str) -> Self { | ||
| 73 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) | ||
| 74 | } | 74 | } |
| 75 | 75 | ||
| 76 | - pub fn key(&self) -> &str { | 76 | + pub fn key(&self) -> String { |
| 77 | - match &self.0.key { | 77 | + self.0.to_string() |
| 78 | - RecordIdKey::String(key) => key, | ||
| 79 | - _ => "", | ||
| 80 | - } | ||
| 81 | } | 78 | } |
| 82 | } | 79 | } |
| 83 | 80 | ||
| 84 | -#[derive(Debug, Clone, SurrealValue)] | 81 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 85 | pub struct BoardStroke { | 82 | pub struct BoardStroke { |
| 86 | pub(crate) id: BoardStrokeId, | 83 | pub(crate) id: BoardStrokeId, |
| 87 | pub(crate) board: crate::domain::board::BoardId, | 84 | pub(crate) board: crate::domain::board::BoardId, |
src/domain/builder.rsmodified+16 -18
| @@ -9,9 +9,9 @@ | |||
| 9 | //! The credential newtypes are [`crate::domain::user`]'s — same rules, same | 9 | //! The credential newtypes are [`crate::domain::user`]'s — same rules, same |
| 10 | //! argon2 discipline, deliberately not a second copy that could drift. | 10 | //! argon2 discipline, deliberately not a second copy that could drift. |
| 11 | 11 | ||
| 12 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 12 | +use uuid::Uuid; |
| 13 | -use ulid::Ulid; | ||
| 14 | 13 | ||
| 14 | +use crate::domain::monotonic_id::next_uuid; | ||
| 15 | use crate::domain::session::SessionToken; | 15 | use crate::domain::session::SessionToken; |
| 16 | use crate::domain::timestamp::Timestamp; | 16 | use crate::domain::timestamp::Timestamp; |
| 17 | use crate::domain::user::{PasswordHash, Username}; | 17 | use crate::domain::user::{PasswordHash, Username}; |
| @@ -19,31 +19,29 @@ use crate::domain::user::{PasswordHash, Username}; | |||
| 19 | pub const BUILDER_TABLE: &str = "builder"; | 19 | pub const BUILDER_TABLE: &str = "builder"; |
| 20 | pub const BUILDER_SESSION_TABLE: &str = "builder_session"; | 20 | pub const BUILDER_SESSION_TABLE: &str = "builder_session"; |
| 21 | 21 | ||
| 22 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 22 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 23 | -pub struct BuilderId(RecordId); | 23 | +#[sqlx(transparent)] |
| 24 | +pub struct BuilderId(Uuid); | ||
| 24 | 25 | ||
| 25 | impl BuilderId { | 26 | impl BuilderId { |
| 27 | + /// A plain random UUID deliberately: builder rows are looked up by | ||
| 28 | + /// username, never listed by id. | ||
| 26 | pub fn generate() -> Self { | 29 | pub fn generate() -> Self { |
| 27 | - Self(RecordId::new(BUILDER_TABLE, Ulid::generate().to_string())) | 30 | + Self(next_uuid()) |
| 28 | } | 31 | } |
| 29 | 32 | ||
| 33 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 34 | + /// which matches no row. | ||
| 30 | pub fn from_key(key: &str) -> Self { | 35 | pub fn from_key(key: &str) -> Self { |
| 31 | - Self(RecordId::new(BUILDER_TABLE, key)) | 36 | + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) |
| 32 | } | 37 | } |
| 33 | 38 | ||
| 34 | - pub fn record(&self) -> RecordId { | 39 | + pub fn key(&self) -> String { |
| 35 | - self.0.clone() | 40 | + self.0.to_string() |
| 36 | - } | ||
| 37 | - | ||
| 38 | - pub fn key(&self) -> &str { | ||
| 39 | - match &self.0.key { | ||
| 40 | - RecordIdKey::String(key) => key, | ||
| 41 | - _ => "", | ||
| 42 | - } | ||
| 43 | } | 41 | } |
| 44 | } | 42 | } |
| 45 | 43 | ||
| 46 | -#[derive(Debug, Clone, SurrealValue)] | 44 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 47 | pub struct Builder { | 45 | pub struct Builder { |
| 48 | pub(crate) id: BuilderId, | 46 | pub(crate) id: BuilderId, |
| 49 | pub(crate) username: Username, | 47 | pub(crate) username: Username, |
| @@ -67,9 +65,9 @@ impl Builder { | |||
| 67 | /// A builder's login session. [`crate::domain::session::Session`]'s shape | 65 | /// A builder's login session. [`crate::domain::session::Session`]'s shape |
| 68 | /// against the control database, with the token type shared so both cookies | 66 | /// against the control database, with the token type shared so both cookies |
| 69 | /// are the same 64 hex chars. | 67 | /// are the same 64 hex chars. |
| 70 | -#[derive(Debug, Clone, SurrealValue)] | 68 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 71 | pub struct BuilderSession { | 69 | pub struct BuilderSession { |
| 72 | - pub(crate) id: RecordId, | 70 | + pub(crate) id: Uuid, |
| 73 | pub(crate) builder: BuilderId, | 71 | pub(crate) builder: BuilderId, |
| 74 | pub(crate) token: SessionToken, | 72 | pub(crate) token: SessionToken, |
| 75 | pub(crate) created_at: Timestamp, | 73 | pub(crate) created_at: Timestamp, |
src/domain/chatbot_message.rsmodified+47 -82
| @@ -7,72 +7,54 @@ | |||
| 7 | //! `failed` by the task that owns the bridge round trip, and a read | 7 | //! `failed` by the task that owns the bridge round trip, and a read |
| 8 | //! projects a long-stale `pending` as failed without writing | 8 | //! projects a long-stale `pending` as failed without writing |
| 9 | //! ([`ChatbotMessage::projected`]) — the durable repair for a dead process | 9 | //! ([`ChatbotMessage::projected`]) — the durable repair for a dead process |
| 10 | -//! happens once, at boot, in `database.rs`. | 10 | +//! happens once, at mint, in `database.rs`'s school migration sweep. |
| 11 | - | ||
| 12 | -use std::sync::{LazyLock, Mutex}; | ||
| 13 | - | ||
| 14 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 15 | -use ulid::{Generator, Ulid}; | ||
| 16 | 11 | ||
| 17 | use crate::constant::{ | 12 | use crate::constant::{ |
| 18 | - CHAT_MESSAGE_TABLE, CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE, | 13 | + CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE, |
| 19 | }; | 14 | }; |
| 20 | use crate::domain::chatbot_thread::ChatbotThreadId; | 15 | use crate::domain::chatbot_thread::ChatbotThreadId; |
| 16 | +use crate::domain::monotonic_id::next_uuid; | ||
| 21 | use crate::domain::timestamp::Timestamp; | 17 | use crate::domain::timestamp::Timestamp; |
| 22 | use crate::domain::user::UserId; | 18 | use crate::domain::user::UserId; |
| 23 | use crate::error::ValidationError; | 19 | use crate::error::ValidationError; |
| 24 | use crate::validate::validate_required; | 20 | use crate::validate::validate_required; |
| 25 | 21 | ||
| 26 | -/// Mints message ids in write order. Unlike `Ulid::generate()`, whose 80 random | 22 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 27 | -/// low bits sort arbitrarily among ids minted in the same millisecond, this | 23 | +#[sqlx(transparent)] |
| 28 | -/// increments the previous id — so the `id` tie-break in the `ORDER BY` of | 24 | +pub struct ChatbotMessageId(uuid::Uuid); |
| 29 | -/// [`list_for_thread`](crate::db::chatbot_message::list_for_thread) / | ||
| 30 | -/// [`list_tail`](crate::db::chatbot_message::list_tail) is the | ||
| 31 | -/// order the rows were written. The user prompt and the assistant row one POST | ||
| 32 | -/// writes back-to-back routinely share a millisecond, and a random tie-break | ||
| 33 | -/// there renders the answer *above* its own question — and hands the AI | ||
| 34 | -/// service a `[assistant, user]` history, breaking the oldest-first contract. | ||
| 35 | -static IDS: LazyLock<Mutex<Generator>> = LazyLock::new(|| Mutex::new(Generator::new())); | ||
| 36 | - | ||
| 37 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 38 | -pub struct ChatbotMessageId(RecordId); | ||
| 39 | 25 | ||
| 40 | impl ChatbotMessageId { | 26 | impl ChatbotMessageId { |
| 27 | + /// Mints in write order. Unlike a plain random UUID, whose random low bits | ||
| 28 | + /// sort arbitrarily among ids minted in the same millisecond, the | ||
| 29 | + /// process-wide context increments — so the `id` tie-break in the | ||
| 30 | + /// `ORDER BY` of | ||
| 31 | + /// [`list_for_thread`](crate::db::chatbot_message::list_for_thread) / | ||
| 32 | + /// [`list_tail`](crate::db::chatbot_message::list_tail) is the | ||
| 33 | + /// order the rows were written. The user prompt and the assistant row one | ||
| 34 | + /// POST writes back-to-back routinely share a millisecond, and a random | ||
| 35 | + /// tie-break there renders the answer *above* its own question — and | ||
| 36 | + /// hands the AI service a `[assistant, user]` history, breaking the | ||
| 37 | + /// oldest-first contract. | ||
| 41 | pub fn generate() -> Self { | 38 | pub fn generate() -> Self { |
| 42 | - let mut ids = IDS.lock().expect("chat id generator poisoned"); | 39 | + Self(next_uuid()) |
| 43 | - // The only error is overflow of the random bits *within* one | ||
| 44 | - // millisecond — 2^80 ids deep, and it clears itself as soon as the | ||
| 45 | - // clock ticks over, so retry rather than fall back to a random id | ||
| 46 | - // (which would silently reintroduce the defect). | ||
| 47 | - let ulid: Ulid = loop { | ||
| 48 | - if let Ok(ulid) = ids.generate() { | ||
| 49 | - break ulid; | ||
| 50 | - } | ||
| 51 | - }; | ||
| 52 | - Self(RecordId::new(CHAT_MESSAGE_TABLE, ulid.to_string())) | ||
| 53 | } | 40 | } |
| 54 | 41 | ||
| 42 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 43 | + /// which matches no row. | ||
| 55 | pub fn from_key(key: &str) -> Self { | 44 | pub fn from_key(key: &str) -> Self { |
| 56 | - Self(RecordId::new(CHAT_MESSAGE_TABLE, key)) | 45 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 57 | } | 46 | } |
| 58 | 47 | ||
| 59 | - pub fn record(&self) -> RecordId { | 48 | + pub fn key(&self) -> String { |
| 60 | - self.0.clone() | 49 | + self.0.to_string() |
| 61 | - } | ||
| 62 | - | ||
| 63 | - pub fn key(&self) -> &str { | ||
| 64 | - match &self.0.key { | ||
| 65 | - RecordIdKey::String(key) => key, | ||
| 66 | - _ => "", | ||
| 67 | - } | ||
| 68 | } | 50 | } |
| 69 | } | 51 | } |
| 70 | 52 | ||
| 71 | -/// Who said a turn. `untagged` + `rename_all` store it as the bare lowercase | 53 | +/// Who said a turn. Stored as the bare lowercase string the `role` column's |
| 72 | -/// string the `role` column types as, and a value the enum doesn't know comes | 54 | +/// CHECK allows; a value the enum doesn't know comes back as a decode error, |
| 73 | -/// back as a deserialization error, never a panic. | 55 | +/// never a panic. |
| 74 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | 56 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] |
| 75 | -#[surreal(untagged, rename_all = "lowercase")] | 57 | +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] |
| 76 | pub enum MessageRole { | 58 | pub enum MessageRole { |
| 77 | User, | 59 | User, |
| 78 | Assistant, | 60 | Assistant, |
| @@ -90,8 +72,8 @@ impl MessageRole { | |||
| 90 | 72 | ||
| 91 | /// Where an assistant turn is in its lifecycle. A user turn is born | 73 | /// Where an assistant turn is in its lifecycle. A user turn is born |
| 92 | /// `Complete` — nothing is ever awaited for it. | 74 | /// `Complete` — nothing is ever awaited for it. |
| 93 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | 75 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] |
| 94 | -#[surreal(untagged, rename_all = "lowercase")] | 76 | +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] |
| 95 | pub enum MessageStatus { | 77 | pub enum MessageStatus { |
| 96 | Pending, | 78 | Pending, |
| 97 | Complete, | 79 | Complete, |
| @@ -110,8 +92,9 @@ impl MessageStatus { | |||
| 110 | 92 | ||
| 111 | /// One turn's text. The hard ceiling only — the school-adjustable | 93 | /// One turn's text. The hard ceiling only — the school-adjustable |
| 112 | /// `max_chatbot_message_len` is the web layer's to enforce, below this. | 94 | /// `max_chatbot_message_len` is the web layer's to enforce, below this. |
| 113 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 95 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 114 | -pub struct ChatContent(pub(crate) String); | 96 | +#[sqlx(transparent)] |
| 97 | +pub struct ChatContent(String); | ||
| 115 | 98 | ||
| 116 | impl ChatContent { | 99 | impl ChatContent { |
| 117 | pub fn try_new(value: &str) -> Result<Self, ValidationError> { | 100 | pub fn try_new(value: &str) -> Result<Self, ValidationError> { |
| @@ -131,7 +114,7 @@ impl ChatContent { | |||
| 131 | } | 114 | } |
| 132 | } | 115 | } |
| 133 | 116 | ||
| 134 | -#[derive(Debug, Clone, SurrealValue)] | 117 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 135 | pub struct ChatbotMessage { | 118 | pub struct ChatbotMessage { |
| 136 | pub(crate) id: ChatbotMessageId, | 119 | pub(crate) id: ChatbotMessageId, |
| 137 | pub(crate) thread_id: ChatbotThreadId, | 120 | pub(crate) thread_id: ChatbotThreadId, |
| @@ -196,7 +179,7 @@ impl ChatbotMessage { | |||
| 196 | /// thread load) run on every page and must not write, a write-back would | 179 | /// thread load) run on every page and must not write, a write-back would |
| 197 | /// race the answering task that is merely slow — closing the door on a | 180 | /// race the answering task that is merely slow — closing the door on a |
| 198 | /// reply that is still coming — and the durable repair for the real cause | 181 | /// reply that is still coming — and the durable repair for the real cause |
| 199 | - /// (a dead process) already happens once, at boot. The stored row stays | 182 | + /// (a dead process) already happens once, at mint. The stored row stays |
| 200 | /// truthful; only the answer handed to the caller is projected. | 183 | /// truthful; only the answer handed to the caller is projected. |
| 201 | pub(crate) fn projected(mut self) -> Self { | 184 | pub(crate) fn projected(mut self) -> Self { |
| 202 | let stale_at = self.created_at.as_millis() + CHATBOT_PENDING_STALE_SECS * 1_000; | 185 | let stale_at = self.created_at.as_millis() + CHATBOT_PENDING_STALE_SECS * 1_000; |
| @@ -219,34 +202,16 @@ mod tests { | |||
| 219 | assert!(ChatContent::try_new(&"x".repeat(MAX_CHATBOT_MESSAGE_LEN + 1)).is_err()); | 202 | assert!(ChatContent::try_new(&"x".repeat(MAX_CHATBOT_MESSAGE_LEN + 1)).is_err()); |
| 220 | } | 203 | } |
| 221 | 204 | ||
| 222 | - #[tokio::test] | 205 | + /// The `role`/`status` columns are `TEXT` with CHECKs listing exactly |
| 223 | - async fn role_and_status_store_as_bare_strings() { | 206 | + /// these spellings — queries match on them, so the storage form may not |
| 224 | - // `TYPE string` columns: an object-wrapped enum would be rejected on | 207 | + /// drift from `as_str` (which `rename_all` mirrors). |
| 225 | - // write, and a junk string must read back as an error, not a panic. | 208 | + #[test] |
| 226 | - for role in [MessageRole::User, MessageRole::Assistant] { | 209 | + fn role_and_status_spellings_are_frozen() { |
| 227 | - let value = role.into_value(); | 210 | + assert_eq!(MessageRole::User.as_str(), "user"); |
| 228 | - assert_eq!( | 211 | + assert_eq!(MessageRole::Assistant.as_str(), "assistant"); |
| 229 | - value, | 212 | + assert_eq!(MessageStatus::Pending.as_str(), "pending"); |
| 230 | - surrealdb::types::Value::String(role.as_str().to_string()) | 213 | + assert_eq!(MessageStatus::Complete.as_str(), "complete"); |
| 231 | - ); | 214 | + assert_eq!(MessageStatus::Failed.as_str(), "failed"); |
| 232 | - assert_eq!(MessageRole::from_value(value).unwrap(), role); | ||
| 233 | - } | ||
| 234 | - for status in [ | ||
| 235 | - MessageStatus::Pending, | ||
| 236 | - MessageStatus::Complete, | ||
| 237 | - MessageStatus::Failed, | ||
| 238 | - ] { | ||
| 239 | - let value = status.into_value(); | ||
| 240 | - assert_eq!( | ||
| 241 | - value, | ||
| 242 | - surrealdb::types::Value::String(status.as_str().to_string()) | ||
| 243 | - ); | ||
| 244 | - assert_eq!(MessageStatus::from_value(value).unwrap(), status); | ||
| 245 | - } | ||
| 246 | - assert!(MessageRole::from_value(surrealdb::types::Value::String("system".into())).is_err()); | ||
| 247 | - assert!( | ||
| 248 | - MessageStatus::from_value(surrealdb::types::Value::String("queued".into())).is_err() | ||
| 249 | - ); | ||
| 250 | } | 215 | } |
| 251 | 216 | ||
| 252 | #[tokio::test] | 217 | #[tokio::test] |
| @@ -254,8 +219,8 @@ mod tests { | |||
| 254 | let aged = |secs: i64| { | 219 | let aged = |secs: i64| { |
| 255 | ChatbotMessage { | 220 | ChatbotMessage { |
| 256 | id: ChatbotMessageId::generate(), | 221 | id: ChatbotMessageId::generate(), |
| 257 | - thread_id: ChatbotThreadId::from_key("c"), | 222 | + thread_id: ChatbotThreadId::from_key("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"), |
| 258 | - user_id: UserId::from_key("u"), | 223 | + user_id: UserId::from_key("0198f1a2-3b4c-7d5e-8f90-aa2b3c4d5e6f"), |
| 259 | role: MessageRole::Assistant, | 224 | role: MessageRole::Assistant, |
| 260 | content: ChatContent::empty(), | 225 | content: ChatContent::empty(), |
| 261 | status: MessageStatus::Pending, | 226 | status: MessageStatus::Pending, |
src/domain/chatbot_thread.rsmodified+18 -22
| @@ -4,46 +4,42 @@ | |||
| 4 | //! [`crate::db::chatbot_message`], and deleting a thread cascades them; the | 4 | //! [`crate::db::chatbot_message`], and deleting a thread cascades them; the |
| 5 | //! threads' own persistence lives in [`crate::db::chatbot_thread`]. | 5 | //! threads' own persistence lives in [`crate::db::chatbot_thread`]. |
| 6 | 6 | ||
| 7 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 7 | +use crate::constant::{MAX_CHATBOT_THREAD_TITLE_LEN}; |
| 8 | - | 8 | +use crate::domain::monotonic_id::next_uuid; |
| 9 | -use crate::constant::{CHATBOT_THREAD_TABLE, MAX_CHATBOT_THREAD_TITLE_LEN}; | ||
| 10 | -use crate::domain::monotonic_id::next_ulid; | ||
| 11 | use crate::domain::timestamp::Timestamp; | 9 | use crate::domain::timestamp::Timestamp; |
| 12 | use crate::domain::user::UserId; | 10 | use crate::domain::user::UserId; |
| 13 | use crate::error::ValidationError; | 11 | use crate::error::ValidationError; |
| 14 | use crate::validate::validate_required; | 12 | use crate::validate::validate_required; |
| 15 | 13 | ||
| 16 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 14 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 17 | -pub struct ChatbotThreadId(RecordId); | 15 | +#[sqlx(transparent)] |
| 16 | +pub struct ChatbotThreadId(uuid::Uuid); | ||
| 18 | 17 | ||
| 19 | impl ChatbotThreadId { | 18 | impl ChatbotThreadId { |
| 20 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 19 | + /// Mints from the process-wide monotonic generator, not a plain random |
| 21 | - /// threads sort `updated_at DESC, id DESC` and the id breaks the tie | 20 | + /// UUID: threads sort `updated_at DESC, id DESC` and the id breaks the tie |
| 22 | /// between two threads last touched in the same millisecond, | 21 | /// between two threads last touched in the same millisecond, |
| 23 | /// and a random low half sorts arbitrarily inside one millisecond. | 22 | /// and a random low half sorts arbitrarily inside one millisecond. |
| 24 | pub fn generate() -> Self { | 23 | pub fn generate() -> Self { |
| 25 | - Self(RecordId::new(CHATBOT_THREAD_TABLE, next_ulid().to_string())) | 24 | + Self(next_uuid()) |
| 26 | } | 25 | } |
| 27 | 26 | ||
| 27 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 28 | + /// which matches no row. | ||
| 28 | pub fn from_key(key: &str) -> Self { | 29 | pub fn from_key(key: &str) -> Self { |
| 29 | - Self(RecordId::new(CHATBOT_THREAD_TABLE, key)) | 30 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 30 | - } | ||
| 31 | - | ||
| 32 | - pub fn record(&self) -> RecordId { | ||
| 33 | - self.0.clone() | ||
| 34 | } | 31 | } |
| 35 | 32 | ||
| 36 | - pub fn key(&self) -> &str { | 33 | + pub fn key(&self) -> String { |
| 37 | - match &self.0.key { | 34 | + self.0.to_string() |
| 38 | - RecordIdKey::String(key) => key, | ||
| 39 | - _ => "", | ||
| 40 | - } | ||
| 41 | } | 35 | } |
| 42 | } | 36 | } |
| 37 | + | ||
| 43 | /// A user-chosen thread name. Required-and-bounded here; "untitled" is | 38 | /// A user-chosen thread name. Required-and-bounded here; "untitled" is |
| 44 | /// `Option<ChatbotThreadTitle>` on the row. | 39 | /// `Option<ChatbotThreadTitle>` on the row. |
| 45 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 40 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 46 | -pub struct ChatbotThreadTitle(pub(crate) String); | 41 | +#[sqlx(transparent)] |
| 42 | +pub struct ChatbotThreadTitle(String); | ||
| 47 | 43 | ||
| 48 | impl ChatbotThreadTitle { | 44 | impl ChatbotThreadTitle { |
| 49 | pub fn try_new(value: &str) -> Result<Self, ValidationError> { | 45 | pub fn try_new(value: &str) -> Result<Self, ValidationError> { |
| @@ -56,7 +52,7 @@ impl ChatbotThreadTitle { | |||
| 56 | } | 52 | } |
| 57 | } | 53 | } |
| 58 | 54 | ||
| 59 | -#[derive(Debug, Clone, SurrealValue)] | 55 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 60 | pub struct ChatbotThread { | 56 | pub struct ChatbotThread { |
| 61 | pub(crate) id: ChatbotThreadId, | 57 | pub(crate) id: ChatbotThreadId, |
| 62 | pub(crate) user_id: UserId, | 58 | pub(crate) user_id: UserId, |
src/domain/class_blueprint.rsmodified+24 -30
| @@ -9,7 +9,7 @@ | |||
| 9 | //! `enrollment` rows, and an elective (seçmeli) placed by hand next to them is | 9 | //! `enrollment` rows, and an elective (seçmeli) placed by hand next to them is |
| 10 | //! still an individual enrollment nothing here can see. | 10 | //! still an individual enrollment nothing here can see. |
| 11 | //! | 11 | //! |
| 12 | -//! This module is the pure shape: the id (the grade label *is* the record | 12 | +//! This module is the pure shape: the id (the grade label *is* the primary |
| 13 | //! key, so "one blueprint per grade" holds by construction), the row, the | 13 | //! key, so "one blueprint per grade" holds by construction), the row, the |
| 14 | //! pump's report types ([`Pumped`], [`Skip`], [`SectionStatus`]) and the | 14 | //! pump's report types ([`Pumped`], [`Skip`], [`SectionStatus`]) and the |
| 15 | //! shared skip vocabulary ([`skip_reason`]). | 15 | //! shared skip vocabulary ([`skip_reason`]). |
| @@ -19,9 +19,7 @@ | |||
| 19 | //! in [`crate::service::class_blueprint`], the queries in | 19 | //! in [`crate::service::class_blueprint`], the queries in |
| 20 | //! [`crate::db::class_blueprint`]. | 20 | //! [`crate::db::class_blueprint`]. |
| 21 | 21 | ||
| 22 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 22 | +use crate::constant::{MAX_CLASS_COURSES}; |
| 23 | - | ||
| 24 | -use crate::constant::{CLASS_BLUEPRINT_TABLE, MAX_CLASS_COURSES}; | ||
| 25 | use crate::db::class_pump::{Attached, Axis}; | 23 | use crate::db::class_pump::{Attached, Axis}; |
| 26 | use crate::domain::class_course::ClassCourse; | 24 | use crate::domain::class_course::ClassCourse; |
| 27 | use crate::domain::class_group::{ClassGrade, ClassGroupId}; | 25 | use crate::domain::class_group::{ClassGrade, ClassGroupId}; |
| @@ -29,37 +27,31 @@ use crate::domain::course::CourseId; | |||
| 29 | use crate::domain::user::UserId; | 27 | use crate::domain::user::UserId; |
| 30 | use crate::error::{AppError, ValidationError}; | 28 | use crate::error::{AppError, ValidationError}; |
| 31 | 29 | ||
| 32 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 30 | +/// A grade label as the table's `TEXT` primary key — one blueprint per grade |
| 33 | -pub struct ClassBlueprintId(RecordId); | 31 | +/// by construction, like the settings singleton's `'school'` row: the key is |
| 32 | +/// a name, not a minted entity id. | ||
| 33 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] | ||
| 34 | +#[sqlx(transparent)] | ||
| 35 | +pub struct ClassBlueprintId(String); | ||
| 34 | 36 | ||
| 35 | impl ClassBlueprintId { | 37 | impl ClassBlueprintId { |
| 36 | - /// The record one grade label always maps to. The label is the key, so | 38 | + /// The key one grade label always maps to. |
| 37 | - /// "one blueprint per grade" holds by construction rather than by a | ||
| 38 | - /// find-then-insert that two managers can race — the shape | ||
| 39 | - /// [`crate::domain::menu::MenuId::for_slot`] uses. | ||
| 40 | pub fn for_grade(grade: &ClassGrade) -> Self { | 39 | pub fn for_grade(grade: &ClassGrade) -> Self { |
| 41 | - Self(RecordId::new(CLASS_BLUEPRINT_TABLE, grade.as_str())) | 40 | + Self(grade.as_str().to_string()) |
| 42 | } | 41 | } |
| 43 | 42 | ||
| 44 | pub fn from_key(key: &str) -> Self { | 43 | pub fn from_key(key: &str) -> Self { |
| 45 | - Self(RecordId::new(CLASS_BLUEPRINT_TABLE, key)) | 44 | + Self(key.to_string()) |
| 46 | - } | ||
| 47 | - | ||
| 48 | - pub fn record(&self) -> RecordId { | ||
| 49 | - self.0.clone() | ||
| 50 | } | 45 | } |
| 51 | 46 | ||
| 52 | pub fn key(&self) -> &str { | 47 | pub fn key(&self) -> &str { |
| 53 | - match &self.0.key { | 48 | + &self.0 |
| 54 | - RecordIdKey::String(key) => key, | ||
| 55 | - _ => "", | ||
| 56 | - } | ||
| 57 | } | 49 | } |
| 58 | } | 50 | } |
| 59 | 51 | ||
| 60 | /// One grade's template. `grade` is stored beside the key it *is*, so a read | 52 | /// One grade's template. `grade` is stored beside the key it *is*, so a read |
| 61 | /// never has to parse a record id back into a domain value. | 53 | /// never has to parse a record id back into a domain value. |
| 62 | -#[derive(Debug, Clone, SurrealValue)] | 54 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 63 | pub struct ClassBlueprint { | 55 | pub struct ClassBlueprint { |
| 64 | pub(crate) id: ClassBlueprintId, | 56 | pub(crate) id: ClassBlueprintId, |
| 65 | pub(crate) grade: ClassGrade, | 57 | pub(crate) grade: ClassGrade, |
| @@ -147,13 +139,13 @@ impl ClassBlueprint { | |||
| 147 | } | 139 | } |
| 148 | 140 | ||
| 149 | /// The grade a blueprint may be keyed on. Non-empty, because the label is | 141 | /// The grade a blueprint may be keyed on. Non-empty, because the label is |
| 150 | - /// the record id and there is no blueprint for "no grade"; and free of the | 142 | + /// the primary key and there is no blueprint for "no grade"; and free of |
| 151 | - /// characters that would make that id unaddressable as a URL path segment, | 143 | + /// the characters that would make that key unaddressable as a URL path |
| 152 | - /// the second gate [`crate::domain::menu::MenuSlot`] carries for the same | 144 | + /// segment, the second gate [`crate::domain::menu::MenuSlot`] carries for |
| 153 | - /// reason. Grades were never validated for this, so a *class* may already | 145 | + /// the same reason. Grades were never validated for this, so a *class* may |
| 154 | - /// carry a label refused here — it simply cannot have a blueprint until it | 146 | + /// already carry a label refused here — it simply cannot have a blueprint |
| 155 | - /// is renamed, which is a 400 the caller can read rather than a route | 147 | + /// until it is renamed, which is a 400 the caller can read rather than a |
| 156 | - /// nobody can reach. | 148 | + /// route nobody can reach. |
| 157 | pub fn grade_key(value: &str) -> Result<ClassGrade, AppError> { | 149 | pub fn grade_key(value: &str) -> Result<ClassGrade, AppError> { |
| 158 | if value.is_empty() { | 150 | if value.is_empty() { |
| 159 | return Err(AppError::Validation(ValidationError::Empty("grade"))); | 151 | return Err(AppError::Validation(ValidationError::Empty("grade"))); |
| @@ -215,12 +207,14 @@ mod tests { | |||
| 215 | /// spend two of the ceiling's places on one course. | 207 | /// spend two of the ceiling's places on one course. |
| 216 | #[test] | 208 | #[test] |
| 217 | fn a_course_list_is_deduplicated_and_bounded() { | 209 | fn a_course_list_is_deduplicated_and_bounded() { |
| 218 | - let algebra = CourseId::from_key("algebra"); | 210 | + let algebra = CourseId::from_key("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"); |
| 219 | let held = ClassBlueprint::course_list(vec![algebra.clone(), algebra.clone()]).unwrap(); | 211 | let held = ClassBlueprint::course_list(vec![algebra.clone(), algebra.clone()]).unwrap(); |
| 220 | assert_eq!(held, vec![algebra]); | 212 | assert_eq!(held, vec![algebra]); |
| 221 | 213 | ||
| 214 | + // One over the ceiling is refused; each key must be a distinct | ||
| 215 | + // *parseable* UUID, or the parser would collapse them all to nil. | ||
| 222 | let too_many: Vec<CourseId> = (0..=MAX_CLASS_COURSES) | 216 | let too_many: Vec<CourseId> = (0..=MAX_CLASS_COURSES) |
| 223 | - .map(|n| CourseId::from_key(&n.to_string())) | 217 | + .map(|n| CourseId::from_key(&format!("0198f1a2-3b4c-7d5e-8f90-{n:012x}"))) |
| 224 | .collect(); | 218 | .collect(); |
| 225 | assert!(ClassBlueprint::course_list(too_many).is_err()); | 219 | assert!(ClassBlueprint::course_list(too_many).is_err()); |
| 226 | } | 220 | } |
src/domain/class_course.rsmodified+25 -27
| @@ -7,41 +7,39 @@ | |||
| 7 | //! [`crate::db::class_course`] — this file is the row shape and its | 7 | //! [`crate::db::class_course`] — this file is the row shape and its |
| 8 | //! composite id. | 8 | //! composite id. |
| 9 | 9 | ||
| 10 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 11 | - | ||
| 12 | -use crate::constant::CLASS_COURSE_TABLE; | ||
| 13 | -use crate::db::class_pump::link_id; | ||
| 14 | use crate::domain::class_blueprint::ClassBlueprintId; | 10 | use crate::domain::class_blueprint::ClassBlueprintId; |
| 15 | use crate::domain::class_group::ClassGroupId; | 11 | use crate::domain::class_group::ClassGroupId; |
| 16 | use crate::domain::course::CourseId; | 12 | use crate::domain::course::CourseId; |
| 17 | use crate::domain::timestamp::Timestamp; | 13 | use crate::domain::timestamp::Timestamp; |
| 18 | use crate::domain::user::UserId; | 14 | use crate::domain::user::UserId; |
| 19 | 15 | ||
| 20 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 16 | +/// The identity of one (class, course) pair. Not a row column: the table's |
| 21 | -pub struct ClassCourseId(RecordId); | 17 | +/// primary key *is* the pair, and this struct's job is the underscore-joined |
| 18 | +/// wire form at the HTTP edge. | ||
| 19 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 20 | +pub struct ClassCourseId { | ||
| 21 | + pub(crate) class: ClassGroupId, | ||
| 22 | + pub(crate) course: CourseId, | ||
| 23 | +} | ||
| 22 | 24 | ||
| 23 | impl ClassCourseId { | 25 | impl ClassCourseId { |
| 24 | - /// The record one (class, course) pair always maps to. | 26 | + /// The one id a (class, course) pair can have. |
| 25 | pub fn composite(class: &ClassGroupId, course: &CourseId) -> Self { | 27 | pub fn composite(class: &ClassGroupId, course: &CourseId) -> Self { |
| 26 | - Self(link_id(CLASS_COURSE_TABLE, class, course.key())) | 28 | + Self { |
| 27 | - } | 29 | + class: class.clone(), |
| 28 | - | 30 | + course: course.clone(), |
| 29 | - pub fn record(&self) -> RecordId { | 31 | + } |
| 30 | - self.0.clone() | ||
| 31 | } | 32 | } |
| 32 | 33 | ||
| 33 | - pub fn key(&self) -> &str { | 34 | + /// The underscore-joined wire form (`{class}_{course}`). |
| 34 | - match &self.0.key { | 35 | + pub fn key(&self) -> String { |
| 35 | - RecordIdKey::String(key) => key, | 36 | + format!("{}_{}", self.class.key(), self.course.key()) |
| 36 | - _ => "", | ||
| 37 | - } | ||
| 38 | } | 37 | } |
| 39 | } | 38 | } |
| 40 | 39 | ||
| 41 | /// One course a class is attached to. `attached_by` is who attached it. | 40 | /// One course a class is attached to. `attached_by` is who attached it. |
| 42 | -#[derive(Debug, Clone, SurrealValue)] | 41 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 43 | pub struct ClassCourse { | 42 | pub struct ClassCourse { |
| 44 | - pub(crate) id: ClassCourseId, | ||
| 45 | pub(crate) class: ClassGroupId, | 43 | pub(crate) class: ClassGroupId, |
| 46 | pub(crate) course: CourseId, | 44 | pub(crate) course: CourseId, |
| 47 | pub(crate) attached_by: UserId, | 45 | pub(crate) attached_by: UserId, |
| @@ -49,19 +47,19 @@ pub struct ClassCourse { | |||
| 49 | /// attached the course to this class directly — the mirror of | 47 | /// attached the course to this class directly — the mirror of |
| 50 | /// [`crate::domain::enrollment`]'s `source`, and read the same way: only a | 48 | /// [`crate::domain::enrollment`]'s `source`, and read the same way: only a |
| 51 | /// row carrying the key is a blueprint's to take back, so a hand-attached | 49 | /// row carrying the key is a blueprint's to take back, so a hand-attached |
| 52 | - /// course survives every blueprint sweep. Rows written before the column | 50 | + /// course survives every blueprint sweep. |
| 53 | - /// carry no key at all, which is exactly "hand-attached". | ||
| 54 | pub(crate) source: Option<ClassBlueprintId>, | 51 | pub(crate) source: Option<ClassBlueprintId>, |
| 55 | - /// When it was attached, and the *only* thing "newest first" can mean here: | 52 | + /// When it was attached, and the *only* thing "newest first" can mean |
| 56 | - /// the row's id is the (class, course) pair, so ordering by it sorts the | 53 | + /// here: the row's primary key is the (class, course) pair, so ordering |
| 57 | - /// list by the course's own ULID. Optional because rows written before this | 54 | + /// falls to this stamp (or the attached course's id). Optional because |
| 58 | - /// column carry no stamp — see the migration note. | 55 | + /// rows written before this column carry no stamp. |
| 59 | pub(crate) attached_at: Option<Timestamp>, | 56 | pub(crate) attached_at: Option<Timestamp>, |
| 60 | } | 57 | } |
| 61 | 58 | ||
| 62 | impl ClassCourse { | 59 | impl ClassCourse { |
| 63 | - pub fn get_id(&self) -> &ClassCourseId { | 60 | + /// The row's identity, built back from its primary-key columns. |
| 64 | - &self.id | 61 | + pub fn get_id(&self) -> ClassCourseId { |
| 62 | + ClassCourseId::composite(&self.class, &self.course) | ||
| 65 | } | 63 | } |
| 66 | 64 | ||
| 67 | pub fn get_class(&self) -> &ClassGroupId { | 65 | pub fn get_class(&self) -> &ClassGroupId { |
src/domain/class_group.rsmodified+17 -22
| @@ -14,40 +14,35 @@ | |||
| 14 | //! the route-facing wrappers in [`crate::service::class_group`] — this file is | 14 | //! the route-facing wrappers in [`crate::service::class_group`] — this file is |
| 15 | //! the row shape, its newtypes and getters. | 15 | //! the row shape, its newtypes and getters. |
| 16 | 16 | ||
| 17 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 17 | +use crate::constant::{MAX_CLASS_GRADE_LEN, MAX_CLASS_NAME_LEN}; |
| 18 | - | 18 | +use crate::domain::monotonic_id::next_uuid; |
| 19 | -use crate::constant::{CLASS_GROUP_TABLE, MAX_CLASS_GRADE_LEN, MAX_CLASS_NAME_LEN}; | ||
| 20 | -use crate::domain::monotonic_id::next_ulid; | ||
| 21 | use crate::domain::term::TermId; | 19 | use crate::domain::term::TermId; |
| 22 | use crate::domain::user::UserId; | 20 | use crate::domain::user::UserId; |
| 23 | use crate::error::ValidationError; | 21 | use crate::error::ValidationError; |
| 24 | use crate::validate::{validate_optional, validate_required}; | 22 | use crate::validate::{validate_optional, validate_required}; |
| 25 | 23 | ||
| 26 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 24 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 27 | -pub struct ClassGroupId(RecordId); | 25 | +#[sqlx(transparent)] |
| 26 | +pub struct ClassGroupId(uuid::Uuid); | ||
| 28 | 27 | ||
| 29 | impl ClassGroupId { | 28 | impl ClassGroupId { |
| 30 | pub fn generate() -> Self { | 29 | pub fn generate() -> Self { |
| 31 | - Self(RecordId::new(CLASS_GROUP_TABLE, next_ulid().to_string())) | 30 | + Self(next_uuid()) |
| 32 | } | 31 | } |
| 33 | 32 | ||
| 33 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 34 | + /// which matches no row. | ||
| 34 | pub fn from_key(key: &str) -> Self { | 35 | pub fn from_key(key: &str) -> Self { |
| 35 | - Self(RecordId::new(CLASS_GROUP_TABLE, key)) | 36 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 36 | - } | ||
| 37 | - | ||
| 38 | - pub fn record(&self) -> RecordId { | ||
| 39 | - self.0.clone() | ||
| 40 | } | 37 | } |
| 41 | 38 | ||
| 42 | - pub fn key(&self) -> &str { | 39 | + pub fn key(&self) -> String { |
| 43 | - match &self.0.key { | 40 | + self.0.to_string() |
| 44 | - RecordIdKey::String(key) => key, | ||
| 45 | - _ => "", | ||
| 46 | - } | ||
| 47 | } | 41 | } |
| 48 | } | 42 | } |
| 49 | 43 | ||
| 50 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 44 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 45 | +#[sqlx(transparent)] | ||
| 51 | pub struct ClassName(String); | 46 | pub struct ClassName(String); |
| 52 | 47 | ||
| 53 | impl ClassName { | 48 | impl ClassName { |
| @@ -64,7 +59,8 @@ impl ClassName { | |||
| 64 | /// The school's own label for the year a class sits in ("9", "10-A", | 59 | /// The school's own label for the year a class sits in ("9", "10-A", |
| 65 | /// "anaokulu"). Free text on purpose — no school's grade ladder is the next | 60 | /// "anaokulu"). Free text on purpose — no school's grade ladder is the next |
| 66 | /// one's — and optional: a club-shaped class has no grade at all. | 61 | /// one's — and optional: a club-shaped class has no grade at all. |
| 67 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 62 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 63 | +#[sqlx(transparent)] | ||
| 68 | pub struct ClassGrade(String); | 64 | pub struct ClassGrade(String); |
| 69 | 65 | ||
| 70 | impl ClassGrade { | 66 | impl ClassGrade { |
| @@ -85,9 +81,8 @@ impl ClassGrade { | |||
| 85 | /// `teacher` is the section's homeroom teacher (sınıf öğretmeni): optional, not | 81 | /// `teacher` is the section's homeroom teacher (sınıf öğretmeni): optional, not |
| 86 | /// refcounted, and merely a label pointing at a teacher-or-higher account — the | 82 | /// refcounted, and merely a label pointing at a teacher-or-higher account — the |
| 87 | /// web layer holds that bar, and a demotion sweeps the column | 83 | /// web layer holds that bar, and a demotion sweeps the column |
| 88 | -/// ([`crate::db::class_group::unassign_everywhere`]). Rows written before the | 84 | +/// ([`crate::db::class_group::unassign_everywhere`]). |
| 89 | -/// column exists carry no key at all, which reads back as `None`. | 85 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 90 | -#[derive(Debug, Clone, SurrealValue)] | ||
| 91 | pub struct ClassGroup { | 86 | pub struct ClassGroup { |
| 92 | pub(crate) id: ClassGroupId, | 87 | pub(crate) id: ClassGroupId, |
| 93 | pub(crate) creator: UserId, | 88 | pub(crate) creator: UserId, |
src/domain/class_member.rsmodified+24 -25
| @@ -7,52 +7,51 @@ | |||
| 7 | //! [`crate::db::class_member`] — this file is the row shape and its | 7 | //! [`crate::db::class_member`] — this file is the row shape and its |
| 8 | //! composite id. | 8 | //! composite id. |
| 9 | 9 | ||
| 10 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 11 | - | ||
| 12 | -use crate::constant::CLASS_MEMBER_TABLE; | ||
| 13 | -use crate::db::class_pump::link_id; | ||
| 14 | use crate::domain::class_group::ClassGroupId; | 10 | use crate::domain::class_group::ClassGroupId; |
| 15 | use crate::domain::timestamp::Timestamp; | 11 | use crate::domain::timestamp::Timestamp; |
| 16 | use crate::domain::user::UserId; | 12 | use crate::domain::user::UserId; |
| 17 | 13 | ||
| 18 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 14 | +/// The identity of one (class, user) pair. Not a row column: the table's |
| 19 | -pub struct ClassMemberId(RecordId); | 15 | +/// primary key *is* the pair, and this struct's job is the underscore-joined |
| 16 | +/// wire form at the HTTP edge. | ||
| 17 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 18 | +pub struct ClassMemberId { | ||
| 19 | + pub(crate) class: ClassGroupId, | ||
| 20 | + pub(crate) user: UserId, | ||
| 21 | +} | ||
| 20 | 22 | ||
| 21 | impl ClassMemberId { | 23 | impl ClassMemberId { |
| 22 | - /// The record one (class, user) pair always maps to. | 24 | + /// The one id a (class, user) pair can have. |
| 23 | pub fn composite(class: &ClassGroupId, user: &UserId) -> Self { | 25 | pub fn composite(class: &ClassGroupId, user: &UserId) -> Self { |
| 24 | - Self(link_id(CLASS_MEMBER_TABLE, class, user.key())) | 26 | + Self { |
| 25 | - } | 27 | + class: class.clone(), |
| 26 | - | 28 | + user: user.clone(), |
| 27 | - pub fn record(&self) -> RecordId { | 29 | + } |
| 28 | - self.0.clone() | ||
| 29 | } | 30 | } |
| 30 | 31 | ||
| 31 | - pub fn key(&self) -> &str { | 32 | + /// The underscore-joined wire form (`{class}_{user}`). |
| 32 | - match &self.0.key { | 33 | + pub fn key(&self) -> String { |
| 33 | - RecordIdKey::String(key) => key, | 34 | + format!("{}_{}", self.class.key(), self.user.key()) |
| 34 | - _ => "", | ||
| 35 | - } | ||
| 36 | } | 35 | } |
| 37 | } | 36 | } |
| 38 | 37 | ||
| 39 | /// One student in one class. `added_by` is who put them there. | 38 | /// One student in one class. `added_by` is who put them there. |
| 40 | -#[derive(Debug, Clone, SurrealValue)] | 39 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 41 | pub struct ClassMember { | 40 | pub struct ClassMember { |
| 42 | - pub(crate) id: ClassMemberId, | ||
| 43 | pub(crate) class: ClassGroupId, | 41 | pub(crate) class: ClassGroupId, |
| 44 | pub(crate) user: UserId, | 42 | pub(crate) user: UserId, |
| 45 | pub(crate) added_by: UserId, | 43 | pub(crate) added_by: UserId, |
| 46 | - /// When they were added, and the *only* thing "newest first" can mean here: | 44 | + /// When they were added, and the *only* thing "newest first" can mean |
| 47 | - /// the row's id is the (class, user) pair, so ordering by it sorts the | 45 | + /// here: the row's primary key is the (class, user) pair, so ordering |
| 48 | - /// roster by the student's account ULID. Optional because rows written | 46 | + /// falls to this stamp. Optional because rows written before this column |
| 49 | - /// before this column carry no stamp — see the migration note. | 47 | + /// carry no stamp. |
| 50 | pub(crate) added_at: Option<Timestamp>, | 48 | pub(crate) added_at: Option<Timestamp>, |
| 51 | } | 49 | } |
| 52 | 50 | ||
| 53 | impl ClassMember { | 51 | impl ClassMember { |
| 54 | - pub fn get_id(&self) -> &ClassMemberId { | 52 | + /// The row's identity, built back from its primary-key columns. |
| 55 | - &self.id | 53 | + pub fn get_id(&self) -> ClassMemberId { |
| 54 | + ClassMemberId::composite(&self.class, &self.user) | ||
| 56 | } | 55 | } |
| 57 | 56 | ||
| 58 | pub fn get_class(&self) -> &ClassGroupId { | 57 | pub fn get_class(&self) -> &ClassGroupId { |
src/domain/course.rsmodified+23 -82
| @@ -1,40 +1,36 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | +use crate::constant::{MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN}; |
| 2 | - | 2 | +use crate::domain::monotonic_id::next_uuid; |
| 3 | -use crate::constant::{COURSE_TABLE, MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN}; | ||
| 4 | -use crate::domain::monotonic_id::next_ulid; | ||
| 5 | use crate::domain::term::TermId; | 3 | use crate::domain::term::TermId; |
| 6 | use crate::domain::user::UserId; | 4 | use crate::domain::user::UserId; |
| 7 | use crate::error::ValidationError; | 5 | use crate::error::ValidationError; |
| 8 | use crate::validate::{validate_course_kind, validate_optional, validate_required}; | 6 | use crate::validate::{validate_course_kind, validate_optional, validate_required}; |
| 9 | 7 | ||
| 10 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 8 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 11 | -pub struct CourseId(RecordId); | 9 | +#[sqlx(transparent)] |
| 10 | +pub struct CourseId(uuid::Uuid); | ||
| 12 | 11 | ||
| 13 | impl CourseId { | 12 | impl CourseId { |
| 14 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 13 | + /// Minted from the process-wide monotonic generator, not a plain random |
| 15 | - /// courses list `id DESC` (newest first, [`crate::db::course::list_all`]), | 14 | + /// UUID: courses list `id DESC` (newest first, |
| 15 | + /// [`crate::db::course::list_all`]), | ||
| 16 | /// and a random low half scrambles rows minted in the same millisecond. | 16 | /// and a random low half scrambles rows minted in the same millisecond. |
| 17 | pub fn generate() -> Self { | 17 | pub fn generate() -> Self { |
| 18 | - Self(RecordId::new(COURSE_TABLE, next_ulid().to_string())) | 18 | + Self(next_uuid()) |
| 19 | } | 19 | } |
| 20 | 20 | ||
| 21 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 22 | + /// which matches no row. | ||
| 21 | pub fn from_key(key: &str) -> Self { | 23 | pub fn from_key(key: &str) -> Self { |
| 22 | - Self(RecordId::new(COURSE_TABLE, key)) | 24 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 23 | - } | ||
| 24 | - | ||
| 25 | - pub fn record(&self) -> RecordId { | ||
| 26 | - self.0.clone() | ||
| 27 | } | 25 | } |
| 28 | 26 | ||
| 29 | - pub fn key(&self) -> &str { | 27 | + pub fn key(&self) -> String { |
| 30 | - match &self.0.key { | 28 | + self.0.to_string() |
| 31 | - RecordIdKey::String(key) => key, | ||
| 32 | - _ => "", | ||
| 33 | - } | ||
| 34 | } | 29 | } |
| 35 | } | 30 | } |
| 36 | 31 | ||
| 37 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 32 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 33 | +#[sqlx(transparent)] | ||
| 38 | pub struct CourseTitle(String); | 34 | pub struct CourseTitle(String); |
| 39 | 35 | ||
| 40 | impl CourseTitle { | 36 | impl CourseTitle { |
| @@ -48,7 +44,8 @@ impl CourseTitle { | |||
| 48 | } | 44 | } |
| 49 | } | 45 | } |
| 50 | 46 | ||
| 51 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 47 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 48 | +#[sqlx(transparent)] | ||
| 52 | pub struct CourseDescription(String); | 49 | pub struct CourseDescription(String); |
| 53 | 50 | ||
| 54 | impl CourseDescription { | 51 | impl CourseDescription { |
| @@ -65,7 +62,8 @@ impl CourseDescription { | |||
| 65 | /// A validated course kind: `course` (a regular class — ders), `study` (a | 62 | /// A validated course kind: `course` (a regular class — ders), `study` (a |
| 66 | /// supervised study session — etüt), or `club` (a student club — kulüp). | 63 | /// supervised study session — etüt), or `club` (a student club — kulüp). |
| 67 | /// Purely a label; all kinds behave identically. | 64 | /// Purely a label; all kinds behave identically. |
| 68 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 65 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 66 | +#[sqlx(transparent)] | ||
| 69 | pub struct CourseKind(String); | 67 | pub struct CourseKind(String); |
| 70 | 68 | ||
| 71 | impl CourseKind { | 69 | impl CourseKind { |
| @@ -88,21 +86,19 @@ impl CourseKind { | |||
| 88 | /// course, each exam weighted by its kind's settings weight. May belong to an | 86 | /// course, each exam weighted by its kind's settings weight. May belong to an |
| 89 | /// academic term. Comes in three behaviorally identical kinds: `course`, | 87 | /// academic term. Comes in three behaviorally identical kinds: `course`, |
| 90 | /// `study` (etüt), and `club` (kulüp). An optional `capacity` caps the roster | 88 | /// `study` (etüt), and `club` (kulüp). An optional `capacity` caps the roster |
| 91 | -/// at enroll time (`None` = unlimited); rows written before the field existed | 89 | +/// at enroll time (`NULL` = unlimited). |
| 92 | -/// decode as uncapped. | ||
| 93 | /// | 90 | /// |
| 94 | /// `creator` owns the course for good — only they (or a manager+) may delete | 91 | /// `creator` owns the course for good — only they (or a manager+) may delete |
| 95 | /// it. `teachers` are the staff a manager assigned to run it: full management | 92 | /// it. `teachers` are the staff a manager assigned to run it: full management |
| 96 | /// rights inside the course, no power to delete it or change the assignment | 93 | /// rights inside the course, no power to delete it or change the assignment |
| 97 | -/// list. Rows written before the field existed decode with nobody assigned. | 94 | +/// list. |
| 98 | /// | 95 | /// |
| 99 | /// Fields are crate-visible: [`crate::db::course`] mints the rows on create | 96 | /// Fields are crate-visible: [`crate::db::course`] mints the rows on create |
| 100 | /// and reads the id when updating and cascading a delete. | 97 | /// and reads the id when updating and cascading a delete. |
| 101 | -#[derive(Debug, Clone, SurrealValue)] | 98 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 102 | pub struct Course { | 99 | pub struct Course { |
| 103 | pub(crate) id: CourseId, | 100 | pub(crate) id: CourseId, |
| 104 | pub(crate) creator: UserId, | 101 | pub(crate) creator: UserId, |
| 105 | - #[surreal(default)] | ||
| 106 | pub(crate) teachers: Vec<UserId>, | 102 | pub(crate) teachers: Vec<UserId>, |
| 107 | pub(crate) title: CourseTitle, | 103 | pub(crate) title: CourseTitle, |
| 108 | pub(crate) description: CourseDescription, | 104 | pub(crate) description: CourseDescription, |
| @@ -181,59 +177,4 @@ mod tests { | |||
| 181 | assert!(CourseKind::try_new("etut").is_err()); | 177 | assert!(CourseKind::try_new("etut").is_err()); |
| 182 | assert_eq!(CourseKind::course().as_str(), "course"); | 178 | assert_eq!(CourseKind::course().as_str(), "course"); |
| 183 | } | 179 | } |
| 184 | - | ||
| 185 | - /// The database strips `NONE`-valued optional columns, and every course | ||
| 186 | - /// row written before the capacity field existed has no `capacity` key at | ||
| 187 | - /// all — both must decode as an uncapped course. | ||
| 188 | - #[tokio::test] | ||
| 189 | - async fn course_decodes_without_capacity_key() { | ||
| 190 | - use surrealdb::types::Value; | ||
| 191 | - | ||
| 192 | - let course = Course { | ||
| 193 | - id: CourseId::generate(), | ||
| 194 | - creator: UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"), | ||
| 195 | - teachers: Vec::new(), | ||
| 196 | - title: CourseTitle::try_new("chess").unwrap(), | ||
| 197 | - description: CourseDescription::try_new("").unwrap(), | ||
| 198 | - kind: CourseKind::try_new("club").unwrap(), | ||
| 199 | - term: None, | ||
| 200 | - capacity: Some(12), | ||
| 201 | - }; | ||
| 202 | - let Value::Object(mut object) = course.into_value() else { | ||
| 203 | - panic!("course must encode as an object"); | ||
| 204 | - }; | ||
| 205 | - object.remove("capacity"); | ||
| 206 | - let decoded = Course::from_value(Value::Object(object)).unwrap(); | ||
| 207 | - assert_eq!(decoded.get_capacity(), None); | ||
| 208 | - } | ||
| 209 | - | ||
| 210 | - /// Every course row written before teacher assignment existed has no | ||
| 211 | - /// `teachers` key. The boot backfill fills them in, but a row read before | ||
| 212 | - /// that lands must still decode — as a course nobody was assigned to, | ||
| 213 | - /// never as a decode error that 500s the catalog. | ||
| 214 | - #[tokio::test] | ||
| 215 | - async fn course_decodes_without_teachers_key() { | ||
| 216 | - use surrealdb::types::Value; | ||
| 217 | - | ||
| 218 | - let assigned = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U"); | ||
| 219 | - let course = Course { | ||
| 220 | - id: CourseId::generate(), | ||
| 221 | - creator: UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"), | ||
| 222 | - teachers: vec![assigned.clone()], | ||
| 223 | - title: CourseTitle::try_new("chess").unwrap(), | ||
| 224 | - description: CourseDescription::try_new("").unwrap(), | ||
| 225 | - kind: CourseKind::try_new("club").unwrap(), | ||
| 226 | - term: None, | ||
| 227 | - capacity: None, | ||
| 228 | - }; | ||
| 229 | - assert!(course.is_assigned(&assigned)); | ||
| 230 | - | ||
| 231 | - let Value::Object(mut object) = course.into_value() else { | ||
| 232 | - panic!("course must encode as an object"); | ||
| 233 | - }; | ||
| 234 | - object.remove("teachers"); | ||
| 235 | - let decoded = Course::from_value(Value::Object(object)).unwrap(); | ||
| 236 | - assert!(decoded.get_teachers().is_empty()); | ||
| 237 | - assert!(!decoded.is_assigned(&assigned)); | ||
| 238 | - } | ||
| 239 | } | 180 | } |
src/domain/course_note.rsmodified+18 -22
| @@ -1,41 +1,36 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | +use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN}; |
| 2 | - | ||
| 3 | -use crate::constant::{COURSE_NOTE_TABLE, MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN}; | ||
| 4 | use crate::domain::course::CourseId; | 2 | use crate::domain::course::CourseId; |
| 5 | -use crate::domain::monotonic_id::next_ulid; | 3 | +use crate::domain::monotonic_id::next_uuid; |
| 6 | use crate::domain::user::UserId; | 4 | use crate::domain::user::UserId; |
| 7 | use crate::error::ValidationError; | 5 | use crate::error::ValidationError; |
| 8 | use crate::validate::{validate_optional, validate_required}; | 6 | use crate::validate::{validate_optional, validate_required}; |
| 9 | 7 | ||
| 10 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 8 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 11 | -pub struct CourseNoteId(RecordId); | 9 | +#[sqlx(transparent)] |
| 10 | +pub struct CourseNoteId(uuid::Uuid); | ||
| 12 | 11 | ||
| 13 | impl CourseNoteId { | 12 | impl CourseNoteId { |
| 14 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 13 | + /// Minted from the process-wide monotonic generator, not a plain random |
| 15 | - /// a course's notes list `id DESC` (newest first, | 14 | + /// UUID: a course's notes list `id DESC` (newest first, |
| 16 | /// [`crate::db::course_note::list_for_course`]), and a random low half | 15 | /// [`crate::db::course_note::list_for_course`]), and a random low half |
| 17 | /// scrambles rows minted in the same millisecond. | 16 | /// scrambles rows minted in the same millisecond. |
| 18 | pub fn generate() -> Self { | 17 | pub fn generate() -> Self { |
| 19 | - Self(RecordId::new(COURSE_NOTE_TABLE, next_ulid().to_string())) | 18 | + Self(next_uuid()) |
| 20 | } | 19 | } |
| 21 | 20 | ||
| 21 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 22 | + /// which matches no row. | ||
| 22 | pub fn from_key(key: &str) -> Self { | 23 | pub fn from_key(key: &str) -> Self { |
| 23 | - Self(RecordId::new(COURSE_NOTE_TABLE, key)) | 24 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 24 | - } | ||
| 25 | - | ||
| 26 | - pub fn record(&self) -> RecordId { | ||
| 27 | - self.0.clone() | ||
| 28 | } | 25 | } |
| 29 | 26 | ||
| 30 | - pub fn key(&self) -> &str { | 27 | + pub fn key(&self) -> String { |
| 31 | - match &self.0.key { | 28 | + self.0.to_string() |
| 32 | - RecordIdKey::String(key) => key, | ||
| 33 | - _ => "", | ||
| 34 | - } | ||
| 35 | } | 29 | } |
| 36 | } | 30 | } |
| 37 | 31 | ||
| 38 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 32 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 33 | +#[sqlx(transparent)] | ||
| 39 | pub struct CourseNoteTitle(String); | 34 | pub struct CourseNoteTitle(String); |
| 40 | 35 | ||
| 41 | impl CourseNoteTitle { | 36 | impl CourseNoteTitle { |
| @@ -49,7 +44,8 @@ impl CourseNoteTitle { | |||
| 49 | } | 44 | } |
| 50 | } | 45 | } |
| 51 | 46 | ||
| 52 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 47 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 48 | +#[sqlx(transparent)] | ||
| 53 | pub struct CourseNoteContent(String); | 49 | pub struct CourseNoteContent(String); |
| 54 | 50 | ||
| 55 | impl CourseNoteContent { | 51 | impl CourseNoteContent { |
| @@ -63,7 +59,7 @@ impl CourseNoteContent { | |||
| 63 | } | 59 | } |
| 64 | } | 60 | } |
| 65 | 61 | ||
| 66 | -#[derive(Debug, Clone, SurrealValue)] | 62 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 67 | pub struct CourseNote { | 63 | pub struct CourseNote { |
| 68 | pub(crate) id: CourseNoteId, | 64 | pub(crate) id: CourseNoteId, |
| 69 | pub(crate) course: CourseId, | 65 | pub(crate) course: CourseId, |
src/domain/course_note_file.rsmodified+18 -27
| @@ -1,53 +1,44 @@ | |||
| 1 | //! A file attached to a course note. The row carries metadata only (original | 1 | //! A file attached to a course note. The row carries metadata only (original |
| 2 | //! filename, MIME type, byte size); the bytes themselves live on disk under | 2 | //! filename, MIME type, byte size); the bytes themselves live on disk under |
| 3 | -//! [`crate::config::Config::files_path`], in a file named by this row's key — | 3 | +//! [`crate::config::Config::files_path`], in a file named by this row's `file` |
| 4 | -//! a server-generated ULID, so no user input ever shapes a disk path. The web | 4 | +//! field — a server-generated UUID, so no user input ever shapes a disk path. |
| 5 | -//! layer owns the blob I/O and its ordering (blob before row on upload, row | 5 | +//! The web layer owns the blob I/O and its ordering (blob before row on |
| 6 | -//! before blob on delete); persistence lives in | 6 | +//! upload, row before blob on delete); persistence lives in |
| 7 | //! [`crate::db::course_note_file`]. `FileName` and `FileContentType` are | 7 | //! [`crate::db::course_note_file`]. `FileName` and `FileContentType` are |
| 8 | //! shared with [`crate::domain::note_file`] — same validation, no reason to | 8 | //! shared with [`crate::domain::note_file`] — same validation, no reason to |
| 9 | //! duplicate it. | 9 | //! duplicate it. |
| 10 | 10 | ||
| 11 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 12 | - | ||
| 13 | pub use crate::domain::note_file::{FileContentType, FileName}; | 11 | pub use crate::domain::note_file::{FileContentType, FileName}; |
| 14 | 12 | ||
| 15 | -use crate::constant::COURSE_NOTE_FILE_TABLE; | ||
| 16 | use crate::domain::course_note::CourseNoteId; | 13 | use crate::domain::course_note::CourseNoteId; |
| 17 | -use crate::domain::monotonic_id::next_ulid; | 14 | +use crate::domain::monotonic_id::next_uuid; |
| 18 | 15 | ||
| 19 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 16 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 20 | -pub struct CourseNoteFileId(RecordId); | 17 | +#[sqlx(transparent)] |
| 18 | +pub struct CourseNoteFileId(uuid::Uuid); | ||
| 21 | 19 | ||
| 22 | impl CourseNoteFileId { | 20 | impl CourseNoteFileId { |
| 23 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 21 | + /// Minted from the process-wide monotonic generator, not a plain random |
| 24 | - /// a note's files list `id DESC` (newest first, | 22 | + /// UUID: a note's files list `id DESC` (newest first, |
| 25 | /// [`crate::db::course_note_file::list_for`]), and a random low half | 23 | /// [`crate::db::course_note_file::list_for`]), and a random low half |
| 26 | /// scrambles rows minted in the same millisecond. | 24 | /// scrambles rows minted in the same millisecond. |
| 27 | pub fn generate() -> Self { | 25 | pub fn generate() -> Self { |
| 28 | - Self(RecordId::new( | 26 | + Self(next_uuid()) |
| 29 | - COURSE_NOTE_FILE_TABLE, | ||
| 30 | - next_ulid().to_string(), | ||
| 31 | - )) | ||
| 32 | } | 27 | } |
| 33 | 28 | ||
| 29 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 30 | + /// which matches no row. | ||
| 34 | pub fn from_key(key: &str) -> Self { | 31 | pub fn from_key(key: &str) -> Self { |
| 35 | - Self(RecordId::new(COURSE_NOTE_FILE_TABLE, key)) | 32 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 36 | } | 33 | } |
| 37 | 34 | ||
| 38 | - pub fn record(&self) -> RecordId { | 35 | + pub fn key(&self) -> String { |
| 39 | - self.0.clone() | 36 | + self.0.to_string() |
| 40 | - } | ||
| 41 | - | ||
| 42 | - pub fn key(&self) -> &str { | ||
| 43 | - match &self.0.key { | ||
| 44 | - RecordIdKey::String(key) => key, | ||
| 45 | - _ => "", | ||
| 46 | - } | ||
| 47 | } | 37 | } |
| 48 | } | 38 | } |
| 49 | 39 | ||
| 50 | -#[derive(Debug, Clone, SurrealValue)] | 40 | + |
| 41 | +#[derive(Debug, Clone, sqlx::FromRow)] | ||
| 51 | pub struct CourseNoteFile { | 42 | pub struct CourseNoteFile { |
| 52 | pub(crate) id: CourseNoteFileId, | 43 | pub(crate) id: CourseNoteFileId, |
| 53 | pub(crate) course_note: CourseNoteId, | 44 | pub(crate) course_note: CourseNoteId, |
src/domain/course_session.rsmodified+17 -22
| @@ -1,42 +1,37 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | +use crate::constant::{MAX_SESSION_TOPIC_LEN}; |
| 2 | - | ||
| 3 | -use crate::constant::{COURSE_SESSION_TABLE, MAX_SESSION_TOPIC_LEN}; | ||
| 4 | use crate::domain::course::CourseId; | 2 | use crate::domain::course::CourseId; |
| 5 | -use crate::domain::monotonic_id::next_ulid; | 3 | +use crate::domain::monotonic_id::next_uuid; |
| 6 | use crate::domain::timestamp::Timestamp; | 4 | use crate::domain::timestamp::Timestamp; |
| 7 | use crate::domain::user::UserId; | 5 | use crate::domain::user::UserId; |
| 8 | use crate::error::ValidationError; | 6 | use crate::error::ValidationError; |
| 9 | use crate::validate::validate_optional; | 7 | use crate::validate::validate_optional; |
| 10 | 8 | ||
| 11 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 9 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 12 | -pub struct CourseSessionId(RecordId); | 10 | +#[sqlx(transparent)] |
| 11 | +pub struct CourseSessionId(uuid::Uuid); | ||
| 13 | 12 | ||
| 14 | impl CourseSessionId { | 13 | impl CourseSessionId { |
| 15 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 14 | + /// Minted from the process-wide monotonic generator, not a plain random |
| 16 | - /// a course's sessions sort `starts_at DESC, id DESC` and the id breaks | 15 | + /// UUID: a course's sessions sort `starts_at DESC, id DESC` and the id |
| 17 | - /// the tie between two sessions starting at the same instant, | 16 | + /// breaks the tie between two sessions starting at the same instant, |
| 18 | /// and a random low half sorts arbitrarily inside one millisecond. | 17 | /// and a random low half sorts arbitrarily inside one millisecond. |
| 19 | pub fn generate() -> Self { | 18 | pub fn generate() -> Self { |
| 20 | - Self(RecordId::new(COURSE_SESSION_TABLE, next_ulid().to_string())) | 19 | + Self(next_uuid()) |
| 21 | } | 20 | } |
| 22 | 21 | ||
| 22 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 23 | + /// which matches no row. | ||
| 23 | pub fn from_key(key: &str) -> Self { | 24 | pub fn from_key(key: &str) -> Self { |
| 24 | - Self(RecordId::new(COURSE_SESSION_TABLE, key)) | 25 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 25 | - } | ||
| 26 | - | ||
| 27 | - pub fn record(&self) -> RecordId { | ||
| 28 | - self.0.clone() | ||
| 29 | } | 26 | } |
| 30 | 27 | ||
| 31 | - pub fn key(&self) -> &str { | 28 | + pub fn key(&self) -> String { |
| 32 | - match &self.0.key { | 29 | + self.0.to_string() |
| 33 | - RecordIdKey::String(key) => key, | ||
| 34 | - _ => "", | ||
| 35 | - } | ||
| 36 | } | 30 | } |
| 37 | } | 31 | } |
| 38 | 32 | ||
| 39 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 33 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 34 | +#[sqlx(transparent)] | ||
| 40 | pub struct SessionTopic(String); | 35 | pub struct SessionTopic(String); |
| 41 | 36 | ||
| 42 | impl SessionTopic { | 37 | impl SessionTopic { |
| @@ -53,7 +48,7 @@ impl SessionTopic { | |||
| 53 | /// One scheduled lesson of a course: the unit roll call is taken on. Unlike a | 48 | /// One scheduled lesson of a course: the unit roll call is taken on. Unlike a |
| 54 | /// generic event, a session always has a start instant and belongs to a course, | 49 | /// generic event, a session always has a start instant and belongs to a course, |
| 55 | /// so its roster is the course's enrollment plus the assigned teacher. | 50 | /// so its roster is the course's enrollment plus the assigned teacher. |
| 56 | -#[derive(Debug, Clone, SurrealValue)] | 51 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 57 | pub struct CourseSession { | 52 | pub struct CourseSession { |
| 58 | pub(crate) id: CourseSessionId, | 53 | pub(crate) id: CourseSessionId, |
| 59 | pub(crate) course: CourseId, | 54 | pub(crate) course: CourseId, |
src/domain/dietary_profile.rsmodified+26 -25
| @@ -1,8 +1,8 @@ | |||
| 1 | //! What one student may not eat: the school's record of their dietary tags | 1 | //! What one student may not eat: the school's record of their dietary tags |
| 2 | //! plus a free-text note for the kitchen. | 2 | //! plus a free-text note for the kitchen. |
| 3 | //! | 3 | //! |
| 4 | -//! One row per student, so the record key **is** the student's key — no | 4 | +//! One row per student, so the primary key **is** the student — no generated |
| 5 | -//! generated id and no composite. Tags are validated against the same | 5 | +//! id and no composite. Tags are validated against the same |
| 6 | //! `dietary_tags` vocabulary a dish's tags come from ([`Settings::get_dietary_tags`]); | 6 | //! `dietary_tags` vocabulary a dish's tags come from ([`Settings::get_dietary_tags`]); |
| 7 | //! that single shared list is what makes "this dish conflicts with this | 7 | //! that single shared list is what makes "this dish conflicts with this |
| 8 | //! student" answerable as a set intersection, without the backend knowing any | 8 | //! student" answerable as a set intersection, without the backend knowing any |
| @@ -13,41 +13,42 @@ | |||
| 13 | //! | 13 | //! |
| 14 | //! [`Settings::get_dietary_tags`]: crate::domain::settings::Settings::get_dietary_tags | 14 | //! [`Settings::get_dietary_tags`]: crate::domain::settings::Settings::get_dietary_tags |
| 15 | 15 | ||
| 16 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 17 | 16 | ||
| 18 | -use crate::constant::{DIETARY_PROFILE_TABLE, MAX_DIETARY_NOTE_LEN, MAX_DIETARY_TAGS}; | 17 | +use crate::constant::{MAX_DIETARY_NOTE_LEN, MAX_DIETARY_TAGS}; |
| 19 | use crate::domain::timestamp::Timestamp; | 18 | use crate::domain::timestamp::Timestamp; |
| 20 | use crate::domain::user::UserId; | 19 | use crate::domain::user::UserId; |
| 21 | use crate::error::ValidationError; | 20 | use crate::error::ValidationError; |
| 22 | use crate::validate::validate_optional; | 21 | use crate::validate::validate_optional; |
| 23 | 22 | ||
| 24 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 23 | +/// The profile's identity: the student it belongs to. Not a row column of its |
| 25 | -pub struct DietaryProfileId(RecordId); | 24 | +/// own — the table's primary key *is* `student`, so "read the caller's |
| 25 | +/// profile" is a single `SELECT` by key and never a scan. | ||
| 26 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 27 | +pub struct DietaryProfileId { | ||
| 28 | + pub(crate) student: UserId, | ||
| 29 | +} | ||
| 26 | 30 | ||
| 27 | impl DietaryProfileId { | 31 | impl DietaryProfileId { |
| 28 | - /// The profile of one student — deterministic, so "read the caller's | ||
| 29 | - /// profile" is a single `SELECT` by id and never a scan. | ||
| 30 | pub fn of(student: &UserId) -> Self { | 32 | pub fn of(student: &UserId) -> Self { |
| 31 | - Self(RecordId::new(DIETARY_PROFILE_TABLE, student.key())) | 33 | + Self { |
| 32 | - } | 34 | + student: student.clone(), |
| 33 | - | 35 | + } |
| 34 | - pub fn record(&self) -> RecordId { | ||
| 35 | - self.0.clone() | ||
| 36 | } | 36 | } |
| 37 | 37 | ||
| 38 | - pub fn key(&self) -> &str { | 38 | + /// The student's wire key, which is the profile's. |
| 39 | - match &self.0.key { | 39 | + pub fn key(&self) -> String { |
| 40 | - RecordIdKey::String(key) => key, | 40 | + self.student.key() |
| 41 | - _ => "", | ||
| 42 | - } | ||
| 43 | } | 41 | } |
| 44 | } | 42 | } |
| 45 | 43 | ||
| 46 | /// The tags a student's diet carries, drawn from the school's `dietary_tags` | 44 | /// The tags a student's diet carries, drawn from the school's `dietary_tags` |
| 47 | /// list — the same vocabulary a dish is tagged from, deduplicated and in the | 45 | /// list — the same vocabulary a dish is tagged from, deduplicated and in the |
| 48 | -/// order given. | 46 | +/// order given. Stored as a `TEXT[]` column. `no_pg_array` skips the derive's |
| 49 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 47 | +/// element-array assertion (which a `Vec` inner cannot satisfy); the impls |
| 50 | -pub struct DietaryTags(pub(crate) Vec<String>); | 48 | +/// still delegate to `Vec<String>`. |
| 49 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] | ||
| 50 | +#[sqlx(transparent, no_pg_array)] | ||
| 51 | +pub struct DietaryTags(Vec<String>); | ||
| 51 | 52 | ||
| 52 | impl DietaryTags { | 53 | impl DietaryTags { |
| 53 | pub fn try_new(values: &[String], allowed: &[String]) -> Result<Self, ValidationError> { | 54 | pub fn try_new(values: &[String], allowed: &[String]) -> Result<Self, ValidationError> { |
| @@ -79,12 +80,13 @@ impl DietaryTags { | |||
| 79 | } | 80 | } |
| 80 | 81 | ||
| 81 | /// Anything the tag list cannot say — "carries an EpiPen", "no pork". | 82 | /// Anything the tag list cannot say — "carries an EpiPen", "no pork". |
| 82 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 83 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 84 | +#[sqlx(transparent)] | ||
| 83 | pub struct DietaryNote(String); | 85 | pub struct DietaryNote(String); |
| 84 | 86 | ||
| 85 | impl DietaryNote { | 87 | impl DietaryNote { |
| 86 | /// Blank (or whitespace-only) means "no note" — `None`, not an empty | 88 | /// Blank (or whitespace-only) means "no note" — `None`, not an empty |
| 87 | - /// string, so the column is absent rather than falsely present. | 89 | + /// string, so the column is NULL rather than falsely present. |
| 88 | pub fn try_new(value: &str) -> Result<Option<Self>, ValidationError> { | 90 | pub fn try_new(value: &str) -> Result<Option<Self>, ValidationError> { |
| 89 | validate_optional("note", value, MAX_DIETARY_NOTE_LEN)?; | 91 | validate_optional("note", value, MAX_DIETARY_NOTE_LEN)?; |
| 90 | let value = value.trim(); | 92 | let value = value.trim(); |
| @@ -96,9 +98,8 @@ impl DietaryNote { | |||
| 96 | } | 98 | } |
| 97 | } | 99 | } |
| 98 | 100 | ||
| 99 | -#[derive(Debug, Clone, SurrealValue)] | 101 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 100 | pub struct DietaryProfile { | 102 | pub struct DietaryProfile { |
| 101 | - pub(crate) id: DietaryProfileId, | ||
| 102 | pub(crate) student: UserId, | 103 | pub(crate) student: UserId, |
| 103 | pub(crate) tags: DietaryTags, | 104 | pub(crate) tags: DietaryTags, |
| 104 | pub(crate) note: Option<DietaryNote>, | 105 | pub(crate) note: Option<DietaryNote>, |
src/domain/enrollment.rsmodified+24 -62
| @@ -1,34 +1,29 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | - | ||
| 3 | -use crate::constant::ENROLLMENT_TABLE; | ||
| 4 | use crate::domain::class_group::ClassGroupId; | 1 | use crate::domain::class_group::ClassGroupId; |
| 5 | use crate::domain::course::CourseId; | 2 | use crate::domain::course::CourseId; |
| 6 | use crate::domain::user::UserId; | 3 | use crate::domain::user::UserId; |
| 7 | 4 | ||
| 8 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 5 | +/// The identity of one (course, user) pair. Not a row column: the table's |
| 9 | -pub struct EnrollmentId(RecordId); | 6 | +/// primary key *is* the pair, which is what makes enrolling a single atomic |
| 7 | +/// UPSERT (`ON CONFLICT (course, app_user)`) with no find-then-insert race | ||
| 8 | +/// and one-row-per-pair by construction. This struct's job is the | ||
| 9 | +/// underscore-joined wire form at the HTTP edge. | ||
| 10 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 11 | +pub struct EnrollmentId { | ||
| 12 | + pub(crate) course: CourseId, | ||
| 13 | + pub(crate) user: UserId, | ||
| 14 | +} | ||
| 10 | 15 | ||
| 11 | impl EnrollmentId { | 16 | impl EnrollmentId { |
| 12 | - /// A deterministic id for the (course, user) pair. The same pair always | ||
| 13 | - /// maps to the same record id, so enrolling is a single atomic UPSERT with | ||
| 14 | - /// no find-then-insert race and one-row-per-pair by construction. ULID keys | ||
| 15 | - /// are alphanumeric, so `_` is an unambiguous joiner. | ||
| 16 | pub fn composite(course: &CourseId, user: &UserId) -> Self { | 17 | pub fn composite(course: &CourseId, user: &UserId) -> Self { |
| 17 | - Self(RecordId::new( | 18 | + Self { |
| 18 | - ENROLLMENT_TABLE, | 19 | + course: course.clone(), |
| 19 | - format!("{}_{}", course.key(), user.key()), | 20 | + user: user.clone(), |
| 20 | - )) | 21 | + } |
| 21 | - } | ||
| 22 | - | ||
| 23 | - pub fn record(&self) -> RecordId { | ||
| 24 | - self.0.clone() | ||
| 25 | } | 22 | } |
| 26 | 23 | ||
| 27 | - pub fn key(&self) -> &str { | 24 | + /// The underscore-joined wire form (`{course}_{user}`). |
| 28 | - match &self.0.key { | 25 | + pub fn key(&self) -> String { |
| 29 | - RecordIdKey::String(key) => key, | 26 | + format!("{}_{}", self.course.key(), self.user.key()) |
| 30 | - _ => "", | ||
| 31 | - } | ||
| 32 | } | 27 | } |
| 33 | } | 28 | } |
| 34 | 29 | ||
| @@ -36,13 +31,11 @@ impl EnrollmentId { | |||
| 36 | /// user's marks from the report but never deletes result rows. | 31 | /// user's marks from the report but never deletes result rows. |
| 37 | /// | 32 | /// |
| 38 | /// `source` names the class ([`crate::domain::class_group::ClassGroup`]) that | 33 | /// `source` names the class ([`crate::domain::class_group::ClassGroup`]) that |
| 39 | -/// pumped this row, and is absent when a human placed the student directly — | 34 | +/// pumped this row, and is NULL when a human placed the student directly — |
| 40 | -/// every row written before classes existed, and every row placed by hand since. | 35 | +/// every row placed by hand. Absence *is* the meaning, so nothing backfills |
| 41 | -/// Absence *is* the meaning, so nothing backfills it: a class sweep may only take | 36 | +/// it: a class sweep may only take back the rows it wrote. |
| 42 | -/// back the rows it wrote. | 37 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 43 | -#[derive(Debug, Clone, SurrealValue)] | ||
| 44 | pub struct Enrollment { | 38 | pub struct Enrollment { |
| 45 | - pub(crate) id: EnrollmentId, | ||
| 46 | pub(crate) course: CourseId, | 39 | pub(crate) course: CourseId, |
| 47 | pub(crate) user: UserId, | 40 | pub(crate) user: UserId, |
| 48 | pub(crate) enrolled_by: UserId, | 41 | pub(crate) enrolled_by: UserId, |
| @@ -50,8 +43,9 @@ pub struct Enrollment { | |||
| 50 | } | 43 | } |
| 51 | 44 | ||
| 52 | impl Enrollment { | 45 | impl Enrollment { |
| 53 | - pub fn get_id(&self) -> &EnrollmentId { | 46 | + /// The row's identity, built back from its primary-key columns. |
| 54 | - &self.id | 47 | + pub fn get_id(&self) -> EnrollmentId { |
| 48 | + EnrollmentId::composite(&self.course, &self.user) | ||
| 55 | } | 49 | } |
| 56 | 50 | ||
| 57 | pub fn get_course(&self) -> &CourseId { | 51 | pub fn get_course(&self) -> &CourseId { |
| @@ -71,35 +65,3 @@ impl Enrollment { | |||
| 71 | self.source.as_ref() | 65 | self.source.as_ref() |
| 72 | } | 66 | } |
| 73 | } | 67 | } |
| 74 | - | ||
| 75 | -#[cfg(test)] | ||
| 76 | -mod tests { | ||
| 77 | - use super::*; | ||
| 78 | - | ||
| 79 | - /// The database strips `NONE`-valued optional columns, and every enrollment | ||
| 80 | - /// row written before classes existed has no `source` key at all — both must | ||
| 81 | - /// decode as a hand-placed row, never as a decode error that 500s a roster. | ||
| 82 | - #[tokio::test] | ||
| 83 | - async fn enrollment_decodes_without_source_key() { | ||
| 84 | - use surrealdb::types::Value; | ||
| 85 | - | ||
| 86 | - let class = crate::domain::class_group::ClassGroupId::from_key("9a"); | ||
| 87 | - let course = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); | ||
| 88 | - let student = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U"); | ||
| 89 | - let enrollment = Enrollment { | ||
| 90 | - id: EnrollmentId::composite(&course, &student), | ||
| 91 | - course, | ||
| 92 | - user: student, | ||
| 93 | - enrolled_by: UserId::from_key("mgr"), | ||
| 94 | - source: Some(class.clone()), | ||
| 95 | - }; | ||
| 96 | - assert_eq!(enrollment.get_source(), Some(&class)); | ||
| 97 | - | ||
| 98 | - let Value::Object(mut object) = enrollment.into_value() else { | ||
| 99 | - panic!("an enrollment must encode as an object"); | ||
| 100 | - }; | ||
| 101 | - object.remove("source"); | ||
| 102 | - let decoded = Enrollment::from_value(Value::Object(object)).unwrap(); | ||
| 103 | - assert_eq!(decoded.get_source(), None); | ||
| 104 | - } | ||
| 105 | -} | ||
src/domain/event.rsmodified+109 -120
| @@ -1,45 +1,39 @@ | |||
| 1 | -// `Value` looks unused but is load-bearing: the `SurrealValue` derive on the | 1 | +use crate::constant::{MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; |
| 2 | -// tagged `EventAudience` enum expands to code that names `Value` unqualified. | ||
| 3 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; | ||
| 4 | - | ||
| 5 | -use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; | ||
| 6 | use crate::domain::class_group::ClassGroupId; | 2 | use crate::domain::class_group::ClassGroupId; |
| 7 | use crate::domain::course::CourseId; | 3 | use crate::domain::course::CourseId; |
| 8 | -use crate::domain::monotonic_id::next_ulid; | 4 | +use crate::domain::monotonic_id::next_uuid; |
| 9 | use crate::domain::role::Role; | 5 | use crate::domain::role::Role; |
| 10 | use crate::domain::timestamp::Timestamp; | 6 | use crate::domain::timestamp::Timestamp; |
| 11 | use crate::domain::user::UserId; | 7 | use crate::domain::user::UserId; |
| 12 | use crate::error::{AppError, ValidationError}; | 8 | use crate::error::{AppError, ValidationError}; |
| 13 | use crate::validate::{validate_optional, validate_required}; | 9 | use crate::validate::{validate_optional, validate_required}; |
| 14 | 10 | ||
| 15 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 11 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 16 | -pub struct EventId(RecordId); | 12 | +#[sqlx(transparent)] |
| 13 | +pub struct EventId(uuid::Uuid); | ||
| 17 | 14 | ||
| 18 | impl EventId { | 15 | impl EventId { |
| 19 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 16 | + /// Minted from the process-wide monotonic generator, not a plain random |
| 20 | - /// events list `id DESC` (newest first, [`crate::db::event::list_all`]), | 17 | + /// UUID: events list `id DESC` (newest first, |
| 18 | + /// [`crate::db::event::list_all`]), | ||
| 21 | /// and a random low half scrambles rows minted in the same millisecond. | 19 | /// and a random low half scrambles rows minted in the same millisecond. |
| 22 | pub fn generate() -> Self { | 20 | pub fn generate() -> Self { |
| 23 | - Self(RecordId::new(EVENT_TABLE, next_ulid().to_string())) | 21 | + Self(next_uuid()) |
| 24 | } | 22 | } |
| 25 | 23 | ||
| 24 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 25 | + /// which matches no row. | ||
| 26 | pub fn from_key(key: &str) -> Self { | 26 | pub fn from_key(key: &str) -> Self { |
| 27 | - Self(RecordId::new(EVENT_TABLE, key)) | 27 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 28 | - } | ||
| 29 | - | ||
| 30 | - pub fn record(&self) -> RecordId { | ||
| 31 | - self.0.clone() | ||
| 32 | } | 28 | } |
| 33 | 29 | ||
| 34 | - pub fn key(&self) -> &str { | 30 | + pub fn key(&self) -> String { |
| 35 | - match &self.0.key { | 31 | + self.0.to_string() |
| 36 | - RecordIdKey::String(key) => key, | ||
| 37 | - _ => "", | ||
| 38 | - } | ||
| 39 | } | 32 | } |
| 40 | } | 33 | } |
| 41 | 34 | ||
| 42 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 35 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 36 | +#[sqlx(transparent)] | ||
| 43 | pub struct EventTitle(String); | 37 | pub struct EventTitle(String); |
| 44 | 38 | ||
| 45 | impl EventTitle { | 39 | impl EventTitle { |
| @@ -53,7 +47,8 @@ impl EventTitle { | |||
| 53 | } | 47 | } |
| 54 | } | 48 | } |
| 55 | 49 | ||
| 56 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 50 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 51 | +#[sqlx(transparent)] | ||
| 57 | pub struct EventDescription(String); | 52 | pub struct EventDescription(String); |
| 58 | 53 | ||
| 59 | impl EventDescription { | 54 | impl EventDescription { |
| @@ -67,51 +62,77 @@ impl EventDescription { | |||
| 67 | } | 62 | } |
| 68 | } | 63 | } |
| 69 | 64 | ||
| 70 | -/// Who an event is aimed at: the expected-attendee roster. Membership is | 65 | +/// Which shape of expected-attendee roster the event carries — the `kind` |
| 66 | +/// discriminant of the old tagged value, now a flat column. Membership is | ||
| 71 | /// resolved live against today's users/enrollments/registrations — never | 67 | /// resolved live against today's users/enrollments/registrations — never |
| 72 | /// snapshotted — so a role change, (un)enrollment, or (un)registration moves | 68 | /// snapshotted — so a role change, (un)enrollment, or (un)registration moves |
| 73 | /// people in and out of rosters by itself. The audience does not gate *seeing* | 69 | /// people in and out of rosters by itself. The audience does not gate *seeing* |
| 74 | /// the event (the calendar stays school-visible); it defines who counts as | 70 | /// the event (the calendar stays school-visible); it defines who counts as |
| 75 | /// expected and who may be marked. | 71 | /// expected and who may be marked. |
| 76 | /// | 72 | /// |
| 77 | -/// Stored internally tagged: `{kind: 'school'}`, `{kind: 'role', role: 'student'}`, | 73 | +/// The payload lives in the sibling columns: `audience_role` for |
| 78 | -/// `{kind: 'course', course: course:…}`, `{kind: 'class', class: class_group:…}`, | 74 | +/// [`EventAudienceKind::Role`], `audience_course` for |
| 79 | -/// `{kind: 'registration', capacity: 30}`. | 75 | +/// [`EventAudienceKind::Course`], `audience_class` for |
| 80 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 76 | +/// [`EventAudienceKind::Class`], `audience_capacity` for |
| 81 | -#[surreal(tag = "kind", rename_all = "lowercase")] | 77 | +/// [`EventAudienceKind::Registration`]. A `School` event carries none. |
| 82 | -pub enum EventAudience { | 78 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] |
| 83 | - /// Everybody — the pre-audience behavior and the backfill for old rows. | 79 | +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] |
| 80 | +pub enum EventAudienceKind { | ||
| 81 | + /// Everybody — the pre-audience behavior. | ||
| 84 | School, | 82 | School, |
| 85 | /// Every user holding exactly this role ("all students", "all teachers"). | 83 | /// Every user holding exactly this role ("all students", "all teachers"). |
| 86 | - Role { role: Role }, | 84 | + Role, |
| 87 | /// A course's enrolled students. Staff running the course are not implied | 85 | /// A course's enrolled students. Staff running the course are not implied |
| 88 | /// members — a mixed gathering wants a registration or role audience. | 86 | /// members — a mixed gathering wants a registration or role audience. |
| 89 | - Course { course: CourseId }, | 87 | + Course, |
| 90 | /// A class section's (şube) students, read live off `class_member` — the | 88 | /// A class section's (şube) students, read live off `class_member` — the |
| 91 | /// same live resolution `Course` and `Role` get, so adding a student to the | 89 | /// same live resolution `Course` and `Role` get, so adding a student to the |
| 92 | /// class puts them on every one of its events' rosters at once. The | 90 | /// class puts them on every one of its events' rosters at once. The |
| 93 | /// homeroom teacher is not implied, matching `Course`. A deleted class | 91 | /// homeroom teacher is not implied, matching `Course`. A deleted class |
| 94 | /// leaves the event standing with an empty roster, exactly as a deleted | 92 | /// leaves the event standing with an empty roster, exactly as a deleted |
| 95 | /// course does (`Course::delete` never touches `event`). | 93 | /// course does (`Course::delete` never touches `event`). |
| 96 | - Class { class: ClassGroupId }, | 94 | + Class, |
| 97 | /// A signup list built one person at a time through the register | 95 | /// A signup list built one person at a time through the register |
| 98 | /// endpoints — teachers place students, staff take their own seat. The | 96 | /// endpoints — teachers place students, staff take their own seat. The |
| 99 | - /// list is capped at `capacity` seats when set (`None` = unlimited) and | 97 | + /// list is capped at the `audience_capacity` seats when set (`NULL` = |
| 100 | - /// closes once the event starts. Rows survive an audience change inertly. | 98 | + /// unlimited) and closes once the event starts. Rows survive an audience |
| 101 | - Registration { capacity: Option<i64> }, | 99 | + /// change inertly. |
| 100 | + Registration, | ||
| 102 | } | 101 | } |
| 103 | 102 | ||
| 104 | -#[derive(Debug, Clone, SurrealValue)] | 103 | +/// Who an event is aimed at, as one flat row. The five audience columns |
| 104 | +/// (kind + payload) are exactly the `audience_*` columns of the migration; | ||
| 105 | +/// every write goes through one validated shape, so only the payload matching | ||
| 106 | +/// `audience_kind` is ever non-NULL. | ||
| 107 | +#[derive(Debug, Clone, sqlx::FromRow)] | ||
| 105 | pub struct Event { | 108 | pub struct Event { |
| 106 | pub(crate) id: EventId, | 109 | pub(crate) id: EventId, |
| 107 | pub(crate) creator: UserId, | 110 | pub(crate) creator: UserId, |
| 108 | pub(crate) title: EventTitle, | 111 | pub(crate) title: EventTitle, |
| 109 | pub(crate) description: EventDescription, | 112 | pub(crate) description: EventDescription, |
| 110 | - pub(crate) audience: EventAudience, | 113 | + pub(crate) audience_kind: EventAudienceKind, |
| 114 | + pub(crate) audience_role: Option<Role>, | ||
| 115 | + pub(crate) audience_course: Option<CourseId>, | ||
| 116 | + pub(crate) audience_class: Option<ClassGroupId>, | ||
| 117 | + pub(crate) audience_capacity: Option<i64>, | ||
| 111 | pub(crate) starts_at: Option<Timestamp>, | 118 | pub(crate) starts_at: Option<Timestamp>, |
| 112 | pub(crate) ends_at: Option<Timestamp>, | 119 | pub(crate) ends_at: Option<Timestamp>, |
| 113 | } | 120 | } |
| 114 | 121 | ||
| 122 | +impl EventAudienceKind { | ||
| 123 | + /// The wire/storage spelling. Must stay in lockstep with `rename_all` — | ||
| 124 | + /// the web layer publishes these as the audience `kind`. | ||
| 125 | + pub fn as_str(self) -> &'static str { | ||
| 126 | + match self { | ||
| 127 | + EventAudienceKind::School => "school", | ||
| 128 | + EventAudienceKind::Role => "role", | ||
| 129 | + EventAudienceKind::Course => "course", | ||
| 130 | + EventAudienceKind::Class => "class", | ||
| 131 | + EventAudienceKind::Registration => "registration", | ||
| 132 | + } | ||
| 133 | + } | ||
| 134 | +} | ||
| 135 | + | ||
| 115 | impl Event { | 136 | impl Event { |
| 116 | pub fn get_id(&self) -> &EventId { | 137 | pub fn get_id(&self) -> &EventId { |
| 117 | &self.id | 138 | &self.id |
| @@ -129,8 +150,26 @@ impl Event { | |||
| 129 | &self.description | 150 | &self.description |
| 130 | } | 151 | } |
| 131 | 152 | ||
| 132 | - pub fn get_audience(&self) -> &EventAudience { | 153 | + /// Which audience shape the event carries; the payload sits in the |
| 133 | - &self.audience | 154 | + /// matching sibling column. |
| 155 | + pub fn get_audience_kind(&self) -> EventAudienceKind { | ||
| 156 | + self.audience_kind | ||
| 157 | + } | ||
| 158 | + | ||
| 159 | + pub fn get_audience_role(&self) -> Option<Role> { | ||
| 160 | + self.audience_role | ||
| 161 | + } | ||
| 162 | + | ||
| 163 | + pub fn get_audience_course(&self) -> Option<&CourseId> { | ||
| 164 | + self.audience_course.as_ref() | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + pub fn get_audience_class(&self) -> Option<&ClassGroupId> { | ||
| 168 | + self.audience_class.as_ref() | ||
| 169 | + } | ||
| 170 | + | ||
| 171 | + pub fn get_audience_capacity(&self) -> Option<i64> { | ||
| 172 | + self.audience_capacity | ||
| 134 | } | 173 | } |
| 135 | 174 | ||
| 136 | pub fn get_starts_at(&self) -> Option<Timestamp> { | 175 | pub fn get_starts_at(&self) -> Option<Timestamp> { |
| @@ -151,12 +190,12 @@ impl Event { | |||
| 151 | /// deadline), the moment that end passes (a truly timeless event never | 190 | /// deadline), the moment that end passes (a truly timeless event never |
| 152 | /// closes). Returns the seat cap for the register path. | 191 | /// closes). Returns the seat cap for the register path. |
| 153 | pub fn registration_capacity(&self) -> Result<Option<i64>, AppError> { | 192 | pub fn registration_capacity(&self) -> Result<Option<i64>, AppError> { |
| 154 | - let EventAudience::Registration { capacity } = &self.audience else { | 193 | + if self.audience_kind != EventAudienceKind::Registration { |
| 155 | return Err(AppError::Validation(ValidationError::Invalid { | 194 | return Err(AppError::Validation(ValidationError::Invalid { |
| 156 | field: "audience", | 195 | field: "audience", |
| 157 | reason: "this event does not take registrations", | 196 | reason: "this event does not take registrations", |
| 158 | })); | 197 | })); |
| 159 | - }; | 198 | + } |
| 160 | // ends_at can't precede starts_at, so when both exist starts_at governs. | 199 | // ends_at can't precede starts_at, so when both exist starts_at governs. |
| 161 | if let Some(closes_at) = self.starts_at.or(self.ends_at) | 200 | if let Some(closes_at) = self.starts_at.or(self.ends_at) |
| 162 | && Timestamp::now().as_millis() >= closes_at.as_millis() | 201 | && Timestamp::now().as_millis() >= closes_at.as_millis() |
| @@ -165,7 +204,7 @@ impl Event { | |||
| 165 | "registration closed — the event has started or ended", | 204 | "registration closed — the event has started or ended", |
| 166 | )); | 205 | )); |
| 167 | } | 206 | } |
| 168 | - Ok(*capacity) | 207 | + Ok(self.audience_capacity) |
| 169 | } | 208 | } |
| 170 | } | 209 | } |
| 171 | 210 | ||
| @@ -185,68 +224,35 @@ mod tests { | |||
| 185 | assert!(EventDescription::try_new("").is_ok()); | 224 | assert!(EventDescription::try_new("").is_ok()); |
| 186 | } | 225 | } |
| 187 | 226 | ||
| 188 | - /// The audience stores as an internally tagged object — `{kind: '…', …}`. | 227 | + /// The `audience_kind` column is `TEXT` with a CHECK listing exactly |
| 189 | - /// The schema's `audience.kind`/`audience.role`/… field definitions and the | 228 | + /// these spellings — audience-shaped queries match on them, so the |
| 190 | - /// boot backfill (`{kind: 'school'}`) are written against exactly this | 229 | + /// storage form may not drift (which `rename_all` mirrors). |
| 191 | - /// encoding; guard that it never drifts. | 230 | + #[test] |
| 192 | - #[tokio::test] | 231 | + fn audience_kind_spellings_are_frozen() { |
| 193 | - async fn audience_encodes_internally_tagged_and_round_trips() { | 232 | + assert_eq!(EventAudienceKind::School.as_str(), "school"); |
| 194 | - use surrealdb::types::Value; | 233 | + assert_eq!(EventAudienceKind::Role.as_str(), "role"); |
| 195 | - | 234 | + assert_eq!(EventAudienceKind::Course.as_str(), "course"); |
| 196 | - let cases = [ | 235 | + assert_eq!(EventAudienceKind::Class.as_str(), "class"); |
| 197 | - (EventAudience::School, "school"), | 236 | + assert_eq!(EventAudienceKind::Registration.as_str(), "registration"); |
| 198 | - ( | ||
| 199 | - EventAudience::Role { | ||
| 200 | - role: Role::Student, | ||
| 201 | - }, | ||
| 202 | - "role", | ||
| 203 | - ), | ||
| 204 | - ( | ||
| 205 | - EventAudience::Course { | ||
| 206 | - course: CourseId::from_key("c1"), | ||
| 207 | - }, | ||
| 208 | - "course", | ||
| 209 | - ), | ||
| 210 | - ( | ||
| 211 | - EventAudience::Class { | ||
| 212 | - class: ClassGroupId::from_key("g1"), | ||
| 213 | - }, | ||
| 214 | - "class", | ||
| 215 | - ), | ||
| 216 | - ( | ||
| 217 | - EventAudience::Registration { capacity: Some(30) }, | ||
| 218 | - "registration", | ||
| 219 | - ), | ||
| 220 | - ( | ||
| 221 | - EventAudience::Registration { capacity: None }, | ||
| 222 | - "registration", | ||
| 223 | - ), | ||
| 224 | - ]; | ||
| 225 | - for (audience, kind) in cases { | ||
| 226 | - let value = audience.clone().into_value(); | ||
| 227 | - let Value::Object(ref object) = value else { | ||
| 228 | - panic!("audience must encode as an object, got {value:?}"); | ||
| 229 | - }; | ||
| 230 | - assert_eq!( | ||
| 231 | - object.get("kind"), | ||
| 232 | - Some(&Value::String(kind.to_string())), | ||
| 233 | - "tag field must be `kind: '{kind}'`" | ||
| 234 | - ); | ||
| 235 | - assert_eq!(EventAudience::from_value(value).unwrap(), audience); | ||
| 236 | - } | ||
| 237 | } | 237 | } |
| 238 | 238 | ||
| 239 | + /// The audience columns as a row writer would set them. | ||
| 239 | fn event_with( | 240 | fn event_with( |
| 240 | - audience: EventAudience, | 241 | + audience_kind: EventAudienceKind, |
| 242 | + audience_capacity: Option<i64>, | ||
| 241 | starts_at: Option<Timestamp>, | 243 | starts_at: Option<Timestamp>, |
| 242 | ends_at: Option<Timestamp>, | 244 | ends_at: Option<Timestamp>, |
| 243 | ) -> Event { | 245 | ) -> Event { |
| 244 | Event { | 246 | Event { |
| 245 | id: EventId::generate(), | 247 | id: EventId::generate(), |
| 246 | - creator: UserId::from_key("u1"), | 248 | + creator: UserId::from_key("0198f1a2-3b4c-7d5e-8f90-aa2b3c4d5e6f"), |
| 247 | title: EventTitle::try_new("signup").unwrap(), | 249 | title: EventTitle::try_new("signup").unwrap(), |
| 248 | description: EventDescription::try_new("").unwrap(), | 250 | description: EventDescription::try_new("").unwrap(), |
| 249 | - audience, | 251 | + audience_kind, |
| 252 | + audience_role: None, | ||
| 253 | + audience_course: None, | ||
| 254 | + audience_class: None, | ||
| 255 | + audience_capacity, | ||
| 250 | starts_at, | 256 | starts_at, |
| 251 | ends_at, | 257 | ends_at, |
| 252 | } | 258 | } |
| @@ -254,21 +260,20 @@ mod tests { | |||
| 254 | 260 | ||
| 255 | #[tokio::test] | 261 | #[tokio::test] |
| 256 | async fn registration_capacity_gates_and_echoes_cap() { | 262 | async fn registration_capacity_gates_and_echoes_cap() { |
| 257 | - let open = |capacity| EventAudience::Registration { capacity }; | ||
| 258 | let past = Some(Timestamp::from_millis(Timestamp::now().as_millis() - 1)); | 263 | let past = Some(Timestamp::from_millis(Timestamp::now().as_millis() - 1)); |
| 259 | 264 | ||
| 260 | assert!(matches!( | 265 | assert!(matches!( |
| 261 | - event_with(EventAudience::School, None, None).registration_capacity(), | 266 | + event_with(EventAudienceKind::School, None, None, None).registration_capacity(), |
| 262 | Err(AppError::Validation(_)) | 267 | Err(AppError::Validation(_)) |
| 263 | )); | 268 | )); |
| 264 | assert_eq!( | 269 | assert_eq!( |
| 265 | - event_with(open(None), None, None) | 270 | + event_with(EventAudienceKind::Registration, None, None, None) |
| 266 | .registration_capacity() | 271 | .registration_capacity() |
| 267 | .unwrap(), | 272 | .unwrap(), |
| 268 | None | 273 | None |
| 269 | ); | 274 | ); |
| 270 | assert_eq!( | 275 | assert_eq!( |
| 271 | - event_with(open(Some(30)), None, None) | 276 | + event_with(EventAudienceKind::Registration, Some(30), None, None) |
| 272 | .registration_capacity() | 277 | .registration_capacity() |
| 273 | .unwrap(), | 278 | .unwrap(), |
| 274 | Some(30) | 279 | Some(30) |
| @@ -276,30 +281,14 @@ mod tests { | |||
| 276 | // Started events close the list; an ends_at-only deadline in the past | 281 | // Started events close the list; an ends_at-only deadline in the past |
| 277 | // does too. | 282 | // does too. |
| 278 | assert!(matches!( | 283 | assert!(matches!( |
| 279 | - event_with(open(Some(30)), past, None).registration_capacity(), | 284 | + event_with(EventAudienceKind::Registration, Some(30), past, None) |
| 285 | + .registration_capacity(), | ||
| 280 | Err(AppError::Conflict(_)) | 286 | Err(AppError::Conflict(_)) |
| 281 | )); | 287 | )); |
| 282 | assert!(matches!( | 288 | assert!(matches!( |
| 283 | - event_with(open(None), None, past).registration_capacity(), | 289 | + event_with(EventAudienceKind::Registration, None, None, past) |
| 290 | + .registration_capacity(), | ||
| 284 | Err(AppError::Conflict(_)) | 291 | Err(AppError::Conflict(_)) |
| 285 | )); | 292 | )); |
| 286 | } | 293 | } |
| 287 | - | ||
| 288 | - /// The database strips `NONE`-valued optional columns and the boot | ||
| 289 | - /// conversion writes a bare `{kind: 'registration'}` — an object with no | ||
| 290 | - /// `capacity` key at all must decode as an uncapped registration. | ||
| 291 | - #[tokio::test] | ||
| 292 | - async fn registration_audience_decodes_without_capacity_key() { | ||
| 293 | - use surrealdb::types::Value; | ||
| 294 | - | ||
| 295 | - let value = EventAudience::Registration { capacity: None }.into_value(); | ||
| 296 | - let Value::Object(mut object) = value else { | ||
| 297 | - panic!("audience must encode as an object, got {value:?}"); | ||
| 298 | - }; | ||
| 299 | - object.remove("capacity"); | ||
| 300 | - assert_eq!( | ||
| 301 | - EventAudience::from_value(Value::Object(object)).unwrap(), | ||
| 302 | - EventAudience::Registration { capacity: None } | ||
| 303 | - ); | ||
| 304 | - } | ||
| 305 | } | 294 | } |
src/domain/exam.rsmodified+36 -47
| @@ -1,10 +1,8 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | - | ||
| 3 | use crate::constant::{ | 1 | use crate::constant::{ |
| 4 | - EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS, | 2 | + MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS, |
| 5 | }; | 3 | }; |
| 6 | use crate::domain::course::CourseId; | 4 | use crate::domain::course::CourseId; |
| 7 | -use crate::domain::monotonic_id::next_ulid; | 5 | +use crate::domain::monotonic_id::next_uuid; |
| 8 | use crate::domain::settings::ExamKindDef; | 6 | use crate::domain::settings::ExamKindDef; |
| 9 | use crate::domain::timestamp::Timestamp; | 7 | use crate::domain::timestamp::Timestamp; |
| 10 | use crate::domain::user::UserId; | 8 | use crate::domain::user::UserId; |
| @@ -24,34 +22,32 @@ use crate::validate::{ | |||
| 24 | validate_required, | 22 | validate_required, |
| 25 | }; | 23 | }; |
| 26 | 24 | ||
| 27 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 25 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 28 | -pub struct ExamId(RecordId); | 26 | +#[sqlx(transparent)] |
| 27 | +pub struct ExamId(uuid::Uuid); | ||
| 29 | 28 | ||
| 30 | impl ExamId { | 29 | impl ExamId { |
| 31 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 30 | + /// Minted from the process-wide monotonic generator, not a plain random |
| 32 | - /// exams list `id DESC` (newest first, [`crate::db::exam::list_all`]), | 31 | + /// UUID: exams list `id DESC` (newest first, |
| 32 | + /// [`crate::db::exam::list_all`]), | ||
| 33 | /// and a random low half scrambles rows minted in the same millisecond. | 33 | /// and a random low half scrambles rows minted in the same millisecond. |
| 34 | pub fn generate() -> Self { | 34 | pub fn generate() -> Self { |
| 35 | - Self(RecordId::new(EXAM_TABLE, next_ulid().to_string())) | 35 | + Self(next_uuid()) |
| 36 | } | 36 | } |
| 37 | 37 | ||
| 38 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 39 | + /// which matches no row. | ||
| 38 | pub fn from_key(key: &str) -> Self { | 40 | pub fn from_key(key: &str) -> Self { |
| 39 | - Self(RecordId::new(EXAM_TABLE, key)) | 41 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 40 | - } | ||
| 41 | - | ||
| 42 | - pub fn record(&self) -> RecordId { | ||
| 43 | - self.0.clone() | ||
| 44 | } | 42 | } |
| 45 | 43 | ||
| 46 | - pub fn key(&self) -> &str { | 44 | + pub fn key(&self) -> String { |
| 47 | - match &self.0.key { | 45 | + self.0.to_string() |
| 48 | - RecordIdKey::String(key) => key, | ||
| 49 | - _ => "", | ||
| 50 | - } | ||
| 51 | } | 46 | } |
| 52 | } | 47 | } |
| 53 | 48 | ||
| 54 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 49 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 50 | +#[sqlx(transparent)] | ||
| 55 | pub struct ExamTitle(String); | 51 | pub struct ExamTitle(String); |
| 56 | 52 | ||
| 57 | impl ExamTitle { | 53 | impl ExamTitle { |
| @@ -65,7 +61,8 @@ impl ExamTitle { | |||
| 65 | } | 61 | } |
| 66 | } | 62 | } |
| 67 | 63 | ||
| 68 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 64 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 65 | +#[sqlx(transparent)] | ||
| 69 | pub struct ExamDescription(String); | 66 | pub struct ExamDescription(String); |
| 70 | 67 | ||
| 71 | impl ExamDescription { | 68 | impl ExamDescription { |
| @@ -84,7 +81,8 @@ impl ExamDescription { | |||
| 84 | /// the exam's weight in the course average (set per kind in settings, not per | 81 | /// the exam's weight in the course average (set per kind in settings, not per |
| 85 | /// exam). Stored exams keep their kind even if the school later edits the | 82 | /// exam). Stored exams keep their kind even if the school later edits the |
| 86 | /// list; only new writes are held to the current one. | 83 | /// list; only new writes are held to the current one. |
| 87 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 84 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 85 | +#[sqlx(transparent)] | ||
| 88 | pub struct ExamKind(String); | 86 | pub struct ExamKind(String); |
| 89 | 87 | ||
| 90 | impl ExamKind { | 88 | impl ExamKind { |
| @@ -106,7 +104,8 @@ impl ExamKind { | |||
| 106 | /// A validated exam mode: `sync` (everyone sits inside one fixed window), | 104 | /// A validated exam mode: `sync` (everyone sits inside one fixed window), |
| 107 | /// `async` (each student starts inside the window and gets `duration_ms`), or | 105 | /// `async` (each student starts inside the window and gets `duration_ms`), or |
| 108 | /// `open` (no window — sit anytime, with an optional per-attempt duration). | 106 | /// `open` (no window — sit anytime, with an optional per-attempt duration). |
| 109 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 107 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 108 | +#[sqlx(transparent)] | ||
| 110 | pub struct ExamMode(String); | 109 | pub struct ExamMode(String); |
| 111 | 110 | ||
| 112 | impl ExamMode { | 111 | impl ExamMode { |
| @@ -122,7 +121,8 @@ impl ExamMode { | |||
| 122 | 121 | ||
| 123 | /// A validated per-attempt time budget, milliseconds. Required for an `async` | 122 | /// A validated per-attempt time budget, milliseconds. Required for an `async` |
| 124 | /// exam, optional for an `open` one (absent = unlimited time). | 123 | /// exam, optional for an `open` one (absent = unlimited time). |
| 125 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | 124 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] |
| 125 | +#[sqlx(transparent)] | ||
| 126 | pub struct ExamDuration(i64); | 126 | pub struct ExamDuration(i64); |
| 127 | 127 | ||
| 128 | impl ExamDuration { | 128 | impl ExamDuration { |
| @@ -140,7 +140,8 @@ impl ExamDuration { | |||
| 140 | /// same spelling on the wire and in storage; `1` (the default) is the classic | 140 | /// same spelling on the wire and in storage; `1` (the default) is the classic |
| 141 | /// single sitting. Editable live: raising it mid-exam grants retakes, and | 141 | /// single sitting. Editable live: raising it mid-exam grants retakes, and |
| 142 | /// lowering it only blocks *future* starts (existing attempts stand). | 142 | /// lowering it only blocks *future* starts (existing attempts stand). |
| 143 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | 143 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] |
| 144 | +#[sqlx(transparent)] | ||
| 144 | pub struct ExamAttemptLimit(i64); | 145 | pub struct ExamAttemptLimit(i64); |
| 145 | 146 | ||
| 146 | impl ExamAttemptLimit { | 147 | impl ExamAttemptLimit { |
| @@ -269,7 +270,15 @@ impl ExamSchedule { | |||
| 269 | } | 270 | } |
| 270 | } | 271 | } |
| 271 | 272 | ||
| 272 | -#[derive(Debug, Clone, SurrealValue)] | 273 | +/// One exam. The schedule is flattened into columns, always written through |
| 274 | +/// an [`ExamSchedule`], so the invariants above hold for every stored row. | ||
| 275 | +/// | ||
| 276 | +/// The `result_count` counter deliberately does NOT live on the struct: it is | ||
| 277 | +/// a plain `BIGINT NOT NULL DEFAULT 0` column that only the mark-write and | ||
| 278 | +/// mark-delete paths touch with conditional single statements, and every read | ||
| 279 | +/// of it is its own `SELECT` — no whole-row rewrite can clobber it, and no | ||
| 280 | +/// stale snapshot can pin it. | ||
| 281 | +#[derive(Debug, Clone, sqlx::FromRow)] | ||
| 273 | pub struct Exam { | 282 | pub struct Exam { |
| 274 | pub(crate) id: ExamId, | 283 | pub(crate) id: ExamId, |
| 275 | pub(crate) creator: UserId, | 284 | pub(crate) creator: UserId, |
| @@ -277,31 +286,16 @@ pub struct Exam { | |||
| 277 | pub(crate) title: ExamTitle, | 286 | pub(crate) title: ExamTitle, |
| 278 | pub(crate) description: ExamDescription, | 287 | pub(crate) description: ExamDescription, |
| 279 | pub(crate) kind: ExamKind, | 288 | pub(crate) kind: ExamKind, |
| 280 | - // The schedule, flattened into columns (SCHEMAFULL keeps them typed). | ||
| 281 | - // Always written through an `ExamSchedule`, so the invariants above hold | ||
| 282 | - // for every stored row; pre-schedule rows read back as all-`None`. | ||
| 283 | pub(crate) mode: Option<ExamMode>, | 289 | pub(crate) mode: Option<ExamMode>, |
| 284 | pub(crate) starts_at: Option<Timestamp>, | 290 | pub(crate) starts_at: Option<Timestamp>, |
| 285 | pub(crate) ends_at: Option<Timestamp>, | 291 | pub(crate) ends_at: Option<Timestamp>, |
| 286 | pub(crate) duration_ms: Option<ExamDuration>, | 292 | pub(crate) duration_ms: Option<ExamDuration>, |
| 287 | - // Attempt policy. Rows predating these columns are backfilled by the boot | ||
| 288 | - // migration (limit 1, rejoin open), so reads never see them missing. | ||
| 289 | pub(crate) max_attempts: ExamAttemptLimit, | 293 | pub(crate) max_attempts: ExamAttemptLimit, |
| 290 | pub(crate) allow_rejoin: bool, | 294 | pub(crate) allow_rejoin: bool, |
| 291 | pub(crate) allow_review: bool, | 295 | pub(crate) allow_review: bool, |
| 292 | // Work-in-progress marker: a draft is visible only to its course's | 296 | // Work-in-progress marker: a draft is visible only to its course's |
| 293 | - // managers, cannot be sat, and cannot be graded. Rows predating the | 297 | + // managers, cannot be sat, and cannot be graded. |
| 294 | - // column are backfilled published (`false`). | ||
| 295 | pub(crate) draft: bool, | 298 | pub(crate) draft: bool, |
| 296 | - /// How many marks the exam carries — a cap-style counter | ||
| 297 | - /// ([`crate::db::cap::claim`] | ||
| 298 | - /// from the grade, decremented by every delete of a mark), absent meaning | ||
| 299 | - /// zero. Unlike every other counter it is carried *in the struct*, because | ||
| 300 | - /// the save below is a whole-row `CONTENT` write: a column this type did | ||
| 301 | - /// not know about would be wiped by the next exam PATCH. Being in the row | ||
| 302 | - /// is also what makes it useful — the save pins it, so a grade landing | ||
| 303 | - /// mid-PATCH refuses the save instead of slipping past its gates. | ||
| 304 | - pub(crate) result_count: Option<i64>, | ||
| 305 | } | 299 | } |
| 306 | 300 | ||
| 307 | impl Exam { | 301 | impl Exam { |
| @@ -309,11 +303,6 @@ impl Exam { | |||
| 309 | &self.id | 303 | &self.id |
| 310 | } | 304 | } |
| 311 | 305 | ||
| 312 | - /// The marks this exam carries, as the counter reads (absent = none yet). | ||
| 313 | - pub fn get_result_count(&self) -> i64 { | ||
| 314 | - self.result_count.unwrap_or(0) | ||
| 315 | - } | ||
| 316 | - | ||
| 317 | pub fn get_creator(&self) -> &UserId { | 306 | pub fn get_creator(&self) -> &UserId { |
| 318 | &self.creator | 307 | &self.creator |
| 319 | } | 308 | } |
src/domain/exam_answer.rsmodified+32 -32
| @@ -1,6 +1,4 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | +use crate::constant::MAX_ANSWER_TEXT_LEN; |
| 2 | - | ||
| 3 | -use crate::constant::{EXAM_ANSWER_TABLE, MAX_ANSWER_TEXT_LEN}; | ||
| 4 | use crate::domain::exam::ExamId; | 2 | use crate::domain::exam::ExamId; |
| 5 | use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId}; | 3 | use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId}; |
| 6 | use crate::domain::key; | 4 | use crate::domain::key; |
| @@ -9,35 +7,38 @@ use crate::domain::user::UserId; | |||
| 9 | use crate::error::ValidationError; | 7 | use crate::error::ValidationError; |
| 10 | use crate::validate::validate_optional; | 8 | use crate::validate::validate_optional; |
| 11 | 9 | ||
| 12 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 10 | +/// The identity of one (question, user, seq) triple — a sitting's answer. Not |
| 13 | -pub struct ExamAnswerId(RecordId); | 11 | +/// a row column: the table's primary key *is* the triple, which is what makes |
| 12 | +/// saving a single atomic UPSERT keyed by seq: re-answering *within a sitting* | ||
| 13 | +/// overwrites its one row, but a retake's `seq` writes a new row, so every | ||
| 14 | +/// sitting keeps its own answer history. See [`key::sitting`] for the wire | ||
| 15 | +/// shape and why the first sitting stays bare. | ||
| 16 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 17 | +pub struct ExamAnswerId { | ||
| 18 | + pub(crate) question: ExamQuestionId, | ||
| 19 | + pub(crate) user: UserId, | ||
| 20 | + pub(crate) seq: i64, | ||
| 21 | +} | ||
| 14 | 22 | ||
| 15 | impl ExamAnswerId { | 23 | impl ExamAnswerId { |
| 16 | - /// A deterministic id for the (question, user, seq) triple. Saving is a | ||
| 17 | - /// single atomic UPSERT keyed by seq: re-answering *within a sitting* | ||
| 18 | - /// overwrites its one row, but a retake's `seq` writes a new row, so every | ||
| 19 | - /// sitting keeps its own answer history. See [`key::sitting`] for the key | ||
| 20 | - /// shape and why the first sitting stays bare. | ||
| 21 | pub fn composite(question: &ExamQuestionId, user: &UserId, seq: i64) -> Self { | 24 | pub fn composite(question: &ExamQuestionId, user: &UserId, seq: i64) -> Self { |
| 22 | - let key = key::sitting(question.key(), user.key(), seq); | 25 | + Self { |
| 23 | - Self(RecordId::new(EXAM_ANSWER_TABLE, key)) | 26 | + question: question.clone(), |
| 24 | - } | 27 | + user: user.clone(), |
| 25 | - | 28 | + seq, |
| 26 | - pub fn record(&self) -> RecordId { | 29 | + } |
| 27 | - self.0.clone() | ||
| 28 | } | 30 | } |
| 29 | 31 | ||
| 30 | - pub fn key(&self) -> &str { | 32 | + /// The underscore-joined wire form (`{question}_{user}[_{seq}]`). |
| 31 | - match &self.0.key { | 33 | + pub fn key(&self) -> String { |
| 32 | - RecordIdKey::String(key) => key, | 34 | + key::sitting(self.question.key().as_str(), self.user.key().as_str(), self.seq) |
| 33 | - _ => "", | ||
| 34 | - } | ||
| 35 | } | 35 | } |
| 36 | } | 36 | } |
| 37 | 37 | ||
| 38 | /// A free-text answer: may be empty (a student clearing their draft is a valid | 38 | /// A free-text answer: may be empty (a student clearing their draft is a valid |
| 39 | /// save), at most `MAX_ANSWER_TEXT_LEN` characters. | 39 | /// save), at most `MAX_ANSWER_TEXT_LEN` characters. |
| 40 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 40 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 41 | +#[sqlx(transparent)] | ||
| 41 | pub struct AnswerText(String); | 42 | pub struct AnswerText(String); |
| 42 | 43 | ||
| 43 | impl AnswerText { | 44 | impl AnswerText { |
| @@ -54,9 +55,8 @@ impl AnswerText { | |||
| 54 | /// One student's answer to one question, autosaved as they type or pick. | 55 | /// One student's answer to one question, autosaved as they type or pick. |
| 55 | /// `exam` is denormalized from the question so per-exam reads (live monitor, | 56 | /// `exam` is denormalized from the question so per-exam reads (live monitor, |
| 56 | /// cascades) don't fan out through `exam_question`. | 57 | /// cascades) don't fan out through `exam_question`. |
| 57 | -#[derive(Debug, Clone, SurrealValue)] | 58 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 58 | pub struct ExamAnswer { | 59 | pub struct ExamAnswer { |
| 59 | - pub(crate) id: ExamAnswerId, | ||
| 60 | pub(crate) exam: ExamId, | 60 | pub(crate) exam: ExamId, |
| 61 | pub(crate) question: ExamQuestionId, | 61 | pub(crate) question: ExamQuestionId, |
| 62 | pub(crate) user: UserId, | 62 | pub(crate) user: UserId, |
| @@ -67,8 +67,9 @@ pub struct ExamAnswer { | |||
| 67 | } | 67 | } |
| 68 | 68 | ||
| 69 | impl ExamAnswer { | 69 | impl ExamAnswer { |
| 70 | - pub fn get_id(&self) -> &ExamAnswerId { | 70 | + /// The row's identity, built back from its primary-key columns. |
| 71 | - &self.id | 71 | + pub fn get_id(&self) -> ExamAnswerId { |
| 72 | + ExamAnswerId::composite(&self.question, &self.user, self.seq) | ||
| 72 | } | 73 | } |
| 73 | 74 | ||
| 74 | pub fn get_exam(&self) -> &ExamId { | 75 | pub fn get_exam(&self) -> &ExamId { |
| @@ -172,7 +173,6 @@ mod tests { | |||
| 172 | fn answer(question: &ExamQuestion, user: &UserId, selected: Option<usize>) -> ExamAnswer { | 173 | fn answer(question: &ExamQuestion, user: &UserId, selected: Option<usize>) -> ExamAnswer { |
| 173 | let selected = selected.map(|index| choice_id(question, index)); | 174 | let selected = selected.map(|index| choice_id(question, index)); |
| 174 | ExamAnswer { | 175 | ExamAnswer { |
| 175 | - id: ExamAnswerId::composite(question.get_id(), user, 1), | ||
| 176 | exam: question.get_exam().clone(), | 176 | exam: question.get_exam().clone(), |
| 177 | question: question.get_id().clone(), | 177 | question: question.get_id().clone(), |
| 178 | user: user.clone(), | 178 | user: user.clone(), |
| @@ -186,12 +186,12 @@ mod tests { | |||
| 186 | } | 186 | } |
| 187 | 187 | ||
| 188 | fn student() -> UserId { | 188 | fn student() -> UserId { |
| 189 | - UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA") | 189 | + UserId::from_key("0198f1a2-3b4c-7d5e-8f90-aa2b3c4d5e6f") |
| 190 | } | 190 | } |
| 191 | 191 | ||
| 192 | #[tokio::test] | 192 | #[tokio::test] |
| 193 | async fn seqs_key_distinct_rows_but_seq_one_keeps_the_bare_key() { | 193 | async fn seqs_key_distinct_rows_but_seq_one_keeps_the_bare_key() { |
| 194 | - let question = ExamQuestionId::from_key("01TESTQUESTIONAAAAAAAAAAAA"); | 194 | + let question = ExamQuestionId::from_key("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"); |
| 195 | let user = student(); | 195 | let user = student(); |
| 196 | // seq 1 keeps the pre-history bare `{question}_{user}` key… | 196 | // seq 1 keeps the pre-history bare `{question}_{user}` key… |
| 197 | let first = ExamAnswerId::composite(&question, &user, 1); | 197 | let first = ExamAnswerId::composite(&question, &user, 1); |
| @@ -215,7 +215,7 @@ mod tests { | |||
| 215 | 215 | ||
| 216 | #[tokio::test] | 216 | #[tokio::test] |
| 217 | async fn auto_score_counts_correct_choices_only() { | 217 | async fn auto_score_counts_correct_choices_only() { |
| 218 | - let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); | 218 | + let exam = ExamId::from_key("0198f1a2-3b4c-7d5e-8f90-be2b3c4d5e6f"); |
| 219 | let user = student(); | 219 | let user = student(); |
| 220 | let q1 = choice_question(&exam, 10, 0); // answered right | 220 | let q1 = choice_question(&exam, 10, 0); // answered right |
| 221 | let q2 = choice_question(&exam, 20, 1); // answered wrong | 221 | let q2 = choice_question(&exam, 20, 1); // answered wrong |
| @@ -233,14 +233,14 @@ mod tests { | |||
| 233 | #[tokio::test] | 233 | #[tokio::test] |
| 234 | async fn auto_score_of_nothing_is_zero() { | 234 | async fn auto_score_of_nothing_is_zero() { |
| 235 | assert_eq!(auto_score(&[], &[]), (0, 0)); | 235 | assert_eq!(auto_score(&[], &[]), (0, 0)); |
| 236 | - let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); | 236 | + let exam = ExamId::from_key("0198f1a2-3b4c-7d5e-8f90-be2b3c4d5e6f"); |
| 237 | let questions = vec![text_question(&exam, 50)]; | 237 | let questions = vec![text_question(&exam, 50)]; |
| 238 | assert_eq!(auto_score(&questions, &[]), (0, 0)); | 238 | assert_eq!(auto_score(&questions, &[]), (0, 0)); |
| 239 | } | 239 | } |
| 240 | 240 | ||
| 241 | #[tokio::test] | 241 | #[tokio::test] |
| 242 | async fn is_correct_judges_choice_questions_only() { | 242 | async fn is_correct_judges_choice_questions_only() { |
| 243 | - let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); | 243 | + let exam = ExamId::from_key("0198f1a2-3b4c-7d5e-8f90-be2b3c4d5e6f"); |
| 244 | let user = student(); | 244 | let user = student(); |
| 245 | let choice = choice_question(&exam, 10, 1); | 245 | let choice = choice_question(&exam, 10, 1); |
| 246 | assert_eq!( | 246 | assert_eq!( |
src/domain/exam_attempt.rsmodified+25 -27
| @@ -1,34 +1,32 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | - | ||
| 3 | -use crate::constant::EXAM_ATTEMPT_TABLE; | ||
| 4 | use crate::domain::exam::Exam; | 1 | use crate::domain::exam::Exam; |
| 5 | use crate::domain::exam::ExamId; | 2 | use crate::domain::exam::ExamId; |
| 6 | use crate::domain::key; | 3 | use crate::domain::key; |
| 7 | use crate::domain::timestamp::Timestamp; | 4 | use crate::domain::timestamp::Timestamp; |
| 8 | use crate::domain::user::UserId; | 5 | use crate::domain::user::UserId; |
| 9 | 6 | ||
| 10 | -/// A deterministic id for the (exam, user, seq) triple, so sitting `seq` | 7 | +/// The identity of one (exam, user, seq) triple, so sitting `seq` exists at |
| 11 | -/// exists at most once by construction — a concurrent double "start" races | 8 | +/// most once by construction — a concurrent double "start" races on the same |
| 12 | -/// on the same id and exactly one create wins. See [`key::sitting`] for the | 9 | +/// primary key and exactly one insert wins. See [`key::sitting`] for the wire |
| 13 | -/// key shape and why the first sitting stays bare. | 10 | +/// shape and why the first sitting stays bare. |
| 14 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 11 | +#[derive(Debug, Clone, PartialEq, Eq)] |
| 15 | -pub struct ExamAttemptId(RecordId); | 12 | +pub struct ExamAttemptId { |
| 13 | + pub(crate) exam: ExamId, | ||
| 14 | + pub(crate) user: UserId, | ||
| 15 | + pub(crate) seq: i64, | ||
| 16 | +} | ||
| 16 | 17 | ||
| 17 | impl ExamAttemptId { | 18 | impl ExamAttemptId { |
| 18 | pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self { | 19 | pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self { |
| 19 | - let key = key::sitting(exam.key(), user.key(), seq); | 20 | + Self { |
| 20 | - Self(RecordId::new(EXAM_ATTEMPT_TABLE, key)) | 21 | + exam: exam.clone(), |
| 21 | - } | 22 | + user: user.clone(), |
| 22 | - | 23 | + seq, |
| 23 | - pub fn record(&self) -> RecordId { | 24 | + } |
| 24 | - self.0.clone() | ||
| 25 | } | 25 | } |
| 26 | 26 | ||
| 27 | - pub fn key(&self) -> &str { | 27 | + /// The underscore-joined wire form (`{exam}_{user}[_{seq}]`). |
| 28 | - match &self.0.key { | 28 | + pub fn key(&self) -> String { |
| 29 | - RecordIdKey::String(key) => key, | 29 | + key::sitting(self.exam.key().as_str(), self.user.key().as_str(), self.seq) |
| 30 | - _ => "", | ||
| 31 | - } | ||
| 32 | } | 30 | } |
| 33 | } | 31 | } |
| 34 | 32 | ||
| @@ -60,12 +58,11 @@ impl AttemptStatus { | |||
| 60 | /// exam allows retakes; `left_at` marks a student who walked out of the exam | 58 | /// exam allows retakes; `left_at` marks a student who walked out of the exam |
| 61 | /// room mid-attempt. Grading stays a separate `exam_result` row. | 59 | /// room mid-attempt. Grading stays a separate `exam_result` row. |
| 62 | /// | 60 | /// |
| 63 | -/// Fields are crate-visible: [`crate::db::exam_attempt`] reads the id to | 61 | +/// Fields are crate-visible: [`crate::db::exam_attempt`] targets its |
| 64 | -/// target its field-scoped writes and [`crate::service::exam_attempt::start`] | 62 | +/// field-scoped writes by the primary-key triple and |
| 65 | -/// mints the rows on create. | 63 | +/// [`crate::service::exam_attempt::start`] mints the rows on create. |
| 66 | -#[derive(Debug, Clone, SurrealValue)] | 64 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 67 | pub struct ExamAttempt { | 65 | pub struct ExamAttempt { |
| 68 | - pub(crate) id: ExamAttemptId, | ||
| 69 | pub(crate) exam: ExamId, | 66 | pub(crate) exam: ExamId, |
| 70 | pub(crate) user: UserId, | 67 | pub(crate) user: UserId, |
| 71 | pub(crate) seq: i64, | 68 | pub(crate) seq: i64, |
| @@ -75,8 +72,9 @@ pub struct ExamAttempt { | |||
| 75 | } | 72 | } |
| 76 | 73 | ||
| 77 | impl ExamAttempt { | 74 | impl ExamAttempt { |
| 78 | - pub fn get_id(&self) -> &ExamAttemptId { | 75 | + /// The row's identity, built back from its primary-key columns. |
| 79 | - &self.id | 76 | + pub fn get_id(&self) -> ExamAttemptId { |
| 77 | + ExamAttemptId::composite(&self.exam, &self.user, self.seq) | ||
| 80 | } | 78 | } |
| 81 | 79 | ||
| 82 | pub fn get_exam(&self) -> &ExamId { | 80 | pub fn get_exam(&self) -> &ExamId { |
src/domain/exam_question.rsmodified+53 -49
| @@ -1,47 +1,43 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | +use sqlx::types::Json; |
| 2 | -use ulid::Ulid; | ||
| 3 | 2 | ||
| 4 | use crate::constant::{ | 3 | use crate::constant::{ |
| 5 | - EXAM_QUESTION_TABLE, MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, | 4 | + MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, |
| 6 | MIN_QUESTION_CHOICES, | 5 | MIN_QUESTION_CHOICES, |
| 7 | }; | 6 | }; |
| 8 | use crate::domain::bank_question::BankQuestionId; | 7 | use crate::domain::bank_question::BankQuestionId; |
| 9 | use crate::domain::exam::ExamId; | 8 | use crate::domain::exam::ExamId; |
| 10 | -use crate::domain::monotonic_id::next_ulid; | 9 | +use crate::domain::monotonic_id::next_uuid; |
| 11 | use crate::domain::subject::SubjectId; | 10 | use crate::domain::subject::SubjectId; |
| 12 | use crate::error::ValidationError; | 11 | use crate::error::ValidationError; |
| 13 | use crate::validate::{validate_question_kind, validate_question_points, validate_required}; | 12 | use crate::validate::{validate_question_kind, validate_question_points, validate_required}; |
| 14 | 13 | ||
| 15 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 14 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 16 | -pub struct ExamQuestionId(RecordId); | 15 | +#[sqlx(transparent)] |
| 16 | +pub struct ExamQuestionId(uuid::Uuid); | ||
| 17 | 17 | ||
| 18 | impl ExamQuestionId { | 18 | impl ExamQuestionId { |
| 19 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: the | 19 | + /// Minted from the process-wide monotonic generator, not a plain random |
| 20 | - /// id *is* the question's presentation order | 20 | + /// UUID: the id *is* the question's presentation order |
| 21 | /// ([`crate::db::exam_question::list_for_exam`] | 21 | /// ([`crate::db::exam_question::list_for_exam`] |
| 22 | /// sorts `id ASC`), and a random low half scrambles a burst of saves that | 22 | /// sorts `id ASC`), and a random low half scrambles a burst of saves that |
| 23 | /// lands inside one millisecond. | 23 | /// lands inside one millisecond. |
| 24 | pub fn generate() -> Self { | 24 | pub fn generate() -> Self { |
| 25 | - Self(RecordId::new(EXAM_QUESTION_TABLE, next_ulid().to_string())) | 25 | + Self(next_uuid()) |
| 26 | } | 26 | } |
| 27 | 27 | ||
| 28 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 29 | + /// which matches no row. | ||
| 28 | pub fn from_key(key: &str) -> Self { | 30 | pub fn from_key(key: &str) -> Self { |
| 29 | - Self(RecordId::new(EXAM_QUESTION_TABLE, key)) | 31 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 30 | } | 32 | } |
| 31 | 33 | ||
| 32 | - pub fn record(&self) -> RecordId { | 34 | + pub fn key(&self) -> String { |
| 33 | - self.0.clone() | 35 | + self.0.to_string() |
| 34 | - } | ||
| 35 | - | ||
| 36 | - pub fn key(&self) -> &str { | ||
| 37 | - match &self.0.key { | ||
| 38 | - RecordIdKey::String(key) => key, | ||
| 39 | - _ => "", | ||
| 40 | - } | ||
| 41 | } | 36 | } |
| 42 | } | 37 | } |
| 43 | 38 | ||
| 44 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 39 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 40 | +#[sqlx(transparent)] | ||
| 45 | pub struct QuestionText(String); | 41 | pub struct QuestionText(String); |
| 46 | 42 | ||
| 47 | impl QuestionText { | 43 | impl QuestionText { |
| @@ -57,7 +53,8 @@ impl QuestionText { | |||
| 57 | 53 | ||
| 58 | /// A validated question kind: `choice` (pick one option, auto-scorable) or | 54 | /// A validated question kind: `choice` (pick one option, auto-scorable) or |
| 59 | /// `text` (free text, judged by the grader). | 55 | /// `text` (free text, judged by the grader). |
| 60 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 56 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 57 | +#[sqlx(transparent)] | ||
| 61 | pub struct QuestionKind(String); | 58 | pub struct QuestionKind(String); |
| 62 | 59 | ||
| 63 | impl QuestionKind { | 60 | impl QuestionKind { |
| @@ -73,7 +70,8 @@ impl QuestionKind { | |||
| 73 | 70 | ||
| 74 | /// A validated question weight in the auto-score, held to | 71 | /// A validated question weight in the auto-score, held to |
| 75 | /// `[MIN_QUESTION_POINTS, MAX_QUESTION_POINTS]`. | 72 | /// `[MIN_QUESTION_POINTS, MAX_QUESTION_POINTS]`. |
| 76 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | 73 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] |
| 74 | +#[sqlx(transparent)] | ||
| 77 | pub struct QuestionPoints(i64); | 75 | pub struct QuestionPoints(i64); |
| 78 | 76 | ||
| 79 | impl QuestionPoints { | 77 | impl QuestionPoints { |
| @@ -88,7 +86,8 @@ impl QuestionPoints { | |||
| 88 | } | 86 | } |
| 89 | 87 | ||
| 90 | /// One option's text: non-blank, at most `MAX_CHOICE_TEXT_LEN` characters. | 88 | /// One option's text: non-blank, at most `MAX_CHOICE_TEXT_LEN` characters. |
| 91 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 89 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type, serde::Serialize, serde::Deserialize)] |
| 90 | +#[sqlx(transparent)] | ||
| 92 | pub struct ChoiceText(String); | 91 | pub struct ChoiceText(String); |
| 93 | 92 | ||
| 94 | impl ChoiceText { | 93 | impl ChoiceText { |
| @@ -102,8 +101,8 @@ impl ChoiceText { | |||
| 102 | } | 101 | } |
| 103 | } | 102 | } |
| 104 | 103 | ||
| 105 | -/// An option's stable identity — a server-minted ULID, never reused, never | 104 | +/// An option's stable identity — a server-minted UUID, never reused, never |
| 106 | -/// taken from client input (it becomes part of an image row's record id and of | 105 | +/// taken from client input (it becomes part of an image row's slot key and of |
| 107 | /// a URL path, so a client-shaped value would be an injection surface). | 106 | /// a URL path, so a client-shaped value would be an injection surface). |
| 108 | /// | 107 | /// |
| 109 | /// This id is the whole point of the choice remodel. `correct`, the per-option | 108 | /// This id is the whole point of the choice remodel. `correct`, the per-option |
| @@ -111,15 +110,19 @@ impl ChoiceText { | |||
| 111 | /// reordering the list or deleting an option moves none of them. They used to | 110 | /// reordering the list or deleting an option moves none of them. They used to |
| 112 | /// be parallel arrays keyed by position, where any edit to the list silently | 111 | /// be parallel arrays keyed by position, where any edit to the list silently |
| 113 | /// re-pointed the others. | 112 | /// re-pointed the others. |
| 114 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 113 | +/// |
| 114 | +/// Stored as a bare string: it travels inside the choices JSON and names a | ||
| 115 | +/// slot in the image tables' `TEXT` columns. | ||
| 116 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type, serde::Serialize, serde::Deserialize)] | ||
| 117 | +#[sqlx(transparent)] | ||
| 115 | pub struct ChoiceId(String); | 118 | pub struct ChoiceId(String); |
| 116 | 119 | ||
| 117 | impl ChoiceId { | 120 | impl ChoiceId { |
| 118 | - /// Plain `Ulid::generate()` deliberately: options are ordered by their position | 121 | + /// Plain `Uuid::new_v4()` deliberately: options are ordered by their |
| 119 | - /// in the stored `Vec`, never by id, so nothing here reads the id as a | 122 | + /// position in the stored `Vec`, never by id, so nothing here reads the id |
| 120 | - /// clock — it only has to be unique. | 123 | + /// as a clock — it only has to be unique. |
| 121 | fn generate() -> Self { | 124 | fn generate() -> Self { |
| 122 | - Self(Ulid::generate().to_string()) | 125 | + Self(uuid::Uuid::new_v4().to_string()) |
| 123 | } | 126 | } |
| 124 | 127 | ||
| 125 | pub fn as_str(&self) -> &str { | 128 | pub fn as_str(&self) -> &str { |
| @@ -127,8 +130,9 @@ impl ChoiceId { | |||
| 127 | } | 130 | } |
| 128 | } | 131 | } |
| 129 | 132 | ||
| 130 | -/// One option of a choice question: its identity plus its text. | 133 | +/// One option of a choice question: its identity plus its text. Stored inside |
| 131 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 134 | +/// the `choices` JSONB column, in list order. |
| 135 | +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] | ||
| 132 | pub struct Choice { | 136 | pub struct Choice { |
| 133 | id: ChoiceId, | 137 | id: ChoiceId, |
| 134 | text: ChoiceText, | 138 | text: ChoiceText, |
| @@ -277,12 +281,12 @@ impl QuestionSpec { | |||
| 277 | } | 281 | } |
| 278 | } | 282 | } |
| 279 | 283 | ||
| 280 | -/// One question of an exam. Order within the exam is the id's ULID order | 284 | +/// One question of an exam. Order within the exam is the id's creation order; |
| 281 | -/// (creation order); the kind-dependent columns always satisfy the | 285 | +/// the kind-dependent columns always satisfy the |
| 282 | /// [`QuestionSpec`] invariants because every write goes through one. Every | 286 | /// [`QuestionSpec`] invariants because every write goes through one. Every |
| 283 | /// question links to a subject of the exam's course — the handlers verify the | 287 | /// question links to a subject of the exam's course — the handlers verify the |
| 284 | /// subject's course matches before any write. | 288 | /// subject's course matches before any write. |
| 285 | -#[derive(Debug, Clone, SurrealValue)] | 289 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 286 | pub struct ExamQuestion { | 290 | pub struct ExamQuestion { |
| 287 | pub(crate) id: ExamQuestionId, | 291 | pub(crate) id: ExamQuestionId, |
| 288 | pub(crate) exam: ExamId, | 292 | pub(crate) exam: ExamId, |
| @@ -290,11 +294,10 @@ pub struct ExamQuestion { | |||
| 290 | pub(crate) text: QuestionText, | 294 | pub(crate) text: QuestionText, |
| 291 | pub(crate) kind: QuestionKind, | 295 | pub(crate) kind: QuestionKind, |
| 292 | pub(crate) points: QuestionPoints, | 296 | pub(crate) points: QuestionPoints, |
| 293 | - pub(crate) choices: Option<Vec<Choice>>, | 297 | + pub(crate) choices: Option<Json<Vec<Choice>>>, |
| 294 | pub(crate) correct: Option<ChoiceId>, | 298 | pub(crate) correct: Option<ChoiceId>, |
| 295 | /// The bank template this question was created *from*, if it was inserted | 299 | /// The bank template this question was created *from*, if it was inserted |
| 296 | /// out of the bank. Written once, at insert. | 300 | /// out of the bank. Written once, at insert. |
| 297 | - #[surreal(default)] | ||
| 298 | pub(crate) from_bank: Option<BankQuestionId>, | 301 | pub(crate) from_bank: Option<BankQuestionId>, |
| 299 | /// The bank template most recently created *by saving this question* into | 302 | /// The bank template most recently created *by saving this question* into |
| 300 | /// the bank, if any. Written by | 303 | /// the bank, if any. Written by |
| @@ -302,7 +305,6 @@ pub struct ExamQuestion { | |||
| 302 | /// repeat save. Never set by an insert-from-bank: the two directions are | 305 | /// repeat save. Never set by an insert-from-bank: the two directions are |
| 303 | /// separate columns precisely so "came from the bank" can't be misread as | 306 | /// separate columns precisely so "came from the bank" can't be misread as |
| 304 | /// "already saved to the bank". | 307 | /// "already saved to the bank". |
| 305 | - #[surreal(default)] | ||
| 306 | pub(crate) banked_as: Option<BankQuestionId>, | 308 | pub(crate) banked_as: Option<BankQuestionId>, |
| 307 | } | 309 | } |
| 308 | 310 | ||
| @@ -332,7 +334,7 @@ impl ExamQuestion { | |||
| 332 | } | 334 | } |
| 333 | 335 | ||
| 334 | pub fn get_choices(&self) -> Option<&[Choice]> { | 336 | pub fn get_choices(&self) -> Option<&[Choice]> { |
| 335 | - self.choices.as_deref() | 337 | + self.choices.as_ref().map(|json| json.0.as_slice()) |
| 336 | } | 338 | } |
| 337 | 339 | ||
| 338 | pub fn get_correct(&self) -> Option<&ChoiceId> { | 340 | pub fn get_correct(&self) -> Option<&ChoiceId> { |
| @@ -352,7 +354,7 @@ impl ExamQuestion { | |||
| 352 | pub fn spec(&self) -> QuestionSpec { | 354 | pub fn spec(&self) -> QuestionSpec { |
| 353 | QuestionSpec::from_stored( | 355 | QuestionSpec::from_stored( |
| 354 | self.kind.clone(), | 356 | self.kind.clone(), |
| 355 | - self.choices.clone(), | 357 | + self.choices.as_ref().map(|json| json.0.clone()), |
| 356 | self.correct.clone(), | 358 | self.correct.clone(), |
| 357 | ) | 359 | ) |
| 358 | } | 360 | } |
| @@ -367,7 +369,7 @@ impl ExamQuestion { | |||
| 367 | text: QuestionText::try_new(text).unwrap(), | 369 | text: QuestionText::try_new(text).unwrap(), |
| 368 | points: QuestionPoints::try_new(points).unwrap(), | 370 | points: QuestionPoints::try_new(points).unwrap(), |
| 369 | kind: spec.kind, | 371 | kind: spec.kind, |
| 370 | - choices: spec.choices, | 372 | + choices: spec.choices.map(Json), |
| 371 | correct: spec.correct, | 373 | correct: spec.correct, |
| 372 | from_bank: None, | 374 | from_bank: None, |
| 373 | banked_as: None, | 375 | banked_as: None, |
| @@ -407,13 +409,13 @@ mod tests { | |||
| 407 | 409 | ||
| 408 | /// A teacher saving several questions back to back gets them back in that | 410 | /// A teacher saving several questions back to back gets them back in that |
| 409 | /// order: `list_for_exam` sorts `id ASC`, so the ids minted inside one | 411 | /// order: `list_for_exam` sorts `id ASC`, so the ids minted inside one |
| 410 | - /// millisecond have to sort in mint order. Revert `generate` to | 412 | + /// millisecond have to sort in mint order. Revert `generate` to a plain |
| 411 | - /// `Ulid::generate()` and this fails — the low 80 bits are redrawn per id, so a | 413 | + /// random UUID and this fails — the random bits are redrawn per id, so a |
| 412 | /// same-tick burst comes out shuffled. | 414 | /// same-tick burst comes out shuffled. |
| 413 | #[tokio::test] | 415 | #[tokio::test] |
| 414 | async fn ids_sort_in_creation_order() { | 416 | async fn ids_sort_in_creation_order() { |
| 415 | let ids: Vec<String> = (0..500) | 417 | let ids: Vec<String> = (0..500) |
| 416 | - .map(|_| ExamQuestionId::generate().key().to_string()) | 418 | + .map(|_| ExamQuestionId::generate().key()) |
| 417 | .collect(); | 419 | .collect(); |
| 418 | let mut sorted = ids.clone(); | 420 | let mut sorted = ids.clone(); |
| 419 | sorted.sort(); | 421 | sorted.sort(); |
| @@ -491,8 +493,8 @@ mod tests { | |||
| 491 | let built = spec(two_choices(), Some("b")).unwrap(); | 493 | let built = spec(two_choices(), Some("b")).unwrap(); |
| 492 | let (_, choices, correct) = built.into_parts(); | 494 | let (_, choices, correct) = built.into_parts(); |
| 493 | let choices = choices.unwrap(); | 495 | let choices = choices.unwrap(); |
| 494 | - // Client labels never reach storage. | 496 | + // Client labels never reach storage; a minted id is a hyphenated UUID. |
| 495 | - assert!(choices.iter().all(|c| c.get_id().as_str().len() == 26)); | 497 | + assert!(choices.iter().all(|c| c.get_id().as_str().len() == 36)); |
| 496 | assert_ne!(choices[0].get_id(), choices[1].get_id()); | 498 | assert_ne!(choices[0].get_id(), choices[1].get_id()); |
| 497 | // `correct` resolved to the *second* option's minted id, by label. | 499 | // `correct` resolved to the *second* option's minted id, by label. |
| 498 | assert_eq!(correct.as_ref(), Some(choices[1].get_id())); | 500 | assert_eq!(correct.as_ref(), Some(choices[1].get_id())); |
| @@ -579,7 +581,7 @@ mod tests { | |||
| 579 | use proptest::prelude::*; | 581 | use proptest::prelude::*; |
| 580 | 582 | ||
| 581 | /// A stored question's options, built the only way they can be: through | 583 | /// A stored question's options, built the only way they can be: through |
| 582 | - /// `try_new` on create, so the ids are real minted ULIDs. | 584 | + /// `try_new` on create, so the ids are real minted UUIDs. |
| 583 | fn stored_set(n: usize) -> Vec<Choice> { | 585 | fn stored_set(n: usize) -> Vec<Choice> { |
| 584 | let inputs = (0..n) | 586 | let inputs = (0..n) |
| 585 | .map(|i| ChoiceInput { | 587 | .map(|i| ChoiceInput { |
| @@ -604,19 +606,21 @@ mod tests { | |||
| 604 | } | 606 | } |
| 605 | 607 | ||
| 606 | fn key() -> impl Strategy<Value = Key> { | 608 | fn key() -> impl Strategy<Value = Key> { |
| 609 | + use proptest::prelude::*; | ||
| 607 | prop_oneof![ | 610 | prop_oneof![ |
| 608 | 4 => (0usize..10).prop_map(Key::Stored), | 611 | 4 => (0usize..10).prop_map(Key::Stored), |
| 609 | 3 => prop_oneof![ | 612 | 3 => prop_oneof![ |
| 610 | Just(String::new()), | 613 | Just(String::new()), |
| 611 | Just("new:1".to_string()), | 614 | Just("new:1".to_string()), |
| 612 | "[a-z0-9]{1,5}", | 615 | "[a-z0-9]{1,5}", |
| 613 | - Just("01ARZ3NDEKTSV4RRFFQ69G5FAV".to_string()), | 616 | + Just("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f".to_string()), |
| 614 | ].prop_map(Key::Other), | 617 | ].prop_map(Key::Other), |
| 615 | 1 => Just(Key::Null), | 618 | 1 => Just(Key::Null), |
| 616 | ] | 619 | ] |
| 617 | } | 620 | } |
| 618 | 621 | ||
| 619 | fn text() -> impl Strategy<Value = String> { | 622 | fn text() -> impl Strategy<Value = String> { |
| 623 | + use proptest::prelude::*; | ||
| 620 | prop_oneof![ | 624 | prop_oneof![ |
| 621 | 6 => "[a-z ]{1,6}", | 625 | 6 => "[a-z ]{1,6}", |
| 622 | 1 => Just(String::new()), | 626 | 1 => Just(String::new()), |
| @@ -691,7 +695,7 @@ mod tests { | |||
| 691 | // freshly minted, so it can never take over a stored | 695 | // freshly minted, so it can never take over a stored |
| 692 | // option's identity or its picture. | 696 | // option's identity or its picture. |
| 693 | None => { | 697 | None => { |
| 694 | - prop_assert_eq!(choice.id.as_str().len(), 26); | 698 | + prop_assert_eq!(choice.id.as_str().len(), 36); |
| 695 | prop_assert!(!stored_ids.contains(&choice.id.as_str())); | 699 | prop_assert!(!stored_ids.contains(&choice.id.as_str())); |
| 696 | } | 700 | } |
| 697 | } | 701 | } |
src/domain/exam_result.rsmodified+63 -41
| @@ -1,8 +1,5 @@ | |||
| 1 | use std::collections::HashMap; | 1 | use std::collections::HashMap; |
| 2 | 2 | ||
| 3 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 4 | - | ||
| 5 | -use crate::constant::{EXAM_RESULT_TABLE, KIND_REF_TABLE}; | ||
| 6 | use crate::domain::exam::ExamId; | 3 | use crate::domain::exam::ExamId; |
| 7 | use crate::domain::key; | 4 | use crate::domain::key; |
| 8 | use crate::domain::user::UserId; | 5 | use crate::domain::user::UserId; |
| @@ -16,19 +13,11 @@ pub(crate) fn draft_error() -> AppError { | |||
| 16 | AppError::Conflict("this exam is a draft — publish it before grading") | 13 | AppError::Conflict("this exam is a draft — publish it before grading") |
| 17 | } | 14 | } |
| 18 | 15 | ||
| 19 | -/// The reference counter for one exam kind — how many marks are written under | ||
| 20 | -/// that name, and whether the school has retired it (see | ||
| 21 | -/// [`crate::db::cap`]). Keyed by the name itself: the kind is snapshotted | ||
| 22 | -/// text on the exam, and this row is what makes "a kind nothing is graded under | ||
| 23 | -/// may be removed" a decision the database takes, not a count a concurrent mark | ||
| 24 | -/// can invalidate. | ||
| 25 | -pub(crate) fn kind_ref(kind: &str) -> RecordId { | ||
| 26 | - RecordId::new(KIND_REF_TABLE, kind) | ||
| 27 | -} | ||
| 28 | - | ||
| 29 | /// The refusal a mark meets once its kind has left the school's list. The | 16 | /// The refusal a mark meets once its kind has left the school's list. The |
| 30 | /// mirror of the settings-side 409: whichever of the two writes reaches the | 17 | /// mirror of the settings-side 409: whichever of the two writes reaches the |
| 31 | -/// counter first, the other is told the name is no longer usable. | 18 | +/// counter row (`kind_ref`) first, the other is told the name is no longer |
| 19 | +/// usable. The ref-row key is the kind's own name — a `TEXT` primary key, | ||
| 20 | +/// like the settings singleton. | ||
| 32 | pub(crate) fn retired_kind_error(kind: &str) -> AppError { | 21 | pub(crate) fn retired_kind_error(kind: &str) -> AppError { |
| 33 | AppError::ConflictOwned(format!( | 22 | AppError::ConflictOwned(format!( |
| 34 | "the '{kind}' exam kind has been removed from the school's settings — \ | 23 | "the '{kind}' exam kind has been removed from the school's settings — \ |
| @@ -36,34 +25,37 @@ pub(crate) fn retired_kind_error(kind: &str) -> AppError { | |||
| 36 | )) | 25 | )) |
| 37 | } | 26 | } |
| 38 | 27 | ||
| 39 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 28 | +/// The identity of one (exam, user, seq) triple — one mark row per sitting, |
| 40 | -pub struct ExamResultId(RecordId); | 29 | +/// so grading is a single atomic UPSERT on the composite primary key with no |
| 30 | +/// find-then-insert race. See [`key::sitting`] for the wire shape and why the | ||
| 31 | +/// first sitting stays bare. | ||
| 32 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 33 | +pub struct ExamResultId { | ||
| 34 | + pub(crate) exam: ExamId, | ||
| 35 | + pub(crate) user: UserId, | ||
| 36 | + pub(crate) seq: i64, | ||
| 37 | +} | ||
| 41 | 38 | ||
| 42 | impl ExamResultId { | 39 | impl ExamResultId { |
| 43 | - /// A deterministic id for the (exam, user, seq) triple — one mark row per | ||
| 44 | - /// sitting, so grading is a single atomic UPSERT with no find-then-insert | ||
| 45 | - /// race. See [`key::sitting`] for the key shape and why the first sitting | ||
| 46 | - /// stays bare. | ||
| 47 | pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self { | 40 | pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self { |
| 48 | - let key = key::sitting(exam.key(), user.key(), seq); | 41 | + Self { |
| 49 | - Self(RecordId::new(EXAM_RESULT_TABLE, key)) | 42 | + exam: exam.clone(), |
| 50 | - } | 43 | + user: user.clone(), |
| 51 | - | 44 | + seq, |
| 52 | - pub fn record(&self) -> RecordId { | 45 | + } |
| 53 | - self.0.clone() | ||
| 54 | } | 46 | } |
| 55 | 47 | ||
| 56 | - pub fn key(&self) -> &str { | 48 | + /// The underscore-joined wire form (`{exam}_{user}[_{seq}]`). |
| 57 | - match &self.0.key { | 49 | + pub fn key(&self) -> String { |
| 58 | - RecordIdKey::String(key) => key, | 50 | + key::sitting(self.exam.key().as_str(), self.user.key().as_str(), self.seq) |
| 59 | - _ => "", | ||
| 60 | - } | ||
| 61 | } | 51 | } |
| 62 | } | 52 | } |
| 63 | 53 | ||
| 64 | -/// A validated exam mark. Stored as an `int`, held to `[MIN_MARK, MAX_MARK]`. | 54 | +/// A validated exam mark. Stored as a `BIGINT`, held to |
| 55 | +/// `[MIN_MARK, MAX_MARK]`. | ||
| 65 | /// Kept in its own row — an exam result is never a course note. | 56 | /// Kept in its own row — an exam result is never a course note. |
| 66 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | 57 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] |
| 58 | +#[sqlx(transparent)] | ||
| 67 | pub struct Mark(i64); | 59 | pub struct Mark(i64); |
| 68 | 60 | ||
| 69 | impl Mark { | 61 | impl Mark { |
| @@ -77,9 +69,8 @@ impl Mark { | |||
| 77 | } | 69 | } |
| 78 | } | 70 | } |
| 79 | 71 | ||
| 80 | -#[derive(Debug, Clone, SurrealValue)] | 72 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 81 | pub struct ExamResult { | 73 | pub struct ExamResult { |
| 82 | - pub(crate) id: ExamResultId, | ||
| 83 | pub(crate) exam: ExamId, | 74 | pub(crate) exam: ExamId, |
| 84 | pub(crate) user: UserId, | 75 | pub(crate) user: UserId, |
| 85 | pub(crate) seq: i64, | 76 | pub(crate) seq: i64, |
| @@ -88,8 +79,9 @@ pub struct ExamResult { | |||
| 88 | } | 79 | } |
| 89 | 80 | ||
| 90 | impl ExamResult { | 81 | impl ExamResult { |
| 91 | - pub fn get_id(&self) -> &ExamResultId { | 82 | + /// The row's identity, built back from its primary-key columns. |
| 92 | - &self.id | 83 | + pub fn get_id(&self) -> ExamResultId { |
| 84 | + ExamResultId::composite(&self.exam, &self.user, self.seq) | ||
| 93 | } | 85 | } |
| 94 | 86 | ||
| 95 | pub fn get_exam(&self) -> &ExamId { | 87 | pub fn get_exam(&self) -> &ExamId { |
| @@ -117,14 +109,14 @@ impl ExamResult { | |||
| 117 | /// The latest-seq mark per (exam, user) pair, preserving the outer list's | 109 | /// The latest-seq mark per (exam, user) pair, preserving the outer list's |
| 118 | /// row order (first appearance of each pair). Grade-of-record is the latest | 110 | /// row order (first appearance of each pair). Grade-of-record is the latest |
| 119 | /// attempt's mark, so a pair with retakes collapses to its highest seq. Done | 111 | /// attempt's mark, so a pair with retakes collapses to its highest seq. Done |
| 120 | -/// in Rust rather than SQL: SurrealDB's `GROUP BY` can't return the whole | 112 | +/// in Rust rather than SQL: it keeps the outer ordering stable without a |
| 121 | -/// row that carries the max, and id-order can't stand in for seq-order once | 113 | +/// window-function dance, and id order can't stand in for seq order once seq |
| 122 | -/// seq reaches two digits. | 114 | +/// reaches two digits. |
| 123 | pub(crate) fn latest_per_pair(rows: Vec<ExamResult>) -> Vec<ExamResult> { | 115 | pub(crate) fn latest_per_pair(rows: Vec<ExamResult>) -> Vec<ExamResult> { |
| 124 | let mut order: Vec<(String, String)> = Vec::new(); | 116 | let mut order: Vec<(String, String)> = Vec::new(); |
| 125 | let mut best: HashMap<(String, String), ExamResult> = HashMap::new(); | 117 | let mut best: HashMap<(String, String), ExamResult> = HashMap::new(); |
| 126 | for row in rows { | 118 | for row in rows { |
| 127 | - let key = (row.exam.key().to_string(), row.user.key().to_string()); | 119 | + let key = (row.exam.key(), row.user.key()); |
| 128 | match best.get(&key) { | 120 | match best.get(&key) { |
| 129 | Some(existing) if existing.seq >= row.seq => {} | 121 | Some(existing) if existing.seq >= row.seq => {} |
| 130 | Some(_) => { | 122 | Some(_) => { |
| @@ -153,4 +145,34 @@ mod tests { | |||
| 153 | assert!(Mark::try_new(-1).is_err()); | 145 | assert!(Mark::try_new(-1).is_err()); |
| 154 | assert!(Mark::try_new(101).is_err()); | 146 | assert!(Mark::try_new(101).is_err()); |
| 155 | } | 147 | } |
| 148 | + | ||
| 149 | + /// Grade-of-record: a pair with retakes collapses to its highest seq, and | ||
| 150 | + /// the outer list keeps its row order. | ||
| 151 | + #[tokio::test] | ||
| 152 | + async fn latest_per_pair_keeps_the_highest_seq_in_first_seen_order() { | ||
| 153 | + let exam_of = |n: u16| ExamId::from_key(&format!("0198f1a2-0000-7000-8000-{n:012x}")); | ||
| 154 | + let user_of = |n: u16| UserId::from_key(&format!("0198f1a2-1111-7000-8000-{n:012x}")); | ||
| 155 | + let (exam, user, other) = (exam_of(1), user_of(1), user_of(2)); | ||
| 156 | + let row = |user: UserId, seq: i64, mark: i64| ExamResult { | ||
| 157 | + exam: exam.clone(), | ||
| 158 | + user, | ||
| 159 | + seq, | ||
| 160 | + mark: Mark::try_new(mark).unwrap(), | ||
| 161 | + graded_by: user_of(9), | ||
| 162 | + }; | ||
| 163 | + | ||
| 164 | + let got = latest_per_pair(vec![ | ||
| 165 | + row(user.clone(), 1, 60), | ||
| 166 | + row(other.clone(), 1, 70), | ||
| 167 | + row(user.clone(), 2, 85), // retake outranks the seq-1 mark | ||
| 168 | + row(other, 3, 40), // third sitting of the second pair | ||
| 169 | + ]); | ||
| 170 | + assert_eq!(got.len(), 2); | ||
| 171 | + assert_eq!(got[0].get_user(), &user); | ||
| 172 | + assert_eq!(got[0].get_seq(), 2); | ||
| 173 | + assert_eq!(got[0].get_mark().as_i64(), 85); | ||
| 174 | + assert_eq!(got[1].get_user(), &other); | ||
| 175 | + assert_eq!(got[1].get_seq(), 3); | ||
| 176 | + assert_eq!(got[1].get_mark().as_i64(), 40); | ||
| 177 | + } | ||
| 156 | } | 178 | } |
src/domain/fee_plan.rsmodified+38 -25
| @@ -4,51 +4,47 @@ | |||
| 4 | //! | 4 | //! |
| 5 | //! The installments are **embedded** on the plan row rather than child rows: | 5 | //! The installments are **embedded** on the plan row rather than child rows: |
| 6 | //! a charge line copies the amount and due date it was assigned at, so the | 6 | //! a charge line copies the amount and due date it was assigned at, so the |
| 7 | -//! installment is a template, never a thing that has to be joined back to. No | 7 | +//! installment is a template, never a thing that has to be joined back to. |
| 8 | -//! field inside the object is optional — SurrealDB 3 drops an object key whose | 8 | +//! The embedded list rides a `JSONB` column in stored order. |
| 9 | -//! value is `NONE`, which would make the stored shape differ from the written | ||
| 10 | -//! one. | ||
| 11 | //! | 9 | //! |
| 12 | //! Due dates may be in the **past**: a school adopting the app mid-year | 10 | //! Due dates may be in the **past**: a school adopting the app mid-year |
| 13 | //! legitimately assigns a plan whose first installments were already due, so | 11 | //! legitimately assigns a plan whose first installments were already due, so |
| 14 | //! the no-past rule that guards exams, lessons and events deliberately does not | 12 | //! the no-past rule that guards exams, lessons and events deliberately does not |
| 15 | //! apply here. | 13 | //! apply here. |
| 16 | 14 | ||
| 17 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 15 | +use sqlx::types::Json; |
| 18 | 16 | ||
| 19 | -use crate::constant::{FEE_PLAN_TABLE, MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN}; | 17 | +use crate::constant::{MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN}; |
| 20 | -use crate::domain::monotonic_id::next_ulid; | 18 | +use crate::domain::monotonic_id::next_uuid; |
| 21 | use crate::domain::payment_ledger::LedgerAmount; | 19 | use crate::domain::payment_ledger::LedgerAmount; |
| 22 | use crate::domain::timestamp::Timestamp; | 20 | use crate::domain::timestamp::Timestamp; |
| 23 | use crate::domain::user::UserId; | 21 | use crate::domain::user::UserId; |
| 24 | use crate::error::ValidationError; | 22 | use crate::error::ValidationError; |
| 25 | use crate::validate::validate_required; | 23 | use crate::validate::validate_required; |
| 26 | 24 | ||
| 27 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 25 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 28 | -pub struct FeePlanId(RecordId); | 26 | +#[sqlx(transparent)] |
| 27 | +pub struct FeePlanId(uuid::Uuid); | ||
| 29 | 28 | ||
| 30 | impl FeePlanId { | 29 | impl FeePlanId { |
| 30 | + /// A write-ordered id: plan listings read newest first. | ||
| 31 | pub fn generate() -> Self { | 31 | pub fn generate() -> Self { |
| 32 | - Self(RecordId::new(FEE_PLAN_TABLE, next_ulid().to_string())) | 32 | + Self(next_uuid()) |
| 33 | } | 33 | } |
| 34 | 34 | ||
| 35 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 36 | + /// which matches no row. | ||
| 35 | pub fn from_key(key: &str) -> Self { | 37 | pub fn from_key(key: &str) -> Self { |
| 36 | - Self(RecordId::new(FEE_PLAN_TABLE, key)) | 38 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 37 | } | 39 | } |
| 38 | 40 | ||
| 39 | - pub fn record(&self) -> RecordId { | 41 | + pub fn key(&self) -> String { |
| 40 | - self.0.clone() | 42 | + self.0.to_string() |
| 41 | - } | ||
| 42 | - | ||
| 43 | - pub fn key(&self) -> &str { | ||
| 44 | - match &self.0.key { | ||
| 45 | - RecordIdKey::String(key) => key, | ||
| 46 | - _ => "", | ||
| 47 | - } | ||
| 48 | } | 43 | } |
| 49 | } | 44 | } |
| 50 | 45 | ||
| 51 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 46 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 47 | +#[sqlx(transparent)] | ||
| 52 | pub struct FeePlanName(String); | 48 | pub struct FeePlanName(String); |
| 53 | 49 | ||
| 54 | impl FeePlanName { | 50 | impl FeePlanName { |
| @@ -64,8 +60,8 @@ impl FeePlanName { | |||
| 64 | } | 60 | } |
| 65 | 61 | ||
| 66 | /// One instalment of a plan: what is owed, and when it falls due. Both fields | 62 | /// One instalment of a plan: what is owed, and when it falls due. Both fields |
| 67 | -/// are required — see the module doc on `NONE` keys. | 63 | +/// are required, so the stored JSON shape always matches the written one. |
| 68 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 64 | +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 69 | pub struct Installment { | 65 | pub struct Installment { |
| 70 | amount_minor: LedgerAmount, | 66 | amount_minor: LedgerAmount, |
| 71 | due_at: Timestamp, | 67 | due_at: Timestamp, |
| @@ -101,11 +97,11 @@ pub fn validate_installments(installments: &[Installment]) -> Result<(), Validat | |||
| 101 | Ok(()) | 97 | Ok(()) |
| 102 | } | 98 | } |
| 103 | 99 | ||
| 104 | -#[derive(Debug, Clone, SurrealValue)] | 100 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 105 | pub struct FeePlan { | 101 | pub struct FeePlan { |
| 106 | pub(crate) id: FeePlanId, | 102 | pub(crate) id: FeePlanId, |
| 107 | pub(crate) name: FeePlanName, | 103 | pub(crate) name: FeePlanName, |
| 108 | - pub(crate) installments: Vec<Installment>, | 104 | + pub(crate) installments: Json<Vec<Installment>>, |
| 109 | pub(crate) created_by: UserId, | 105 | pub(crate) created_by: UserId, |
| 110 | pub(crate) created_at: Timestamp, | 106 | pub(crate) created_at: Timestamp, |
| 111 | } | 107 | } |
| @@ -158,4 +154,21 @@ mod tests { | |||
| 158 | assert!(validate_installments(&vec![one.clone(); MAX_FEE_PLAN_INSTALLMENTS]).is_ok()); | 154 | assert!(validate_installments(&vec![one.clone(); MAX_FEE_PLAN_INSTALLMENTS]).is_ok()); |
| 159 | assert!(validate_installments(&vec![one; MAX_FEE_PLAN_INSTALLMENTS + 1]).is_err()); | 155 | assert!(validate_installments(&vec![one; MAX_FEE_PLAN_INSTALLMENTS + 1]).is_err()); |
| 160 | } | 156 | } |
| 157 | + | ||
| 158 | + /// The installments ride the row as JSON, so the storage contract is that | ||
| 159 | + /// an installment round-trips through `serde_json` unchanged — the amount | ||
| 160 | + /// stays an integer minor-unit count and the due date a bare millisecond | ||
| 161 | + /// number. | ||
| 162 | + #[test] | ||
| 163 | + fn an_installment_survives_the_json_round_trip() { | ||
| 164 | + let one = Installment::new( | ||
| 165 | + LedgerAmount::try_new(12_345).unwrap(), | ||
| 166 | + Timestamp::from_millis(1_700_000_000_000), | ||
| 167 | + ); | ||
| 168 | + let json = serde_json::to_value(&one).unwrap(); | ||
| 169 | + assert_eq!(json["amount_minor"], serde_json::json!(12_345)); | ||
| 170 | + assert_eq!(json["due_at"], serde_json::json!(1_700_000_000_000)); | ||
| 171 | + let back: Installment = serde_json::from_value(json).unwrap(); | ||
| 172 | + assert_eq!(back, one); | ||
| 173 | + } | ||
| 161 | } | 174 | } |
src/domain/fee_plan_assignment.rsmodified+61 -29
| @@ -2,8 +2,8 @@ | |||
| 2 | //! owed: assigning appends *every* installment of the plan as a charge line at | 2 | //! owed: assigning appends *every* installment of the plan as a charge line at |
| 3 | //! once, each carrying its own due date. | 3 | //! once, each carrying its own due date. |
| 4 | //! | 4 | //! |
| 5 | -//! The row is keyed `<plan>_<student>`, and every charge it raises is keyed | 5 | +//! The row is keyed (plan, student), and every charge it raises is keyed from |
| 6 | -//! from that same key plus the installment number, so the whole operation is | 6 | +//! that same pair plus the installment number, so the whole operation is |
| 7 | //! idempotent **by identity**: assigning twice writes nothing the second time, | 7 | //! idempotent **by identity**: assigning twice writes nothing the second time, |
| 8 | //! however the two requests interleave, and an assign cut short after three of | 8 | //! however the two requests interleave, and an assign cut short after three of |
| 9 | //! twelve charges landed completes itself when it is repeated. No scan decides | 9 | //! twelve charges landed completes itself when it is repeated. No scan decides |
| @@ -15,47 +15,49 @@ | |||
| 15 | //! its charges. That is also why the plan's assignment refcount is only ever | 15 | //! its charges. That is also why the plan's assignment refcount is only ever |
| 16 | //! claimed and never released — a plan, once assigned, stays frozen for good. | 16 | //! claimed and never released — a plan, once assigned, stays frozen for good. |
| 17 | 17 | ||
| 18 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 19 | - | ||
| 20 | -use crate::constant::FEE_PLAN_ASSIGNMENT_TABLE; | ||
| 21 | use crate::domain::fee_plan::FeePlanId; | 18 | use crate::domain::fee_plan::FeePlanId; |
| 22 | use crate::domain::timestamp::Timestamp; | 19 | use crate::domain::timestamp::Timestamp; |
| 23 | use crate::domain::user::UserId; | 20 | use crate::domain::user::UserId; |
| 24 | 21 | ||
| 25 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 22 | +/// The identity of one (plan, student) pair. Not a row column: the table's |
| 26 | -pub struct FeePlanAssignmentId(RecordId); | 23 | +/// primary key *is* the pair — one assignment per pair by construction — and |
| 24 | +/// this struct's job is the underscore-joined wire form at the HTTP edge. | ||
| 25 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 26 | +pub struct FeePlanAssignmentId { | ||
| 27 | + pub(crate) plan: FeePlanId, | ||
| 28 | + pub(crate) student: UserId, | ||
| 29 | +} | ||
| 27 | 30 | ||
| 28 | impl FeePlanAssignmentId { | 31 | impl FeePlanAssignmentId { |
| 29 | - /// A deterministic id for the (plan, student) pair — one assignment per | ||
| 30 | - /// pair by construction, and the prefix every charge line of that | ||
| 31 | - /// assignment is keyed from. ULID keys are alphanumeric, so `_` is an | ||
| 32 | - /// unambiguous joiner. | ||
| 33 | pub fn composite(plan: &FeePlanId, student: &UserId) -> Self { | 32 | pub fn composite(plan: &FeePlanId, student: &UserId) -> Self { |
| 34 | - Self(RecordId::new( | 33 | + Self { |
| 35 | - FEE_PLAN_ASSIGNMENT_TABLE, | 34 | + plan: plan.clone(), |
| 36 | - format!("{}_{}", plan.key(), student.key()), | 35 | + student: student.clone(), |
| 37 | - )) | 36 | + } |
| 38 | } | 37 | } |
| 39 | 38 | ||
| 39 | + /// Splits a wire key back into its pair. A malformed key (no `_` joiner, | ||
| 40 | + /// unparseable halves) yields nil components, which match no row — the | ||
| 41 | + /// same 404 a well-formed but absent key gets. | ||
| 40 | pub fn from_key(key: &str) -> Self { | 42 | pub fn from_key(key: &str) -> Self { |
| 41 | - Self(RecordId::new(FEE_PLAN_ASSIGNMENT_TABLE, key)) | 43 | + let (plan, student) = match key.split_once('_') { |
| 42 | - } | 44 | + Some((plan, student)) => (plan, student), |
| 43 | - | 45 | + None => ("", ""), |
| 44 | - pub fn record(&self) -> RecordId { | 46 | + }; |
| 45 | - self.0.clone() | 47 | + Self { |
| 48 | + plan: FeePlanId::from_key(plan), | ||
| 49 | + student: UserId::from_key(student), | ||
| 50 | + } | ||
| 46 | } | 51 | } |
| 47 | 52 | ||
| 48 | - pub fn key(&self) -> &str { | 53 | + /// The underscore-joined wire form (`{plan}_{student}`). |
| 49 | - match &self.0.key { | 54 | + pub fn key(&self) -> String { |
| 50 | - RecordIdKey::String(key) => key, | 55 | + format!("{}_{}", self.plan.key(), self.student.key()) |
| 51 | - _ => "", | ||
| 52 | - } | ||
| 53 | } | 56 | } |
| 54 | } | 57 | } |
| 55 | 58 | ||
| 56 | -#[derive(Debug, Clone, SurrealValue)] | 59 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 57 | pub struct FeePlanAssignment { | 60 | pub struct FeePlanAssignment { |
| 58 | - pub(crate) id: FeePlanAssignmentId, | ||
| 59 | pub(crate) plan: FeePlanId, | 61 | pub(crate) plan: FeePlanId, |
| 60 | pub(crate) student: UserId, | 62 | pub(crate) student: UserId, |
| 61 | pub(crate) assigned_by: UserId, | 63 | pub(crate) assigned_by: UserId, |
| @@ -63,8 +65,9 @@ pub struct FeePlanAssignment { | |||
| 63 | } | 65 | } |
| 64 | 66 | ||
| 65 | impl FeePlanAssignment { | 67 | impl FeePlanAssignment { |
| 66 | - pub fn get_id(&self) -> &FeePlanAssignmentId { | 68 | + /// The row's identity, built back from its primary-key columns. |
| 67 | - &self.id | 69 | + pub fn get_id(&self) -> FeePlanAssignmentId { |
| 70 | + FeePlanAssignmentId::composite(&self.plan, &self.student) | ||
| 68 | } | 71 | } |
| 69 | 72 | ||
| 70 | pub fn get_plan(&self) -> &FeePlanId { | 73 | pub fn get_plan(&self) -> &FeePlanId { |
| @@ -83,3 +86,32 @@ impl FeePlanAssignment { | |||
| 83 | self.created_at | 86 | self.created_at |
| 84 | } | 87 | } |
| 85 | } | 88 | } |
| 89 | + | ||
| 90 | +#[cfg(test)] | ||
| 91 | +mod tests { | ||
| 92 | + use super::*; | ||
| 93 | + | ||
| 94 | + const PLAN: &str = "0198f1a2-0000-7000-8000-000000000001"; | ||
| 95 | + const STUDENT: &str = "0198f1a2-1111-7000-8000-000000000002"; | ||
| 96 | + | ||
| 97 | + /// The wire key is the pair, and the pair survives the round trip — this | ||
| 98 | + /// is what lets a charge line's `assignment` reference travel as one path | ||
| 99 | + /// segment. | ||
| 100 | + #[test] | ||
| 101 | + fn the_wire_key_round_trips_through_the_pair() { | ||
| 102 | + let plan = FeePlanId::from_key(PLAN); | ||
| 103 | + let student = UserId::from_key(STUDENT); | ||
| 104 | + let id = FeePlanAssignmentId::composite(&plan, &student); | ||
| 105 | + assert_eq!(id.key(), format!("{PLAN}_{STUDENT}")); | ||
| 106 | + assert_eq!(FeePlanAssignmentId::from_key(&id.key()), id); | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + /// A key that is not a pair cannot name an assignment: it decodes to nil | ||
| 110 | + /// components, which match no row (a 404, never a panic). | ||
| 111 | + #[test] | ||
| 112 | + fn a_malformed_key_decodes_to_something_that_matches_nothing() { | ||
| 113 | + let junk = FeePlanAssignmentId::from_key("not-a-pair"); | ||
| 114 | + assert_eq!(junk.plan.key(), uuid::Uuid::nil().to_string()); | ||
| 115 | + assert_eq!(junk.student.key(), uuid::Uuid::nil().to_string()); | ||
| 116 | + } | ||
| 117 | +} | ||
src/domain/homework.rsmodified+34 -34
| @@ -6,51 +6,47 @@ | |||
| 6 | //! ([`crate::domain::homework_result`]). Persistence lives in | 6 | //! ([`crate::domain::homework_result`]). Persistence lives in |
| 7 | //! [`crate::db::homework`], workflows in [`crate::service::homework`]. | 7 | //! [`crate::db::homework`], workflows in [`crate::service::homework`]. |
| 8 | //! | 8 | //! |
| 9 | -//! `course`, `created_by`, and `created_at` are fixed at creation (the schema | 9 | +//! `course`, `created_by`, and `created_at` are fixed at creation (READONLY |
| 10 | -//! marks them `READONLY`): moving a homework between courses would strand the | 10 | +//! app discipline): moving a homework between courses would strand the |
| 11 | //! submissions and grades of students not in the target course. `subject` is | 11 | //! submissions and grades of students not in the target course. `subject` is |
| 12 | -//! deliberately *not* readonly — it is re-taggable through PATCH, validated | 12 | +//! deliberately *not* fixed — it is re-taggable through PATCH, validated |
| 13 | //! same-course by the web layer, exactly like an exam question's subject. | 13 | //! same-course by the web layer, exactly like an exam question's subject. |
| 14 | 14 | ||
| 15 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 15 | +use crate::constant::{MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN}; |
| 16 | - | ||
| 17 | -use crate::constant::{HOMEWORK_TABLE, MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN}; | ||
| 18 | use crate::domain::course::CourseId; | 16 | use crate::domain::course::CourseId; |
| 19 | -use crate::domain::monotonic_id::next_ulid; | 17 | +use crate::domain::monotonic_id::next_uuid; |
| 20 | use crate::domain::subject::SubjectId; | 18 | use crate::domain::subject::SubjectId; |
| 21 | use crate::domain::timestamp::Timestamp; | 19 | use crate::domain::timestamp::Timestamp; |
| 22 | use crate::domain::user::UserId; | 20 | use crate::domain::user::UserId; |
| 23 | use crate::error::ValidationError; | 21 | use crate::error::ValidationError; |
| 24 | use crate::validate::{validate_optional, validate_required}; | 22 | use crate::validate::{validate_optional, validate_required}; |
| 25 | 23 | ||
| 26 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 24 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 27 | -pub struct HomeworkId(RecordId); | 25 | +#[sqlx(transparent)] |
| 26 | +pub struct HomeworkId(uuid::Uuid); | ||
| 28 | 27 | ||
| 29 | impl HomeworkId { | 28 | impl HomeworkId { |
| 30 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 29 | + /// Minted from the process-wide monotonic generator, not a plain random |
| 31 | - /// homework lists `id DESC` (newest first, [`Homework::list_all`]), | 30 | + /// UUID: homework lists `id DESC` (newest first, [`HomeworkId`]-ordered |
| 32 | - /// and a random low half scrambles rows minted in the same millisecond. | 31 | + /// listings), and a random low half scrambles rows minted in the same |
| 32 | + /// millisecond. | ||
| 33 | pub fn generate() -> Self { | 33 | pub fn generate() -> Self { |
| 34 | - Self(RecordId::new(HOMEWORK_TABLE, next_ulid().to_string())) | 34 | + Self(next_uuid()) |
| 35 | } | 35 | } |
| 36 | 36 | ||
| 37 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 38 | + /// which matches no row. | ||
| 37 | pub fn from_key(key: &str) -> Self { | 39 | pub fn from_key(key: &str) -> Self { |
| 38 | - Self(RecordId::new(HOMEWORK_TABLE, key)) | 40 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 39 | } | 41 | } |
| 40 | 42 | ||
| 41 | - pub fn record(&self) -> RecordId { | 43 | + pub fn key(&self) -> String { |
| 42 | - self.0.clone() | 44 | + self.0.to_string() |
| 43 | - } | ||
| 44 | - | ||
| 45 | - pub fn key(&self) -> &str { | ||
| 46 | - match &self.0.key { | ||
| 47 | - RecordIdKey::String(key) => key, | ||
| 48 | - _ => "", | ||
| 49 | - } | ||
| 50 | } | 45 | } |
| 51 | } | 46 | } |
| 52 | 47 | ||
| 53 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 48 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 49 | +#[sqlx(transparent)] | ||
| 54 | pub struct HomeworkTitle(String); | 50 | pub struct HomeworkTitle(String); |
| 55 | 51 | ||
| 56 | impl HomeworkTitle { | 52 | impl HomeworkTitle { |
| @@ -64,7 +60,8 @@ impl HomeworkTitle { | |||
| 64 | } | 60 | } |
| 65 | } | 61 | } |
| 66 | 62 | ||
| 67 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 63 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 64 | +#[sqlx(transparent)] | ||
| 68 | pub struct HomeworkDescription(String); | 65 | pub struct HomeworkDescription(String); |
| 69 | 66 | ||
| 70 | impl HomeworkDescription { | 67 | impl HomeworkDescription { |
| @@ -78,12 +75,12 @@ impl HomeworkDescription { | |||
| 78 | } | 75 | } |
| 79 | } | 76 | } |
| 80 | 77 | ||
| 81 | -/// A homework assignment. `assigned` is the optional student subset: `None` | 78 | +/// A homework assignment. `assigned` is the optional student subset (`uuid[] |
| 82 | -/// (the column absent) and an empty list both mean "the whole course" — see | 79 | +/// NULL`): `NULL` and an empty list both mean "the whole course" — see |
| 83 | /// [`Homework::student_sees`]. Because whole-course homework carries no roster, | 80 | /// [`Homework::student_sees`]. Because whole-course homework carries no roster, |
| 84 | /// a student who enrolls later is covered automatically; a subset is a fixed | 81 | /// a student who enrolls later is covered automatically; a subset is a fixed |
| 85 | /// snapshot of the students named at assign (or last PATCH) time. | 82 | /// snapshot of the students named at assign (or last PATCH) time. |
| 86 | -#[derive(Debug, Clone, SurrealValue)] | 83 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 87 | pub struct Homework { | 84 | pub struct Homework { |
| 88 | pub(crate) id: HomeworkId, | 85 | pub(crate) id: HomeworkId, |
| 89 | pub(crate) course: CourseId, | 86 | pub(crate) course: CourseId, |
| @@ -135,7 +132,7 @@ impl Homework { | |||
| 135 | } | 132 | } |
| 136 | 133 | ||
| 137 | /// Whether `user` is in this homework's audience. A whole-course homework | 134 | /// Whether `user` is in this homework's audience. A whole-course homework |
| 138 | - /// (`assigned` absent or empty) is visible to every enrolled student; a | 135 | + /// (`assigned` NULL or empty) is visible to every enrolled student; a |
| 139 | /// subset homework only to the students it names. Callers pair this with an | 136 | /// subset homework only to the students it names. Callers pair this with an |
| 140 | /// enrollment check — being named is visibility, not enrollment. | 137 | /// enrollment check — being named is visibility, not enrollment. |
| 141 | pub fn student_sees(&self, user: &UserId) -> bool { | 138 | pub fn student_sees(&self, user: &UserId) -> bool { |
| @@ -150,6 +147,9 @@ impl Homework { | |||
| 150 | mod tests { | 147 | mod tests { |
| 151 | use super::*; | 148 | use super::*; |
| 152 | 149 | ||
| 150 | + const A: &str = "0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e"; | ||
| 151 | + const B: &str = "0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f"; | ||
| 152 | + | ||
| 153 | #[tokio::test] | 153 | #[tokio::test] |
| 154 | async fn title_is_required() { | 154 | async fn title_is_required() { |
| 155 | assert!(HomeworkTitle::try_new("Read chapter 3").is_ok()); | 155 | assert!(HomeworkTitle::try_new("Read chapter 3").is_ok()); |
| @@ -166,12 +166,12 @@ mod tests { | |||
| 166 | 166 | ||
| 167 | #[tokio::test] | 167 | #[tokio::test] |
| 168 | async fn student_sees_covers_whole_course_and_named_subsets() { | 168 | async fn student_sees_covers_whole_course_and_named_subsets() { |
| 169 | - let a = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | 169 | + let a = UserId::from_key(A); |
| 170 | - let b = UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"); | 170 | + let b = UserId::from_key(B); |
| 171 | let with = |assigned| Homework { | 171 | let with = |assigned| Homework { |
| 172 | id: HomeworkId::generate(), | 172 | id: HomeworkId::generate(), |
| 173 | - course: CourseId::from_key("01TESTCOURSEAAAAAAAAAAAAAA"), | 173 | + course: CourseId::from_key("0198f1a2-3b4c-7d5e-8f90-cccc3c4d5e6f"), |
| 174 | - subject: SubjectId::from_key("01TESTSUBJECTAAAAAAAAAAAAA"), | 174 | + subject: SubjectId::from_key("0198f1a2-3b4c-7d5e-8f90-dddd4c4d5e6f"), |
| 175 | title: HomeworkTitle::try_new("hw").unwrap(), | 175 | title: HomeworkTitle::try_new("hw").unwrap(), |
| 176 | description: None, | 176 | description: None, |
| 177 | due_at: Timestamp::from_millis(1), | 177 | due_at: Timestamp::from_millis(1), |
| @@ -179,7 +179,7 @@ mod tests { | |||
| 179 | created_by: a.clone(), | 179 | created_by: a.clone(), |
| 180 | created_at: Timestamp::from_millis(1), | 180 | created_at: Timestamp::from_millis(1), |
| 181 | }; | 181 | }; |
| 182 | - // Whole course: absent or empty list means everyone sees it. | 182 | + // Whole course: NULL or empty list means everyone sees it. |
| 183 | assert!(with(None).student_sees(&a)); | 183 | assert!(with(None).student_sees(&a)); |
| 184 | assert!(with(Some(vec![])).student_sees(&b)); | 184 | assert!(with(Some(vec![])).student_sees(&b)); |
| 185 | // Subset: only the named students. | 185 | // Subset: only the named students. |
src/domain/homework_file.rsmodified+25 -32
| @@ -1,54 +1,46 @@ | |||
| 1 | //! A file attached to a homework submission. Like a note file, the row carries | 1 | //! A file attached to a homework submission. Like a note file, the row carries |
| 2 | //! metadata only (original filename, MIME type, byte size) and the bytes live | 2 | //! metadata only (original filename, MIME type, byte size) and the bytes live |
| 3 | //! on disk under [`crate::config::Config::files_path`] — but named by this | 3 | //! on disk under [`crate::config::Config::files_path`] — but named by this |
| 4 | -//! row's own `file` field (a fresh server-generated ULID per upload, like a | 4 | +//! row's own `file` field (a fresh server-generated UUID per upload, like a |
| 5 | //! question image), never by user input, so nothing a client sends shapes a | 5 | //! question image), never by user input, so nothing a client sends shapes a |
| 6 | //! disk path. Files are immutable: created and deleted, never updated, so the | 6 | //! disk path. Files are immutable: created and deleted, never updated, so the |
| 7 | -//! `READONLY` `submission`/`file`/`created_at` columns are only ever set once. | 7 | +//! `submission`/`file`/`created_at` columns are only ever set once (READONLY |
| 8 | -//! The web layer owns the blob I/O and its ordering (blob before row on | 8 | +//! app discipline — single writer). The web layer owns the blob I/O and its |
| 9 | -//! upload, row before blob on delete); the rows are written and read by | 9 | +//! ordering (blob before row on upload, row before blob on delete); the rows |
| 10 | -//! [`crate::db::homework_file`], the upload/attach workflow by | 10 | +//! are written and read by [`crate::db::homework_file`], the upload/attach |
| 11 | -//! [`crate::service::homework_file`]. | 11 | +//! workflow by [`crate::service::homework_file`]. |
| 12 | 12 | ||
| 13 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 14 | -use ulid::Ulid; | ||
| 15 | - | ||
| 16 | -use crate::constant::HOMEWORK_FILE_TABLE; | ||
| 17 | use crate::domain::homework_submission::HomeworkSubmissionId; | 13 | use crate::domain::homework_submission::HomeworkSubmissionId; |
| 18 | -use crate::domain::monotonic_id::next_ulid; | 14 | +use crate::domain::monotonic_id::next_uuid; |
| 19 | use crate::domain::note_file::{FileContentType, FileName}; | 15 | use crate::domain::note_file::{FileContentType, FileName}; |
| 20 | use crate::domain::timestamp::Timestamp; | 16 | use crate::domain::timestamp::Timestamp; |
| 21 | 17 | ||
| 22 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 18 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 23 | -pub struct HomeworkFileId(RecordId); | 19 | +#[sqlx(transparent)] |
| 20 | +pub struct HomeworkFileId(uuid::Uuid); | ||
| 24 | 21 | ||
| 25 | impl HomeworkFileId { | 22 | impl HomeworkFileId { |
| 26 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 23 | + /// Minted from the process-wide monotonic generator, not a plain random |
| 27 | - /// a submission's files list `id DESC` (newest first, [`HomeworkFile::list_for_submission`]), | 24 | + /// UUID: a submission's files list `id DESC` (newest first), and a random |
| 28 | - /// and a random low half scrambles rows minted in the same millisecond. | 25 | + /// low half scrambles rows minted in the same millisecond. |
| 29 | pub fn generate() -> Self { | 26 | pub fn generate() -> Self { |
| 30 | - Self(RecordId::new(HOMEWORK_FILE_TABLE, next_ulid().to_string())) | 27 | + Self(next_uuid()) |
| 31 | } | 28 | } |
| 32 | 29 | ||
| 30 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, | ||
| 31 | + /// which matches no row. | ||
| 33 | pub fn from_key(key: &str) -> Self { | 32 | pub fn from_key(key: &str) -> Self { |
| 34 | - Self(RecordId::new(HOMEWORK_FILE_TABLE, key)) | 33 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) |
| 35 | - } | ||
| 36 | - | ||
| 37 | - pub fn record(&self) -> RecordId { | ||
| 38 | - self.0.clone() | ||
| 39 | } | 34 | } |
| 40 | 35 | ||
| 41 | - pub fn key(&self) -> &str { | 36 | + pub fn key(&self) -> String { |
| 42 | - match &self.0.key { | 37 | + self.0.to_string() |
| 43 | - RecordIdKey::String(key) => key, | ||
| 44 | - _ => "", | ||
| 45 | - } | ||
| 46 | } | 38 | } |
| 47 | } | 39 | } |
| 48 | 40 | ||
| 49 | -/// An attachment row. `file` is the blob's on-disk name (a fresh ULID per | 41 | +/// An attachment row. `file` is the blob's on-disk name (a fresh UUID per |
| 50 | /// upload), independent of the row id and reused as the GC key on cascade. | 42 | /// upload), independent of the row id and reused as the GC key on cascade. |
| 51 | -#[derive(Debug, Clone, SurrealValue)] | 43 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 52 | pub struct HomeworkFile { | 44 | pub struct HomeworkFile { |
| 53 | pub(crate) id: HomeworkFileId, | 45 | pub(crate) id: HomeworkFileId, |
| 54 | pub(crate) submission: HomeworkSubmissionId, | 46 | pub(crate) submission: HomeworkSubmissionId, |
| @@ -62,7 +54,8 @@ pub struct HomeworkFile { | |||
| 62 | impl HomeworkFile { | 54 | impl HomeworkFile { |
| 63 | /// Assemble a row (fresh blob name generated here) without persisting it. | 55 | /// Assemble a row (fresh blob name generated here) without persisting it. |
| 64 | /// The caller writes the blob under [`Self::get_file`] first, then calls | 56 | /// The caller writes the blob under [`Self::get_file`] first, then calls |
| 65 | - /// [`Self::insert`] — so a stored row always points at a real blob. | 57 | + /// [`crate::db::homework_file::insert`] — so a stored row always points at |
| 58 | + /// a real blob. | ||
| 66 | pub fn new( | 59 | pub fn new( |
| 67 | submission: &HomeworkSubmissionId, | 60 | submission: &HomeworkSubmissionId, |
| 68 | name: FileName, | 61 | name: FileName, |
| @@ -75,7 +68,7 @@ impl HomeworkFile { | |||
| 75 | name, | 68 | name, |
| 76 | content_type, | 69 | content_type, |
| 77 | size, | 70 | size, |
| 78 | - file: Ulid::generate().to_string(), | 71 | + file: uuid::Uuid::new_v4().to_string(), |
| 79 | created_at: Timestamp::now(), | 72 | created_at: Timestamp::now(), |
| 80 | } | 73 | } |
| 81 | } | 74 | } |
| @@ -100,7 +93,7 @@ impl HomeworkFile { | |||
| 100 | self.size | 93 | self.size |
| 101 | } | 94 | } |
| 102 | 95 | ||
| 103 | - /// The blob's on-disk name — a fresh ULID, so no user input shapes a path. | 96 | + /// The blob's on-disk name — a fresh UUID, so no user input shapes a path. |
| 104 | pub fn get_file(&self) -> &str { | 97 | pub fn get_file(&self) -> &str { |
| 105 | &self.file | 98 | &self.file |
| 106 | } | 99 | } |
src/domain/homework_result.rsmodified+28 -37
| @@ -1,8 +1,9 @@ | |||
| 1 | //! A teacher's grade on one student's homework: a status | 1 | //! A teacher's grade on one student's homework: a status |
| 2 | //! (`done`/`incomplete`/`missing`) plus an optional numeric [`Mark`] (0..=100, | 2 | //! (`done`/`incomplete`/`missing`) plus an optional numeric [`Mark`] (0..=100, |
| 3 | -//! reused from exam results). Like an exam result, the row id is the | 3 | +//! reused from exam results). The row carries its own `id` primary key and a |
| 4 | -//! deterministic `{homework}_{user}` composite, so grading is one atomic UPSERT | 4 | +//! `UNIQUE (homework, app_user)` constraint, so grading is one atomic UPSERT |
| 5 | -//! and there is exactly one grade per (homework, user) by construction. | 5 | +//! (`ON CONFLICT (homework, app_user)`) and there is exactly one grade per |
| 6 | +//! (homework, user) by construction. | ||
| 6 | //! | 7 | //! |
| 7 | //! A stored result is what *freezes* a submission: while a grade exists the | 8 | //! A stored result is what *freezes* a submission: while a grade exists the |
| 8 | //! student's submission and files are locked (the web layer answers 409), | 9 | //! student's submission and files are locked (the web layer answers 409), |
| @@ -13,40 +14,32 @@ | |||
| 13 | //! [`crate::db::homework_result`], the grading gates in | 14 | //! [`crate::db::homework_result`], the grading gates in |
| 14 | //! [`crate::service::homework_result`]. | 15 | //! [`crate::service::homework_result`]. |
| 15 | 16 | ||
| 16 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 17 | - | ||
| 18 | -use crate::constant::HOMEWORK_RESULT_TABLE; | ||
| 19 | use crate::domain::exam_result::Mark; | 17 | use crate::domain::exam_result::Mark; |
| 20 | use crate::domain::homework::HomeworkId; | 18 | use crate::domain::homework::HomeworkId; |
| 19 | +use crate::domain::monotonic_id::next_uuid; | ||
| 21 | use crate::domain::timestamp::Timestamp; | 20 | use crate::domain::timestamp::Timestamp; |
| 22 | use crate::domain::user::UserId; | 21 | use crate::domain::user::UserId; |
| 23 | use crate::error::ValidationError; | 22 | use crate::error::ValidationError; |
| 24 | use crate::validate::validate_homework_status; | 23 | use crate::validate::validate_homework_status; |
| 25 | 24 | ||
| 26 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 25 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 27 | -pub struct HomeworkResultId(RecordId); | 26 | +#[sqlx(transparent)] |
| 27 | +pub struct HomeworkResultId(uuid::Uuid); | ||
| 28 | 28 | ||
| 29 | impl HomeworkResultId { | 29 | impl HomeworkResultId { |
| 30 | - /// The one id a (homework, user) pair can have — a deterministic composite, | 30 | + /// A write-ordered id: grade listings read newest first. |
| 31 | - /// so grading is a single atomic UPSERT with no find-then-insert race and | 31 | + pub fn generate() -> Self { |
| 32 | - /// one grade per pair by construction. ULID keys are alphanumeric, so `_` | 32 | + Self(next_uuid()) |
| 33 | - /// is an unambiguous joiner. | ||
| 34 | - pub fn composite(homework: &HomeworkId, user: &UserId) -> Self { | ||
| 35 | - Self(RecordId::new( | ||
| 36 | - HOMEWORK_RESULT_TABLE, | ||
| 37 | - format!("{}_{}", homework.key(), user.key()), | ||
| 38 | - )) | ||
| 39 | } | 33 | } |
| 40 | 34 | ||
| 41 | - pub fn record(&self) -> RecordId { | 35 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, |
| 42 | - self.0.clone() | 36 | + /// which matches no row. |
| 37 | + pub fn from_key(key: &str) -> Self { | ||
| 38 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) | ||
| 43 | } | 39 | } |
| 44 | 40 | ||
| 45 | - pub fn key(&self) -> &str { | 41 | + pub fn key(&self) -> String { |
| 46 | - match &self.0.key { | 42 | + self.0.to_string() |
| 47 | - RecordIdKey::String(key) => key, | ||
| 48 | - _ => "", | ||
| 49 | - } | ||
| 50 | } | 43 | } |
| 51 | } | 44 | } |
| 52 | 45 | ||
| @@ -54,12 +47,12 @@ impl HomeworkResultId { | |||
| 54 | /// (submitted but lacking), or `missing` (not done). Held to the | 47 | /// (submitted but lacking), or `missing` (not done). Held to the |
| 55 | /// [`crate::constant::HOMEWORK_STATUSES`] set by [`HomeworkStatus::try_new`] — | 48 | /// [`crate::constant::HOMEWORK_STATUSES`] set by [`HomeworkStatus::try_new`] — |
| 56 | /// the same validated-string-against-a-const shape as | 49 | /// the same validated-string-against-a-const shape as |
| 57 | -/// [`crate::domain::exam::ExamMode`], which is why the `status` column needs no | 50 | +/// [`crate::domain::exam::ExamMode`]. It stores as the bare string. A stored |
| 58 | -/// DDL `ASSERT` (repo convention: enums live in Rust newtypes, not the schema). | 51 | +/// `missing` is a teacher's deliberate verdict, distinct from the roster's |
| 59 | -/// It stores as the bare string. A stored `missing` is a teacher's deliberate | 52 | +/// *computed* missing (unsubmitted past due, derived in the web layer, never |
| 60 | -/// verdict, distinct from the roster's *computed* missing (unsubmitted past due, | 53 | +/// stored). |
| 61 | -/// derived in the web layer, never stored). | 54 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 62 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 55 | +#[sqlx(transparent)] |
| 63 | pub struct HomeworkStatus(String); | 56 | pub struct HomeworkStatus(String); |
| 64 | 57 | ||
| 65 | impl HomeworkStatus { | 58 | impl HomeworkStatus { |
| @@ -73,7 +66,7 @@ impl HomeworkStatus { | |||
| 73 | } | 66 | } |
| 74 | } | 67 | } |
| 75 | 68 | ||
| 76 | -#[derive(Debug, Clone, SurrealValue)] | 69 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 77 | pub struct HomeworkResult { | 70 | pub struct HomeworkResult { |
| 78 | pub(crate) id: HomeworkResultId, | 71 | pub(crate) id: HomeworkResultId, |
| 79 | pub(crate) homework: HomeworkId, | 72 | pub(crate) homework: HomeworkId, |
| @@ -119,17 +112,15 @@ impl HomeworkResult { | |||
| 119 | mod tests { | 112 | mod tests { |
| 120 | use super::*; | 113 | use super::*; |
| 121 | use crate::constant::HOMEWORK_STATUSES; | 114 | use crate::constant::HOMEWORK_STATUSES; |
| 122 | - use surrealdb::types::Value; | ||
| 123 | 115 | ||
| 124 | #[tokio::test] | 116 | #[tokio::test] |
| 125 | - async fn status_is_held_to_the_const_and_stores_as_a_bare_string() { | 117 | + async fn status_is_held_to_the_const() { |
| 126 | - // Enforcement lives in the newtype against HOMEWORK_STATUSES (the DDL | 118 | + // Enforcement lives in the newtype against HOMEWORK_STATUSES, and the |
| 127 | - // carries no ASSERT), and the stored value is the bare validated string | 119 | + // stored value is the bare validated string the `status` TEXT column |
| 128 | - // the `status` column's `TYPE string` accepts. Guard both never drift. | 120 | + // accepts — queries match on these spellings, so they may not drift. |
| 129 | for status in HOMEWORK_STATUSES { | 121 | for status in HOMEWORK_STATUSES { |
| 130 | let parsed = HomeworkStatus::try_new(status).unwrap(); | 122 | let parsed = HomeworkStatus::try_new(status).unwrap(); |
| 131 | assert_eq!(parsed.as_str(), status); | 123 | assert_eq!(parsed.as_str(), status); |
| 132 | - assert_eq!(parsed.into_value(), Value::String(status.to_string())); | ||
| 133 | } | 124 | } |
| 134 | assert!(HomeworkStatus::try_new("late").is_err()); | 125 | assert!(HomeworkStatus::try_new("late").is_err()); |
| 135 | assert!(HomeworkStatus::try_new("").is_err()); | 126 | assert!(HomeworkStatus::try_new("").is_err()); |
src/domain/homework_submission.rsmodified+24 -30
| @@ -1,12 +1,12 @@ | |||
| 1 | //! One student's submission to a homework: an optional free-text note plus any | 1 | //! One student's submission to a homework: an optional free-text note plus any |
| 2 | -//! number of files ([`crate::domain::homework_file`]). The row id is the | 2 | +//! number of files ([`crate::domain::homework_file`]). The row carries its own |
| 3 | -//! deterministic `{homework}_{user}` composite, so a student has exactly one | 3 | +//! `id` primary key and a `UNIQUE (homework, app_user)` constraint, so a |
| 4 | -//! submission per homework by construction and a re-submit is a single atomic | 4 | +//! student has exactly one submission per homework by construction and a |
| 5 | -//! UPSERT. | 5 | +//! re-submit is a single atomic UPSERT on the pair. |
| 6 | //! | 6 | //! |
| 7 | -//! `submitted_at` — the first-submit stamp — is `READONLY` and survives every | 7 | +//! `submitted_at` — the first-submit stamp — is write-once and survives every |
| 8 | -//! re-submit; [`crate::db::homework_submission::upsert`] preserves it inside one | 8 | +//! re-submit; [`crate::db::homework_submission::upsert`] preserves it inside |
| 9 | -//! statement rather than through `.content()`, see there. `updated_at` moves to | 9 | +//! one statement rather than overwriting the whole row. `updated_at` moves to |
| 10 | //! now on every (re-)submit (and, later, on a file add/delete) and drives the | 10 | //! now on every (re-)submit (and, later, on a file add/delete) and drives the |
| 11 | //! computed "late" flag (`updated_at > homework.due_at`, judged in the web | 11 | //! computed "late" flag (`updated_at > homework.due_at`, judged in the web |
| 12 | //! layer, never stored): `submitted_at` answers "was the first hand-in on | 12 | //! layer, never stored): `submitted_at` answers "was the first hand-in on |
| @@ -14,45 +14,39 @@ | |||
| 14 | //! live in [`crate::db::homework_submission`], the submit/withdraw workflows | 14 | //! live in [`crate::db::homework_submission`], the submit/withdraw workflows |
| 15 | //! in [`crate::service::homework_submission`]. | 15 | //! in [`crate::service::homework_submission`]. |
| 16 | 16 | ||
| 17 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 17 | +use crate::constant::MAX_HOMEWORK_TEXT_LEN; |
| 18 | - | ||
| 19 | -use crate::constant::{HOMEWORK_SUBMISSION_TABLE, MAX_HOMEWORK_TEXT_LEN}; | ||
| 20 | use crate::domain::homework::HomeworkId; | 18 | use crate::domain::homework::HomeworkId; |
| 19 | +use crate::domain::monotonic_id::next_uuid; | ||
| 21 | use crate::domain::timestamp::Timestamp; | 20 | use crate::domain::timestamp::Timestamp; |
| 22 | use crate::domain::user::UserId; | 21 | use crate::domain::user::UserId; |
| 23 | use crate::error::ValidationError; | 22 | use crate::error::ValidationError; |
| 24 | use crate::validate::validate_optional; | 23 | use crate::validate::validate_optional; |
| 25 | 24 | ||
| 26 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 25 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 27 | -pub struct HomeworkSubmissionId(RecordId); | 26 | +#[sqlx(transparent)] |
| 27 | +pub struct HomeworkSubmissionId(uuid::Uuid); | ||
| 28 | 28 | ||
| 29 | impl HomeworkSubmissionId { | 29 | impl HomeworkSubmissionId { |
| 30 | - /// The one id a (homework, user) pair can have. A deterministic composite | 30 | + /// A write-ordered id: submission listings read newest first. |
| 31 | - /// means one submission per pair with no unique index and no | 31 | + pub fn generate() -> Self { |
| 32 | - /// find-then-insert race — a re-submit UPSERTs the same row. ULID keys are | 32 | + Self(next_uuid()) |
| 33 | - /// alphanumeric, so `_` is an unambiguous joiner. | ||
| 34 | - pub fn composite(homework: &HomeworkId, user: &UserId) -> Self { | ||
| 35 | - Self(RecordId::new( | ||
| 36 | - HOMEWORK_SUBMISSION_TABLE, | ||
| 37 | - format!("{}_{}", homework.key(), user.key()), | ||
| 38 | - )) | ||
| 39 | } | 33 | } |
| 40 | 34 | ||
| 41 | - pub fn record(&self) -> RecordId { | 35 | + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, |
| 42 | - self.0.clone() | 36 | + /// which matches no row. |
| 37 | + pub fn from_key(key: &str) -> Self { | ||
| 38 | + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) | ||
| 43 | } | 39 | } |
| 44 | 40 | ||
| 45 | - pub fn key(&self) -> &str { | 41 | + pub fn key(&self) -> String { |
| 46 | - match &self.0.key { | 42 | + self.0.to_string() |
| 47 | - RecordIdKey::String(key) => key, | ||
| 48 | - _ => "", | ||
| 49 | - } | ||
| 50 | } | 43 | } |
| 51 | } | 44 | } |
| 52 | 45 | ||
| 53 | /// A submission's optional free-text note: may be empty, at most | 46 | /// A submission's optional free-text note: may be empty, at most |
| 54 | /// `MAX_HOMEWORK_TEXT_LEN` characters. Files ride separately. | 47 | /// `MAX_HOMEWORK_TEXT_LEN` characters. Files ride separately. |
| 55 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 48 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 49 | +#[sqlx(transparent)] | ||
| 56 | pub struct SubmissionText(String); | 50 | pub struct SubmissionText(String); |
| 57 | 51 | ||
| 58 | impl SubmissionText { | 52 | impl SubmissionText { |
| @@ -66,7 +60,7 @@ impl SubmissionText { | |||
| 66 | } | 60 | } |
| 67 | } | 61 | } |
| 68 | 62 | ||
| 69 | -#[derive(Debug, Clone, SurrealValue)] | 63 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 70 | pub struct HomeworkSubmission { | 64 | pub struct HomeworkSubmission { |
| 71 | pub(crate) id: HomeworkSubmissionId, | 65 | pub(crate) id: HomeworkSubmissionId, |
| 72 | pub(crate) homework: HomeworkId, | 66 | pub(crate) homework: HomeworkId, |
src/domain/key.rsmodified+32 -27
| @@ -1,18 +1,19 @@ | |||
| 1 | -//! Deterministic record keys shared by the per-sitting exam tables and the | 1 | +//! Deterministic wire keys shared by the per-sitting exam tables and the |
| 2 | //! image-slot tables. | 2 | //! image-slot tables. |
| 3 | +// | ||
| 4 | +// With natural composite primary keys these are no longer storage ids — a | ||
| 5 | +// row is keyed by its component columns. They are the **HTTP edge** form only: | ||
| 6 | +// when a sitting key or a slot key crosses a path or body, it travels as one | ||
| 7 | +// underscore-joined string, and these helpers are its single spelling. | ||
| 3 | 8 | ||
| 4 | -/// The key for a `(scope, user, seq)` triple, where `scope` is whatever the row | 9 | +/// The wire key for a `(scope, user, seq)` triple, where `scope` is whatever |
| 5 | -/// hangs off — an exam for attempts and results, a question for answers and | 10 | +/// the row hangs off — an exam for attempts and results, a question for |
| 6 | -/// drawings. The same triple always maps to the same key, so "one row per | 11 | +/// answers and drawings. The first sitting keeps the historical |
| 7 | -/// student per sitting" holds by construction: a concurrent double write races | 12 | +/// `{scope}_{user}` shape — rows written before per-attempt history existed |
| 8 | -/// on one id instead of creating two rows, and no unique index is needed. | 13 | +/// stay addressable, unchanged, forever — so only later sittings carry their |
| 9 | -/// | 14 | +/// number. That bare-`seq == 1` case is migration law, not a style choice: |
| 10 | -/// The first sitting keeps the historical `{scope}_{user}` shape — rows written | 15 | +/// change it and every pre-history row becomes unreachable. UUID strings |
| 11 | -/// before per-attempt history existed stay addressable, unchanged, forever — so | 16 | +/// contain only `-` and hex, so `_` is an unambiguous joiner. |
| 12 | -/// only later sittings carry their number. That bare-`seq == 1` case is | ||
| 13 | -/// migration law, not a style choice: change it and every pre-history row | ||
| 14 | -/// becomes unreachable. ULID keys are alphanumeric, so `_` is an unambiguous | ||
| 15 | -/// joiner. | ||
| 16 | pub fn sitting(scope: &str, user: &str, seq: i64) -> String { | 17 | pub fn sitting(scope: &str, user: &str, seq: i64) -> String { |
| 17 | if seq == 1 { | 18 | if seq == 1 { |
| 18 | format!("{scope}_{user}") | 19 | format!("{scope}_{user}") |
| @@ -21,12 +22,10 @@ pub fn sitting(scope: &str, user: &str, seq: i64) -> String { | |||
| 21 | } | 22 | } |
| 22 | } | 23 | } |
| 23 | 24 | ||
| 24 | -/// The key for one image slot on `owner` — `{owner}_q` for the thing's own | 25 | +/// The wire key for one image slot on `owner` — `{owner}_q` for the thing's |
| 25 | -/// illustration, `{owner}_{choice id}` for one option's picture. Uniqueness per | 26 | +/// own illustration, `{owner}_{choice id}` for one option's picture. A UUID is |
| 26 | -/// slot needs no index this way, and keying by the option's *stable id* means | 27 | +/// never `"q"` and never contains `_`, so the two shapes can never collide — |
| 27 | -/// reordering the choice list moves no picture. `_` is not in Crockford base32 | 28 | +/// the rule behind every image table's slot keys, spelled once. |
| 28 | -/// and a ULID is never `"q"`, so the two shapes can never collide — the rule | ||
| 29 | -/// behind every image table's ids, spelled once. | ||
| 30 | pub fn slot(owner: &str, slot: Option<&str>) -> String { | 29 | pub fn slot(owner: &str, slot: Option<&str>) -> String { |
| 31 | format!("{owner}_{}", slot.unwrap_or("q")) | 30 | format!("{owner}_{}", slot.unwrap_or("q")) |
| 32 | } | 31 | } |
| @@ -35,20 +34,26 @@ pub fn slot(owner: &str, slot: Option<&str>) -> String { | |||
| 35 | mod tests { | 34 | mod tests { |
| 36 | use super::{sitting, slot}; | 35 | use super::{sitting, slot}; |
| 37 | 36 | ||
| 37 | + const QUESTION: &str = "0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"; | ||
| 38 | + const STUDENT: &str = "0198f1a2-3b4c-7d5e-8f90-aa2b3c4d5e6f"; | ||
| 39 | + | ||
| 38 | #[test] | 40 | #[test] |
| 39 | fn a_slot_key_never_collides_with_the_illustration() { | 41 | fn a_slot_key_never_collides_with_the_illustration() { |
| 40 | - assert_eq!(slot("Q", None), "Q_q"); | 42 | + assert_eq!(slot(QUESTION, None), format!("{QUESTION}_q")); |
| 41 | - assert_eq!(slot("Q", Some("01J8XZ")), "Q_01J8XZ"); | 43 | + assert_eq!(slot(QUESTION, Some(STUDENT)), format!("{QUESTION}_{STUDENT}")); |
| 42 | - // A choice id is a ULID, so it can never be the literal "q". | 44 | + // A choice id is a UUID, so it can never be the literal "q". |
| 43 | - assert_ne!(slot("Q", Some("01J8XZ")), slot("Q", None)); | 45 | + assert_ne!(slot(QUESTION, Some(STUDENT)), slot(QUESTION, None)); |
| 44 | } | 46 | } |
| 45 | 47 | ||
| 46 | #[test] | 48 | #[test] |
| 47 | fn the_first_sitting_stays_bare_and_later_ones_are_numbered() { | 49 | fn the_first_sitting_stays_bare_and_later_ones_are_numbered() { |
| 48 | - // Byte-for-byte the shape the four exam id types wrote before this | 50 | + // Byte-for-byte the shape the four sitting-keyed tables wrote before |
| 49 | - // helper existed; a pre-history row is keyed by the bare pair. | 51 | + // this helper existed; a pre-history row is keyed by the bare pair. |
| 50 | - assert_eq!(sitting("EXAM", "USER", 1), "EXAM_USER"); | 52 | + assert_eq!(sitting(QUESTION, STUDENT, 1), format!("{QUESTION}_{STUDENT}")); |
| 51 | - assert_eq!(sitting("EXAM", "USER", 2), "EXAM_USER_2"); | 53 | + assert_eq!( |
| 54 | + sitting(QUESTION, STUDENT, 2), | ||
| 55 | + format!("{QUESTION}_{STUDENT}_2") | ||
| 56 | + ); | ||
| 52 | assert_eq!(sitting("Q", "U", 11), "Q_U_11"); | 57 | assert_eq!(sitting("Q", "U", 11), "Q_U_11"); |
| 53 | } | 58 | } |
| 54 | } | 59 | } |
src/domain/meal_attendance.rsmodified+45 -29
| @@ -1,7 +1,7 @@ | |||
| 1 | -//! Who actually ate. One row per (menu, student), keyed by a deterministic | 1 | +//! Who actually ate. One row per (menu, student), keyed by the natural |
| 2 | -//! composite id — the same pair always maps to the same record, so marking is a | 2 | +//! composite primary key — the same pair always maps to the same row, so |
| 3 | -//! single atomic UPSERT with no find-then-insert race, and re-marking flips the | 3 | +//! marking is a single atomic upsert with no find-then-insert race, and |
| 4 | -//! status instead of stacking a second row. | 4 | +//! re-marking flips the status instead of stacking a second row. |
| 5 | //! | 5 | //! |
| 6 | //! **Attendance is reporting only — it has zero billing effect.** Booking is | 6 | //! **Attendance is reporting only — it has zero billing effect.** Booking is |
| 7 | //! the sole charge trigger: a student who booked and did not eat still pays, | 7 | //! the sole charge trigger: a student who booked and did not eat still pays, |
| @@ -18,42 +18,63 @@ | |||
| 18 | //! The queries live in [`crate::db::meal_attendance`]; the web layer reads | 18 | //! The queries live in [`crate::db::meal_attendance`]; the web layer reads |
| 19 | //! through [`crate::service::meal_attendance`]. | 19 | //! through [`crate::service::meal_attendance`]. |
| 20 | 20 | ||
| 21 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 21 | +use sqlx::Type; |
| 22 | 22 | ||
| 23 | -use crate::constant::{MEAL_ATTENDANCE_STATUSES, MEAL_ATTENDANCE_TABLE}; | 23 | +use crate::constant::MEAL_ATTENDANCE_STATUSES; |
| 24 | use crate::domain::menu::MenuId; | 24 | use crate::domain::menu::MenuId; |
| 25 | use crate::domain::timestamp::Timestamp; | 25 | use crate::domain::timestamp::Timestamp; |
| 26 | use crate::domain::user::UserId; | 26 | use crate::domain::user::UserId; |
| 27 | use crate::error::ValidationError; | 27 | use crate::error::ValidationError; |
| 28 | 28 | ||
| 29 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 29 | +/// The (menu, student) pair — the table's natural composite primary key. The |
| 30 | -pub struct MealAttendanceId(RecordId); | 30 | +/// same trick as |
| 31 | +/// [`MealBookingId`](crate::domain::meal_booking::MealBookingId). UUID strings | ||
| 32 | +/// carry only `-`, so `_` is an unambiguous joiner — and the student half is | ||
| 33 | +/// last, so the menu key (a `{date}_{slot}` pair, itself underscored) reads | ||
| 34 | +/// back whole. | ||
| 35 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 36 | +pub struct MealAttendanceId { | ||
| 37 | + menu: MenuId, | ||
| 38 | + student: UserId, | ||
| 39 | +} | ||
| 31 | 40 | ||
| 32 | impl MealAttendanceId { | 41 | impl MealAttendanceId { |
| 33 | - /// A deterministic id for the (menu, student) pair — same trick as | ||
| 34 | - /// [`MealBookingId`](crate::domain::meal_booking::MealBookingId). ULID keys | ||
| 35 | - /// are alphanumeric, so `_` is an unambiguous joiner. | ||
| 36 | pub fn composite(menu: &MenuId, student: &UserId) -> Self { | 42 | pub fn composite(menu: &MenuId, student: &UserId) -> Self { |
| 37 | - Self(RecordId::new( | 43 | + Self { |
| 38 | - MEAL_ATTENDANCE_TABLE, | 44 | + menu: menu.clone(), |
| 39 | - format!("{}_{}", menu.key(), student.key()), | 45 | + student: *student, |
| 40 | - )) | 46 | + } |
| 41 | } | 47 | } |
| 42 | 48 | ||
| 43 | - pub fn record(&self) -> RecordId { | 49 | + /// Parse the `{menu}_{student}` wire form. A key that parses as no pair |
| 44 | - self.0.clone() | 50 | + /// reads as the nil pair, which matches no row — exactly the 404 a |
| 51 | + /// dangling composite key produced under the old store, without turning a | ||
| 52 | + /// typo into a panic. | ||
| 53 | + pub fn from_key(key: &str) -> Self { | ||
| 54 | + let (menu, student) = key.rsplit_once('_').unwrap_or(("", "")); | ||
| 55 | + Self { | ||
| 56 | + menu: MenuId::from_key(menu), | ||
| 57 | + student: UserId::from_key(student), | ||
| 58 | + } | ||
| 45 | } | 59 | } |
| 46 | 60 | ||
| 47 | - pub fn key(&self) -> &str { | 61 | + /// The `{menu}_{student}` wire form. |
| 48 | - match &self.0.key { | 62 | + pub fn key(&self) -> String { |
| 49 | - RecordIdKey::String(key) => key, | 63 | + format!("{}_{}", self.menu.key(), self.student.key()) |
| 50 | - _ => "", | 64 | + } |
| 51 | - } | 65 | + |
| 66 | + pub fn menu(&self) -> &MenuId { | ||
| 67 | + &self.menu | ||
| 68 | + } | ||
| 69 | + | ||
| 70 | + pub fn student(&self) -> UserId { | ||
| 71 | + self.student | ||
| 52 | } | 72 | } |
| 53 | } | 73 | } |
| 54 | 74 | ||
| 55 | /// `served` or `missed`, and nothing else — see the module header. | 75 | /// `served` or `missed`, and nothing else — see the module header. |
| 56 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 76 | +#[derive(Debug, Clone, PartialEq, Eq, Type)] |
| 77 | +#[sqlx(transparent)] | ||
| 57 | pub struct MealAttendanceStatus(String); | 78 | pub struct MealAttendanceStatus(String); |
| 58 | 79 | ||
| 59 | impl MealAttendanceStatus { | 80 | impl MealAttendanceStatus { |
| @@ -73,9 +94,8 @@ impl MealAttendanceStatus { | |||
| 73 | } | 94 | } |
| 74 | } | 95 | } |
| 75 | 96 | ||
| 76 | -#[derive(Debug, Clone, SurrealValue)] | 97 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 77 | pub struct MealAttendance { | 98 | pub struct MealAttendance { |
| 78 | - pub(crate) id: MealAttendanceId, | ||
| 79 | pub(crate) menu: MenuId, | 99 | pub(crate) menu: MenuId, |
| 80 | pub(crate) student: UserId, | 100 | pub(crate) student: UserId, |
| 81 | pub(crate) status: MealAttendanceStatus, | 101 | pub(crate) status: MealAttendanceStatus, |
| @@ -84,10 +104,6 @@ pub struct MealAttendance { | |||
| 84 | } | 104 | } |
| 85 | 105 | ||
| 86 | impl MealAttendance { | 106 | impl MealAttendance { |
| 87 | - pub fn get_id(&self) -> &MealAttendanceId { | ||
| 88 | - &self.id | ||
| 89 | - } | ||
| 90 | - | ||
| 91 | pub fn get_menu(&self) -> &MenuId { | 107 | pub fn get_menu(&self) -> &MenuId { |
| 92 | &self.menu | 108 | &self.menu |
| 93 | } | 109 | } |
src/domain/meal_booking.rsmodified+105 -90
| @@ -1,6 +1,7 @@ | |||
| 1 | //! A student's seat on a published [`Menu`]. One row per (menu, student), | 1 | //! A student's seat on a published [`Menu`]. One row per (menu, student), |
| 2 | -//! keyed by a deterministic composite id — the same pair always maps to the | 2 | +//! |
| 3 | -//! same record, so booking is a single atomic UPSERT with no find-then-insert | 3 | +//! keyed by the natural composite primary key — the same pair always maps to |
| 4 | +//! the same row, so booking is a single atomic upsert with no find-then-insert | ||
| 4 | //! race and one-row-per-pair by construction. | 5 | //! race and one-row-per-pair by construction. |
| 5 | //! | 6 | //! |
| 6 | //! This module is the pure row shape: the id and status, the booking row, and | 7 | //! This module is the pure row shape: the id and status, the booking row, and |
| @@ -16,11 +17,11 @@ | |||
| 16 | //! to `cancelled` with a `cancelled_at` stamp, so the freed seat is still | 17 | //! to `cancelled` with a `cancelled_at` stamp, so the freed seat is still |
| 17 | //! auditable against the money it moved. Only `booked` rows count against | 18 | //! auditable against the money it moved. Only `booked` rows count against |
| 18 | //! the menu's capacity, which is what makes the seat genuinely free again — | 19 | //! the menu's capacity, which is what makes the seat genuinely free again — |
| 19 | -//! and re-booking is the same UPSERT flipping it back. | 20 | +//! and re-booking is the same upsert flipping it back. |
| 20 | //! - **Capacity is the menu's `seats_booked` counter**, claimed by a | 21 | //! - **Capacity is the menu's `seats_booked` counter**, claimed by a |
| 21 | -//! conditional single-record write ([`cap`](crate::db::cap)). Counting the rows instead is | 22 | +//! conditional single-row write ([`cap`](crate::db::cap)). Counting the rows instead is |
| 22 | -//! write-skew — SurrealDB does not conflict-check a cross-record count | 23 | +//! write-skew — a cross-row count checked outside the insert can always be |
| 23 | -//! against a concurrent insert — and a process-wide lock around that count | 24 | +//! overtaken by a racing insert — and a process-wide lock around that count |
| 24 | //! is released around the very round trip the racing insert lands in. | 25 | //! is released around the very round trip the racing insert lands in. |
| 25 | //! Cancelling gives the seat back in the *same transaction* as the flip. | 26 | //! Cancelling gives the seat back in the *same transaction* as the flip. |
| 26 | //! - **The price is claimed, not just read.** The seat is taken at the menu | 27 | //! - **The price is claimed, not just read.** The seat is taken at the menu |
| @@ -36,9 +37,8 @@ | |||
| 36 | //! trails the seat by one write can be overtaken by the next attempt and | 37 | //! trails the seat by one write can be overtaken by the next attempt and |
| 37 | //! stranded forever: every ledger id carries the attempt it belongs to. | 38 | //! stranded forever: every ledger id carries the attempt it belongs to. |
| 38 | 39 | ||
| 39 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 40 | +use sqlx::Type; |
| 40 | 41 | ||
| 41 | -use crate::constant::MEAL_BOOKING_TABLE; | ||
| 42 | use crate::domain::meal_ledger::LedgerAmount; | 42 | use crate::domain::meal_ledger::LedgerAmount; |
| 43 | use crate::domain::menu::{MenuDate, MenuId, MenuSlot}; | 43 | use crate::domain::menu::{MenuDate, MenuId, MenuSlot}; |
| 44 | use crate::domain::settings::{MealSlotDef, Settings}; | 44 | use crate::domain::settings::{MealSlotDef, Settings}; |
| @@ -46,56 +46,61 @@ use crate::domain::timestamp::Timestamp; | |||
| 46 | use crate::domain::user::UserId; | 46 | use crate::domain::user::UserId; |
| 47 | use crate::error::AppError; | 47 | use crate::error::AppError; |
| 48 | 48 | ||
| 49 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 49 | +/// The (menu, student) pair — the table's natural composite primary key. |
| 50 | -pub struct MealBookingId(RecordId); | 50 | +/// UUID strings carry only `-`, so `_` is an unambiguous joiner — and the |
| 51 | +/// student half is last, so the menu key (a `{date}_{slot}` pair, itself | ||
| 52 | +/// underscored) reads back whole. | ||
| 53 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 54 | +pub struct MealBookingId { | ||
| 55 | + menu: MenuId, | ||
| 56 | + student: UserId, | ||
| 57 | +} | ||
| 51 | 58 | ||
| 52 | impl MealBookingId { | 59 | impl MealBookingId { |
| 53 | - /// A deterministic id for the (menu, student) pair — same trick as | ||
| 54 | - /// `EnrollmentId`. ULID keys are alphanumeric, so `_` is an unambiguous | ||
| 55 | - /// joiner. | ||
| 56 | pub fn composite(menu: &MenuId, student: &UserId) -> Self { | 60 | pub fn composite(menu: &MenuId, student: &UserId) -> Self { |
| 57 | - Self(RecordId::new( | 61 | + Self { |
| 58 | - MEAL_BOOKING_TABLE, | 62 | + menu: menu.clone(), |
| 59 | - format!("{}_{}", menu.key(), student.key()), | 63 | + student: *student, |
| 60 | - )) | 64 | + } |
| 61 | } | 65 | } |
| 62 | 66 | ||
| 67 | + /// Parse the `{menu}_{student}` wire form. A key that parses as no pair | ||
| 68 | + /// reads as the nil pair, which matches no row — exactly the 404 a | ||
| 69 | + /// dangling composite key produced under the old store, without turning a | ||
| 70 | + /// typo into a panic. | ||
| 63 | pub fn from_key(key: &str) -> Self { | 71 | pub fn from_key(key: &str) -> Self { |
| 64 | - Self(RecordId::new(MEAL_BOOKING_TABLE, key)) | 72 | + let (menu, student) = key.rsplit_once('_').unwrap_or(("", "")); |
| 73 | + Self { | ||
| 74 | + menu: MenuId::from_key(menu), | ||
| 75 | + student: UserId::from_key(student), | ||
| 76 | + } | ||
| 65 | } | 77 | } |
| 66 | 78 | ||
| 67 | - /// Who the seat is for, read straight back off the key: [`Self::composite`] | 79 | + /// The `{menu}_{student}` wire form. |
| 68 | - /// joins with `_` and a ULID user key carries none, so the last segment is | 80 | + pub fn key(&self) -> String { |
| 69 | - /// always the student (a slot name may well hold one, and the menu half is | 81 | + format!("{}_{}", self.menu.key(), self.student.key()) |
| 70 | - /// in front). `None` for a key no `composite` ever minted. | 82 | + } |
| 83 | + | ||
| 84 | + /// Who the seat is for, read straight off the pair. | ||
| 71 | /// | 85 | /// |
| 72 | /// This is what lets a cancel decide *whose* seat it is asked to free | 86 | /// This is what lets a cancel decide *whose* seat it is asked to free |
| 73 | /// before reading the row — the id is fully derivable from a menu and a | 87 | /// before reading the row — the id is fully derivable from a menu and a |
| 74 | /// user id, both readable by a teacher, so a 403-or-404 answered off the | 88 | /// user id, both readable by a teacher, so a 403-or-404 answered off the |
| 75 | /// row is an existence oracle for the manager-only booking list. | 89 | /// row is an existence oracle for the manager-only booking list. |
| 76 | - pub fn student(&self) -> Option<UserId> { | 90 | + pub fn student(&self) -> UserId { |
| 77 | - self.key() | 91 | + self.student |
| 78 | - .rsplit_once('_') | ||
| 79 | - .map(|(_, student)| UserId::from_key(student)) | ||
| 80 | } | 92 | } |
| 81 | 93 | ||
| 82 | - pub fn record(&self) -> RecordId { | 94 | + pub fn menu(&self) -> &MenuId { |
| 83 | - self.0.clone() | 95 | + &self.menu |
| 84 | - } | ||
| 85 | - | ||
| 86 | - pub fn key(&self) -> &str { | ||
| 87 | - match &self.0.key { | ||
| 88 | - RecordIdKey::String(key) => key, | ||
| 89 | - _ => "", | ||
| 90 | - } | ||
| 91 | } | 96 | } |
| 92 | } | 97 | } |
| 93 | 98 | ||
| 94 | -/// Where a booking stands. `untagged` + `rename_all` store it as the bare | 99 | +/// Where a booking stands. Stored as the bare lowercase TEXT value the |
| 95 | -/// lowercase string the `status` column types as, exactly like | 100 | +/// `status` column carries, exactly like |
| 96 | /// [`AppointmentStatus`](crate::domain::appointment::AppointmentStatus). | 101 | /// [`AppointmentStatus`](crate::domain::appointment::AppointmentStatus). |
| 97 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | 102 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] |
| 98 | -#[surreal(untagged, rename_all = "lowercase")] | 103 | +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] |
| 99 | pub enum MealBookingStatus { | 104 | pub enum MealBookingStatus { |
| 100 | Booked, | 105 | Booked, |
| 101 | Cancelled, | 106 | Cancelled, |
| @@ -111,9 +116,8 @@ impl MealBookingStatus { | |||
| 111 | } | 116 | } |
| 112 | } | 117 | } |
| 113 | 118 | ||
| 114 | -#[derive(Debug, Clone, SurrealValue)] | 119 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 115 | pub struct MealBooking { | 120 | pub struct MealBooking { |
| 116 | - pub(crate) id: MealBookingId, | ||
| 117 | pub(crate) menu: MenuId, | 121 | pub(crate) menu: MenuId, |
| 118 | pub(crate) student: UserId, | 122 | pub(crate) student: UserId, |
| 119 | pub(crate) booked_by: UserId, | 123 | pub(crate) booked_by: UserId, |
| @@ -123,7 +127,7 @@ pub struct MealBooking { | |||
| 123 | /// idempotence key, so a re-book bills afresh while a repeat `POST` of a | 127 | /// idempotence key, so a re-book bills afresh while a repeat `POST` of a |
| 124 | /// seat already held bills nothing. | 128 | /// seat already held bills nothing. |
| 125 | pub(crate) attempt: i64, | 129 | pub(crate) attempt: i64, |
| 126 | - /// What the menu cost when the current attempt took the seat; `None` means | 130 | + /// What the menu cost when the current attempt took the seat; `NULL` means |
| 127 | /// it was free *then*. Recorded rather than inferred: without it, "the menu | 131 | /// it was free *then*. Recorded rather than inferred: without it, "the menu |
| 128 | /// was free" is indistinguishable from "not billed yet", and a dish added | 132 | /// was free" is indistinguishable from "not billed yet", and a dish added |
| 129 | /// afterwards bills a seat that was free when taken. | 133 | /// afterwards bills a seat that was free when taken. |
| @@ -133,10 +137,6 @@ pub struct MealBooking { | |||
| 133 | } | 137 | } |
| 134 | 138 | ||
| 135 | impl MealBooking { | 139 | impl MealBooking { |
| 136 | - pub fn get_id(&self) -> &MealBookingId { | ||
| 137 | - &self.id | ||
| 138 | - } | ||
| 139 | - | ||
| 140 | pub fn get_menu(&self) -> &MenuId { | 140 | pub fn get_menu(&self) -> &MenuId { |
| 141 | &self.menu | 141 | &self.menu |
| 142 | } | 142 | } |
| @@ -168,6 +168,12 @@ impl MealBooking { | |||
| 168 | pub fn get_created_at(&self) -> Timestamp { | 168 | pub fn get_created_at(&self) -> Timestamp { |
| 169 | self.created_at | 169 | self.created_at |
| 170 | } | 170 | } |
| 171 | + | ||
| 172 | + /// The id of the seat this row holds — the pair that is the row's primary | ||
| 173 | + /// key. | ||
| 174 | + pub fn id(&self) -> MealBookingId { | ||
| 175 | + MealBookingId::composite(&self.menu, &self.student) | ||
| 176 | + } | ||
| 171 | } | 177 | } |
| 172 | 178 | ||
| 173 | /// The school's meal deadline policy, resolved once per request: how many | 179 | /// The school's meal deadline policy, resolved once per request: how many |
| @@ -271,20 +277,20 @@ pub(crate) fn check_day_not_past(date: &MenuDate) -> Result<(), AppError> { | |||
| 271 | /// (the slot list is read live). | 277 | /// (the slot list is read live). |
| 272 | /// | 278 | /// |
| 273 | /// A date no serving instant can be computed from **fails closed**. A menu on | 279 | /// A date no serving instant can be computed from **fails closed**. A menu on |
| 274 | -/// an impossible day (a 31st of February — refused by [`MenuDate`] now, but | 280 | +/// an impossible day (a 31st of February — refused by [`MenuDate`]) otherwise |
| 275 | -/// rows written before that rule are still on the volume) otherwise skipped the | 281 | +/// skipped the deadline entirely, silently and forever, however large the |
| 276 | -/// deadline entirely, silently and forever, however large the school set it: | 282 | +/// school set it: the one menu with no cutoff at all would be the one nobody |
| 277 | -/// the one menu with no cutoff at all would be the one nobody meant to publish. | 283 | +/// meant to publish. Refusing is the only answer that keeps "the deadline |
| 278 | -/// Refusing is the only answer that keeps "the deadline binds every menu" true; | 284 | +/// binds every menu" true; the menu has to be republished on a real day to |
| 279 | -/// the menu has to be republished on a real day to become bookable again. | 285 | +/// become bookable again. |
| 280 | pub(crate) fn check_cutoff( | 286 | pub(crate) fn check_cutoff( |
| 281 | date: &MenuDate, | 287 | date: &MenuDate, |
| 282 | slot: &MenuSlot, | 288 | slot: &MenuSlot, |
| 283 | cutoff: &MealCutoff, | 289 | cutoff: &MealCutoff, |
| 284 | ) -> Result<(), AppError> { | 290 | ) -> Result<(), AppError> { |
| 285 | // A school with no cutoff configured closes nothing anyway, so an | 291 | // A school with no cutoff configured closes nothing anyway, so an |
| 286 | - // impossible date is not refused there either — that would take the canteen | 292 | + // impossible date is not refused there either — that would take the |
| 287 | - // offline for a deadline the school never set. | 293 | + // canteen offline for a deadline the school never set. |
| 288 | let Some(minutes) = cutoff.minutes else { | 294 | let Some(minutes) = cutoff.minutes else { |
| 289 | return Ok(()); | 295 | return Ok(()); |
| 290 | }; | 296 | }; |
| @@ -312,22 +318,8 @@ pub(crate) fn check_cutoff( | |||
| 312 | 318 | ||
| 313 | #[cfg(test)] | 319 | #[cfg(test)] |
| 314 | mod tests { | 320 | mod tests { |
| 315 | - use surrealdb::types::Value; | ||
| 316 | - | ||
| 317 | use super::*; | 321 | use super::*; |
| 318 | 322 | ||
| 319 | - /// The `status` column is `TYPE string`: an object-wrapped enum would be | ||
| 320 | - /// rejected on write, and the `status = 'booked'` capacity count would | ||
| 321 | - /// silently match nothing. | ||
| 322 | - #[test] | ||
| 323 | - fn status_stores_as_a_bare_string() { | ||
| 324 | - for status in [MealBookingStatus::Booked, MealBookingStatus::Cancelled] { | ||
| 325 | - let value = status.into_value(); | ||
| 326 | - assert_eq!(value, Value::String(status.as_str().to_string())); | ||
| 327 | - assert_eq!(MealBookingStatus::from_value(value).unwrap(), status); | ||
| 328 | - } | ||
| 329 | - } | ||
| 330 | - | ||
| 331 | fn cutoff(minutes: Option<i64>, serving_minute: Option<i64>) -> MealCutoff { | 323 | fn cutoff(minutes: Option<i64>, serving_minute: Option<i64>) -> MealCutoff { |
| 332 | MealCutoff { | 324 | MealCutoff { |
| 333 | minutes, | 325 | minutes, |
| @@ -350,23 +342,6 @@ mod tests { | |||
| 350 | assert!(check_cutoff(&past, &lunch(), &cutoff(Some(60), Some(720))).is_err()); | 342 | assert!(check_cutoff(&past, &lunch(), &cutoff(Some(60), Some(720))).is_err()); |
| 351 | } | 343 | } |
| 352 | 344 | ||
| 353 | - /// A menu stored on a day that does not exist has no serving instant, so no | ||
| 354 | - /// deadline can be counted back from it — and it must therefore refuse, not | ||
| 355 | - /// pass. `MenuDate::try_new` rejects such a date now; this is a row written | ||
| 356 | - /// before that rule, read back off the store exactly as the domain reads it | ||
| 357 | - /// (the column is `TYPE string`), which is the only way one can still turn | ||
| 358 | - /// up. Passing is what let it be booked and cancelled with no cutoff ever. | ||
| 359 | - #[test] | ||
| 360 | - fn an_impossible_day_has_no_open_deadline() { | ||
| 361 | - let impossible = MenuDate::from_value(Value::String("2026-02-29".into())).unwrap(); | ||
| 362 | - assert!(MenuDate::try_new(impossible.as_str()).is_err()); | ||
| 363 | - assert!(check_cutoff(&impossible, &lunch(), &cutoff(Some(60), Some(720))).is_err()); | ||
| 364 | - assert!(check_cutoff(&impossible, &lunch(), &cutoff(Some(60), None)).is_err()); | ||
| 365 | - // A school that set no cutoff closes nothing anyway, impossible day or | ||
| 366 | - // not: refusing there would take the canteen offline for no deadline. | ||
| 367 | - assert!(check_cutoff(&impossible, &lunch(), &cutoff(None, Some(720))).is_ok()); | ||
| 368 | - } | ||
| 369 | - | ||
| 370 | /// A slot with no serving hour has no instant to count a deadline back | 345 | /// A slot with no serving hour has no instant to count a deadline back |
| 371 | /// from, so nothing on it ever closes. It used to count from midnight UTC | 346 | /// from, so nothing on it ever closes. It used to count from midnight UTC |
| 372 | /// of the menu's day, which shut every same-day menu the moment a school | 347 | /// of the menu's day, which shut every same-day menu the moment a school |
| @@ -411,11 +386,6 @@ mod tests { | |||
| 411 | ) | 386 | ) |
| 412 | .is_ok() | 387 | .is_ok() |
| 413 | ); | 388 | ); |
| 414 | - // A day no calendar can place is left to the cutoff, which fails it | ||
| 415 | - // closed when one is configured; guessing "past" here would shut the | ||
| 416 | - // canteen for a school that set no deadline. | ||
| 417 | - let impossible = MenuDate::from_value(Value::String("2026-02-29".into())).unwrap(); | ||
| 418 | - assert!(check_day_not_past(&impossible).is_ok()); | ||
| 419 | } | 389 | } |
| 420 | 390 | ||
| 421 | /// The instant the deadline counts back from: midnight UTC of the day plus | 391 | /// The instant the deadline counts back from: midnight UTC of the day plus |
| @@ -439,4 +409,49 @@ mod tests { | |||
| 439 | ); | 409 | ); |
| 440 | assert_eq!(MealCutoff::default().serving_minute(&lunch()), None); | 410 | assert_eq!(MealCutoff::default().serving_minute(&lunch()), None); |
| 441 | } | 411 | } |
| 412 | + | ||
| 413 | + #[test] | ||
| 414 | + fn status_as_str_is_the_storage_form() { | ||
| 415 | + assert_eq!(MealBookingStatus::Booked.as_str(), "booked"); | ||
| 416 | + assert_eq!(MealBookingStatus::Cancelled.as_str(), "cancelled"); | ||
| 417 | + } | ||
| 418 | + | ||
| 419 | + /// The `status` column is `TEXT` with a CHECK on these exact words; the | ||
| 420 | + /// sqlx encoding must never drift from `as_str`, or the `status = | ||
| 421 | + /// 'booked'` capacity count silently matches nothing. | ||
| 422 | + #[test] | ||
| 423 | + fn sqlx_encodes_the_storage_form() { | ||
| 424 | + let mut buf = sqlx::postgres::PgArgumentBuffer::default(); | ||
| 425 | + for status in [MealBookingStatus::Booked, MealBookingStatus::Cancelled] { | ||
| 426 | + buf.clear(); | ||
| 427 | + sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&status, &mut buf); | ||
| 428 | + assert_eq!(std::str::from_utf8(&buf).unwrap(), status.as_str()); | ||
| 429 | + } | ||
| 430 | + } | ||
| 431 | + | ||
| 432 | + /// The composite key round-trips: the menu half (itself underscored) reads | ||
| 433 | + /// back whole, and a key that parses as no pair reads as the nil pair that | ||
| 434 | + /// matches no row. | ||
| 435 | + #[test] | ||
| 436 | + fn the_booking_key_round_trips() { | ||
| 437 | + let menu = MenuId::for_slot( | ||
| 438 | + &MenuDate::try_new("2026-09-14").unwrap(), | ||
| 439 | + &MenuSlot::try_new( | ||
| 440 | + "öğle yemeği", | ||
| 441 | + &[MealSlotDef::try_new("öğle yemeği", None).unwrap()], | ||
| 442 | + ) | ||
| 443 | + .unwrap(), | ||
| 444 | + ); | ||
| 445 | + let student = UserId::from_key("018f1a00-0000-7000-8000-000000000001"); | ||
| 446 | + let id = MealBookingId::composite(&menu, &student); | ||
| 447 | + assert_eq!(MealBookingId::from_key(&id.key()), id); | ||
| 448 | + assert_eq!( | ||
| 449 | + MealBookingId::from_key("no-pair-here").student(), | ||
| 450 | + UserId::from_key("") | ||
| 451 | + ); | ||
| 452 | + assert_eq!( | ||
| 453 | + MealBookingId::from_key("no-pair-here").menu.key(), | ||
| 454 | + MenuId::from_key("").key() | ||
| 455 | + ); | ||
| 456 | + } | ||
| 442 | } | 457 | } |
src/domain/meal_ledger.rsmodified+92 -95
| @@ -1,11 +1,11 @@ | |||
| 1 | //! The food program's money: an **append-only** ledger of what a student was | 1 | //! The food program's money: an **append-only** ledger of what a student was |
| 2 | //! charged and what they paid. | 2 | //! charged and what they paid. |
| 3 | //! | 3 | //! |
| 4 | -//! Nothing here ever `UPDATE`s or `DELETE`s a row, and no such path exists — | 4 | +//! Nothing here ever `UPDATE`s or `DELETE`s a row, and no such path exists. A |
| 5 | -//! every field is `READONLY` in the schema as well. A ledger line that can be | 5 | +//! ledger line that can be edited or dropped silently rewrites a student's |
| 6 | -//! edited or dropped silently rewrites a student's financial history with no | 6 | +//! financial history with no trace of the rewrite; a mistake is corrected by |
| 7 | -//! trace of the rewrite; a mistake is corrected by appending the opposing | 7 | +//! appending the opposing line, which leaves both the mistake and the |
| 8 | -//! line, which leaves both the mistake and the correction visible. | 8 | +//! correction visible. |
| 9 | //! | 9 | //! |
| 10 | //! **The balance is never stored.** It is always the fold | 10 | //! **The balance is never stored.** It is always the fold |
| 11 | //! | 11 | //! |
| @@ -33,7 +33,7 @@ | |||
| 33 | //! than its flip could be overtaken by that re-book and then never be | 33 | //! than its flip could be overtaken by that re-book and then never be |
| 34 | //! writable at all. | 34 | //! writable at all. |
| 35 | //! - **Every booking line is keyed by `(booking, attempt)`.** Both the charge | 35 | //! - **Every booking line is keyed by `(booking, attempt)`.** Both the charge |
| 36 | -//! and its reversal derive their record id from the seat and the attempt | 36 | +//! and its reversal derive their row id from the seat and the attempt |
| 37 | //! number, so replaying either writes nothing at all. Money must never | 37 | //! number, so replaying either writes nothing at all. Money must never |
| 38 | //! depend on a "has this been billed yet?" scan: two concurrent `POST`s of | 38 | //! depend on a "has this been billed yet?" scan: two concurrent `POST`s of |
| 39 | //! one seat can both read "no charge yet" and both append, which is how a | 39 | //! one seat can both read "no charge yet" and both append, which is how a |
| @@ -42,7 +42,7 @@ | |||
| 42 | //! client-chosen `request_key`, which lands in the line's id | 42 | //! client-chosen `request_key`, which lands in the line's id |
| 43 | //! ([`MealLedgerId::for_request`]) and makes the call retry-safe by the same | 43 | //! ([`MealLedgerId::for_request`]) and makes the call retry-safe by the same |
| 44 | //! identity rule: a retry after a timeout resolves the line it already wrote. | 44 | //! identity rule: a retry after a timeout resolves the line it already wrote. |
| 45 | -//! Without one, a fresh ulid is minted and a resent request is a second | 45 | +//! Without one, a fresh id is minted and a resent request is a second |
| 46 | //! credit — which nothing here can edit or delete afterwards. | 46 | //! credit — which nothing here can edit or delete afterwards. |
| 47 | //! - **A no-show still pays.** Meal attendance has zero billing effect — | 47 | //! - **A no-show still pays.** Meal attendance has zero billing effect — |
| 48 | //! nothing in this file reads or writes it. Do not add a no-show penalty | 48 | //! nothing in this file reads or writes it. Do not add a no-show penalty |
| @@ -50,56 +50,51 @@ | |||
| 50 | //! | 50 | //! |
| 51 | //! Money is `i64` minor units (kuruş) end to end. No float, no decimal, ever. | 51 | //! Money is `i64` minor units (kuruş) end to end. No float, no decimal, ever. |
| 52 | //! | 52 | //! |
| 53 | +//! The ledger row ids are **derived TEXT keys**, not minted uuids — they are | ||
| 54 | +//! the identity the store's uniqueness check enforces (`id TEXT PRIMARY | ||
| 55 | +//! KEY`): a duplicate insert of the same key is the "already billed" answer. | ||
| 56 | +//! Only the unkeyed-credit fallback mints a fresh (uuid-string) key. | ||
| 57 | +//! | ||
| 53 | //! The writes and the SUM/balance reads live in [`crate::db::meal_ledger`]; | 58 | //! The writes and the SUM/balance reads live in [`crate::db::meal_ledger`]; |
| 54 | //! the charge/reversal and credit workflows in | 59 | //! the charge/reversal and credit workflows in |
| 55 | //! [`crate::service::meal_ledger`]. | 60 | //! [`crate::service::meal_ledger`]. |
| 56 | 61 | ||
| 57 | -use std::sync::LazyLock; | 62 | +use serde::{Deserialize, Serialize}; |
| 58 | - | 63 | +use sqlx::Type; |
| 59 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 60 | -use ulid::Generator; | ||
| 61 | 64 | ||
| 62 | -use crate::constant::{ | 65 | +use crate::constant::{MAX_LEDGER_AMOUNT_MINOR, MAX_LEDGER_METHOD_LEN, MAX_LEDGER_NOTE_LEN}; |
| 63 | - MAX_LEDGER_AMOUNT_MINOR, MAX_LEDGER_METHOD_LEN, MAX_LEDGER_NOTE_LEN, MEAL_LEDGER_TABLE, | ||
| 64 | -}; | ||
| 65 | // The client-chosen idempotence key both ledgers take — one grammar, one | 66 | // The client-chosen idempotence key both ledgers take — one grammar, one |
| 66 | // validator, one type, rather than a second newtype that could drift from it. | 67 | // validator, one type, rather than a second newtype that could drift from it. |
| 68 | +use crate::domain::monotonic_id::next_uuid; | ||
| 67 | use crate::domain::payment_ledger::PaymentRequestKey; | 69 | use crate::domain::payment_ledger::PaymentRequestKey; |
| 68 | use crate::domain::timestamp::Timestamp; | 70 | use crate::domain::timestamp::Timestamp; |
| 69 | use crate::domain::user::UserId; | 71 | use crate::domain::user::UserId; |
| 70 | use crate::error::ValidationError; | 72 | use crate::error::ValidationError; |
| 71 | use crate::validate::validate_optional; | 73 | use crate::validate::validate_optional; |
| 72 | 74 | ||
| 73 | -/// Mints ledger ids in write order — `Ulid::generate()`'s random low bits sort | 75 | +/// The ledger line's id — a derived TEXT key (`id TEXT PRIMARY KEY`): |
| 74 | -/// arbitrarily within one millisecond, which would scramble the `id` tie-break | 76 | +/// `{booking-key}_c{attempt}` / `{booking-key}_r{attempt}` for the booking |
| 75 | -/// of the newest-first statement below. | 77 | +/// lines, `{student-key}_k_{request_key}` for a keyed credit, or a fresh |
| 76 | -static IDS: LazyLock<std::sync::Mutex<Generator>> = | 78 | +/// uuid-string key for an unkeyed one. |
| 77 | - LazyLock::new(|| std::sync::Mutex::new(Generator::new())); | 79 | +#[derive(Debug, Clone, PartialEq, Eq, Type)] |
| 78 | - | 80 | +#[sqlx(transparent)] |
| 79 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 81 | +pub struct MealLedgerId(String); |
| 80 | -pub struct MealLedgerId(RecordId); | ||
| 81 | 82 | ||
| 82 | impl MealLedgerId { | 83 | impl MealLedgerId { |
| 84 | + /// A fresh key in write order — the process-wide uuid v7 generator's | ||
| 85 | + /// string form, so the `id` tie-break of the newest-first statement below | ||
| 86 | + /// still sorts in mint order. | ||
| 83 | pub fn generate() -> Self { | 87 | pub fn generate() -> Self { |
| 84 | - let mut ids = IDS.lock().expect("meal ledger id generator poisoned"); | 88 | + Self(next_uuid().to_string()) |
| 85 | - // The only error is exhausting the random bits within one millisecond | ||
| 86 | - // (2^80 ids deep); it clears itself as the clock ticks, so retry. | ||
| 87 | - let ulid = loop { | ||
| 88 | - if let Ok(ulid) = ids.generate() { | ||
| 89 | - break ulid; | ||
| 90 | - } | ||
| 91 | - }; | ||
| 92 | - Self(RecordId::new(MEAL_LEDGER_TABLE, ulid.to_string())) | ||
| 93 | } | 89 | } |
| 94 | 90 | ||
| 95 | /// The one line a booking attempt may ever write of this `kind` — a | 91 | /// The one line a booking attempt may ever write of this `kind` — a |
| 96 | - /// deterministic id, exactly like [`MealBookingId::composite`](crate::domain::meal_booking::MealBookingId::composite). | 92 | + /// deterministic key, exactly like the booking pair itself. Two racing |
| 97 | - /// Two racing | 93 | + /// `POST`s of one seat derive the *same* key and so cannot become two |
| 98 | - /// `POST`s of one seat derive the *same* id and so cannot become two | ||
| 99 | /// charges: idempotence rests on identity, never on a scan that a | 94 | /// charges: idempotence rests on identity, never on a scan that a |
| 100 | /// concurrent writer can slip past. The `attempt` counter is what keeps a | 95 | /// concurrent writer can slip past. The `attempt` counter is what keeps a |
| 101 | /// re-book after a cancel a genuinely fresh charge. Booking keys are | 96 | /// re-book after a cancel a genuinely fresh charge. Booking keys are |
| 102 | - /// `<ulid>_<ulid>`, so the `c`/`r` marker keeps the two kinds apart. | 97 | + /// `<menu>_<student>`, so the `c`/`r` marker keeps the two kinds apart. |
| 103 | pub fn for_attempt( | 98 | pub fn for_attempt( |
| 104 | booking: &crate::domain::meal_booking::MealBookingId, | 99 | booking: &crate::domain::meal_booking::MealBookingId, |
| 105 | attempt: i64, | 100 | attempt: i64, |
| @@ -111,53 +106,34 @@ impl MealLedgerId { | |||
| 111 | // A credit is money arriving out of the blue, tied to no booking. | 106 | // A credit is money arriving out of the blue, tied to no booking. |
| 112 | MealLedgerKind::Credit => 'k', | 107 | MealLedgerKind::Credit => 'k', |
| 113 | }; | 108 | }; |
| 114 | - Self(RecordId::new( | 109 | + Self(format!("{}_{}{attempt}", booking.key(), marker)) |
| 115 | - MEAL_LEDGER_TABLE, | ||
| 116 | - format!("{}_{marker}{attempt}", booking.key()), | ||
| 117 | - )) | ||
| 118 | } | 110 | } |
| 119 | 111 | ||
| 120 | - /// The one credit a `(student, request_key)` pair may ever have. Same trick | 112 | + /// The one credit a `(student, request_key)` pair may ever have. Same |
| 121 | - /// as [`PaymentLedgerId::for_request`](crate::domain::payment_ledger::PaymentLedgerId::for_request), | 113 | + /// identity trick as |
| 114 | + /// [`PaymentLedgerId::for_request`](crate::domain::payment_ledger::PaymentLedgerId::for_request), | ||
| 122 | /// scoped by the student because a credit points at no line of its own: one | 115 | /// scoped by the student because a credit points at no line of its own: one |
| 123 | /// office's "receipt-114" cannot land on another student's account, and a | 116 | /// office's "receipt-114" cannot land on another student's account, and a |
| 124 | /// key replayed for the wrong student cannot resolve to this line at all. | 117 | /// key replayed for the wrong student cannot resolve to this line at all. |
| 125 | /// | 118 | /// |
| 126 | - /// The grammar parses uniquely because `_` joins the parts. A booking line | 119 | + /// The grammar parses uniquely because `_` joins the parts: a student key |
| 127 | - /// is `<date>_<slot>_<student>_c<n>`, whose first part carries the `-` of a | 120 | + /// is a UUID (hex and `-` only) and a `request_key` is |
| 128 | - /// `YYYY-MM-DD` day, and an unkeyed line is a bare ULID; a credit's first | 121 | + /// [`crate::validate::validate_request_key`]'s `[A-Za-z0-9-]` — neither can |
| 129 | - /// part is a student ULID (`[0-9A-Z]`) and a `request_key` is | 122 | + /// spell the `_k_` separator. No key can therefore derive an id some other |
| 130 | - /// [`crate::validate::validate_request_key`]'s `[A-Za-z0-9-]`, which cannot | 123 | + /// line owns — a collision would hand money to the wrong row. |
| 131 | - /// spell a separator plus a marker. No key can therefore derive an id some | ||
| 132 | - /// other line owns — a collision would hand money to the wrong row. | ||
| 133 | pub fn for_request(student: &UserId, key: &PaymentRequestKey) -> Self { | 124 | pub fn for_request(student: &UserId, key: &PaymentRequestKey) -> Self { |
| 134 | - Self(RecordId::new( | 125 | + Self(format!("{}_k_{}", student.key(), key.as_str())) |
| 135 | - MEAL_LEDGER_TABLE, | ||
| 136 | - format!("{}_k_{}", student.key(), key.as_str()), | ||
| 137 | - )) | ||
| 138 | - } | ||
| 139 | - | ||
| 140 | - pub fn record(&self) -> RecordId { | ||
| 141 | - self.0.clone() | ||
| 142 | } | 126 | } |
| 143 | 127 | ||
| 144 | pub fn key(&self) -> &str { | 128 | pub fn key(&self) -> &str { |
| 145 | - key_of(&self.0) | 129 | + &self.0 |
| 146 | - } | ||
| 147 | -} | ||
| 148 | - | ||
| 149 | -/// The bare key of a record id — how every id leaves this API. | ||
| 150 | -fn key_of(record: &RecordId) -> &str { | ||
| 151 | - match &record.key { | ||
| 152 | - RecordIdKey::String(key) => key, | ||
| 153 | - _ => "", | ||
| 154 | } | 130 | } |
| 155 | } | 131 | } |
| 156 | 132 | ||
| 157 | -/// What a line means. `untagged` + `rename_all` store it as the bare lowercase | 133 | +/// What a line means. Stored as the bare lowercase TEXT value the `kind` |
| 158 | -/// string the `kind` column types as, in lockstep with `MEAL_LEDGER_KINDS`. | 134 | +/// column carries, in lockstep with `MEAL_LEDGER_KINDS`. |
| 159 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | 135 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] |
| 160 | -#[surreal(untagged, rename_all = "lowercase")] | 136 | +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] |
| 161 | pub enum MealLedgerKind { | 137 | pub enum MealLedgerKind { |
| 162 | Charge, | 138 | Charge, |
| 163 | Credit, | 139 | Credit, |
| @@ -186,7 +162,11 @@ impl MealLedgerKind { | |||
| 186 | 162 | ||
| 187 | /// One line's amount, always positive — the sign is the [`MealLedgerKind`]'s | 163 | /// One line's amount, always positive — the sign is the [`MealLedgerKind`]'s |
| 188 | /// business. Capped so a slipped keystroke cannot book a fortune. | 164 | /// business. Capped so a slipped keystroke cannot book a fortune. |
| 189 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | 165 | +/// |
| 166 | +/// `Serialize`/`Deserialize` ride along because the fee plan's installments | ||
| 167 | +/// (a `Json<Vec<Installment>>` column) embed this same money type. | ||
| 168 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)] | ||
| 169 | +#[sqlx(transparent)] | ||
| 190 | pub struct LedgerAmount(i64); | 170 | pub struct LedgerAmount(i64); |
| 191 | 171 | ||
| 192 | impl LedgerAmount { | 172 | impl LedgerAmount { |
| @@ -207,7 +187,8 @@ impl LedgerAmount { | |||
| 207 | 187 | ||
| 208 | /// How the money arrived ("cash", "havale", …). Free text: the backend never | 188 | /// How the money arrived ("cash", "havale", …). Free text: the backend never |
| 209 | /// speaks to a payment gateway and stores no card data, ever. | 189 | /// speaks to a payment gateway and stores no card data, ever. |
| 210 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 190 | +#[derive(Debug, Clone, PartialEq, Eq, Type)] |
| 191 | +#[sqlx(transparent)] | ||
| 211 | pub struct LedgerMethod(String); | 192 | pub struct LedgerMethod(String); |
| 212 | 193 | ||
| 213 | impl LedgerMethod { | 194 | impl LedgerMethod { |
| @@ -224,7 +205,8 @@ impl LedgerMethod { | |||
| 224 | 205 | ||
| 225 | /// The bookkeeper's own words about a line — a receipt number, whose envelope | 206 | /// The bookkeeper's own words about a line — a receipt number, whose envelope |
| 226 | /// it came in. | 207 | /// it came in. |
| 227 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 208 | +#[derive(Debug, Clone, PartialEq, Eq, Type)] |
| 209 | +#[sqlx(transparent)] | ||
| 228 | pub struct LedgerNote(String); | 210 | pub struct LedgerNote(String); |
| 229 | 211 | ||
| 230 | impl LedgerNote { | 212 | impl LedgerNote { |
| @@ -239,15 +221,16 @@ impl LedgerNote { | |||
| 239 | } | 221 | } |
| 240 | } | 222 | } |
| 241 | 223 | ||
| 242 | -#[derive(Debug, Clone, SurrealValue)] | 224 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 243 | pub struct MealLedger { | 225 | pub struct MealLedger { |
| 244 | pub(crate) id: MealLedgerId, | 226 | pub(crate) id: MealLedgerId, |
| 245 | pub(crate) student: UserId, | 227 | pub(crate) student: UserId, |
| 246 | pub(crate) kind: MealLedgerKind, | 228 | pub(crate) kind: MealLedgerKind, |
| 247 | pub(crate) amount_minor: LedgerAmount, | 229 | pub(crate) amount_minor: LedgerAmount, |
| 248 | - /// What caused the line: a charge points at its `meal_booking`, a reversal | 230 | + /// What caused the line: a charge points at its `meal_booking` row's |
| 249 | - /// at the `meal_ledger` charge it undoes. Untyped, hence a bare `RecordId`. | 231 | + /// `{menu}_{student}` key, a reversal at the `meal_ledger` charge it |
| 250 | - pub(crate) source: Option<RecordId>, | 232 | + /// undoes. Polymorphic by kind, hence a bare TEXT key — no foreign key. |
| 233 | + pub(crate) source: Option<String>, | ||
| 251 | pub(crate) method: Option<LedgerMethod>, | 234 | pub(crate) method: Option<LedgerMethod>, |
| 252 | pub(crate) note: Option<LedgerNote>, | 235 | pub(crate) note: Option<LedgerNote>, |
| 253 | pub(crate) recorded_by: UserId, | 236 | pub(crate) recorded_by: UserId, |
| @@ -273,7 +256,7 @@ impl MealLedger { | |||
| 273 | 256 | ||
| 274 | /// The cause's bare key; which table it lives in follows from the kind. | 257 | /// The cause's bare key; which table it lives in follows from the kind. |
| 275 | pub fn get_source_key(&self) -> Option<&str> { | 258 | pub fn get_source_key(&self) -> Option<&str> { |
| 276 | - self.source.as_ref().map(key_of) | 259 | + self.source.as_deref() |
| 277 | } | 260 | } |
| 278 | 261 | ||
| 279 | pub fn get_method(&self) -> Option<&LedgerMethod> { | 262 | pub fn get_method(&self) -> Option<&LedgerMethod> { |
| @@ -307,14 +290,14 @@ impl MealLedger { | |||
| 307 | let amount = booking.get_price_minor()?; | 290 | let amount = booking.get_price_minor()?; |
| 308 | Some(MealLedger { | 291 | Some(MealLedger { |
| 309 | id: MealLedgerId::for_attempt( | 292 | id: MealLedgerId::for_attempt( |
| 310 | - booking.get_id(), | 293 | + &booking.id(), |
| 311 | booking.get_attempt(), | 294 | booking.get_attempt(), |
| 312 | MealLedgerKind::Charge, | 295 | MealLedgerKind::Charge, |
| 313 | ), | 296 | ), |
| 314 | student: booking.get_student().clone(), | 297 | student: booking.get_student().clone(), |
| 315 | kind: MealLedgerKind::Charge, | 298 | kind: MealLedgerKind::Charge, |
| 316 | amount_minor: amount, | 299 | amount_minor: amount, |
| 317 | - source: Some(booking.get_id().record()), | 300 | + source: Some(booking.id().key()), |
| 318 | method: None, | 301 | method: None, |
| 319 | note: None, | 302 | note: None, |
| 320 | recorded_by: recorded_by.clone(), | 303 | recorded_by: recorded_by.clone(), |
| @@ -323,34 +306,34 @@ impl MealLedger { | |||
| 323 | } | 306 | } |
| 324 | 307 | ||
| 325 | /// The refund `booking`'s current attempt owes, as `(the charge it undoes, | 308 | /// The refund `booking`'s current attempt owes, as `(the charge it undoes, |
| 326 | - /// the reversal line)` — the two ids | 309 | + /// the reversal line)` — the two keys |
| 327 | /// [`release_seat`](crate::db::meal_booking::release_seat) needs to | 310 | /// [`release_seat`](crate::db::meal_booking::release_seat) needs to |
| 328 | /// append the money back inside the transaction that frees the seat. | 311 | /// append the money back inside the transaction that frees the seat. |
| 329 | /// `None` when the seat was never billed (a free menu), which owes no line. | 312 | /// `None` when the seat was never billed (a free menu), which owes no line. |
| 330 | /// | 313 | /// |
| 331 | - /// Only the ids and the row are built here: whether the charge exists is a | 314 | + /// Only the keys and the row are built here: whether the charge exists is |
| 332 | - /// read, and the caller that writes in one transaction has to make it there | 315 | + /// a read, and the caller that writes in one transaction has to make it |
| 333 | - /// rather than a round trip earlier. | 316 | + /// there rather than a round trip earlier. |
| 334 | pub(crate) fn reversal_for( | 317 | pub(crate) fn reversal_for( |
| 335 | booking: &crate::domain::meal_booking::MealBooking, | 318 | booking: &crate::domain::meal_booking::MealBooking, |
| 336 | recorded_by: &UserId, | 319 | recorded_by: &UserId, |
| 337 | ) -> Option<(MealLedgerId, MealLedger)> { | 320 | ) -> Option<(MealLedgerId, MealLedger)> { |
| 338 | let amount = booking.get_price_minor()?; | 321 | let amount = booking.get_price_minor()?; |
| 339 | let charge = MealLedgerId::for_attempt( | 322 | let charge = MealLedgerId::for_attempt( |
| 340 | - booking.get_id(), | 323 | + &booking.id(), |
| 341 | booking.get_attempt(), | 324 | booking.get_attempt(), |
| 342 | MealLedgerKind::Charge, | 325 | MealLedgerKind::Charge, |
| 343 | ); | 326 | ); |
| 344 | let line = MealLedger { | 327 | let line = MealLedger { |
| 345 | id: MealLedgerId::for_attempt( | 328 | id: MealLedgerId::for_attempt( |
| 346 | - booking.get_id(), | 329 | + &booking.id(), |
| 347 | booking.get_attempt(), | 330 | booking.get_attempt(), |
| 348 | MealLedgerKind::Reversal, | 331 | MealLedgerKind::Reversal, |
| 349 | ), | 332 | ), |
| 350 | student: booking.get_student().clone(), | 333 | student: booking.get_student().clone(), |
| 351 | kind: MealLedgerKind::Reversal, | 334 | kind: MealLedgerKind::Reversal, |
| 352 | amount_minor: amount, | 335 | amount_minor: amount, |
| 353 | - source: Some(charge.record()), | 336 | + source: Some(charge.key()), |
| 354 | method: None, | 337 | method: None, |
| 355 | note: None, | 338 | note: None, |
| 356 | recorded_by: recorded_by.clone(), | 339 | recorded_by: recorded_by.clone(), |
| @@ -362,23 +345,23 @@ impl MealLedger { | |||
| 362 | 345 | ||
| 363 | #[cfg(test)] | 346 | #[cfg(test)] |
| 364 | mod tests { | 347 | mod tests { |
| 365 | - use surrealdb::types::Value; | ||
| 366 | - | ||
| 367 | use super::*; | 348 | use super::*; |
| 368 | 349 | ||
| 369 | - /// The `kind` column is `TYPE string`: an object-wrapped enum would be | 350 | + /// The `kind` column is `TEXT` with a CHECK on these exact words; the |
| 370 | - /// rejected on write, and the `kind = 'charge'` lookup would silently | 351 | + /// sqlx encoding must never drift from `as_str`, or the `kind = 'charge'` |
| 371 | - /// match nothing — which would double-charge every re-booking. | 352 | + /// lookup would silently match nothing — which would double-charge every |
| 353 | + /// re-booking. | ||
| 372 | #[test] | 354 | #[test] |
| 373 | - fn kind_stores_as_a_bare_string() { | 355 | + fn sqlx_encodes_the_storage_form() { |
| 356 | + let mut buf = sqlx::postgres::PgArgumentBuffer::default(); | ||
| 374 | for kind in [ | 357 | for kind in [ |
| 375 | MealLedgerKind::Charge, | 358 | MealLedgerKind::Charge, |
| 376 | MealLedgerKind::Credit, | 359 | MealLedgerKind::Credit, |
| 377 | MealLedgerKind::Reversal, | 360 | MealLedgerKind::Reversal, |
| 378 | ] { | 361 | ] { |
| 379 | - let value = kind.into_value(); | 362 | + buf.clear(); |
| 380 | - assert_eq!(value, Value::String(kind.as_str().to_string())); | 363 | + sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&kind, &mut buf); |
| 381 | - assert_eq!(MealLedgerKind::from_value(value).unwrap(), kind); | 364 | + assert_eq!(std::str::from_utf8(&buf).unwrap(), kind.as_str()); |
| 382 | } | 365 | } |
| 383 | } | 366 | } |
| 384 | 367 | ||
| @@ -408,4 +391,18 @@ mod tests { | |||
| 408 | assert!(LedgerAmount::try_new(MAX_LEDGER_AMOUNT_MINOR + 1).is_err()); | 391 | assert!(LedgerAmount::try_new(MAX_LEDGER_AMOUNT_MINOR + 1).is_err()); |
| 409 | assert_eq!(LedgerAmount::try_new(1).unwrap().as_minor(), 1); | 392 | assert_eq!(LedgerAmount::try_new(1).unwrap().as_minor(), 1); |
| 410 | } | 393 | } |
| 394 | + | ||
| 395 | + /// A keyed credit's id is scoped by the student and stable across retries; | ||
| 396 | + /// an unkeyed line mints a fresh uuid-string key. | ||
| 397 | + #[test] | ||
| 398 | + fn credit_keys_derive_deterministically() { | ||
| 399 | + let student = UserId::from_key("018f1a00-0000-7000-8000-000000000001"); | ||
| 400 | + let key = PaymentRequestKey::try_new("receipt-114").unwrap(); | ||
| 401 | + let first = MealLedgerId::for_request(&student, &key); | ||
| 402 | + assert_eq!(MealLedgerId::for_request(&student, &key), first); | ||
| 403 | + assert_eq!(first.key(), format!("{}_k_receipt-114", student.key())); | ||
| 404 | + // A key replayed for another student cannot resolve to the same line. | ||
| 405 | + let other = UserId::from_key("018f1a00-0000-7000-8000-000000000002"); | ||
| 406 | + assert_ne!(MealLedgerId::for_request(&other, &key), first); | ||
| 407 | + } | ||
| 411 | } | 408 | } |
src/domain/menu.rsmodified+40 -59
| @@ -13,9 +13,9 @@ | |||
| 13 | //! The queries live in [`crate::db::menu`]; the kitchen workflows (and the | 13 | //! The queries live in [`crate::db::menu`]; the kitchen workflows (and the |
| 14 | //! dish-cap lock) in [`crate::service::menu`]. | 14 | //! dish-cap lock) in [`crate::service::menu`]. |
| 15 | 15 | ||
| 16 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 16 | +use sqlx::Type; |
| 17 | 17 | ||
| 18 | -use crate::constant::{MAX_MENU_CAPACITY, MENU_TABLE, SLOT_REF_TABLE}; | 18 | +use crate::constant::MAX_MENU_CAPACITY; |
| 19 | use crate::domain::settings::MealSlotDef; | 19 | use crate::domain::settings::MealSlotDef; |
| 20 | use crate::domain::timestamp::Timestamp; | 20 | use crate::domain::timestamp::Timestamp; |
| 21 | use crate::domain::user::UserId; | 21 | use crate::domain::user::UserId; |
| @@ -26,48 +26,45 @@ use crate::error::ValidationError; | |||
| 26 | /// [`crate::db::cap`]). The mirror of | 26 | /// [`crate::db::cap`]). The mirror of |
| 27 | /// [`kind_ref`](crate::domain::exam_result::kind_ref) for exam kinds: the slot | 27 | /// [`kind_ref`](crate::domain::exam_result::kind_ref) for exam kinds: the slot |
| 28 | /// is snapshotted text on the menu, so this row is the only place the two | 28 | /// is snapshotted text on the menu, so this row is the only place the two |
| 29 | -/// tables' relationship is a single record concurrent writes can contend on. | 29 | +/// tables' relationship is a single row concurrent writes can contend on. |
| 30 | -pub(crate) fn slot_ref(slot: &str) -> RecordId { | 30 | +/// The `slot_ref` row is keyed by the slot's name. |
| 31 | - RecordId::new(SLOT_REF_TABLE, slot) | 31 | +pub(crate) fn slot_ref(slot: &str) -> String { |
| 32 | + slot.to_string() | ||
| 32 | } | 33 | } |
| 33 | 34 | ||
| 34 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 35 | +/// Typed menu row id — the `{date}_{slot}` pair joined with `_`. Not a minted |
| 35 | -pub struct MenuId(RecordId); | 36 | +/// id: the pair *is* the identity, the same trick the enrollment tables use. |
| 37 | +/// `date` is fixed-width `YYYY-MM-DD`, and slot names never carry `_`-breaking | ||
| 38 | +/// ambiguity, so two requests publishing the same meal race on one row and the | ||
| 39 | +/// loser is told "already exists" by the store. | ||
| 40 | +#[derive(Debug, Clone, PartialEq, Eq, Type)] | ||
| 41 | +#[sqlx(transparent)] | ||
| 42 | +pub struct MenuId(String); | ||
| 36 | 43 | ||
| 37 | impl MenuId { | 44 | impl MenuId { |
| 38 | /// The one id a menu for this day and slot can have. Deterministic on | 45 | /// The one id a menu for this day and slot can have. Deterministic on |
| 39 | - /// purpose (the `EnrollmentId` trick): two requests publishing the same | 46 | + /// purpose (the enrollment trick): two requests publishing the same meal |
| 40 | - /// meal race on a single record instead of writing two rows, so the loser | 47 | + /// race on a single row instead of writing two, so the loser is told |
| 41 | - /// is told "already exists" by the store and answered the same 409 the | 48 | + /// "already exists" by the store and answered the same 409 the pre-check |
| 42 | - /// pre-check gives. `date` is fixed-width `YYYY-MM-DD`, so the `_` joiner | 49 | + /// gives. |
| 43 | - /// cannot be read two ways however the school spells its slots. | ||
| 44 | pub fn for_slot(date: &MenuDate, slot: &MenuSlot) -> Self { | 50 | pub fn for_slot(date: &MenuDate, slot: &MenuSlot) -> Self { |
| 45 | - Self(RecordId::new( | 51 | + Self(format!("{}_{}", date.as_str(), slot.as_str())) |
| 46 | - MENU_TABLE, | ||
| 47 | - format!("{}_{}", date.as_str(), slot.as_str()), | ||
| 48 | - )) | ||
| 49 | } | 52 | } |
| 50 | 53 | ||
| 51 | pub fn from_key(key: &str) -> Self { | 54 | pub fn from_key(key: &str) -> Self { |
| 52 | - Self(RecordId::new(MENU_TABLE, key)) | 55 | + Self(key.to_string()) |
| 53 | - } | ||
| 54 | - | ||
| 55 | - pub fn record(&self) -> RecordId { | ||
| 56 | - self.0.clone() | ||
| 57 | } | 56 | } |
| 58 | 57 | ||
| 59 | pub fn key(&self) -> &str { | 58 | pub fn key(&self) -> &str { |
| 60 | - match &self.0.key { | 59 | + &self.0 |
| 61 | - RecordIdKey::String(key) => key, | ||
| 62 | - _ => "", | ||
| 63 | - } | ||
| 64 | } | 60 | } |
| 65 | } | 61 | } |
| 66 | 62 | ||
| 67 | /// A calendar day as `YYYY-MM-DD`. Zero-padded and fixed-width on purpose: | 63 | /// A calendar day as `YYYY-MM-DD`. Zero-padded and fixed-width on purpose: |
| 68 | /// that makes the text sort chronologically, so the `?from=&to=` range filter | 64 | /// that makes the text sort chronologically, so the `?from=&to=` range filter |
| 69 | /// and the newest-first ordering are plain string comparisons. | 65 | /// and the newest-first ordering are plain string comparisons. |
| 70 | -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, SurrealValue)] | 66 | +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Type)] |
| 67 | +#[sqlx(transparent)] | ||
| 71 | pub struct MenuDate(String); | 68 | pub struct MenuDate(String); |
| 72 | 69 | ||
| 73 | impl MenuDate { | 70 | impl MenuDate { |
| @@ -87,7 +84,7 @@ impl MenuDate { | |||
| 87 | // rather than by two independent checks that can drift apart. They did: | 84 | // rather than by two independent checks that can drift apart. They did: |
| 88 | // a hand-rolled `"+1".parse::<u32>()` accepted a signed component (std | 85 | // a hand-rolled `"+1".parse::<u32>()` accepted a signed component (std |
| 89 | // does), `from_ymd_opt` was then handed the normalized number and said | 86 | // does), `from_ymd_opt` was then handed the normalized number and said |
| 90 | - // yes, and `2026-+1-01` became a *second* record id for the 1st of | 87 | + // yes, and `2026-+1-01` became a *second* row id for the 1st of |
| 91 | // January — its own capacity and seat counter, invisible to every | 88 | // January — its own capacity and seat counter, invisible to every |
| 92 | // `date >= $from` range read ('+' sorts below '0'), and unbookable | 89 | // `date >= $from` range read ('+' sorts below '0'), and unbookable |
| 93 | // besides, since chrono refuses to parse it back. | 90 | // besides, since chrono refuses to parse it back. |
| @@ -116,8 +113,7 @@ impl MenuDate { | |||
| 116 | /// This is the whole day's deadline, not the meal's: a menu for *today* is | 113 | /// This is the whole day's deadline, not the meal's: a menu for *today* is |
| 117 | /// still publishable and still bookable at any hour, whatever the slot's | 114 | /// still publishable and still bookable at any hour, whatever the slot's |
| 118 | /// serving time says — that is [`MealCutoff`](crate::domain::meal_booking::MealCutoff)'s | 115 | /// serving time says — that is [`MealCutoff`](crate::domain::meal_booking::MealCutoff)'s |
| 119 | - /// separate business. `None` for a day that cannot be parsed (a row written | 116 | + /// separate business. `None` for a day that cannot be parsed. |
| 120 | - /// before `try_new` rejected impossible days). | ||
| 121 | pub fn day_end(&self) -> Option<Timestamp> { | 117 | pub fn day_end(&self) -> Option<Timestamp> { |
| 122 | let day = chrono::NaiveDate::parse_from_str(&self.0, "%Y-%m-%d").ok()?; | 118 | let day = chrono::NaiveDate::parse_from_str(&self.0, "%Y-%m-%d").ok()?; |
| 123 | Some(Timestamp::from_millis( | 119 | Some(Timestamp::from_millis( |
| @@ -132,7 +128,8 @@ impl MenuDate { | |||
| 132 | /// The meal slot a menu was published for, snapshotted as text. Validated | 128 | /// The meal slot a menu was published for, snapshotted as text. Validated |
| 133 | /// against the school's *current* list at write time — that list is the only | 129 | /// against the school's *current* list at write time — that list is the only |
| 134 | /// place slot names are defined, and this is the sole funnel into the column. | 130 | /// place slot names are defined, and this is the sole funnel into the column. |
| 135 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 131 | +#[derive(Debug, Clone, PartialEq, Eq, Type)] |
| 132 | +#[sqlx(transparent)] | ||
| 136 | pub struct MenuSlot(String); | 133 | pub struct MenuSlot(String); |
| 137 | 134 | ||
| 138 | impl MenuSlot { | 135 | impl MenuSlot { |
| @@ -144,7 +141,7 @@ impl MenuSlot { | |||
| 144 | reason: "not one of the school's meal slots (see GET /settings)", | 141 | reason: "not one of the school's meal slots (see GET /settings)", |
| 145 | }); | 142 | }); |
| 146 | } | 143 | } |
| 147 | - // The slot goes verbatim into the menu's record id ([`MenuId::for_slot`]), | 144 | + // The slot goes verbatim into the menu's id ([`MenuId::for_slot`]), |
| 148 | // and that id is a URL path segment: a slot named `a/b` publishes a menu | 145 | // and that id is a URL path segment: a slot named `a/b` publishes a menu |
| 149 | // at `/meals/menus/2026-09-14_a/b`, which no route can ever address | 146 | // at `/meals/menus/2026-09-14_a/b`, which no route can ever address |
| 150 | // again — the menu could not be read, edited or deleted. | 147 | // again — the menu could not be read, edited or deleted. |
| @@ -182,15 +179,14 @@ pub fn validate_capacity(value: Option<i64>) -> Result<(), ValidationError> { | |||
| 182 | } | 179 | } |
| 183 | } | 180 | } |
| 184 | 181 | ||
| 185 | -#[derive(Debug, Clone, SurrealValue)] | 182 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 186 | pub struct Menu { | 183 | pub struct Menu { |
| 187 | pub(crate) id: MenuId, | 184 | pub(crate) id: MenuId, |
| 188 | pub(crate) date: MenuDate, | 185 | pub(crate) date: MenuDate, |
| 189 | pub(crate) slot: MenuSlot, | 186 | pub(crate) slot: MenuSlot, |
| 190 | pub(crate) capacity: Option<i64>, | 187 | pub(crate) capacity: Option<i64>, |
| 191 | - /// The menu's revision (see [`MENU_VERSION_FIELD`](crate::constant::MENU_VERSION_FIELD)). | 188 | + /// The menu's revision. `NULL` (never written by the current code) reads |
| 192 | - /// Absent on rows written before the column existed, which reads as | 189 | + /// as revision zero — the same thing `(version ?? 0)` says in the claim's |
| 193 | - /// revision zero — the same thing `(version ?? 0)` says in the claim's | ||
| 194 | /// `WHERE`. The seat counter is deliberately *not* here: it is the | 190 | /// `WHERE`. The seat counter is deliberately *not* here: it is the |
| 195 | /// database's to own, and a whole-row save must never carry a stale copy | 191 | /// database's to own, and a whole-row save must never carry a stale copy |
| 196 | /// of it. | 192 | /// of it. |
| @@ -217,8 +213,7 @@ impl Menu { | |||
| 217 | } | 213 | } |
| 218 | 214 | ||
| 219 | /// The revision a booking must still find on the row when it claims its | 215 | /// The revision a booking must still find on the row when it claims its |
| 220 | - /// seat. Absent (a pre-column row) is revision zero, exactly as the `WHERE` | 216 | + /// seat. Absent is revision zero, exactly as the `WHERE` reads it. |
| 221 | - /// reads it. | ||
| 222 | pub fn get_version(&self) -> i64 { | 217 | pub fn get_version(&self) -> i64 { |
| 223 | self.version.unwrap_or(0) | 218 | self.version.unwrap_or(0) |
| 224 | } | 219 | } |
| @@ -235,7 +230,6 @@ impl Menu { | |||
| 235 | #[cfg(test)] | 230 | #[cfg(test)] |
| 236 | mod tests { | 231 | mod tests { |
| 237 | use super::*; | 232 | use super::*; |
| 238 | - use surrealdb::types::Value; | ||
| 239 | 233 | ||
| 240 | #[test] | 234 | #[test] |
| 241 | fn date_accepts_only_padded_calendar_days() { | 235 | fn date_accepts_only_padded_calendar_days() { |
| @@ -268,7 +262,7 @@ mod tests { | |||
| 268 | 262 | ||
| 269 | /// A signed component is not a calendar day, however willingly | 263 | /// A signed component is not a calendar day, however willingly |
| 270 | /// `"+1".parse::<u32>()` reads one out of it. Accepting one minted a | 264 | /// `"+1".parse::<u32>()` reads one out of it. Accepting one minted a |
| 271 | - /// *second* record id for the same day — its own capacity and seat counter | 265 | + /// *second* row id for the same day — its own capacity and seat counter |
| 272 | /// — that sorted below every `?from=` bound (`+` is 0x2B, `0` is 0x30) and | 266 | /// — that sorted below every `?from=` bound (`+` is 0x2B, `0` is 0x30) and |
| 273 | /// that the serving-instant parser could not read at all. | 267 | /// that the serving-instant parser could not read at all. |
| 274 | #[test] | 268 | #[test] |
| @@ -314,9 +308,6 @@ mod tests { | |||
| 314 | fn a_day_ends_at_the_next_midnight_utc() { | 308 | fn a_day_ends_at_the_next_midnight_utc() { |
| 315 | let day = MenuDate::try_new("1970-01-01").unwrap(); | 309 | let day = MenuDate::try_new("1970-01-01").unwrap(); |
| 316 | assert_eq!(day.day_end().unwrap().as_millis(), 86_400_000); | 310 | assert_eq!(day.day_end().unwrap().as_millis(), 86_400_000); |
| 317 | - // A row written before `try_new` refused impossible days has no end. | ||
| 318 | - let impossible = MenuDate::from_value(Value::String("2026-02-29".into())).unwrap(); | ||
| 319 | - assert!(impossible.day_end().is_none()); | ||
| 320 | } | 311 | } |
| 321 | 312 | ||
| 322 | #[test] | 313 | #[test] |
| @@ -327,29 +318,19 @@ mod tests { | |||
| 327 | assert!(MenuSlot::try_new("lunch", &[]).is_err()); | 318 | assert!(MenuSlot::try_new("lunch", &[]).is_err()); |
| 328 | } | 319 | } |
| 329 | 320 | ||
| 330 | - /// The slot becomes the menu's record id, and the id becomes a URL path | 321 | + /// The slot becomes the menu's id, and the id becomes a URL path |
| 331 | /// segment: a name carrying a separator publishes a menu at an address no | 322 | /// segment: a name carrying a separator publishes a menu at an address no |
| 332 | /// route can match again. `MealSlotDef::try_new` refuses the name too, so | 323 | /// route can match again. `MealSlotDef::try_new` refuses the name too, so |
| 333 | - /// no school can define such a slot any more — this gate is what a settings | 324 | + /// no school can define such a slot any more — this gate is what a |
| 334 | - /// row written *before* that rule still runs into. Ordinary names — spaces | 325 | + /// settings row written *before* that rule still runs into. Ordinary names — |
| 335 | - /// and Turkish letters included — are untouched; they percent-encode into | 326 | + /// spaces and Turkish letters included — are untouched; they percent-encode |
| 336 | - /// one segment as they always have. | 327 | + /// into one segment as they always have. |
| 337 | #[test] | 328 | #[test] |
| 338 | fn a_slot_name_that_would_break_the_menu_url_is_refused() { | 329 | fn a_slot_name_that_would_break_the_menu_url_is_refused() { |
| 339 | // The only shape that can still carry such a name: a stored slot, | 330 | // The only shape that can still carry such a name: a stored slot, |
| 340 | - // decoded rather than constructed. | 331 | + // which `try_kept` admits exactly because it is already on the row. |
| 341 | - use surrealdb::types::Value; | ||
| 342 | - let stale = |name: &str| { | ||
| 343 | - let Value::Object(mut object) = | ||
| 344 | - MealSlotDef::try_new("lunch", None).unwrap().into_value() | ||
| 345 | - else { | ||
| 346 | - panic!("a slot must encode as an object"); | ||
| 347 | - }; | ||
| 348 | - object.insert("name".to_string(), Value::String(name.into())); | ||
| 349 | - vec![MealSlotDef::from_value(Value::Object(object)).unwrap()] | ||
| 350 | - }; | ||
| 351 | let named = |name: &str| { | 332 | let named = |name: &str| { |
| 352 | - MenuSlot::try_new(name, &stale(name)) | 333 | + MenuSlot::try_new(name, &[MealSlotDef::try_kept(name, None).unwrap()]) |
| 353 | .map(|slot| MenuId::for_slot(&MenuDate::try_new("2026-09-14").unwrap(), &slot)) | 334 | .map(|slot| MenuId::for_slot(&MenuDate::try_new("2026-09-14").unwrap(), &slot)) |
| 354 | }; | 335 | }; |
| 355 | for broken in ["a/b", "a\\b", "a?b", "a#b", "a%b"] { | 336 | for broken in ["a/b", "a\\b", "a?b", "a#b", "a%b"] { |
src/domain/menu_dish.rsmodified+32 -38
| @@ -8,58 +8,48 @@ | |||
| 8 | //! The queries live in [`crate::db::menu_dish`]; the dish-cap gate and the | 8 | //! The queries live in [`crate::db::menu_dish`]; the dish-cap gate and the |
| 9 | //! write lock in [`crate::service::menu`]. | 9 | //! write lock in [`crate::service::menu`]. |
| 10 | 10 | ||
| 11 | -use std::sync::LazyLock; | 11 | +use sqlx::Type; |
| 12 | - | 12 | +use uuid::Uuid; |
| 13 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 14 | -use ulid::Generator; | ||
| 15 | 13 | ||
| 16 | use crate::constant::{ | 14 | use crate::constant::{ |
| 17 | MAX_DISH_DESCRIPTION_LEN, MAX_DISH_NAME_LEN, MAX_DISH_PRICE_MINOR, MAX_DISH_TAGS, | 15 | MAX_DISH_DESCRIPTION_LEN, MAX_DISH_NAME_LEN, MAX_DISH_PRICE_MINOR, MAX_DISH_TAGS, |
| 18 | - MENU_DISH_TABLE, | ||
| 19 | }; | 16 | }; |
| 20 | use crate::domain::menu::MenuId; | 17 | use crate::domain::menu::MenuId; |
| 18 | +use crate::domain::monotonic_id::next_uuid; | ||
| 21 | use crate::domain::timestamp::Timestamp; | 19 | use crate::domain::timestamp::Timestamp; |
| 22 | use crate::error::ValidationError; | 20 | use crate::error::ValidationError; |
| 23 | use crate::validate::{validate_optional, validate_required}; | 21 | use crate::validate::{validate_optional, validate_required}; |
| 24 | 22 | ||
| 25 | -/// Mints dish ids in write order — see [`MenuId::generate`]; the listings below | 23 | +/// Typed menu-dish row id. A UUIDv7 minted by the process-wide monotonic |
| 26 | -/// order by `id` within a menu, which random low bits would scramble. | 24 | +/// generator, so `id` order is mint order. |
| 27 | -static IDS: LazyLock<std::sync::Mutex<Generator>> = | 25 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] |
| 28 | - LazyLock::new(|| std::sync::Mutex::new(Generator::new())); | 26 | +#[sqlx(transparent)] |
| 29 | - | 27 | +pub struct MenuDishId(Uuid); |
| 30 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 31 | -pub struct MenuDishId(RecordId); | ||
| 32 | 28 | ||
| 33 | impl MenuDishId { | 29 | impl MenuDishId { |
| 30 | + /// Minted from the process-wide monotonic generator, not a random v4 — | ||
| 31 | + /// the listings order by `id` within a menu, which random low bits would | ||
| 32 | + /// scramble. | ||
| 34 | pub fn generate() -> Self { | 33 | pub fn generate() -> Self { |
| 35 | - let mut ids = IDS.lock().expect("menu dish id generator poisoned"); | 34 | + Self(next_uuid()) |
| 36 | - // The only error is exhausting the random bits within one millisecond | ||
| 37 | - // (2^80 ids deep); it clears itself as the clock ticks, so retry. | ||
| 38 | - let ulid = loop { | ||
| 39 | - if let Ok(ulid) = ids.generate() { | ||
| 40 | - break ulid; | ||
| 41 | - } | ||
| 42 | - }; | ||
| 43 | - Self(RecordId::new(MENU_DISH_TABLE, ulid.to_string())) | ||
| 44 | } | 35 | } |
| 45 | 36 | ||
| 37 | + /// Parse a wire key. A key that parses as no UUID — a malformed path | ||
| 38 | + /// segment — reads as the nil id, which matches no row: exactly the 404 a | ||
| 39 | + /// dangling record key produced under the old store, without turning a | ||
| 40 | + /// typo into a panic. | ||
| 46 | pub fn from_key(key: &str) -> Self { | 41 | pub fn from_key(key: &str) -> Self { |
| 47 | - Self(RecordId::new(MENU_DISH_TABLE, key)) | 42 | + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) |
| 48 | } | 43 | } |
| 49 | 44 | ||
| 50 | - pub fn record(&self) -> RecordId { | 45 | + /// The hyphenated wire form. |
| 51 | - self.0.clone() | 46 | + pub fn key(&self) -> String { |
| 52 | - } | 47 | + self.0.to_string() |
| 53 | - | ||
| 54 | - pub fn key(&self) -> &str { | ||
| 55 | - match &self.0.key { | ||
| 56 | - RecordIdKey::String(key) => key, | ||
| 57 | - _ => "", | ||
| 58 | - } | ||
| 59 | } | 48 | } |
| 60 | } | 49 | } |
| 61 | 50 | ||
| 62 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 51 | +#[derive(Debug, Clone, PartialEq, Eq, Type)] |
| 52 | +#[sqlx(transparent)] | ||
| 63 | pub struct DishName(String); | 53 | pub struct DishName(String); |
| 64 | 54 | ||
| 65 | impl DishName { | 55 | impl DishName { |
| @@ -73,12 +63,13 @@ impl DishName { | |||
| 73 | } | 63 | } |
| 74 | } | 64 | } |
| 75 | 65 | ||
| 76 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 66 | +#[derive(Debug, Clone, PartialEq, Eq, Type)] |
| 67 | +#[sqlx(transparent)] | ||
| 77 | pub struct DishDescription(String); | 68 | pub struct DishDescription(String); |
| 78 | 69 | ||
| 79 | impl DishDescription { | 70 | impl DishDescription { |
| 80 | /// Blank (or whitespace-only) means "no description" — `None`, not an | 71 | /// Blank (or whitespace-only) means "no description" — `None`, not an |
| 81 | - /// empty string, so the column is absent rather than falsely present. | 72 | + /// empty string, so the column is NULL rather than falsely present. |
| 82 | pub fn try_new(value: &str) -> Result<Option<Self>, ValidationError> { | 73 | pub fn try_new(value: &str) -> Result<Option<Self>, ValidationError> { |
| 83 | validate_optional("description", value, MAX_DISH_DESCRIPTION_LEN)?; | 74 | validate_optional("description", value, MAX_DISH_DESCRIPTION_LEN)?; |
| 84 | let value = value.trim(); | 75 | let value = value.trim(); |
| @@ -92,7 +83,8 @@ impl DishDescription { | |||
| 92 | 83 | ||
| 93 | /// What one serving costs, in **minor units** (kuruş). Never negative — a | 84 | /// What one serving costs, in **minor units** (kuruş). Never negative — a |
| 94 | /// giveaway dish is `0`, and money that flows the other way is a ledger line. | 85 | /// giveaway dish is `0`, and money that flows the other way is a ledger line. |
| 95 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | 86 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] |
| 87 | +#[sqlx(transparent)] | ||
| 96 | pub struct DishPrice(i64); | 88 | pub struct DishPrice(i64); |
| 97 | 89 | ||
| 98 | impl DishPrice { | 90 | impl DishPrice { |
| @@ -113,8 +105,10 @@ impl DishPrice { | |||
| 113 | 105 | ||
| 114 | /// The dietary tags a dish carries, drawn from the school's `dietary_tags` | 106 | /// The dietary tags a dish carries, drawn from the school's `dietary_tags` |
| 115 | /// list. Deduplicated, order preserved — the list is what a student's profile | 107 | /// list. Deduplicated, order preserved — the list is what a student's profile |
| 116 | -/// is matched against, so a repeat carries no extra meaning. | 108 | +/// is matched against, so a repeat carries no extra meaning. Stored as a |
| 117 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 109 | +/// `TEXT[]` column. |
| 110 | +#[derive(Debug, Clone, PartialEq, Eq, Type)] | ||
| 111 | +#[sqlx(transparent, no_pg_array)] | ||
| 118 | pub struct DishTags(Vec<String>); | 112 | pub struct DishTags(Vec<String>); |
| 119 | 113 | ||
| 120 | impl DishTags { | 114 | impl DishTags { |
| @@ -146,7 +140,7 @@ impl DishTags { | |||
| 146 | } | 140 | } |
| 147 | } | 141 | } |
| 148 | 142 | ||
| 149 | -#[derive(Debug, Clone, SurrealValue)] | 143 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 150 | pub struct MenuDish { | 144 | pub struct MenuDish { |
| 151 | pub(crate) id: MenuDishId, | 145 | pub(crate) id: MenuDishId, |
| 152 | pub(crate) menu: MenuId, | 146 | pub(crate) menu: MenuId, |
src/domain/message.rsmodified+51 -36
| @@ -1,18 +1,11 @@ | |||
| 1 | -//! One-to-one mail-style messages. A single row serves both ends: the | 1 | +use sqlx::Type; |
| 2 | -//! recipient's `read` flag plus one folder field per side, so each party | 2 | +use uuid::Uuid; |
| 3 | -//! files (archive/trash) and deletes their copy without touching the | ||
| 4 | -//! other's. Filing also stamps that side's origin folder, so a copy can be | ||
| 5 | -//! put back where it came from. A side that permanently deletes goes to the | ||
| 6 | -//! hidden `deleted` folder; once both sides are `deleted` the row itself is | ||
| 7 | -//! removed. | ||
| 8 | - | ||
| 9 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 10 | 3 | ||
| 11 | use crate::constant::{ | 4 | use crate::constant::{ |
| 12 | - MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN, MESSAGE_TABLE, | 5 | + MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN, |
| 13 | RECIPIENT_FOLDERS, SENDER_FOLDERS, | 6 | RECIPIENT_FOLDERS, SENDER_FOLDERS, |
| 14 | }; | 7 | }; |
| 15 | -use crate::domain::monotonic_id::next_ulid; | 8 | +use crate::domain::monotonic_id::next_uuid; |
| 16 | use crate::domain::timestamp::Timestamp; | 9 | use crate::domain::timestamp::Timestamp; |
| 17 | use crate::domain::user::UserId; | 10 | use crate::domain::user::UserId; |
| 18 | use crate::error::ValidationError; | 11 | use crate::error::ValidationError; |
| @@ -23,11 +16,11 @@ use crate::validate::{validate_optional, validate_required}; | |||
| 23 | /// query filter and the restore stamp all pass through this enum, so a typo | 16 | /// query filter and the restore stamp all pass through this enum, so a typo |
| 24 | /// is a compile error rather than a silently empty folder. | 17 | /// is a compile error rather than a silently empty folder. |
| 25 | /// | 18 | /// |
| 26 | -/// `#[surreal(untagged, rename_all = "lowercase")]` stores each variant as a | 19 | +/// Each variant stores as a bare lowercase TEXT value (`"inbox"`, |
| 27 | -/// bare lowercase string (`"inbox"`, `"archive"`, …) in the `TYPE string` | 20 | +/// `"archive"`, …) and round-trips straight back — same trick as |
| 28 | -/// columns, and round-trips straight back — same trick as `domain::role`. | 21 | +/// `domain::role`. |
| 29 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | 22 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] |
| 30 | -#[surreal(untagged, rename_all = "lowercase")] | 23 | +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] |
| 31 | pub enum Folder { | 24 | pub enum Folder { |
| 32 | Inbox, | 25 | Inbox, |
| 33 | Sent, | 26 | Sent, |
| @@ -96,35 +89,37 @@ impl Folder { | |||
| 96 | } | 89 | } |
| 97 | } | 90 | } |
| 98 | 91 | ||
| 99 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 92 | +/// Typed message row id. A UUIDv7 minted by the process-wide monotonic |
| 100 | -pub struct MessageId(RecordId); | 93 | +/// generator, so `id` order is mint order. |
| 94 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] | ||
| 95 | +#[sqlx(transparent)] | ||
| 96 | +pub struct MessageId(Uuid); | ||
| 101 | 97 | ||
| 102 | impl MessageId { | 98 | impl MessageId { |
| 103 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 99 | + /// Minted from the process-wide monotonic generator, not a random v4: |
| 104 | /// the folder listings sort `id DESC` (newest first, | 100 | /// the folder listings sort `id DESC` (newest first, |
| 105 | /// [`crate::db::message::list_folder`]), | 101 | /// [`crate::db::message::list_folder`]), |
| 106 | /// and a random low half scrambles rows minted in the same millisecond. | 102 | /// and a random low half scrambles rows minted in the same millisecond. |
| 107 | pub fn generate() -> Self { | 103 | pub fn generate() -> Self { |
| 108 | - Self(RecordId::new(MESSAGE_TABLE, next_ulid().to_string())) | 104 | + Self(next_uuid()) |
| 109 | } | 105 | } |
| 110 | 106 | ||
| 107 | + /// Parse a wire key. A key that parses as no UUID — a malformed path | ||
| 108 | + /// segment — reads as the nil id, which matches no row: exactly the 404 a | ||
| 109 | + /// dangling record key produced under the old store, without turning a | ||
| 110 | + /// typo into a panic. | ||
| 111 | pub fn from_key(key: &str) -> Self { | 111 | pub fn from_key(key: &str) -> Self { |
| 112 | - Self(RecordId::new(MESSAGE_TABLE, key)) | 112 | + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) |
| 113 | - } | ||
| 114 | - | ||
| 115 | - pub fn record(&self) -> RecordId { | ||
| 116 | - self.0.clone() | ||
| 117 | } | 113 | } |
| 118 | 114 | ||
| 119 | - pub fn key(&self) -> &str { | 115 | + /// The hyphenated wire form. |
| 120 | - match &self.0.key { | 116 | + pub fn key(&self) -> String { |
| 121 | - RecordIdKey::String(key) => key, | 117 | + self.0.to_string() |
| 122 | - _ => "", | ||
| 123 | - } | ||
| 124 | } | 118 | } |
| 125 | } | 119 | } |
| 126 | 120 | ||
| 127 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 121 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 122 | +#[sqlx(transparent)] | ||
| 128 | pub struct MessageSubject(String); | 123 | pub struct MessageSubject(String); |
| 129 | 124 | ||
| 130 | impl MessageSubject { | 125 | impl MessageSubject { |
| @@ -138,7 +133,8 @@ impl MessageSubject { | |||
| 138 | } | 133 | } |
| 139 | } | 134 | } |
| 140 | 135 | ||
| 141 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 136 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 137 | +#[sqlx(transparent)] | ||
| 142 | pub struct MessageBody(String); | 138 | pub struct MessageBody(String); |
| 143 | 139 | ||
| 144 | impl MessageBody { | 140 | impl MessageBody { |
| @@ -154,7 +150,8 @@ impl MessageBody { | |||
| 154 | 150 | ||
| 155 | /// A sender-chosen tag ("Etüt", "Sınav", …) the UI renders as a badge. | 151 | /// A sender-chosen tag ("Etüt", "Sınav", …) the UI renders as a badge. |
| 156 | /// Required-and-bounded here; "no label" is `Option<MessageLabel>` on the row. | 152 | /// Required-and-bounded here; "no label" is `Option<MessageLabel>` on the row. |
| 157 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 153 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 154 | +#[sqlx(transparent)] | ||
| 158 | pub struct MessageLabel(String); | 155 | pub struct MessageLabel(String); |
| 159 | 156 | ||
| 160 | impl MessageLabel { | 157 | impl MessageLabel { |
| @@ -168,7 +165,7 @@ impl MessageLabel { | |||
| 168 | } | 165 | } |
| 169 | } | 166 | } |
| 170 | 167 | ||
| 171 | -#[derive(Debug, Clone, SurrealValue)] | 168 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 172 | pub struct Message { | 169 | pub struct Message { |
| 173 | pub(crate) id: MessageId, | 170 | pub(crate) id: MessageId, |
| 174 | pub(crate) sender: UserId, | 171 | pub(crate) sender: UserId, |
| @@ -257,8 +254,8 @@ mod tests { | |||
| 257 | 254 | ||
| 258 | #[tokio::test] | 255 | #[tokio::test] |
| 259 | async fn folder_sides_resolve_by_membership() { | 256 | async fn folder_sides_resolve_by_membership() { |
| 260 | - let sender = UserId::from_key("a"); | 257 | + let sender = UserId::from_key("018f1a00-0000-7000-8000-000000000001"); |
| 261 | - let recipient = UserId::from_key("b"); | 258 | + let recipient = UserId::from_key("018f1a00-0000-7000-8000-000000000002"); |
| 262 | let message = Message { | 259 | let message = Message { |
| 263 | id: MessageId::generate(), | 260 | id: MessageId::generate(), |
| 264 | sender: sender.clone(), | 261 | sender: sender.clone(), |
| @@ -293,4 +290,22 @@ mod tests { | |||
| 293 | assert!(Folder::allowed_for(false).contains(&Folder::Archive)); | 290 | assert!(Folder::allowed_for(false).contains(&Folder::Archive)); |
| 294 | assert!(!Folder::allowed_for(true).contains(&Folder::Inbox)); | 291 | assert!(!Folder::allowed_for(true).contains(&Folder::Inbox)); |
| 295 | } | 292 | } |
| 293 | + | ||
| 294 | + #[test] | ||
| 295 | + fn sqlx_encodes_the_storage_form() { | ||
| 296 | + // The folder columns are TEXT with a CHECK on these exact words; the | ||
| 297 | + // sqlx encoding must never drift from `as_str`. | ||
| 298 | + let mut buf = sqlx::postgres::PgArgumentBuffer::default(); | ||
| 299 | + for folder in [ | ||
| 300 | + Folder::Inbox, | ||
| 301 | + Folder::Sent, | ||
| 302 | + Folder::Archive, | ||
| 303 | + Folder::Trash, | ||
| 304 | + Folder::Deleted, | ||
| 305 | + ] { | ||
| 306 | + buf.clear(); | ||
| 307 | + sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&folder, &mut buf); | ||
| 308 | + assert_eq!(std::str::from_utf8(&buf).unwrap(), folder.as_str()); | ||
| 309 | + } | ||
| 310 | + } | ||
| 296 | } | 311 | } |
src/domain/mod.rsmodified+53 -2
| @@ -1,6 +1,8 @@ | |||
| 1 | //! Domain layer: every value is a validated newtype, and each entity owns its | 1 | //! Domain layer: every value is a validated newtype, and each entity owns its |
| 2 | -//! own persistence. Types derive `surrealdb::types::SurrealValue` so the exact | 2 | +//! own persistence. Row structs derive `sqlx::FromRow` so the exact same typed |
| 3 | -//! same typed value flows from HTTP input all the way into the database. | 3 | +//! value flows from HTTP input all the way into PostgreSQL; transparent |
| 4 | +//! newtypes derive `sqlx::Type` so a column reads straight into the validated | ||
| 5 | +//! wrapper. | ||
| 4 | 6 | ||
| 5 | pub mod answer_image; | 7 | pub mod answer_image; |
| 6 | pub mod appointment; | 8 | pub mod appointment; |
| @@ -66,3 +68,52 @@ pub mod text_fold; | |||
| 66 | pub mod timestamp; | 68 | pub mod timestamp; |
| 67 | pub mod user; | 69 | pub mod user; |
| 68 | pub mod work_entry; | 70 | pub mod work_entry; |
| 71 | + | ||
| 72 | +/// Fallback for lowercase-string enums whose `#[sqlx(type_name = "TEXT", | ||
| 73 | +/// rename_all = "lowercase")]` derive the `sqlx::Type` macro rejects (an | ||
| 74 | +/// exotic shape, not a plain C-like enum). Emits the same thing the derive | ||
| 75 | +/// would: `Type` reporting `TEXT`, `Encode` writing the lowercase name, | ||
| 76 | +/// `Decode` reading a TEXT value back and refusing an unknown one as a decode | ||
| 77 | +/// error — never a panic. Unused today: every current enum derives fine; kept | ||
| 78 | +/// so the fallback shape stays one `macro_rules!` away, identically across | ||
| 79 | +/// the domain. | ||
| 80 | +#[allow(unused_macros)] | ||
| 81 | +macro_rules! text_enum { | ||
| 82 | + ($name:ident { $($variant:ident),+ $(,)? }) => { | ||
| 83 | + impl sqlx::Type<sqlx::Postgres> for $name { | ||
| 84 | + fn type_info() -> sqlx::postgres::PgTypeInfo { | ||
| 85 | + sqlx::postgres::PgTypeInfo::with_name("TEXT") | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | + | ||
| 89 | + impl<'r> sqlx::Decode<'r, sqlx::Postgres> for $name { | ||
| 90 | + fn decode( | ||
| 91 | + value: sqlx::postgres::PgValueRef<'r>, | ||
| 92 | + ) -> Result<Self, sqlx::error::BoxDynError> { | ||
| 93 | + let text: &str = sqlx::Decode::<sqlx::Postgres>::decode(value)?; | ||
| 94 | + match text { | ||
| 95 | + $(stringify!($variant) => Ok(Self::$variant),)+ | ||
| 96 | + other => Err(format!( | ||
| 97 | + concat!("unknown ", stringify!($name), " value: `{}`"), | ||
| 98 | + other | ||
| 99 | + ) | ||
| 100 | + .into()), | ||
| 101 | + } | ||
| 102 | + } | ||
| 103 | + } | ||
| 104 | + | ||
| 105 | + impl<'q> sqlx::Encode<'q, sqlx::Postgres> for $name { | ||
| 106 | + fn encode_by_ref( | ||
| 107 | + &self, | ||
| 108 | + buf: &mut sqlx::postgres::PgArgumentBuffer, | ||
| 109 | + ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> { | ||
| 110 | + sqlx::Encode::<sqlx::Postgres>::encode( | ||
| 111 | + match self { | ||
| 112 | + $(Self::$variant => stringify!($variant),)+ | ||
| 113 | + }, | ||
| 114 | + buf, | ||
| 115 | + ) | ||
| 116 | + } | ||
| 117 | + } | ||
| 118 | + }; | ||
| 119 | +} | ||
src/domain/monotonic_id.rsmodified+30 -25
| @@ -1,34 +1,38 @@ | |||
| 1 | //! Ids that sort in write order, for tables whose listings lean on `id` to | 1 | //! Ids that sort in write order, for tables whose listings lean on `id` to |
| 2 | //! break ties (or to mean "newest first" outright). | 2 | //! break ties (or to mean "newest first" outright). |
| 3 | //! | 3 | //! |
| 4 | -//! `Ulid::generate()` fills the low 80 bits at random, so two ids minted in the | 4 | +//! A bare `Uuid::new_v7()` redraws its random bits per id, so two ids minted |
| 5 | -//! *same millisecond* sort arbitrarily against each other — millisecond- | 5 | +//! in the *same millisecond* sort arbitrarily against each other — |
| 6 | -//! accurate ordering only. That is not enough when a burst of writes lands | 6 | +//! millisecond-accurate ordering only. That is not enough when a burst of |
| 7 | -//! inside one tick (a recurring appointment publish expanding a series, a | 7 | +//! writes lands inside one tick (a recurring appointment publish expanding a |
| 8 | -//! teacher saving templates back to back, a test creating rows in a loop): | 8 | +//! series, a teacher saving templates back to back, a test creating rows in a |
| 9 | -//! `ORDER BY id DESC` then scrambles them. [`next_ulid`] mints from one | 9 | +//! loop): `ORDER BY id DESC` then scrambles them. [`next_uuid`] mints through |
| 10 | -//! process-wide [`Generator`], which keeps ids strictly increasing within a | 10 | +//! one process-wide [`ContextV7`], which keeps ids strictly increasing within |
| 11 | -//! millisecond by incrementing the random part instead of redrawing it. | 11 | +//! a millisecond by incrementing its counter instead of redrawing it. |
| 12 | 12 | ||
| 13 | use std::sync::{LazyLock, Mutex}; | 13 | use std::sync::{LazyLock, Mutex}; |
| 14 | 14 | ||
| 15 | -use ulid::{Generator, Ulid}; | 15 | +use uuid::{ContextV7, Uuid}; |
| 16 | 16 | ||
| 17 | -static IDS: LazyLock<Mutex<Generator>> = LazyLock::new(|| Mutex::new(Generator::new())); | 17 | +use crate::domain::timestamp::Timestamp; |
| 18 | 18 | ||
| 19 | -/// The next id in write order. Process-wide: two processes writing the same | 19 | +/// `ContextV7` is `Send` but not `Sync` (interior `Cell`s), so the |
| 20 | -/// table still only get millisecond accuracy, which is what a distributed id | 20 | +/// process-wide context lives behind a mutex — the same serialization the id |
| 21 | -/// can promise anyway. | 21 | +/// generator always had, and the price of one process-wide mint order. |
| 22 | -pub fn next_ulid() -> Ulid { | 22 | +static CTX: LazyLock<Mutex<ContextV7>> = LazyLock::new(|| Mutex::new(ContextV7::new())); |
| 23 | - let mut ids = IDS.lock().expect("monotonic id generator poisoned"); | 23 | + |
| 24 | - // The only error is exhausting the random bits *within* one millisecond | 24 | +/// The next id in write order. The wall clock is the codebase's single read |
| 25 | - // (2^80 ids deep); it clears itself as the clock ticks, so retry rather | 25 | +/// ([`Timestamp::now`]); the context contributes the within-millisecond |
| 26 | - // than fall back to a random id and silently reintroduce the defect. | 26 | +/// counter. Process-wide: two processes writing the same table still only get |
| 27 | - loop { | 27 | +/// millisecond accuracy, which is what a distributed id can promise anyway. |
| 28 | - if let Ok(ulid) = ids.generate() { | 28 | +pub fn next_uuid() -> Uuid { |
| 29 | - break ulid; | 29 | + let millis = Timestamp::now().as_millis(); |
| 30 | - } | 30 | + let context = CTX.lock().expect("uuid v7 context poisoned"); |
| 31 | - } | 31 | + Uuid::new_v7(uuid::Timestamp::from_unix( |
| 32 | + &*context, | ||
| 33 | + (millis / 1_000) as u64, | ||
| 34 | + (millis % 1_000) as u32 * 1_000_000, | ||
| 35 | + )) | ||
| 32 | } | 36 | } |
| 33 | 37 | ||
| 34 | #[cfg(test)] | 38 | #[cfg(test)] |
| @@ -36,10 +40,11 @@ mod tests { | |||
| 36 | use super::*; | 40 | use super::*; |
| 37 | 41 | ||
| 38 | /// The defect this module exists for: ids minted back to back (well inside | 42 | /// The defect this module exists for: ids minted back to back (well inside |
| 39 | - /// one millisecond) must still sort in mint order. | 43 | + /// one millisecond) must still sort in mint order. `Uuid`'s `Ord` is |
| 44 | + /// big-endian byte order, exactly what a `uuid` column sorts by. | ||
| 40 | #[test] | 45 | #[test] |
| 41 | fn ids_sort_in_mint_order_within_a_millisecond() { | 46 | fn ids_sort_in_mint_order_within_a_millisecond() { |
| 42 | - let ids: Vec<String> = (0..1000).map(|_| next_ulid().to_string()).collect(); | 47 | + let ids: Vec<Uuid> = (0..1000).map(|_| next_uuid()).collect(); |
| 43 | let mut sorted = ids.clone(); | 48 | let mut sorted = ids.clone(); |
| 44 | sorted.sort(); | 49 | sorted.sort(); |
| 45 | assert_eq!(ids, sorted); | 50 | assert_eq!(ids, sorted); |
src/domain/note.rsmodified+24 -20
| @@ -1,39 +1,41 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | +use uuid::Uuid; |
| 2 | 2 | ||
| 3 | -use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN, NOTE_TABLE}; | 3 | +use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN}; |
| 4 | -use crate::domain::monotonic_id::next_ulid; | 4 | +use crate::domain::monotonic_id::next_uuid; |
| 5 | use crate::domain::user::UserId; | 5 | use crate::domain::user::UserId; |
| 6 | use crate::error::ValidationError; | 6 | use crate::error::ValidationError; |
| 7 | use crate::validate::{validate_optional, validate_required}; | 7 | use crate::validate::{validate_optional, validate_required}; |
| 8 | 8 | ||
| 9 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 9 | +/// Typed note row id. A UUIDv7 minted by the process-wide monotonic |
| 10 | -pub struct NoteId(RecordId); | 10 | +/// generator, so `id` order is mint order. |
| 11 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] | ||
| 12 | +#[sqlx(transparent)] | ||
| 13 | +pub struct NoteId(Uuid); | ||
| 11 | 14 | ||
| 12 | impl NoteId { | 15 | impl NoteId { |
| 13 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 16 | + /// Minted from the process-wide monotonic generator, not a random v4: |
| 14 | /// notes list `id DESC` (newest first, [`crate::db::note::list_for`]), | 17 | /// notes list `id DESC` (newest first, [`crate::db::note::list_for`]), |
| 15 | /// and a random low half scrambles rows minted in the same millisecond. | 18 | /// and a random low half scrambles rows minted in the same millisecond. |
| 16 | pub fn generate() -> Self { | 19 | pub fn generate() -> Self { |
| 17 | - Self(RecordId::new(NOTE_TABLE, next_ulid().to_string())) | 20 | + Self(next_uuid()) |
| 18 | } | 21 | } |
| 19 | 22 | ||
| 23 | + /// Parse a wire key. A key that parses as no UUID — a malformed path | ||
| 24 | + /// segment — reads as the nil id, which matches no row: exactly the 404 a | ||
| 25 | + /// dangling record key produced under the old store, without turning a | ||
| 26 | + /// typo into a panic. | ||
| 20 | pub fn from_key(key: &str) -> Self { | 27 | pub fn from_key(key: &str) -> Self { |
| 21 | - Self(RecordId::new(NOTE_TABLE, key)) | 28 | + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) |
| 22 | } | 29 | } |
| 23 | 30 | ||
| 24 | - pub fn record(&self) -> RecordId { | 31 | + /// The hyphenated wire form. |
| 25 | - self.0.clone() | 32 | + pub fn key(&self) -> String { |
| 26 | - } | 33 | + self.0.to_string() |
| 27 | - | ||
| 28 | - pub fn key(&self) -> &str { | ||
| 29 | - match &self.0.key { | ||
| 30 | - RecordIdKey::String(key) => key, | ||
| 31 | - _ => "", | ||
| 32 | - } | ||
| 33 | } | 34 | } |
| 34 | } | 35 | } |
| 35 | 36 | ||
| 36 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 37 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 38 | +#[sqlx(transparent)] | ||
| 37 | pub struct NoteTitle(String); | 39 | pub struct NoteTitle(String); |
| 38 | 40 | ||
| 39 | impl NoteTitle { | 41 | impl NoteTitle { |
| @@ -47,7 +49,8 @@ impl NoteTitle { | |||
| 47 | } | 49 | } |
| 48 | } | 50 | } |
| 49 | 51 | ||
| 50 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 52 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 53 | +#[sqlx(transparent)] | ||
| 51 | pub struct NoteContent(String); | 54 | pub struct NoteContent(String); |
| 52 | 55 | ||
| 53 | impl NoteContent { | 56 | impl NoteContent { |
| @@ -63,9 +66,10 @@ impl NoteContent { | |||
| 63 | 66 | ||
| 64 | /// Fields are crate-visible: [`crate::db::note`] mints the rows on create and | 67 | /// Fields are crate-visible: [`crate::db::note`] mints the rows on create and |
| 65 | /// reads the id when updating and cascading a delete. | 68 | /// reads the id when updating and cascading a delete. |
| 66 | -#[derive(Debug, Clone, SurrealValue)] | 69 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 67 | pub struct Note { | 70 | pub struct Note { |
| 68 | pub(crate) id: NoteId, | 71 | pub(crate) id: NoteId, |
| 72 | + #[sqlx(rename = "app_user")] | ||
| 69 | pub(crate) user: UserId, | 73 | pub(crate) user: UserId, |
| 70 | pub(crate) title: NoteTitle, | 74 | pub(crate) title: NoteTitle, |
| 71 | pub(crate) content: NoteContent, | 75 | pub(crate) content: NoteContent, |
src/domain/note_file.rsmodified+26 -23
| @@ -1,49 +1,51 @@ | |||
| 1 | //! A file attached to a note. The row carries metadata only (original | 1 | //! A file attached to a note. The row carries metadata only (original |
| 2 | //! filename, MIME type, byte size); the bytes themselves live on disk under | 2 | //! filename, MIME type, byte size); the bytes themselves live on disk under |
| 3 | //! [`crate::config::Config::files_path`], in a file named by this row's key — | 3 | //! [`crate::config::Config::files_path`], in a file named by this row's key — |
| 4 | -//! a server-generated ULID, so no user input ever shapes a disk path. The web | 4 | +//! a server-generated UUIDv7, so no user input ever shapes a disk path. The |
| 5 | -//! layer owns the blob I/O and its ordering (blob before row on upload, row | 5 | +//! web layer owns the blob I/O and its ordering (blob before row on upload, |
| 6 | -//! before blob on delete); persistence lives in [`crate::db::note_file`]. | 6 | +//! row before blob on delete); persistence lives in [`crate::db::note_file`]. |
| 7 | 7 | ||
| 8 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 8 | +use uuid::Uuid; |
| 9 | 9 | ||
| 10 | -use crate::constant::{MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN, NOTE_FILE_TABLE}; | 10 | +use crate::constant::{MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN}; |
| 11 | -use crate::domain::monotonic_id::next_ulid; | 11 | +use crate::domain::monotonic_id::next_uuid; |
| 12 | use crate::domain::note::NoteId; | 12 | use crate::domain::note::NoteId; |
| 13 | use crate::error::ValidationError; | 13 | use crate::error::ValidationError; |
| 14 | 14 | ||
| 15 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 15 | +/// Typed note-file row id. A UUIDv7 minted by the process-wide monotonic |
| 16 | -pub struct NoteFileId(RecordId); | 16 | +/// generator, so `id` order is mint order. |
| 17 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] | ||
| 18 | +#[sqlx(transparent)] | ||
| 19 | +pub struct NoteFileId(Uuid); | ||
| 17 | 20 | ||
| 18 | impl NoteFileId { | 21 | impl NoteFileId { |
| 19 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 22 | + /// Minted from the process-wide monotonic generator, not a random v4: |
| 20 | /// a note's files list `id DESC` (newest first, | 23 | /// a note's files list `id DESC` (newest first, |
| 21 | /// [`crate::db::note_file::list_for`]), and a random low half scrambles | 24 | /// [`crate::db::note_file::list_for`]), and a random low half scrambles |
| 22 | /// rows minted in the same millisecond. | 25 | /// rows minted in the same millisecond. |
| 23 | pub fn generate() -> Self { | 26 | pub fn generate() -> Self { |
| 24 | - Self(RecordId::new(NOTE_FILE_TABLE, next_ulid().to_string())) | 27 | + Self(next_uuid()) |
| 25 | } | 28 | } |
| 26 | 29 | ||
| 30 | + /// Parse a wire key. A key that parses as no UUID — a malformed path | ||
| 31 | + /// segment — reads as the nil id, which matches no row: exactly the 404 a | ||
| 32 | + /// dangling record key produced under the old store, without turning a | ||
| 33 | + /// typo into a panic. | ||
| 27 | pub fn from_key(key: &str) -> Self { | 34 | pub fn from_key(key: &str) -> Self { |
| 28 | - Self(RecordId::new(NOTE_FILE_TABLE, key)) | 35 | + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) |
| 29 | } | 36 | } |
| 30 | 37 | ||
| 31 | - pub fn record(&self) -> RecordId { | 38 | + /// The hyphenated wire form. |
| 32 | - self.0.clone() | 39 | + pub fn key(&self) -> String { |
| 33 | - } | 40 | + self.0.to_string() |
| 34 | - | ||
| 35 | - pub fn key(&self) -> &str { | ||
| 36 | - match &self.0.key { | ||
| 37 | - RecordIdKey::String(key) => key, | ||
| 38 | - _ => "", | ||
| 39 | - } | ||
| 40 | } | 41 | } |
| 41 | } | 42 | } |
| 42 | 43 | ||
| 43 | /// The uploader's original filename, kept for display and download headers. | 44 | /// The uploader's original filename, kept for display and download headers. |
| 44 | /// Never used as a disk path — but path separators and control characters are | 45 | /// Never used as a disk path — but path separators and control characters are |
| 45 | /// refused anyway: they are not filenames, only header/log injection attempts. | 46 | /// refused anyway: they are not filenames, only header/log injection attempts. |
| 46 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 47 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 48 | +#[sqlx(transparent)] | ||
| 47 | pub struct FileName(String); | 49 | pub struct FileName(String); |
| 48 | 50 | ||
| 49 | impl FileName { | 51 | impl FileName { |
| @@ -79,7 +81,8 @@ impl FileName { | |||
| 79 | /// The MIME type the client declared for the file. Blank defaults to | 81 | /// The MIME type the client declared for the file. Blank defaults to |
| 80 | /// `application/octet-stream`; it is echoed back on download, so it is held | 82 | /// `application/octet-stream`; it is echoed back on download, so it is held |
| 81 | /// to header-safe ASCII. | 83 | /// to header-safe ASCII. |
| 82 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 84 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 85 | +#[sqlx(transparent)] | ||
| 83 | pub struct FileContentType(String); | 86 | pub struct FileContentType(String); |
| 84 | 87 | ||
| 85 | impl FileContentType { | 88 | impl FileContentType { |
| @@ -112,7 +115,7 @@ impl FileContentType { | |||
| 112 | } | 115 | } |
| 113 | } | 116 | } |
| 114 | 117 | ||
| 115 | -#[derive(Debug, Clone, SurrealValue)] | 118 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 116 | pub struct NoteFile { | 119 | pub struct NoteFile { |
| 117 | pub(crate) id: NoteFileId, | 120 | pub(crate) id: NoteFileId, |
| 118 | pub(crate) note: NoteId, | 121 | pub(crate) note: NoteId, |
src/domain/parent_link.rsmodified+35 -26
| @@ -1,32 +1,46 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | - | ||
| 3 | -use crate::constant::PARENT_LINK_TABLE; | ||
| 4 | use crate::domain::user::UserId; | 1 | use crate::domain::user::UserId; |
| 5 | 2 | ||
| 6 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 3 | +/// The (parent, student) pair — the table's natural composite primary key. |
| 7 | -pub struct ParentLinkId(RecordId); | 4 | +/// The same pair always maps to the same row, so linking is a single atomic |
| 5 | +/// upsert with no find-then-insert race and one-row-per-pair by construction. | ||
| 6 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 7 | +pub struct ParentLinkId { | ||
| 8 | + parent: UserId, | ||
| 9 | + student: UserId, | ||
| 10 | +} | ||
| 8 | 11 | ||
| 9 | impl ParentLinkId { | 12 | impl ParentLinkId { |
| 10 | - /// A deterministic id for the (parent, student) pair — same trick as | ||
| 11 | - /// `EnrollmentId`: the same pair always maps to the same record id, so | ||
| 12 | - /// linking is a single atomic UPSERT with no find-then-insert race and | ||
| 13 | - /// one-row-per-pair by construction. | ||
| 14 | pub fn composite(parent: &UserId, student: &UserId) -> Self { | 13 | pub fn composite(parent: &UserId, student: &UserId) -> Self { |
| 15 | - Self(RecordId::new( | 14 | + Self { |
| 16 | - PARENT_LINK_TABLE, | 15 | + parent: *parent, |
| 17 | - format!("{}_{}", parent.key(), student.key()), | 16 | + student: *student, |
| 18 | - )) | 17 | + } |
| 19 | } | 18 | } |
| 20 | 19 | ||
| 21 | - pub fn record(&self) -> RecordId { | 20 | + /// Parse the `{parent}_{student}` wire form. A key that parses as no pair |
| 22 | - self.0.clone() | 21 | + /// reads as the nil pair, which matches no row — exactly the 404 a |
| 22 | + /// dangling composite key produced under the old store, without turning a | ||
| 23 | + /// typo into a panic. UUID strings carry only `-`, so `_` is an | ||
| 24 | + /// unambiguous joiner. | ||
| 25 | + pub fn from_key(key: &str) -> Self { | ||
| 26 | + let (parent, student) = key.rsplit_once('_').unwrap_or(("", "")); | ||
| 27 | + Self { | ||
| 28 | + parent: UserId::from_key(parent), | ||
| 29 | + student: UserId::from_key(student), | ||
| 30 | + } | ||
| 23 | } | 31 | } |
| 24 | 32 | ||
| 25 | - pub fn key(&self) -> &str { | 33 | + /// The `{parent}_{student}` wire form. |
| 26 | - match &self.0.key { | 34 | + pub fn key(&self) -> String { |
| 27 | - RecordIdKey::String(key) => key, | 35 | + format!("{}_{}", self.parent.key(), self.student.key()) |
| 28 | - _ => "", | 36 | + } |
| 29 | - } | 37 | + |
| 38 | + pub fn parent(&self) -> UserId { | ||
| 39 | + self.parent | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + pub fn student(&self) -> UserId { | ||
| 43 | + self.student | ||
| 30 | } | 44 | } |
| 31 | } | 45 | } |
| 32 | 46 | ||
| @@ -35,19 +49,14 @@ impl ParentLinkId { | |||
| 35 | /// attendance, pomodoro). The single write it authorizes is the food program — | 49 | /// attendance, pomodoro). The single write it authorizes is the food program — |
| 36 | /// a parent books and cancels a linked child's meals, since paying for lunch | 50 | /// a parent books and cancels a linked child's meals, since paying for lunch |
| 37 | /// is a parent's job and a small child cannot do it themselves. | 51 | /// is a parent's job and a small child cannot do it themselves. |
| 38 | -#[derive(Debug, Clone, SurrealValue)] | 52 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 39 | pub struct ParentLink { | 53 | pub struct ParentLink { |
| 40 | - pub(crate) id: ParentLinkId, | ||
| 41 | pub(crate) parent: UserId, | 54 | pub(crate) parent: UserId, |
| 42 | pub(crate) student: UserId, | 55 | pub(crate) student: UserId, |
| 43 | pub(crate) linked_by: UserId, | 56 | pub(crate) linked_by: UserId, |
| 44 | } | 57 | } |
| 45 | 58 | ||
| 46 | impl ParentLink { | 59 | impl ParentLink { |
| 47 | - pub fn get_id(&self) -> &ParentLinkId { | ||
| 48 | - &self.id | ||
| 49 | - } | ||
| 50 | - | ||
| 51 | pub fn get_parent(&self) -> &UserId { | 60 | pub fn get_parent(&self) -> &UserId { |
| 52 | &self.parent | 61 | &self.parent |
| 53 | } | 62 | } |
src/domain/payment_ledger.rsmodified+96 -104
| @@ -1,11 +1,11 @@ | |||
| 1 | //! School fees: an **append-only** ledger of what a student was charged, what | 1 | //! School fees: an **append-only** ledger of what a student was charged, what |
| 2 | //! they paid against each charge, and what was paid back out. | 2 | //! they paid against each charge, and what was paid back out. |
| 3 | //! | 3 | //! |
| 4 | -//! Nothing here ever `UPDATE`s or `DELETE`s a row, and no such path exists — | 4 | +//! Nothing here ever `UPDATE`s or `DELETE`s a row, and no such path exists. A |
| 5 | -//! every field is `READONLY` in the schema as well. A ledger line that can be | 5 | +//! ledger line that can be edited or dropped silently rewrites a family's |
| 6 | -//! edited or dropped silently rewrites a family's financial history with no | 6 | +//! financial history with no trace of the rewrite; a mistake is corrected by |
| 7 | -//! trace of the rewrite; a mistake is corrected by appending the opposing line, | 7 | +//! appending the opposing line, which leaves both the mistake and the |
| 8 | -//! which leaves both the mistake and the correction visible. | 8 | +//! correction visible. |
| 9 | //! | 9 | //! |
| 10 | //! **The balance is never stored.** It is always the fold | 10 | //! **The balance is never stored.** It is always the fold |
| 11 | //! | 11 | //! |
| @@ -31,103 +31,103 @@ | |||
| 31 | //! - **A reversal only undoes a negative-fold line** (a charge, or a refund). | 31 | //! - **A reversal only undoes a negative-fold line** (a charge, or a refund). |
| 32 | //! A mistaken *credit* is corrected by a refund pointing at it, so that the | 32 | //! A mistaken *credit* is corrected by a refund pointing at it, so that the |
| 33 | //! money leaving the school is always spelled the same way. A reversal itself | 33 | //! money leaving the school is always spelled the same way. A reversal itself |
| 34 | -//! is never reversed (the id would collide with its own target's, and the | 34 | +//! is never reversed (the key would collide with its own target's, and the |
| 35 | //! kind check refuses it): a charge dropped by mistake is re-raised by | 35 | //! kind check refuses it): a charge dropped by mistake is re-raised by |
| 36 | //! assigning a fresh one-installment plan, which mints a new deterministic | 36 | //! assigning a fresh one-installment plan, which mints a new deterministic |
| 37 | -//! charge id instead of resurrecting the old one. | 37 | +//! charge key instead of resurrecting the old one. |
| 38 | //! - **Every replayable line is keyed by its cause.** An installment charge's | 38 | //! - **Every replayable line is keyed by its cause.** An installment charge's |
| 39 | -//! id is `(plan, student, n)` and a reversal's is `<line>_r`, so replaying | 39 | +//! key is `{assignment-key}_c{n}` and a reversal's is `{line-key}_r`, so |
| 40 | -//! either writes nothing at all, and an assignment that crashed half-way | 40 | +//! replaying either writes nothing at all, and an assignment that crashed |
| 41 | -//! self-heals when it is repeated. Money must never depend on a "has this | 41 | +//! half-way self-heals when it is repeated. Money must never depend on a |
| 42 | -//! been billed yet?" scan: two concurrent requests can both read "not yet" | 42 | +//! "has this been billed yet?" scan: two concurrent requests can both read |
| 43 | -//! and both append. | 43 | +//! "not yet" and both append. |
| 44 | +//! | ||
| 45 | +//! The ledger row ids are **derived TEXT keys**, not minted uuids — they are | ||
| 46 | +//! the identity the store's uniqueness check enforces (`id TEXT PRIMARY | ||
| 47 | +//! KEY`): a duplicate insert of the same key is the "already billed" answer. | ||
| 48 | +//! | ||
| 49 | +//! The writes and the balance reads live in [`crate::db::payment_ledger`]; | ||
| 50 | +//! the credit/refund/reversal workflows in | ||
| 51 | +//! [`crate::service::payment_ledger`]. | ||
| 44 | 52 | ||
| 45 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 53 | +use sqlx::Type; |
| 46 | 54 | ||
| 47 | -use crate::constant::PAYMENT_LEDGER_TABLE; | ||
| 48 | use crate::domain::fee_plan_assignment::FeePlanAssignmentId; | 55 | use crate::domain::fee_plan_assignment::FeePlanAssignmentId; |
| 49 | // The three value types are the *same* money vocabulary the canteen ledger | 56 | // The three value types are the *same* money vocabulary the canteen ledger |
| 50 | // speaks, so they are imported rather than copied: one cap, one trim rule, one | 57 | // speaks, so they are imported rather than copied: one cap, one trim rule, one |
| 51 | // error message for both ledgers. | 58 | // error message for both ledgers. |
| 52 | pub use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote}; | 59 | pub use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote}; |
| 53 | -use crate::domain::monotonic_id::next_ulid; | ||
| 54 | use crate::domain::timestamp::Timestamp; | 60 | use crate::domain::timestamp::Timestamp; |
| 55 | use crate::domain::user::UserId; | 61 | use crate::domain::user::UserId; |
| 56 | use crate::error::ValidationError; | 62 | use crate::error::ValidationError; |
| 57 | 63 | ||
| 58 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 64 | +/// The ledger line's id — a derived TEXT key (`id TEXT PRIMARY KEY`): |
| 59 | -pub struct PaymentLedgerId(RecordId); | 65 | +/// `{assignment-key}_c{n}` for an installment charge, `{line-key}_r` for a |
| 66 | +/// reversal, `{target-key}_{marker}_{request_key}` for a keyed payment or | ||
| 67 | +/// refund, or a fresh uuid-string key otherwise. | ||
| 68 | +#[derive(Debug, Clone, PartialEq, Eq, Type)] | ||
| 69 | +#[sqlx(transparent)] | ||
| 70 | +pub struct PaymentLedgerId(String); | ||
| 60 | 71 | ||
| 61 | impl PaymentLedgerId { | 72 | impl PaymentLedgerId { |
| 62 | - /// A fresh id in write order — `Ulid::generate()`'s random low bits sort | 73 | + /// A fresh key in write order — the process-wide uuid v7 generator's |
| 63 | - /// arbitrarily within one millisecond, which would scramble the `id` | 74 | + /// string form, so the `id` tie-break of the newest-first statement below |
| 64 | - /// tie-break of the newest-first statement below. | 75 | + /// still sorts in mint order. |
| 65 | pub fn generate() -> Self { | 76 | pub fn generate() -> Self { |
| 66 | - Self(RecordId::new(PAYMENT_LEDGER_TABLE, next_ulid().to_string())) | 77 | + Self(crate::domain::monotonic_id::next_uuid().to_string()) |
| 67 | } | 78 | } |
| 68 | 79 | ||
| 80 | + /// Parse a stored key back into an id. Ledger keys are TEXT, so any | ||
| 81 | + /// string round-trips. | ||
| 69 | pub fn from_key(key: &str) -> Self { | 82 | pub fn from_key(key: &str) -> Self { |
| 70 | - Self(RecordId::new(PAYMENT_LEDGER_TABLE, key)) | 83 | + Self(key.to_string()) |
| 71 | } | 84 | } |
| 72 | 85 | ||
| 73 | /// The one charge line installment `n` (1-based) of this assignment may | 86 | /// The one charge line installment `n` (1-based) of this assignment may |
| 74 | - /// ever have. The assignment key is already `<plan>_<student>`, so this is | 87 | + /// ever have. The assignment key is already `{plan}_{student}`, so this is |
| 75 | - /// `<plan>_<student>_c<n>`: two concurrent assigns derive the *same* ids | 88 | + /// `{plan}_{student}_c{n}`: two concurrent assigns derive the *same* keys |
| 76 | - /// and so cannot bill a plan twice. Idempotence rests on identity, never on | 89 | + /// and so cannot bill a plan twice. Idempotence rests on identity, never |
| 77 | - /// a scan a concurrent writer can slip past. | 90 | + /// on a scan a concurrent writer can slip past. |
| 78 | pub fn for_installment(assignment: &FeePlanAssignmentId, n: usize) -> Self { | 91 | pub fn for_installment(assignment: &FeePlanAssignmentId, n: usize) -> Self { |
| 79 | - Self(RecordId::new( | 92 | + Self(format!("{}_c{n}", assignment.key())) |
| 80 | - PAYMENT_LEDGER_TABLE, | ||
| 81 | - format!("{}_c{n}", assignment.key()), | ||
| 82 | - )) | ||
| 83 | } | 93 | } |
| 84 | 94 | ||
| 85 | /// The one reversal a line may ever have — a retried undo appends nothing | 95 | /// The one reversal a line may ever have — a retried undo appends nothing |
| 86 | - /// the second time — the id decides that, not a scan. | 96 | + /// the second time — the key decides that, not a scan. |
| 87 | pub fn for_reversal(line: &PaymentLedgerId) -> Self { | 97 | pub fn for_reversal(line: &PaymentLedgerId) -> Self { |
| 88 | - Self(RecordId::new( | 98 | + Self(format!("{}_r", line.key())) |
| 89 | - PAYMENT_LEDGER_TABLE, | ||
| 90 | - format!("{}_r", line.key()), | ||
| 91 | - )) | ||
| 92 | } | 99 | } |
| 93 | 100 | ||
| 94 | - /// The one line a `(target, request_key)` pair may ever have: `<target>_k_` | 101 | + /// The one line a `(target, request_key)` pair may ever have: |
| 95 | - /// for a payment, `<target>_kr_` for a refund. Scoping the key by the line | 102 | + /// `{target}_k_{key}` for a payment, `{target}_kr_{key}` for a refund. |
| 96 | - /// it targets is what keeps one office's "receipt-114" from colliding with | 103 | + /// Scoping the key by the line it targets is what keeps one office's |
| 97 | - /// another charge's, and the two markers keep the kinds apart the same way | 104 | + /// "receipt-114" from colliding with another charge's, and the two markers |
| 98 | - /// `_c<n>` and `_r` do above. | 105 | + /// keep the kinds apart the same way `_c{n}` and `_r` do above. |
| 99 | /// | 106 | /// |
| 100 | /// **The grammar parses uniquely because `_` joins the parts and cannot | 107 | /// **The grammar parses uniquely because `_` joins the parts and cannot |
| 101 | - /// appear inside one.** Every id here is `<ulid>_<ulid>_c<n>` optionally | 108 | + /// appear inside one.** Every key here is `<uuid>_<uuid>_c<n>` optionally |
| 102 | - /// followed by one `_k_<key>`, `_kr_<key>` or `_r` — plan and student keys | 109 | + /// followed by one `_k_<key>`, `_kr_<key>` or `_r` — uuid halves carry |
| 103 | - /// are ULIDs (`[0-9A-Z]` only) and a `request_key` is | 110 | + /// only hex digits and `-`, and a `request_key` is |
| 104 | /// [`crate::validate::validate_request_key`]'s `[A-Za-z0-9-]`, so no part | 111 | /// [`crate::validate::validate_request_key`]'s `[A-Za-z0-9-]`, so no part |
| 105 | /// can spell a separator plus a marker. That is not decoration: a key of | 112 | /// can spell a separator plus a marker. That is not decoration: a key of |
| 106 | - /// `abc_r` on a refund would derive exactly the id that refund's *reversal* | 113 | + /// `abc_r` on a refund would derive exactly the key that refund's |
| 107 | - /// must own, and the loser of that collision would be handed a line of the | 114 | + /// *reversal* must own, and the loser of that collision would be handed a |
| 108 | - /// wrong kind and the wrong amount, with the real reversal impossible | 115 | + /// line of the wrong kind and the wrong amount, with the real reversal |
| 109 | - /// forever after. The ban on `_` in a key is what makes the collision | 116 | + /// impossible forever after. The ban on `_` in a key is what makes the |
| 110 | - /// unconstructible; `crate::db::payment_ledger::append` re-checks the | 117 | + /// collision unconstructible; `crate::db::payment_ledger::append` re-checks |
| 111 | - /// kind anyway. | 118 | + /// the kind anyway. |
| 112 | pub fn for_request(target: &PaymentLedgerId, marker: &str, key: &PaymentRequestKey) -> Self { | 119 | pub fn for_request(target: &PaymentLedgerId, marker: &str, key: &PaymentRequestKey) -> Self { |
| 113 | - Self(RecordId::new( | 120 | + Self(format!("{}_{marker}_{}", target.key(), key.as_str())) |
| 114 | - PAYMENT_LEDGER_TABLE, | ||
| 115 | - format!("{}_{marker}_{}", target.key(), key.as_str()), | ||
| 116 | - )) | ||
| 117 | - } | ||
| 118 | - | ||
| 119 | - pub fn record(&self) -> RecordId { | ||
| 120 | - self.0.clone() | ||
| 121 | } | 121 | } |
| 122 | 122 | ||
| 123 | pub fn key(&self) -> &str { | 123 | pub fn key(&self) -> &str { |
| 124 | - key_of(&self.0) | 124 | + &self.0 |
| 125 | } | 125 | } |
| 126 | } | 126 | } |
| 127 | 127 | ||
| 128 | /// A client-chosen idempotence key for one payment or refund. Never stored as | 128 | /// A client-chosen idempotence key for one payment or refund. Never stored as |
| 129 | -/// a column — it lives inside the line's record id, which is what makes a retry | 129 | +/// a column — it lives inside the line's derived key, which is what makes a |
| 130 | -/// derive the row it already wrote instead of a second one. | 130 | +/// retry derive the row it already wrote instead of a second one. |
| 131 | #[derive(Debug, Clone)] | 131 | #[derive(Debug, Clone)] |
| 132 | pub struct PaymentRequestKey(String); | 132 | pub struct PaymentRequestKey(String); |
| 133 | 133 | ||
| @@ -142,18 +142,10 @@ impl PaymentRequestKey { | |||
| 142 | } | 142 | } |
| 143 | } | 143 | } |
| 144 | 144 | ||
| 145 | -/// The bare key of a record id — how every id leaves this API. | 145 | +/// What a line means. Stored as the bare lowercase TEXT value the `kind` |
| 146 | -fn key_of(record: &RecordId) -> &str { | 146 | +/// column carries, in lockstep with `PAYMENT_LEDGER_KINDS`. |
| 147 | - match &record.key { | 147 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] |
| 148 | - RecordIdKey::String(key) => key, | 148 | +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] |
| 149 | - _ => "", | ||
| 150 | - } | ||
| 151 | -} | ||
| 152 | - | ||
| 153 | -/// What a line means. `untagged` + `rename_all` store it as the bare lowercase | ||
| 154 | -/// string the `kind` column types as, in lockstep with `PAYMENT_LEDGER_KINDS`. | ||
| 155 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | ||
| 156 | -#[surreal(untagged, rename_all = "lowercase")] | ||
| 157 | pub enum PaymentLedgerKind { | 149 | pub enum PaymentLedgerKind { |
| 158 | Charge, | 150 | Charge, |
| 159 | Credit, | 151 | Credit, |
| @@ -185,17 +177,18 @@ impl PaymentLedgerKind { | |||
| 185 | 177 | ||
| 186 | /// Fields are crate-visible: [`crate::db::payment_ledger`] mints the charge | 178 | /// Fields are crate-visible: [`crate::db::payment_ledger`] mints the charge |
| 187 | /// rows, and [`crate::service::payment_ledger`] appends the credits, refunds, | 179 | /// rows, and [`crate::service::payment_ledger`] appends the credits, refunds, |
| 188 | -/// and reversals the cap lock authorizes. | 180 | +/// and reversals the guard authorizes. |
| 189 | -#[derive(Debug, Clone, SurrealValue)] | 181 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 190 | pub struct PaymentLedger { | 182 | pub struct PaymentLedger { |
| 191 | pub(crate) id: PaymentLedgerId, | 183 | pub(crate) id: PaymentLedgerId, |
| 192 | pub(crate) student: UserId, | 184 | pub(crate) student: UserId, |
| 193 | pub(crate) kind: PaymentLedgerKind, | 185 | pub(crate) kind: PaymentLedgerKind, |
| 194 | pub(crate) amount_minor: LedgerAmount, | 186 | pub(crate) amount_minor: LedgerAmount, |
| 195 | - /// What caused the line: a charge points at its `fee_plan_assignment`, a | 187 | + /// What caused the line: a charge points at its `fee_plan_assignment` |
| 196 | - /// credit at the charge it pays, a refund at the credit it returns, a | 188 | + /// row's `{plan}_{student}` key, a credit at the charge it pays, a refund |
| 197 | - /// reversal at the line it undoes. Untyped, hence a bare `RecordId`. | 189 | + /// at the credit it returns, a reversal at the line it undoes. |
| 198 | - pub(crate) source: Option<RecordId>, | 190 | + /// Polymorphic by kind, hence a bare TEXT key — no foreign key. |
| 191 | + pub(crate) source: Option<String>, | ||
| 199 | /// When this installment falls due. Charges only — nothing else has one. | 192 | /// When this installment falls due. Charges only — nothing else has one. |
| 200 | pub(crate) due_at: Option<Timestamp>, | 193 | pub(crate) due_at: Option<Timestamp>, |
| 201 | pub(crate) method: Option<LedgerMethod>, | 194 | pub(crate) method: Option<LedgerMethod>, |
| @@ -223,7 +216,7 @@ impl PaymentLedger { | |||
| 223 | 216 | ||
| 224 | /// The cause's bare key; which table it lives in follows from the kind. | 217 | /// The cause's bare key; which table it lives in follows from the kind. |
| 225 | pub fn get_source_key(&self) -> Option<&str> { | 218 | pub fn get_source_key(&self) -> Option<&str> { |
| 226 | - self.source.as_ref().map(key_of) | 219 | + self.source.as_deref() |
| 227 | } | 220 | } |
| 228 | 221 | ||
| 229 | pub fn get_due_at(&self) -> Option<Timestamp> { | 222 | pub fn get_due_at(&self) -> Option<Timestamp> { |
| @@ -268,26 +261,24 @@ impl PaymentLedger { | |||
| 268 | 261 | ||
| 269 | #[cfg(test)] | 262 | #[cfg(test)] |
| 270 | mod tests { | 263 | mod tests { |
| 271 | - use surrealdb::types::Value; | ||
| 272 | - | ||
| 273 | use super::*; | 264 | use super::*; |
| 274 | use crate::domain::fee_plan::FeePlanId; | 265 | use crate::domain::fee_plan::FeePlanId; |
| 275 | - use crate::domain::user::UserId; | ||
| 276 | 266 | ||
| 277 | - /// The `kind` column is `TYPE string`: an object-wrapped enum would be | 267 | + /// The `kind` column is `TEXT` with a CHECK on these exact words; the |
| 278 | - /// rejected on write, and a `kind = 'charge'` lookup would silently match | 268 | + /// sqlx encoding must never drift from `as_str`, or a `kind = 'charge'` |
| 279 | - /// nothing. | 269 | + /// lookup would silently match nothing. |
| 280 | #[test] | 270 | #[test] |
| 281 | - fn kind_stores_as_a_bare_string() { | 271 | + fn sqlx_encodes_the_storage_form() { |
| 272 | + let mut buf = sqlx::postgres::PgArgumentBuffer::default(); | ||
| 282 | for kind in [ | 273 | for kind in [ |
| 283 | PaymentLedgerKind::Charge, | 274 | PaymentLedgerKind::Charge, |
| 284 | PaymentLedgerKind::Credit, | 275 | PaymentLedgerKind::Credit, |
| 285 | PaymentLedgerKind::Reversal, | 276 | PaymentLedgerKind::Reversal, |
| 286 | PaymentLedgerKind::Refund, | 277 | PaymentLedgerKind::Refund, |
| 287 | ] { | 278 | ] { |
| 288 | - let value = kind.into_value(); | 279 | + buf.clear(); |
| 289 | - assert_eq!(value, Value::String(kind.as_str().to_string())); | 280 | + sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&kind, &mut buf); |
| 290 | - assert_eq!(PaymentLedgerKind::from_value(value).unwrap(), kind); | 281 | + assert_eq!(std::str::from_utf8(&buf).unwrap(), kind.as_str()); |
| 291 | } | 282 | } |
| 292 | } | 283 | } |
| 293 | 284 | ||
| @@ -335,49 +326,50 @@ mod tests { | |||
| 335 | } | 326 | } |
| 336 | 327 | ||
| 337 | /// Idempotence rests on identity: the same (plan, student, installment) | 328 | /// Idempotence rests on identity: the same (plan, student, installment) |
| 338 | - /// must always derive the same charge id, and a reversal must be the one | 329 | + /// must always derive the same charge key, and a reversal must be the one |
| 339 | /// line its target can ever have. | 330 | /// line its target can ever have. |
| 340 | #[test] | 331 | #[test] |
| 341 | - fn a_charge_id_is_the_plan_the_student_and_the_installment() { | 332 | + fn a_charge_key_is_the_plan_the_student_and_the_installment() { |
| 342 | - let assignment = FeePlanAssignmentId::composite( | 333 | + const PLAN: &str = "018f1a00-0000-7000-8000-000000000001"; |
| 343 | - &FeePlanId::from_key("plan1"), | 334 | + const STU: &str = "018f1a00-0000-7000-8000-000000000002"; |
| 344 | - &UserId::from_key("stu1"), | 335 | + let assignment = FeePlanAssignmentId::composite(&FeePlanId::from_key(PLAN), &UserId::from_key(STU)); |
| 345 | - ); | ||
| 346 | let first = PaymentLedgerId::for_installment(&assignment, 1); | 336 | let first = PaymentLedgerId::for_installment(&assignment, 1); |
| 347 | - assert_eq!(first.key(), "plan1_stu1_c1"); | 337 | + assert_eq!(first.key(), format!("{PLAN}_{STU}_c1")); |
| 348 | assert_eq!( | 338 | assert_eq!( |
| 349 | PaymentLedgerId::for_installment(&assignment, 1), | 339 | PaymentLedgerId::for_installment(&assignment, 1), |
| 350 | first, | 340 | first, |
| 351 | - "a replayed assign must derive the same id, or it bills twice" | 341 | + "a replayed assign must derive the same key, or it bills twice" |
| 352 | ); | 342 | ); |
| 353 | assert_ne!(PaymentLedgerId::for_installment(&assignment, 2), first); | 343 | assert_ne!(PaymentLedgerId::for_installment(&assignment, 2), first); |
| 354 | assert_eq!( | 344 | assert_eq!( |
| 355 | PaymentLedgerId::for_reversal(&first).key(), | 345 | PaymentLedgerId::for_reversal(&first).key(), |
| 356 | - "plan1_stu1_c1_r" | 346 | + format!("{PLAN}_{STU}_c1_r") |
| 357 | ); | 347 | ); |
| 358 | } | 348 | } |
| 359 | 349 | ||
| 360 | - /// A `request_key` is only an idempotence key if it derives the same id | 350 | + /// A `request_key` is only an idempotence key if it derives the same key |
| 361 | /// every time, and only *safe* if it is scoped by the line it targets and | 351 | /// every time, and only *safe* if it is scoped by the line it targets and |
| 362 | /// tells a payment from a refund. | 352 | /// tells a payment from a refund. |
| 363 | #[test] | 353 | #[test] |
| 364 | fn a_request_key_is_scoped_by_its_target_and_its_kind() { | 354 | fn a_request_key_is_scoped_by_its_target_and_its_kind() { |
| 365 | - let charge = PaymentLedgerId::from_key("plan1_stu1_c1"); | 355 | + const PLAN: &str = "018f1a00-0000-7000-8000-000000000001"; |
| 366 | - let other = PaymentLedgerId::from_key("plan1_stu1_c2"); | 356 | + const STU: &str = "018f1a00-0000-7000-8000-000000000002"; |
| 357 | + let charge = PaymentLedgerId::from_key(format!("{PLAN}_{STU}_c1")); | ||
| 358 | + let other = PaymentLedgerId::from_key(format!("{PLAN}_{STU}_c2")); | ||
| 367 | let key = PaymentRequestKey::try_new("receipt-114").unwrap(); | 359 | let key = PaymentRequestKey::try_new("receipt-114").unwrap(); |
| 368 | let credit = PaymentLedgerId::for_request(&charge, "k", &key); | 360 | let credit = PaymentLedgerId::for_request(&charge, "k", &key); |
| 369 | 361 | ||
| 370 | - assert_eq!(credit.key(), "plan1_stu1_c1_k_receipt-114"); | 362 | + assert_eq!(credit.key(), format!("{PLAN}_{STU}_c1_k_receipt-114")); |
| 371 | assert_eq!( | 363 | assert_eq!( |
| 372 | PaymentLedgerId::for_request(&charge, "k", &key), | 364 | PaymentLedgerId::for_request(&charge, "k", &key), |
| 373 | credit, | 365 | credit, |
| 374 | - "a retry must derive the same id, or it pays twice" | 366 | + "a retry must derive the same key, or it pays twice" |
| 375 | ); | 367 | ); |
| 376 | assert_ne!(PaymentLedgerId::for_request(&other, "k", &key), credit); | 368 | assert_ne!(PaymentLedgerId::for_request(&other, "k", &key), credit); |
| 377 | assert_ne!(PaymentLedgerId::for_request(&charge, "kr", &key), credit); | 369 | assert_ne!(PaymentLedgerId::for_request(&charge, "kr", &key), credit); |
| 378 | assert_eq!( | 370 | assert_eq!( |
| 379 | PaymentLedgerId::for_request(&credit, "kr", &key).key(), | 371 | PaymentLedgerId::for_request(&credit, "kr", &key).key(), |
| 380 | - "plan1_stu1_c1_k_receipt-114_kr_receipt-114" | 372 | + format!("{PLAN}_{STU}_c1_k_receipt-114_kr_receipt-114") |
| 381 | ); | 373 | ); |
| 382 | } | 374 | } |
| 383 | } | 375 | } |
src/domain/pomodoro.rsmodified+40 -43
| @@ -1,46 +1,34 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | +use uuid::Uuid; |
| 2 | 2 | ||
| 3 | -use crate::constant::POMODORO_SESSION_TABLE; | 3 | +use crate::domain::monotonic_id::next_uuid; |
| 4 | -use crate::domain::monotonic_id::next_ulid; | ||
| 5 | use crate::domain::timestamp::Timestamp; | 4 | use crate::domain::timestamp::Timestamp; |
| 6 | use crate::domain::user::UserId; | 5 | use crate::domain::user::UserId; |
| 7 | 6 | ||
| 8 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 7 | +/// Typed pomodoro-session row id. A UUIDv7 minted by the process-wide |
| 9 | -pub struct PomodoroSessionId(RecordId); | 8 | +/// monotonic generator, so `id` order is mint order. |
| 9 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] | ||
| 10 | +#[sqlx(transparent)] | ||
| 11 | +pub struct PomodoroSessionId(Uuid); | ||
| 10 | 12 | ||
| 11 | impl PomodoroSessionId { | 13 | impl PomodoroSessionId { |
| 12 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 14 | + /// Minted from the process-wide monotonic generator, not a random v4: |
| 13 | - /// the log sorts `started_at DESC, id DESC` and the id breaks the tie between | 15 | + /// the log sorts `started_at DESC, id DESC` and the id breaks the tie |
| 14 | - /// two sessions started at the same instant. The `open_` key below never ties | 16 | + /// between two sessions started at the same instant. |
| 15 | - /// with itself (one running session per user), so it needs no ordering. | ||
| 16 | pub fn generate() -> Self { | 17 | pub fn generate() -> Self { |
| 17 | - Self(RecordId::new( | 18 | + Self(next_uuid()) |
| 18 | - POMODORO_SESSION_TABLE, | ||
| 19 | - next_ulid().to_string(), | ||
| 20 | - )) | ||
| 21 | } | 19 | } |
| 22 | 20 | ||
| 23 | - /// The deterministic id of `user`'s *running* session. At most one runs | 21 | + /// Parse a wire key. A key that parses as no UUID — a malformed path |
| 24 | - /// per user by construction: starting is a single `UPSERT` on this id | 22 | + /// segment — reads as the nil id, which matches no row: exactly the 404 a |
| 25 | - /// (atomic — a restart replaces the row in place), and finishing | 23 | + /// dangling record key produced under the old store, without turning a |
| 26 | - /// atomically takes the row and re-files it under a ULID id. `open_` | 24 | + /// typo into a panic. |
| 27 | - /// cannot collide with a ULID key (ULIDs are bare alphanumerics). | 25 | + pub fn from_key(key: &str) -> Self { |
| 28 | - pub fn open_for(user: &UserId) -> Self { | 26 | + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) |
| 29 | - Self(RecordId::new( | ||
| 30 | - POMODORO_SESSION_TABLE, | ||
| 31 | - format!("open_{}", user.key()), | ||
| 32 | - )) | ||
| 33 | } | 27 | } |
| 34 | 28 | ||
| 35 | - pub fn record(&self) -> RecordId { | 29 | + /// The hyphenated wire form. |
| 36 | - self.0.clone() | 30 | + pub fn key(&self) -> String { |
| 37 | - } | 31 | + self.0.to_string() |
| 38 | - | ||
| 39 | - pub fn key(&self) -> &str { | ||
| 40 | - match &self.0.key { | ||
| 41 | - RecordIdKey::String(key) => key, | ||
| 42 | - _ => "", | ||
| 43 | - } | ||
| 44 | } | 32 | } |
| 45 | } | 33 | } |
| 46 | 34 | ||
| @@ -49,18 +37,27 @@ impl PomodoroSessionId { | |||
| 49 | /// client can never supply its own instants, so the recorded focus time is | 37 | /// client can never supply its own instants, so the recorded focus time is |
| 50 | /// honest. Breaks are not stored; the frontend owns the work/break rhythm and | 38 | /// honest. Breaks are not stored; the frontend owns the work/break rhythm and |
| 51 | /// the backend records only the focus stint. | 39 | /// the backend records only the focus stint. |
| 52 | -#[derive(Debug, Clone, SurrealValue)] | 40 | +/// |
| 41 | +/// "At most one running session per student" is no longer carried by a | ||
| 42 | +/// deterministic key: it is a partial unique index on the table | ||
| 43 | +/// (`pomodoro_session_open_stint`) over rows whose `finished_at` is NULL, so | ||
| 44 | +/// the database itself refuses (or restarts) a second running stint. | ||
| 45 | +#[derive(Debug, Clone, sqlx::FromRow)] | ||
| 53 | pub struct PomodoroSession { | 46 | pub struct PomodoroSession { |
| 54 | - id: PomodoroSessionId, | 47 | + pub(crate) id: PomodoroSessionId, |
| 55 | - user: UserId, | 48 | + #[sqlx(rename = "app_user")] |
| 56 | - started_at: Timestamp, | 49 | + pub(crate) user: UserId, |
| 57 | - finished_at: Option<Timestamp>, | 50 | + pub(crate) started_at: Timestamp, |
| 58 | - /// The student's own name for what this stint is for ("math", "TYT | 51 | + pub(crate) finished_at: Option<Timestamp>, |
| 52 | + /// The verdict `finish` reached for this stint, stamped at close so a later | ||
| 53 | + /// reader never re-derives it against thresholds that have since moved. | ||
| 54 | + /// `NULL`: a running stint has no verdict yet, and a stint closed | ||
| 55 | + /// before the rule existed carries none and cannot honestly be given one. | ||
| 56 | + pub(crate) counted: Option<bool>, | ||
| 57 | + /// The student's own name for what the stint is for ("math", "TYT | ||
| 59 | /// denemesi") — free text given at start, not a subject reference. | 58 | /// denemesi") — free text given at start, not a subject reference. |
| 60 | - /// `None` on an unnamed stint and on any row from before the field | 59 | + /// `NULL` on an unnamed stint. |
| 61 | - /// existed, which reads exactly like an unnamed one. | 60 | + pub(crate) label: Option<String>, |
| 62 | - label: Option<String>, | ||
| 63 | - counted: Option<bool>, | ||
| 64 | } | 61 | } |
| 65 | 62 | ||
| 66 | impl PomodoroSession { | 63 | impl PomodoroSession { |
| @@ -89,7 +86,7 @@ impl PomodoroSession { | |||
| 89 | } | 86 | } |
| 90 | 87 | ||
| 91 | /// What the student called this stint when they started it. `None` when | 88 | /// What the student called this stint when they started it. `None` when |
| 92 | - /// they started it unnamed, and on rows that predate the field. | 89 | + /// they started it unnamed. |
| 93 | pub fn get_label(&self) -> Option<&str> { | 90 | pub fn get_label(&self) -> Option<&str> { |
| 94 | self.label.as_deref() | 91 | self.label.as_deref() |
| 95 | } | 92 | } |
src/domain/pool_question.rsmodified+26 -24
| @@ -7,52 +7,53 @@ | |||
| 7 | //! question's solutions with it. An optional photo of the problem rides on | 7 | //! question's solutions with it. An optional photo of the problem rides on |
| 8 | //! the row as metadata (`image_*`); the bytes live on disk under | 8 | //! the row as metadata (`image_*`); the bytes live on disk under |
| 9 | //! [`crate::config::Config::files_path`] in a file named by `image_file` — a | 9 | //! [`crate::config::Config::files_path`] in a file named by `image_file` — a |
| 10 | -//! fresh server-generated ULID per upload. The web layer owns the blob I/O; | 10 | +//! fresh server-generated id per upload. The web layer owns the blob I/O; |
| 11 | //! the queries live in [`crate::db::pool_question`], the workflows in | 11 | //! the queries live in [`crate::db::pool_question`], the workflows in |
| 12 | //! [`crate::service::pool_question`]. | 12 | //! [`crate::service::pool_question`]. |
| 13 | 13 | ||
| 14 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 14 | +use uuid::Uuid; |
| 15 | 15 | ||
| 16 | use crate::constant::{ | 16 | use crate::constant::{ |
| 17 | - MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN, POOL_QUESTION_TABLE, STATUS_APPROVED, | 17 | + MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN, STATUS_APPROVED, STATUS_PENDING, |
| 18 | - STATUS_PENDING, | ||
| 19 | }; | 18 | }; |
| 20 | -use crate::domain::monotonic_id::next_ulid; | 19 | +use crate::domain::monotonic_id::next_uuid; |
| 21 | use crate::domain::note_file::FileContentType; | 20 | use crate::domain::note_file::FileContentType; |
| 22 | use crate::domain::timestamp::Timestamp; | 21 | use crate::domain::timestamp::Timestamp; |
| 23 | use crate::domain::user::UserId; | 22 | use crate::domain::user::UserId; |
| 24 | use crate::error::ValidationError; | 23 | use crate::error::ValidationError; |
| 25 | use crate::validate::validate_required; | 24 | use crate::validate::validate_required; |
| 26 | 25 | ||
| 27 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 26 | +/// Typed pool-question row id. A UUIDv7 minted by the process-wide monotonic |
| 28 | -pub struct PoolQuestionId(RecordId); | 27 | +/// generator, so `id` order is mint order. |
| 28 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] | ||
| 29 | +#[sqlx(transparent)] | ||
| 30 | +pub struct PoolQuestionId(Uuid); | ||
| 29 | 31 | ||
| 30 | impl PoolQuestionId { | 32 | impl PoolQuestionId { |
| 31 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 33 | + /// Minted from the process-wide monotonic generator, not a random v4: |
| 32 | /// the pool sorts `asked_at DESC, id DESC` and the id *is* the tie-break | 34 | /// the pool sorts `asked_at DESC, id DESC` and the id *is* the tie-break |
| 33 | /// ([`crate::db::pool_question::list_all`]), | 35 | /// ([`crate::db::pool_question::list_all`]), |
| 34 | /// and a random low half scrambles rows minted in the same millisecond. | 36 | /// and a random low half scrambles rows minted in the same millisecond. |
| 35 | pub fn generate() -> Self { | 37 | pub fn generate() -> Self { |
| 36 | - Self(RecordId::new(POOL_QUESTION_TABLE, next_ulid().to_string())) | 38 | + Self(next_uuid()) |
| 37 | } | 39 | } |
| 38 | 40 | ||
| 41 | + /// Parse a wire key. A key that parses as no UUID — a malformed path | ||
| 42 | + /// segment — reads as the nil id, which matches no row: exactly the 404 a | ||
| 43 | + /// dangling record key produced under the old store, without turning a | ||
| 44 | + /// typo into a panic. | ||
| 39 | pub fn from_key(key: &str) -> Self { | 45 | pub fn from_key(key: &str) -> Self { |
| 40 | - Self(RecordId::new(POOL_QUESTION_TABLE, key)) | 46 | + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) |
| 41 | } | 47 | } |
| 42 | 48 | ||
| 43 | - pub fn record(&self) -> RecordId { | 49 | + /// The hyphenated wire form. |
| 44 | - self.0.clone() | 50 | + pub fn key(&self) -> String { |
| 45 | - } | 51 | + self.0.to_string() |
| 46 | - | ||
| 47 | - pub fn key(&self) -> &str { | ||
| 48 | - match &self.0.key { | ||
| 49 | - RecordIdKey::String(key) => key, | ||
| 50 | - _ => "", | ||
| 51 | - } | ||
| 52 | } | 52 | } |
| 53 | } | 53 | } |
| 54 | 54 | ||
| 55 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 55 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 56 | +#[sqlx(transparent)] | ||
| 56 | pub struct PoolQuestionTitle(String); | 57 | pub struct PoolQuestionTitle(String); |
| 57 | 58 | ||
| 58 | impl PoolQuestionTitle { | 59 | impl PoolQuestionTitle { |
| @@ -66,7 +67,8 @@ impl PoolQuestionTitle { | |||
| 66 | } | 67 | } |
| 67 | } | 68 | } |
| 68 | 69 | ||
| 69 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 70 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 71 | +#[sqlx(transparent)] | ||
| 70 | pub struct PoolQuestionBody(String); | 72 | pub struct PoolQuestionBody(String); |
| 71 | 73 | ||
| 72 | impl PoolQuestionBody { | 74 | impl PoolQuestionBody { |
| @@ -80,7 +82,7 @@ impl PoolQuestionBody { | |||
| 80 | } | 82 | } |
| 81 | } | 83 | } |
| 82 | 84 | ||
| 83 | -#[derive(Debug, Clone, SurrealValue)] | 85 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 84 | pub struct PoolQuestion { | 86 | pub struct PoolQuestion { |
| 85 | pub(crate) id: PoolQuestionId, | 87 | pub(crate) id: PoolQuestionId, |
| 86 | pub(crate) asker: UserId, | 88 | pub(crate) asker: UserId, |
| @@ -89,8 +91,8 @@ pub struct PoolQuestion { | |||
| 89 | pub(crate) status: String, | 91 | pub(crate) status: String, |
| 90 | pub(crate) asked_at: Timestamp, | 92 | pub(crate) asked_at: Timestamp, |
| 91 | pub(crate) approved_by: Option<UserId>, | 93 | pub(crate) approved_by: Option<UserId>, |
| 92 | - /// The photo's on-disk blob name — a fresh ULID every upload; `None` when | 94 | + /// The photo's on-disk blob name — a fresh server-generated id every |
| 93 | - /// the question carries no image. | 95 | + /// upload; `None` when the question carries no image. |
| 94 | pub(crate) image_file: Option<String>, | 96 | pub(crate) image_file: Option<String>, |
| 95 | pub(crate) image_content_type: Option<FileContentType>, | 97 | pub(crate) image_content_type: Option<FileContentType>, |
| 96 | pub(crate) image_size: Option<i64>, | 98 | pub(crate) image_size: Option<i64>, |
src/domain/preferences.rsmodified+25 -24
| @@ -3,18 +3,17 @@ | |||
| 3 | //! and the frontend falls back to the device preference (`prefers-color-scheme`, | 3 | //! and the frontend falls back to the device preference (`prefers-color-scheme`, |
| 4 | //! browser language) or its own default accent. | 4 | //! browser language) or its own default accent. |
| 5 | 5 | ||
| 6 | -use surrealdb::types::SurrealValue; | 6 | +use sqlx::Type; |
| 7 | 7 | ||
| 8 | use crate::constant::{LANGUAGES, PALETTE_COLOR_LEN, THEMES}; | 8 | use crate::constant::{LANGUAGES, PALETTE_COLOR_LEN, THEMES}; |
| 9 | use crate::error::ValidationError; | 9 | use crate::error::ValidationError; |
| 10 | 10 | ||
| 11 | /// The frontend color scheme. | 11 | /// The frontend color scheme. |
| 12 | /// | 12 | /// |
| 13 | -/// `#[surreal(untagged, rename_all = "lowercase")]` stores each variant as a | 13 | +/// Each variant stores as a bare lowercase TEXT value (`"light"` / |
| 14 | -/// bare lowercase string (`"light"` / `"dark"`) — same encoding contract as | 14 | +/// `"dark"`) — same encoding contract as [`crate::domain::role::Role`]. |
| 15 | -/// [`crate::domain::role::Role`]. | 15 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] |
| 16 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | 16 | +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] |
| 17 | -#[surreal(untagged, rename_all = "lowercase")] | ||
| 18 | pub enum Theme { | 17 | pub enum Theme { |
| 19 | Light, | 18 | Light, |
| 20 | Dark, | 19 | Dark, |
| @@ -43,8 +42,8 @@ impl Theme { | |||
| 43 | 42 | ||
| 44 | /// The frontend interface language, as an ISO 639-1 code — the same values the | 43 | /// The frontend interface language, as an ISO 639-1 code — the same values the |
| 45 | /// frontend's locale switch uses (`"tr"` Turkish, `"en"` English). | 44 | /// frontend's locale switch uses (`"tr"` Turkish, `"en"` English). |
| 46 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | 45 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] |
| 47 | -#[surreal(untagged, rename_all = "lowercase")] | 46 | +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] |
| 48 | pub enum Language { | 47 | pub enum Language { |
| 49 | Tr, | 48 | Tr, |
| 50 | En, | 49 | En, |
| @@ -77,8 +76,9 @@ impl Language { | |||
| 77 | /// Unlike [`Theme`] and [`Language`] this is an **open** value set: any valid | 76 | /// Unlike [`Theme`] and [`Language`] this is an **open** value set: any valid |
| 78 | /// hex passes, so the frontend can grow its palette without a backend change. | 77 | /// hex passes, so the frontend can grow its palette without a backend change. |
| 79 | /// A plain newtype over `String`, which stores as a bare string — the same | 78 | /// A plain newtype over `String`, which stores as a bare string — the same |
| 80 | -/// `option<string>` column contract the two enums encode into. | 79 | +/// `TEXT NULL` column contract the two enums encode into. |
| 81 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 80 | +#[derive(Debug, Clone, PartialEq, Eq, Type)] |
| 81 | +#[sqlx(transparent)] | ||
| 82 | pub struct PaletteColor(String); | 82 | pub struct PaletteColor(String); |
| 83 | 83 | ||
| 84 | impl PaletteColor { | 84 | impl PaletteColor { |
| @@ -109,7 +109,6 @@ impl PaletteColor { | |||
| 109 | mod tests { | 109 | mod tests { |
| 110 | use super::*; | 110 | use super::*; |
| 111 | use crate::constant::PALETTE_COLOR_PATTERN; | 111 | use crate::constant::PALETTE_COLOR_PATTERN; |
| 112 | - use surrealdb::types::Value; | ||
| 113 | 112 | ||
| 114 | #[tokio::test] | 113 | #[tokio::test] |
| 115 | async fn theme_str_round_trips() { | 114 | async fn theme_str_round_trips() { |
| @@ -200,23 +199,25 @@ mod tests { | |||
| 200 | } | 199 | } |
| 201 | } | 200 | } |
| 202 | 201 | ||
| 203 | - #[tokio::test] | 202 | + #[test] |
| 204 | - async fn surreal_values_are_plain_strings() { | 203 | + fn sqlx_encodes_the_storage_form() { |
| 205 | - // `untagged` keeps the stored value a bare string so the `option<string>` | 204 | + // `rename_all` keeps the stored value the bare lowercase string the |
| 206 | - // columns accept it. Guard that the encoding never regresses. | 205 | + // TEXT columns carry; the palette color stores as the string it |
| 206 | + // validated to. Guard that the sqlx encoding never drifts. | ||
| 207 | + let mut buf = sqlx::postgres::PgArgumentBuffer::default(); | ||
| 207 | for theme in THEMES { | 208 | for theme in THEMES { |
| 208 | - let value = theme.into_value(); | 209 | + buf.clear(); |
| 209 | - assert_eq!(value, Value::String(theme.as_str().to_string())); | 210 | + sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&theme, &mut buf); |
| 210 | - assert_eq!(Theme::from_value(value).unwrap(), theme); | 211 | + assert_eq!(std::str::from_utf8(&buf).unwrap(), theme.as_str()); |
| 211 | } | 212 | } |
| 212 | for language in LANGUAGES { | 213 | for language in LANGUAGES { |
| 213 | - let value = language.into_value(); | 214 | + buf.clear(); |
| 214 | - assert_eq!(value, Value::String(language.as_str().to_string())); | 215 | + sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&language, &mut buf); |
| 215 | - assert_eq!(Language::from_value(value).unwrap(), language); | 216 | + assert_eq!(std::str::from_utf8(&buf).unwrap(), language.as_str()); |
| 216 | } | 217 | } |
| 217 | let color = PaletteColor::try_from_str("#fefae0").unwrap(); | 218 | let color = PaletteColor::try_from_str("#fefae0").unwrap(); |
| 218 | - let value = color.clone().into_value(); | 219 | + buf.clear(); |
| 219 | - assert_eq!(value, Value::String("#fefae0".to_string())); | 220 | + sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&color, &mut buf); |
| 220 | - assert_eq!(PaletteColor::from_value(value).unwrap(), color); | 221 | + assert_eq!(std::str::from_utf8(&buf).unwrap(), "#fefae0"); |
| 221 | } | 222 | } |
| 222 | } | 223 | } |
src/domain/profile.rsmodified+13 -9
| @@ -1,8 +1,6 @@ | |||
| 1 | //! Personal-info newtypes shared by every account role — student, teacher, | 1 | //! Personal-info newtypes shared by every account role — student, teacher, |
| 2 | //! manager, and admin records all carry the same optional contact fields. | 2 | //! manager, and admin records all carry the same optional contact fields. |
| 3 | 3 | ||
| 4 | -use surrealdb::types::SurrealValue; | ||
| 5 | - | ||
| 6 | use crate::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN, MAX_NAME_LEN}; | 4 | use crate::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN, MAX_NAME_LEN}; |
| 7 | use crate::domain::badge::BadgeStats; | 5 | use crate::domain::badge::BadgeStats; |
| 8 | use crate::domain::timestamp::Timestamp; | 6 | use crate::domain::timestamp::Timestamp; |
| @@ -12,7 +10,8 @@ use crate::validate::{validate_email, validate_optional, validate_phone, validat | |||
| 12 | /// A person's given or family name. One type serves both fields — the `field` | 10 | /// A person's given or family name. One type serves both fields — the `field` |
| 13 | /// tag only steers the error message ("name …" vs "surname …"). Stored trimmed; | 11 | /// tag only steers the error message ("name …" vs "surname …"). Stored trimmed; |
| 14 | /// unicode is welcome (names are not ASCII). | 12 | /// unicode is welcome (names are not ASCII). |
| 15 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 13 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 14 | +#[sqlx(transparent)] | ||
| 16 | pub struct PersonName(String); | 15 | pub struct PersonName(String); |
| 17 | 16 | ||
| 18 | impl PersonName { | 17 | impl PersonName { |
| @@ -27,7 +26,8 @@ impl PersonName { | |||
| 27 | } | 26 | } |
| 28 | 27 | ||
| 29 | /// A plausibly-shaped email address (see [`validate_email`]). Stored trimmed. | 28 | /// A plausibly-shaped email address (see [`validate_email`]). Stored trimmed. |
| 30 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 29 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 30 | +#[sqlx(transparent)] | ||
| 31 | pub struct Email(String); | 31 | pub struct Email(String); |
| 32 | 32 | ||
| 33 | impl Email { | 33 | impl Email { |
| @@ -43,7 +43,8 @@ impl Email { | |||
| 43 | 43 | ||
| 44 | /// A phone number: optional leading `+`, 7–15 digits, cosmetic separators | 44 | /// A phone number: optional leading `+`, 7–15 digits, cosmetic separators |
| 45 | /// allowed (see [`validate_phone`]). Stored trimmed, separators kept as given. | 45 | /// allowed (see [`validate_phone`]). Stored trimmed, separators kept as given. |
| 46 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 46 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 47 | +#[sqlx(transparent)] | ||
| 47 | pub struct Phone(String); | 48 | pub struct Phone(String); |
| 48 | 49 | ||
| 49 | impl Phone { | 50 | impl Phone { |
| @@ -65,7 +66,8 @@ impl Phone { | |||
| 65 | /// UTC+14) legitimately submits a date the server's UTC calendar hasn't | 66 | /// UTC+14) legitimately submits a date the server's UTC calendar hasn't |
| 66 | /// reached yet. Without the grace, "born today" entered from Istanbul or | 67 | /// reached yet. Without the grace, "born today" entered from Istanbul or |
| 67 | /// Auckland shortly after local midnight is wrongly rejected. | 68 | /// Auckland shortly after local midnight is wrongly rejected. |
| 68 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 69 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 70 | +#[sqlx(transparent)] | ||
| 69 | pub struct BirthDate(String); | 71 | pub struct BirthDate(String); |
| 70 | 72 | ||
| 71 | impl BirthDate { | 73 | impl BirthDate { |
| @@ -96,7 +98,8 @@ impl BirthDate { | |||
| 96 | /// The name a profile shows instead of the legal one — a nickname, a shortened | 98 | /// The name a profile shows instead of the legal one — a nickname, a shortened |
| 97 | /// form, whatever the person answers to. Stored trimmed; unicode is welcome, | 99 | /// form, whatever the person answers to. Stored trimmed; unicode is welcome, |
| 98 | /// same as [`PersonName`] and unlike the ASCII-only username. | 100 | /// same as [`PersonName`] and unlike the ASCII-only username. |
| 99 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 101 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 102 | +#[sqlx(transparent)] | ||
| 100 | pub struct DisplayName(String); | 103 | pub struct DisplayName(String); |
| 101 | 104 | ||
| 102 | impl DisplayName { | 105 | impl DisplayName { |
| @@ -113,7 +116,8 @@ impl DisplayName { | |||
| 113 | /// A short self-description on the public profile. Free text within | 116 | /// A short self-description on the public profile. Free text within |
| 114 | /// [`MAX_BIO_LEN`], blank allowed — an empty bio is a written-then-erased one, | 117 | /// [`MAX_BIO_LEN`], blank allowed — an empty bio is a written-then-erased one, |
| 115 | /// which is a legitimate state and not an error. Stored trimmed. | 118 | /// which is a legitimate state and not an error. Stored trimmed. |
| 116 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 119 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 120 | +#[sqlx(transparent)] | ||
| 117 | pub struct Bio(String); | 121 | pub struct Bio(String); |
| 118 | 122 | ||
| 119 | impl Bio { | 123 | impl Bio { |
| @@ -136,7 +140,7 @@ impl Bio { | |||
| 136 | /// One named struct on purpose: the auto-earned badge rules take a whole | 140 | /// One named struct on purpose: the auto-earned badge rules take a whole |
| 137 | /// `ProfileStats` as their sole input, so a counter added here reaches them | 141 | /// `ProfileStats` as their sole input, so a counter added here reaches them |
| 138 | /// without touching a signature. | 142 | /// without touching a signature. |
| 139 | -#[derive(Debug, Clone, SurrealValue)] | 143 | +#[derive(Debug, Clone)] |
| 140 | pub struct ProfileStats { | 144 | pub struct ProfileStats { |
| 141 | pub(crate) pomodoro_sessions: i64, | 145 | pub(crate) pomodoro_sessions: i64, |
| 142 | pub(crate) pomodoro_focus_ms: i64, | 146 | pub(crate) pomodoro_focus_ms: i64, |
src/domain/question_image.rsmodified+62 -37
| @@ -1,58 +1,66 @@ | |||
| 1 | //! An image pinned to an exam question — the question's own illustration | 1 | //! An image pinned to an exam question — the question's own illustration |
| 2 | -//! (`slot = NONE`, any kind: a map above the prompt) or one choice's picture | 2 | +//! (`slot = NULL`, any kind: a map above the prompt) or one choice's picture |
| 3 | -//! (`slot` = that choice's stable id, choice questions only). The row carries metadata; the bytes | 3 | +//! (`slot` = that choice's stable id, choice questions only). The row carries |
| 4 | -//! live on disk under [`crate::config::Config::files_path`] in a file named by | 4 | +//! metadata; the bytes live on disk under |
| 5 | -//! `file` — a fresh server-generated ULID per upload, so no user input ever | 5 | +//! [`crate::config::Config::files_path`] in a file named by `file` — a fresh |
| 6 | -//! shapes a disk path and a replace never overwrites bytes in place. The row | 6 | +//! server-generated id per upload, so no user input ever shapes a disk path |
| 7 | -//! id is *deterministic* per (question, slot), so "one image per slot" holds | 7 | +//! and a replace never overwrites bytes in place. The row's identity is the |
| 8 | -//! by construction and a replace is a plain UPSERT. The queries and | 8 | +//! natural pair of its question and slot — "one image per slot" holds by |
| 9 | -//! transactions over these rows live in [`crate::db::question_image`]; the web | 9 | +//! construction and a replace is a plain upsert. The queries and |
| 10 | -//! layer owns the blob I/O and its ordering (new blob before row, row before | 10 | +//! transactions over these rows live in [`crate::db::question_image`]; the |
| 11 | -//! old blob). | 11 | +//! web layer owns the blob I/O and its ordering (new blob before row, row |
| 12 | +//! before old blob). | ||
| 12 | 13 | ||
| 13 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 14 | -use ulid::Ulid; | ||
| 15 | - | ||
| 16 | -use crate::constant::QUESTION_IMAGE_TABLE; | ||
| 17 | use crate::domain::exam::ExamId; | 14 | use crate::domain::exam::ExamId; |
| 18 | use crate::domain::exam_question::{ChoiceId, ExamQuestionId}; | 15 | use crate::domain::exam_question::{ChoiceId, ExamQuestionId}; |
| 19 | -use crate::domain::key; | 16 | +use crate::domain::monotonic_id::next_uuid; |
| 20 | use crate::domain::note_file::FileContentType; | 17 | use crate::domain::note_file::FileContentType; |
| 21 | 18 | ||
| 22 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 19 | +/// The (question, slot) pair — the table's natural unique identity. The same |
| 23 | -pub struct QuestionImageId(RecordId); | 20 | +/// trick as the exam id types' composite keys: the slot sentinel `"q"` keeps |
| 21 | +/// the illustration apart from every choice's picture, and a choice's stable | ||
| 22 | +/// id can never be `"q"`, so the two shapes can never collide. | ||
| 23 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 24 | +pub struct QuestionImageId { | ||
| 25 | + question: ExamQuestionId, | ||
| 26 | + slot: Option<ChoiceId>, | ||
| 27 | +} | ||
| 24 | 28 | ||
| 25 | impl QuestionImageId { | 29 | impl QuestionImageId { |
| 26 | - /// The one id a (question, slot) pair can have — see [`key::slot`] for the | 30 | + /// The one identity a (question, slot) pair can have — see |
| 27 | - /// key shape and why the two forms can never collide. | 31 | + /// [`crate::domain::key::slot`] for the key shape and why the two forms |
| 32 | + /// can never collide. | ||
| 28 | pub fn for_slot(question: &ExamQuestionId, slot: Option<&ChoiceId>) -> Self { | 33 | pub fn for_slot(question: &ExamQuestionId, slot: Option<&ChoiceId>) -> Self { |
| 29 | - Self(RecordId::new( | 34 | + Self { |
| 30 | - QUESTION_IMAGE_TABLE, | 35 | + question: question.clone(), |
| 31 | - key::slot(question.key(), slot.map(|id| id.as_str())), | 36 | + slot: slot.cloned(), |
| 32 | - )) | 37 | + } |
| 33 | } | 38 | } |
| 34 | 39 | ||
| 35 | - pub fn record(&self) -> RecordId { | 40 | + /// The wire form, `None` spelled with the `"q"` sentinel — the same |
| 36 | - self.0.clone() | 41 | + /// spelling the stored key uses. |
| 42 | + pub fn key(&self) -> String { | ||
| 43 | + crate::domain::key::slot(&self.question.key(), self.slot.as_ref().map(|id| id.as_str())) | ||
| 37 | } | 44 | } |
| 38 | 45 | ||
| 39 | - pub fn key(&self) -> &str { | 46 | + pub fn question(&self) -> &ExamQuestionId { |
| 40 | - match &self.0.key { | 47 | + &self.question |
| 41 | - RecordIdKey::String(key) => key, | 48 | + } |
| 42 | - _ => "", | 49 | + |
| 43 | - } | 50 | + pub fn slot(&self) -> Option<&ChoiceId> { |
| 51 | + self.slot.as_ref() | ||
| 44 | } | 52 | } |
| 45 | } | 53 | } |
| 46 | 54 | ||
| 47 | -#[derive(Debug, Clone, SurrealValue)] | 55 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 48 | pub struct QuestionImage { | 56 | pub struct QuestionImage { |
| 49 | - pub(crate) id: QuestionImageId, | ||
| 50 | pub(crate) exam: ExamId, | 57 | pub(crate) exam: ExamId, |
| 51 | pub(crate) question: ExamQuestionId, | 58 | pub(crate) question: ExamQuestionId, |
| 52 | - /// `NONE` = the question's illustration; otherwise the id of the option | 59 | + /// `NULL` = the question's illustration; otherwise the id of the option |
| 53 | - /// this picture belongs to. | 60 | + /// this picture belongs to. Together with `question` this is the row's |
| 61 | + /// `UNIQUE NULLS NOT DISTINCT` identity. | ||
| 54 | pub(crate) slot: Option<ChoiceId>, | 62 | pub(crate) slot: Option<ChoiceId>, |
| 55 | - /// The blob's on-disk name — a fresh ULID every upload. | 63 | + /// The blob's on-disk name — a fresh server-generated id every upload. |
| 56 | pub(crate) file: String, | 64 | pub(crate) file: String, |
| 57 | pub(crate) content_type: FileContentType, | 65 | pub(crate) content_type: FileContentType, |
| 58 | pub(crate) size: i64, | 66 | pub(crate) size: i64, |
| @@ -71,11 +79,10 @@ impl QuestionImage { | |||
| 71 | size: i64, | 79 | size: i64, |
| 72 | ) -> Self { | 80 | ) -> Self { |
| 73 | Self { | 81 | Self { |
| 74 | - id: QuestionImageId::for_slot(question, slot), | ||
| 75 | exam: exam.clone(), | 82 | exam: exam.clone(), |
| 76 | question: question.clone(), | 83 | question: question.clone(), |
| 77 | slot: slot.cloned(), | 84 | slot: slot.cloned(), |
| 78 | - file: Ulid::generate().to_string(), | 85 | + file: next_uuid().to_string(), |
| 79 | content_type, | 86 | content_type, |
| 80 | size, | 87 | size, |
| 81 | } | 88 | } |
| @@ -101,3 +108,21 @@ impl QuestionImage { | |||
| 101 | self.size | 108 | self.size |
| 102 | } | 109 | } |
| 103 | } | 110 | } |
| 111 | + | ||
| 112 | +#[cfg(test)] | ||
| 113 | +mod tests { | ||
| 114 | + use super::*; | ||
| 115 | + | ||
| 116 | + /// The illustration (`None`) and a choice picture key apart — the `"q"` | ||
| 117 | + /// sentinel can never be a choice's id. | ||
| 118 | + #[test] | ||
| 119 | + fn the_illustration_and_a_choice_never_collide() { | ||
| 120 | + let question = ExamQuestionId::from_key("018f1a00-0000-7000-8000-000000000001"); | ||
| 121 | + let illustration = QuestionImageId::for_slot(&question, None); | ||
| 122 | + assert_eq!( | ||
| 123 | + illustration.key(), | ||
| 124 | + format!("{}_q", question.key()), | ||
| 125 | + "the sentinel spelling is the stored key's spelling" | ||
| 126 | + ); | ||
| 127 | + } | ||
| 128 | +} | ||
src/domain/rag_output.rsmodified+25 -23
| @@ -14,43 +14,44 @@ | |||
| 14 | //! connected. Persistence lives in [`crate::db::rag_output`]. | 14 | //! connected. Persistence lives in [`crate::db::rag_output`]. |
| 15 | 15 | ||
| 16 | use serde_json::Value; | 16 | use serde_json::Value; |
| 17 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 17 | +use sqlx::types::Json; |
| 18 | +use uuid::Uuid; | ||
| 18 | 19 | ||
| 19 | -use crate::constant::RAG_OUTPUT_TABLE; | ||
| 20 | use crate::domain::course::CourseId; | 20 | use crate::domain::course::CourseId; |
| 21 | use crate::domain::course_note::CourseNoteId; | 21 | use crate::domain::course_note::CourseNoteId; |
| 22 | use crate::domain::course_note_file::CourseNoteFileId; | 22 | use crate::domain::course_note_file::CourseNoteFileId; |
| 23 | -use crate::domain::monotonic_id::next_ulid; | 23 | +use crate::domain::monotonic_id::next_uuid; |
| 24 | use crate::domain::timestamp::Timestamp; | 24 | use crate::domain::timestamp::Timestamp; |
| 25 | 25 | ||
| 26 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 26 | +/// Typed rag-output row id. A UUIDv7 minted by the process-wide monotonic |
| 27 | -pub struct RagOutputId(RecordId); | 27 | +/// generator, so `id` order is mint order. |
| 28 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] | ||
| 29 | +#[sqlx(transparent)] | ||
| 30 | +pub struct RagOutputId(Uuid); | ||
| 28 | 31 | ||
| 29 | impl RagOutputId { | 32 | impl RagOutputId { |
| 30 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 33 | + /// Minted from the process-wide monotonic generator, not a random v4: |
| 31 | /// a note's outputs list `id DESC` (newest first, | 34 | /// a note's outputs list `id DESC` (newest first, |
| 32 | /// [`list_for`](crate::db::rag_output::list_for)). | 35 | /// [`list_for`](crate::db::rag_output::list_for)). |
| 33 | pub fn generate() -> Self { | 36 | pub fn generate() -> Self { |
| 34 | - Self(RecordId::new(RAG_OUTPUT_TABLE, next_ulid().to_string())) | 37 | + Self(next_uuid()) |
| 35 | } | 38 | } |
| 36 | 39 | ||
| 40 | + /// Parse a wire key. A key that parses as no UUID — a malformed path | ||
| 41 | + /// segment — reads as the nil id, which matches no row: exactly the 404 a | ||
| 42 | + /// dangling record key produced under the old store, without turning a | ||
| 43 | + /// typo into a panic. | ||
| 37 | pub fn from_key(key: &str) -> Self { | 44 | pub fn from_key(key: &str) -> Self { |
| 38 | - Self(RecordId::new(RAG_OUTPUT_TABLE, key)) | 45 | + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) |
| 39 | } | 46 | } |
| 40 | 47 | ||
| 41 | - pub fn record(&self) -> RecordId { | 48 | + /// The hyphenated wire form. |
| 42 | - self.0.clone() | 49 | + pub fn key(&self) -> String { |
| 43 | - } | 50 | + self.0.to_string() |
| 44 | - | ||
| 45 | - pub fn key(&self) -> &str { | ||
| 46 | - match &self.0.key { | ||
| 47 | - RecordIdKey::String(key) => key, | ||
| 48 | - _ => "", | ||
| 49 | - } | ||
| 50 | } | 51 | } |
| 51 | } | 52 | } |
| 52 | 53 | ||
| 53 | -#[derive(Debug, Clone, SurrealValue)] | 54 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 54 | pub struct RagOutput { | 55 | pub struct RagOutput { |
| 55 | pub(crate) id: RagOutputId, | 56 | pub(crate) id: RagOutputId, |
| 56 | pub(crate) course_note: CourseNoteId, | 57 | pub(crate) course_note: CourseNoteId, |
| @@ -61,10 +62,11 @@ pub struct RagOutput { | |||
| 61 | /// ([`delete_with_source`](crate::db::rag_output::delete_with_source)) | 62 | /// ([`delete_with_source`](crate::db::rag_output::delete_with_source)) |
| 62 | /// rather than leaving an output citing a file that no longer exists. | 63 | /// rather than leaving an output citing a file that no longer exists. |
| 63 | pub(crate) sources: Vec<CourseNoteFileId>, | 64 | pub(crate) sources: Vec<CourseNoteFileId>, |
| 64 | - /// The service's answer, stored verbatim. Opaque to the backend — it is a | 65 | + /// The service's answer, stored verbatim in a JSONB column. Opaque to the |
| 65 | - /// service-owned shape, so this side neither validates nor interprets it, | 66 | + /// backend — it is a service-owned shape, so this side neither validates |
| 66 | - /// beyond it having to be a JSON **object** (the stored column is one). | 67 | + /// nor interprets it, beyond it having to be a JSON **object** (the |
| 67 | - pub(crate) payload: Value, | 68 | + /// stored column is one). |
| 69 | + pub(crate) payload: Json<Value>, | ||
| 68 | pub(crate) generated_at: Timestamp, | 70 | pub(crate) generated_at: Timestamp, |
| 69 | } | 71 | } |
| 70 | 72 | ||
| @@ -86,7 +88,7 @@ impl RagOutput { | |||
| 86 | } | 88 | } |
| 87 | 89 | ||
| 88 | pub fn get_payload(&self) -> &Value { | 90 | pub fn get_payload(&self) -> &Value { |
| 89 | - &self.payload | 91 | + &self.payload.0 |
| 90 | } | 92 | } |
| 91 | 93 | ||
| 92 | pub fn get_generated_at(&self) -> Timestamp { | 94 | pub fn get_generated_at(&self) -> Timestamp { |
src/domain/registration.rsmodified+38 -27
| @@ -1,33 +1,48 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | - | ||
| 3 | -use crate::constant::REGISTRATION_TABLE; | ||
| 4 | use crate::domain::event::EventId; | 1 | use crate::domain::event::EventId; |
| 5 | use crate::domain::user::UserId; | 2 | use crate::domain::user::UserId; |
| 6 | 3 | ||
| 7 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 4 | +/// The (event, user) pair — the table's natural composite primary key. The |
| 8 | -pub struct RegistrationId(RecordId); | 5 | +/// same pair always maps to the same row, so one-row-per-pair holds by |
| 6 | +/// construction (the enrollment trick) even if a write ever slipped past the | ||
| 7 | +/// register lock. UUID strings carry only `-`, so `_` is an unambiguous | ||
| 8 | +/// joiner. | ||
| 9 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 10 | +pub struct RegistrationId { | ||
| 11 | + event: EventId, | ||
| 12 | + user: UserId, | ||
| 13 | +} | ||
| 9 | 14 | ||
| 10 | impl RegistrationId { | 15 | impl RegistrationId { |
| 11 | - /// A deterministic id for the (event, user) pair — the same pair always | ||
| 12 | - /// maps to the same record id, so one-row-per-pair holds by construction | ||
| 13 | - /// (the enrollment trick) even if a write ever slipped past the register | ||
| 14 | - /// lock. ULID keys are alphanumeric, so `_` is unambiguous. | ||
| 15 | pub fn composite(event: &EventId, user: &UserId) -> Self { | 16 | pub fn composite(event: &EventId, user: &UserId) -> Self { |
| 16 | - Self(RecordId::new( | 17 | + Self { |
| 17 | - REGISTRATION_TABLE, | 18 | + event: *event, |
| 18 | - format!("{}_{}", event.key(), user.key()), | 19 | + user: *user, |
| 19 | - )) | 20 | + } |
| 20 | } | 21 | } |
| 21 | 22 | ||
| 22 | - pub fn record(&self) -> RecordId { | 23 | + /// Parse the `{event}_{user}` wire form. A key that parses as no pair |
| 23 | - self.0.clone() | 24 | + /// reads as the nil pair, which matches no row — exactly the 404 a |
| 25 | + /// dangling composite key produced under the old store, without turning a | ||
| 26 | + /// typo into a panic. | ||
| 27 | + pub fn from_key(key: &str) -> Self { | ||
| 28 | + let (event, user) = key.rsplit_once('_').unwrap_or(("", "")); | ||
| 29 | + Self { | ||
| 30 | + event: EventId::from_key(event), | ||
| 31 | + user: UserId::from_key(user), | ||
| 32 | + } | ||
| 24 | } | 33 | } |
| 25 | 34 | ||
| 26 | - pub fn key(&self) -> &str { | 35 | + /// The `{event}_{user}` wire form. |
| 27 | - match &self.0.key { | 36 | + pub fn key(&self) -> String { |
| 28 | - RecordIdKey::String(key) => key, | 37 | + format!("{}_{}", self.event.key(), self.user.key()) |
| 29 | - _ => "", | 38 | + } |
| 30 | - } | 39 | + |
| 40 | + pub fn event(&self) -> EventId { | ||
| 41 | + self.event | ||
| 42 | + } | ||
| 43 | + | ||
| 44 | + pub fn user(&self) -> UserId { | ||
| 45 | + self.user | ||
| 31 | } | 46 | } |
| 32 | } | 47 | } |
| 33 | 48 | ||
| @@ -35,19 +50,15 @@ impl RegistrationId { | |||
| 35 | /// event's roster: whoever holds a row is expected (and markable), everyone | 50 | /// event's roster: whoever holds a row is expected (and markable), everyone |
| 36 | /// else is not. Rows survive audience changes inertly — switching the event | 51 | /// else is not. Rows survive audience changes inertly — switching the event |
| 37 | /// away from the registration kind hides them without deleting them. | 52 | /// away from the registration kind hides them without deleting them. |
| 38 | -#[derive(Debug, Clone, SurrealValue)] | 53 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 39 | pub struct Registration { | 54 | pub struct Registration { |
| 40 | - pub(crate) id: RegistrationId, | ||
| 41 | pub(crate) event: EventId, | 55 | pub(crate) event: EventId, |
| 56 | + #[sqlx(rename = "app_user")] | ||
| 42 | pub(crate) user: UserId, | 57 | pub(crate) user: UserId, |
| 43 | pub(crate) registered_by: UserId, | 58 | pub(crate) registered_by: UserId, |
| 44 | } | 59 | } |
| 45 | 60 | ||
| 46 | impl Registration { | 61 | impl Registration { |
| 47 | - pub fn get_id(&self) -> &RegistrationId { | ||
| 48 | - &self.id | ||
| 49 | - } | ||
| 50 | - | ||
| 51 | pub fn get_event(&self) -> &EventId { | 62 | pub fn get_event(&self) -> &EventId { |
| 52 | &self.event | 63 | &self.event |
| 53 | } | 64 | } |
| @@ -65,7 +76,7 @@ impl Registration { | |||
| 65 | // arm of [`crate::service::user::set_role`], so the seat comes back in | 76 | // arm of [`crate::service::user::set_role`], so the seat comes back in |
| 66 | // the same transaction as the role that invalidated it. The freeze it obeys | 77 | // the same transaction as the role that invalidated it. The freeze it obeys |
| 67 | // is [`crate::domain::event::Event::registration_capacity`]'s `Conflict` | 78 | // is [`crate::domain::event::Event::registration_capacity`]'s `Conflict` |
| 68 | - // arm, re-spelled for SurrealQL as | 79 | + // arm, re-spelled for the stored guard in |
| 69 | // [`crate::constant::REGISTRATION_FROZEN_GUARD`] and held to it by | 80 | // [`crate::constant::REGISTRATION_FROZEN_GUARD`] and held to it by |
| 70 | // `event::tests::the_sql_freeze_guard_matches_the_rust_one`. | 81 | // `event::tests::the_sql_freeze_guard_matches_the_rust_one`. |
| 71 | } | 82 | } |
src/domain/role.rsmodified+19 -16
| @@ -1,4 +1,4 @@ | |||
| 1 | -use surrealdb::types::SurrealValue; | 1 | +use sqlx::Type; |
| 2 | 2 | ||
| 3 | use crate::constant::ROLES; | 3 | use crate::constant::ROLES; |
| 4 | use crate::error::ValidationError; | 4 | use crate::error::ValidationError; |
| @@ -20,12 +20,12 @@ use crate::error::ValidationError; | |||
| 20 | /// exact `== Student` gate, so parents can't sit exams, enroll, or be marked on | 20 | /// exact `== Student` gate, so parents can't sit exams, enroll, or be marked on |
| 21 | /// a roll call — they only read their own students' reports. | 21 | /// a roll call — they only read their own students' reports. |
| 22 | /// | 22 | /// |
| 23 | -/// `#[surreal(untagged, rename_all = "lowercase")]` makes each variant serialize | 23 | +/// [`Role`] derives [`sqlx::Type`] as a bare TEXT enum: each variant stores as |
| 24 | -/// to a bare lowercase string (`"student"`, `"teacher"`, …) instead of the | 24 | +/// its lowercase name (`"student"`, `"teacher"`, …) and round-trips straight |
| 25 | -/// default object-wrapped form, so it stores in the `role` column's `TYPE string` | 25 | +/// back, which the `role` column's `CHECK` lists and every `role = 'teacher'` |
| 26 | -/// and round-trips straight back into the enum. | 26 | +/// filter spells. [`Role::as_str`] must stay in lockstep with it. |
| 27 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, SurrealValue)] | 27 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Type)] |
| 28 | -#[surreal(untagged, rename_all = "lowercase")] | 28 | +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] |
| 29 | pub enum Role { | 29 | pub enum Role { |
| 30 | Ai, | 30 | Ai, |
| 31 | Parent, | 31 | Parent, |
| @@ -92,7 +92,6 @@ impl Role { | |||
| 92 | #[cfg(test)] | 92 | #[cfg(test)] |
| 93 | mod tests { | 93 | mod tests { |
| 94 | use super::*; | 94 | use super::*; |
| 95 | - use surrealdb::types::Value; | ||
| 96 | 95 | ||
| 97 | #[tokio::test] | 96 | #[tokio::test] |
| 98 | async fn hierarchy_orders_low_to_high() { | 97 | async fn hierarchy_orders_low_to_high() { |
| @@ -167,14 +166,18 @@ mod tests { | |||
| 167 | assert!(Role::try_from_str("").is_err()); | 166 | assert!(Role::try_from_str("").is_err()); |
| 168 | } | 167 | } |
| 169 | 168 | ||
| 170 | - #[tokio::test] | 169 | + #[test] |
| 171 | - async fn surreal_value_is_a_plain_string() { | 170 | + fn sqlx_encodes_the_storage_form() { |
| 172 | - // The whole point of `untagged`: the stored value is a bare string, so a | 171 | + // The whole point of the TEXT encoding: the stored value is the bare |
| 173 | - // `TYPE string` column accepts it. Guard that the encoding never regresses. | 172 | + // lowercase string, so the `role` column accepts it and every |
| 174 | - for role in ROLES { | 173 | + // `role = 'teacher'` filter matches. Guard that the sqlx encoding |
| 175 | - let value = role.into_value(); | 174 | + // never drifts from `as_str` — the CHECK constraint and the filters |
| 176 | - assert_eq!(value, Value::String(role.as_str().to_string())); | 175 | + // spell these same words. |
| 177 | - assert_eq!(Role::from_value(value).unwrap(), role); | 176 | + let mut buf = sqlx::postgres::PgArgumentBuffer::default(); |
| 177 | + for role in [Role::Ai, Role::Parent, Role::Student, Role::Teacher, Role::Manager, Role::Admin] { | ||
| 178 | + buf.clear(); | ||
| 179 | + sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&role, &mut buf); | ||
| 180 | + assert_eq!(std::str::from_utf8(&buf).unwrap(), role.as_str()); | ||
| 178 | } | 181 | } |
| 179 | } | 182 | } |
| 180 | } | 183 | } |
src/domain/session.rsmodified+16 -17
| @@ -1,34 +1,32 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | +use uuid::Uuid; |
| 2 | -use ulid::Ulid; | ||
| 3 | 2 | ||
| 4 | -use crate::constant::SESSION_TABLE; | 3 | +use crate::domain::monotonic_id::next_uuid; |
| 5 | use crate::domain::timestamp::Timestamp; | 4 | use crate::domain::timestamp::Timestamp; |
| 6 | use crate::domain::user::UserId; | 5 | use crate::domain::user::UserId; |
| 7 | use crate::error::AppError; | 6 | use crate::error::AppError; |
| 8 | 7 | ||
| 9 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 8 | +/// Typed session row id. A UUIDv7 minted by the process-wide monotonic |
| 10 | -pub struct SessionId(RecordId); | 9 | +/// generator. (The table is `user_session` in PostgreSQL — the Rust type |
| 10 | +/// keeps its name.) | ||
| 11 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] | ||
| 12 | +#[sqlx(transparent)] | ||
| 13 | +pub struct SessionId(Uuid); | ||
| 11 | 14 | ||
| 12 | impl SessionId { | 15 | impl SessionId { |
| 13 | pub fn generate() -> Self { | 16 | pub fn generate() -> Self { |
| 14 | - Self(RecordId::new(SESSION_TABLE, Ulid::generate().to_string())) | 17 | + Self(next_uuid()) |
| 15 | - } | ||
| 16 | - | ||
| 17 | - pub fn record(&self) -> RecordId { | ||
| 18 | - self.0.clone() | ||
| 19 | } | 18 | } |
| 20 | 19 | ||
| 20 | + /// The hyphenated wire form. | ||
| 21 | #[allow(dead_code)] | 21 | #[allow(dead_code)] |
| 22 | - pub fn key(&self) -> &str { | 22 | + pub fn key(&self) -> String { |
| 23 | - match &self.0.key { | 23 | + self.0.to_string() |
| 24 | - RecordIdKey::String(key) => key, | ||
| 25 | - _ => "", | ||
| 26 | - } | ||
| 27 | } | 24 | } |
| 28 | } | 25 | } |
| 29 | 26 | ||
| 30 | /// A random, opaque session token (64 hex chars). | 27 | /// A random, opaque session token (64 hex chars). |
| 31 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 28 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 29 | +#[sqlx(transparent)] | ||
| 32 | pub struct SessionToken(String); | 30 | pub struct SessionToken(String); |
| 33 | 31 | ||
| 34 | impl SessionToken { | 32 | impl SessionToken { |
| @@ -44,9 +42,10 @@ impl SessionToken { | |||
| 44 | } | 42 | } |
| 45 | 43 | ||
| 46 | /// Fields are crate-visible: [`crate::db::session`] mints the rows on login. | 44 | /// Fields are crate-visible: [`crate::db::session`] mints the rows on login. |
| 47 | -#[derive(Debug, Clone, SurrealValue)] | 45 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 48 | pub struct Session { | 46 | pub struct Session { |
| 49 | pub(crate) id: SessionId, | 47 | pub(crate) id: SessionId, |
| 48 | + #[sqlx(rename = "app_user")] | ||
| 50 | pub(crate) user: UserId, | 49 | pub(crate) user: UserId, |
| 51 | pub(crate) token: SessionToken, | 50 | pub(crate) token: SessionToken, |
| 52 | pub(crate) expires_at: Timestamp, | 51 | pub(crate) expires_at: Timestamp, |
src/domain/session_attendance.rsmodified+37 -27
| @@ -1,35 +1,49 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | - | ||
| 3 | -use crate::constant::SESSION_ATTENDANCE_TABLE; | ||
| 4 | use crate::domain::attendance::AttendanceStatus; | 1 | use crate::domain::attendance::AttendanceStatus; |
| 5 | use crate::domain::course::CourseId; | 2 | use crate::domain::course::CourseId; |
| 6 | use crate::domain::course_session::CourseSessionId; | 3 | use crate::domain::course_session::CourseSessionId; |
| 7 | use crate::domain::user::UserId; | 4 | use crate::domain::user::UserId; |
| 8 | 5 | ||
| 9 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 6 | +/// The (session, user) pair — the table's natural composite primary key. |
| 10 | -pub struct SessionAttendanceId(RecordId); | 7 | +/// Because the same pair always maps to the same row, marking is a single |
| 8 | +/// atomic upsert with no find-then-insert race, and one-row-per-pair holds by | ||
| 9 | +/// construction. UUID strings carry only `-`, so `_` is an unambiguous joiner. | ||
| 10 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 11 | +pub struct SessionAttendanceId { | ||
| 12 | + session: CourseSessionId, | ||
| 13 | + user: UserId, | ||
| 14 | +} | ||
| 11 | 15 | ||
| 12 | impl SessionAttendanceId { | 16 | impl SessionAttendanceId { |
| 13 | - /// A deterministic id for the (session, user) pair. Because the same pair | ||
| 14 | - /// always maps to the same record id, marking is a single atomic UPSERT with | ||
| 15 | - /// no find-then-insert race, and one-row-per-pair holds by construction. | ||
| 16 | - /// ULID keys are alphanumeric, so `_` is an unambiguous joiner. | ||
| 17 | pub fn composite(session: &CourseSessionId, user: &UserId) -> Self { | 17 | pub fn composite(session: &CourseSessionId, user: &UserId) -> Self { |
| 18 | - Self(RecordId::new( | 18 | + Self { |
| 19 | - SESSION_ATTENDANCE_TABLE, | 19 | + session: *session, |
| 20 | - format!("{}_{}", session.key(), user.key()), | 20 | + user: *user, |
| 21 | - )) | 21 | + } |
| 22 | } | 22 | } |
| 23 | 23 | ||
| 24 | - pub fn record(&self) -> RecordId { | 24 | + /// Parse the `{session}_{user}` wire form. A key that parses as no pair |
| 25 | - self.0.clone() | 25 | + /// reads as the nil pair, which matches no row — exactly the 404 a |
| 26 | + /// dangling composite key produced under the old store, without turning a | ||
| 27 | + /// typo into a panic. | ||
| 28 | + pub fn from_key(key: &str) -> Self { | ||
| 29 | + let (session, user) = key.rsplit_once('_').unwrap_or(("", "")); | ||
| 30 | + Self { | ||
| 31 | + session: CourseSessionId::from_key(session), | ||
| 32 | + user: UserId::from_key(user), | ||
| 33 | + } | ||
| 26 | } | 34 | } |
| 27 | 35 | ||
| 28 | - pub fn key(&self) -> &str { | 36 | + /// The `{session}_{user}` wire form. |
| 29 | - match &self.0.key { | 37 | + pub fn key(&self) -> String { |
| 30 | - RecordIdKey::String(key) => key, | 38 | + format!("{}_{}", self.session.key(), self.user.key()) |
| 31 | - _ => "", | 39 | + } |
| 32 | - } | 40 | + |
| 41 | + pub fn session(&self) -> CourseSessionId { | ||
| 42 | + self.session | ||
| 43 | + } | ||
| 44 | + | ||
| 45 | + pub fn user(&self) -> UserId { | ||
| 46 | + self.user | ||
| 33 | } | 47 | } |
| 34 | } | 48 | } |
| 35 | 49 | ||
| @@ -51,22 +65,18 @@ pub(crate) fn counts_as_attended(status: &AttendanceStatus) -> bool { | |||
| 51 | 65 | ||
| 52 | /// One person's roll-call state for one lesson. `course` is denormalized from | 66 | /// One person's roll-call state for one lesson. `course` is denormalized from |
| 53 | /// the session so the per-course attendance report is a single indexed query | 67 | /// the session so the per-course attendance report is a single indexed query |
| 54 | -/// (`WHERE user = $u`) with no join. | 68 | +/// (`WHERE app_user = $u`) with no join. |
| 55 | -#[derive(Debug, Clone, SurrealValue)] | 69 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 56 | pub struct SessionAttendance { | 70 | pub struct SessionAttendance { |
| 57 | - pub(crate) id: SessionAttendanceId, | ||
| 58 | pub(crate) session: CourseSessionId, | 71 | pub(crate) session: CourseSessionId, |
| 59 | pub(crate) course: CourseId, | 72 | pub(crate) course: CourseId, |
| 73 | + #[sqlx(rename = "app_user")] | ||
| 60 | pub(crate) user: UserId, | 74 | pub(crate) user: UserId, |
| 61 | pub(crate) status: AttendanceStatus, | 75 | pub(crate) status: AttendanceStatus, |
| 62 | pub(crate) marked_by: UserId, | 76 | pub(crate) marked_by: UserId, |
| 63 | } | 77 | } |
| 64 | 78 | ||
| 65 | impl SessionAttendance { | 79 | impl SessionAttendance { |
| 66 | - pub fn get_id(&self) -> &SessionAttendanceId { | ||
| 67 | - &self.id | ||
| 68 | - } | ||
| 69 | - | ||
| 70 | pub fn get_session(&self) -> &CourseSessionId { | 80 | pub fn get_session(&self) -> &CourseSessionId { |
| 71 | &self.session | 81 | &self.session |
| 72 | } | 82 | } |
src/domain/settings.rsmodified+34 -27
| @@ -11,7 +11,9 @@ | |||
| 11 | //! without a backfill (backfills crash boots — `DEFAULT` never rescues | 11 | //! without a backfill (backfills crash boots — `DEFAULT` never rescues |
| 12 | //! existing rows, and `UPDATE` re-validates whole records). | 12 | //! existing rows, and `UPDATE` re-validates whole records). |
| 13 | 13 | ||
| 14 | -use surrealdb::types::{RecordId, SurrealValue}; | 14 | + |
| 15 | +use serde::{Deserialize, Serialize}; | ||
| 16 | +use sqlx::types::Json; | ||
| 15 | 17 | ||
| 16 | use crate::constant::{ | 18 | use crate::constant::{ |
| 17 | DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_DIETARY_TAGS, | 19 | DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_DIETARY_TAGS, |
| @@ -21,7 +23,7 @@ use crate::constant::{ | |||
| 21 | MAX_MAX_CHATBOT_THREADS, MAX_MAX_FILE_BYTES, MAX_MEAL_CANCEL_CUTOFF_MINUTES, | 23 | MAX_MAX_CHATBOT_THREADS, MAX_MAX_FILE_BYTES, MAX_MEAL_CANCEL_CUTOFF_MINUTES, |
| 22 | MAX_MEAL_SERVING_MINUTE, MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, | 24 | MAX_MEAL_SERVING_MINUTE, MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, |
| 23 | MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN, | 25 | MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN, |
| 24 | - MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES, SETTINGS_KEY, SETTINGS_TABLE, | 26 | + MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES, SETTINGS_KEY, |
| 25 | }; | 27 | }; |
| 26 | use crate::domain::text_fold; | 28 | use crate::domain::text_fold; |
| 27 | use crate::error::ValidationError; | 29 | use crate::error::ValidationError; |
| @@ -30,7 +32,7 @@ use crate::error::ValidationError; | |||
| 30 | /// how many times an exam of that kind counts into its course's average. | 32 | /// how many times an exam of that kind counts into its course's average. |
| 31 | /// Weight lives here, not on the exam — reweighting a kind reweights every | 33 | /// Weight lives here, not on the exam — reweighting a kind reweights every |
| 32 | /// exam of that kind at once. | 34 | /// exam of that kind at once. |
| 33 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 35 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 34 | pub struct ExamKindDef { | 36 | pub struct ExamKindDef { |
| 35 | name: String, | 37 | name: String, |
| 36 | weight: i64, | 38 | weight: i64, |
| @@ -77,7 +79,7 @@ impl ExamKindDef { | |||
| 77 | /// `540` (09:00) for a meal served at noon locally. `None` — every slot | 79 | /// `540` (09:00) for a meal served at noon locally. `None` — every slot |
| 78 | /// written before the field existed — falls back to midnight UTC, the old | 80 | /// written before the field existed — falls back to midnight UTC, the old |
| 79 | /// behaviour. | 81 | /// behaviour. |
| 80 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 82 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 81 | pub struct MealSlotDef { | 83 | pub struct MealSlotDef { |
| 82 | name: String, | 84 | name: String, |
| 83 | serving_minute: Option<i64>, | 85 | serving_minute: Option<i64>, |
| @@ -152,7 +154,7 @@ impl MealSlotDef { | |||
| 152 | 154 | ||
| 153 | /// One grade-display band: marks at or above `min` (and below the next band's | 155 | /// One grade-display band: marks at or above `min` (and below the next band's |
| 154 | /// `min`) render as `label`. Display only — storage and averaging stay numeric. | 156 | /// `min`) render as `label`. Display only — storage and averaging stay numeric. |
| 155 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 157 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 156 | pub struct GradeBand { | 158 | pub struct GradeBand { |
| 157 | min: i64, | 159 | min: i64, |
| 158 | label: String, | 160 | label: String, |
| @@ -192,12 +194,12 @@ impl GradeBand { | |||
| 192 | /// like every other entity, an existing `Settings` is always internally | 194 | /// like every other entity, an existing `Settings` is always internally |
| 193 | /// consistent). Fields are crate-visible because [`crate::db::settings`] | 195 | /// consistent). Fields are crate-visible because [`crate::db::settings`] |
| 194 | /// binds them directly in the compare-and-set guard. | 196 | /// binds them directly in the compare-and-set guard. |
| 195 | -#[derive(Debug, Clone, SurrealValue)] | 197 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 196 | pub struct Settings { | 198 | pub struct Settings { |
| 197 | - id: RecordId, | 199 | + pub(crate) id: String, |
| 198 | - pub(crate) exam_kinds: Vec<ExamKindDef>, | 200 | + pub(crate) exam_kinds: Json<Vec<ExamKindDef>>, |
| 199 | pub(crate) attendance_statuses: Vec<String>, | 201 | pub(crate) attendance_statuses: Vec<String>, |
| 200 | - pub(crate) grade_bands: Vec<GradeBand>, | 202 | + pub(crate) grade_bands: Json<Vec<GradeBand>>, |
| 201 | /// Per-file byte cap for note uploads. `None` = the row predates the | 203 | /// Per-file byte cap for note uploads. `None` = the row predates the |
| 202 | /// field (or the defaults) — reads as `DEFAULT_MAX_FILE_BYTES`. | 204 | /// field (or the defaults) — reads as `DEFAULT_MAX_FILE_BYTES`. |
| 203 | pub(crate) max_file_bytes: Option<i64>, | 205 | pub(crate) max_file_bytes: Option<i64>, |
| @@ -209,7 +211,7 @@ pub struct Settings { | |||
| 209 | /// the columns are `option<…>`, never `DEFAULT []`: `save_if_unchanged` | 211 | /// the columns are `option<…>`, never `DEFAULT []`: `save_if_unchanged` |
| 210 | /// writes the whole row, so a field this struct did not carry would coerce | 212 | /// writes the whole row, so a field this struct did not carry would coerce |
| 211 | /// to `NONE` and abort the transaction. | 213 | /// to `NONE` and abort the transaction. |
| 212 | - pub(crate) meal_slots: Option<Vec<MealSlotDef>>, | 214 | + pub(crate) meal_slots: Option<Json<Vec<MealSlotDef>>>, |
| 213 | pub(crate) dietary_tags: Option<Vec<String>>, | 215 | pub(crate) dietary_tags: Option<Vec<String>>, |
| 214 | /// Minutes before a meal at which booking *and* cancelling close. One knob | 216 | /// Minutes before a meal at which booking *and* cancelling close. One knob |
| 215 | /// for both deadlines; `None` = no cutoff at all, which is also what an | 217 | /// for both deadlines; `None` = no cutoff at all, which is also what an |
| @@ -236,8 +238,9 @@ pub struct SettingsParams { | |||
| 236 | } | 238 | } |
| 237 | 239 | ||
| 238 | impl Settings { | 240 | impl Settings { |
| 239 | - pub(crate) fn record_id() -> RecordId { | 241 | + /// The singleton row's key (`settings.id` is `TEXT PRIMARY KEY`). |
| 240 | - RecordId::new(SETTINGS_TABLE, SETTINGS_KEY) | 242 | + pub(crate) fn record_id() -> String { |
| 243 | + SETTINGS_KEY.to_string() | ||
| 241 | } | 244 | } |
| 242 | 245 | ||
| 243 | /// The out-of-the-box policy — mirrors the constants that were previously | 246 | /// The out-of-the-box policy — mirrors the constants that were previously |
| @@ -245,14 +248,16 @@ impl Settings { | |||
| 245 | pub fn defaults() -> Self { | 248 | pub fn defaults() -> Self { |
| 246 | Self { | 249 | Self { |
| 247 | id: Self::record_id(), | 250 | id: Self::record_id(), |
| 248 | - exam_kinds: DEFAULT_EXAM_KINDS | 251 | + exam_kinds: Json( |
| 249 | - .map(|(name, weight)| ExamKindDef { | 252 | + DEFAULT_EXAM_KINDS |
| 250 | - name: name.to_string(), | 253 | + .map(|(name, weight)| ExamKindDef { |
| 251 | - weight, | 254 | + name: name.to_string(), |
| 252 | - }) | 255 | + weight, |
| 253 | - .to_vec(), | 256 | + }) |
| 257 | + .to_vec(), | ||
| 258 | + ), | ||
| 254 | attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(), | 259 | attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(), |
| 255 | - grade_bands: Vec::new(), | 260 | + grade_bands: Json(Vec::new()), |
| 256 | max_file_bytes: None, | 261 | max_file_bytes: None, |
| 257 | chatbot_history_turns: None, | 262 | chatbot_history_turns: None, |
| 258 | max_chatbot_threads: None, | 263 | max_chatbot_threads: None, |
| @@ -267,9 +272,9 @@ impl Settings { | |||
| 267 | /// value it currently reads as. | 272 | /// value it currently reads as. |
| 268 | pub fn params(&self) -> SettingsParams { | 273 | pub fn params(&self) -> SettingsParams { |
| 269 | SettingsParams { | 274 | SettingsParams { |
| 270 | - exam_kinds: self.exam_kinds.clone(), | 275 | + exam_kinds: self.exam_kinds.0.clone(), |
| 271 | attendance_statuses: self.attendance_statuses.clone(), | 276 | attendance_statuses: self.attendance_statuses.clone(), |
| 272 | - grade_bands: self.grade_bands.clone(), | 277 | + grade_bands: self.grade_bands.0.clone(), |
| 273 | max_file_bytes: self.get_max_file_bytes(), | 278 | max_file_bytes: self.get_max_file_bytes(), |
| 274 | chatbot_history_turns: self.get_chatbot_history_turns(), | 279 | chatbot_history_turns: self.get_chatbot_history_turns(), |
| 275 | max_chatbot_threads: self.get_max_chatbot_threads(), | 280 | max_chatbot_threads: self.get_max_chatbot_threads(), |
| @@ -396,21 +401,21 @@ impl Settings { | |||
| 396 | 401 | ||
| 397 | Ok(Self { | 402 | Ok(Self { |
| 398 | id: Self::record_id(), | 403 | id: Self::record_id(), |
| 399 | - exam_kinds, | 404 | + exam_kinds: Json(exam_kinds), |
| 400 | attendance_statuses, | 405 | attendance_statuses, |
| 401 | - grade_bands, | 406 | + grade_bands: Json(grade_bands), |
| 402 | max_file_bytes: Some(max_file_bytes), | 407 | max_file_bytes: Some(max_file_bytes), |
| 403 | chatbot_history_turns: Some(chatbot_history_turns), | 408 | chatbot_history_turns: Some(chatbot_history_turns), |
| 404 | max_chatbot_threads: Some(max_chatbot_threads), | 409 | max_chatbot_threads: Some(max_chatbot_threads), |
| 405 | max_chatbot_message_len: Some(max_chatbot_message_len), | 410 | max_chatbot_message_len: Some(max_chatbot_message_len), |
| 406 | - meal_slots: Some(meal_slots), | 411 | + meal_slots: Some(Json(meal_slots)), |
| 407 | dietary_tags: Some(dietary_tags), | 412 | dietary_tags: Some(dietary_tags), |
| 408 | meal_cancel_cutoff_minutes, | 413 | meal_cancel_cutoff_minutes, |
| 409 | }) | 414 | }) |
| 410 | } | 415 | } |
| 411 | 416 | ||
| 412 | pub fn get_exam_kinds(&self) -> &[ExamKindDef] { | 417 | pub fn get_exam_kinds(&self) -> &[ExamKindDef] { |
| 413 | - &self.exam_kinds | 418 | + &self.exam_kinds.0 |
| 414 | } | 419 | } |
| 415 | 420 | ||
| 416 | /// The weight of the kind named `kind` (exact match, like kind | 421 | /// The weight of the kind named `kind` (exact match, like kind |
| @@ -419,6 +424,7 @@ impl Settings { | |||
| 419 | /// (settings edits never rewrite history), so it must still count. | 424 | /// (settings edits never rewrite history), so it must still count. |
| 420 | pub fn exam_kind_weight(&self, kind: &str) -> Option<i64> { | 425 | pub fn exam_kind_weight(&self, kind: &str) -> Option<i64> { |
| 421 | self.exam_kinds | 426 | self.exam_kinds |
| 427 | + .0 | ||
| 422 | .iter() | 428 | .iter() |
| 423 | .find(|def| def.get_name() == kind) | 429 | .find(|def| def.get_name() == kind) |
| 424 | .map(ExamKindDef::get_weight) | 430 | .map(ExamKindDef::get_weight) |
| @@ -429,7 +435,7 @@ impl Settings { | |||
| 429 | } | 435 | } |
| 430 | 436 | ||
| 431 | pub fn get_grade_bands(&self) -> &[GradeBand] { | 437 | pub fn get_grade_bands(&self) -> &[GradeBand] { |
| 432 | - &self.grade_bands | 438 | + &self.grade_bands.0 |
| 433 | } | 439 | } |
| 434 | 440 | ||
| 435 | /// The per-file upload cap in bytes; the built-in default while the | 441 | /// The per-file upload cap in bytes; the built-in default while the |
| @@ -463,7 +469,7 @@ impl Settings { | |||
| 463 | /// one (including rows saved before the field existed). An explicitly | 469 | /// one (including rows saved before the field existed). An explicitly |
| 464 | /// stored empty list stays empty — that is "no meal program", not "unset". | 470 | /// stored empty list stays empty — that is "no meal program", not "unset". |
| 465 | pub fn get_meal_slots(&self) -> Vec<MealSlotDef> { | 471 | pub fn get_meal_slots(&self) -> Vec<MealSlotDef> { |
| 466 | - self.meal_slots.clone().unwrap_or_else(|| { | 472 | + self.meal_slots.as_ref().map(|slots| slots.0.clone()).unwrap_or_else(|| { |
| 467 | DEFAULT_MEAL_SLOTS | 473 | DEFAULT_MEAL_SLOTS |
| 468 | .map(|name| MealSlotDef { | 474 | .map(|name| MealSlotDef { |
| 469 | name: name.to_string(), | 475 | name: name.to_string(), |
| @@ -497,6 +503,7 @@ impl Settings { | |||
| 497 | /// `f64` so course averages label the same way plain marks do. | 503 | /// `f64` so course averages label the same way plain marks do. |
| 498 | pub fn grade_label(&self, mark: f64) -> Option<&str> { | 504 | pub fn grade_label(&self, mark: f64) -> Option<&str> { |
| 499 | self.grade_bands | 505 | self.grade_bands |
| 506 | + .0 | ||
| 500 | .iter() | 507 | .iter() |
| 501 | .filter(|band| band.get_min() as f64 <= mark) | 508 | .filter(|band| band.get_min() as f64 <= mark) |
| 502 | .max_by_key(|band| band.get_min()) | 509 | .max_by_key(|band| band.get_min()) |
src/domain/solution.rsmodified+24 -32
| @@ -1,17 +1,7 @@ | |||
| 1 | -//! A solution offered on an approved pool question (see | 1 | +use uuid::Uuid; |
| 2 | -//! [`crate::domain::pool_question`]). Anyone in the school — student or staff | 2 | + |
| 3 | -//! — may offer one; rows list oldest first, reading as a discussion thread. | 3 | +use crate::constant::MAX_SOLUTION_BODY_LEN; |
| 4 | -//! Solutions die with their question (the question delete cascades here). | 4 | +use crate::domain::monotonic_id::next_uuid; |
| 5 | -//! Like a question, a solution may carry one photo (`image_*` metadata on the | ||
| 6 | -//! row, bytes on disk under a server-generated ULID) — but unlike a question | ||
| 7 | -//! it has no moderation state, so its author may edit the body and swap the | ||
| 8 | -//! photo at any time; there is nothing to freeze. The queries live in | ||
| 9 | -//! [`crate::db::solution`], the funnels in [`crate::service::solution`]. | ||
| 10 | - | ||
| 11 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 12 | - | ||
| 13 | -use crate::constant::{MAX_SOLUTION_BODY_LEN, SOLUTION_TABLE}; | ||
| 14 | -use crate::domain::monotonic_id::next_ulid; | ||
| 15 | use crate::domain::note_file::FileContentType; | 5 | use crate::domain::note_file::FileContentType; |
| 16 | use crate::domain::pool_question::PoolQuestionId; | 6 | use crate::domain::pool_question::PoolQuestionId; |
| 17 | use crate::domain::timestamp::Timestamp; | 7 | use crate::domain::timestamp::Timestamp; |
| @@ -19,35 +9,37 @@ use crate::domain::user::UserId; | |||
| 19 | use crate::error::ValidationError; | 9 | use crate::error::ValidationError; |
| 20 | use crate::validate::validate_required; | 10 | use crate::validate::validate_required; |
| 21 | 11 | ||
| 22 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 12 | +/// Typed solution row id. A UUIDv7 minted by the process-wide monotonic |
| 23 | -pub struct SolutionId(RecordId); | 13 | +/// generator, so `id` order is mint order. |
| 14 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] | ||
| 15 | +#[sqlx(transparent)] | ||
| 16 | +pub struct SolutionId(Uuid); | ||
| 24 | 17 | ||
| 25 | impl SolutionId { | 18 | impl SolutionId { |
| 26 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 19 | + /// Minted from the process-wide monotonic generator, not a random v4: |
| 27 | /// solutions sort `offered_at ASC, id ASC` and the id *is* the tie-break | 20 | /// solutions sort `offered_at ASC, id ASC` and the id *is* the tie-break |
| 28 | /// ([`crate::db::solution::list_for`]), | 21 | /// ([`crate::db::solution::list_for`]), |
| 29 | /// and a random low half scrambles rows minted in the same millisecond. | 22 | /// and a random low half scrambles rows minted in the same millisecond. |
| 30 | pub fn generate() -> Self { | 23 | pub fn generate() -> Self { |
| 31 | - Self(RecordId::new(SOLUTION_TABLE, next_ulid().to_string())) | 24 | + Self(next_uuid()) |
| 32 | } | 25 | } |
| 33 | 26 | ||
| 27 | + /// Parse a wire key. A key that parses as no UUID — a malformed path | ||
| 28 | + /// segment — reads as the nil id, which matches no row: exactly the 404 a | ||
| 29 | + /// dangling record key produced under the old store, without turning a | ||
| 30 | + /// typo into a panic. | ||
| 34 | pub fn from_key(key: &str) -> Self { | 31 | pub fn from_key(key: &str) -> Self { |
| 35 | - Self(RecordId::new(SOLUTION_TABLE, key)) | 32 | + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) |
| 36 | - } | ||
| 37 | - | ||
| 38 | - pub fn record(&self) -> RecordId { | ||
| 39 | - self.0.clone() | ||
| 40 | } | 33 | } |
| 41 | 34 | ||
| 42 | - pub fn key(&self) -> &str { | 35 | + /// The hyphenated wire form. |
| 43 | - match &self.0.key { | 36 | + pub fn key(&self) -> String { |
| 44 | - RecordIdKey::String(key) => key, | 37 | + self.0.to_string() |
| 45 | - _ => "", | ||
| 46 | - } | ||
| 47 | } | 38 | } |
| 48 | } | 39 | } |
| 49 | 40 | ||
| 50 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 41 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 42 | +#[sqlx(transparent)] | ||
| 51 | pub struct SolutionBody(String); | 43 | pub struct SolutionBody(String); |
| 52 | 44 | ||
| 53 | impl SolutionBody { | 45 | impl SolutionBody { |
| @@ -61,15 +53,15 @@ impl SolutionBody { | |||
| 61 | } | 53 | } |
| 62 | } | 54 | } |
| 63 | 55 | ||
| 64 | -#[derive(Debug, Clone, SurrealValue)] | 56 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 65 | pub struct Solution { | 57 | pub struct Solution { |
| 66 | pub(crate) id: SolutionId, | 58 | pub(crate) id: SolutionId, |
| 67 | pub(crate) question: PoolQuestionId, | 59 | pub(crate) question: PoolQuestionId, |
| 68 | pub(crate) author: UserId, | 60 | pub(crate) author: UserId, |
| 69 | pub(crate) body: SolutionBody, | 61 | pub(crate) body: SolutionBody, |
| 70 | pub(crate) offered_at: Timestamp, | 62 | pub(crate) offered_at: Timestamp, |
| 71 | - /// The photo's on-disk blob name — a fresh ULID every upload; `None` when | 63 | + /// The photo's on-disk blob name — a fresh server-generated id every |
| 72 | - /// the solution carries no image. | 64 | + /// upload; `None` when the solution carries no image. |
| 73 | pub(crate) image_file: Option<String>, | 65 | pub(crate) image_file: Option<String>, |
| 74 | pub(crate) image_content_type: Option<FileContentType>, | 66 | pub(crate) image_content_type: Option<FileContentType>, |
| 75 | pub(crate) image_size: Option<i64>, | 67 | pub(crate) image_size: Option<i64>, |
src/domain/subject.rsmodified+28 -24
| @@ -1,40 +1,43 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | +use sqlx::Type; |
| 2 | +use uuid::Uuid; | ||
| 2 | 3 | ||
| 3 | -use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN, SUBJECT_TABLE}; | 4 | +use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN}; |
| 4 | use crate::domain::course::CourseId; | 5 | use crate::domain::course::CourseId; |
| 5 | -use crate::domain::monotonic_id::next_ulid; | 6 | +use crate::domain::monotonic_id::next_uuid; |
| 6 | use crate::error::ValidationError; | 7 | use crate::error::ValidationError; |
| 7 | use crate::validate::{validate_optional, validate_required}; | 8 | use crate::validate::{validate_optional, validate_required}; |
| 8 | 9 | ||
| 9 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 10 | +/// Typed subject row id. A UUIDv7 minted by the process-wide monotonic |
| 10 | -pub struct SubjectId(RecordId); | 11 | +/// generator, so `id` order is mint order. |
| 12 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] | ||
| 13 | +#[sqlx(transparent)] | ||
| 14 | +pub struct SubjectId(Uuid); | ||
| 11 | 15 | ||
| 12 | impl SubjectId { | 16 | impl SubjectId { |
| 13 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: the | 17 | + /// Minted from the process-wide monotonic generator, not a random v4: the |
| 14 | /// id *is* the curriculum's order ([`crate::db::subject::list_for_course`] | 18 | /// id *is* the curriculum's order ([`crate::db::subject::list_for_course`] |
| 15 | /// sorts `id ASC`), and a random low half scrambles a burst of saves that | 19 | /// sorts `id ASC`), and a random low half scrambles a burst of saves that |
| 16 | /// lands inside one millisecond. | 20 | /// lands inside one millisecond. |
| 17 | pub fn generate() -> Self { | 21 | pub fn generate() -> Self { |
| 18 | - Self(RecordId::new(SUBJECT_TABLE, next_ulid().to_string())) | 22 | + Self(next_uuid()) |
| 19 | } | 23 | } |
| 20 | 24 | ||
| 25 | + /// Parse a wire key. A key that parses as no UUID — a malformed path | ||
| 26 | + /// segment — reads as the nil id, which matches no row: exactly the 404 a | ||
| 27 | + /// dangling record key produced under the old store, without turning a | ||
| 28 | + /// typo into a panic. | ||
| 21 | pub fn from_key(key: &str) -> Self { | 29 | pub fn from_key(key: &str) -> Self { |
| 22 | - Self(RecordId::new(SUBJECT_TABLE, key)) | 30 | + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) |
| 23 | } | 31 | } |
| 24 | 32 | ||
| 25 | - pub fn record(&self) -> RecordId { | 33 | + /// The hyphenated wire form. |
| 26 | - self.0.clone() | 34 | + pub fn key(&self) -> String { |
| 27 | - } | 35 | + self.0.to_string() |
| 28 | - | ||
| 29 | - pub fn key(&self) -> &str { | ||
| 30 | - match &self.0.key { | ||
| 31 | - RecordIdKey::String(key) => key, | ||
| 32 | - _ => "", | ||
| 33 | - } | ||
| 34 | } | 36 | } |
| 35 | } | 37 | } |
| 36 | 38 | ||
| 37 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 39 | +#[derive(Debug, Clone, PartialEq, Eq, Type)] |
| 40 | +#[sqlx(transparent)] | ||
| 38 | pub struct SubjectName(String); | 41 | pub struct SubjectName(String); |
| 39 | 42 | ||
| 40 | impl SubjectName { | 43 | impl SubjectName { |
| @@ -48,7 +51,8 @@ impl SubjectName { | |||
| 48 | } | 51 | } |
| 49 | } | 52 | } |
| 50 | 53 | ||
| 51 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 54 | +#[derive(Debug, Clone, PartialEq, Eq, Type)] |
| 55 | +#[sqlx(transparent)] | ||
| 52 | pub struct SubjectDescription(String); | 56 | pub struct SubjectDescription(String); |
| 53 | 57 | ||
| 54 | impl SubjectDescription { | 58 | impl SubjectDescription { |
| @@ -66,7 +70,7 @@ impl SubjectDescription { | |||
| 66 | /// a subject of its exam's course, so results can later be read per topic. The | 70 | /// a subject of its exam's course, so results can later be read per topic. The |
| 67 | /// course link is fixed at creation — a subject is course content, and moving | 71 | /// course link is fixed at creation — a subject is course content, and moving |
| 68 | /// it would strand the questions tagged with it. | 72 | /// it would strand the questions tagged with it. |
| 69 | -#[derive(Debug, Clone, SurrealValue)] | 73 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 70 | pub struct Subject { | 74 | pub struct Subject { |
| 71 | pub(crate) id: SubjectId, | 75 | pub(crate) id: SubjectId, |
| 72 | pub(crate) course: CourseId, | 76 | pub(crate) course: CourseId, |
| @@ -98,13 +102,13 @@ mod tests { | |||
| 98 | 102 | ||
| 99 | /// A teacher entering a curriculum gets it back in the order they typed it: | 103 | /// A teacher entering a curriculum gets it back in the order they typed it: |
| 100 | /// `list_for_course` sorts `id ASC`, so the ids minted inside one | 104 | /// `list_for_course` sorts `id ASC`, so the ids minted inside one |
| 101 | - /// millisecond have to sort in mint order. Revert `generate` to | 105 | + /// millisecond have to sort in mint order. Revert `generate` to a random |
| 102 | - /// `Ulid::generate()` and this fails — the low 80 bits are redrawn per id, so a | 106 | + /// v4 and this fails — the low bits are redrawn per id, so a same-tick |
| 103 | - /// same-tick burst comes out shuffled. | 107 | + /// burst comes out shuffled. |
| 104 | #[tokio::test] | 108 | #[tokio::test] |
| 105 | async fn ids_sort_in_creation_order() { | 109 | async fn ids_sort_in_creation_order() { |
| 106 | let ids: Vec<String> = (0..500) | 110 | let ids: Vec<String> = (0..500) |
| 107 | - .map(|_| SubjectId::generate().key().to_string()) | 111 | + .map(|_| SubjectId::generate().key()) |
| 108 | .collect(); | 112 | .collect(); |
| 109 | let mut sorted = ids.clone(); | 113 | let mut sorted = ids.clone(); |
| 110 | sorted.sort(); | 114 | sorted.sort(); |
src/domain/term.rsmodified+28 -37
| @@ -1,44 +1,38 @@ | |||
| 1 | -//! An academic term — semester, trimester, quarter, whatever this school | 1 | +use sqlx::Type; |
| 2 | -//! runs; the structure is just rows, so it needs no code change per school. | 2 | +use uuid::Uuid; |
| 3 | -//! Courses may link to one term. | 3 | + |
| 4 | -//! | 4 | +use crate::constant::MAX_TERM_NAME_LEN; |
| 5 | -//! Terms are calendar structure, not schedules: a school adopting the app | 5 | +use crate::domain::monotonic_id::next_uuid; |
| 6 | -//! mid-year legitimately creates a term that already started, so the no-past | ||
| 7 | -//! rule that guards exams/lessons/events deliberately does not apply here. | ||
| 8 | - | ||
| 9 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 10 | - | ||
| 11 | -use crate::constant::{MAX_TERM_NAME_LEN, TERM_TABLE}; | ||
| 12 | -use crate::domain::monotonic_id::next_ulid; | ||
| 13 | use crate::domain::timestamp::Timestamp; | 6 | use crate::domain::timestamp::Timestamp; |
| 14 | use crate::error::{AppError, ValidationError}; | 7 | use crate::error::{AppError, ValidationError}; |
| 15 | use crate::validate::validate_required; | 8 | use crate::validate::validate_required; |
| 16 | 9 | ||
| 17 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 10 | +/// Typed term row id. A UUIDv7 minted by the process-wide monotonic |
| 18 | -pub struct TermId(RecordId); | 11 | +/// generator, so `id` order is mint order. |
| 12 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] | ||
| 13 | +#[sqlx(transparent)] | ||
| 14 | +pub struct TermId(Uuid); | ||
| 19 | 15 | ||
| 20 | impl TermId { | 16 | impl TermId { |
| 21 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 17 | + /// Minted from the process-wide monotonic generator, not a random v4: |
| 22 | /// terms sort `starts_at DESC, id DESC` and the id breaks the tie between | 18 | /// terms sort `starts_at DESC, id DESC` and the id breaks the tie between |
| 23 | /// two terms starting at the same instant, | 19 | /// two terms starting at the same instant, |
| 24 | /// and a random low half sorts arbitrarily inside one millisecond. | 20 | /// and a random low half sorts arbitrarily inside one millisecond. |
| 25 | pub fn generate() -> Self { | 21 | pub fn generate() -> Self { |
| 26 | - Self(RecordId::new(TERM_TABLE, next_ulid().to_string())) | 22 | + Self(next_uuid()) |
| 27 | } | 23 | } |
| 28 | 24 | ||
| 25 | + /// Parse a wire key. A key that parses as no UUID — a malformed path | ||
| 26 | + /// segment — reads as the nil id, which matches no row: exactly the 404 a | ||
| 27 | + /// dangling record key produced under the old store, without turning a | ||
| 28 | + /// typo into a panic. | ||
| 29 | pub fn from_key(key: &str) -> Self { | 29 | pub fn from_key(key: &str) -> Self { |
| 30 | - Self(RecordId::new(TERM_TABLE, key)) | 30 | + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) |
| 31 | - } | ||
| 32 | - | ||
| 33 | - pub fn record(&self) -> RecordId { | ||
| 34 | - self.0.clone() | ||
| 35 | } | 31 | } |
| 36 | 32 | ||
| 37 | - pub fn key(&self) -> &str { | 33 | + /// The hyphenated wire form. |
| 38 | - match &self.0.key { | 34 | + pub fn key(&self) -> String { |
| 39 | - RecordIdKey::String(key) => key, | 35 | + self.0.to_string() |
| 40 | - _ => "", | ||
| 41 | - } | ||
| 42 | } | 36 | } |
| 43 | } | 37 | } |
| 44 | 38 | ||
| @@ -69,18 +63,16 @@ pub fn archived_error() -> AppError { | |||
| 69 | pub fn ref_move( | 63 | pub fn ref_move( |
| 70 | current: Option<&TermId>, | 64 | current: Option<&TermId>, |
| 71 | patch: &Option<Option<TermId>>, | 65 | patch: &Option<Option<TermId>>, |
| 72 | -) -> (Option<RecordId>, Option<RecordId>) { | 66 | +) -> (Option<TermId>, Option<TermId>) { |
| 73 | match patch { | 67 | match patch { |
| 74 | None => (None, None), | 68 | None => (None, None), |
| 75 | Some(next) if next.as_ref() == current => (None, None), | 69 | Some(next) if next.as_ref() == current => (None, None), |
| 76 | - Some(next) => ( | 70 | + Some(next) => (*next, current.copied()), |
| 77 | - next.as_ref().map(TermId::record), | ||
| 78 | - current.map(TermId::record), | ||
| 79 | - ), | ||
| 80 | } | 71 | } |
| 81 | } | 72 | } |
| 82 | 73 | ||
| 83 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 74 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 75 | +#[sqlx(transparent)] | ||
| 84 | pub struct TermName(String); | 76 | pub struct TermName(String); |
| 85 | 77 | ||
| 86 | impl TermName { | 78 | impl TermName { |
| @@ -96,16 +88,15 @@ impl TermName { | |||
| 96 | 88 | ||
| 97 | /// One term on the school's academic calendar. Both ends are required — a | 89 | /// One term on the school's academic calendar. Both ends are required — a |
| 98 | /// term is a date range by definition. | 90 | /// term is a date range by definition. |
| 99 | -#[derive(Debug, Clone, SurrealValue)] | 91 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 100 | pub struct Term { | 92 | pub struct Term { |
| 101 | pub(crate) id: TermId, | 93 | pub(crate) id: TermId, |
| 102 | pub(crate) name: TermName, | 94 | pub(crate) name: TermName, |
| 103 | pub(crate) starts_at: Timestamp, | 95 | pub(crate) starts_at: Timestamp, |
| 104 | pub(crate) ends_at: Timestamp, | 96 | pub(crate) ends_at: Timestamp, |
| 105 | - /// When a manager archived this term; `None` = open. `#[surreal(default)]` | 97 | + /// When a manager archived this term; `None` = open. The column is |
| 106 | - /// for the same reason `BankQuestion::subject` has one: rows written before | 98 | + /// nullable, so a term that predates archiving reads exactly like an |
| 107 | - /// the column existed still decode, as open terms. | 99 | + /// open one. |
| 108 | - #[surreal(default)] | ||
| 109 | pub(crate) archived_at: Option<Timestamp>, | 100 | pub(crate) archived_at: Option<Timestamp>, |
| 110 | } | 101 | } |
| 111 | 102 | ||
src/domain/text_fold.rsmodified+33 -30
| @@ -8,12 +8,12 @@ | |||
| 8 | //! conflate distinct letters (`tur` ≠ `tür`, `kir` ≠ `kır`). | 8 | //! conflate distinct letters (`tur` ≠ `tür`, `kir` ≠ `kır`). |
| 9 | //! | 9 | //! |
| 10 | //! The search fold is shared by the needle (Rust side) and the column | 10 | //! The search fold is shared by the needle (Rust side) and the column |
| 11 | -//! (SurrealQL side) so the two can never disagree. | 11 | +//! (PostgreSQL side) so the two can never disagree. |
| 12 | //! | 12 | //! |
| 13 | -//! Rust's `to_lowercase` and SurrealQL's `string::lowercase` are both | 13 | +//! Rust's `to_lowercase` and PostgreSQL's `lower()` are both |
| 14 | -//! locale-invariant: Turkish `İ` (U+0130) lowercases to `i` + U+0307 | 14 | +//! locale-invariant here: Turkish `İ` (U+0130) lowercases to `i` + U+0307 |
| 15 | -//! (combining dot above), so plain `string::lowercase(text) CONTAINS $q` never | 15 | +//! (combining dot above), so plain `lower(text) LIKE '%q%'` never matched |
| 16 | -//! matched `İSTANBUL` for a teacher who typed `istanbul`. Folding strips that | 16 | +//! `İSTANBUL` for a teacher who typed `istanbul`. Folding strips that |
| 17 | //! leftover dot and maps the Turkish letters onto their ASCII base, which also | 17 | //! leftover dot and maps the Turkish letters onto their ASCII base, which also |
| 18 | //! makes the search work in both directions (`istanbul` ↔ `İSTANBUL`, | 18 | //! makes the search work in both directions (`istanbul` ↔ `İSTANBUL`, |
| 19 | //! `ıgdır` ↔ `Iğdır`). | 19 | //! `ıgdır` ↔ `Iğdır`). |
| @@ -31,13 +31,13 @@ pub fn search_fold(text: &str) -> String { | |||
| 31 | folded | 31 | folded |
| 32 | } | 32 | } |
| 33 | 33 | ||
| 34 | -/// The same folding as a SurrealQL expression over `column`, for use inside a | 34 | +/// The same folding as a PostgreSQL expression over `column`, for use inside |
| 35 | -/// `WHERE`. `column` is always a literal field name we wrote — never user | 35 | +/// a `WHERE`. `column` is always a literal field name we wrote — never user |
| 36 | /// input. | 36 | /// input. |
| 37 | pub fn search_fold_sql(column: &str) -> String { | 37 | pub fn search_fold_sql(column: &str) -> String { |
| 38 | - let mut expr = format!("string::lowercase({column})"); | 38 | + let mut expr = format!("lower({column})"); |
| 39 | for (from, to) in TEXT_FOLD_REPLACEMENTS { | 39 | for (from, to) in TEXT_FOLD_REPLACEMENTS { |
| 40 | - expr = format!("string::replace({expr}, '{from}', '{to}')"); | 40 | + expr = format!("replace({expr}, '{from}', '{to}')"); |
| 41 | } | 41 | } |
| 42 | expr | 42 | expr |
| 43 | } | 43 | } |
| @@ -89,16 +89,37 @@ mod tests { | |||
| 89 | } | 89 | } |
| 90 | 90 | ||
| 91 | /// `search_fold` and `search_fold_sql` are one table, two consumers — the | 91 | /// `search_fold` and `search_fold_sql` are one table, two consumers — the |
| 92 | - /// SQL must emit a `string::replace` for every rule, or the column and the | 92 | + /// SQL must emit a `replace()` for every rule, or the column and the |
| 93 | /// needle drift apart and a search silently stops matching. | 93 | /// needle drift apart and a search silently stops matching. |
| 94 | #[test] | 94 | #[test] |
| 95 | fn sql_covers_every_replacement() { | 95 | fn sql_covers_every_replacement() { |
| 96 | let sql = search_fold_sql("name"); | 96 | let sql = search_fold_sql("name"); |
| 97 | assert_eq!( | 97 | assert_eq!( |
| 98 | - sql.matches("string::replace").count(), | 98 | + sql.matches("replace(").count(), |
| 99 | TEXT_FOLD_REPLACEMENTS.len(), | 99 | TEXT_FOLD_REPLACEMENTS.len(), |
| 100 | - "one string::replace per rule" | 100 | + "one replace() per rule" |
| 101 | ); | 101 | ); |
| 102 | + // The base is PostgreSQL's locale-invariant lower(), applied before | ||
| 103 | + // any letter folding, over the exact column named. | ||
| 104 | + assert!(sql.starts_with(&format!("lower({})", "name"))); | ||
| 105 | + } | ||
| 106 | + | ||
| 107 | + /// The expression folds a sample exactly like the Rust side does: same | ||
| 108 | + /// table, same order. (The old engine-checked variant of this test ran | ||
| 109 | + /// the SQL against a live store; the string shape above plus this fold | ||
| 110 | + /// pin the generator, and the live round-trip belongs to the integration | ||
| 111 | + /// suite.) | ||
| 112 | + #[test] | ||
| 113 | + fn sql_folding_mirrors_rust_folding_rules() { | ||
| 114 | + let sql = search_fold_sql("name"); | ||
| 115 | + for (from, to) in TEXT_FOLD_REPLACEMENTS { | ||
| 116 | + assert!( | ||
| 117 | + sql.contains(&format!("replace(")) | ||
| 118 | + && sql.contains(&format!("'{from}', '{to}'")), | ||
| 119 | + "rule {from} -> {to} missing from the emitted expression" | ||
| 120 | + ); | ||
| 121 | + assert_eq!(search_fold(&from.to_string()), to); | ||
| 122 | + } | ||
| 102 | } | 123 | } |
| 103 | 124 | ||
| 104 | /// The identity fold folds case (Turkish rules) and *nothing else* — the | 125 | /// The identity fold folds case (Turkish rules) and *nothing else* — the |
| @@ -137,22 +158,4 @@ mod tests { | |||
| 137 | // Decomposed `İ` (i + combining dot) is still plain `i`. | 158 | // Decomposed `İ` (i + combining dot) is still plain `i`. |
| 138 | assert_eq!(case_fold_tr("i\u{307}zin"), "izin"); | 159 | assert_eq!(case_fold_tr("i\u{307}zin"), "izin"); |
| 139 | } | 160 | } |
| 140 | - | ||
| 141 | - /// The SQL side must fold a literal exactly like the Rust side does, or the | ||
| 142 | - /// needle and the column disagree again. | ||
| 143 | - #[tokio::test] | ||
| 144 | - async fn sql_folding_matches_rust_folding() { | ||
| 145 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 146 | - for sample in ["İSTANBUL", "Iğdır", "ÇÖZÜM", "istanbul"] { | ||
| 147 | - let mut result = db | ||
| 148 | - .query(format!("RETURN {};", search_fold_sql("$text"))) | ||
| 149 | - .bind(("text", sample.to_string())) | ||
| 150 | - .await | ||
| 151 | - .unwrap() | ||
| 152 | - .check() | ||
| 153 | - .unwrap(); | ||
| 154 | - let got = result.take::<Option<String>>(0).unwrap().unwrap(); | ||
| 155 | - assert_eq!(got, search_fold(sample), "sql fold disagrees for {sample}"); | ||
| 156 | - } | ||
| 157 | - } | ||
| 158 | } | 161 | } |
src/domain/timestamp.rsmodified+22 -7
| @@ -1,9 +1,9 @@ | |||
| 1 | //! Time policy for the whole backend, in one place. | 1 | //! Time policy for the whole backend, in one place. |
| 2 | //! | 2 | //! |
| 3 | -//! - Every instant is a **unix-millisecond `i64`, always UTC** — stored as an | 3 | +//! - Every instant is a **unix-millisecond `i64`, always UTC** — stored as a |
| 4 | -//! `int`, sent over the wire as a plain number. No timezone is ever stored | 4 | +//! `BIGINT`, sent over the wire as a plain number. No timezone is ever |
| 5 | -//! or parsed, so the server's `TZ`, the client's locale, and the container's | 5 | +//! stored or parsed, so the server's `TZ`, the client's locale, and the |
| 6 | -//! clock configuration cannot change what a value means. | 6 | +//! container's clock configuration cannot change what a value means. |
| 7 | //! - [`Timestamp::now`] is the **only wall-clock read in the codebase**. The | 7 | //! - [`Timestamp::now`] is the **only wall-clock read in the codebase**. The |
| 8 | //! clippy `disallowed-methods` config (clippy.toml) rejects every other | 8 | //! clippy `disallowed-methods` config (clippy.toml) rejects every other |
| 9 | //! `now()` source (`chrono::Utc/Local`, `SystemTime`, `time::OffsetDateTime`) | 9 | //! `now()` source (`chrono::Utc/Local`, `SystemTime`, `time::OffsetDateTime`) |
| @@ -12,7 +12,6 @@ | |||
| 12 | //! `Instant` clock instead, which NTP adjustments cannot move backwards. | 12 | //! `Instant` clock instead, which NTP adjustments cannot move backwards. |
| 13 | 13 | ||
| 14 | use chrono::Datelike; | 14 | use chrono::Datelike; |
| 15 | -use surrealdb::types::SurrealValue; | ||
| 16 | 15 | ||
| 17 | use crate::constant::MILLIS_PER_DAY; | 16 | use crate::constant::MILLIS_PER_DAY; |
| 18 | use crate::error::{AppError, ValidationError}; | 17 | use crate::error::{AppError, ValidationError}; |
| @@ -27,8 +26,11 @@ pub(crate) fn range_error() -> AppError { | |||
| 27 | }) | 26 | }) |
| 28 | } | 27 | } |
| 29 | 28 | ||
| 30 | -/// A unix-millisecond instant (UTC by construction). Stored as an `int`. | 29 | +/// A unix-millisecond instant (UTC by construction). Stored as a `BIGINT`. |
| 31 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, SurrealValue)] | 30 | +/// Also serializes as its bare number: the fee plan's installments ride the |
| 31 | +/// row as JSON, and a due date must stay a plain millisecond count there too. | ||
| 32 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, sqlx::Type, serde::Serialize, serde::Deserialize)] | ||
| 33 | +#[sqlx(transparent)] | ||
| 32 | pub struct Timestamp(i64); | 34 | pub struct Timestamp(i64); |
| 33 | 35 | ||
| 34 | impl Timestamp { | 36 | impl Timestamp { |
| @@ -160,4 +162,17 @@ mod tests { | |||
| 160 | // boundary crossing between them would still satisfy `<=`. | 162 | // boundary crossing between them would still satisfy `<=`. |
| 161 | assert!(today <= from_millis); | 163 | assert!(today <= from_millis); |
| 162 | } | 164 | } |
| 165 | + | ||
| 166 | + /// JSON is part of the storage contract now (embedded installments ride a | ||
| 167 | + /// JSONB column): the instant must stay a bare millisecond number, never | ||
| 168 | + /// a string or an object. | ||
| 169 | + #[test] | ||
| 170 | + fn json_form_is_the_bare_millisecond_number() { | ||
| 171 | + assert_eq!( | ||
| 172 | + serde_json::to_value(Timestamp::from_millis(1_700_000_000_000)).unwrap(), | ||
| 173 | + serde_json::json!(1_700_000_000_000) | ||
| 174 | + ); | ||
| 175 | + let back: Timestamp = serde_json::from_value(serde_json::json!(1_700_000_000_000)).unwrap(); | ||
| 176 | + assert_eq!(back.as_millis(), 1_700_000_000_000); | ||
| 177 | + } | ||
| 163 | } | 178 | } |
src/domain/user.rsmodified+35 -33
| @@ -7,10 +7,10 @@ use std::sync::OnceLock; | |||
| 7 | 7 | ||
| 8 | use argon2::password_hash::phc::PasswordHash as PhcHash; | 8 | use argon2::password_hash::phc::PasswordHash as PhcHash; |
| 9 | use argon2::{Argon2, PasswordHasher, PasswordVerifier}; | 9 | use argon2::{Argon2, PasswordHasher, PasswordVerifier}; |
| 10 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 10 | +use uuid::Uuid; |
| 11 | 11 | ||
| 12 | -use crate::constant::{AI_PRINCIPAL_KEY, DECOY_PASSWORD, USER_TABLE}; | 12 | +use crate::constant::{AI_PRINCIPAL_KEY, DECOY_PASSWORD}; |
| 13 | -use crate::domain::monotonic_id::next_ulid; | 13 | +use crate::domain::monotonic_id::next_uuid; |
| 14 | use crate::domain::note_file::FileContentType; | 14 | use crate::domain::note_file::FileContentType; |
| 15 | use crate::domain::preferences::{Language, PaletteColor, Theme}; | 15 | use crate::domain::preferences::{Language, PaletteColor, Theme}; |
| 16 | use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; | 16 | use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; |
| @@ -18,33 +18,34 @@ use crate::domain::role::Role; | |||
| 18 | use crate::error::{AppError, ValidationError}; | 18 | use crate::error::{AppError, ValidationError}; |
| 19 | use crate::validate::{validate_password, validate_username}; | 19 | use crate::validate::{validate_password, validate_username}; |
| 20 | 20 | ||
| 21 | -/// Typed user record id (`user:<ulid>`). | 21 | +/// Typed user row id. A UUIDv7 minted by the process-wide monotonic |
| 22 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 22 | +/// generator, so `id` order is mint order. |
| 23 | -pub struct UserId(RecordId); | 23 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] |
| 24 | +#[sqlx(transparent)] | ||
| 25 | +pub struct UserId(Uuid); | ||
| 24 | 26 | ||
| 25 | impl UserId { | 27 | impl UserId { |
| 26 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 28 | + /// Minted from the process-wide monotonic generator, not a random v4: |
| 27 | - /// users list `id DESC` (newest first, [`crate::db::user::list_all`]) and page by | 29 | + /// users list `id DESC` (newest first, [`crate::db::user::list_all`]) and |
| 28 | - /// offset over that order, and a random low half scrambles rows minted in | 30 | + /// page by offset over that order, and a random low half scrambles rows |
| 29 | - /// the same millisecond. Not a secret: the session token is separate | 31 | + /// minted in the same millisecond. Not a secret: the session token is |
| 30 | - /// (32-byte CSPRNG, `web::auth`), so id order carries no authority. | 32 | + /// separate (32-byte CSPRNG, `web::auth`), so id order carries no |
| 33 | + /// authority. | ||
| 31 | pub fn generate() -> Self { | 34 | pub fn generate() -> Self { |
| 32 | - Self(RecordId::new(USER_TABLE, next_ulid().to_string())) | 35 | + Self(next_uuid()) |
| 33 | } | 36 | } |
| 34 | 37 | ||
| 38 | + /// Parse a wire key. A key that parses as no UUID — a malformed path | ||
| 39 | + /// segment — reads as the nil id, which matches no row: exactly the 404 a | ||
| 40 | + /// dangling record key produced under the old store, without turning a | ||
| 41 | + /// typo into a panic. | ||
| 35 | pub fn from_key(key: &str) -> Self { | 42 | pub fn from_key(key: &str) -> Self { |
| 36 | - Self(RecordId::new(USER_TABLE, key)) | 43 | + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) |
| 37 | } | 44 | } |
| 38 | 45 | ||
| 39 | - pub fn record(&self) -> RecordId { | 46 | + /// The hyphenated wire form. |
| 40 | - self.0.clone() | 47 | + pub fn key(&self) -> String { |
| 41 | - } | 48 | + self.0.to_string() |
| 42 | - | ||
| 43 | - pub fn key(&self) -> &str { | ||
| 44 | - match &self.0.key { | ||
| 45 | - RecordIdKey::String(key) => key, | ||
| 46 | - _ => "", | ||
| 47 | - } | ||
| 48 | } | 49 | } |
| 49 | } | 50 | } |
| 50 | 51 | ||
| @@ -52,7 +53,8 @@ impl UserId { | |||
| 52 | /// canonicalizes the value: the stored string is trimmed, since the unique | 53 | /// canonicalizes the value: the stored string is trimmed, since the unique |
| 53 | /// index and the login lookup key on it — `"ali "` must be `"ali"`, not a | 54 | /// index and the login lookup key on it — `"ali "` must be `"ali"`, not a |
| 54 | /// second, visually identical account. | 55 | /// second, visually identical account. |
| 55 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 56 | +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 57 | +#[sqlx(transparent)] | ||
| 56 | pub struct Username(String); | 58 | pub struct Username(String); |
| 57 | 59 | ||
| 58 | impl Username { | 60 | impl Username { |
| @@ -116,7 +118,8 @@ impl Password { | |||
| 116 | } | 118 | } |
| 117 | 119 | ||
| 118 | /// An argon2 PHC hash, safe to persist. | 120 | /// An argon2 PHC hash, safe to persist. |
| 119 | -#[derive(Debug, Clone, SurrealValue)] | 121 | +#[derive(Debug, Clone, sqlx::Type)] |
| 122 | +#[sqlx(transparent)] | ||
| 120 | pub struct PasswordHash(String); | 123 | pub struct PasswordHash(String); |
| 121 | 124 | ||
| 122 | /// A process-wide decoy hash, computed once on first use. Verifying against it | 125 | /// A process-wide decoy hash, computed once on first use. Verifying against it |
| @@ -189,7 +192,7 @@ impl PasswordHash { | |||
| 189 | } | 192 | } |
| 190 | } | 193 | } |
| 191 | 194 | ||
| 192 | -#[derive(Debug, Clone, SurrealValue)] | 195 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 193 | /// Fields are crate-visible: [`crate::db::user`] mints rows and the role | 196 | /// Fields are crate-visible: [`crate::db::user`] mints rows and the role |
| 194 | /// cascade reads the id, exactly as the other split domains do. | 197 | /// cascade reads the id, exactly as the other split domains do. |
| 195 | pub struct User { | 198 | pub struct User { |
| @@ -226,15 +229,14 @@ pub struct User { | |||
| 226 | impl User { | 229 | impl User { |
| 227 | /// The in-memory principal an AI service acts as over the QUIC bridge. | 230 | /// The in-memory principal an AI service acts as over the QUIC bridge. |
| 228 | /// | 231 | /// |
| 229 | - /// Never written to the database, and never read back from one: the id key | 232 | + /// Never written to the database, and never read back from one: the id is |
| 230 | - /// is the literal `"ai_service"`, which no minted row can collide with | 233 | + /// the nil UUID, which no minted id (always a v7) can ever equal. Every |
| 231 | - /// ([`UserId::generate`] only ever produces ULIDs). Every other field is | 234 | + /// other field is inert — the empty password hash parses as no argon2 hash, |
| 232 | - /// inert — the empty password hash parses as no argon2 hash, so it verifies | 235 | + /// so it verifies against nothing, and [`Role::Ai`] clears no `at_least` |
| 233 | - /// against nothing, and [`Role::Ai`] clears no `at_least` bar and fails | 236 | + /// bar and fails every exact `== Role::Student` / `== Role::Parent` gate. |
| 234 | - /// every exact `== Role::Student` / `== Role::Parent` gate. | ||
| 235 | pub(crate) fn ai_principal() -> User { | 237 | pub(crate) fn ai_principal() -> User { |
| 236 | User { | 238 | User { |
| 237 | - id: UserId::from_key(AI_PRINCIPAL_KEY), | 239 | + id: UserId(Uuid::nil()), |
| 238 | username: Username(AI_PRINCIPAL_KEY.to_string()), | 240 | username: Username(AI_PRINCIPAL_KEY.to_string()), |
| 239 | password_hash: PasswordHash(String::new()), | 241 | password_hash: PasswordHash(String::new()), |
| 240 | role: Role::Ai, | 242 | role: Role::Ai, |
| @@ -374,7 +376,7 @@ mod tests { | |||
| 374 | #[tokio::test] | 376 | #[tokio::test] |
| 375 | async fn user_id_key_roundtrips() { | 377 | async fn user_id_key_roundtrips() { |
| 376 | let id = UserId::generate(); | 378 | let id = UserId::generate(); |
| 377 | - let key = id.key().to_string(); | 379 | + let key = id.key(); |
| 378 | assert!(!key.is_empty()); | 380 | assert!(!key.is_empty()); |
| 379 | assert_eq!(UserId::from_key(&key).key(), key); | 381 | assert_eq!(UserId::from_key(&key).key(), key); |
| 380 | } | 382 | } |
src/domain/work_entry.rsmodified+25 -43
| @@ -1,58 +1,34 @@ | |||
| 1 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | +use uuid::Uuid; |
| 2 | 2 | ||
| 3 | -use crate::constant::WORK_ENTRY_TABLE; | 3 | +use crate::domain::monotonic_id::next_uuid; |
| 4 | -use crate::domain::monotonic_id::next_ulid; | ||
| 5 | use crate::domain::timestamp::Timestamp; | 4 | use crate::domain::timestamp::Timestamp; |
| 6 | use crate::domain::user::UserId; | 5 | use crate::domain::user::UserId; |
| 7 | -use crate::error::{AppError, ValidationError}; | ||
| 8 | 6 | ||
| 9 | -/// The one spelling of "this stint is inverted", shared by the handler's | 7 | +/// Typed work-entry row id. A UUIDv7 minted by the process-wide monotonic |
| 10 | -/// pre-flight check and the write-time `WHERE` guard that re-makes it against | 8 | +/// generator, so `id` order is mint order. |
| 11 | -/// the stored row. | 9 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] |
| 12 | -pub(crate) fn out_before_in_error() -> AppError { | 10 | +#[sqlx(transparent)] |
| 13 | - AppError::Validation(ValidationError::Invalid { | 11 | +pub struct WorkEntryId(Uuid); |
| 14 | - field: "check_out", | ||
| 15 | - reason: "must be at or after check_in", | ||
| 16 | - }) | ||
| 17 | -} | ||
| 18 | - | ||
| 19 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 20 | -pub struct WorkEntryId(RecordId); | ||
| 21 | 12 | ||
| 22 | impl WorkEntryId { | 13 | impl WorkEntryId { |
| 23 | - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: | 14 | + /// Minted from the process-wide monotonic generator, not a random v4: |
| 24 | /// the log sorts `check_in DESC, id DESC` and the id breaks the tie between | 15 | /// the log sorts `check_in DESC, id DESC` and the id breaks the tie between |
| 25 | - /// two stints checked in at the same instant. The `open_` key below never | 16 | + /// two stints checked in at the same instant. |
| 26 | - /// ties with itself (one open stint per user), so it needs no ordering. | ||
| 27 | pub fn generate() -> Self { | 17 | pub fn generate() -> Self { |
| 28 | - Self(RecordId::new(WORK_ENTRY_TABLE, next_ulid().to_string())) | 18 | + Self(next_uuid()) |
| 29 | - } | ||
| 30 | - | ||
| 31 | - /// The deterministic id of `user`'s *open* entry. At most one open stint | ||
| 32 | - /// per user holds by construction: checking in is a single `INSERT IGNORE` | ||
| 33 | - /// on this id (atomic — a second check-in changes nothing), and checking | ||
| 34 | - /// out atomically takes the row and re-files it under a ULID id. | ||
| 35 | - /// `open_` cannot collide with a ULID key (ULIDs are bare alphanumerics). | ||
| 36 | - pub fn open_for(user: &UserId) -> Self { | ||
| 37 | - Self(RecordId::new( | ||
| 38 | - WORK_ENTRY_TABLE, | ||
| 39 | - format!("open_{}", user.key()), | ||
| 40 | - )) | ||
| 41 | } | 19 | } |
| 42 | 20 | ||
| 21 | + /// Parse a wire key. A key that parses as no UUID — a malformed path | ||
| 22 | + /// segment — reads as the nil id, which matches no row: exactly the 404 a | ||
| 23 | + /// dangling record key produced under the old store, without turning a | ||
| 24 | + /// typo into a panic. | ||
| 43 | pub fn from_key(key: &str) -> Self { | 25 | pub fn from_key(key: &str) -> Self { |
| 44 | - Self(RecordId::new(WORK_ENTRY_TABLE, key)) | 26 | + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) |
| 45 | - } | ||
| 46 | - | ||
| 47 | - pub fn record(&self) -> RecordId { | ||
| 48 | - self.0.clone() | ||
| 49 | } | 27 | } |
| 50 | 28 | ||
| 51 | - pub fn key(&self) -> &str { | 29 | + /// The hyphenated wire form. |
| 52 | - match &self.0.key { | 30 | + pub fn key(&self) -> String { |
| 53 | - RecordIdKey::String(key) => key, | 31 | + self.0.to_string() |
| 54 | - _ => "", | ||
| 55 | - } | ||
| 56 | } | 32 | } |
| 57 | } | 33 | } |
| 58 | 34 | ||
| @@ -60,9 +36,15 @@ impl WorkEntryId { | |||
| 60 | /// `check_out` once closed. The wall clock is read server-side only — a | 36 | /// `check_out` once closed. The wall clock is read server-side only — a |
| 61 | /// client can never supply its own instants (managers correct closed entries | 37 | /// client can never supply its own instants (managers correct closed entries |
| 62 | /// through an explicit endpoint instead). | 38 | /// through an explicit endpoint instead). |
| 63 | -#[derive(Debug, Clone, SurrealValue)] | 39 | +/// |
| 40 | +/// "At most one open stint per staff member" is no longer carried by a | ||
| 41 | +/// deterministic key: it is a partial unique index on the table | ||
| 42 | +/// (`work_entry_open`) over rows whose `check_out` is NULL, so the database | ||
| 43 | +/// itself refuses a second check-in. | ||
| 44 | +#[derive(Debug, Clone, sqlx::FromRow)] | ||
| 64 | pub struct WorkEntry { | 45 | pub struct WorkEntry { |
| 65 | pub(crate) id: WorkEntryId, | 46 | pub(crate) id: WorkEntryId, |
| 47 | + #[sqlx(rename = "app_user")] | ||
| 66 | pub(crate) user: UserId, | 48 | pub(crate) user: UserId, |
| 67 | pub(crate) check_in: Timestamp, | 49 | pub(crate) check_in: Timestamp, |
| 68 | pub(crate) check_out: Option<Timestamp>, | 50 | pub(crate) check_out: Option<Timestamp>, |
src/error.rsmodified+51 -59
| @@ -93,48 +93,46 @@ pub enum AppError { | |||
| 93 | #[error("too many requests")] | 93 | #[error("too many requests")] |
| 94 | TooManyRequests { retry_after_secs: u64 }, | 94 | TooManyRequests { retry_after_secs: u64 }, |
| 95 | #[error("database error")] | 95 | #[error("database error")] |
| 96 | - Db(#[source] surrealdb::Error), | 96 | + Db(#[source] sqlx::Error), |
| 97 | - /// The database WebSocket dropped and is mid-reconnect. Covers a query in | 97 | + /// The pool refused before the statement ran: the pool timed out waiting |
| 98 | - /// flight when the socket died (the SDK fails it as a connection error) | 98 | + /// for a connection, was closed, or TLS to the server failed to come up. |
| 99 | - /// and a query racing the SDK's replay of session state (signin, | 99 | + /// Nothing executed, so a retry is safe. Transient, self-healing, |
| 100 | - /// namespace), which the server refuses before execution. Transient, | 100 | + /// retryable. |
| 101 | - /// self-healing, retryable. | ||
| 102 | #[error("database unavailable")] | 101 | #[error("database unavailable")] |
| 103 | DbUnavailable, | 102 | DbUnavailable, |
| 104 | - /// The request outran [`crate::constant::REQUEST_TIMEOUT_SECS`], which in | 103 | + /// The request outran [`crate::constant::REQUEST_TIMEOUT_SECS`], or the |
| 105 | - /// practice means it reached the database in the window between the socket | 104 | + /// connection it rode died mid-flight (Postgres reports that as an I/O |
| 106 | - /// dying and the keepalive noticing, and got parked in the SDK's queue. | 105 | + /// error, not a verdict). |
| 107 | /// | 106 | /// |
| 108 | - /// Deliberately NOT `DbUnavailable`: that one promises the query was | 107 | + /// Deliberately NOT `DbUnavailable`: that one promises the statement was |
| 109 | - /// refused before execution, so a retry is safe. A parked query is still | 108 | + /// refused before it executed, so a retry is safe. A request that died on |
| 110 | - /// queued and *does* execute once the socket heals (verified: pings | 109 | + /// the wire may still have applied server-side (the commit can race the |
| 111 | - /// abandoned during an outage all fire on reconnect), so retrying can | 110 | + /// connection dropping), so retrying can apply the same write twice. |
| 112 | - /// apply the same write twice. Same 503, honest message. | 111 | + /// Same 503, honest message. |
| 113 | #[error("request timed out")] | 112 | #[error("request timed out")] |
| 114 | DbTimeout, | 113 | DbTimeout, |
| 115 | #[error("internal error: {0}")] | 114 | #[error("internal error: {0}")] |
| 116 | Internal(String), | 115 | Internal(String), |
| 117 | } | 116 | } |
| 118 | 117 | ||
| 119 | -/// Is this database error a query refused during the SDK's post-reconnect | ||
| 120 | -/// session replay? Two signatures, matched narrowly: "Specify a namespace" | ||
| 121 | -/// (signin replayed, namespace not yet) and "Anonymous access not allowed" | ||
| 122 | -/// (signin not yet). The backend signs in as root, so neither can be a real | ||
| 123 | -/// authorization verdict — but a bare "Not enough permissions" could be, so | ||
| 124 | -/// that alone must never match. | ||
| 125 | -pub(crate) fn is_session_replay_error(message: &str) -> bool { | ||
| 126 | - message.contains("Specify a namespace") || message.contains("Anonymous access not allowed") | ||
| 127 | -} | ||
| 128 | 118 | ||
| 129 | -impl From<surrealdb::Error> for AppError { | 119 | +impl From<sqlx::Error> for AppError { |
| 130 | - fn from(e: surrealdb::Error) -> Self { | 120 | + fn from(e: sqlx::Error) -> Self { |
| 131 | - // `is_connection()`: the SDK's own verdict that the socket itself | 121 | + match e { |
| 132 | - // failed ("Connection reset", "WebSocket error: ..."). Structurally | 122 | + // A `fetch_one` that found nothing is the caller's 404, not a 500. |
| 133 | - // distinct from query/permission errors, so it can't misfile one. | 123 | + sqlx::Error::RowNotFound => AppError::NotFound, |
| 134 | - if e.is_connection() || is_session_replay_error(&e.to_string()) { | 124 | + // Pool problems refuse on the acquire path: nothing was queued, |
| 135 | - AppError::DbUnavailable | 125 | + // let alone executed, so a retry cannot double-apply a write. |
| 136 | - } else { | 126 | + sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed | sqlx::Error::Tls(_) => { |
| 137 | - AppError::Db(e) | 127 | + AppError::DbUnavailable |
| 128 | + } | ||
| 129 | + // A connection that died under a request. The statement may or | ||
| 130 | + // may not have applied — the honest, retry-unsafe 503. | ||
| 131 | + sqlx::Error::Io(_) => AppError::DbTimeout, | ||
| 132 | + // Everything else is a verdict (or a bug) the server returned — | ||
| 133 | + // refusals included; the helpers in [`crate::database`] read the | ||
| 134 | + // SQLSTATE off it. | ||
| 135 | + _ => AppError::Db(e), | ||
| 138 | } | 136 | } |
| 139 | } | 137 | } |
| 140 | } | 138 | } |
| @@ -291,26 +289,6 @@ impl AppError { | |||
| 291 | mod tests { | 289 | mod tests { |
| 292 | use super::*; | 290 | use super::*; |
| 293 | 291 | ||
| 294 | - #[test] | ||
| 295 | - fn replay_signatures_classify_as_unavailable() { | ||
| 296 | - // The two exact refusals a query racing the post-reconnect session | ||
| 297 | - // replay gets, as they appear in the wire error. | ||
| 298 | - assert!(is_session_replay_error("Specify a namespace to use")); | ||
| 299 | - assert!(is_session_replay_error( | ||
| 300 | - "Anonymous access not allowed: Not enough permissions to perform this action" | ||
| 301 | - )); | ||
| 302 | - } | ||
| 303 | - | ||
| 304 | - #[test] | ||
| 305 | - fn connection_errors_classify_as_unavailable() { | ||
| 306 | - // What the SDK fails an in-flight query with when the socket dies — | ||
| 307 | - // same wire error `clear_pending_requests` produces. | ||
| 308 | - let e = surrealdb::Error::connection( | ||
| 309 | - "Connection reset".to_string(), | ||
| 310 | - surrealdb::types::ConnectionError::ConnectionFailed, | ||
| 311 | - ); | ||
| 312 | - assert!(matches!(AppError::from(e), AppError::DbUnavailable)); | ||
| 313 | - } | ||
| 314 | 292 | ||
| 315 | /// The refusal a gated nest answers with. Both keys, and the `403` — a | 293 | /// The refusal a gated nest answers with. Both keys, and the `403` — a |
| 316 | /// client switches on `module`, so neither may drift. | 294 | /// client switches on `module`, so neither may drift. |
| @@ -328,14 +306,28 @@ mod tests { | |||
| 328 | } | 306 | } |
| 329 | 307 | ||
| 330 | #[test] | 308 | #[test] |
| 331 | - fn real_errors_stay_db_errors() { | 309 | + fn sqlx_errors_split_into_honest_classes() { |
| 332 | - // A genuine authorization verdict shares the suffix but must not match. | 310 | + use sqlx::Error; |
| 333 | - assert!(!is_session_replay_error( | 311 | + // Pool problems refuse on the acquire path: nothing executed, so a |
| 334 | - "Not enough permissions to perform this action" | 312 | + // retry is safe. |
| 313 | + assert!(matches!( | ||
| 314 | + AppError::from(Error::PoolTimedOut), | ||
| 315 | + AppError::DbUnavailable | ||
| 335 | )); | 316 | )); |
| 336 | - assert!(!is_session_replay_error("Parse error: unexpected token")); | 317 | + assert!(matches!( |
| 337 | - assert!(!is_session_replay_error( | 318 | + AppError::from(Error::PoolClosed), |
| 338 | - "Database index `user_username` already contains 'admin'" | 319 | + AppError::DbUnavailable |
| 339 | )); | 320 | )); |
| 321 | + assert!(matches!( | ||
| 322 | + AppError::from(Error::Tls("tls".into())), | ||
| 323 | + AppError::DbUnavailable | ||
| 324 | + )); | ||
| 325 | + // A connection that died under a request: the honest 503 — the write | ||
| 326 | + // may or may not have applied, so a retry is NOT advertised as safe. | ||
| 327 | + let io = std::io::Error::new(std::io::ErrorKind::ConnectionReset, "gone"); | ||
| 328 | + assert!(matches!(AppError::from(Error::Io(io)), AppError::DbTimeout)); | ||
| 329 | + // A query that found no row is the caller's 404, never a 500. | ||
| 330 | + assert!(matches!(AppError::from(Error::RowNotFound), AppError::NotFound)); | ||
| 340 | } | 331 | } |
| 332 | + | ||
| 341 | } | 333 | } |
src/lib.rsmodified+35 -43
| @@ -5,7 +5,6 @@ pub mod database; | |||
| 5 | pub mod db; | 5 | pub mod db; |
| 6 | pub mod domain; | 6 | pub mod domain; |
| 7 | pub mod error; | 7 | pub mod error; |
| 8 | -pub mod migration_sql; | ||
| 9 | pub mod module; | 8 | pub mod module; |
| 10 | pub mod rate_limit; | 9 | pub mod rate_limit; |
| 11 | pub mod service; | 10 | pub mod service; |
| @@ -219,12 +218,8 @@ pub fn build_router(state: AppState) -> Router { | |||
| 219 | // Every tier's budget outlives the process it was spent in (see | 218 | // Every tier's budget outlives the process it was spent in (see |
| 220 | // [`rate_limit::RateLimiter::share`]). The chatbot tier is shared here too | 219 | // [`rate_limit::RateLimiter::share`]). The chatbot tier is shared here too |
| 221 | // rather than in `main`, so a router built anywhere gets the same behaviour. | 220 | // rather than in `main`, so a router built anywhere gets the same behaviour. |
| 222 | - api_limiter.share("api", state.db.clone(), state.db_up.clone()); | 221 | + api_limiter.share("api", state.db.clone()); |
| 223 | - state | 222 | + state.chatbot_limit.share("chatbot", state.db.clone()); |
| 224 | - .chatbot_limit | ||
| 225 | - .share("chatbot", state.db.clone(), state.db_up.clone()); | ||
| 226 | - | ||
| 227 | - let db_up = state.db_up.clone(); | ||
| 228 | let metrics = state.metrics.clone(); | 223 | let metrics = state.metrics.clone(); |
| 229 | 224 | ||
| 230 | let cors_allowlist = cors_allowlist_from_env(); | 225 | let cors_allowlist = cors_allowlist_from_env(); |
| @@ -242,13 +237,12 @@ pub fn build_router(state: AppState) -> Router { | |||
| 242 | // request from a service is not a browser request from an IP: it has no | 237 | // request from a service is not a browser request from an IP: it has no |
| 243 | // client address to bill the per-IP limiter (it would drain the shared | 238 | // client address to bill the per-IP limiter (it would drain the shared |
| 244 | // unknown-client budget), and `ETag`/CORS are browser concerns. Skipping the | 239 | // unknown-client budget), and `ETag`/CORS are browser concerns. Skipping the |
| 245 | - // layers means skipping the db guard too, so the bridge runs the liveness | 240 | + // layers means skipping the request deadline too, so the bridge applies the |
| 246 | - // check and the request timeout itself (see `ai::server`). | 241 | + // same deadline to its own dispatch (see `ai::server`). |
| 247 | if let Some(ai) = &state.ai { | 242 | if let Some(ai) = &state.ai { |
| 248 | ai.arm_api( | 243 | ai.arm_api( |
| 249 | service.clone(), | 244 | service.clone(), |
| 250 | state.tenants.clone(), | 245 | state.tenants.clone(), |
| 251 | - state.db_up.clone(), | ||
| 252 | state.files_path.clone(), | 246 | state.files_path.clone(), |
| 253 | metrics.clone(), | 247 | metrics.clone(), |
| 254 | ); | 248 | ); |
| @@ -259,10 +253,7 @@ pub fn build_router(state: AppState) -> Router { | |||
| 259 | // matching `If-None-Match`. Innermost, so it sees the handler's own | 253 | // matching `If-None-Match`. Innermost, so it sees the handler's own |
| 260 | // response (mutations and errors pass straight through untouched). | 254 | // response (mutations and errors pass straight through untouched). |
| 261 | .layer(middleware::from_fn(web::etag::etag)) | 255 | .layer(middleware::from_fn(web::etag::etag)) |
| 262 | - .layer(middleware::from_fn(move |req: Request, next: Next| { | 256 | + .layer(middleware::from_fn(request_timeout)) |
| 263 | - let health = db_up.clone(); | ||
| 264 | - async move { db_guard(health, req, next).await } | ||
| 265 | - })) | ||
| 266 | .layer(middleware::from_fn(move |req: Request, next: Next| { | 257 | .layer(middleware::from_fn(move |req: Request, next: Next| { |
| 267 | let limiter = api_limiter.clone(); | 258 | let limiter = api_limiter.clone(); |
| 268 | async move { limiter.enforce(req, next).await } | 259 | async move { limiter.enforce(req, next).await } |
| @@ -463,39 +454,32 @@ impl Drop for InFlight<'_> { | |||
| 463 | } | 454 | } |
| 464 | } | 455 | } |
| 465 | 456 | ||
| 466 | -/// Refuse work the database cannot currently do, and cap how long any request | 457 | +/// Cap how long any request may wait on the database. The deadline covers both |
| 467 | -/// may wait on it. | 458 | +/// the pool wait for a connection and the query run on it. |
| 468 | -/// | ||
| 469 | -/// Both halves exist because a query issued while the database socket is down | ||
| 470 | -/// never fails — the SDK parks it until the connection returns, so without a | ||
| 471 | -/// guard a handler waits out the entire outage holding a connection open. | ||
| 472 | /// | 459 | /// |
| 473 | -/// Order matters. The liveness check comes first and is the honest path: it | 460 | +/// The health half this guard used to carry is gone with the engine that |
| 474 | -/// answers before the request touches the database, so nothing is queued and | 461 | +/// needed it: a sqlx query issued on a dead pool fails with an error instead |
| 475 | -/// the caller's retry cannot double-apply a write. The timeout only catches | 462 | +/// of being parked until the socket returns, so there is no known-outage |
| 476 | -/// requests that slipped through in the window between the socket dying and | 463 | +/// verdict to publish and no queued work to refuse up front. What stays is |
| 477 | -/// the keepalive noticing — those are already queued, hence the weaker | 464 | +/// the honest [`AppError::DbTimeout`] semantics: a request that outlives the |
| 478 | -/// [`AppError::DbTimeout`] verdict. | 465 | +/// deadline may or may not have applied its write, so a caller must not |
| 466 | +/// blind-retry it. | ||
| 479 | /// | 467 | /// |
| 480 | /// Long-lived responses are unaffected: a WebSocket upgrade and an SSE stream | 468 | /// Long-lived responses are unaffected: a WebSocket upgrade and an SSE stream |
| 481 | /// both return their response immediately and do the work afterwards, so | 469 | /// both return their response immediately and do the work afterwards, so |
| 482 | /// neither is measured against the timeout. | 470 | /// neither is measured against the timeout. |
| 483 | -async fn db_guard(health: state::DbHealth, req: Request, next: Next) -> Response { | 471 | +async fn request_timeout(req: Request, next: Next) -> Response { |
| 484 | // `/limits` never touches the database — it serializes constants and this | 472 | // `/limits` never touches the database — it serializes constants and this |
| 485 | - // process's own configuration. Refusing it during an outage would be a | 473 | + // process's own configuration. Holding it to the deadline would be a pure |
| 486 | - // pure own-goal: a frontend booting into a degraded backend is exactly | 474 | + // own-goal: a frontend booting into a degraded backend is exactly when it |
| 487 | - // when it needs the validation contract, and answering `503` would push it | 475 | + // needs the validation contract. `/health` and its `/` mirror are exempt |
| 488 | - // back to the hard-coded copy this endpoint exists to delete. | 476 | + // for the same reason and one more: their own probe is bounded at 2s, far |
| 489 | - // `/health` and its `/` mirror are exempt for the same reason and one | 477 | + // inside this deadline, and the generic timeout body would replace the |
| 490 | - // more: refusing them with the guard's own 503 would replace the probe's | 478 | + // probe's answer ("degraded, the database is down") with one that names |
| 491 | - // answer ("degraded, the database is down") with a generic body that names | 479 | + // nothing. |
| 492 | - // nothing. They read the keepalive's verdict and touch no database. | ||
| 493 | if matches!(req.uri().path(), "/limits" | "/health" | "/") { | 480 | if matches!(req.uri().path(), "/limits" | "/health" | "/") { |
| 494 | return next.run(req).await; | 481 | return next.run(req).await; |
| 495 | } | 482 | } |
| 496 | - if !health.is_up() { | ||
| 497 | - return AppError::DbUnavailable.into_response(); | ||
| 498 | - } | ||
| 499 | let timeout = std::time::Duration::from_secs(constant::REQUEST_TIMEOUT_SECS); | 483 | let timeout = std::time::Duration::from_secs(constant::REQUEST_TIMEOUT_SECS); |
| 500 | match tokio::time::timeout(timeout, next.run(req)).await { | 484 | match tokio::time::timeout(timeout, next.run(req)).await { |
| 501 | Ok(response) => response, | 485 | Ok(response) => response, |
| @@ -561,7 +545,7 @@ struct HealthResponse { | |||
| 561 | /// one is not (today: the database). | 545 | /// one is not (today: the database). |
| 562 | #[schema(example = "ok")] | 546 | #[schema(example = "ok")] |
| 563 | status: &'static str, | 547 | status: &'static str, |
| 564 | - /// Did the database socket answer its last keepalive ping? | 548 | + /// Did the bounded database probe (`SELECT 1`) answer? |
| 565 | #[schema(example = "up")] | 549 | #[schema(example = "up")] |
| 566 | db: &'static str, | 550 | db: &'static str, |
| 567 | /// The optional AI bridge (see the `ai` tag). | 551 | /// The optional AI bridge (see the `ai` tag). |
| @@ -580,9 +564,10 @@ struct AiHealth { | |||
| 580 | 564 | ||
| 581 | /// Health probe: the database verdict and the AI bridge, `503` when degraded. | 565 | /// Health probe: the database verdict and the AI bridge, `503` when degraded. |
| 582 | /// | 566 | /// |
| 583 | -/// Answers even while the database is down — it reads the keepalive's verdict | 567 | +/// Probes the database with a `SELECT 1` bounded to 2s — far inside the |
| 584 | -/// and touches nothing — which is the whole point: a probe that 503s with an | 568 | +/// request deadline — so a dead or wedged database answers `503` with a body |
| 585 | -/// empty body says "down" without saying what is down. | 569 | +/// that says what is down, instead of the poll hanging on a full request |
| 570 | +/// timeout. | ||
| 586 | #[utoipa::path( | 571 | #[utoipa::path( |
| 587 | get, | 572 | get, |
| 588 | path = "/health", | 573 | path = "/health", |
| @@ -593,7 +578,14 @@ struct AiHealth { | |||
| 593 | ), | 578 | ), |
| 594 | )] | 579 | )] |
| 595 | async fn health(axum::extract::State(state): axum::extract::State<AppState>) -> Response { | 580 | async fn health(axum::extract::State(state): axum::extract::State<AppState>) -> Response { |
| 596 | - let up = state.db_up.is_up(); | 581 | + let up = matches!( |
| 582 | + tokio::time::timeout( | ||
| 583 | + std::time::Duration::from_secs(2), | ||
| 584 | + sqlx::query("SELECT 1").execute(&state.db), | ||
| 585 | + ) | ||
| 586 | + .await, | ||
| 587 | + Ok(Ok(_)) | ||
| 588 | + ); | ||
| 597 | let status = if up { | 589 | let status = if up { |
| 598 | axum::http::StatusCode::OK | 590 | axum::http::StatusCode::OK |
| 599 | } else { | 591 | } else { |
src/main.rsmodified+1 -77
| @@ -1,8 +1,7 @@ | |||
| 1 | use anyhow::Context; | 1 | use anyhow::Context; |
| 2 | use hezarfen_backend::config::Config; | 2 | use hezarfen_backend::config::Config; |
| 3 | -use hezarfen_backend::database::Database; | ||
| 4 | use hezarfen_backend::rate_limit::UserRateLimiter; | 3 | use hezarfen_backend::rate_limit::UserRateLimiter; |
| 5 | -use hezarfen_backend::state::{AppState, DbHealth}; | 4 | +use hezarfen_backend::state::AppState; |
| 6 | use hezarfen_backend::{build_router, database}; | 5 | use hezarfen_backend::{build_router, database}; |
| 7 | 6 | ||
| 8 | #[tokio::main] | 7 | #[tokio::main] |
| @@ -29,10 +28,6 @@ async fn main() -> anyhow::Result<()> { | |||
| 29 | // all of it idempotent and unconditional on every boot. School databases | 28 | // all of it idempotent and unconditional on every boot. School databases |
| 30 | // come up lazily, one connection each, on first use. | 29 | // come up lazily, one connection each, on first use. |
| 31 | let tenants = database::init(&cfg).await?; | 30 | let tenants = database::init(&cfg).await?; |
| 32 | - let db_up = DbHealth::default(); | ||
| 33 | - // The control connection is the one every request touches (the school | ||
| 34 | - // lookup rides it), so it is the socket worth watching. | ||
| 35 | - keepalive(tenants.control().clone(), db_up.clone()); | ||
| 36 | tokio::fs::create_dir_all(&cfg.files_path) | 31 | tokio::fs::create_dir_all(&cfg.files_path) |
| 37 | .await | 32 | .await |
| 38 | .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?; | 33 | .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?; |
| @@ -46,7 +41,6 @@ async fn main() -> anyhow::Result<()> { | |||
| 46 | chatbot_limit: UserRateLimiter::per_user_minute(cfg.chatbot_per_minute), | 41 | chatbot_limit: UserRateLimiter::per_user_minute(cfg.chatbot_per_minute), |
| 47 | exam_presence: Default::default(), | 42 | exam_presence: Default::default(), |
| 48 | board_hub: Default::default(), | 43 | board_hub: Default::default(), |
| 49 | - db_up, | ||
| 50 | ai, | 44 | ai, |
| 51 | metrics, | 45 | metrics, |
| 52 | }); | 46 | }); |
| @@ -66,76 +60,6 @@ async fn main() -> anyhow::Result<()> { | |||
| 66 | Ok(()) | 60 | Ok(()) |
| 67 | } | 61 | } |
| 68 | 62 | ||
| 69 | -/// Ping the database forever so the WebSocket never sits idle long enough to | ||
| 70 | -/// be dropped, and publish each verdict to `health` so the request guard can | ||
| 71 | -/// refuse callers while the socket is down. | ||
| 72 | -/// | ||
| 73 | -/// The ping needs its own deadline. A query issued while the socket is down | ||
| 74 | -/// does not fail — the SDK parks it until the connection returns, so an | ||
| 75 | -/// un-deadlined ping hangs exactly as long as the outage and never reports the | ||
| 76 | -/// outage it exists to detect. | ||
| 77 | -fn keepalive(db: Database, health: DbHealth) { | ||
| 78 | - tokio::spawn(async move { | ||
| 79 | - let mut interval = tokio::time::interval(std::time::Duration::from_secs( | ||
| 80 | - hezarfen_backend::constant::DB_KEEPALIVE_INTERVAL_SECS, | ||
| 81 | - )); | ||
| 82 | - interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); | ||
| 83 | - let ping_timeout = | ||
| 84 | - std::time::Duration::from_secs(hezarfen_backend::constant::DB_PING_TIMEOUT_SECS); | ||
| 85 | - let metrics = hezarfen_backend::telemetry::Metrics::global(); | ||
| 86 | - // The transitions are what an operator is paged about; a line per tick | ||
| 87 | - // would bury them. `None` until the first verdict, so that one always | ||
| 88 | - // announces itself. | ||
| 89 | - let mut was_up: Option<bool> = None; | ||
| 90 | - let mut down_since: Option<tokio::time::Instant> = None; | ||
| 91 | - loop { | ||
| 92 | - interval.tick().await; | ||
| 93 | - // corner-cut: an abandoned ping stays queued in the SDK and replays | ||
| 94 | - // when the socket heals, so a long outage lands a burst of no-op | ||
| 95 | - // `RETURN 1`s on recovery. Harmless; probe over a raw TCP dial | ||
| 96 | - // instead if that burst ever shows up in a profile. | ||
| 97 | - let started = tokio::time::Instant::now(); | ||
| 98 | - let outcome = tokio::time::timeout(ping_timeout, db.query("RETURN 1")).await; | ||
| 99 | - let elapsed = started.elapsed(); | ||
| 100 | - metrics.db_ping_duration.record(elapsed.as_secs_f64(), &[]); | ||
| 101 | - let up = match &outcome { | ||
| 102 | - Ok(Ok(_)) => { | ||
| 103 | - tracing::debug!("database keepalive ping ok"); | ||
| 104 | - true | ||
| 105 | - } | ||
| 106 | - Ok(Err(err)) => { | ||
| 107 | - tracing::debug!("database keepalive ping failed: {err}"); | ||
| 108 | - false | ||
| 109 | - } | ||
| 110 | - Err(_) => { | ||
| 111 | - tracing::debug!("database keepalive ping timed out"); | ||
| 112 | - false | ||
| 113 | - } | ||
| 114 | - }; | ||
| 115 | - health.set(up); | ||
| 116 | - metrics.db_up.record(u64::from(up), &[]); | ||
| 117 | - match (was_up, up) { | ||
| 118 | - // The first verdict announces itself either way, so an operator | ||
| 119 | - // reading the log can tell "healthy since boot" from "we never | ||
| 120 | - // logged anything yet". | ||
| 121 | - (None, true) => tracing::info!(db_up = true, "database reachable"), | ||
| 122 | - (Some(true) | None, false) => { | ||
| 123 | - down_since = Some(started); | ||
| 124 | - tracing::warn!("database is down: the keepalive ping did not answer"); | ||
| 125 | - } | ||
| 126 | - (Some(false), true) => { | ||
| 127 | - let outage_secs = down_since | ||
| 128 | - .take() | ||
| 129 | - .map_or(0.0, |since| since.elapsed().as_secs_f64()); | ||
| 130 | - tracing::warn!(outage_secs, "database is back"); | ||
| 131 | - } | ||
| 132 | - _ => {} | ||
| 133 | - } | ||
| 134 | - was_up = Some(up); | ||
| 135 | - } | ||
| 136 | - }); | ||
| 137 | -} | ||
| 138 | - | ||
| 139 | /// Resolve on SIGINT (Ctrl-C) or SIGTERM. As PID 1 in a container the process | 63 | /// Resolve on SIGINT (Ctrl-C) or SIGTERM. As PID 1 in a container the process |
| 140 | /// gets no default signal handling, so without this a `podman stop` waits out | 64 | /// gets no default signal handling, so without this a `podman stop` waits out |
| 141 | /// its grace period and SIGKILLs us — dropping in-flight requests mid-write. | 65 | /// its grace period and SIGKILLs us — dropping in-flight requests mid-write. |
src/migration_sql.rsdeleted+0 -1524
| @@ -1,1524 +0,0 @@ | |||
| 1 | -//! The boot migration, as SurrealQL text. | ||
| 2 | -//! | ||
| 3 | -//! Split out of [`crate::constant`] purely for size: these three batches are | ||
| 4 | -//! ~700 lines of schema, and left in the constants file they buried the | ||
| 5 | -//! validation bounds that file exists to hold. Nothing else changed — they are | ||
| 6 | -//! still `pub const`, still the only migration text, and | ||
| 7 | -//! [`crate::database::migrate`] still reads [`MIGRATION_BATCHES`] and nothing | ||
| 8 | -//! else. | ||
| 9 | -//! | ||
| 10 | -//! Numbers stay in `constant.rs`: `tests/limits_completeness.rs` sweeps `src/` | ||
| 11 | -//! for stray bounds, and a bound hidden here would reach neither `GET /limits` | ||
| 12 | -//! nor the OpenAPI spec. Only SurrealQL strings live in this file. | ||
| 13 | - | ||
| 14 | -/// Repairs that must run *before* the DDL batch, because the DDL is what makes | ||
| 15 | -/// them impossible. | ||
| 16 | -/// | ||
| 17 | -/// `MIGRATION` retires `exam_question.source_bank` with `REMOVE FIELD`, and | ||
| 18 | -/// once the column is gone SCHEMAFULL rejects every write to a row that still | ||
| 19 | -/// stores it ("Found field 'source_bank', but no such field exists") — an | ||
| 20 | -/// UNSET included. So the value has to go while its definition is still | ||
| 21 | -/// standing. Runs as its own query for the usual reason (see `MIGRATION`). | ||
| 22 | -/// | ||
| 23 | -/// `chatbot_message.claimed_by` / `claimed_at` (retired 2026-07-30 with the | ||
| 24 | -/// chat claim queue) are the same story, one table over. | ||
| 25 | -/// | ||
| 26 | -/// The table-exists guard is load-bearing: on a fresh database `MIGRATION` has | ||
| 27 | -/// not run yet, and an UPDATE against an undefined table is an error, not an | ||
| 28 | -/// empty result. On a database that has the table but never had the column the | ||
| 29 | -/// `WHERE` simply matches nothing. | ||
| 30 | -pub const PRE_REPAIR: &str = " | ||
| 31 | - IF 'exam_question' IN object::keys((INFO FOR DB).tables) { | ||
| 32 | - UPDATE exam_question UNSET source_bank WHERE source_bank != NONE | ||
| 33 | - }; | ||
| 34 | - IF 'chatbot_message' IN object::keys((INFO FOR DB).tables) { | ||
| 35 | - UPDATE chatbot_message UNSET claimed_by, claimed_at | ||
| 36 | - WHERE claimed_by != NONE OR claimed_at != NONE | ||
| 37 | - }; | ||
| 38 | -"; | ||
| 39 | - | ||
| 40 | -/// SCHEMAFULL schema: every column is typed, references use `record<..>`. | ||
| 41 | -/// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the | ||
| 42 | -/// definitions and `REMOVE ... IF EXISTS` retires schema (like the | ||
| 43 | -/// single-attempt unique index) exactly once. DDL only — data backfills live | ||
| 44 | -/// in `BACKFILL`, which runs as a *separate* query: statements inside one | ||
| 45 | -/// batch see the schema as it stood when the batch started, so an UPDATE next | ||
| 46 | -/// to a fresh `DEFINE FIELD audience.*` writes against the old field set and | ||
| 47 | -/// SCHEMAFULL silently strips the very keys being backfilled. | ||
| 48 | -pub const MIGRATION: &str = " | ||
| 49 | - DEFINE TABLE IF NOT EXISTS user SCHEMAFULL; | ||
| 50 | - DEFINE FIELD IF NOT EXISTS username ON user TYPE string; | ||
| 51 | - DEFINE FIELD IF NOT EXISTS password_hash ON user TYPE string; | ||
| 52 | - DEFINE FIELD IF NOT EXISTS role ON user TYPE string DEFAULT 'student'; | ||
| 53 | - DEFINE FIELD IF NOT EXISTS name ON user TYPE option<string>; | ||
| 54 | - DEFINE FIELD IF NOT EXISTS surname ON user TYPE option<string>; | ||
| 55 | - DEFINE FIELD IF NOT EXISTS email ON user TYPE option<string>; | ||
| 56 | - DEFINE FIELD IF NOT EXISTS phone ON user TYPE option<string>; | ||
| 57 | - DEFINE FIELD IF NOT EXISTS birth_date ON user TYPE option<string>; | ||
| 58 | - DEFINE FIELD IF NOT EXISTS theme ON user TYPE option<string>; | ||
| 59 | - DEFINE FIELD IF NOT EXISTS language ON user TYPE option<string>; | ||
| 60 | - DEFINE FIELD IF NOT EXISTS palette_color ON user TYPE option<string>; | ||
| 61 | - DEFINE FIELD IF NOT EXISTS display_name ON user TYPE option<string>; | ||
| 62 | - DEFINE FIELD IF NOT EXISTS bio ON user TYPE option<string>; | ||
| 63 | - DEFINE FIELD IF NOT EXISTS avatar_file ON user TYPE option<string>; | ||
| 64 | - DEFINE FIELD IF NOT EXISTS avatar_content_type ON user TYPE option<string>; | ||
| 65 | - DEFINE FIELD IF NOT EXISTS avatar_size ON user TYPE option<int>; | ||
| 66 | - DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option<int>; | ||
| 67 | - DEFINE FIELD IF NOT EXISTS board_count ON user TYPE option<int>; | ||
| 68 | - -- Lifetime badge counters (2026-08-04). Not caps and never released: each | ||
| 69 | - -- counts something the student *did*, so a badge earned off one stands even | ||
| 70 | - -- if the counter later drops. `option<int>` and absent reads as zero, so a | ||
| 71 | - -- row written before them needs no repair to be *readable* — but it does | ||
| 72 | - -- need one to be *right*, which is what the BACKFILL seeding is for. | ||
| 73 | - DEFINE FIELD IF NOT EXISTS homework_submitted_total ON user TYPE option<int>; | ||
| 74 | - DEFINE FIELD IF NOT EXISTS homework_on_time_total ON user TYPE option<int>; | ||
| 75 | - DEFINE FIELD IF NOT EXISTS exam_sat_total ON user TYPE option<int>; | ||
| 76 | - DEFINE FIELD IF NOT EXISTS pomodoro_finished_total ON user TYPE option<int>; | ||
| 77 | - DEFINE FIELD IF NOT EXISTS pomodoro_focus_ms_total ON user TYPE option<int>; | ||
| 78 | - -- Pass 3 (2026-08-04): the staff-side counters, two more student ones, and | ||
| 79 | - -- the study streak. `study_streak_longest` is the badge counter; the other | ||
| 80 | - -- two streak columns are bookkeeping the write site needs to compute it and | ||
| 81 | - -- are read by nothing else. Definitions only — the seeding of the | ||
| 82 | - -- row-derivable ones is a BACKFILL under its own migration mark, never in | ||
| 83 | - -- this batch (same-batch DDL + backfill reads a stale schema). | ||
| 84 | - DEFINE FIELD IF NOT EXISTS marks_given_total ON user TYPE option<int>; | ||
| 85 | - DEFINE FIELD IF NOT EXISTS lessons_held_total ON user TYPE option<int>; | ||
| 86 | - DEFINE FIELD IF NOT EXISTS pool_approved_total ON user TYPE option<int>; | ||
| 87 | - DEFINE FIELD IF NOT EXISTS pool_published_total ON user TYPE option<int>; | ||
| 88 | - DEFINE FIELD IF NOT EXISTS lessons_attended_total ON user TYPE option<int>; | ||
| 89 | - DEFINE FIELD IF NOT EXISTS high_mark_total ON user TYPE option<int>; | ||
| 90 | - DEFINE FIELD IF NOT EXISTS study_streak_longest ON user TYPE option<int>; | ||
| 91 | - DEFINE FIELD IF NOT EXISTS study_streak_current ON user TYPE option<int>; | ||
| 92 | - DEFINE FIELD IF NOT EXISTS study_streak_last_day ON user TYPE option<int>; | ||
| 93 | - -- The counted-stint quota (2026-08-05): which UTC day the student last had | ||
| 94 | - -- a pomodoro stint counted on, and how many counted that day. Bookkeeping | ||
| 95 | - -- for the daily cap, read by nothing else; absent reads as no day yet, | ||
| 96 | - -- which is what makes the first finish after this deploy open a fresh | ||
| 97 | - -- bucket with no backfill. | ||
| 98 | - DEFINE FIELD IF NOT EXISTS pomodoro_counted_day ON user TYPE option<int>; | ||
| 99 | - DEFINE FIELD IF NOT EXISTS pomodoro_counted_today ON user TYPE option<int>; | ||
| 100 | - DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; | ||
| 101 | - | ||
| 102 | - DEFINE TABLE IF NOT EXISTS session SCHEMAFULL; | ||
| 103 | - DEFINE FIELD IF NOT EXISTS user ON session TYPE record<user>; | ||
| 104 | - DEFINE FIELD IF NOT EXISTS token ON session TYPE string; | ||
| 105 | - DEFINE FIELD IF NOT EXISTS expires_at ON session TYPE int; | ||
| 106 | - DEFINE INDEX IF NOT EXISTS session_token ON session FIELDS token UNIQUE; | ||
| 107 | - DEFINE INDEX IF NOT EXISTS session_expires ON session FIELDS expires_at; | ||
| 108 | - | ||
| 109 | - DEFINE TABLE IF NOT EXISTS note SCHEMAFULL; | ||
| 110 | - DEFINE FIELD IF NOT EXISTS user ON note TYPE record<user>; | ||
| 111 | - DEFINE FIELD IF NOT EXISTS title ON note TYPE string; | ||
| 112 | - DEFINE FIELD IF NOT EXISTS content ON note TYPE string; | ||
| 113 | - DEFINE FIELD IF NOT EXISTS file_count ON note TYPE option<int>; | ||
| 114 | - DEFINE INDEX IF NOT EXISTS note_user ON note FIELDS user; | ||
| 115 | - | ||
| 116 | - DEFINE TABLE IF NOT EXISTS message SCHEMAFULL; | ||
| 117 | - DEFINE FIELD IF NOT EXISTS sender ON message TYPE record<user>; | ||
| 118 | - DEFINE FIELD IF NOT EXISTS recipient ON message TYPE record<user>; | ||
| 119 | - DEFINE FIELD IF NOT EXISTS subject ON message TYPE string; | ||
| 120 | - DEFINE FIELD IF NOT EXISTS body ON message TYPE string; | ||
| 121 | - DEFINE FIELD IF NOT EXISTS label ON message TYPE option<string>; | ||
| 122 | - DEFINE FIELD IF NOT EXISTS sent_at ON message TYPE int; | ||
| 123 | - DEFINE FIELD IF NOT EXISTS read ON message TYPE bool DEFAULT false; | ||
| 124 | - DEFINE FIELD IF NOT EXISTS sender_folder ON message TYPE string DEFAULT 'sent'; | ||
| 125 | - DEFINE FIELD IF NOT EXISTS recipient_folder ON message TYPE string DEFAULT 'inbox'; | ||
| 126 | - -- Where each side's copy sat before it was filed into archive/trash, so a | ||
| 127 | - -- restore lands where it came from. NONE while the copy is in its home | ||
| 128 | - -- folder — and on rows filed before this field existed (2026-07-23), which | ||
| 129 | - -- restore to the home folder just as they always did. | ||
| 130 | - DEFINE FIELD IF NOT EXISTS sender_origin ON message TYPE option<string>; | ||
| 131 | - DEFINE FIELD IF NOT EXISTS recipient_origin ON message TYPE option<string>; | ||
| 132 | - DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender; | ||
| 133 | - DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient; | ||
| 134 | - | ||
| 135 | - -- Collaborative whiteboard (2026-07-31): one `board` is a room, one | ||
| 136 | - -- `board_stroke` is one append-only mark. A clear NEVER deletes — it bumps | ||
| 137 | - -- `epoch`, so the canvas empties while the whole history stays replayable. | ||
| 138 | - -- `locked` is a plain bool, not an option: the open-board guard asks for | ||
| 139 | - -- `locked = false`, which a NONE would never match. `locked_by`/`locked_at`/ | ||
| 140 | - -- `closed_at` are three top-level option columns rather than one nested | ||
| 141 | - -- object, because SurrealDB 3 drops an object key valued NONE. | ||
| 142 | - DEFINE TABLE IF NOT EXISTS board SCHEMAFULL; | ||
| 143 | - DEFINE FIELD IF NOT EXISTS creator ON board TYPE record<user>; | ||
| 144 | - DEFINE FIELD IF NOT EXISTS title ON board TYPE string; | ||
| 145 | - DEFINE FIELD IF NOT EXISTS participants ON board TYPE array<record<user>>; | ||
| 146 | - DEFINE FIELD IF NOT EXISTS locked ON board TYPE bool DEFAULT false; | ||
| 147 | - DEFINE FIELD IF NOT EXISTS locked_by ON board TYPE option<record<user>>; | ||
| 148 | - DEFINE FIELD IF NOT EXISTS locked_at ON board TYPE option<int>; | ||
| 149 | - DEFINE FIELD IF NOT EXISTS epoch ON board TYPE int DEFAULT 0; | ||
| 150 | - -- Resets to 0 on every clear (recoverable); never resets (stamps closed_at). | ||
| 151 | - DEFINE FIELD IF NOT EXISTS epoch_stroke_count ON board TYPE option<int>; | ||
| 152 | - DEFINE FIELD IF NOT EXISTS total_stroke_count ON board TYPE option<int>; | ||
| 153 | - -- Stamped once, when the lifetime cap is hit: permanently read-only. | ||
| 154 | - DEFINE FIELD IF NOT EXISTS closed_at ON board TYPE option<int>; | ||
| 155 | - DEFINE FIELD IF NOT EXISTS created_at ON board TYPE int; | ||
| 156 | - DEFINE INDEX IF NOT EXISTS board_creator ON board FIELDS creator; | ||
| 157 | - -- Listing a user's boards asks `creator = $u OR participants CONTAINS $u`; | ||
| 158 | - -- without this the CONTAINS half is a full scan. SurrealDB indexes an | ||
| 159 | - -- array field per element, so it covers the membership test directly. | ||
| 160 | - DEFINE INDEX IF NOT EXISTS board_participants ON board FIELDS participants; | ||
| 161 | - | ||
| 162 | - DEFINE TABLE IF NOT EXISTS board_stroke SCHEMAFULL; | ||
| 163 | - DEFINE FIELD IF NOT EXISTS board ON board_stroke TYPE record<board>; | ||
| 164 | - DEFINE FIELD IF NOT EXISTS author ON board_stroke TYPE record<user>; | ||
| 165 | - -- 'stroke' or 'clear'; `payload` is the opaque blob, absent on a clear | ||
| 166 | - -- marker, and `count` is populated only on a clear marker — the final | ||
| 167 | - -- stroke count of the epoch that marker closed. | ||
| 168 | - DEFINE FIELD IF NOT EXISTS kind ON board_stroke TYPE string; | ||
| 169 | - DEFINE FIELD IF NOT EXISTS payload ON board_stroke TYPE option<string>; | ||
| 170 | - DEFINE FIELD IF NOT EXISTS count ON board_stroke TYPE option<int>; | ||
| 171 | - DEFINE FIELD IF NOT EXISTS epoch ON board_stroke TYPE int; | ||
| 172 | - DEFINE FIELD IF NOT EXISTS created_at ON board_stroke TYPE int; | ||
| 173 | - -- Keeps a socket's join-replay scoped to the current epoch instead of | ||
| 174 | - -- scanning the board's whole history. | ||
| 175 | - DEFINE INDEX IF NOT EXISTS board_stroke_board_epoch ON board_stroke FIELDS board, epoch; | ||
| 176 | - -- The clear markers ARE the epoch index, so listing them is a hot read. | ||
| 177 | - DEFINE INDEX IF NOT EXISTS board_stroke_board_kind ON board_stroke FIELDS board, kind; | ||
| 178 | - | ||
| 179 | - DEFINE TABLE IF NOT EXISTS note_file SCHEMAFULL; | ||
| 180 | - DEFINE FIELD IF NOT EXISTS note ON note_file TYPE record<note>; | ||
| 181 | - DEFINE FIELD IF NOT EXISTS name ON note_file TYPE string; | ||
| 182 | - DEFINE FIELD IF NOT EXISTS content_type ON note_file TYPE string; | ||
| 183 | - DEFINE FIELD IF NOT EXISTS size ON note_file TYPE int; | ||
| 184 | - DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note; | ||
| 185 | - | ||
| 186 | - DEFINE TABLE IF NOT EXISTS course_note SCHEMAFULL; | ||
| 187 | - DEFINE FIELD IF NOT EXISTS course ON course_note TYPE record<course>; | ||
| 188 | - DEFINE FIELD IF NOT EXISTS author ON course_note TYPE record<user>; | ||
| 189 | - DEFINE FIELD IF NOT EXISTS title ON course_note TYPE string; | ||
| 190 | - DEFINE FIELD IF NOT EXISTS content ON course_note TYPE string; | ||
| 191 | - DEFINE FIELD IF NOT EXISTS file_count ON course_note TYPE option<int>; | ||
| 192 | - DEFINE INDEX IF NOT EXISTS course_note_course ON course_note FIELDS course; | ||
| 193 | - | ||
| 194 | - DEFINE TABLE IF NOT EXISTS course_note_file SCHEMAFULL; | ||
| 195 | - DEFINE FIELD IF NOT EXISTS course_note ON course_note_file TYPE record<course_note>; | ||
| 196 | - DEFINE FIELD IF NOT EXISTS name ON course_note_file TYPE string; | ||
| 197 | - DEFINE FIELD IF NOT EXISTS content_type ON course_note_file TYPE string; | ||
| 198 | - DEFINE FIELD IF NOT EXISTS size ON course_note_file TYPE int; | ||
| 199 | - DEFINE INDEX IF NOT EXISTS course_note_file_note ON course_note_file FIELDS course_note; | ||
| 200 | - | ||
| 201 | - -- What an AI service produced for a course note (rag.index, 2026-09-05). | ||
| 202 | - -- Derived and disposable: the note is the source of truth, so the rows | ||
| 203 | - -- cascade from the note AND from any attachment they were built from. | ||
| 204 | - -- `payload` is FLEXIBLE because its shape belongs to the service, not to | ||
| 205 | - -- this schema — SCHEMAFULL would otherwise strip every key inside it. | ||
| 206 | - DEFINE TABLE IF NOT EXISTS rag_output SCHEMAFULL; | ||
| 207 | - DEFINE FIELD IF NOT EXISTS course_note ON rag_output TYPE record<course_note>; | ||
| 208 | - DEFINE FIELD IF NOT EXISTS course ON rag_output TYPE record<course>; | ||
| 209 | - DEFINE FIELD IF NOT EXISTS sources ON rag_output TYPE array<record<course_note_file>>; | ||
| 210 | - DEFINE FIELD IF NOT EXISTS payload ON rag_output TYPE object FLEXIBLE; | ||
| 211 | - DEFINE FIELD IF NOT EXISTS generated_at ON rag_output TYPE int; | ||
| 212 | - DEFINE INDEX IF NOT EXISTS rag_output_note ON rag_output FIELDS course_note; | ||
| 213 | - -- Retire the course index: nothing queries rag_output by course. | ||
| 214 | - REMOVE INDEX IF EXISTS rag_output_course ON rag_output; | ||
| 215 | - -- Indexed per element, so the source cascade's `sources CONTAINS $file` | ||
| 216 | - -- is a lookup rather than a table scan. | ||
| 217 | - DEFINE INDEX IF NOT EXISTS rag_output_source ON rag_output FIELDS sources; | ||
| 218 | - | ||
| 219 | - -- Chatbot relay (2026-07-23): a `thread` groups the turns, one | ||
| 220 | - -- `chatbot_message` is one turn. `user_id` rides on the message too so an | ||
| 221 | - -- ownership check needs no join. An assistant turn is born `pending` and | ||
| 222 | - -- is completed (or failed) by the task holding the AI-bridge stream — | ||
| 223 | - -- hence the BACKFILL sweep, since that task dies with the process. | ||
| 224 | - DEFINE TABLE IF NOT EXISTS chatbot_thread SCHEMAFULL; | ||
| 225 | - DEFINE FIELD IF NOT EXISTS user_id ON chatbot_thread TYPE record<user> READONLY; | ||
| 226 | - DEFINE FIELD IF NOT EXISTS title ON chatbot_thread TYPE option<string>; | ||
| 227 | - DEFINE FIELD IF NOT EXISTS created_at ON chatbot_thread TYPE int READONLY; | ||
| 228 | - DEFINE FIELD IF NOT EXISTS updated_at ON chatbot_thread TYPE int; | ||
| 229 | - DEFINE INDEX IF NOT EXISTS chatbot_thread_user_updated ON chatbot_thread FIELDS user_id, updated_at; | ||
| 230 | - | ||
| 231 | - DEFINE TABLE IF NOT EXISTS chatbot_message SCHEMAFULL; | ||
| 232 | - DEFINE FIELD IF NOT EXISTS thread_id ON chatbot_message TYPE record<chatbot_thread> READONLY; | ||
| 233 | - DEFINE FIELD IF NOT EXISTS user_id ON chatbot_message TYPE record<user> READONLY; | ||
| 234 | - DEFINE FIELD IF NOT EXISTS role ON chatbot_message TYPE string READONLY; | ||
| 235 | - DEFINE FIELD IF NOT EXISTS content ON chatbot_message TYPE string; | ||
| 236 | - DEFINE FIELD IF NOT EXISTS status ON chatbot_message TYPE string; | ||
| 237 | - DEFINE FIELD IF NOT EXISTS truncated ON chatbot_message TYPE bool DEFAULT false; | ||
| 238 | - DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option<string>; | ||
| 239 | - DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY; | ||
| 240 | - DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option<int>; | ||
| 241 | - -- The chat claim queue is gone (2026-07-30): one process answers its own | ||
| 242 | - -- turns, so nothing claims them. PRE_REPAIR clears the values first — | ||
| 243 | - -- SCHEMAFULL rejects every write to a row still storing a column that no | ||
| 244 | - -- longer exists. | ||
| 245 | - REMOVE FIELD IF EXISTS claimed_by ON TABLE chatbot_message; | ||
| 246 | - REMOVE FIELD IF EXISTS claimed_at ON TABLE chatbot_message; | ||
| 247 | - DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at; | ||
| 248 | - DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id; | ||
| 249 | - -- The boot sweep asks for pending rows by age. | ||
| 250 | - DEFINE INDEX IF NOT EXISTS chatbot_message_status_created ON chatbot_message FIELDS status, created_at; | ||
| 251 | - | ||
| 252 | - -- The AI worker presence table is gone (2026-07-30): one process holds | ||
| 253 | - -- every worker socket, so its in-process registry is the whole truth and | ||
| 254 | - -- nothing needed publishing. | ||
| 255 | - REMOVE TABLE IF EXISTS ai_worker; | ||
| 256 | - | ||
| 257 | - -- The elected-boot lease is gone with it (2026-07-30): one process migrates, | ||
| 258 | - -- so nothing takes the lock. SCHEMALESS and read by nobody, so unlike the | ||
| 259 | - -- claim columns it needs no PRE_REPAIR — the table just goes. | ||
| 260 | - REMOVE TABLE IF EXISTS migration_lock; | ||
| 261 | - | ||
| 262 | - -- How much of a rate-limit budget one client has spent in one wall window | ||
| 263 | - -- (2026-07-27). One row per tier+client+window, id-keyed so a restart of | ||
| 264 | - -- the process lands back on the same record; `hits` is the durable total | ||
| 265 | - -- the in-memory bucket folds its local admits into (see | ||
| 266 | - -- `crate::rate_limit`), which is what carries a window across a restart. | ||
| 267 | - -- Rows are swept by the same task once their window is past. | ||
| 268 | - DEFINE TABLE IF NOT EXISTS rate_limit SCHEMAFULL; | ||
| 269 | - DEFINE FIELD IF NOT EXISTS hits ON rate_limit TYPE int DEFAULT 0; | ||
| 270 | - DEFINE FIELD IF NOT EXISTS window_start ON rate_limit TYPE int; | ||
| 271 | - | ||
| 272 | - DEFINE TABLE IF NOT EXISTS event SCHEMAFULL; | ||
| 273 | - DEFINE FIELD IF NOT EXISTS creator ON event TYPE record<user>; | ||
| 274 | - DEFINE FIELD IF NOT EXISTS title ON event TYPE string; | ||
| 275 | - DEFINE FIELD IF NOT EXISTS description ON event TYPE string; | ||
| 276 | - DEFINE FIELD IF NOT EXISTS audience ON event TYPE object; | ||
| 277 | - DEFINE FIELD IF NOT EXISTS audience.kind ON event TYPE string; | ||
| 278 | - DEFINE FIELD IF NOT EXISTS audience.role ON event TYPE option<string>; | ||
| 279 | - DEFINE FIELD IF NOT EXISTS audience.course ON event TYPE option<record<course>>; | ||
| 280 | - DEFINE FIELD IF NOT EXISTS audience.class ON event TYPE option<record<class_group>>; | ||
| 281 | - DEFINE FIELD IF NOT EXISTS audience.capacity ON event TYPE option<int>; | ||
| 282 | - -- Seats taken on the signup list, the stored capacity guard that closes | ||
| 283 | - -- write-skew between concurrent request tasks (see `crate::db::cap`). | ||
| 284 | - -- Absent reads as zero, so no Rust struct needs it. | ||
| 285 | - DEFINE FIELD IF NOT EXISTS registration_count ON event TYPE option<int>; | ||
| 286 | - REMOVE FIELD IF EXISTS audience.users ON TABLE event; | ||
| 287 | - DEFINE FIELD IF NOT EXISTS starts_at ON event TYPE option<int>; | ||
| 288 | - DEFINE FIELD IF NOT EXISTS ends_at ON event TYPE option<int>; | ||
| 289 | - | ||
| 290 | - DEFINE TABLE IF NOT EXISTS attendance SCHEMAFULL; | ||
| 291 | - DEFINE FIELD IF NOT EXISTS event ON attendance TYPE record<event>; | ||
| 292 | - DEFINE FIELD IF NOT EXISTS user ON attendance TYPE record<user>; | ||
| 293 | - DEFINE FIELD IF NOT EXISTS status ON attendance TYPE string; | ||
| 294 | - DEFINE FIELD IF NOT EXISTS marked_by ON attendance TYPE record<user>; | ||
| 295 | - DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE; | ||
| 296 | - DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user; | ||
| 297 | - | ||
| 298 | - DEFINE TABLE IF NOT EXISTS registration SCHEMAFULL; | ||
| 299 | - DEFINE FIELD IF NOT EXISTS event ON registration TYPE record<event>; | ||
| 300 | - DEFINE FIELD IF NOT EXISTS user ON registration TYPE record<user>; | ||
| 301 | - DEFINE FIELD IF NOT EXISTS registered_by ON registration TYPE record<user>; | ||
| 302 | - DEFINE INDEX IF NOT EXISTS registration_event_user ON registration FIELDS event, user UNIQUE; | ||
| 303 | - DEFINE INDEX IF NOT EXISTS registration_event ON registration FIELDS event; | ||
| 304 | - | ||
| 305 | - DEFINE TABLE IF NOT EXISTS term SCHEMAFULL; | ||
| 306 | - DEFINE FIELD IF NOT EXISTS name ON term TYPE string; | ||
| 307 | - DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int; | ||
| 308 | - DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int; | ||
| 309 | - -- When the term was archived; absent = open. `option<int>` and no | ||
| 310 | - -- BACKFILL: every term that exists predates archiving and is open, which | ||
| 311 | - -- is exactly what an absent stamp already means. | ||
| 312 | - DEFINE FIELD IF NOT EXISTS archived_at ON term TYPE option<int>; | ||
| 313 | - -- Courses still linking this term, the stored delete guard that closes | ||
| 314 | - -- write-skew between concurrent request tasks (see `crate::db::cap`). | ||
| 315 | - -- Absent reads as zero, so no Rust struct needs it. | ||
| 316 | - DEFINE FIELD IF NOT EXISTS course_count ON term TYPE option<int>; | ||
| 317 | - -- Classes linking this term, the other half of the same guard. A column of | ||
| 318 | - -- its own because `course_count` is seeded from the course rows alone. | ||
| 319 | - DEFINE FIELD IF NOT EXISTS class_count ON term TYPE option<int>; | ||
| 320 | - | ||
| 321 | - DEFINE TABLE IF NOT EXISTS course SCHEMAFULL; | ||
| 322 | - DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>; | ||
| 323 | - DEFINE FIELD IF NOT EXISTS teachers ON course TYPE array<record<user>> DEFAULT []; | ||
| 324 | - DEFINE FIELD IF NOT EXISTS teachers[*] ON course TYPE record<user>; | ||
| 325 | - DEFINE FIELD IF NOT EXISTS title ON course TYPE string; | ||
| 326 | - DEFINE FIELD IF NOT EXISTS description ON course TYPE string; | ||
| 327 | - DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course'; | ||
| 328 | - DEFINE FIELD IF NOT EXISTS term ON course TYPE option<record<term>>; | ||
| 329 | - DEFINE FIELD IF NOT EXISTS capacity ON course TYPE option<int>; | ||
| 330 | - DEFINE FIELD IF NOT EXISTS enrollment_count ON course TYPE option<int>; | ||
| 331 | - | ||
| 332 | - DEFINE TABLE IF NOT EXISTS subject SCHEMAFULL; | ||
| 333 | - DEFINE FIELD IF NOT EXISTS course ON subject TYPE record<course>; | ||
| 334 | - DEFINE FIELD IF NOT EXISTS name ON subject TYPE string; | ||
| 335 | - DEFINE FIELD IF NOT EXISTS description ON subject TYPE string; | ||
| 336 | - -- How many exam questions and how many homework still point here. The | ||
| 337 | - -- delete is conditioned on both reading zero, which is what makes the | ||
| 338 | - -- guard hold against a question created by a concurrent request task. | ||
| 339 | - DEFINE FIELD IF NOT EXISTS exam_question_count ON subject TYPE option<int>; | ||
| 340 | - DEFINE FIELD IF NOT EXISTS homework_count ON subject TYPE option<int>; | ||
| 341 | - DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course; | ||
| 342 | - | ||
| 343 | - -- A class section (şube) is a named set of students that bulk-manages real | ||
| 344 | - -- `enrollment` rows: `class_member` is one student in it, `class_course` one | ||
| 345 | - -- course it is attached to. Both counters gate the class delete. | ||
| 346 | - DEFINE TABLE IF NOT EXISTS class_group SCHEMAFULL; | ||
| 347 | - DEFINE FIELD IF NOT EXISTS name ON class_group TYPE string; | ||
| 348 | - DEFINE FIELD IF NOT EXISTS grade ON class_group TYPE option<string>; | ||
| 349 | - DEFINE FIELD IF NOT EXISTS term ON class_group TYPE option<record<term>>; | ||
| 350 | - DEFINE FIELD IF NOT EXISTS creator ON class_group TYPE record<user>; | ||
| 351 | - DEFINE FIELD IF NOT EXISTS teacher ON class_group TYPE option<record<user>>; | ||
| 352 | - DEFINE FIELD IF NOT EXISTS class_member_count ON class_group TYPE option<int>; | ||
| 353 | - DEFINE FIELD IF NOT EXISTS class_course_count ON class_group TYPE option<int>; | ||
| 354 | - -- Every class at one grade is what a blueprint pumps, so the grade label is | ||
| 355 | - -- that read's whole `WHERE`. | ||
| 356 | - DEFINE INDEX IF NOT EXISTS class_group_grade ON class_group FIELDS grade; | ||
| 357 | - | ||
| 358 | - -- A grade's course template: the courses every class section at that grade | ||
| 359 | - -- carries. The grade label *is* the record key, so a second blueprint for | ||
| 360 | - -- one grade cannot exist and no find-then-insert has to race for it (the shape | ||
| 361 | - -- `menu` uses for its date+slot). It holds no term — the class names its | ||
| 362 | - -- own — and `courses` carries no DEFAULT: a defaulted array on a SCHEMAFULL | ||
| 363 | - -- row is what broke every settings PATCH. | ||
| 364 | - DEFINE TABLE IF NOT EXISTS class_blueprint SCHEMAFULL; | ||
| 365 | - DEFINE FIELD IF NOT EXISTS grade ON class_blueprint TYPE string; | ||
| 366 | - DEFINE FIELD IF NOT EXISTS courses ON class_blueprint TYPE array<record<course>>; | ||
| 367 | - DEFINE FIELD IF NOT EXISTS creator ON class_blueprint TYPE record<user>; | ||
| 368 | - | ||
| 369 | - DEFINE TABLE IF NOT EXISTS class_member SCHEMAFULL; | ||
| 370 | - DEFINE FIELD IF NOT EXISTS class ON class_member TYPE record<class_group>; | ||
| 371 | - DEFINE FIELD IF NOT EXISTS user ON class_member TYPE record<user>; | ||
| 372 | - DEFINE FIELD IF NOT EXISTS added_by ON class_member TYPE record<user>; | ||
| 373 | - -- When the student was put in. Both link tables key on the *pair* | ||
| 374 | - -- (`<class>_<user>`), so ordering a roster by its record id sorts it by the | ||
| 375 | - -- member's account ULID — an arbitrary order the routes nevertheless | ||
| 376 | - -- documented as newest-first. `option<int>` and no BACKFILL: rows written | ||
| 377 | - -- before this column are of unknown age, and an absent stamp is NONE, which | ||
| 378 | - -- SurrealDB sorts *last* under DESC — already the honest place for them, so | ||
| 379 | - -- there is no number to invent. | ||
| 380 | - DEFINE FIELD IF NOT EXISTS added_at ON class_member TYPE option<int>; | ||
| 381 | - DEFINE INDEX IF NOT EXISTS class_member_class_user ON class_member FIELDS class, user UNIQUE; | ||
| 382 | - DEFINE INDEX IF NOT EXISTS class_member_class ON class_member FIELDS class; | ||
| 383 | - DEFINE INDEX IF NOT EXISTS class_member_user ON class_member FIELDS user; | ||
| 384 | - | ||
| 385 | - DEFINE TABLE IF NOT EXISTS class_course SCHEMAFULL; | ||
| 386 | - DEFINE FIELD IF NOT EXISTS class ON class_course TYPE record<class_group>; | ||
| 387 | - DEFINE FIELD IF NOT EXISTS course ON class_course TYPE record<course>; | ||
| 388 | - DEFINE FIELD IF NOT EXISTS attached_by ON class_course TYPE record<user>; | ||
| 389 | - -- The mirror of `class_member.added_at`, for the same reason: without it | ||
| 390 | - -- the course list is ordered by the *course's* ULID. | ||
| 391 | - DEFINE FIELD IF NOT EXISTS attached_at ON class_course TYPE option<int>; | ||
| 392 | - -- The blueprint that attached this course, absent when a human attached it | ||
| 393 | - -- by hand — the same shape, and the same meaning, as `enrollment.source` | ||
| 394 | - -- one table down. The line is not optional bookkeeping: `class_course` is | ||
| 395 | - -- SCHEMAFULL with a definition per key, so an undefined column is silently | ||
| 396 | - -- stripped on write and a blueprint could never take back what it placed. | ||
| 397 | - -- Absence *is* the meaning, so there is nothing to backfill: a row written | ||
| 398 | - -- before this column reads back as hand-attached, and `source = $blueprint` | ||
| 399 | - -- is false for an absent key, which is what keeps a hand-attached course | ||
| 400 | - -- unreachable by every blueprint sweep. | ||
| 401 | - DEFINE FIELD IF NOT EXISTS source ON class_course TYPE option<record<class_blueprint>>; | ||
| 402 | - DEFINE INDEX IF NOT EXISTS class_course_class_course ON class_course FIELDS class, course UNIQUE; | ||
| 403 | - DEFINE INDEX IF NOT EXISTS class_course_class ON class_course FIELDS class; | ||
| 404 | - DEFINE INDEX IF NOT EXISTS class_course_course ON class_course FIELDS course; | ||
| 405 | - | ||
| 406 | - DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL; | ||
| 407 | - DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record<course>; | ||
| 408 | - DEFINE FIELD IF NOT EXISTS user ON enrollment TYPE record<user>; | ||
| 409 | - DEFINE FIELD IF NOT EXISTS enrolled_by ON enrollment TYPE record<user>; | ||
| 410 | - -- The class that pumped this row, absent when a human placed the student | ||
| 411 | - -- directly. Absence is the meaning, so there is nothing to backfill: a class | ||
| 412 | - -- sweep may only take back the rows it wrote. | ||
| 413 | - DEFINE FIELD IF NOT EXISTS source ON enrollment TYPE option<record<class_group>>; | ||
| 414 | - DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE; | ||
| 415 | - DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user; | ||
| 416 | - | ||
| 417 | - DEFINE TABLE IF NOT EXISTS parent_link SCHEMAFULL; | ||
| 418 | - DEFINE FIELD IF NOT EXISTS parent ON parent_link TYPE record<user>; | ||
| 419 | - DEFINE FIELD IF NOT EXISTS student ON parent_link TYPE record<user>; | ||
| 420 | - DEFINE FIELD IF NOT EXISTS linked_by ON parent_link TYPE record<user>; | ||
| 421 | - DEFINE INDEX IF NOT EXISTS parent_link_parent_student ON parent_link FIELDS parent, student UNIQUE; | ||
| 422 | - DEFINE INDEX IF NOT EXISTS parent_link_parent ON parent_link FIELDS parent; | ||
| 423 | - DEFINE INDEX IF NOT EXISTS parent_link_student ON parent_link FIELDS student; | ||
| 424 | - | ||
| 425 | - DEFINE TABLE IF NOT EXISTS course_session SCHEMAFULL; | ||
| 426 | - DEFINE FIELD IF NOT EXISTS course ON course_session TYPE record<course>; | ||
| 427 | - DEFINE FIELD IF NOT EXISTS teacher ON course_session TYPE record<user>; | ||
| 428 | - DEFINE FIELD IF NOT EXISTS topic ON course_session TYPE string; | ||
| 429 | - DEFINE FIELD IF NOT EXISTS starts_at ON course_session TYPE int; | ||
| 430 | - DEFINE FIELD IF NOT EXISTS ends_at ON course_session TYPE option<int>; | ||
| 431 | - -- The once-per-session guard behind `lessons_held_total` (2026-08-04): | ||
| 432 | - -- stamped by the first roll call taken for the lesson, read by nothing but | ||
| 433 | - -- that guard. Definition only, and deliberately no backfill — a session | ||
| 434 | - -- that predates it carries no stamp, so the next roll call taken on it | ||
| 435 | - -- credits its teacher once, which is the rule this column encodes anyway. | ||
| 436 | - DEFINE FIELD IF NOT EXISTS held_counted_at ON course_session TYPE option<int>; | ||
| 437 | - DEFINE INDEX IF NOT EXISTS course_session_course ON course_session FIELDS course; | ||
| 438 | - | ||
| 439 | - DEFINE TABLE IF NOT EXISTS session_attendance SCHEMAFULL; | ||
| 440 | - DEFINE FIELD IF NOT EXISTS session ON session_attendance TYPE record<course_session>; | ||
| 441 | - DEFINE FIELD IF NOT EXISTS course ON session_attendance TYPE record<course>; | ||
| 442 | - DEFINE FIELD IF NOT EXISTS user ON session_attendance TYPE record<user>; | ||
| 443 | - DEFINE FIELD IF NOT EXISTS status ON session_attendance TYPE string; | ||
| 444 | - DEFINE FIELD IF NOT EXISTS marked_by ON session_attendance TYPE record<user>; | ||
| 445 | - DEFINE INDEX IF NOT EXISTS session_attendance_session_user ON session_attendance FIELDS session, user UNIQUE; | ||
| 446 | - DEFINE INDEX IF NOT EXISTS session_attendance_session ON session_attendance FIELDS session; | ||
| 447 | - DEFINE INDEX IF NOT EXISTS session_attendance_user ON session_attendance FIELDS user; | ||
| 448 | - DEFINE INDEX IF NOT EXISTS session_attendance_course ON session_attendance FIELDS course; | ||
| 449 | - | ||
| 450 | - DEFINE TABLE IF NOT EXISTS work_entry SCHEMAFULL; | ||
| 451 | - DEFINE FIELD IF NOT EXISTS user ON work_entry TYPE record<user>; | ||
| 452 | - DEFINE FIELD IF NOT EXISTS check_in ON work_entry TYPE int; | ||
| 453 | - DEFINE FIELD IF NOT EXISTS check_out ON work_entry TYPE option<int>; | ||
| 454 | - DEFINE INDEX IF NOT EXISTS work_entry_user ON work_entry FIELDS user; | ||
| 455 | - | ||
| 456 | - DEFINE TABLE IF NOT EXISTS pomodoro_session SCHEMAFULL; | ||
| 457 | - DEFINE FIELD IF NOT EXISTS user ON pomodoro_session TYPE record<user>; | ||
| 458 | - DEFINE FIELD IF NOT EXISTS started_at ON pomodoro_session TYPE int; | ||
| 459 | - DEFINE FIELD IF NOT EXISTS finished_at ON pomodoro_session TYPE option<int>; | ||
| 460 | - -- The verdict `finish` reached for this stint, stamped at close so a later | ||
| 461 | - -- reader never re-derives it against thresholds that have since moved. | ||
| 462 | - -- `option<bool>`: a running stint has no verdict yet, and a stint closed | ||
| 463 | - -- before the rule existed carries none and cannot honestly be given one. | ||
| 464 | - DEFINE FIELD IF NOT EXISTS counted ON pomodoro_session TYPE option<bool>; | ||
| 465 | - -- The student's own name for what the stint is for ('math', 'TYT | ||
| 466 | - -- denemesi') — free text given at start, not a subject link. Shipped in | ||
| 467 | - -- the same deploy as the code that writes it: on a SCHEMAFULL table a | ||
| 468 | - -- write naming an undefined field fails, and `option` lets rows from | ||
| 469 | - -- before the field read as none. | ||
| 470 | - DEFINE FIELD IF NOT EXISTS label ON pomodoro_session TYPE option<string>; | ||
| 471 | - DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user; | ||
| 472 | - | ||
| 473 | - DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; | ||
| 474 | - DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record<user>; | ||
| 475 | - DEFINE FIELD IF NOT EXISTS course ON exam TYPE record<course>; | ||
| 476 | - DEFINE FIELD IF NOT EXISTS title ON exam TYPE string; | ||
| 477 | - DEFINE FIELD IF NOT EXISTS description ON exam TYPE string; | ||
| 478 | - DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string; | ||
| 479 | - DEFINE FIELD IF NOT EXISTS mode ON exam TYPE option<string>; | ||
| 480 | - DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option<int>; | ||
| 481 | - DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option<int>; | ||
| 482 | - DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option<int>; | ||
| 483 | - DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1; | ||
| 484 | - DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true; | ||
| 485 | - DEFINE FIELD IF NOT EXISTS allow_review ON exam TYPE bool DEFAULT false; | ||
| 486 | - DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false; | ||
| 487 | - -- How many marks the exam carries (2026-07-27). A kind change is refused | ||
| 488 | - -- against it, and the exam's own compare-and-set pins it, so a grade | ||
| 489 | - -- landing mid-PATCH refuses that save instead of slipping past its gates. | ||
| 490 | - DEFINE FIELD IF NOT EXISTS result_count ON exam TYPE option<int>; | ||
| 491 | - DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course; | ||
| 492 | - | ||
| 493 | - DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL; | ||
| 494 | - DEFINE FIELD IF NOT EXISTS exam ON exam_attempt TYPE record<exam>; | ||
| 495 | - DEFINE FIELD IF NOT EXISTS user ON exam_attempt TYPE record<user>; | ||
| 496 | - DEFINE FIELD IF NOT EXISTS seq ON exam_attempt TYPE int DEFAULT 1; | ||
| 497 | - DEFINE FIELD IF NOT EXISTS started_at ON exam_attempt TYPE int; | ||
| 498 | - DEFINE FIELD IF NOT EXISTS finished_at ON exam_attempt TYPE option<int>; | ||
| 499 | - DEFINE FIELD IF NOT EXISTS left_at ON exam_attempt TYPE option<int>; | ||
| 500 | - DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user_seq ON exam_attempt FIELDS exam, user, seq UNIQUE; | ||
| 501 | - DEFINE INDEX IF NOT EXISTS exam_attempt_exam ON exam_attempt FIELDS exam; | ||
| 502 | - | ||
| 503 | - DEFINE TABLE IF NOT EXISTS exam_question SCHEMAFULL; | ||
| 504 | - DEFINE FIELD IF NOT EXISTS exam ON exam_question TYPE record<exam>; | ||
| 505 | - DEFINE FIELD IF NOT EXISTS text ON exam_question TYPE string; | ||
| 506 | - DEFINE FIELD IF NOT EXISTS kind ON exam_question TYPE string; | ||
| 507 | - DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int; | ||
| 508 | - -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices | ||
| 509 | - -- gained stable ids (`array<string>`/`int` -> `array<object>`/`string`), | ||
| 510 | - -- and IF NOT EXISTS would leave an existing database on the old types. | ||
| 511 | - DEFINE FIELD OVERWRITE choices ON exam_question TYPE option<array<object>>; | ||
| 512 | - -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice | ||
| 513 | - -- object's own fields are declared too (same shape as `settings.exam_kinds`). | ||
| 514 | - DEFINE FIELD OVERWRITE choices.*.id ON exam_question TYPE string; | ||
| 515 | - DEFINE FIELD OVERWRITE choices.*.text ON exam_question TYPE string; | ||
| 516 | - DEFINE FIELD OVERWRITE correct ON exam_question TYPE option<string>; | ||
| 517 | - DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record<subject>; | ||
| 518 | - -- Provenance, one column per direction: `from_bank` is the template this | ||
| 519 | - -- question was inserted from, `banked_as` the template most recently minted | ||
| 520 | - -- by saving it into the bank. They replace the single `source_bank`, which | ||
| 521 | - -- both directions wrote — so a question inserted from the bank read as | ||
| 522 | - -- already-saved. OVERWRITE (not IF NOT EXISTS): the old column has to | ||
| 523 | - -- actually go on an existing database, or SCHEMAFULL keeps accepting it | ||
| 524 | - -- while the struct no longer writes it. | ||
| 525 | - DEFINE FIELD OVERWRITE from_bank ON exam_question TYPE option<record<bank_question>>; | ||
| 526 | - DEFINE FIELD OVERWRITE banked_as ON exam_question TYPE option<record<bank_question>>; | ||
| 527 | - REMOVE FIELD IF EXISTS source_bank ON TABLE exam_question; | ||
| 528 | - DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam; | ||
| 529 | - DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject; | ||
| 530 | - | ||
| 531 | - DEFINE TABLE IF NOT EXISTS question_image SCHEMAFULL; | ||
| 532 | - DEFINE FIELD IF NOT EXISTS exam ON question_image TYPE record<exam>; | ||
| 533 | - DEFINE FIELD IF NOT EXISTS question ON question_image TYPE record<exam_question>; | ||
| 534 | - -- OVERWRITE: `slot` is now the choice's id, not its position. | ||
| 535 | - DEFINE FIELD OVERWRITE slot ON question_image TYPE option<string>; | ||
| 536 | - DEFINE FIELD IF NOT EXISTS file ON question_image TYPE string; | ||
| 537 | - DEFINE FIELD IF NOT EXISTS content_type ON question_image TYPE string; | ||
| 538 | - DEFINE FIELD IF NOT EXISTS size ON question_image TYPE int; | ||
| 539 | - DEFINE INDEX IF NOT EXISTS question_image_exam ON question_image FIELDS exam; | ||
| 540 | - DEFINE INDEX IF NOT EXISTS question_image_question ON question_image FIELDS question; | ||
| 541 | - | ||
| 542 | - DEFINE TABLE IF NOT EXISTS bank_question SCHEMAFULL; | ||
| 543 | - DEFINE FIELD IF NOT EXISTS owner ON bank_question TYPE record<user>; | ||
| 544 | - -- OVERWRITE, not IF NOT EXISTS: the field started life as a required | ||
| 545 | - -- `record<subject>` and has to actually change type on an existing database, | ||
| 546 | - -- otherwise the subject-delete cascade (`SET subject = NONE`) is rejected. | ||
| 547 | - DEFINE FIELD OVERWRITE subject ON bank_question TYPE option<record<subject>>; | ||
| 548 | - DEFINE FIELD IF NOT EXISTS text ON bank_question TYPE string; | ||
| 549 | - DEFINE FIELD IF NOT EXISTS kind ON bank_question TYPE string; | ||
| 550 | - DEFINE FIELD IF NOT EXISTS points ON bank_question TYPE int; | ||
| 551 | - -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices | ||
| 552 | - -- gained stable ids (`array<string>`/`int` -> `array<object>`/`string`), | ||
| 553 | - -- and IF NOT EXISTS would leave an existing database on the old types. | ||
| 554 | - DEFINE FIELD OVERWRITE choices ON bank_question TYPE option<array<object>>; | ||
| 555 | - -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice | ||
| 556 | - -- object's own fields are declared too (same shape as `settings.exam_kinds`). | ||
| 557 | - DEFINE FIELD OVERWRITE choices.*.id ON bank_question TYPE string; | ||
| 558 | - DEFINE FIELD OVERWRITE choices.*.text ON bank_question TYPE string; | ||
| 559 | - DEFINE FIELD OVERWRITE correct ON bank_question TYPE option<string>; | ||
| 560 | - DEFINE FIELD IF NOT EXISTS source_exam ON bank_question TYPE option<record<exam>>; | ||
| 561 | - -- 'private' | 'school'. DEFAULT so a row that predates the field (or any | ||
| 562 | - -- partial write) can never come out published: the answer key stays the | ||
| 563 | - -- owner's until they publish it. | ||
| 564 | - DEFINE FIELD IF NOT EXISTS visibility ON bank_question TYPE string DEFAULT 'private'; | ||
| 565 | - DEFINE FIELD IF NOT EXISTS created_at ON bank_question TYPE int READONLY; | ||
| 566 | - DEFINE INDEX IF NOT EXISTS bank_question_owner ON bank_question FIELDS owner; | ||
| 567 | - DEFINE INDEX IF NOT EXISTS bank_question_subject ON bank_question FIELDS subject; | ||
| 568 | - | ||
| 569 | - DEFINE TABLE IF NOT EXISTS bank_question_image SCHEMAFULL; | ||
| 570 | - DEFINE FIELD IF NOT EXISTS bank_question ON bank_question_image TYPE record<bank_question>; | ||
| 571 | - -- OVERWRITE: `slot` is now the choice's id, not its position. | ||
| 572 | - DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option<string>; | ||
| 573 | - DEFINE FIELD IF NOT EXISTS file ON bank_question_image TYPE string; | ||
| 574 | - DEFINE FIELD IF NOT EXISTS content_type ON bank_question_image TYPE string; | ||
| 575 | - DEFINE FIELD IF NOT EXISTS size ON bank_question_image TYPE int; | ||
| 576 | - DEFINE INDEX IF NOT EXISTS bank_question_image_question ON bank_question_image FIELDS bank_question; | ||
| 577 | - | ||
| 578 | - DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL; | ||
| 579 | - DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record<exam>; | ||
| 580 | - DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record<exam_question>; | ||
| 581 | - DEFINE FIELD IF NOT EXISTS user ON exam_answer TYPE record<user>; | ||
| 582 | - -- OVERWRITE: `selected` now names the picked option by id. | ||
| 583 | - DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option<string>; | ||
| 584 | - DEFINE FIELD IF NOT EXISTS text ON exam_answer TYPE option<string>; | ||
| 585 | - DEFINE FIELD IF NOT EXISTS updated_at ON exam_answer TYPE int; | ||
| 586 | - -- `seq` numbers the sitting an answer belongs to (1, 2, …), mirroring | ||
| 587 | - -- exam_attempt. It rides the record key too, so a retake's answer is a new | ||
| 588 | - -- row, not an overwrite of the prior sitting. | ||
| 589 | - DEFINE FIELD IF NOT EXISTS seq ON exam_answer TYPE int DEFAULT 1; | ||
| 590 | - -- Retire the pre-history unique index: (question, user) is no longer unique | ||
| 591 | - -- once a student re-sits; (question, user, seq) is. | ||
| 592 | - REMOVE INDEX IF EXISTS exam_answer_question_user ON exam_answer; | ||
| 593 | - DEFINE INDEX IF NOT EXISTS exam_answer_question_user_seq ON exam_answer FIELDS question, user, seq UNIQUE; | ||
| 594 | - DEFINE INDEX IF NOT EXISTS exam_answer_exam_user ON exam_answer FIELDS exam, user; | ||
| 595 | - DEFINE INDEX IF NOT EXISTS exam_answer_exam ON exam_answer FIELDS exam; | ||
| 596 | - | ||
| 597 | - DEFINE TABLE IF NOT EXISTS answer_image SCHEMAFULL; | ||
| 598 | - DEFINE FIELD IF NOT EXISTS exam ON answer_image TYPE record<exam>; | ||
| 599 | - DEFINE FIELD IF NOT EXISTS question ON answer_image TYPE record<exam_question>; | ||
| 600 | - DEFINE FIELD IF NOT EXISTS user ON answer_image TYPE record<user>; | ||
| 601 | - DEFINE FIELD IF NOT EXISTS file ON answer_image TYPE string; | ||
| 602 | - DEFINE FIELD IF NOT EXISTS content_type ON answer_image TYPE string; | ||
| 603 | - DEFINE FIELD IF NOT EXISTS size ON answer_image TYPE int; | ||
| 604 | - -- `seq` numbers the sitting this drawing belongs to; it rides the record | ||
| 605 | - -- key so a retake's image never overwrites the prior sitting's. | ||
| 606 | - DEFINE FIELD IF NOT EXISTS seq ON answer_image TYPE int DEFAULT 1; | ||
| 607 | - DEFINE INDEX IF NOT EXISTS answer_image_exam ON answer_image FIELDS exam; | ||
| 608 | - DEFINE INDEX IF NOT EXISTS answer_image_user ON answer_image FIELDS user; | ||
| 609 | - | ||
| 610 | - DEFINE TABLE IF NOT EXISTS exam_result SCHEMAFULL; | ||
| 611 | - DEFINE FIELD IF NOT EXISTS exam ON exam_result TYPE record<exam>; | ||
| 612 | - DEFINE FIELD IF NOT EXISTS user ON exam_result TYPE record<user>; | ||
| 613 | - DEFINE FIELD IF NOT EXISTS mark ON exam_result TYPE int; | ||
| 614 | - DEFINE FIELD IF NOT EXISTS graded_by ON exam_result TYPE record<user>; | ||
| 615 | - -- `seq` numbers the sitting a mark belongs to; a retake earns its own mark | ||
| 616 | - -- row, and the latest seq is the student's standing. | ||
| 617 | - DEFINE FIELD IF NOT EXISTS seq ON exam_result TYPE int DEFAULT 1; | ||
| 618 | - REMOVE INDEX IF EXISTS exam_result_exam_user ON exam_result; | ||
| 619 | - DEFINE INDEX IF NOT EXISTS exam_result_exam_user_seq ON exam_result FIELDS exam, user, seq UNIQUE; | ||
| 620 | - | ||
| 621 | - DEFINE TABLE IF NOT EXISTS pool_question SCHEMAFULL; | ||
| 622 | - DEFINE FIELD IF NOT EXISTS asker ON pool_question TYPE record<user>; | ||
| 623 | - DEFINE FIELD IF NOT EXISTS title ON pool_question TYPE string; | ||
| 624 | - DEFINE FIELD IF NOT EXISTS body ON pool_question TYPE string; | ||
| 625 | - DEFINE FIELD IF NOT EXISTS status ON pool_question TYPE string DEFAULT 'pending'; | ||
| 626 | - DEFINE FIELD IF NOT EXISTS asked_at ON pool_question TYPE int; | ||
| 627 | - DEFINE FIELD IF NOT EXISTS approved_by ON pool_question TYPE option<record<user>>; | ||
| 628 | - DEFINE FIELD IF NOT EXISTS image_file ON pool_question TYPE option<string>; | ||
| 629 | - DEFINE FIELD IF NOT EXISTS image_content_type ON pool_question TYPE option<string>; | ||
| 630 | - DEFINE FIELD IF NOT EXISTS image_size ON pool_question TYPE option<int>; | ||
| 631 | - DEFINE INDEX IF NOT EXISTS pool_question_status ON pool_question FIELDS status; | ||
| 632 | - DEFINE INDEX IF NOT EXISTS pool_question_asker ON pool_question FIELDS asker; | ||
| 633 | - | ||
| 634 | - DEFINE TABLE IF NOT EXISTS solution SCHEMAFULL; | ||
| 635 | - DEFINE FIELD IF NOT EXISTS question ON solution TYPE record<pool_question>; | ||
| 636 | - DEFINE FIELD IF NOT EXISTS author ON solution TYPE record<user>; | ||
| 637 | - DEFINE FIELD IF NOT EXISTS body ON solution TYPE string; | ||
| 638 | - DEFINE FIELD IF NOT EXISTS offered_at ON solution TYPE int; | ||
| 639 | - DEFINE FIELD IF NOT EXISTS image_file ON solution TYPE option<string>; | ||
| 640 | - DEFINE FIELD IF NOT EXISTS image_content_type ON solution TYPE option<string>; | ||
| 641 | - DEFINE FIELD IF NOT EXISTS image_size ON solution TYPE option<int>; | ||
| 642 | - DEFINE INDEX IF NOT EXISTS solution_question ON solution FIELDS question; | ||
| 643 | - | ||
| 644 | - DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL; | ||
| 645 | - DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array<object>; | ||
| 646 | - DEFINE FIELD IF NOT EXISTS exam_kinds.*.name ON settings TYPE string; | ||
| 647 | - DEFINE FIELD IF NOT EXISTS exam_kinds.*.weight ON settings TYPE int; | ||
| 648 | - DEFINE FIELD IF NOT EXISTS attendance_statuses ON settings TYPE array<string>; | ||
| 649 | - DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array<object>; | ||
| 650 | - DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int; | ||
| 651 | - DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string; | ||
| 652 | - DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option<int>; | ||
| 653 | - DEFINE FIELD IF NOT EXISTS chatbot_history_turns ON settings TYPE option<int>; | ||
| 654 | - DEFINE FIELD IF NOT EXISTS max_chatbot_threads ON settings TYPE option<int>; | ||
| 655 | - DEFINE FIELD IF NOT EXISTS max_chatbot_message_len ON settings TYPE option<int>; | ||
| 656 | - -- Food program (2026-07-26). `meal_slots` mirrors the `exam_kinds` shape — | ||
| 657 | - -- a named list a menu snapshots from — and `dietary_tags` mirrors | ||
| 658 | - -- `attendance_statuses`. `meal_cancel_cutoff_minutes` is ONE knob for both | ||
| 659 | - -- the booking and the cancel deadline; absent means no cutoff at all. All | ||
| 660 | - -- three are `option<>`, exactly like `max_file_bytes`: NOT `DEFAULT []`. | ||
| 661 | - -- `DEFAULT` fires on create only, and `PATCH /settings` writes the whole | ||
| 662 | - -- row with `UPDATE ... CONTENT`, so a required-with-default field a writer | ||
| 663 | - -- omits coerces to NONE and fails every settings write until the domain | ||
| 664 | - -- struct carries it. `option<>` also means the existing singleton reads | ||
| 665 | - -- fine, which is why the food program needs no BACKFILL anywhere. | ||
| 666 | - DEFINE FIELD IF NOT EXISTS meal_slots ON settings TYPE option<array<object>>; | ||
| 667 | - DEFINE FIELD IF NOT EXISTS meal_slots.*.name ON settings TYPE string; | ||
| 668 | - -- Minutes past midnight UTC at which the slot is served (2026-07-26). | ||
| 669 | - -- `option<int>` for the same reason the list itself is: slots written | ||
| 670 | - -- before the field existed simply have no key, and read back as NONE -> | ||
| 671 | - -- the booking cutoff falls back to midnight UTC, its old meaning. No | ||
| 672 | - -- BACKFILL, and no DEFAULT — see the note above. | ||
| 673 | - DEFINE FIELD IF NOT EXISTS meal_slots.*.serving_minute ON settings TYPE option<int>; | ||
| 674 | - DEFINE FIELD IF NOT EXISTS dietary_tags ON settings TYPE option<array<string>>; | ||
| 675 | - DEFINE FIELD IF NOT EXISTS meal_cancel_cutoff_minutes ON settings TYPE option<int>; | ||
| 676 | - | ||
| 677 | - -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students | ||
| 678 | - -- submit files + optional text, a teacher grades a status + optional mark. | ||
| 679 | - -- `course`/`created_by`/`created_at` are READONLY (a homework never moves | ||
| 680 | - -- course, and stamps never rewrite); `subject` is NOT — it is re-taggable | ||
| 681 | - -- via PATCH. `assigned` NONE/empty means the whole course. No BACKFILL: the | ||
| 682 | - -- tables are new, so the whole migration stays additive and idempotent. | ||
| 683 | - DEFINE TABLE IF NOT EXISTS homework SCHEMAFULL; | ||
| 684 | - DEFINE FIELD IF NOT EXISTS course ON homework TYPE record<course> READONLY; | ||
| 685 | - DEFINE FIELD IF NOT EXISTS subject ON homework TYPE record<subject>; | ||
| 686 | - DEFINE FIELD IF NOT EXISTS title ON homework TYPE string; | ||
| 687 | - DEFINE FIELD IF NOT EXISTS description ON homework TYPE option<string>; | ||
| 688 | - DEFINE FIELD IF NOT EXISTS due_at ON homework TYPE int; | ||
| 689 | - DEFINE FIELD IF NOT EXISTS assigned ON homework TYPE option<array<record<user>>>; | ||
| 690 | - DEFINE FIELD IF NOT EXISTS assigned[*] ON homework TYPE record<user>; | ||
| 691 | - DEFINE FIELD IF NOT EXISTS created_by ON homework TYPE record<user> READONLY; | ||
| 692 | - DEFINE FIELD IF NOT EXISTS created_at ON homework TYPE int READONLY; | ||
| 693 | - DEFINE INDEX IF NOT EXISTS homework_course ON homework FIELDS course; | ||
| 694 | - | ||
| 695 | - DEFINE TABLE IF NOT EXISTS homework_submission SCHEMAFULL; | ||
| 696 | - DEFINE FIELD IF NOT EXISTS homework ON homework_submission TYPE record<homework> READONLY; | ||
| 697 | - DEFINE FIELD IF NOT EXISTS user ON homework_submission TYPE record<user> READONLY; | ||
| 698 | - DEFINE FIELD IF NOT EXISTS text ON homework_submission TYPE option<string>; | ||
| 699 | - DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY; | ||
| 700 | - DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int; | ||
| 701 | - DEFINE FIELD IF NOT EXISTS file_count ON homework_submission TYPE option<int>; | ||
| 702 | - -- The on-time verdict the badge counter was actually credited with, stamped | ||
| 703 | - -- at the first hand-in and never re-judged. `due_at` is mutable (a teacher | ||
| 704 | - -- moves a deadline with `PATCH /homework/{id}`), so re-deriving the verdict | ||
| 705 | - -- at withdrawal read a *different* deadline than the credit did and gave | ||
| 706 | - -- back the wrong thing in both directions — extend the deadline after a late | ||
| 707 | - -- hand-in and the withdrawal debited an on-time credit that was never given; | ||
| 708 | - -- pull it back after a punctual one and it debited nothing, leaving on_time | ||
| 709 | - -- above submitted. `option<>` because every row predating 2026-08-04 has no | ||
| 710 | - -- stored verdict and cannot be given one for a credit that already happened: | ||
| 711 | - -- those fall back to the old comparison (see | ||
| 712 | - -- [`crate::db::homework_submission::delete`]). | ||
| 713 | - DEFINE FIELD IF NOT EXISTS counted_on_time ON homework_submission TYPE option<bool>; | ||
| 714 | - -- The grade that froze this submission, absent while it is still open. The | ||
| 715 | - -- freeze used to be a cross-table read (does a homework_result exist?) | ||
| 716 | - -- followed by a write here, which no lock can hold across replicas; the | ||
| 717 | - -- stamp turns every submission edit into a conditional single-record write | ||
| 718 | - -- (`WHERE graded_by_result = NONE`), the one guard that survives. Set by | ||
| 719 | - -- grading, cleared by un-grading, never by the student. | ||
| 720 | - DEFINE FIELD IF NOT EXISTS graded_by_result ON homework_submission TYPE option<record<homework_result>>; | ||
| 721 | - DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework; | ||
| 722 | - | ||
| 723 | - DEFINE TABLE IF NOT EXISTS homework_file SCHEMAFULL; | ||
| 724 | - DEFINE FIELD IF NOT EXISTS submission ON homework_file TYPE record<homework_submission> READONLY; | ||
| 725 | - DEFINE FIELD IF NOT EXISTS name ON homework_file TYPE string; | ||
| 726 | - DEFINE FIELD IF NOT EXISTS content_type ON homework_file TYPE string; | ||
| 727 | - DEFINE FIELD IF NOT EXISTS size ON homework_file TYPE int; | ||
| 728 | - DEFINE FIELD IF NOT EXISTS file ON homework_file TYPE string READONLY; | ||
| 729 | - DEFINE FIELD IF NOT EXISTS created_at ON homework_file TYPE int READONLY; | ||
| 730 | - DEFINE INDEX IF NOT EXISTS homework_file_submission ON homework_file FIELDS submission; | ||
| 731 | - | ||
| 732 | - DEFINE TABLE IF NOT EXISTS homework_result SCHEMAFULL; | ||
| 733 | - DEFINE FIELD IF NOT EXISTS homework ON homework_result TYPE record<homework> READONLY; | ||
| 734 | - DEFINE FIELD IF NOT EXISTS user ON homework_result TYPE record<user> READONLY; | ||
| 735 | - DEFINE FIELD IF NOT EXISTS status ON homework_result TYPE string; | ||
| 736 | - DEFINE FIELD IF NOT EXISTS mark ON homework_result TYPE option<int>; | ||
| 737 | - DEFINE FIELD IF NOT EXISTS graded_by ON homework_result TYPE record<user>; | ||
| 738 | - DEFINE FIELD IF NOT EXISTS created_at ON homework_result TYPE int; | ||
| 739 | - DEFINE INDEX IF NOT EXISTS homework_result_homework ON homework_result FIELDS homework; | ||
| 740 | - | ||
| 741 | - -- Appointments (greenfield, 2026-07-23): a teacher publishes availability | ||
| 742 | - -- slots, a student or parent books one. `series` groups the occurrences a | ||
| 743 | - -- weekly repeat expanded into, so one cancel deletes one row and a series | ||
| 744 | - -- delete finds the rest. A booking's live/dead state is the `status` | ||
| 745 | - -- string; `occupied` is the cap-1 counter that says whether the slot is | ||
| 746 | - -- taken (2026-07-27 — it used to be counted from the booking rows under a | ||
| 747 | - -- process-local lock, which two replicas could each pass), decremented in | ||
| 748 | - -- the same transaction as the reject/cancel that frees it. | ||
| 749 | - -- The `proposed_*` fields carry a teacher's counter-proposal on the same | ||
| 750 | - -- row until the requester accepts. | ||
| 751 | - DEFINE TABLE IF NOT EXISTS appointment_slot SCHEMAFULL; | ||
| 752 | - DEFINE FIELD IF NOT EXISTS teacher ON appointment_slot TYPE record<user>; | ||
| 753 | - DEFINE FIELD IF NOT EXISTS starts_at ON appointment_slot TYPE int; | ||
| 754 | - DEFINE FIELD IF NOT EXISTS ends_at ON appointment_slot TYPE int; | ||
| 755 | - DEFINE FIELD IF NOT EXISTS occupied ON appointment_slot TYPE option<int>; | ||
| 756 | - DEFINE FIELD IF NOT EXISTS note ON appointment_slot TYPE option<string>; | ||
| 757 | - DEFINE FIELD IF NOT EXISTS series ON appointment_slot TYPE option<string>; | ||
| 758 | - DEFINE FIELD IF NOT EXISTS created_at ON appointment_slot TYPE int; | ||
| 759 | - DEFINE INDEX IF NOT EXISTS appointment_slot_teacher_starts ON appointment_slot FIELDS teacher, starts_at; | ||
| 760 | - DEFINE INDEX IF NOT EXISTS appointment_slot_series ON appointment_slot FIELDS series; | ||
| 761 | - | ||
| 762 | - DEFINE TABLE IF NOT EXISTS appointment SCHEMAFULL; | ||
| 763 | - DEFINE FIELD IF NOT EXISTS slot ON appointment TYPE record<appointment_slot>; | ||
| 764 | - DEFINE FIELD IF NOT EXISTS requester ON appointment TYPE record<user>; | ||
| 765 | - DEFINE FIELD IF NOT EXISTS status ON appointment TYPE string DEFAULT 'pending'; | ||
| 766 | - DEFINE FIELD IF NOT EXISTS reason ON appointment TYPE string; | ||
| 767 | - DEFINE FIELD IF NOT EXISTS proposed_starts_at ON appointment TYPE option<int>; | ||
| 768 | - DEFINE FIELD IF NOT EXISTS proposed_ends_at ON appointment TYPE option<int>; | ||
| 769 | - DEFINE FIELD IF NOT EXISTS proposed_by ON appointment TYPE option<record<user>>; | ||
| 770 | - DEFINE FIELD IF NOT EXISTS decided_by ON appointment TYPE option<record<user>>; | ||
| 771 | - DEFINE FIELD IF NOT EXISTS cancelled_by ON appointment TYPE option<record<user>>; | ||
| 772 | - DEFINE FIELD IF NOT EXISTS cancel_reason ON appointment TYPE option<string>; | ||
| 773 | - DEFINE FIELD IF NOT EXISTS reject_reason ON appointment TYPE option<string>; | ||
| 774 | - DEFINE FIELD IF NOT EXISTS created_at ON appointment TYPE int; | ||
| 775 | - DEFINE INDEX IF NOT EXISTS appointment_slot_ref ON appointment FIELDS slot; | ||
| 776 | - DEFINE INDEX IF NOT EXISTS appointment_requester ON appointment FIELDS requester; | ||
| 777 | - DEFINE INDEX IF NOT EXISTS appointment_status ON appointment FIELDS status; | ||
| 778 | - | ||
| 779 | - -- Food program (greenfield, 2026-07-26): a published menu per day+slot, | ||
| 780 | - -- dishes on it, a dietary profile per student, bookings against a menu's | ||
| 781 | - -- capacity, who actually ate, and the money that moved. `date` is a | ||
| 782 | - -- calendar day as `YYYY-MM-DD` text, not a timestamp: the unique index is | ||
| 783 | - -- an equality test and a midnight-in-millis day is only unique for one | ||
| 784 | - -- timezone. `slot` is snapshotted text, not a link, so retiring a slot in | ||
| 785 | - -- settings never rewrites a past menu. Stamps stay `int` millis like the | ||
| 786 | - -- rest of the schema. No BACKFILL: all six tables are new. | ||
| 787 | - DEFINE TABLE IF NOT EXISTS menu SCHEMAFULL; | ||
| 788 | - DEFINE FIELD IF NOT EXISTS date ON menu TYPE string READONLY; | ||
| 789 | - DEFINE FIELD IF NOT EXISTS slot ON menu TYPE string READONLY; | ||
| 790 | - DEFINE FIELD IF NOT EXISTS capacity ON menu TYPE option<int>; | ||
| 791 | - -- `seats_booked` is the seat cap's counter (see `db::cap`) and | ||
| 792 | - -- `version` the menu's revision: a booking claims its seat only while the | ||
| 793 | - -- menu still stands at the revision it read the price at, so a dish | ||
| 794 | - -- re-priced mid-booking cannot be billed as the old price. Both absent | ||
| 795 | - -- means zero, which is what `(x ?? 0)` reads on a row written before them. | ||
| 796 | - DEFINE FIELD IF NOT EXISTS seats_booked ON menu TYPE option<int>; | ||
| 797 | - DEFINE FIELD IF NOT EXISTS version ON menu TYPE option<int>; | ||
| 798 | - DEFINE FIELD IF NOT EXISTS created_by ON menu TYPE record<user> READONLY; | ||
| 799 | - DEFINE FIELD IF NOT EXISTS created_at ON menu TYPE int READONLY; | ||
| 800 | - DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE; | ||
| 801 | - | ||
| 802 | - DEFINE TABLE IF NOT EXISTS menu_dish SCHEMAFULL; | ||
| 803 | - DEFINE FIELD IF NOT EXISTS menu ON menu_dish TYPE record<menu> READONLY; | ||
| 804 | - DEFINE FIELD IF NOT EXISTS name ON menu_dish TYPE string; | ||
| 805 | - DEFINE FIELD IF NOT EXISTS description ON menu_dish TYPE option<string>; | ||
| 806 | - -- Money is minor units (kuruş) as an integer, everywhere. Never decimal. | ||
| 807 | - DEFINE FIELD IF NOT EXISTS price_minor ON menu_dish TYPE int; | ||
| 808 | - DEFINE FIELD IF NOT EXISTS tags ON menu_dish TYPE array<string> DEFAULT []; | ||
| 809 | - DEFINE FIELD IF NOT EXISTS tags[*] ON menu_dish TYPE string; | ||
| 810 | - DEFINE FIELD IF NOT EXISTS created_at ON menu_dish TYPE int READONLY; | ||
| 811 | - DEFINE INDEX IF NOT EXISTS menu_dish_menu ON menu_dish FIELDS menu; | ||
| 812 | - | ||
| 813 | - DEFINE TABLE IF NOT EXISTS dietary_profile SCHEMAFULL; | ||
| 814 | - DEFINE FIELD IF NOT EXISTS student ON dietary_profile TYPE record<user> READONLY; | ||
| 815 | - DEFINE FIELD IF NOT EXISTS tags ON dietary_profile TYPE array<string> DEFAULT []; | ||
| 816 | - DEFINE FIELD IF NOT EXISTS tags[*] ON dietary_profile TYPE string; | ||
| 817 | - DEFINE FIELD IF NOT EXISTS note ON dietary_profile TYPE option<string>; | ||
| 818 | - DEFINE FIELD IF NOT EXISTS updated_by ON dietary_profile TYPE record<user>; | ||
| 819 | - DEFINE FIELD IF NOT EXISTS updated_at ON dietary_profile TYPE int; | ||
| 820 | - DEFINE INDEX IF NOT EXISTS dietary_profile_student ON dietary_profile FIELDS student UNIQUE; | ||
| 821 | - | ||
| 822 | - -- A cancel flips `status` and stamps `cancelled_at`; the row stays so the | ||
| 823 | - -- freed seat is still auditable against the ledger line it charged. | ||
| 824 | - DEFINE TABLE IF NOT EXISTS meal_booking SCHEMAFULL; | ||
| 825 | - DEFINE FIELD IF NOT EXISTS menu ON meal_booking TYPE record<menu> READONLY; | ||
| 826 | - DEFINE FIELD IF NOT EXISTS student ON meal_booking TYPE record<user> READONLY; | ||
| 827 | - DEFINE FIELD IF NOT EXISTS booked_by ON meal_booking TYPE record<user> READONLY; | ||
| 828 | - DEFINE FIELD IF NOT EXISTS status ON meal_booking TYPE string DEFAULT 'booked'; | ||
| 829 | - -- How many times this seat has been taken, and what it cost when the | ||
| 830 | - -- *current* attempt took it (NONE = the menu was free then). Together they | ||
| 831 | - -- key the attempt's ledger lines, which is what makes billing idempotent | ||
| 832 | - -- by identity rather than by scanning for an outstanding charge. | ||
| 833 | - DEFINE FIELD IF NOT EXISTS attempt ON meal_booking TYPE int DEFAULT 1; | ||
| 834 | - DEFINE FIELD IF NOT EXISTS price_minor ON meal_booking TYPE option<int>; | ||
| 835 | - DEFINE FIELD IF NOT EXISTS cancelled_at ON meal_booking TYPE option<int>; | ||
| 836 | - DEFINE FIELD IF NOT EXISTS created_at ON meal_booking TYPE int READONLY; | ||
| 837 | - DEFINE INDEX IF NOT EXISTS meal_booking_menu ON meal_booking FIELDS menu; | ||
| 838 | - DEFINE INDEX IF NOT EXISTS meal_booking_student ON meal_booking FIELDS student; | ||
| 839 | - | ||
| 840 | - DEFINE TABLE IF NOT EXISTS meal_attendance SCHEMAFULL; | ||
| 841 | - DEFINE FIELD IF NOT EXISTS menu ON meal_attendance TYPE record<menu> READONLY; | ||
| 842 | - DEFINE FIELD IF NOT EXISTS student ON meal_attendance TYPE record<user> READONLY; | ||
| 843 | - DEFINE FIELD IF NOT EXISTS status ON meal_attendance TYPE string; | ||
| 844 | - DEFINE FIELD IF NOT EXISTS marked_by ON meal_attendance TYPE record<user>; | ||
| 845 | - DEFINE FIELD IF NOT EXISTS marked_at ON meal_attendance TYPE int; | ||
| 846 | - DEFINE INDEX IF NOT EXISTS meal_attendance_menu_student ON meal_attendance FIELDS menu, student UNIQUE; | ||
| 847 | - | ||
| 848 | - -- APPEND-ONLY by design: a mistake is corrected with an opposing | ||
| 849 | - -- `reversal` line, never by editing or deleting one. Hence every field is | ||
| 850 | - -- READONLY. `source` is untyped on purpose — a charge points at the | ||
| 851 | - -- booking that caused it, a reversal at the line it undoes. | ||
| 852 | - DEFINE TABLE IF NOT EXISTS meal_ledger SCHEMAFULL; | ||
| 853 | - DEFINE FIELD IF NOT EXISTS student ON meal_ledger TYPE record<user> READONLY; | ||
| 854 | - DEFINE FIELD IF NOT EXISTS kind ON meal_ledger TYPE string READONLY; | ||
| 855 | - DEFINE FIELD IF NOT EXISTS amount_minor ON meal_ledger TYPE int READONLY; | ||
| 856 | - DEFINE FIELD IF NOT EXISTS source ON meal_ledger TYPE option<record> READONLY; | ||
| 857 | - DEFINE FIELD IF NOT EXISTS method ON meal_ledger TYPE option<string> READONLY; | ||
| 858 | - DEFINE FIELD IF NOT EXISTS note ON meal_ledger TYPE option<string> READONLY; | ||
| 859 | - DEFINE FIELD IF NOT EXISTS recorded_by ON meal_ledger TYPE record<user> READONLY; | ||
| 860 | - DEFINE FIELD IF NOT EXISTS created_at ON meal_ledger TYPE int READONLY; | ||
| 861 | - DEFINE INDEX IF NOT EXISTS meal_ledger_student ON meal_ledger FIELDS student; | ||
| 862 | - | ||
| 863 | - -- A school fee plan: a name and its installments, each an amount and the | ||
| 864 | - -- day it falls due. The installments are embedded (SCHEMAFULL, so the | ||
| 865 | - -- object's own fields are declared too, same shape as `settings.exam_kinds`) | ||
| 866 | - -- because a charge line copies the amount it was assigned at — child rows | ||
| 867 | - -- would buy nothing. Neither field inside the object is optional: a NONE | ||
| 868 | - -- value would be dropped from the stored object entirely. | ||
| 869 | - DEFINE TABLE IF NOT EXISTS fee_plan SCHEMAFULL; | ||
| 870 | - DEFINE FIELD IF NOT EXISTS name ON fee_plan TYPE string; | ||
| 871 | - DEFINE FIELD IF NOT EXISTS installments ON fee_plan TYPE array<object>; | ||
| 872 | - DEFINE FIELD IF NOT EXISTS installments.*.amount_minor ON fee_plan TYPE int; | ||
| 873 | - DEFINE FIELD IF NOT EXISTS installments.*.due_at ON fee_plan TYPE int; | ||
| 874 | - DEFINE FIELD IF NOT EXISTS created_by ON fee_plan TYPE record<user> READONLY; | ||
| 875 | - DEFINE FIELD IF NOT EXISTS created_at ON fee_plan TYPE int READONLY; | ||
| 876 | - -- How many students are on the plan. The edit and delete guards read it, | ||
| 877 | - -- an assignment's own transaction increments it, and nothing decrements it | ||
| 878 | - -- (assignments are never removed). `option<int>` and no DEFAULT, like every | ||
| 879 | - -- other counter: no Rust struct carries it, so the plan's create must not | ||
| 880 | - -- be expected to state it. | ||
| 881 | - DEFINE FIELD IF NOT EXISTS assignment_count ON fee_plan TYPE option<int>; | ||
| 882 | - | ||
| 883 | - -- One plan on one student, keyed `<plan>_<student>`: assigning twice is the | ||
| 884 | - -- same record id, so a replay writes nothing and an assignment cut short | ||
| 885 | - -- half-way self-heals when it is repeated. Nothing here is ever edited. | ||
| 886 | - DEFINE TABLE IF NOT EXISTS fee_plan_assignment SCHEMAFULL; | ||
| 887 | - DEFINE FIELD IF NOT EXISTS plan ON fee_plan_assignment TYPE record<fee_plan> READONLY; | ||
| 888 | - DEFINE FIELD IF NOT EXISTS student ON fee_plan_assignment TYPE record<user> READONLY; | ||
| 889 | - DEFINE FIELD IF NOT EXISTS assigned_by ON fee_plan_assignment TYPE record<user> READONLY; | ||
| 890 | - DEFINE FIELD IF NOT EXISTS created_at ON fee_plan_assignment TYPE int READONLY; | ||
| 891 | - DEFINE INDEX IF NOT EXISTS fee_plan_assignment_plan ON fee_plan_assignment FIELDS plan; | ||
| 892 | - DEFINE INDEX IF NOT EXISTS fee_plan_assignment_student ON fee_plan_assignment FIELDS student; | ||
| 893 | - | ||
| 894 | - -- School fees, APPEND-ONLY by design exactly like `meal_ledger`: a mistake | ||
| 895 | - -- is corrected with an opposing line, never by editing or deleting one, | ||
| 896 | - -- hence every field is READONLY. `source` is untyped on purpose — a charge | ||
| 897 | - -- points at the `fee_plan_assignment` that raised it, a credit at the charge | ||
| 898 | - -- it pays, a refund at the credit it returns, a reversal at the line it | ||
| 899 | - -- undoes. `due_at` is set on charges alone. | ||
| 900 | - DEFINE TABLE IF NOT EXISTS payment_ledger SCHEMAFULL; | ||
| 901 | - DEFINE FIELD IF NOT EXISTS student ON payment_ledger TYPE record<user> READONLY; | ||
| 902 | - DEFINE FIELD IF NOT EXISTS kind ON payment_ledger TYPE string READONLY; | ||
| 903 | - DEFINE FIELD IF NOT EXISTS amount_minor ON payment_ledger TYPE int READONLY; | ||
| 904 | - DEFINE FIELD IF NOT EXISTS source ON payment_ledger TYPE option<record> READONLY; | ||
| 905 | - DEFINE FIELD IF NOT EXISTS due_at ON payment_ledger TYPE option<int> READONLY; | ||
| 906 | - DEFINE FIELD IF NOT EXISTS method ON payment_ledger TYPE option<string> READONLY; | ||
| 907 | - DEFINE FIELD IF NOT EXISTS note ON payment_ledger TYPE option<string> READONLY; | ||
| 908 | - DEFINE FIELD IF NOT EXISTS recorded_by ON payment_ledger TYPE record<user> READONLY; | ||
| 909 | - DEFINE FIELD IF NOT EXISTS created_at ON payment_ledger TYPE int READONLY; | ||
| 910 | - DEFINE INDEX IF NOT EXISTS payment_ledger_student ON payment_ledger FIELDS student; | ||
| 911 | - DEFINE INDEX IF NOT EXISTS payment_ledger_source ON payment_ledger FIELDS source; | ||
| 912 | - | ||
| 913 | - -- One row per badge a user has earned, keyed `{user}_{badge}` so the award | ||
| 914 | - -- is written by an UPSERT that can never double (domain::badge). `earned_at` | ||
| 915 | - -- is `option<int>` because that is what makes the stamp write-once: the | ||
| 916 | - -- UPSERT carries `WHERE earned_at = NONE`, so a re-sync of a badge already | ||
| 917 | - -- held leaves the original date standing. Awards are permanent — nothing | ||
| 918 | - -- deletes a row here — so the table needs no repair and no BACKFILL. | ||
| 919 | - DEFINE TABLE IF NOT EXISTS badge_award SCHEMAFULL; | ||
| 920 | - DEFINE FIELD IF NOT EXISTS user ON badge_award TYPE record<user>; | ||
| 921 | - DEFINE FIELD IF NOT EXISTS badge ON badge_award TYPE string; | ||
| 922 | - DEFINE FIELD IF NOT EXISTS earned_at ON badge_award TYPE option<int>; | ||
| 923 | - -- A plain field index, never `FIELDS user[*]`: the per-element form is used | ||
| 924 | - -- by the planner and then returns zero rows (see the `course.teachers` note). | ||
| 925 | - DEFINE INDEX IF NOT EXISTS badge_award_user ON badge_award FIELDS user; | ||
| 926 | - | ||
| 927 | - -- Reference counters, one row per *name* the settings offer, keyed by the | ||
| 928 | - -- name itself (2026-07-27). They are how 'a kind nothing is graded under | ||
| 929 | - -- may be removed' survives a second replica: the guard used to be a | ||
| 930 | - -- count-then-write across two tables under a process-wide lock, and the | ||
| 931 | - -- database serializes neither half of that. Both columns are `option<…>` | ||
| 932 | - -- so an absent row reads as zero references, in service — the counter is | ||
| 933 | - -- created by the first claim, never seeded per name. | ||
| 934 | - DEFINE TABLE IF NOT EXISTS kind_ref SCHEMAFULL; | ||
| 935 | - DEFINE FIELD IF NOT EXISTS count ON kind_ref TYPE option<int>; | ||
| 936 | - DEFINE FIELD IF NOT EXISTS retired ON kind_ref TYPE option<bool>; | ||
| 937 | - | ||
| 938 | - DEFINE TABLE IF NOT EXISTS slot_ref SCHEMAFULL; | ||
| 939 | - DEFINE FIELD IF NOT EXISTS count ON slot_ref TYPE option<int>; | ||
| 940 | - DEFINE FIELD IF NOT EXISTS retired ON slot_ref TYPE option<bool>; | ||
| 941 | - | ||
| 942 | - -- One row per backfill that is genuinely *one-time*, keyed by the backfill's | ||
| 943 | - -- own name (2026-08-02). Most of `BACKFILL` is a `WHERE` that matches no row | ||
| 944 | - -- once it has converged, so re-running it is free — but a repair whose cost | ||
| 945 | - -- is the *scan* rather than the write pays that cost on every boot forever, | ||
| 946 | - -- and the board-roster sweep's scan is one full `user` pass per board. A | ||
| 947 | - -- marker row is the smallest thing that can say 'this one is finished': the | ||
| 948 | - -- boot loop carries no lock and no fingerprint any more (2026-07-30), so | ||
| 949 | - -- there is nowhere else for that fact to live. A database that never ran the | ||
| 950 | - -- repair holds no row and runs it; the row is written by the same query. | ||
| 951 | - -- | ||
| 952 | - -- `fingerprint` is *which* text ran (2026-08-05), and it is what makes a | ||
| 953 | - -- marked block correctable. Saying only 'this ran' meant an edit to a block | ||
| 954 | - -- that was already marked could never reach a volume that had booted once: | ||
| 955 | - -- the `exam_sat_total` correction below shipped inside one and would have | ||
| 956 | - -- been dead on arrival on every existing database. The gate compares the | ||
| 957 | - -- stored number against the hash of the text *this* binary would run | ||
| 958 | - -- (`database::marked_blocks`), so an edited block runs once more and | ||
| 959 | - -- re-stamps, and an unedited one still costs a single record read. | ||
| 960 | - -- `option<int>`: a mark written before this column existed carries none, | ||
| 961 | - -- which matches no fingerprint and so re-runs its block exactly once. | ||
| 962 | - DEFINE TABLE IF NOT EXISTS migration_mark SCHEMAFULL; | ||
| 963 | - DEFINE FIELD IF NOT EXISTS done_at ON migration_mark TYPE int; | ||
| 964 | - DEFINE FIELD IF NOT EXISTS fingerprint ON migration_mark TYPE option<int>; | ||
| 965 | -"; | ||
| 966 | - | ||
| 967 | -/// Data backfills for rows written by older binaries. Runs *after* (and apart | ||
| 968 | -/// from) the DDL batch so every statement sees the freshly defined schema — | ||
| 969 | -/// see the `MIGRATION` doc for why sharing the batch corrupts the writes. | ||
| 970 | -/// Idempotent: each backfill's `WHERE` only matches unconverted rows. | ||
| 971 | -pub const BACKFILL: &str = " | ||
| 972 | - UPDATE user SET role = 'student' WHERE role = NONE; | ||
| 973 | - | ||
| 974 | - UPDATE course SET kind = 'course' WHERE kind = NONE; | ||
| 975 | - | ||
| 976 | - -- Courses predate assignable teachers (2026-07-21): every existing course | ||
| 977 | - -- was run by its creator alone, so it starts with nobody else assigned. | ||
| 978 | - UPDATE course SET teachers = [] WHERE teachers = NONE; | ||
| 979 | - | ||
| 980 | - -- Exams predate the draft flag (2026-07-19): everything already out there | ||
| 981 | - -- was live for its course, so it stays published. | ||
| 982 | - UPDATE exam SET draft = false WHERE draft = NONE; | ||
| 983 | - | ||
| 984 | - -- Exams predate the review toggle (2026-07-24): default it closed (opt-in). | ||
| 985 | - UPDATE exam SET allow_review = false WHERE allow_review = NONE; | ||
| 986 | - | ||
| 987 | - UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {}; | ||
| 988 | - | ||
| 989 | - -- Questions written before subjects existed (2026-07-17) are destroyed, not | ||
| 990 | - -- backfilled: a subject is mandatory and there is nothing truthful to | ||
| 991 | - -- assign. Their answers go first so no answer row outlives its question. | ||
| 992 | - DELETE exam_answer WHERE question IN (SELECT VALUE id FROM exam_question WHERE subject = NONE); | ||
| 993 | - DELETE exam_question WHERE subject = NONE; | ||
| 994 | - | ||
| 995 | - -- The hand-picked `users` audience retired into `registration` (2026-07-16): | ||
| 996 | - -- each listed user becomes a signup row credited to the event's creator, and | ||
| 997 | - -- the event becomes an uncapped registration list. Runs once — converted | ||
| 998 | - -- events no longer match the `kind = 'users'` filter. (`?? []`: an empty | ||
| 999 | - -- statement-subquery evaluates to NONE, which FOR refuses to iterate.) | ||
| 1000 | - FOR $ev IN ((SELECT id, creator, audience FROM event WHERE audience.kind = 'users') ?? []) { | ||
| 1001 | - FOR $usr IN ($ev.audience.users ?? []) { | ||
| 1002 | - UPSERT type::record('registration', string::concat(record::id($ev.id), '_', record::id($usr))) CONTENT { | ||
| 1003 | - event: $ev.id, | ||
| 1004 | - user: $usr, | ||
| 1005 | - registered_by: $ev.creator, | ||
| 1006 | - }; | ||
| 1007 | - }; | ||
| 1008 | - UPDATE $ev.id SET audience = { kind: 'registration' }; | ||
| 1009 | - }; | ||
| 1010 | - | ||
| 1011 | - -- Turns written before the clipped-answer flag existed (2026-07-23): the | ||
| 1012 | - -- clip was silent then, so nothing can be recovered — they read as whole, | ||
| 1013 | - -- which is what they were presented as all along. | ||
| 1014 | - UPDATE chatbot_message SET truncated = false WHERE truncated = NONE; | ||
| 1015 | - | ||
| 1016 | - -- An assistant turn is answered by a task in this process, so a restart can | ||
| 1017 | - -- leave its row `pending` with nobody left to complete it. Only rows past | ||
| 1018 | - -- the stale horizon ($stale_ms, from `CHATBOT_PENDING_STALE_SECS`) are | ||
| 1019 | - -- certainly abandoned though: a young one may still be being answered on | ||
| 1020 | - -- the other side of the AI bridge, and a deploy must not shoot down a turn | ||
| 1021 | - -- dispatched seconds ago. Nothing is lost by waiting — a reader already | ||
| 1022 | - -- presents an over-age `pending` row as failed, and the next boot sweeps | ||
| 1023 | - -- for real whatever crossed the horizon in the meantime. | ||
| 1024 | - -- | ||
| 1025 | - -- The claim half of this guard went with the claim queue (2026-07-30): it | ||
| 1026 | - -- only ever spared a row a *live peer* was answering, and there is no peer. | ||
| 1027 | - -- The rows selected are otherwise the same ones — an unclaimed row past the | ||
| 1028 | - -- horizon was always swept, and a claim of this process's own could not | ||
| 1029 | - -- outlive the process whose boot is running this. | ||
| 1030 | - UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted', | ||
| 1031 | - completed_at = time::unix(time::now()) * 1000 | ||
| 1032 | - WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms; | ||
| 1033 | - | ||
| 1034 | - -- The seats the sweep below spent every past boot *not* giving back: until | ||
| 1035 | - -- today it deleted those rows without touching the course's counter, so | ||
| 1036 | - -- every course it ever swept carries a phantom seat — one that denies a real | ||
| 1037 | - -- student a place, and that `Course::delete` refuses to let anyone past, | ||
| 1038 | - -- forever (its guard is `(enrollment_count ?? 0) = 0` on the course row). | ||
| 1039 | - -- This recomputes the counter for every course whose stored number disagrees | ||
| 1040 | - -- with the enrollment rows it actually has. | ||
| 1041 | - -- | ||
| 1042 | - -- Counting the rows cannot read *low*. The counter has exactly one meaning — | ||
| 1043 | - -- the live enrollment rows of this course — and every writer moves it with | ||
| 1044 | - -- the row in one transaction (`db::enrollment`'s `enroll`/`remove`, `set_role`'s | ||
| 1045 | - -- demotion sweep, the class pump's attach and detach); `Course::delete` takes | ||
| 1046 | - -- the rows *and* the course together, so no cascade leaves counted rows | ||
| 1047 | - -- behind. That is what separates it from the lifetime tallies below, which | ||
| 1048 | - -- are seeded once precisely because their rows do die under them. The claims | ||
| 1049 | - -- that borrow this column as a collision device (`cap::touch_and_create`, | ||
| 1050 | - -- `Axis::pivot_claim`) bump and restore it inside their own transaction, so | ||
| 1051 | - -- no other reader ever sees the raised value — and `migrate` runs to | ||
| 1052 | - -- completion before the router is bound, one process per volume, so there is | ||
| 1053 | - -- no concurrent writer to see it from anyway. | ||
| 1054 | - -- | ||
| 1055 | - -- Neither `= NONE`-guarded nor marked, for the board-stroke repair's reason: | ||
| 1056 | - -- this is not an opinion the live system maintains, it is the course's row | ||
| 1057 | - -- count, so recomputing converges instead of overwriting and the `!=` guard | ||
| 1058 | - -- writes nothing on the next boot. It runs *before* the sweep, so the two | ||
| 1059 | - -- own separate halves of the same invariant — this one clears the drift the | ||
| 1060 | - -- volume arrived with, the sweep's own decrement leaves none behind — and it | ||
| 1061 | - -- does not fight the `= NONE` seeding further down either: a pre-counter | ||
| 1062 | - -- course with rows gets the same number here that the seeding would have | ||
| 1063 | - -- given it, and one with no rows stays absent for the zero pass to fill. | ||
| 1064 | - -- | ||
| 1065 | - -- Per course rather than `GROUP BY course`, because the case that matters | ||
| 1066 | - -- most forms no group: a course whose last enrollment the sweep took away has | ||
| 1067 | - -- zero rows and a counter above zero, and a grouped pass would never visit | ||
| 1068 | - -- it. `array::len` over ids rather than `count()`, because an aggregate over | ||
| 1069 | - -- an indexed field (`enrollment` is indexed on `course`) can come back as | ||
| 1070 | - -- `{ count: n }` from the server — a shape the in-memory engine never | ||
| 1071 | - -- produces and `option<int>` would refuse. | ||
| 1072 | - FOR $c IN ((SELECT VALUE id FROM course) ?? []) { | ||
| 1073 | - LET $live = array::len((SELECT VALUE id FROM enrollment WHERE course = $c)); | ||
| 1074 | - UPDATE $c SET enrollment_count = $live WHERE (enrollment_count ?? 0) != $live; | ||
| 1075 | - }; | ||
| 1076 | - | ||
| 1077 | - -- Promotion out of student now deletes the user's enrollments (2026-07-18); | ||
| 1078 | - -- this sweeps rows promoted before that fix. A deleted user reads as | ||
| 1079 | - -- `user.role = NONE`, which is also != 'student' — those rows go too. | ||
| 1080 | - -- | ||
| 1081 | - -- The course's seat goes back with the row, per course, exactly the way | ||
| 1082 | - -- `User::set_role`'s own demotion sweep releases it: the counter is the | ||
| 1083 | - -- roster's authority, so a swept row that kept its seat denies a real | ||
| 1084 | - -- student a place *and* makes the course undeletable for good | ||
| 1085 | - -- (`Course::delete` refuses on `(enrollment_count ?? 0) = 0`). Several rows | ||
| 1086 | - -- of one course each take their own turn through the loop, so the counter | ||
| 1087 | - -- comes down by exactly as many rows as went. | ||
| 1088 | - LET $swept = (DELETE enrollment WHERE user.role != 'student' RETURN BEFORE); | ||
| 1089 | - FOR $row IN ($swept ?? []) { | ||
| 1090 | - UPDATE $row.course SET enrollment_count = | ||
| 1091 | - math::max([(enrollment_count ?? 0) - 1, 0]); | ||
| 1092 | - }; | ||
| 1093 | - | ||
| 1094 | - -- Choices gained stable ids (2026-07-24): `choices` held bare strings and | ||
| 1095 | - -- `correct`/`selected`/`slot` held the option's *position*. The DDL above | ||
| 1096 | - -- retypes those columns, which leaves every old-shaped row readable but | ||
| 1097 | - -- unwritable ('Expected `none | array<object>` but found `[..]`'), so this | ||
| 1098 | - -- conversion is repair, not cosmetics. | ||
| 1099 | - -- | ||
| 1100 | - -- Ids are minted in array order, so the id at position i *is* the id for | ||
| 1101 | - -- old index i — that identity is what keeps a stored answer, and an option | ||
| 1102 | - -- picture, pointing at the option the student actually saw. Hence the | ||
| 1103 | - -- dependent rows are remapped inside the loop that mints `$new`, against | ||
| 1104 | - -- that same array: once the ids are stored the positions are still | ||
| 1105 | - -- recoverable, but nothing guarantees a later pass would look them up the | ||
| 1106 | - -- same way. `WHERE choices[0] != NONE AND type::is_string(choices[0])` | ||
| 1107 | - -- matches only unconverted rows, so a second boot re-mints nothing; an | ||
| 1108 | - -- empty or absent `choices` needs no conversion at all. A question-level | ||
| 1109 | - -- picture (`slot = NONE`) is not an index and is left alone. | ||
| 1110 | - -- | ||
| 1111 | - -- Runs *before* every other backfill that writes these rows (the `seq` | ||
| 1112 | - -- stamps below): a write coerces the whole record, so touching a row for | ||
| 1113 | - -- any reason fails while its choices are still positional. For the same | ||
| 1114 | - -- reason the answer's remap stamps `seq` itself — the two legacy gaps sit | ||
| 1115 | - -- on the same row, and a write that fixes only one of them is rejected for | ||
| 1116 | - -- the other. `seq ?? 1` leaves an already-numbered sitting alone (DEFAULT | ||
| 1117 | - -- fills a CREATE, not an UPDATE of a row that predates the column). | ||
| 1118 | - FOR $q IN ((SELECT id, choices, correct FROM exam_question | ||
| 1119 | - WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) { | ||
| 1120 | - LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c }); | ||
| 1121 | - UPDATE $q.id SET choices = $new, | ||
| 1122 | - correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id }; | ||
| 1123 | - FOR $img IN ((SELECT id, slot FROM question_image | ||
| 1124 | - WHERE question = $q.id AND type::is_int(slot)) ?? []) { | ||
| 1125 | - UPDATE $img.id SET slot = $new[$img.slot].id; | ||
| 1126 | - }; | ||
| 1127 | - FOR $ans IN ((SELECT id, selected FROM exam_answer | ||
| 1128 | - WHERE question = $q.id AND type::is_int(selected)) ?? []) { | ||
| 1129 | - UPDATE $ans.id SET selected = $new[$ans.selected].id, seq = seq ?? 1; | ||
| 1130 | - }; | ||
| 1131 | - }; | ||
| 1132 | - | ||
| 1133 | - FOR $q IN ((SELECT id, choices, correct FROM bank_question | ||
| 1134 | - WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) { | ||
| 1135 | - LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c }); | ||
| 1136 | - UPDATE $q.id SET choices = $new, | ||
| 1137 | - correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id }; | ||
| 1138 | - FOR $img IN ((SELECT id, slot FROM bank_question_image | ||
| 1139 | - WHERE bank_question = $q.id AND type::is_int(slot)) ?? []) { | ||
| 1140 | - UPDATE $img.id SET slot = $new[$img.slot].id; | ||
| 1141 | - }; | ||
| 1142 | - }; | ||
| 1143 | - | ||
| 1144 | - -- Per-attempt history (2026-07-24): sittings, answers, drawings, and marks | ||
| 1145 | - -- written before retakes stopped wiping belong to the student's first | ||
| 1146 | - -- sitting. They already use the bare (seq==1) record key, so only the | ||
| 1147 | - -- denormalized `seq` field needs stamping. | ||
| 1148 | - -- | ||
| 1149 | - -- `exam_attempt` was left out of this list when the other three were added | ||
| 1150 | - -- and that is not a decision, it is a gap: `DEFAULT 1` fills a CREATE, never | ||
| 1151 | - -- a row stored before the column was defined, and 3.2.3 does not synthesize | ||
| 1152 | - -- it on read either — such a row comes back with no `seq` key at all, which | ||
| 1153 | - -- makes `ExamAttempt` (a non-`option` `i64`) fail to deserialize *and* makes | ||
| 1154 | - -- every later write to the row fail coercion, so finishing or leaving that | ||
| 1155 | - -- sitting 500s forever. Ungated like its siblings and for the same reason: | ||
| 1156 | - -- the cost here is the write, not a scan, and `WHERE seq = NONE` matches | ||
| 1157 | - -- nothing the moment it has converged. | ||
| 1158 | - UPDATE exam_attempt SET seq = 1 WHERE seq = NONE; | ||
| 1159 | - UPDATE exam_answer SET seq = 1 WHERE seq = NONE; | ||
| 1160 | - UPDATE answer_image SET seq = 1 WHERE seq = NONE; | ||
| 1161 | - UPDATE exam_result SET seq = 1 WHERE seq = NONE; | ||
| 1162 | - | ||
| 1163 | - -- The homework freeze became cross-replica (2026-07-27): a grade that | ||
| 1164 | - -- predates the stamp column has to put it on the submission it already | ||
| 1165 | - -- froze, or that submission would read as open and be editable again. | ||
| 1166 | - -- Result and submission share the deterministic `{homework}_{user}` key, so | ||
| 1167 | - -- the owning row is addressed directly rather than searched for; an UPDATE | ||
| 1168 | - -- of a record that isn't there (graded absent work) is an empty no-op. The | ||
| 1169 | - -- `= NONE` guard keeps it one-time, for the same reason the counters below | ||
| 1170 | - -- are one-time — migrate() runs again on every boot against a volume the | ||
| 1171 | - -- live system has been writing to since. | ||
| 1172 | - FOR $r IN ((SELECT VALUE id FROM homework_result) ?? []) { | ||
| 1173 | - UPDATE type::record('homework_submission', record::id($r)) | ||
| 1174 | - SET graded_by_result = $r WHERE graded_by_result = NONE; | ||
| 1175 | - }; | ||
| 1176 | - | ||
| 1177 | - -- Count caps became cross-replica (2026-07-27): the authority moved from a | ||
| 1178 | - -- process-wide mutex to a counter column on the parent row, so every parent | ||
| 1179 | - -- that predates the column is seeded from the children it actually has. | ||
| 1180 | - -- Runs LAST, after the sweeps above have deleted whatever they delete. | ||
| 1181 | - -- | ||
| 1182 | - -- Deliberately one-time (`= NONE` guards every write): migrate() reruns on | ||
| 1183 | - -- every boot of an existing volume, and recounting a seeded counter would | ||
| 1184 | - -- overwrite what the live system has maintained since. An absent | ||
| 1185 | - -- counter reads as zero, so the group pass runs before the zero pass. | ||
| 1186 | - FOR $row IN ((SELECT course, count() AS n FROM enrollment GROUP BY course) ?? []) { | ||
| 1187 | - UPDATE $row.course SET enrollment_count = $row.n WHERE enrollment_count = NONE; | ||
| 1188 | - }; | ||
| 1189 | - UPDATE course SET enrollment_count = 0 WHERE enrollment_count = NONE; | ||
| 1190 | - | ||
| 1191 | - -- The one refcount among them: courses per term, not children per parent. | ||
| 1192 | - -- Same one-time `= NONE` guard, and `WHERE term != NONE` keeps the | ||
| 1193 | - -- unlinked courses out of the group (they would form a NONE bucket). | ||
| 1194 | - FOR $row IN ((SELECT term, count() AS n FROM course WHERE term != NONE GROUP BY term) ?? []) { | ||
| 1195 | - UPDATE $row.term SET course_count = $row.n WHERE course_count = NONE; | ||
| 1196 | - }; | ||
| 1197 | - UPDATE term SET course_count = 0 WHERE course_count = NONE; | ||
| 1198 | - | ||
| 1199 | - FOR $row IN ((SELECT event, count() AS n FROM registration GROUP BY event) ?? []) { | ||
| 1200 | - UPDATE $row.event SET registration_count = $row.n WHERE registration_count = NONE; | ||
| 1201 | - }; | ||
| 1202 | - UPDATE event SET registration_count = 0 WHERE registration_count = NONE; | ||
| 1203 | - | ||
| 1204 | - FOR $row IN ((SELECT note, count() AS n FROM note_file GROUP BY note) ?? []) { | ||
| 1205 | - UPDATE $row.note SET file_count = $row.n WHERE file_count = NONE; | ||
| 1206 | - }; | ||
| 1207 | - UPDATE note SET file_count = 0 WHERE file_count = NONE; | ||
| 1208 | - | ||
| 1209 | - FOR $row IN ((SELECT submission, count() AS n FROM homework_file GROUP BY submission) ?? []) { | ||
| 1210 | - UPDATE $row.submission SET file_count = $row.n WHERE file_count = NONE; | ||
| 1211 | - }; | ||
| 1212 | - UPDATE homework_submission SET file_count = 0 WHERE file_count = NONE; | ||
| 1213 | - | ||
| 1214 | - FOR $row IN ((SELECT user_id, count() AS n FROM chatbot_thread GROUP BY user_id) ?? []) { | ||
| 1215 | - UPDATE $row.user_id SET chatbot_thread_count = $row.n WHERE chatbot_thread_count = NONE; | ||
| 1216 | - }; | ||
| 1217 | - UPDATE user SET chatbot_thread_count = 0 WHERE chatbot_thread_count = NONE; | ||
| 1218 | - | ||
| 1219 | - -- The appointment slot's counter is the odd one out: it counts only the | ||
| 1220 | - -- bookings that are still *live*, because a rejected or cancelled one gave | ||
| 1221 | - -- the slot back long before this column existed. | ||
| 1222 | - FOR $row IN ((SELECT slot, count() AS n FROM appointment | ||
| 1223 | - WHERE status IN ['pending', 'approved'] GROUP BY slot) ?? []) { | ||
| 1224 | - UPDATE $row.slot SET occupied = $row.n WHERE occupied = NONE; | ||
| 1225 | - }; | ||
| 1226 | - UPDATE appointment_slot SET occupied = 0 WHERE occupied = NONE; | ||
| 1227 | - | ||
| 1228 | - -- A menu's seats, counted from the bookings still *held* — a cancelled one | ||
| 1229 | - -- gave its seat back before this column existed, exactly like the slot | ||
| 1230 | - -- above. `version` gets no pass at all: absent already reads as revision | ||
| 1231 | - -- zero everywhere it is compared, so writing it would be a no-op that | ||
| 1232 | - -- touches every menu row. | ||
| 1233 | - FOR $row IN ((SELECT menu, count() AS n FROM meal_booking | ||
| 1234 | - WHERE status = 'booked' GROUP BY menu) ?? []) { | ||
| 1235 | - UPDATE $row.menu SET seats_booked = $row.n WHERE seats_booked = NONE; | ||
| 1236 | - }; | ||
| 1237 | - UPDATE menu SET seats_booked = 0 WHERE seats_booked = NONE; | ||
| 1238 | - | ||
| 1239 | - -- A subject's two reference counters, seeded from what actually points at | ||
| 1240 | - -- it. This must run *after* the legacy sweep above destroys the questions | ||
| 1241 | - -- that predate subjects, or a subject would be seeded with rows that are | ||
| 1242 | - -- about to vanish and could then never be deleted. No zero pass, for the | ||
| 1243 | - -- same reason `version` gets none: absent already reads as zero in the | ||
| 1244 | - -- delete's `(count ?? 0) = 0` guard, so writing it would touch every | ||
| 1245 | - -- subject row to say what it already says. | ||
| 1246 | - FOR $row IN ((SELECT subject, count() AS n FROM exam_question GROUP BY subject) ?? []) { | ||
| 1247 | - UPDATE $row.subject SET exam_question_count = $row.n WHERE exam_question_count = NONE; | ||
| 1248 | - }; | ||
| 1249 | - | ||
| 1250 | - FOR $row IN ((SELECT subject, count() AS n FROM homework GROUP BY subject) ?? []) { | ||
| 1251 | - UPDATE $row.subject SET homework_count = $row.n WHERE homework_count = NONE; | ||
| 1252 | - }; | ||
| 1253 | - | ||
| 1254 | - -- The settings guards became cross-replica the same way (2026-07-27): an | ||
| 1255 | - -- exam kind counts the marks written under it, a meal slot the menus | ||
| 1256 | - -- published for it, and a name is removable exactly while its counter reads | ||
| 1257 | - -- zero. Rows written before the counters existed are counted once here. | ||
| 1258 | - -- | ||
| 1259 | - -- Same `= NONE` guard and the same reason as the caps above: migrate() | ||
| 1260 | - -- reruns on every boot of an existing volume, and recounting a seeded | ||
| 1261 | - -- counter would overwrite what the live system has maintained since, handing | ||
| 1262 | - -- back a reference that is still held. No zero pass either — an | ||
| 1263 | - -- absent counter already reads as zero, and a name nobody ever used needs | ||
| 1264 | - -- no row at all. | ||
| 1265 | - -- | ||
| 1266 | - -- Marks predate the counter but so may their *kind*: an exam whose kind was | ||
| 1267 | - -- removed from the list long ago is counted too, which only ever refuses a | ||
| 1268 | - -- removal that already happened. `slot` is text on the menu, so its group | ||
| 1269 | - -- needs no join; `kind` lives on the exam, one hop from the mark. | ||
| 1270 | - FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result GROUP BY kind) ?? []) { | ||
| 1271 | - UPSERT type::record('kind_ref', $row.kind) SET count = $row.n WHERE count = NONE; | ||
| 1272 | - }; | ||
| 1273 | - | ||
| 1274 | - FOR $row IN ((SELECT slot, count() AS n FROM menu GROUP BY slot) ?? []) { | ||
| 1275 | - UPSERT type::record('slot_ref', $row.slot) SET count = $row.n WHERE count = NONE; | ||
| 1276 | - }; | ||
| 1277 | - | ||
| 1278 | - -- Same one-time seeding for the per-exam mark counter: an exam graded by an | ||
| 1279 | - -- older binary must read as graded, or its kind could be changed under the | ||
| 1280 | - -- marks it already carries. | ||
| 1281 | - FOR $row IN ((SELECT exam, count() AS n FROM exam_result GROUP BY exam) ?? []) { | ||
| 1282 | - UPDATE $row.exam SET result_count = $row.n WHERE result_count = NONE; | ||
| 1283 | - }; | ||
| 1284 | - | ||
| 1285 | - -- The fee-plan guard became a refcount (2026-07-30): editing or deleting a | ||
| 1286 | - -- plan is now refused by `(assignment_count ?? 0) = 0` on the plan row | ||
| 1287 | - -- itself, instead of by a scan a concurrent assign could land behind. | ||
| 1288 | - -- | ||
| 1289 | - -- This seeding is what keeps a *stale* volume safe: a plan written by an | ||
| 1290 | - -- older binary carries no counter, an absent counter reads as zero, and a | ||
| 1291 | - -- zero would make an already-assigned plan editable and deletable again — | ||
| 1292 | - -- the exact thing the 409 exists to prevent. Boot seeds it from the | ||
| 1293 | - -- assignment rows that actually exist, and `migrate` runs to completion | ||
| 1294 | - -- before the router is bound, so no request is ever served against the | ||
| 1295 | - -- unseeded shape. `= NONE` keeps it one-time, so a second boot recomputes | ||
| 1296 | - -- nothing. | ||
| 1297 | - -- | ||
| 1298 | - -- No zero pass, for the same reason the subject counters get none: a plan | ||
| 1299 | - -- nobody is on has no assignment rows, and absent already reads as zero in | ||
| 1300 | - -- the guard — writing it would touch every plan row to say what it says. | ||
| 1301 | - FOR $row IN ((SELECT plan, count() AS n FROM fee_plan_assignment GROUP BY plan) ?? []) { | ||
| 1302 | - UPDATE $row.plan SET assignment_count = $row.n WHERE assignment_count = NONE; | ||
| 1303 | - }; | ||
| 1304 | - | ||
| 1305 | - -- The clear marker began paying the board's lifetime counter (2026-08-02): | ||
| 1306 | - -- it is a real `board_stroke` row, so a marker that charged nothing left | ||
| 1307 | - -- `total_stroke_count` counting marks *drawn* instead of rows *stored*, and | ||
| 1308 | - -- every board an older binary cleared is short exactly one per past clear. | ||
| 1309 | - -- | ||
| 1310 | - -- The only repair here that is NOT `= NONE`-guarded, and the one counter | ||
| 1311 | - -- that may be: it is not an opinion the live system maintains, it is the | ||
| 1312 | - -- board's row count — every stroke and every marker charges 1, and a stroke | ||
| 1313 | - -- row is only ever deleted with the board itself (domain::board_stroke). | ||
| 1314 | - -- So recomputing converges instead of overwriting, and `!= $row.n` writes | ||
| 1315 | - -- nothing on the next boot, when every counter already equals its count. | ||
| 1316 | - -- No zero pass: a board nobody drew on forms no group, and an absent | ||
| 1317 | - -- counter already reads as zero through the `?? 0` every reader applies. | ||
| 1318 | - FOR $row IN ((SELECT board, count() AS n FROM board_stroke GROUP BY board) ?? []) { | ||
| 1319 | - UPDATE $row.board SET total_stroke_count = $row.n WHERE total_stroke_count != $row.n; | ||
| 1320 | - }; | ||
| 1321 | - | ||
| 1322 | - -- Board rosters became self-repairing (2026-08-02). `set_role` sweeps a | ||
| 1323 | - -- demoted user off every board *going forward*, but a volume written before | ||
| 1324 | - -- that sweep still holds rosters naming parents — and ids of users who have | ||
| 1325 | - -- since been deleted outright, which no sweep ever covered. | ||
| 1326 | - -- | ||
| 1327 | - -- It is not a cosmetic staleness: the roster is served back on every read | ||
| 1328 | - -- and `resolve_participants` refuses an id that no longer resolves to a | ||
| 1329 | - -- student-or-above, so the creator's next read-modify-write roster PATCH | ||
| 1330 | - -- echoes the stale id and takes a 400 — the board's invite list is frozen | ||
| 1331 | - -- until the row is repaired. | ||
| 1332 | - -- | ||
| 1333 | - -- `parent` is the only role below `student` (domain::role), so `!= 'parent'` | ||
| 1334 | - -- is the same cut `Role::at_least(Student)` makes; a missing user matches no | ||
| 1335 | - -- row and so falls out of `$keep` for free. A board whose whole roster is | ||
| 1336 | - -- stale ends with `participants = []` — the creator alone on it, which is | ||
| 1337 | - -- the same shape a board created without invites carries. Not `= NONE` | ||
| 1338 | - -- guarded and it need not be: `$keep` is derived from the rows that exist, | ||
| 1339 | - -- so it converges, and `WHERE participants != $keep` writes nothing on the | ||
| 1340 | - -- next boot. `$keep` comes back deduped and in record-id order, so a | ||
| 1341 | - -- repaired row can be *reordered* relative to what it stored, never | ||
| 1342 | - -- duplicated — and the roster is a set to every reader. | ||
| 1343 | - -- | ||
| 1344 | - -- Marked one-time (`migration_mark`), unlike every backfill above it. Those | ||
| 1345 | - -- converge to a `WHERE` that matches nothing, so their second run is a cheap | ||
| 1346 | - -- index probe; this one's cost is the *scan* — a `board` table scan whose | ||
| 1347 | - -- body runs a full `user` scan per row, measured at 773ms for 300 boards | ||
| 1348 | - -- over 2000 users on a boot with nothing left to write. That is paid on | ||
| 1349 | - -- every restart forever, and it buys nothing: `set_role` sweeps rosters | ||
| 1350 | - -- going forward and a deleted user is swept with its row, so no new stale id | ||
| 1351 | - -- is ever created. The mark is written *after* the loop and in the same | ||
| 1352 | - -- statement batch, so a boot killed mid-repair writes no mark and the next | ||
| 1353 | - -- one redoes the whole sweep — which is free, because the sweep is | ||
| 1354 | - -- idempotent. `UPSERT`, not `CREATE`: re-marking must never be an error. | ||
| 1355 | - -- | ||
| 1356 | - -- Editing this block is therefore safe at any time: the fingerprint gate | ||
| 1357 | - -- re-runs it once and the sweep converges on whatever it finds, exactly as | ||
| 1358 | - -- a boot killed mid-repair would. The mark buys the scan back, not | ||
| 1359 | - -- correctness. | ||
| 1360 | - IF array::len((SELECT VALUE id FROM migration_mark:board_roster | ||
| 1361 | - WHERE fingerprint = $fp_board_roster)) = 0 { | ||
| 1362 | - FOR $row IN ((SELECT id, participants FROM board WHERE array::len(participants ?? []) > 0) ?? []) { | ||
| 1363 | - LET $keep = (SELECT VALUE id FROM user WHERE id IN $row.participants AND role != 'parent'); | ||
| 1364 | - UPDATE $row.id SET participants = $keep WHERE participants != $keep; | ||
| 1365 | - }; | ||
| 1366 | - UPSERT migration_mark:board_roster SET done_at = time::unix(time::now()) * 1000, | ||
| 1367 | - fingerprint = $fp_board_roster; | ||
| 1368 | - }; | ||
| 1369 | - | ||
| 1370 | - -- The badge counters, seeded from the history that already exists | ||
| 1371 | - -- (2026-08-04). Badges are earned off stored lifetime totals, and every | ||
| 1372 | - -- account on an existing volume predates the columns — so starting them all | ||
| 1373 | - -- at zero would not merely lose a number, it would mis-award every student | ||
| 1374 | - -- permanently: someone who really handed in 40 homeworks would owe 10 *more* | ||
| 1375 | - -- than a new account does to reach the same badge. The counts below are the | ||
| 1376 | - -- rows that exist, so the seed says exactly what the student did. | ||
| 1377 | - -- | ||
| 1378 | - -- Marked one-time, like the board-roster sweep above and unlike every other | ||
| 1379 | - -- backfill in this file — but for the opposite reason. Those recompute a | ||
| 1380 | - -- number the live system does not own; these columns are maintained by the | ||
| 1381 | - -- request path from here on (a submission increments as it lands), so a | ||
| 1382 | - -- second recount would not converge, it would *overwrite* everything earned | ||
| 1383 | - -- since boot. The mark is the only thing that makes that safe. | ||
| 1384 | - -- | ||
| 1385 | - -- The reset is inside the mark and comes first, so the whole block is | ||
| 1386 | - -- recompute-from-scratch: a boot killed mid-seed writes no mark and the next | ||
| 1387 | - -- one redoes it from a clean slate, and an operator who clears the mark to | ||
| 1388 | - -- force a re-seed gets the counts as they stand rather than a stale high | ||
| 1389 | - -- water mark. It is the one place a *zero pass* is right: it writes over | ||
| 1390 | - -- whatever a half-finished pass left, and it runs exactly once per volume. | ||
| 1391 | - -- | ||
| 1392 | - -- Every counter here has to *mean* what the request path means, or a | ||
| 1393 | - -- pre-existing student diverges from a new one forever. So the on-time cut | ||
| 1394 | - -- is `submitted_at <= due_at`, the stamp both live sites use: the create | ||
| 1395 | - -- credits on the first hand-in and the delete debits by `submitted_at`, so | ||
| 1396 | - -- judging the seed by `updated_at` would let a withdrawal decrement a | ||
| 1397 | - -- submission the seed never credited and drive the counter *below* the | ||
| 1398 | - -- truth — and `touch()` moves `updated_at` on every file add or delete, so | ||
| 1399 | - -- merely attaching a file after the deadline would have done it. A dangling | ||
| 1400 | - -- `homework` link still falls out of the pass rather than counting as on | ||
| 1401 | - -- time (the traversal yields no value, so the comparison fails). | ||
| 1402 | - -- | ||
| 1403 | - -- The focus sum floors *per row*, like the live close does | ||
| 1404 | - -- (`math::max([started_at, done])`), not per user: a legacy stint written | ||
| 1405 | - -- with a backwards clock is negative, and flooring the total instead would | ||
| 1406 | - -- let one such row swallow the real stints beside it. `math::max` *around* | ||
| 1407 | - -- the aggregate is the spelling that is rejected ('nested aggregate | ||
| 1408 | - -- functions are not supported'); inside it, per row, is fine. | ||
| 1409 | - -- | ||
| 1410 | - -- Two counters the seed cannot make whole, for the same reason: | ||
| 1411 | - -- `exam_sat_total` (deleting an exam or a course deletes its `exam_attempt` | ||
| 1412 | - -- rows) and `homework_submitted_total` (deleting a homework cascades its | ||
| 1413 | - -- `homework_submission` rows away). Neither delete decrements — deliberate, | ||
| 1414 | - -- a lifetime 'did it' tally must not shrink because a teacher tidied up — so | ||
| 1415 | - -- the live count stands where the request path left it while a re-seed of | ||
| 1416 | - -- the same volume would read *lower*: the rows do not exist to be counted. | ||
| 1417 | - -- Do not 'repair' this by making the live path decrement; that breaks the | ||
| 1418 | - -- tally for everyone to patch history for a few. | ||
| 1419 | - -- | ||
| 1420 | - -- `counted_on_time` is stamped here too, for every row the pass looks at and | ||
| 1421 | - -- by the very same cut, so a submission that predates this seed debits at | ||
| 1422 | - -- withdrawal exactly what the seed credited it. Absolute like every SET | ||
| 1423 | - -- below, so it converges on a forced re-seed. | ||
| 1424 | - -- | ||
| 1425 | - -- corner-cut: editing this block re-runs it (the fingerprint gate), and unlike | ||
| 1426 | - -- the board sweep above this one is only *mostly* re-runnable. Every SET is | ||
| 1427 | - -- absolute, so a re-run converges on the rows that exist — but two of the | ||
| 1428 | - -- counters are lifetime tallies the request path never decrements while the | ||
| 1429 | - -- rows behind them can be deleted (`exam_sat_total`, | ||
| 1430 | - -- `homework_submitted_total`, see the paragraph above). On a volume where a | ||
| 1431 | - -- teacher has deleted an exam or a homework since the last seed, a re-run | ||
| 1432 | - -- reads *lower* than the live count and the student's tally walks backwards | ||
| 1433 | - -- — badges already awarded are permanent, so nothing is revoked, but the | ||
| 1434 | - -- next one moves further away. Correcting this block is a deliberate trade, | ||
| 1435 | - -- not a free edit. The upgrade path, if it ever needs to be free: keep the | ||
| 1436 | - -- deleted rows' contribution on the row (a `*_retired` column the delete | ||
| 1437 | - -- bumps) so the recount can add it back. | ||
| 1438 | - IF array::len((SELECT VALUE id FROM migration_mark:profile_counters | ||
| 1439 | - WHERE fingerprint = $fp_profile_counters)) = 0 { | ||
| 1440 | - UPDATE user SET homework_submitted_total = 0, homework_on_time_total = 0, | ||
| 1441 | - exam_sat_total = 0, pomodoro_finished_total = 0, pomodoro_focus_ms_total = 0; | ||
| 1442 | - FOR $row IN ((SELECT user, count() AS n FROM homework_submission GROUP BY user) ?? []) { | ||
| 1443 | - UPDATE $row.user SET homework_submitted_total = $row.n; | ||
| 1444 | - }; | ||
| 1445 | - FOR $row IN ((SELECT user, count() AS n FROM homework_submission | ||
| 1446 | - WHERE submitted_at <= homework.due_at GROUP BY user) ?? []) { | ||
| 1447 | - UPDATE $row.user SET homework_on_time_total = $row.n; | ||
| 1448 | - }; | ||
| 1449 | - UPDATE homework_submission SET counted_on_time = submitted_at <= homework.due_at; | ||
| 1450 | - -- `(seq ?? 1) = 1` is one row per (exam, student) pair, so this counts | ||
| 1451 | - -- *exams sat* — what the request path credits (a retake writes a higher | ||
| 1452 | - -- seq and moves nothing). Counting every row instead would seed a | ||
| 1453 | - -- pre-existing student above a new one for the same work, and above | ||
| 1454 | - -- what the live path would ever give them again. | ||
| 1455 | - FOR $row IN ((SELECT user, count() AS n FROM exam_attempt | ||
| 1456 | - WHERE (seq ?? 1) = 1 GROUP BY user) ?? []) { | ||
| 1457 | - UPDATE $row.user SET exam_sat_total = $row.n; | ||
| 1458 | - }; | ||
| 1459 | - FOR $row IN ((SELECT user, count() AS sessions, | ||
| 1460 | - math::sum(math::max([finished_at - started_at, 0])) AS focus_ms | ||
| 1461 | - FROM pomodoro_session WHERE finished_at != NONE GROUP BY user) ?? []) { | ||
| 1462 | - UPDATE $row.user SET pomodoro_finished_total = $row.sessions, | ||
| 1463 | - pomodoro_focus_ms_total = $row.focus_ms; | ||
| 1464 | - }; | ||
| 1465 | - UPSERT migration_mark:profile_counters SET done_at = time::unix(time::now()) * 1000, | ||
| 1466 | - fingerprint = $fp_profile_counters; | ||
| 1467 | - }; | ||
| 1468 | -"; | ||
| 1469 | - | ||
| 1470 | -/// The **control** database's schema — the one database per deployment that | ||
| 1471 | -/// knows which schools exist and who may create them. Everything else lives in | ||
| 1472 | -/// a school database, whose schema is [`MIGRATION_BATCHES`] and is applied | ||
| 1473 | -/// per school by [`crate::tenant::Tenants::create`]. | ||
| 1474 | -/// | ||
| 1475 | -/// The `rate_limit` copy is deliberate: the shared per-IP window | ||
| 1476 | -/// (`crate::rate_limit::RateLimiter::share`) is billed against the control | ||
| 1477 | -/// handle, because the limiter runs in front of the router — before any cookie | ||
| 1478 | -/// has named a school. One budget per deployment is also the honest one for an | ||
| 1479 | -/// unauthenticated brute-forcer, who has not picked a school yet either. | ||
| 1480 | -pub const CONTROL_MIGRATION: &str = " | ||
| 1481 | - DEFINE TABLE IF NOT EXISTS school SCHEMAFULL; | ||
| 1482 | - DEFINE FIELD IF NOT EXISTS slug ON school TYPE string; | ||
| 1483 | - DEFINE FIELD IF NOT EXISTS name ON school TYPE string; | ||
| 1484 | - DEFINE FIELD IF NOT EXISTS status ON school TYPE string; | ||
| 1485 | - DEFINE FIELD IF NOT EXISTS created_at ON school TYPE int; | ||
| 1486 | - -- Which product modules this school has bought (see `crate::module`). The | ||
| 1487 | - -- names are bound from `Module::ALL`, never spelled here, so a new module | ||
| 1488 | - -- cannot be forgotten in this string. | ||
| 1489 | - DEFINE FIELD IF NOT EXISTS modules ON school TYPE array<string> DEFAULT []; | ||
| 1490 | - -- Only `NONE` — a row written before the field existed, which predates the | ||
| 1491 | - -- idea of buying modules and so had all of them. An empty array is a | ||
| 1492 | - -- deliberate \"nothing enabled\" and must never be re-widened by a boot. | ||
| 1493 | - UPDATE school SET modules = $all_modules WHERE modules = NONE; | ||
| 1494 | - -- Redundant with the `school:<slug>` id, and kept anyway: the id is the | ||
| 1495 | - -- fast path, the index is what makes a second row on the same slug | ||
| 1496 | - -- impossible if a future write ever mints an id some other way. | ||
| 1497 | - DEFINE INDEX IF NOT EXISTS school_slug ON school FIELDS slug UNIQUE; | ||
| 1498 | - | ||
| 1499 | - DEFINE TABLE IF NOT EXISTS builder SCHEMAFULL; | ||
| 1500 | - DEFINE FIELD IF NOT EXISTS username ON builder TYPE string; | ||
| 1501 | - DEFINE FIELD IF NOT EXISTS password_hash ON builder TYPE string; | ||
| 1502 | - DEFINE INDEX IF NOT EXISTS builder_username ON builder FIELDS username UNIQUE; | ||
| 1503 | - | ||
| 1504 | - DEFINE TABLE IF NOT EXISTS builder_session SCHEMAFULL; | ||
| 1505 | - DEFINE FIELD IF NOT EXISTS builder ON builder_session TYPE record<builder>; | ||
| 1506 | - DEFINE FIELD IF NOT EXISTS token ON builder_session TYPE string; | ||
| 1507 | - DEFINE FIELD IF NOT EXISTS created_at ON builder_session TYPE int; | ||
| 1508 | - DEFINE FIELD IF NOT EXISTS expires_at ON builder_session TYPE int; | ||
| 1509 | - DEFINE INDEX IF NOT EXISTS builder_session_token ON builder_session FIELDS token UNIQUE; | ||
| 1510 | - DEFINE INDEX IF NOT EXISTS builder_session_expires ON builder_session FIELDS expires_at; | ||
| 1511 | - | ||
| 1512 | - -- Verbatim from `MIGRATION`; see the note above this constant. | ||
| 1513 | - DEFINE TABLE IF NOT EXISTS rate_limit SCHEMAFULL; | ||
| 1514 | - DEFINE FIELD IF NOT EXISTS hits ON rate_limit TYPE int DEFAULT 0; | ||
| 1515 | - DEFINE FIELD IF NOT EXISTS window_start ON rate_limit TYPE int; | ||
| 1516 | -"; | ||
| 1517 | - | ||
| 1518 | -pub const CONTROL_MIGRATION_BATCHES: [&str; 1] = [CONTROL_MIGRATION]; | ||
| 1519 | - | ||
| 1520 | -/// The migration batches, in the order a boot applies them — and the *only* | ||
| 1521 | -/// list of them. [`crate::database::migrate`] runs exactly these. They stay | ||
| 1522 | -/// three separate queries: statements in one batch see the schema as it stood | ||
| 1523 | -/// when the batch started (see `MIGRATION`). | ||
| 1524 | -pub const MIGRATION_BATCHES: [&str; 3] = [PRE_REPAIR, MIGRATION, BACKFILL]; | ||
src/rate_limit.rsmodified+59 -122
| @@ -86,7 +86,6 @@ use std::time::Duration; | |||
| 86 | use axum::extract::{ConnectInfo, Request}; | 86 | use axum::extract::{ConnectInfo, Request}; |
| 87 | use axum::middleware::Next; | 87 | use axum::middleware::Next; |
| 88 | use axum::response::Response; | 88 | use axum::response::Response; |
| 89 | -use surrealdb::types::RecordId; | ||
| 90 | // tokio's `Instant` wraps `std::time::Instant` in production but obeys | 89 | // tokio's `Instant` wraps `std::time::Instant` in production but obeys |
| 91 | // `tokio::time::pause`/`advance` under `start_paused` tests, which makes the | 90 | // `tokio::time::pause`/`advance` under `start_paused` tests, which makes the |
| 92 | // window arithmetic below testable without sleeping. | 91 | // window arithmetic below testable without sleeping. |
| @@ -99,7 +98,6 @@ use crate::constant::{ | |||
| 99 | use crate::database::Database; | 98 | use crate::database::Database; |
| 100 | use crate::domain::timestamp::Timestamp; | 99 | use crate::domain::timestamp::Timestamp; |
| 101 | use crate::error::AppError; | 100 | use crate::error::AppError; |
| 102 | -use crate::state::DbHealth; | ||
| 103 | use crate::telemetry::Metrics; | 101 | use crate::telemetry::Metrics; |
| 104 | 102 | ||
| 105 | /// Per-IP rate-limit knobs, sourced from the environment (see `.env.example`) and | 103 | /// Per-IP rate-limit knobs, sourced from the environment (see `.env.example`) and |
| @@ -221,7 +219,7 @@ impl<K> RateLimiter<K> { | |||
| 221 | } | 219 | } |
| 222 | } | 220 | } |
| 223 | 221 | ||
| 224 | -/// The per-user tier, keyed by user record key instead of client IP. Lives in | 222 | +/// The per-user tier, keyed by user id instead of client IP. Lives in |
| 225 | /// [`crate::state::AppState`] and is called from inside a handler, after | 223 | /// [`crate::state::AppState`] and is called from inside a handler, after |
| 226 | /// `CurrentUser` has identified the caller. | 224 | /// `CurrentUser` has identified the caller. |
| 227 | pub type UserRateLimiter = RateLimiter<String>; | 225 | pub type UserRateLimiter = RateLimiter<String>; |
| @@ -433,8 +431,8 @@ where | |||
| 433 | /// The task holds a *weak* reference to the buckets, so it stops with the | 431 | /// The task holds a *weak* reference to the buckets, so it stops with the |
| 434 | /// limiter rather than keeping a dropped one alive (test suites build | 432 | /// limiter rather than keeping a dropped one alive (test suites build |
| 435 | /// dozens). | 433 | /// dozens). |
| 436 | - pub fn share(&self, tier: &'static str, db: Database, db_up: DbHealth) { | 434 | + pub fn share(&self, tier: &'static str, db: Database) { |
| 437 | - self.share_windowed(tier, db, db_up, None); | 435 | + self.share_windowed(tier, db, None); |
| 438 | } | 436 | } |
| 439 | 437 | ||
| 440 | /// [`RateLimiter::share`] with the wall window pinned, for tests only. | 438 | /// [`RateLimiter::share`] with the wall window pinned, for tests only. |
| @@ -445,17 +443,11 @@ where | |||
| 445 | /// would see the other's spend. An accidental relationship to the wall | 443 | /// would see the other's spend. An accidental relationship to the wall |
| 446 | /// clock is precisely what kept the epoch-roll double-charge out of | 444 | /// clock is precisely what kept the epoch-roll double-charge out of |
| 447 | /// `tests/rate_limit.rs`, so the sharing tests choose their window instead. | 445 | /// `tests/rate_limit.rs`, so the sharing tests choose their window instead. |
| 448 | - pub fn share_pinned(&self, tier: &'static str, db: Database, db_up: DbHealth, epoch: i64) { | 446 | + pub fn share_pinned(&self, tier: &'static str, db: Database, epoch: i64) { |
| 449 | - self.share_windowed(tier, db, db_up, Some(epoch)); | 447 | + self.share_windowed(tier, db, Some(epoch)); |
| 450 | } | 448 | } |
| 451 | 449 | ||
| 452 | - fn share_windowed( | 450 | + fn share_windowed(&self, tier: &'static str, db: Database, pinned: Option<i64>) { |
| 453 | - &self, | ||
| 454 | - tier: &'static str, | ||
| 455 | - db: Database, | ||
| 456 | - db_up: DbHealth, | ||
| 457 | - pinned: Option<i64>, | ||
| 458 | - ) { | ||
| 459 | // Before the early return: a disabled tier still wants its name, so a | 451 | // Before the early return: a disabled tier still wants its name, so a |
| 460 | // limiter turned on later reports under it. | 452 | // limiter turned on later reports under it. |
| 461 | let _ = self.tier.set(tier); | 453 | let _ = self.tier.set(tier); |
| @@ -473,20 +465,19 @@ where | |||
| 473 | let Some(buckets) = buckets.upgrade() else { | 465 | let Some(buckets) = buckets.upgrade() else { |
| 474 | return; | 466 | return; |
| 475 | }; | 467 | }; |
| 476 | - // Never queue work on a database that is down: the SDK parks a | 468 | + // `with_deadline` bounds every round, so an outage costs the |
| 477 | - // query instead of failing it, so this task would sit on a | 469 | + // sharing nothing but skipped rounds: local budgets keep |
| 478 | - // round for the whole outage and then apply a stale total. | 470 | + // admitting and the deltas ride the first round after recovery. |
| 479 | - if !db_up.is_up() { | ||
| 480 | - continue; | ||
| 481 | - } | ||
| 482 | let epoch = pinned.unwrap_or_else(|| current_epoch(window)); | 471 | let epoch = pinned.unwrap_or_else(|| current_epoch(window)); |
| 483 | sync_once(tier, &buckets, window, epoch, &db).await; | 472 | sync_once(tier, &buckets, window, epoch, &db).await; |
| 484 | // Piggybacked cleanup, once per window: rows for a window that | 473 | // Piggybacked cleanup, once per window: rows for a window that |
| 485 | // has passed can never be read again. | 474 | // has passed can never be read again. |
| 486 | if swept != epoch { | 475 | if swept != epoch { |
| 487 | swept = epoch; | 476 | swept = epoch; |
| 488 | - let sql = format!("DELETE {RATE_LIMIT_TABLE} WHERE window_start < $cutoff"); | 477 | + let sql = format!("DELETE FROM {RATE_LIMIT_TABLE} WHERE window_start < $1"); |
| 489 | - if let Err(err) = with_deadline(db.query(sql).bind(("cutoff", epoch))).await { | 478 | + if let Err(err) = |
| 479 | + with_deadline(sqlx::query(&sql).bind(epoch).execute(&db)).await | ||
| 480 | + { | ||
| 490 | tracing::warn!(%err, "rate-limit sweep failed; retrying next window"); | 481 | tracing::warn!(%err, "rate-limit sweep failed; retrying next window"); |
| 491 | } | 482 | } |
| 492 | } | 483 | } |
| @@ -495,14 +486,17 @@ where | |||
| 495 | } | 486 | } |
| 496 | } | 487 | } |
| 497 | 488 | ||
| 498 | -/// Fold every live bucket's new admits into its shared row and take the | 489 | +/// Fold every live bucket's new admits into their shared rows and take the |
| 499 | -/// window's total back. | 490 | +/// window's totals back. |
| 500 | /// | 491 | /// |
| 501 | -/// One statement per bucket in one query, and each statement is its own | 492 | +/// The whole round is one statement: `INSERT … ON CONFLICT (id) DO UPDATE SET |
| 502 | -/// transaction — so a statement that loses a write race fails alone. Its bucket | 493 | +/// hits = rate_limit.hits + EXCLUDED.hits RETURNING id, hits`, so a fold is |
| 503 | -/// simply keeps the delta unreported and the next round (2s later) carries it, | 494 | +/// atomic — the old engine could fail one bucket's statement inside a round, |
| 504 | -/// which is why no retry loop is needed here: retrying the *query* would | 495 | +/// Postgres cannot fail half a statement. A round that fails (deadline, |
| 505 | -/// double-apply the statements that did land, since `hits` accumulates. | 496 | +/// outage) lands nothing: every bucket keeps its delta unreported and the |
| 497 | +/// next round (2s later) carries it, which is why no retry loop is needed | ||
| 498 | +/// here. Retrying the *statement* would double-apply the hits that landed, | ||
| 499 | +/// since the fold accumulates — skipping a round is the only honest failure. | ||
| 506 | async fn sync_once<K: Eq + Hash + Clone + std::fmt::Display>( | 500 | async fn sync_once<K: Eq + Hash + Clone + std::fmt::Display>( |
| 507 | tier: &str, | 501 | tier: &str, |
| 508 | buckets: &Mutex<HashMap<K, Bucket>>, | 502 | buckets: &Mutex<HashMap<K, Bucket>>, |
| @@ -551,34 +545,38 @@ async fn sync_once<K: Eq + Hash + Clone + std::fmt::Display>( | |||
| 551 | return; | 545 | return; |
| 552 | } | 546 | } |
| 553 | 547 | ||
| 554 | - let sql: String = (0..pending.len()) | 548 | + // One statement for the whole round. A row's id pins its wall window |
| 555 | - .map(|i| { | 549 | + // (`row_key` folds the epoch in), so a conflict can only be another |
| 556 | - format!("UPSERT $id{i} SET hits = (hits ?? 0) + $delta{i}, window_start = $window RETURN VALUE hits;") | 550 | + // limiter of the same tier folding the same client inside the same window |
| 557 | - }) | 551 | + // — the ON CONFLICT fold is exactly the replay that must add, not clobber. |
| 558 | - .collect(); | 552 | + let mut fold = sqlx::QueryBuilder::<sqlx::Postgres>::new(); |
| 559 | - let mut query = db.query(sql).bind(("window", epoch)); | 553 | + fold.push("INSERT INTO ") |
| 560 | - for (i, p) in pending.iter().enumerate() { | 554 | + .push(RATE_LIMIT_TABLE) |
| 561 | - let id = RecordId::new(RATE_LIMIT_TABLE, row_key(tier, &p.key, epoch)); | 555 | + .push(" (id, hits, window_start) "); |
| 562 | - query = query | 556 | + fold.push_values(pending.iter(), |mut b, p| { |
| 563 | - .bind((format!("id{i}"), id)) | 557 | + b.push_bind(row_key(tier, &p.key, epoch)) |
| 564 | - .bind((format!("delta{i}"), i64::from(p.delta))); | 558 | + .push_bind(i64::from(p.delta)) |
| 565 | - } | 559 | + .push_bind(epoch); |
| 566 | - let mut response = match with_deadline(query).await { | 560 | + }); |
| 567 | - Ok(response) => response, | 561 | + fold.push(" ON CONFLICT (id) DO UPDATE SET hits = rate_limit.hits + EXCLUDED.hits RETURNING id, hits"); |
| 562 | + let rows: Vec<(String, i64)> = match with_deadline(fold.build_query_as()).await { | ||
| 563 | + Ok(rows) => rows, | ||
| 568 | Err(err) => { | 564 | Err(err) => { |
| 569 | tracing::warn!(%err, tier, "rate-limit sync failed; counting locally until it recovers"); | 565 | tracing::warn!(%err, tier, "rate-limit sync failed; counting locally until it recovers"); |
| 570 | return; | 566 | return; |
| 571 | } | 567 | } |
| 572 | }; | 568 | }; |
| 569 | + let totals: HashMap<String, i64> = rows.into_iter().collect(); | ||
| 573 | 570 | ||
| 574 | let mut guard = buckets.lock().expect("rate limiter mutex poisoned"); | 571 | let mut guard = buckets.lock().expect("rate limiter mutex poisoned"); |
| 575 | - for (i, p) in pending.iter().enumerate() { | 572 | + for p in &pending { |
| 576 | - // A statement that failed (a lost write race) leaves its bucket | 573 | + // A row missing from the fold's answer stands in for the failed |
| 577 | - // untouched: the delta stays unreported and the next round carries it. | 574 | + // statement it replaces: its bucket stays untouched, the delta stays |
| 578 | - let Ok(total) = response.take::<Vec<i64>>(i) else { | 575 | + // unreported, and the next round carries it. |
| 576 | + let Some(total) = totals.get(&row_key(tier, &p.key, epoch)) else { | ||
| 579 | continue; | 577 | continue; |
| 580 | }; | 578 | }; |
| 581 | - let (Some(total), Some(bucket)) = (total.first(), guard.get_mut(&p.key)) else { | 579 | + let Some(bucket) = guard.get_mut(&p.key) else { |
| 582 | continue; | 580 | continue; |
| 583 | }; | 581 | }; |
| 584 | // The window may have rolled while the query was in flight, in which | 582 | // The window may have rolled while the query was in flight, in which |
| @@ -617,20 +615,19 @@ impl std::fmt::LowerHex for ByteSlice<'_> { | |||
| 617 | } | 615 | } |
| 618 | } | 616 | } |
| 619 | 617 | ||
| 620 | -/// Run a sync query under a deadline. The liveness flag catches a *known* | 618 | +/// Run one sync statement under a deadline. Postgres fails a dead connection |
| 621 | -/// outage; this catches the socket that died between the last ping and now, | 619 | +/// instead of parking the query, but a slow or overloaded server can still |
| 622 | -/// which the SDK would otherwise park until the database returned — wedging | 620 | +/// stall a round past what the sharing can afford — every tier's budget rides |
| 623 | -/// the one task every tier's sharing depends on. | 621 | +/// this one task, so a wedged round would stall all of them. A dropped round |
| 624 | -async fn with_deadline<T>( | 622 | +/// leaves its deltas unreported and the next round carries them. |
| 625 | - query: impl std::future::IntoFuture<Output = surrealdb::Result<T>>, | 623 | +async fn with_deadline<T, Fut>(query: Fut) -> Result<T, AppError> |
| 626 | -) -> Result<T, AppError> { | 624 | +where |
| 627 | - tokio::time::timeout( | 625 | + Fut: Future<Output = Result<T, sqlx::Error>>, |
| 628 | - Duration::from_secs(RATE_SYNC_TIMEOUT_SECS), | 626 | +{ |
| 629 | - query.into_future(), | 627 | + tokio::time::timeout(Duration::from_secs(RATE_SYNC_TIMEOUT_SECS), query) |
| 630 | - ) | 628 | + .await |
| 631 | - .await | 629 | + .map_err(|_| AppError::Internal("rate-limit sync timed out".into()))? |
| 632 | - .map_err(|_| AppError::Internal("rate-limit sync timed out".into()))? | 630 | + .map_err(AppError::from) |
| 633 | - .map_err(AppError::from) | ||
| 634 | } | 631 | } |
| 635 | 632 | ||
| 636 | /// Resolve the client IP a request is billed against. | 633 | /// Resolve the client IP a request is billed against. |
| @@ -901,66 +898,6 @@ mod tests { | |||
| 901 | ); | 898 | ); |
| 902 | } | 899 | } |
| 903 | 900 | ||
| 904 | - /// The wall window rolls under a live local one — every local window | ||
| 905 | - /// straddles exactly one boundary, since both are 60s and only the shared | ||
| 906 | - /// one is clock-aligned. Each request must land in exactly one shared row: | ||
| 907 | - /// re-reporting the whole local count to the new row charges the client | ||
| 908 | - /// twice and spends the next window's budget before it starts. | ||
| 909 | - /// | ||
| 910 | - /// `sync_once` takes the epoch, so the boundary is driven here instead of | ||
| 911 | - /// waited for — the sharing tests in `tests/rate_limit.rs` all run inside | ||
| 912 | - /// one real wall window (`current_epoch` reads the wall clock, which | ||
| 913 | - /// `tokio::time::pause` does not touch), which is why this path had no | ||
| 914 | - /// coverage at all. | ||
| 915 | - #[tokio::test] | ||
| 916 | - async fn a_wall_epoch_roll_charges_no_request_twice() { | ||
| 917 | - const MAX: u32 = 5; | ||
| 918 | - let db = crate::database::init_mem().await.expect("in-memory db"); | ||
| 919 | - let limiter = UserRateLimiter::per_user_minute(MAX); | ||
| 920 | - let window = Duration::from_secs(60); | ||
| 921 | - let epoch = current_epoch(window); | ||
| 922 | - assert_eq!(window.as_millis() as i64, 60_000, "epochs are 60s apart"); | ||
| 923 | - | ||
| 924 | - // A burst early in the client's local window, folded into row `epoch`. | ||
| 925 | - for _ in 0..MAX { | ||
| 926 | - assert!(limiter.enforce_user("user:a").is_ok()); | ||
| 927 | - } | ||
| 928 | - sync_once("test", &limiter.buckets, window, epoch, &db).await; | ||
| 929 | - | ||
| 930 | - // The wall clock rolls while that local window is still running. | ||
| 931 | - sync_once("test", &limiter.buckets, window, epoch + 60_000, &db).await; | ||
| 932 | - | ||
| 933 | - // The local window lapses, so the client opens a fresh one — inside the | ||
| 934 | - // *same* new wall window — and spends one request in it. | ||
| 935 | - tokio::time::pause(); | ||
| 936 | - tokio::time::advance(Duration::from_secs(61)).await; | ||
| 937 | - tokio::time::resume(); | ||
| 938 | - assert_eq!(admits(&limiter, "user:a", 1), 1, "a fresh local window"); | ||
| 939 | - sync_once("test", &limiter.buckets, window, epoch + 60_000, &db).await; | ||
| 940 | - | ||
| 941 | - let mut rows = db | ||
| 942 | - .query("SELECT VALUE hits FROM rate_limit ORDER BY window_start") | ||
| 943 | - .await | ||
| 944 | - .expect("read shared counters"); | ||
| 945 | - assert_eq!( | ||
| 946 | - rows.take::<Vec<i64>>(0).unwrap(), | ||
| 947 | - vec![i64::from(MAX), 1], | ||
| 948 | - "the new wall row may hold only what was admitted inside it" | ||
| 949 | - ); | ||
| 950 | - assert_eq!( | ||
| 951 | - admits(&limiter, "user:a", 4), | ||
| 952 | - 4, | ||
| 953 | - "the client spent 1 of {MAX} in this window and must keep the rest" | ||
| 954 | - ); | ||
| 955 | - } | ||
| 956 | - | ||
| 957 | - /// How many of `tries` requests the limiter admits for `user`. | ||
| 958 | - fn admits(limiter: &UserRateLimiter, user: &str, tries: usize) -> usize { | ||
| 959 | - (0..tries) | ||
| 960 | - .filter(|_| limiter.enforce_user(user).is_ok()) | ||
| 961 | - .count() | ||
| 962 | - } | ||
| 963 | - | ||
| 964 | /// The flood above was cheap to tell apart. This one is not: every flood | 901 | /// The flood above was cheap to tell apart. This one is not: every flood |
| 965 | /// key is driven to *exactly* the spend of the bucket it is trying to | 902 | /// key is driven to *exactly* the spend of the bucket it is trying to |
| 966 | /// free, so a cheapest-first cutoff of `<=` puts the victim inside the tie | 903 | /// free, so a cheapest-first cutoff of `<=` puts the victim inside the tie |
src/state.rsmodified+0 -42
| @@ -1,6 +1,5 @@ | |||
| 1 | use std::collections::HashMap; | 1 | use std::collections::HashMap; |
| 2 | use std::path::PathBuf; | 2 | use std::path::PathBuf; |
| 3 | -use std::sync::atomic::{AtomicBool, Ordering}; | ||
| 4 | use std::sync::{Arc, Mutex}; | 3 | use std::sync::{Arc, Mutex}; |
| 5 | 4 | ||
| 6 | use tokio::sync::broadcast; | 5 | use tokio::sync::broadcast; |
| @@ -40,8 +39,6 @@ pub struct AppState { | |||
| 40 | pub exam_presence: ExamPresence, | 39 | pub exam_presence: ExamPresence, |
| 41 | /// Live stroke fan-out for the shared whiteboards (see [`BoardHub`]). | 40 | /// Live stroke fan-out for the shared whiteboards (see [`BoardHub`]). |
| 42 | pub board_hub: BoardHub, | 41 | pub board_hub: BoardHub, |
| 43 | - /// Whether the database socket answered its last ping (see [`DbHealth`]). | ||
| 44 | - pub db_up: DbHealth, | ||
| 45 | /// The QUIC bridge to the AI services, when one is configured | 42 | /// The QUIC bridge to the AI services, when one is configured |
| 46 | /// (`AI_QUIC_ADDR`). `None` means AI features are off for this deployment | 43 | /// (`AI_QUIC_ADDR`). `None` means AI features are off for this deployment |
| 47 | /// — handlers must degrade rather than fail, since the core API has never | 44 | /// — handlers must degrade rather than fail, since the core API has never |
| @@ -53,45 +50,6 @@ pub struct AppState { | |||
| 53 | pub metrics: crate::telemetry::Metrics, | 50 | pub metrics: crate::telemetry::Metrics, |
| 54 | } | 51 | } |
| 55 | 52 | ||
| 56 | -/// Last known state of the database WebSocket, published by the keepalive task | ||
| 57 | -/// in `main` and read by the guard layer in [`crate::build_router`]. | ||
| 58 | -/// | ||
| 59 | -/// It exists because a query issued while the socket is down does not fail — | ||
| 60 | -/// it hangs. The SDK's reconnect loop stops draining its request channel while | ||
| 61 | -/// it retries, so the query is parked until the database returns, and *then* | ||
| 62 | -/// executes. Refusing at the edge is what keeps a 503 honest: nothing was | ||
| 63 | -/// queued, so the caller's retry cannot double-apply a write. | ||
| 64 | -/// | ||
| 65 | -/// Starts up: `init` only returns once a connection and the migration | ||
| 66 | -/// succeeded, so the first ping has nothing to correct. | ||
| 67 | -#[derive(Clone)] | ||
| 68 | -pub struct DbHealth(Arc<AtomicBool>); | ||
| 69 | - | ||
| 70 | -impl Default for DbHealth { | ||
| 71 | - fn default() -> Self { | ||
| 72 | - Self(Arc::new(AtomicBool::new(true))) | ||
| 73 | - } | ||
| 74 | -} | ||
| 75 | - | ||
| 76 | -impl DbHealth { | ||
| 77 | - /// Did the last ping answer? | ||
| 78 | - pub fn is_up(&self) -> bool { | ||
| 79 | - self.0.load(Ordering::Relaxed) | ||
| 80 | - } | ||
| 81 | - | ||
| 82 | - /// Publish the latest ping verdict, logging only the transitions — a long | ||
| 83 | - /// outage should not print a line every [`crate::constant::DB_KEEPALIVE_INTERVAL_SECS`]. | ||
| 84 | - pub fn set(&self, up: bool) { | ||
| 85 | - if self.0.swap(up, Ordering::Relaxed) != up { | ||
| 86 | - if up { | ||
| 87 | - tracing::info!("database socket recovered — serving requests again"); | ||
| 88 | - } else { | ||
| 89 | - tracing::error!("database socket down — refusing requests with 503"); | ||
| 90 | - } | ||
| 91 | - } | ||
| 92 | - } | ||
| 93 | -} | ||
| 94 | - | ||
| 95 | /// The map key for `key` inside `slug`'s school. One process serves every | 53 | /// The map key for `key` inside `slug`'s school. One process serves every |
| 96 | /// school, but record keys are only unique *within* a database, so an | 54 | /// school, but record keys are only unique *within* a database, so an |
| 97 | /// unscoped key would put two schools' identical attempts (or boards) in the | 55 | /// unscoped key would put two schools' identical attempts (or boards) in the |
src/tenant.rsmodified+217 -427
| @@ -1,61 +1,57 @@ | |||
| 1 | -//! Multi-school tenancy: one SurrealDB **database** per school inside one | 1 | +//! Multi-school tenancy: one PostgreSQL **database** per school on one |
| 2 | -//! namespace, plus a **control** database holding the school registry, the | 2 | +//! server, plus a **control** database holding the school registry, the |
| 3 | -//! builder accounts that manage it, and the deployment-wide rate-limit window. | 3 | +//! builder accounts that manage it, and the deployment-wide rate-limit |
| 4 | +//! window. | ||
| 4 | //! | 5 | //! |
| 5 | -//! Isolation is the store's, not ours. A school database sees only its own | 6 | +//! Isolation is the server's, not ours. A school database sees only its own |
| 6 | //! rows, so no handler needs a `WHERE school = …` it could forget: the school | 7 | //! rows, so no handler needs a `WHERE school = …` it could forget: the school |
| 7 | //! is chosen once, at the edge (`crate::web::tenant_state::State`), and every | 8 | //! is chosen once, at the edge (`crate::web::tenant_state::State`), and every |
| 8 | //! query underneath runs against that handle. | 9 | //! query underneath runs against that handle. |
| 9 | //! | 10 | //! |
| 10 | -//! # One connection per school, never a clone | 11 | +//! # One pool per school, cached |
| 11 | //! | 12 | //! |
| 12 | -//! [`crate::database::Database`] is `Arc<Surreal<Any>>` for the reason spelled | 13 | +//! `crate::database::Database` is a `PgPool`, and a school's pool is its own |
| 13 | -//! out there — `Surreal::clone()` mints a racing server-side session — and the | 14 | +//! dial — switching databases on a shared connection is not a thing the pool |
| 14 | -//! same reasoning forbids the obvious shortcut here: switching `use_db` on the | 15 | +//! API offers, which is just as well: a cache miss dials a fresh pool |
| 15 | -//! control handle would repoint *every* in-flight query on it. So a cache miss | 16 | +//! (`max_connections(4)`) pinned to the school's database for its lifetime, |
| 16 | -//! dials a **new** connection, signs it in, and pins it to the school's | 17 | +//! and the cache is the only thing that finds it again. |
| 17 | -//! database for its lifetime. | ||
| 18 | -//! | ||
| 19 | -//! In-memory mode (tests) has no server to define databases on: each | ||
| 20 | -//! `connect("memory")` is an independent datastore, so a school *is* its own | ||
| 21 | -//! store and the cache is the only thing that finds it again. | ||
| 22 | 18 | ||
| 23 | use std::collections::HashMap; | 19 | use std::collections::HashMap; |
| 24 | use std::sync::{Arc, RwLock}; | 20 | use std::sync::{Arc, RwLock}; |
| 25 | 21 | ||
| 26 | use serde::Serialize; | 22 | use serde::Serialize; |
| 27 | -use surrealdb::opt::auth::Root; | 23 | +use sqlx::postgres::PgConnectOptions; |
| 28 | -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 29 | 24 | ||
| 30 | -use crate::config::Config; | ||
| 31 | use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN}; | 25 | use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN}; |
| 32 | -use crate::database::{Database, lost_the_race, migrate, migrate_control}; | 26 | +use crate::database::{ |
| 33 | -use crate::db::page::PagedList; | 27 | + create_database_sql, is_duplicate_database, migrate_school, school_pool, unique_violation, |
| 28 | + Database, | ||
| 29 | +}; | ||
| 34 | use crate::domain::timestamp::Timestamp; | 30 | use crate::domain::timestamp::Timestamp; |
| 35 | use crate::error::{AppError, ValidationError}; | 31 | use crate::error::{AppError, ValidationError}; |
| 36 | use crate::module::ModuleSet; | 32 | use crate::module::ModuleSet; |
| 37 | use crate::telemetry::Metrics; | 33 | use crate::telemetry::Metrics; |
| 38 | use crate::web::tenant_state::ResolvedTenant; | 34 | use crate::web::tenant_state::ResolvedTenant; |
| 39 | 35 | ||
| 40 | -pub(crate) const SCHOOL_TABLE: &str = "school"; | 36 | +/// The school every in-memory test bootstrap got and every test suite still |
| 41 | - | 37 | +/// names. Not special to the code — just the one name the test harness and |
| 42 | -/// The school every in-memory test bootstrap gets. Not special to the code — | 38 | +/// the suites agree on. |
| 43 | -/// just the one name the test harness and the suites agree on. | ||
| 44 | pub const DEMO_SLUG: &str = "demo"; | 39 | pub const DEMO_SLUG: &str = "demo"; |
| 45 | 40 | ||
| 46 | /// Slugs that name something other than a school: the builder cookie prefix and | 41 | /// Slugs that name something other than a school: the builder cookie prefix and |
| 47 | /// the control database itself. Refused at construction, so neither a login nor | 42 | /// the control database itself. Refused at construction, so neither a login nor |
| 48 | -/// a `DEFINE DATABASE` can ever be aimed at them. | 43 | +/// a `CREATE DATABASE` can ever be aimed at them. |
| 49 | pub const RESERVED_SLUGS: [&str; 2] = ["builder", "control"]; | 44 | pub const RESERVED_SLUGS: [&str; 2] = ["builder", "control"]; |
| 50 | 45 | ||
| 51 | /// A school's identity everywhere it is named: the cookie prefix, the database | 46 | /// A school's identity everywhere it is named: the cookie prefix, the database |
| 52 | /// name, and the files subdirectory. The character set is deliberately the | 47 | /// name, and the files subdirectory. The character set is deliberately the |
| 53 | /// intersection of what all three accept — lowercase alphanumerics and `-`, | 48 | /// intersection of what all three accept — lowercase alphanumerics and `-`, |
| 54 | -/// starting with an alphanumeric — which is also what makes it safe to | 49 | +/// starting with an alphanumeric. It is also what makes the database names |
| 55 | -/// interpolate into `DEFINE DATABASE` / `REMOVE DATABASE`, the two statements | 50 | +/// injective: `school_db_name` maps `-` to `_`, and `_` is not in the slug |
| 56 | -/// SurrealQL gives no way to bind a name into. | 51 | +/// charset, so two slugs can never collide onto one database. |
| 57 | -#[derive(Debug, Clone, PartialEq, Eq, Hash, SurrealValue, Serialize)] | 52 | +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, sqlx::Type)] |
| 58 | #[serde(transparent)] | 53 | #[serde(transparent)] |
| 54 | +#[sqlx(transparent)] | ||
| 59 | pub struct Slug(String); | 55 | pub struct Slug(String); |
| 60 | 56 | ||
| 61 | /// `^[a-z0-9][a-z0-9-]{1,31}$`, spelled out. `regex` is a dev-dependency here | 57 | /// `^[a-z0-9][a-z0-9-]{1,31}$`, spelled out. `regex` is a dev-dependency here |
| @@ -101,21 +97,19 @@ impl std::fmt::Display for Slug { | |||
| 101 | } | 97 | } |
| 102 | } | 98 | } |
| 103 | 99 | ||
| 104 | -/// A school slug as a SurrealQL identifier. A database name cannot be bound | 100 | +/// A school database's name: `{control_db}_school_{slug}`, the slug's `-` |
| 105 | -/// as a parameter, so it is interpolated — and it MUST be backtick-quoted: an | 101 | +/// spelled `_` (Postgres identifiers allow `-` only quoted, and the name is |
| 106 | -/// unquoted `ata-koleji` parses as a subtraction, `2024school` as a duration, | 102 | +/// built, not user-typed). Injective — see [`Slug`]'s charset note. |
| 107 | -/// `12345` as a number (SurrealDB 3.2). The `Slug` charset (`[a-z0-9-]`) can | 103 | +pub fn school_db_name(control_db: &str, slug: &Slug) -> String { |
| 108 | -/// never contain a backtick, so the quoting cannot be escaped from. | 104 | + format!("{}_school_{}", control_db, slug.as_str().replace('-', "_")) |
| 109 | -pub fn quoted_ident(slug: &Slug) -> String { | ||
| 110 | - format!("`{}`", slug.as_str()) | ||
| 111 | } | 105 | } |
| 112 | 106 | ||
| 113 | /// Whether a school may be reached at all. Suspension is immediate and total: | 107 | /// Whether a school may be reached at all. Suspension is immediate and total: |
| 114 | /// [`Tenants::get`] refuses before any handler runs, and login is no exception. | 108 | /// [`Tenants::get`] refuses before any handler runs, and login is no exception. |
| 115 | /// | 109 | /// |
| 116 | /// Stored as a bare lowercase string, like [`crate::domain::role::Role`]. | 110 | /// Stored as a bare lowercase string, like [`crate::domain::role::Role`]. |
| 117 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue, Serialize)] | 111 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, sqlx::Type)] |
| 118 | -#[surreal(untagged, rename_all = "lowercase")] | 112 | +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] |
| 119 | #[serde(rename_all = "lowercase")] | 113 | #[serde(rename_all = "lowercase")] |
| 120 | pub enum SchoolStatus { | 114 | pub enum SchoolStatus { |
| 121 | Active, | 115 | Active, |
| @@ -142,32 +136,24 @@ impl SchoolStatus { | |||
| 142 | } | 136 | } |
| 143 | } | 137 | } |
| 144 | 138 | ||
| 145 | -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 139 | +/// A school's id **is** its slug — the registry can never hold two rows for |
| 146 | -pub struct SchoolId(RecordId); | 140 | +/// one school, and the database name is derived from the same word. |
| 141 | +#[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
| 142 | +pub struct SchoolId(Slug); | ||
| 147 | 143 | ||
| 148 | impl SchoolId { | 144 | impl SchoolId { |
| 149 | - /// The id **is** the slug, so the registry can never hold two rows for one | ||
| 150 | - /// school even if the unique index were dropped. | ||
| 151 | pub fn from_slug(slug: &Slug) -> Self { | 145 | pub fn from_slug(slug: &Slug) -> Self { |
| 152 | - Self(RecordId::new(SCHOOL_TABLE, slug.as_str())) | 146 | + Self(slug.clone()) |
| 153 | - } | ||
| 154 | - | ||
| 155 | - pub fn record(&self) -> RecordId { | ||
| 156 | - self.0.clone() | ||
| 157 | } | 147 | } |
| 158 | 148 | ||
| 159 | pub fn key(&self) -> &str { | 149 | pub fn key(&self) -> &str { |
| 160 | - match &self.0.key { | 150 | + self.0.as_str() |
| 161 | - RecordIdKey::String(key) => key, | ||
| 162 | - _ => "", | ||
| 163 | - } | ||
| 164 | } | 151 | } |
| 165 | } | 152 | } |
| 166 | 153 | ||
| 167 | /// A row in the control database's school registry. | 154 | /// A row in the control database's school registry. |
| 168 | -#[derive(Debug, Clone, SurrealValue)] | 155 | +#[derive(Debug, Clone, sqlx::FromRow)] |
| 169 | pub struct School { | 156 | pub struct School { |
| 170 | - id: SchoolId, | ||
| 171 | slug: Slug, | 157 | slug: Slug, |
| 172 | name: String, | 158 | name: String, |
| 173 | status: SchoolStatus, | 159 | status: SchoolStatus, |
| @@ -180,8 +166,9 @@ pub struct School { | |||
| 180 | } | 166 | } |
| 181 | 167 | ||
| 182 | impl School { | 168 | impl School { |
| 183 | - pub fn get_id(&self) -> &SchoolId { | 169 | + /// The id is the slug; rebuilt rather than stored a second copy. |
| 184 | - &self.id | 170 | + pub fn get_id(&self) -> SchoolId { |
| 171 | + SchoolId::from_slug(&self.slug) | ||
| 185 | } | 172 | } |
| 186 | 173 | ||
| 187 | pub fn slug(&self) -> &Slug { | 174 | pub fn slug(&self) -> &Slug { |
| @@ -218,20 +205,36 @@ impl School { | |||
| 218 | } | 205 | } |
| 219 | 206 | ||
| 220 | pub async fn read(slug: &Slug, control: &Database) -> Result<Option<School>, AppError> { | 207 | pub async fn read(slug: &Slug, control: &Database) -> Result<Option<School>, AppError> { |
| 221 | - Ok(control.select(SchoolId::from_slug(slug).record()).await?) | 208 | + sqlx::query_as::<_, School>( |
| 209 | + "SELECT slug, name, status, created_at, modules FROM school WHERE slug = $1", | ||
| 210 | + ) | ||
| 211 | + .bind(slug.as_str()) | ||
| 212 | + .fetch_optional(control) | ||
| 213 | + .await | ||
| 214 | + .map_err(Into::into) | ||
| 222 | } | 215 | } |
| 223 | 216 | ||
| 224 | /// One page of the registry, newest first. Same `(rows, total)` shape every | 217 | /// One page of the registry, newest first. Same `(rows, total)` shape every |
| 225 | /// other list domain returns, so the builder API can wrap it in the usual | 218 | /// other list domain returns, so the builder API can wrap it in the usual |
| 226 | - /// [`crate::web::Page`] envelope. | 219 | + /// [`crate::web::Page`] envelope. `None` limits to every row. |
| 227 | pub async fn list( | 220 | pub async fn list( |
| 228 | limit: Option<i64>, | 221 | limit: Option<i64>, |
| 229 | offset: i64, | 222 | offset: i64, |
| 230 | control: &Database, | 223 | control: &Database, |
| 231 | ) -> Result<(Vec<School>, i64), AppError> { | 224 | ) -> Result<(Vec<School>, i64), AppError> { |
| 232 | - PagedList::new(SCHOOL_TABLE, "ORDER BY created_at DESC, id DESC") | 225 | + let rows = sqlx::query_as::<_, School>( |
| 233 | - .run::<School>(limit, offset, control) | 226 | + "SELECT slug, name, status, created_at, modules FROM school |
| 234 | - .await | 227 | + ORDER BY created_at DESC, slug DESC |
| 228 | + LIMIT $1 OFFSET $2", | ||
| 229 | + ) | ||
| 230 | + .bind(limit) | ||
| 231 | + .bind(offset) | ||
| 232 | + .fetch_all(control) | ||
| 233 | + .await?; | ||
| 234 | + let (total,): (i64,) = sqlx::query_as("SELECT count(*) FROM school") | ||
| 235 | + .fetch_one(control) | ||
| 236 | + .await?; | ||
| 237 | + Ok((rows, total)) | ||
| 235 | } | 238 | } |
| 236 | 239 | ||
| 237 | /// Rename a school. The slug is immutable — it names a database and a | 240 | /// Rename a school. The slug is immutable — it names a database and a |
| @@ -241,104 +244,45 @@ impl School { | |||
| 241 | name: &str, | 244 | name: &str, |
| 242 | control: &Database, | 245 | control: &Database, |
| 243 | ) -> Result<School, AppError> { | 246 | ) -> Result<School, AppError> { |
| 244 | - let updated: Option<School> = control | 247 | + sqlx::query_as::<_, School>( |
| 245 | - .query("UPDATE $id SET name = $name RETURN AFTER") | 248 | + "UPDATE school SET name = $1 WHERE slug = $2 |
| 246 | - .bind(("id", SchoolId::from_slug(slug).record())) | 249 | + RETURNING slug, name, status, created_at, modules", |
| 247 | - .bind(("name", name.to_string())) | 250 | + ) |
| 248 | - .await? | 251 | + .bind(name) |
| 249 | - .check()? | 252 | + .bind(slug.as_str()) |
| 250 | - .take::<Vec<School>>(0)? | 253 | + .fetch_optional(control) |
| 251 | - .into_iter() | 254 | + .await? |
| 252 | - .next(); | 255 | + .ok_or(AppError::NotFound) |
| 253 | - updated.ok_or(AppError::NotFound) | ||
| 254 | } | 256 | } |
| 255 | } | 257 | } |
| 256 | 258 | ||
| 257 | -/// How a school handle is minted. Remote dials the server the control handle | 259 | +/// The school registry plus its live pools. |
| 258 | -/// came from; `Mem` mints an independent embedded datastore per school. | ||
| 259 | -#[derive(Debug)] | ||
| 260 | -enum Mode { | ||
| 261 | - Remote { | ||
| 262 | - url: String, | ||
| 263 | - user: String, | ||
| 264 | - pass: String, | ||
| 265 | - ns: String, | ||
| 266 | - }, | ||
| 267 | - Mem, | ||
| 268 | -} | ||
| 269 | - | ||
| 270 | -/// The school registry plus its live connections. | ||
| 271 | #[derive(Clone)] | 260 | #[derive(Clone)] |
| 272 | pub struct Tenants { | 261 | pub struct Tenants { |
| 273 | control: Database, | 262 | control: Database, |
| 274 | cache: Arc<RwLock<HashMap<String, Database>>>, | 263 | cache: Arc<RwLock<HashMap<String, Database>>>, |
| 275 | - mode: Arc<Mode>, | 264 | + /// Dial options for the Postgres server the control pool came from — a |
| 265 | + /// school pool is the same dial with only the database swapped. | ||
| 266 | + base: PgConnectOptions, | ||
| 267 | + /// The control database's name; every school database is | ||
| 268 | + /// [`school_db_name`] of it. | ||
| 269 | + control_db: String, | ||
| 276 | } | 270 | } |
| 277 | 271 | ||
| 278 | impl Tenants { | 272 | impl Tenants { |
| 279 | - /// Wrap an already-connected, already-migrated control handle. | 273 | + /// Wrap an already-connected, already-migrated control pool. Production |
| 280 | - pub fn new_remote(control: Database, cfg: &Config) -> Tenants { | 274 | + /// constructor — [`crate::database::init`] calls it once at boot. |
| 275 | + pub fn new(control: Database, base: PgConnectOptions, control_db: String) -> Tenants { | ||
| 281 | Tenants { | 276 | Tenants { |
| 282 | control, | 277 | control, |
| 283 | cache: Arc::new(RwLock::new(HashMap::new())), | 278 | cache: Arc::new(RwLock::new(HashMap::new())), |
| 284 | - mode: Arc::new(Mode::Remote { | 279 | + base, |
| 285 | - url: cfg.db_url.clone(), | 280 | + control_db, |
| 286 | - user: cfg.db_user.clone(), | ||
| 287 | - pass: cfg.db_pass.clone(), | ||
| 288 | - ns: cfg.db_ns.clone(), | ||
| 289 | - }), | ||
| 290 | } | 281 | } |
| 291 | } | 282 | } |
| 292 | 283 | ||
| 293 | - /// A fresh in-memory control database with the control schema applied, and | ||
| 294 | - /// no schools. For tests. | ||
| 295 | - pub async fn new_mem() -> Result<Tenants, AppError> { | ||
| 296 | - let control = surrealdb::engine::any::connect("memory").await?; | ||
| 297 | - control.use_ns("hezarfen").use_db("control").await?; | ||
| 298 | - migrate_control(&control).await?; | ||
| 299 | - Ok(Tenants { | ||
| 300 | - control: Arc::new(control), | ||
| 301 | - cache: Arc::new(RwLock::new(HashMap::new())), | ||
| 302 | - mode: Arc::new(Mode::Mem), | ||
| 303 | - }) | ||
| 304 | - } | ||
| 305 | - | ||
| 306 | - /// A fresh in-memory registry that already knows `slug`, backed by a handle | ||
| 307 | - /// that already exists rather than a new store. | ||
| 308 | - /// | ||
| 309 | - /// This is how a suite simulates a reboot: the process (and so the registry, | ||
| 310 | - /// the connection cache and the control database) is new, while the school's | ||
| 311 | - /// data is the very data the previous process wrote. | ||
| 312 | - pub async fn new_mem_adopting( | ||
| 313 | - slug: &Slug, | ||
| 314 | - name: &str, | ||
| 315 | - db: Database, | ||
| 316 | - ) -> Result<Tenants, AppError> { | ||
| 317 | - let tenants = Tenants::new_mem().await?; | ||
| 318 | - let school = School { | ||
| 319 | - id: SchoolId::from_slug(slug), | ||
| 320 | - slug: slug.clone(), | ||
| 321 | - name: name.to_string(), | ||
| 322 | - status: SchoolStatus::Active, | ||
| 323 | - created_at: Timestamp::now(), | ||
| 324 | - modules: ModuleSet::all().names(), | ||
| 325 | - }; | ||
| 326 | - let _: Option<School> = tenants | ||
| 327 | - .control | ||
| 328 | - .create(school.id.record()) | ||
| 329 | - .content(school) | ||
| 330 | - .await?; | ||
| 331 | - let size = { | ||
| 332 | - let mut cache = tenants.cache.write().expect("tenant cache lock"); | ||
| 333 | - cache.insert(slug.as_str().to_string(), db); | ||
| 334 | - cache.len() | ||
| 335 | - }; | ||
| 336 | - Self::report_size(size); | ||
| 337 | - Ok(tenants) | ||
| 338 | - } | ||
| 339 | - | ||
| 340 | /// The control database: schools, builders, the shared rate-limit window. | 284 | /// The control database: schools, builders, the shared rate-limit window. |
| 341 | - /// Never `use_db`-switched — see this module's header. | 285 | + /// It is never re-purposed for a school's rows — see this module's header. |
| 342 | pub fn control(&self) -> &Database { | 286 | pub fn control(&self) -> &Database { |
| 343 | &self.control | 287 | &self.control |
| 344 | } | 288 | } |
| @@ -363,7 +307,7 @@ impl Tenants { | |||
| 363 | match School::read(slug, &self.control).await? { | 307 | match School::read(slug, &self.control).await? { |
| 364 | None => Err(AppError::Unauthorized), | 308 | None => Err(AppError::Unauthorized), |
| 365 | Some(school) if school.status == SchoolStatus::Suspended => { | 309 | Some(school) if school.status == SchoolStatus::Suspended => { |
| 366 | - self.evict(slug); | 310 | + self.evict(slug).await; |
| 367 | Err(AppError::Forbidden("school is suspended")) | 311 | Err(AppError::Forbidden("school is suspended")) |
| 368 | } | 312 | } |
| 369 | Some(school) => Ok(ResolvedTenant { | 313 | Some(school) => Ok(ResolvedTenant { |
| @@ -386,7 +330,7 @@ impl Tenants { | |||
| 386 | 330 | ||
| 387 | /// Register a school and bring its database into being: registry row first | 331 | /// Register a school and bring its database into being: registry row first |
| 388 | /// (so a lost race is a `409` and not a half-made database), then | 332 | /// (so a lost race is a `409` and not a half-made database), then |
| 389 | - /// `DEFINE DATABASE`, then the school schema. | 333 | + /// `CREATE DATABASE`, then the school schema. |
| 390 | pub async fn create( | 334 | pub async fn create( |
| 391 | &self, | 335 | &self, |
| 392 | slug: &Slug, | 336 | slug: &Slug, |
| @@ -397,42 +341,38 @@ impl Tenants { | |||
| 397 | // every violation at once), but the registry refuses an unsatisfiable | 341 | // every violation at once), but the registry refuses an unsatisfiable |
| 398 | // set too, so no future caller can persist one. | 342 | // set too, so no future caller can persist one. |
| 399 | modules.validate()?; | 343 | modules.validate()?; |
| 400 | - let school = School { | 344 | + let inserted = sqlx::query( |
| 401 | - id: SchoolId::from_slug(slug), | 345 | + "INSERT INTO school (slug, name, status, created_at, modules) |
| 402 | - slug: slug.clone(), | 346 | + VALUES ($1, $2, $3, $4, $5)", |
| 403 | - name: name.to_string(), | 347 | + ) |
| 404 | - status: SchoolStatus::Active, | 348 | + .bind(slug.as_str()) |
| 405 | - created_at: Timestamp::now(), | 349 | + .bind(name) |
| 406 | - modules: modules.names(), | 350 | + .bind(SchoolStatus::Active) |
| 407 | - }; | 351 | + .bind(Timestamp::now().as_millis()) |
| 408 | - let created: Result<Option<School>, surrealdb::Error> = self | 352 | + .bind(modules.names()) |
| 409 | - .control | 353 | + .execute(&self.control) |
| 410 | - .create(school.id.record()) | 354 | + .await; |
| 411 | - .content(school.clone()) | 355 | + if let Err(err) = inserted { |
| 412 | - .await; | 356 | + // The slug is the table's only unique key, so a unique violation |
| 413 | - match created { | 357 | + // here is exactly "taken" — a rival's row, or the row already |
| 414 | - Ok(Some(_)) => {} | 358 | + // stood. Same verdict either way, as it always was. |
| 415 | - Ok(None) => return Err(AppError::Internal("failed to create the school".into())), | 359 | + if unique_violation(&err).is_some() { |
| 416 | - // The id is the slug, so "already exists" is exactly "taken" — and | ||
| 417 | - // a lost transaction race is the same verdict reached differently. | ||
| 418 | - Err(err) if lost_the_race(&err) => { | ||
| 419 | return Err(AppError::Conflict("school slug already taken")); | 360 | return Err(AppError::Conflict("school slug already taken")); |
| 420 | } | 361 | } |
| 421 | - Err(err) => return Err(err.into()), | 362 | + return Err(err.into()); |
| 422 | } | 363 | } |
| 423 | 364 | ||
| 424 | // Everything past the registry row rolls that row back on failure: | 365 | // Everything past the registry row rolls that row back on failure: |
| 425 | // the row is what makes the slug "taken", and a slug taken by a | 366 | // the row is what makes the slug "taken", and a slug taken by a |
| 426 | - // school that never came to exist is wedged for good (found by the | 367 | + // school that never came to exist is wedged for good. (A database |
| 427 | - // delete-path verifier: `ata-koleji` failed `DEFINE DATABASE` unquoted | 368 | + // created before the failure is not a wedge: the adopt branch in |
| 428 | - // and could then be neither re-created nor deleted). | 369 | + // [`Self::bring_up`] picks it up, migrations being idempotent.) |
| 429 | let db = match self.bring_up(slug).await { | 370 | let db = match self.bring_up(slug).await { |
| 430 | Ok(db) => db, | 371 | Ok(db) => db, |
| 431 | Err(err) => { | 372 | Err(err) => { |
| 432 | - let _ = self | 373 | + let _ = sqlx::query("DELETE FROM school WHERE slug = $1") |
| 433 | - .control | 374 | + .bind(slug.as_str()) |
| 434 | - .query("DELETE $id") | 375 | + .execute(&self.control) |
| 435 | - .bind(("id", SchoolId::from_slug(slug).record())) | ||
| 436 | .await; | 376 | .await; |
| 437 | return Err(err); | 377 | return Err(err); |
| 438 | } | 378 | } |
| @@ -446,113 +386,121 @@ impl Tenants { | |||
| 446 | Ok(db) | 386 | Ok(db) |
| 447 | } | 387 | } |
| 448 | 388 | ||
| 449 | - /// Define (remote) or mint (memory) the school's database and apply the | 389 | + /// Create (or adopt) the school's database and apply the school schema to |
| 450 | - /// school schema to it. Split out of [`Tenants::create`] so one `?` chain | 390 | + /// it. Split out of [`Tenants::create`] so one `?` chain can be rolled |
| 451 | - /// can be rolled back as a unit. | 391 | + /// back as a unit. |
| 452 | async fn bring_up(&self, slug: &Slug) -> Result<Database, AppError> { | 392 | async fn bring_up(&self, slug: &Slug) -> Result<Database, AppError> { |
| 453 | - let db = match &*self.mode { | 393 | + let db_name = school_db_name(&self.control_db, slug); |
| 454 | - Mode::Remote { .. } => { | 394 | + // `CREATE DATABASE` cannot run inside a transaction; `Pool::execute` |
| 455 | - self.control | 395 | + // sends it as a bare autocommit statement. A name left over by a |
| 456 | - .query(format!( | 396 | + // create that died before its rollback is adopted, not fought. |
| 457 | - "DEFINE DATABASE IF NOT EXISTS {}", | 397 | + if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(create_database_sql( |
| 458 | - quoted_ident(slug) | 398 | + "CREATE DATABASE", |
| 459 | - )) | 399 | + &db_name, |
| 460 | - .await? | 400 | + ))) |
| 461 | - .check()?; | 401 | + .execute(&self.control) |
| 462 | - self.connect(slug).await? | 402 | + .await |
| 403 | + { | ||
| 404 | + if !is_duplicate_database(&err) { | ||
| 405 | + return Err(err.into()); | ||
| 463 | } | 406 | } |
| 464 | - Mode::Mem => self.connect(slug).await?, | 407 | + } |
| 465 | - }; | 408 | + let pool = school_pool(&self.base, &db_name).await?; |
| 466 | - migrate(&db).await?; | 409 | + let migrated = migrate_school(&pool).await; |
| 467 | - Ok(db) | 410 | + if migrated.is_err() { |
| 411 | + pool.close().await; | ||
| 412 | + migrated?; | ||
| 413 | + } | ||
| 414 | + Ok(pool) | ||
| 468 | } | 415 | } |
| 469 | 416 | ||
| 470 | /// Flip a school between active and suspended. Suspending also drops the | 417 | /// Flip a school between active and suspended. Suspending also drops the |
| 471 | - /// cached handle, so nothing that already resolved keeps serving. | 418 | + /// cached pool, so nothing that already resolved keeps serving. |
| 472 | pub async fn set_status(&self, slug: &Slug, status: SchoolStatus) -> Result<(), AppError> { | 419 | pub async fn set_status(&self, slug: &Slug, status: SchoolStatus) -> Result<(), AppError> { |
| 473 | - let updated: Vec<School> = self | 420 | + let updated = sqlx::query_as::<_, School>( |
| 474 | - .control | 421 | + "UPDATE school SET status = $1 WHERE slug = $2 |
| 475 | - .query("UPDATE $id SET status = $status RETURN AFTER") | 422 | + RETURNING slug, name, status, created_at, modules", |
| 476 | - .bind(("id", SchoolId::from_slug(slug).record())) | 423 | + ) |
| 477 | - .bind(("status", status)) | 424 | + .bind(status) |
| 478 | - .await? | 425 | + .bind(slug.as_str()) |
| 479 | - .check()? | 426 | + .fetch_optional(&self.control) |
| 480 | - .take(0)?; | 427 | + .await?; |
| 481 | - if updated.is_empty() { | 428 | + if updated.is_none() { |
| 482 | return Err(AppError::NotFound); | 429 | return Err(AppError::NotFound); |
| 483 | } | 430 | } |
| 484 | if status == SchoolStatus::Suspended { | 431 | if status == SchoolStatus::Suspended { |
| 485 | - self.evict(slug); | 432 | + self.evict(slug).await; |
| 486 | } | 433 | } |
| 487 | Ok(()) | 434 | Ok(()) |
| 488 | } | 435 | } |
| 489 | 436 | ||
| 490 | /// Sell (or take back) modules. Mirrors [`Tenants::set_status`] minus the | 437 | /// Sell (or take back) modules. Mirrors [`Tenants::set_status`] minus the |
| 491 | /// eviction: entitlements are read off the registry row on every request, | 438 | /// eviction: entitlements are read off the registry row on every request, |
| 492 | - /// so a change takes effect on the next call and no cached handle carries a | 439 | + /// so a change takes effect on the next call and no cached pool carries a |
| 493 | /// stale answer. | 440 | /// stale answer. |
| 494 | pub async fn set_modules(&self, slug: &Slug, modules: &ModuleSet) -> Result<(), AppError> { | 441 | pub async fn set_modules(&self, slug: &Slug, modules: &ModuleSet) -> Result<(), AppError> { |
| 495 | modules.validate()?; | 442 | modules.validate()?; |
| 496 | - let updated: Vec<School> = self | 443 | + let updated = sqlx::query_as::<_, School>( |
| 497 | - .control | 444 | + "UPDATE school SET modules = $1 WHERE slug = $2 |
| 498 | - .query("UPDATE $id SET modules = $modules RETURN AFTER") | 445 | + RETURNING slug, name, status, created_at, modules", |
| 499 | - .bind(("id", SchoolId::from_slug(slug).record())) | 446 | + ) |
| 500 | - .bind(("modules", modules.names())) | 447 | + .bind(modules.names()) |
| 501 | - .await? | 448 | + .bind(slug.as_str()) |
| 502 | - .check()? | 449 | + .fetch_optional(&self.control) |
| 503 | - .take(0)?; | 450 | + .await?; |
| 504 | - if updated.is_empty() { | 451 | + if updated.is_none() { |
| 505 | return Err(AppError::NotFound); | 452 | return Err(AppError::NotFound); |
| 506 | } | 453 | } |
| 507 | Ok(()) | 454 | Ok(()) |
| 508 | } | 455 | } |
| 509 | 456 | ||
| 510 | /// Delete a school outright: its data, then its registry row, then its | 457 | /// Delete a school outright: its data, then its registry row, then its |
| 511 | - /// handle. Irreversible on purpose — there is no soft-delete state, that is | 458 | + /// pool. Irreversible on purpose — there is no soft-delete state, that is |
| 512 | /// what [`SchoolStatus::Suspended`] is for. | 459 | /// what [`SchoolStatus::Suspended`] is for. |
| 513 | pub async fn drop(&self, slug: &Slug) -> Result<(), AppError> { | 460 | pub async fn drop(&self, slug: &Slug) -> Result<(), AppError> { |
| 514 | - if let Mode::Remote { .. } = &*self.mode { | 461 | + // Close the pool first: nothing should be dialling a school whose |
| 515 | - self.control | 462 | + // database is about to go away, and `WITH (FORCE)` should never find |
| 516 | - .query(format!("REMOVE DATABASE IF EXISTS {}", quoted_ident(slug))) | 463 | + // one of our connections to kill. |
| 517 | - .await? | 464 | + self.evict(slug).await; |
| 518 | - .check()?; | 465 | + sqlx::query("DELETE FROM school WHERE slug = $1") |
| 519 | - } | 466 | + .bind(slug.as_str()) |
| 520 | - self.control | 467 | + .execute(&self.control) |
| 521 | - .query("DELETE $id") | 468 | + .await?; |
| 522 | - .bind(("id", SchoolId::from_slug(slug).record())) | 469 | + let db_name = school_db_name(&self.control_db, slug); |
| 523 | - .await? | 470 | + sqlx::query(sqlx::AssertSqlSafe( |
| 524 | - .check()?; | 471 | + create_database_sql("DROP DATABASE IF EXISTS", &db_name) + " WITH (FORCE)", |
| 525 | - self.forget(slug); | 472 | + )) |
| 473 | + .execute(&self.control) | ||
| 474 | + .await?; | ||
| 526 | Ok(()) | 475 | Ok(()) |
| 527 | } | 476 | } |
| 528 | 477 | ||
| 529 | - /// Forget a school's connection. The next request dials a fresh one. | 478 | + /// Forget a school's pool and close it. The next request dials a fresh |
| 479 | + /// one. | ||
| 530 | /// | 480 | /// |
| 531 | - /// A no-op in memory mode, where the cached handle *is* the school's | 481 | + /// Nothing depends on eviction for correctness — [`Tenants::get`] |
| 532 | - /// datastore and dropping it would delete the school's data rather than its | ||
| 533 | - /// connection. Nothing depends on eviction for correctness — [`Tenants::get`] | ||
| 534 | /// re-reads the registry row on every request, so a suspension is refused | 482 | /// re-reads the registry row on every request, so a suspension is refused |
| 535 | - /// whether or not a handle survived it. [`Tenants::drop`], which does mean to | 483 | + /// whether or not a pool survived it. [`Tenants::drop`], which does mean |
| 536 | - /// destroy the store, forgets it unconditionally. | 484 | + /// to destroy the store, evicts unconditionally. |
| 537 | - pub fn evict(&self, slug: &Slug) { | 485 | + pub async fn evict(&self, slug: &Slug) { |
| 538 | - if matches!(&*self.mode, Mode::Mem) { | 486 | + if let Some(pool) = self.forget(slug) { |
| 539 | - return; | 487 | + pool.close().await; |
| 540 | } | 488 | } |
| 541 | - self.forget(slug); | ||
| 542 | } | 489 | } |
| 543 | 490 | ||
| 544 | - fn forget(&self, slug: &Slug) { | 491 | + fn forget(&self, slug: &Slug) -> Option<Database> { |
| 545 | let (removed, size) = { | 492 | let (removed, size) = { |
| 546 | let mut cache = self.cache.write().expect("tenant cache lock"); | 493 | let mut cache = self.cache.write().expect("tenant cache lock"); |
| 547 | - (cache.remove(slug.as_str()).is_some(), cache.len()) | 494 | + (cache.remove(slug.as_str()), cache.len()) |
| 548 | }; | 495 | }; |
| 549 | - if removed { | 496 | + if removed.is_some() { |
| 550 | - tracing::info!(school = %slug, "tenant connection evicted"); | 497 | + tracing::info!(school = %slug, "tenant pool evicted"); |
| 551 | Self::report_size(size); | 498 | Self::report_size(size); |
| 552 | } | 499 | } |
| 500 | + removed | ||
| 553 | } | 501 | } |
| 554 | 502 | ||
| 555 | - /// The cached handle, or a freshly dialled one. | 503 | + /// The cached pool, or a freshly dialled one. |
| 556 | async fn handle(&self, slug: &Slug) -> Result<Database, AppError> { | 504 | async fn handle(&self, slug: &Slug) -> Result<Database, AppError> { |
| 557 | if let Some(db) = self | 505 | if let Some(db) = self |
| 558 | .cache | 506 | .cache |
| @@ -562,20 +510,15 @@ impl Tenants { | |||
| 562 | { | 510 | { |
| 563 | return Ok(db.clone()); | 511 | return Ok(db.clone()); |
| 564 | } | 512 | } |
| 565 | - let db = self.connect(slug).await?; | 513 | + let db = school_pool(&self.base, &school_db_name(&self.control_db, slug)).await?; |
| 566 | - // In-memory mode has nowhere for a school's rows to have survived a | 514 | + // Losing the race here is harmless — both pools are equivalent — but |
| 567 | - // cache miss, so a fresh store needs the schema. Remote already has it. | 515 | + // the winner is kept so two requests never diverge onto two pools. |
| 568 | - if matches!(&*self.mode, Mode::Mem) { | ||
| 569 | - migrate(&db).await?; | ||
| 570 | - } | ||
| 571 | - // Losing the race here is harmless — both handles are equivalent — but | ||
| 572 | - // the winner is kept so two requests never diverge onto two sessions. | ||
| 573 | let (db, size) = { | 516 | let (db, size) = { |
| 574 | let mut cache = self.cache.write().expect("tenant cache lock"); | 517 | let mut cache = self.cache.write().expect("tenant cache lock"); |
| 575 | let db = cache.entry(slug.as_str().to_string()).or_insert(db).clone(); | 518 | let db = cache.entry(slug.as_str().to_string()).or_insert(db).clone(); |
| 576 | (db, cache.len()) | 519 | (db, cache.len()) |
| 577 | }; | 520 | }; |
| 578 | - tracing::info!(school = %slug, "tenant connection opened"); | 521 | + tracing::info!(school = %slug, "tenant pool opened"); |
| 579 | Self::report_size(size); | 522 | Self::report_size(size); |
| 580 | Ok(db) | 523 | Ok(db) |
| 581 | } | 524 | } |
| @@ -586,33 +529,6 @@ impl Tenants { | |||
| 586 | fn report_size(size: usize) { | 529 | fn report_size(size: usize) { |
| 587 | Metrics::global().tenant_cache_size.record(size as u64, &[]); | 530 | Metrics::global().tenant_cache_size.record(size as u64, &[]); |
| 588 | } | 531 | } |
| 589 | - | ||
| 590 | - /// One new connection, pinned to `slug`'s database for its lifetime. | ||
| 591 | - async fn connect(&self, slug: &Slug) -> Result<Database, AppError> { | ||
| 592 | - let db = match &*self.mode { | ||
| 593 | - Mode::Remote { | ||
| 594 | - url, | ||
| 595 | - user, | ||
| 596 | - pass, | ||
| 597 | - ns, | ||
| 598 | - } => { | ||
| 599 | - let db = surrealdb::engine::any::connect(url.clone()).await?; | ||
| 600 | - db.signin(Root { | ||
| 601 | - username: user.clone(), | ||
| 602 | - password: pass.clone(), | ||
| 603 | - }) | ||
| 604 | - .await?; | ||
| 605 | - db.use_ns(ns.clone()).use_db(slug.as_str()).await?; | ||
| 606 | - db | ||
| 607 | - } | ||
| 608 | - Mode::Mem => { | ||
| 609 | - let db = surrealdb::engine::any::connect("memory").await?; | ||
| 610 | - db.use_ns("hezarfen").use_db(slug.as_str()).await?; | ||
| 611 | - db | ||
| 612 | - } | ||
| 613 | - }; | ||
| 614 | - Ok(Arc::new(db)) | ||
| 615 | - } | ||
| 616 | } | 532 | } |
| 617 | 533 | ||
| 618 | #[cfg(test)] | 534 | #[cfg(test)] |
| @@ -623,20 +539,8 @@ mod tests { | |||
| 623 | Slug::try_new(value).expect(value) | 539 | Slug::try_new(value).expect(value) |
| 624 | } | 540 | } |
| 625 | 541 | ||
| 626 | - async fn count(db: &Database, table: &str) -> usize { | 542 | + #[test] |
| 627 | - let mut rows = db | 543 | + fn a_slug_names_a_school_and_nothing_reserved() { |
| 628 | - .query(format!("SELECT id FROM {table}")) | ||
| 629 | - .await | ||
| 630 | - .unwrap() | ||
| 631 | - .check() | ||
| 632 | - .unwrap(); | ||
| 633 | - rows.take::<Vec<surrealdb::types::RecordId>>(0) | ||
| 634 | - .unwrap() | ||
| 635 | - .len() | ||
| 636 | - } | ||
| 637 | - | ||
| 638 | - #[tokio::test] | ||
| 639 | - async fn a_slug_names_a_school_and_nothing_reserved() { | ||
| 640 | for good in ["demo", "a1", "ata-koleji", &"x".repeat(32)] { | 544 | for good in ["demo", "a1", "ata-koleji", &"x".repeat(32)] { |
| 641 | assert!(Slug::try_new(good).is_ok(), "{good:?} should be a slug"); | 545 | assert!(Slug::try_new(good).is_ok(), "{good:?} should be a slug"); |
| 642 | } | 546 | } |
| @@ -658,151 +562,37 @@ mod tests { | |||
| 658 | } | 562 | } |
| 659 | } | 563 | } |
| 660 | 564 | ||
| 661 | - #[tokio::test] | 565 | + /// The database-per-school model lives or dies by this mapping: two |
| 662 | - async fn two_schools_do_not_see_each_others_rows() { | 566 | + /// schools sharing a database name would share every row in it. `-` |
| 663 | - let tenants = Tenants::new_mem().await.unwrap(); | 567 | + /// becoming `_` is the only rewrite, and `_` is not in the slug charset, |
| 664 | - let (a, b) = (slug("alpha"), slug("beta")); | 568 | + /// so no two slugs can land on one name. |
| 665 | - let one = tenants.create(&a, "Alpha", ModuleSet::all()).await.unwrap(); | 569 | + #[test] |
| 666 | - let two = tenants.create(&b, "Beta", ModuleSet::all()).await.unwrap(); | 570 | + fn school_db_names_are_injective() { |
| 667 | - | 571 | + let control = "hezarfen_control"; |
| 668 | - one.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'") | ||
| 669 | - .await | ||
| 670 | - .unwrap() | ||
| 671 | - .check() | ||
| 672 | - .unwrap(); | ||
| 673 | - assert_eq!(count(&one, "user").await, 1); | ||
| 674 | assert_eq!( | 572 | assert_eq!( |
| 675 | - count(&two, "user").await, | 573 | + school_db_name(control, &slug("demo")), |
| 676 | - 0, | 574 | + "hezarfen_control_school_demo" |
| 677 | - "a row written in one school must be invisible in the other" | ||
| 678 | ); | 575 | ); |
| 679 | - // A second `create` on a taken slug is a conflict, not a second school. | ||
| 680 | - assert!(matches!( | ||
| 681 | - tenants.create(&a, "Alpha again", ModuleSet::all()).await, | ||
| 682 | - Err(AppError::Conflict(_)) | ||
| 683 | - )); | ||
| 684 | - } | ||
| 685 | - | ||
| 686 | - #[tokio::test] | ||
| 687 | - async fn suspending_refuses_the_school_and_the_handle_it_already_had() { | ||
| 688 | - let tenants = Tenants::new_mem().await.unwrap(); | ||
| 689 | - let s = slug("alpha"); | ||
| 690 | - tenants.create(&s, "Alpha", ModuleSet::all()).await.unwrap(); | ||
| 691 | - // Cached by the first resolve; the suspension must beat the cache. | ||
| 692 | - tenants.get(&s).await.expect("active school resolves"); | ||
| 693 | - | ||
| 694 | - tenants | ||
| 695 | - .set_status(&s, SchoolStatus::Suspended) | ||
| 696 | - .await | ||
| 697 | - .unwrap(); | ||
| 698 | - assert!(matches!( | ||
| 699 | - tenants.get(&s).await, | ||
| 700 | - Err(AppError::Forbidden("school is suspended")) | ||
| 701 | - )); | ||
| 702 | - // Builder tooling still reaches it, which is how it gets un-suspended. | ||
| 703 | - let (_, status) = tenants.get_any_status(&s).await.unwrap(); | ||
| 704 | - assert_eq!(status, SchoolStatus::Suspended); | ||
| 705 | - | ||
| 706 | - tenants.set_status(&s, SchoolStatus::Active).await.unwrap(); | ||
| 707 | - assert!(tenants.get(&s).await.is_ok()); | ||
| 708 | - // An unknown school is a bad credential, never a `404`. | ||
| 709 | - assert!(matches!( | ||
| 710 | - tenants.get(&slug("ghost")).await, | ||
| 711 | - Err(AppError::Unauthorized) | ||
| 712 | - )); | ||
| 713 | - assert!(matches!( | ||
| 714 | - tenants.get_any_status(&slug("ghost")).await, | ||
| 715 | - Err(AppError::NotFound) | ||
| 716 | - )); | ||
| 717 | - } | ||
| 718 | - | ||
| 719 | - #[tokio::test] | ||
| 720 | - async fn dropping_a_school_takes_its_rows_with_it() { | ||
| 721 | - let tenants = Tenants::new_mem().await.unwrap(); | ||
| 722 | - let s = slug("alpha"); | ||
| 723 | - let db = tenants.create(&s, "Alpha", ModuleSet::all()).await.unwrap(); | ||
| 724 | - db.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'") | ||
| 725 | - .await | ||
| 726 | - .unwrap() | ||
| 727 | - .check() | ||
| 728 | - .unwrap(); | ||
| 729 | - assert_eq!(count(&db, "user").await, 1); | ||
| 730 | - | ||
| 731 | - tenants.drop(&s).await.unwrap(); | ||
| 732 | - assert!(matches!(tenants.get(&s).await, Err(AppError::Unauthorized))); | ||
| 733 | - | ||
| 734 | - let fresh = tenants | ||
| 735 | - .create(&s, "Alpha reborn", ModuleSet::all()) | ||
| 736 | - .await | ||
| 737 | - .unwrap(); | ||
| 738 | - assert_eq!( | ||
| 739 | - count(&fresh, "user").await, | ||
| 740 | - 0, | ||
| 741 | - "a re-created school must not inherit the dropped one's rows" | ||
| 742 | - ); | ||
| 743 | - } | ||
| 744 | - | ||
| 745 | - #[tokio::test] | ||
| 746 | - async fn the_registry_lists_and_renames() { | ||
| 747 | - let tenants = Tenants::new_mem().await.unwrap(); | ||
| 748 | - tenants | ||
| 749 | - .create(&slug("alpha"), "Alpha", ModuleSet::all()) | ||
| 750 | - .await | ||
| 751 | - .unwrap(); | ||
| 752 | - tenants | ||
| 753 | - .create(&slug("beta"), "Beta", ModuleSet::all()) | ||
| 754 | - .await | ||
| 755 | - .unwrap(); | ||
| 756 | - | ||
| 757 | - let (rows, total) = School::list(None, 0, tenants.control()).await.unwrap(); | ||
| 758 | - assert_eq!(total, 2); | ||
| 759 | - assert_eq!(rows.len(), 2); | ||
| 760 | - | ||
| 761 | - let renamed = School::update_name(&slug("alpha"), "Alpha Koleji", tenants.control()) | ||
| 762 | - .await | ||
| 763 | - .unwrap(); | ||
| 764 | - assert_eq!(renamed.name(), "Alpha Koleji"); | ||
| 765 | assert_eq!( | 576 | assert_eq!( |
| 766 | - renamed.slug().as_str(), | 577 | + school_db_name(control, &slug("ata-koleji")), |
| 767 | - "alpha", | 578 | + "hezarfen_control_school_ata_koleji" |
| 768 | - "a rename never moves the slug" | ||
| 769 | ); | 579 | ); |
| 770 | - assert!(matches!( | 580 | + for a in ["a", "a-b", "ab", "a1b", "1a", "x-y-z"] { |
| 771 | - School::update_name(&slug("ghost"), "Nope", tenants.control()).await, | 581 | + for b in ["a", "a-b", "ab", "a1b", "1a", "x-y-z"] { |
| 772 | - Err(AppError::NotFound) | 582 | + if a != b { |
| 773 | - )); | 583 | + assert_ne!( |
| 774 | - } | 584 | + school_db_name(control, &slug(a)), |
| 775 | - /// The builder API validates a set before it calls here (its message names | 585 | + school_db_name(control, &slug(b)), |
| 776 | - /// every violation at once), but the registry is the last gate: no caller, | 586 | + "{a:?} and {b:?} must not share a database" |
| 777 | - /// present or future, may persist a set a school could not run on. | 587 | + ); |
| 778 | - #[tokio::test] | 588 | + } |
| 779 | - async fn the_registry_refuses_an_unsatisfiable_set_on_create_and_on_sale() { | 589 | + } |
| 780 | - let tenants = Tenants::new_mem().await.unwrap(); | 590 | + } |
| 781 | - let s = slug("alpha"); | 591 | + // The control database's own name is never a school's name: the |
| 782 | - let mut lone = ModuleSet::empty(); | 592 | + // suffix keeps the namespaces apart. |
| 783 | - lone.insert(crate::module::Module::Exams); | 593 | + assert_ne!( |
| 784 | - | 594 | + school_db_name(control, &slug("school")), |
| 785 | - assert!( | 595 | + control |
| 786 | - matches!( | ||
| 787 | - tenants.create(&s, "Alpha", lone.clone()).await, | ||
| 788 | - Err(AppError::ConflictOwned(_)) | ||
| 789 | - ), | ||
| 790 | - "exams alone is unsatisfiable, so the school must not come into being" | ||
| 791 | - ); | ||
| 792 | - assert!( | ||
| 793 | - matches!(tenants.get(&s).await, Err(AppError::Unauthorized)), | ||
| 794 | - "a refused create leaves no registry row behind" | ||
| 795 | - ); | ||
| 796 | - | ||
| 797 | - tenants.create(&s, "Alpha", ModuleSet::all()).await.unwrap(); | ||
| 798 | - assert!(matches!( | ||
| 799 | - tenants.set_modules(&s, &lone).await, | ||
| 800 | - Err(AppError::ConflictOwned(_)) | ||
| 801 | - )); | ||
| 802 | - assert_eq!( | ||
| 803 | - tenants.resolve(&s).await.unwrap().modules, | ||
| 804 | - ModuleSet::all(), | ||
| 805 | - "the refused sale must not have touched the row" | ||
| 806 | ); | 596 | ); |
| 807 | } | 597 | } |
| 808 | } | 598 | } |
src/web/auth.rsmodified+1 -1
| @@ -31,7 +31,7 @@ pub fn routes(state: &AppState) -> OpenApiRouter<AppState> { | |||
| 31 | let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy); | 31 | let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy); |
| 32 | // The budget survives a restart — the tier only means something if a | 32 | // The budget survives a restart — the tier only means something if a |
| 33 | // brute-forcer cannot reset it by waiting out a deploy. | 33 | // brute-forcer cannot reset it by waiting out a deploy. |
| 34 | - limiter.share("auth", state.db.clone(), state.db_up.clone()); | 34 | + limiter.share("auth", state.db.clone()); |
| 35 | OpenApiRouter::new() | 35 | OpenApiRouter::new() |
| 36 | .routes(routes!(register)) | 36 | .routes(routes!(register)) |
| 37 | .routes(routes!(login)) | 37 | .routes(routes!(login)) |
src/web/builder.rsmodified+1 -1
| @@ -48,7 +48,7 @@ pub fn routes(state: &AppState) -> OpenApiRouter<AppState> { | |||
| 48 | // budget, since a school's brute-forcer must not spend the vendor's. | 48 | // budget, since a school's brute-forcer must not spend the vendor's. |
| 49 | let rate_limit: &RateLimitConfig = &state.rate_limit; | 49 | let rate_limit: &RateLimitConfig = &state.rate_limit; |
| 50 | let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy); | 50 | let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy); |
| 51 | - limiter.share("builder", state.db.clone(), state.db_up.clone()); | 51 | + limiter.share("builder", state.db.clone()); |
| 52 | OpenApiRouter::new() | 52 | OpenApiRouter::new() |
| 53 | .routes(routes!(builder_login)) | 53 | .routes(routes!(builder_login)) |
| 54 | .route_layer(middleware::from_fn(move |req: Request, next: Next| { | 54 | .route_layer(middleware::from_fn(move |req: Request, next: Next| { |
src/web/tenant_state.rsmodified+0 -2
| @@ -243,7 +243,6 @@ mod tests { | |||
| 243 | chatbot_limit: Default::default(), | 243 | chatbot_limit: Default::default(), |
| 244 | exam_presence: Default::default(), | 244 | exam_presence: Default::default(), |
| 245 | board_hub: Default::default(), | 245 | board_hub: Default::default(), |
| 246 | - db_up: Default::default(), | ||
| 247 | ai: None, | 246 | ai: None, |
| 248 | metrics: crate::telemetry::Metrics::noop(), | 247 | metrics: crate::telemetry::Metrics::noop(), |
| 249 | }; | 248 | }; |
| @@ -355,7 +354,6 @@ mod tests { | |||
| 355 | chatbot_limit: Default::default(), | 354 | chatbot_limit: Default::default(), |
| 356 | exam_presence: Default::default(), | 355 | exam_presence: Default::default(), |
| 357 | board_hub: Default::default(), | 356 | board_hub: Default::default(), |
| 358 | - db_up: Default::default(), | ||
| 359 | ai: None, | 357 | ai: None, |
| 360 | metrics: crate::telemetry::Metrics::noop(), | 358 | metrics: crate::telemetry::Metrics::noop(), |
| 361 | }; | 359 | }; |