diff --git a/.env.example b/.env.example index 0b320d3..90339c9 100644 --- a/.env.example +++ b/.env.example @@ -2,15 +2,14 @@ HOST=127.0.0.1 PORT=8080 -# SurrealDB server endpoint + root credentials. For local dev start one with: -# surreal start --user root --pass root surrealkv:./data/hezarfen.db -DB_URL=ws://127.0.0.1:8000 -DB_USER=root -DB_PASS=root -DB_NAMESPACE=hezarfen -# The CONTROL database: the school registry and the builder accounts. Each -# school gets a database of its own inside DB_NAMESPACE, named by its slug. -DB_DATABASE=control +# PostgreSQL connection string. Also read by sqlx's compile-time query macros, +# so `cargo check` prepares every query against this database. For local dev: +# podman compose up -d postgres +DATABASE_URL=postgres://hezarfen:hezarfen@127.0.0.1:5432/hezarfen_control + +# The maintenance database tests clone scratch databases from (see +# tests/common). Uncomment to override the default. +# HEZARFEN_TEST_DATABASE_URL=postgres://hezarfen:hezarfen@127.0.0.1:5432/postgres # Directory for uploaded note-file blobs (created at startup). Each school # writes into a subdirectory of it named by its slug. diff --git a/.sqlx/.gitkeep b/.sqlx/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/Cargo.lock b/Cargo.lock index 6776a95..9a59e35 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,62 +2,12 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "addr" -version = "0.15.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a93b8a41dbe230ad5087cc721f8d41611de654542180586b315d9f4cf6b72bef" -dependencies = [ - "psl-types", -] - [[package]] name = "adler2" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" -[[package]] -name = "affinitypool" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4a46f56d354df11b6bcd8ca4f84fa03ac816cc41c72568a1b337d8f7e5af90e" -dependencies = [ - "arc-swap", - "async-task", - "crossbeam-deque", - "crossbeam-utils", - "libc", - "num_cpus", - "parking_lot", - "thiserror", - "winapi", -] - -[[package]] -name = "ahash" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" -dependencies = [ - "getrandom 0.2.17", - "once_cell", - "version_check", -] - -[[package]] -name = "ahash" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" -dependencies = [ - "cfg-if", - "getrandom 0.3.4", - "once_cell", - "version_check", - "zerocopy", -] - [[package]] name = "aho-corasick" version = "1.1.4" @@ -73,18 +23,6 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" -[[package]] -name = "ammonia" -version = "4.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc6d763210e2eb7670d1a5183a08bebefa3f97db2a738a684f2ce00bd49f681d" -dependencies = [ - "cssparser", - "html5ever", - "maplit", - "url", -] - [[package]] name = "android_system_properties" version = "0.1.5" @@ -100,15 +38,6 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" -[[package]] -name = "approx" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" -dependencies = [ - "num-traits", -] - [[package]] name = "arbitrary" version = "1.4.2" @@ -118,27 +47,6 @@ dependencies = [ "derive_arbitrary", ] -[[package]] -name = "arc-swap" -version = "1.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" -dependencies = [ - "rustversion", -] - -[[package]] -name = "argon2" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" -dependencies = [ - "base64ct", - "blake2 0.10.6", - "cpufeatures 0.2.17", - "password-hash 0.5.0", -] - [[package]] name = "argon2" version = "0.6.0" @@ -146,33 +54,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c" dependencies = [ "base64ct", - "blake2 0.11.0", + "blake2", "cpufeatures 0.3.1", - "password-hash 0.6.1", -] - -[[package]] -name = "arrayref" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" - -[[package]] -name = "arrayvec" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" - -[[package]] -name = "as-slice" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45403b49e3954a4b8428a0ac21a4b7afadccf92bfd96273f1a58cd4812496ae0" -dependencies = [ - "generic-array 0.12.4", - "generic-array 0.13.3", - "generic-array 0.14.7", - "stable_deref_trait", + "password-hash", ] [[package]] @@ -214,46 +98,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "async-channel" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" -dependencies = [ - "concurrent-queue", - "event-listener-strategy", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" -dependencies = [ - "async-stream-impl", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream-impl" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "async-task" -version = "4.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" - [[package]] name = "async-trait" version = "0.1.91" @@ -266,12 +110,12 @@ dependencies = [ ] [[package]] -name = "atomic-polyfill" -version = "1.0.3" +name = "atoi" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cf2bce30dfe09ef0bfaef228b9d414faaf7e563035494d7fe092dba54b300f4" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" dependencies = [ - "critical-section", + "num-traits", ] [[package]] @@ -286,30 +130,6 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" -[[package]] -name = "aws-lc-rs" -version = "1.17.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00bdb5da18dac48ca2cc7cd4a98e533e8635a58e2361d13a1a4ee3888e0d72f1" -dependencies = [ - "aws-lc-sys", - "untrusted 0.7.1", - "zeroize", -] - -[[package]] -name = "aws-lc-sys" -version = "0.43.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43103168cc76fe62678a375e722fc9cb3a0146159ac5828bc4f0dfd755c2224c" -dependencies = [ - "cc", - "cmake", - "dunce", - "fs_extra", - "pkg-config", -] - [[package]] name = "axum" version = "0.8.9" @@ -388,12 +208,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "base16ct" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" - [[package]] name = "base64" version = "0.22.1" @@ -412,39 +226,6 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" -[[package]] -name = "bcrypt" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a0f5948f30df5f43ac29d310b7476793be97c50787e6ef4a63d960a0d0be827" -dependencies = [ - "base64 0.22.1", - "blowfish", - "getrandom 0.3.4", - "subtle", - "zeroize", -] - -[[package]] -name = "bincode" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740" -dependencies = [ - "bincode_derive", - "serde", - "unty", -] - -[[package]] -name = "bincode_derive" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf95709a440f45e986983918d0e8a1f30a9b1df04918fc828670606804ac3c09" -dependencies = [ - "virtue", -] - [[package]] name = "bit-set" version = "0.8.0" @@ -474,26 +255,8 @@ name = "bitflags" version = "2.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" - -[[package]] -name = "bitvec" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" -dependencies = [ - "funty", - "radium", - "tap", - "wyz", -] - -[[package]] -name = "blake2" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" dependencies = [ - "digest 0.10.7", + "serde_core", ] [[package]] @@ -505,27 +268,13 @@ dependencies = [ "digest 0.11.3", ] -[[package]] -name = "blake3" -version = "1.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0aa83c34e62843d924f905e0f5c866eb1dd6545fc4d719e803d9ba6030371fce" -dependencies = [ - "arrayref", - "arrayvec", - "cc", - "cfg-if", - "constant_time_eq", - "cpufeatures 0.3.1", -] - [[package]] name = "block-buffer" version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" dependencies = [ - "generic-array 0.14.7", + "generic-array", ] [[package]] @@ -537,100 +286,12 @@ dependencies = [ "hybrid-array", ] -[[package]] -name = "blowfish" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7" -dependencies = [ - "byteorder", - "cipher", -] - -[[package]] -name = "bnum" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f781dba93de3a5ef6dc5b17c9958b208f6f3f021623b360fb605ea51ce443f10" - -[[package]] -name = "borsh" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a88b7ea17d208c4193f2c1e6de3c35fe71f98c96982d5ced308bdcc749ff6e1f" -dependencies = [ - "borsh-derive", - "bytes", - "cfg_aliases", -] - -[[package]] -name = "borsh-derive" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8f347189c62a579b8cd5f80714efa178f52e461dc2e6d701d264f5ff22e566c" -dependencies = [ - "once_cell", - "proc-macro-crate", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "boxcar" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36f64beae40a84da1b4b26ff2761a5b895c12adc41dc25aaee1c4f2bbfe97a6e" - [[package]] name = "bumpalo" version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" -[[package]] -name = "bytecheck" -version = "0.6.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23cdc57ce23ac53c931e88a43d06d070a6fd142f2617be5855eb75efc9beb1c2" -dependencies = [ - "bytecheck_derive", - "ptr_meta", - "simdutf8", -] - -[[package]] -name = "bytecheck_derive" -version = "0.6.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3db406d29fbcd95542e92559bed4d8ad92636d1ca8b3b72ede10b4bcc010e659" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "bytemuck" -version = "1.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" -dependencies = [ - "bytemuck_derive", -] - -[[package]] -name = "bytemuck_derive" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f65693059b6b9c588b9f62fed1cedbf0a8b805631457ea162d68f0de186f3de5" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "byteorder" version = "1.5.0" @@ -642,18 +303,6 @@ name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" -dependencies = [ - "serde", -] - -[[package]] -name = "castaway" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" -dependencies = [ - "rustversion", -] [[package]] name = "cc" @@ -662,8 +311,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80" dependencies = [ "find-msvc-tools", - "jobserver", - "libc", "shlex", ] @@ -699,106 +346,38 @@ dependencies = [ "iana-time-zone", "js-sys", "num-traits", - "serde", "wasm-bindgen", - "windows-link 0.2.1", + "windows-link", ] [[package]] -name = "ciborium" -version = "0.2.2" +name = "cmov" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" -dependencies = [ - "ciborium-io", - "ciborium-ll", - "serde", -] +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" [[package]] -name = "ciborium-io" -version = "0.2.2" +name = "const-oid" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" [[package]] -name = "ciborium-ll" -version = "0.2.2" +name = "cookie" +version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" dependencies = [ - "ciborium-io", - "half", + "percent-encoding", + "time", + "version_check", ] [[package]] -name = "cipher" -version = "0.4.4" +name = "cookie_store" +version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" -dependencies = [ - "crypto-common 0.1.7", - "inout", -] - -[[package]] -name = "cmake" -version = "0.1.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" -dependencies = [ - "cc", -] - -[[package]] -name = "cmov" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" - -[[package]] -name = "concurrent-queue" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "const-oid" -version = "0.9.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" - -[[package]] -name = "const-oid" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" - -[[package]] -name = "constant_time_eq" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" - -[[package]] -name = "cookie" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" -dependencies = [ - "percent-encoding", - "time", - "version_check", -] - -[[package]] -name = "cookie_store" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" dependencies = [ "cookie", "document-features", @@ -837,81 +416,43 @@ dependencies = [ ] [[package]] -name = "crc32fast" -version = "1.5.0" +name = "crc" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" dependencies = [ - "cfg-if", + "crc-catalog", ] [[package]] -name = "critical-section" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" - -[[package]] -name = "crossbeam-deque" -version = "0.8.7" +name = "crc-catalog" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" -dependencies = [ - "crossbeam-epoch", - "crossbeam-utils", -] +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" [[package]] -name = "crossbeam-epoch" -version = "0.9.20" +name = "crc32fast" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" dependencies = [ - "crossbeam-utils", + "cfg-if", ] [[package]] name = "crossbeam-queue" -version = "0.3.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "803d13fb3b09d88be9f4dbc29062c66b19bf7170867ceb746d2a8689bf6c7a26" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-skiplist" -version = "0.1.3" +version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df29de440c58ca2cc6e587ec3d22347551a32435fbde9d2bff64e78a9ffa151b" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" dependencies = [ - "crossbeam-epoch", "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" - -[[package]] -name = "crunchy" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" - -[[package]] -name = "crypto-bigint" -version = "0.5.5" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" -dependencies = [ - "generic-array 0.14.7", - "rand_core 0.6.4", - "subtle", - "zeroize", -] +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" [[package]] name = "crypto-common" @@ -919,7 +460,7 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ - "generic-array 0.14.7", + "generic-array", "typenum", ] @@ -932,17 +473,6 @@ dependencies = [ "hybrid-array", ] -[[package]] -name = "cssparser" -version = "0.37.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98" -dependencies = [ - "dtoa-short", - "itoa", - "smallvec", -] - [[package]] name = "ctutils" version = "0.4.2" @@ -952,64 +482,12 @@ dependencies = [ "cmov", ] -[[package]] -name = "curve25519-dalek" -version = "4.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "curve25519-dalek-derive", - "digest 0.10.7", - "fiat-crypto", - "rustc_version", - "subtle", - "zeroize", -] - -[[package]] -name = "curve25519-dalek-derive" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "dashmap" -version = "6.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" -dependencies = [ - "cfg-if", - "crossbeam-utils", - "hashbrown 0.14.5", - "lock_api", - "once_cell", - "parking_lot_core", -] - [[package]] name = "data-encoding" version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" -[[package]] -name = "der" -version = "0.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" -dependencies = [ - "const-oid 0.9.6", - "pem-rfc7468", - "zeroize", -] - [[package]] name = "der-parser" version = "10.0.0" @@ -1041,12 +519,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "deunicode" -version = "1.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abd57806937c9cc163efc8ea3910e00a62e2aeb0b8119f1793a978088f8f6b04" - [[package]] name = "digest" version = "0.10.7" @@ -1054,9 +526,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", - "const-oid 0.9.6", "crypto-common 0.1.7", - "subtle", ] [[package]] @@ -1066,69 +536,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid 0.10.2", + "const-oid", "crypto-common 0.2.2", "ctutils", ] -[[package]] -name = "diskann" -version = "0.54.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "421c6cf955c6cb1451d36c8a3740ab2a22880265d0fa93d8ea22cbc425c90479" -dependencies = [ - "anyhow", - "bytemuck", - "diskann-utils", - "diskann-vector", - "diskann-wide", - "futures-util", - "half", - "hashbrown 0.16.1", - "num-traits", - "rand 0.9.5", - "thiserror", - "tokio", -] - -[[package]] -name = "diskann-utils" -version = "0.54.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cdf7d491910fbff13338e07460c9197a3c172268cfd4d8f8e69e5cec5a256d9" -dependencies = [ - "bytemuck", - "cfg-if", - "diskann-vector", - "diskann-wide", - "half", - "rand 0.9.5", - "rand_distr", - "rayon", - "thiserror", -] - -[[package]] -name = "diskann-vector" -version = "0.54.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de1643bbece645f03527ef120bc7dd5e4e40557980dbe52ee51129adfb58a851" -dependencies = [ - "cfg-if", - "diskann-wide", - "half", -] - -[[package]] -name = "diskann-wide" -version = "0.54.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "421f02c42e57a2153dc65b66b4b95fe2be56e14bf9f95253b663abcac8521166" -dependencies = [ - "cfg-if", - "half", -] - [[package]] name = "displaydoc" version = "0.2.7" @@ -1140,16 +552,6 @@ dependencies = [ "syn 3.0.5", ] -[[package]] -name = "dmp" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb2dfc7a18dffd3ef60a442b72a827126f1557d914620f8fc4d1049916da43c1" -dependencies = [ - "trice", - "urlencoding", -] - [[package]] name = "document-features" version = "0.2.12" @@ -1165,100 +567,13 @@ version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" -[[package]] -name = "dtoa" -version = "1.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" - -[[package]] -name = "dtoa-short" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" -dependencies = [ - "dtoa", -] - -[[package]] -name = "dunce" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" - -[[package]] -name = "earcutr" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79127ed59a85d7687c409e9978547cffb7dc79675355ed22da6b66fd5f6ead01" -dependencies = [ - "itertools 0.11.0", - "num-traits", -] - -[[package]] -name = "ecdsa" -version = "0.16.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" -dependencies = [ - "der", - "digest 0.10.7", - "elliptic-curve", - "rfc6979", - "signature", - "spki", -] - -[[package]] -name = "ed25519" -version = "2.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" -dependencies = [ - "pkcs8", - "signature", -] - -[[package]] -name = "ed25519-dalek" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" -dependencies = [ - "curve25519-dalek", - "ed25519", - "serde", - "sha2 0.10.9", - "subtle", - "zeroize", -] - [[package]] name = "either" version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" - -[[package]] -name = "elliptic-curve" -version = "0.13.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" dependencies = [ - "base16ct", - "crypto-bigint", - "digest 0.10.7", - "ff", - "generic-array 0.14.7", - "group", - "hkdf", - "pem-rfc7468", - "pkcs8", - "rand_core 0.6.4", - "sec1", - "subtle", - "zeroize", + "serde", ] [[package]] @@ -1287,89 +602,37 @@ dependencies = [ ] [[package]] -name = "event-listener" -version = "5.4.1" +name = "etcetera" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +checksum = "de48cc4d1c1d97a20fd819def54b890cadde72ed3ad0c614822a0a433361be96" dependencies = [ - "concurrent-queue", - "parking", - "pin-project-lite", + "cfg-if", + "windows-sys 0.61.2", ] [[package]] -name = "event-listener-strategy" -version = "0.5.4" +name = "event-listener" +version = "5.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" dependencies = [ - "event-listener", + "parking", "pin-project-lite", ] -[[package]] -name = "ext-sort" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf5d3b056bcc471d38082b8c453acb6670f7327fd44219b3c411e40834883569" -dependencies = [ - "log", - "rayon", - "rmp-serde", - "serde", - "tempfile", -] - -[[package]] -name = "fastnum" -version = "0.7.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "020d1b59a944bc239d79903fbac2eda2365138b44890c27979562f6592059dcd" -dependencies = [ - "bnum", - "num-integer", - "num-traits", -] - [[package]] name = "fastrand" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" -[[package]] -name = "ff" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" -dependencies = [ - "rand_core 0.6.4", - "subtle", -] - -[[package]] -name = "fiat-crypto" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" - [[package]] name = "find-msvc-tools" version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" -[[package]] -name = "flatbuffers" -version = "25.12.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3" -dependencies = [ - "bitflags", - "rustc_version", - "serde", -] - [[package]] name = "flate2" version = "1.1.9" @@ -1381,10 +644,15 @@ dependencies = [ ] [[package]] -name = "float_next_after" -version = "1.0.0" +name = "flume" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8" +checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] [[package]] name = "fnv" @@ -1407,39 +675,6 @@ dependencies = [ "percent-encoding", ] -[[package]] -name = "fs_extra" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" - -[[package]] -name = "fst" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ab85b9b05e3978cc9a9cf8fea7f01b494e1a09ed3037e16ba39edc7a29eb61a" - -[[package]] -name = "funty" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" - -[[package]] -name = "futures" -version = "0.3.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - [[package]] name = "futures-channel" version = "0.3.34" @@ -1467,6 +702,17 @@ dependencies = [ "futures-util", ] +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + [[package]] name = "futures-io" version = "0.3.34" @@ -1502,7 +748,6 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ - "futures-channel", "futures-core", "futures-io", "futures-macro", @@ -1513,33 +758,6 @@ dependencies = [ "slab", ] -[[package]] -name = "fuzzy-matcher" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54614a3312934d066701a80f20f15fa3b56d67ac7722b39eea5b4c9dd1d66c94" -dependencies = [ - "thread_local", -] - -[[package]] -name = "generic-array" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" -dependencies = [ - "typenum", -] - -[[package]] -name = "generic-array" -version = "0.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f797e67af32588215eaaab8327027ee8e71b9dd0b2b26996aedf20c030fce309" -dependencies = [ - "typenum", -] - [[package]] name = "generic-array" version = "0.14.7" @@ -1548,54 +766,6 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", - "zeroize", -] - -[[package]] -name = "geo" -version = "0.32.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f3901269ec6d4f6068d3f09e5f02f995bd076398dcd1dfec407cd230b02d11b" -dependencies = [ - "earcutr", - "float_next_after", - "geo-types", - "geographiclib-rs", - "i_overlay", - "log", - "num-traits", - "rand 0.8.7", - "robust", - "rstar 0.12.2", - "serde", - "sif-itree", - "spade", -] - -[[package]] -name = "geo-types" -version = "0.7.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94776032c45f950d30a13af6113c2ad5625316c9abfbccee4dd5a6695f8fe0f5" -dependencies = [ - "approx", - "num-traits", - "rayon", - "rstar 0.10.0", - "rstar 0.11.0", - "rstar 0.12.2", - "rstar 0.8.4", - "rstar 0.9.3", - "serde", -] - -[[package]] -name = "geographiclib-rs" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5a7f08910fd98737a6eda7568e7c5e645093e073328eeef49758cfe8b0489c7" -dependencies = [ - "libm", ] [[package]] @@ -1618,11 +788,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", - "js-sys", "libc", "r-efi 5.3.0", "wasip2", - "wasm-bindgen", ] [[package]] @@ -1632,22 +800,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", - "js-sys", - "libc", - "r-efi 6.0.0", - "rand_core 0.10.1", - "wasm-bindgen", -] - -[[package]] -name = "group" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" -dependencies = [ - "ff", - "rand_core 0.6.4", - "subtle", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -1669,63 +826,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "half" -version = "2.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" -dependencies = [ - "bytemuck", - "cfg-if", - "crunchy", - "num-traits", - "rand 0.9.5", - "rand_distr", - "zerocopy", -] - -[[package]] -name = "hash32" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4041af86e63ac4298ce40e5cca669066e75b6f1aa3390fe2561ffa5e1d9f4cc" -dependencies = [ - "byteorder", -] - -[[package]] -name = "hash32" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67" -dependencies = [ - "byteorder", -] - -[[package]] -name = "hash32" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" -dependencies = [ - "byteorder", -] - -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" -dependencies = [ - "ahash 0.7.8", -] - -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" - [[package]] name = "hashbrown" version = "0.16.1" @@ -1744,75 +844,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" [[package]] -name = "headers" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb" -dependencies = [ - "base64 0.22.1", - "bytes", - "headers-core", - "http", - "httpdate", - "mime", - "sha1 0.10.7", -] - -[[package]] -name = "headers-core" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" -dependencies = [ - "http", -] - -[[package]] -name = "heapless" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "634bd4d29cbf24424d0a4bfcbf80c6960129dc24424752a7d1d1390607023422" -dependencies = [ - "as-slice", - "generic-array 0.14.7", - "hash32 0.1.1", - "stable_deref_trait", -] - -[[package]] -name = "heapless" -version = "0.7.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f" -dependencies = [ - "atomic-polyfill", - "hash32 0.2.1", - "rustc_version", - "spin", - "stable_deref_trait", -] - -[[package]] -name = "heapless" -version = "0.8.0" +name = "hashlink" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" +checksum = "824e001ac4f3012dd16a264bec811403a67ca9deb6c102fc5049b32c4574b35f" dependencies = [ - "hash32 0.3.1", - "stable_deref_trait", + "hashbrown 0.16.1", ] [[package]] name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - -[[package]] -name = "hermit-abi" -version = "0.5.2" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "hex" @@ -1825,7 +869,7 @@ name = "hezarfen_backend" version = "0.1.0" dependencies = [ "anyhow", - "argon2 0.6.0", + "argon2", "axum", "axum-extra", "base64 0.23.1", @@ -1849,7 +893,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", - "surrealdb", + "sqlx", "tempfile", "thiserror", "time", @@ -1861,7 +905,6 @@ dependencies = [ "tracing", "tracing-opentelemetry", "tracing-subscriber", - "ulid 3.0.0", "utoipa", "utoipa-axum", "utoipa-swagger-ui", @@ -1870,30 +913,20 @@ dependencies = [ [[package]] name = "hkdf" -version = "0.12.4" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" dependencies = [ "hmac", ] [[package]] name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest 0.10.7", -] - -[[package]] -name = "html5ever" -version = "0.39.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" dependencies = [ - "log", - "markup5ever", + "digest 0.11.3", ] [[package]] @@ -1941,12 +974,6 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" -[[package]] -name = "humantime" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" - [[package]] name = "hybrid-array" version = "0.4.15" @@ -2014,49 +1041,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "i_float" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "010025c2c532c8d82e42d0b8bb5184afa449fa6f06c709ea9adcb16c49ae405b" -dependencies = [ - "libm", -] - -[[package]] -name = "i_key_sort" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9190f86706ca38ac8add223b2aed8b1330002b5cdbbce28fb58b10914d38fc27" - -[[package]] -name = "i_overlay" -version = "4.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413183068e6e0289e18d7d0a1f661b81546e6918d5453a44570b9ab30cbed1b3" -dependencies = [ - "i_float", - "i_key_sort", - "i_shape", - "i_tree", - "rayon", -] - -[[package]] -name = "i_shape" -version = "1.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ea154b742f7d43dae2897fcd5ead86bc7b5eefcedd305a7ebf9f69d44d61082" -dependencies = [ - "i_float", -] - -[[package]] -name = "i_tree" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35e6d558e6d4c7b82bc51d9c771e7a927862a161a7d87bf2b0541450e0e20915" - [[package]] name = "iana-time-zone" version = "0.1.65" @@ -2069,7 +1053,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core 0.62.2", + "windows-core", ] [[package]] @@ -2196,39 +1180,12 @@ dependencies = [ "serde_core", ] -[[package]] -name = "inout" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" -dependencies = [ - "generic-array 0.14.7", -] - [[package]] name = "ipnet" version = "2.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" -[[package]] -name = "itertools" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" -dependencies = [ - "either", -] - -[[package]] -name = "itertools" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.14.0" @@ -2244,16 +1201,6 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" -[[package]] -name = "jobserver" -version = "0.1.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" -dependencies = [ - "getrandom 0.4.3", - "libc", -] - [[package]] name = "js-sys" version = "0.3.103" @@ -2265,48 +1212,11 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "jsonwebtoken" -version = "10.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eba32bfb4ffdeaca3e34431072faf01745c9b26d25504aa7a6cf5684334fc4fc" -dependencies = [ - "aws-lc-rs", - "base64 0.22.1", - "ed25519-dalek", - "getrandom 0.2.17", - "hmac", - "js-sys", - "p256", - "p384", - "pem 3.0.6", - "rand 0.8.7", - "rsa", - "serde", - "serde_json", - "sha2 0.10.9", - "signature", - "simple_asn1", - "zeroize", -] - [[package]] name = "lazy_static" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" -dependencies = [ - "spin", -] - -[[package]] -name = "lexicmp" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e8f89da8fd95c4eb6274e914694bea90c7826523b26f2a2fd863d44b9d42c43" -dependencies = [ - "deunicode", -] [[package]] name = "libc" @@ -2315,10 +1225,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" [[package]] -name = "libm" -version = "0.2.16" +name = "libsqlite3-sys" +version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" +checksum = "b1f111c8c41e7c61a49cd34e44c7619462967221a6443b0ec299e0ac30cfb9b1" +dependencies = [ + "pkg-config", + "vcpkg", +] [[package]] name = "linux-raw-sys" @@ -2359,42 +1273,6 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" -[[package]] -name = "lz4" -version = "1.28.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a20b523e860d03443e98350ceaac5e71c6ba89aea7d960769ec3ce37f4de5af4" -dependencies = [ - "lz4-sys", -] - -[[package]] -name = "lz4-sys" -version = "1.11.1+lz4-1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bd8c0d6c6ed0cd30b3652886bb8711dc4bb01d637a68105a3d5158039b418e6" -dependencies = [ - "cc", - "libc", -] - -[[package]] -name = "maplit" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" - -[[package]] -name = "markup5ever" -version = "0.39.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" -dependencies = [ - "log", - "tendril", - "web_atoms", -] - [[package]] name = "matchers" version = "0.2.0" @@ -2410,24 +1288,14 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" -[[package]] -name = "matrixmultiply" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7" -dependencies = [ - "autocfg", - "rawpointer", -] - [[package]] name = "md-5" -version = "0.10.6" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" dependencies = [ "cfg-if", - "digest 0.10.7", + "digest 0.11.3", ] [[package]] @@ -2469,76 +1337,31 @@ dependencies = [ ] [[package]] -name = "mio" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" -dependencies = [ - "libc", - "wasi", - "windows-sys 0.61.2", -] - -[[package]] -name = "multer" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" -dependencies = [ - "bytes", - "encoding_rs", - "futures-util", - "http", - "httparse", - "memchr", - "mime", - "spin", - "version_check", -] - -[[package]] -name = "ndarray" -version = "0.17.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d" -dependencies = [ - "matrixmultiply", - "num-complex", - "num-integer", - "num-traits", - "portable-atomic", - "portable-atomic-util", - "rawpointer", -] - -[[package]] -name = "ndarray-stats" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b6e54a8b65764f71827a90ca1d56965ec0c67f069f996477bd493402a901d1f" -dependencies = [ - "indexmap", - "itertools 0.13.0", - "ndarray", - "noisy_float", - "num-integer", - "num-traits", - "rand 0.8.7", -] - -[[package]] -name = "new_debug_unreachable" -version = "1.0.6" +name = "mio" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] [[package]] -name = "noisy_float" -version = "0.2.1" +name = "multer" +version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c16843be85dd410c6a12251c4eca0dd1d3ee8c5725f746c4d5e0fdcec0a864b2" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" dependencies = [ - "num-traits", + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", ] [[package]] @@ -2551,15 +1374,6 @@ dependencies = [ "minimal-lexical", ] -[[package]] -name = "ntapi" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" -dependencies = [ - "winapi", -] - [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -2579,31 +1393,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "num-bigint-dig" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" -dependencies = [ - "lazy_static", - "libm", - "num-integer", - "num-iter", - "num-traits", - "rand 0.8.7", - "smallvec", - "zeroize", -] - -[[package]] -name = "num-complex" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" -dependencies = [ - "num-traits", -] - [[package]] name = "num-conv" version = "0.2.2" @@ -2619,16 +1408,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "num-iter" -version = "0.1.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" -dependencies = [ - "num-integer", - "num-traits", -] - [[package]] name = "num-traits" version = "0.2.19" @@ -2636,62 +1415,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", - "libm", -] - -[[package]] -name = "num_cpus" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "objc2-core-foundation" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" -dependencies = [ - "bitflags", -] - -[[package]] -name = "objc2-io-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" -dependencies = [ - "libc", - "objc2-core-foundation", -] - -[[package]] -name = "object_store" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "622acbc9100d3c10e2ee15804b0caa40e55c933d5aa53814cd520805b7958a49" -dependencies = [ - "async-trait", - "bytes", - "chrono", - "futures-channel", - "futures-core", - "futures-util", - "http", - "humantime", - "itertools 0.14.0", - "parking_lot", - "percent-encoding", - "thiserror", - "tokio", - "tracing", - "url", - "walkdir", - "wasm-bindgen-futures", - "web-time", ] [[package]] @@ -2804,40 +1527,6 @@ dependencies = [ "tokio-stream", ] -[[package]] -name = "p256" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" -dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", - "sha2 0.10.9", -] - -[[package]] -name = "p384" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" -dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", - "sha2 0.10.9", -] - -[[package]] -name = "papaya" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "997ee03cd38c01469a7046643714f0ad28880bcb9e6679ff0666e24817ca19b7" -dependencies = [ - "equivalent", - "seize", -] - [[package]] name = "parking" version = "2.2.1" @@ -2864,18 +1553,7 @@ dependencies = [ "libc", "redox_syscall", "smallvec", - "windows-link 0.2.1", -] - -[[package]] -name = "password-hash" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" -dependencies = [ - "base64ct", - "rand_core 0.6.4", - "subtle", + "windows-link", ] [[package]] @@ -2894,40 +1572,6 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" -[[package]] -name = "path-clean" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17359afc20d7ab31fdb42bb844c8b3bb1dabd7dcf7e68428492da7f16966fcef" - -[[package]] -name = "pbkdf2" -version = "0.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" -dependencies = [ - "digest 0.10.7", - "hmac", - "password-hash 0.5.0", - "sha2 0.10.9", -] - -[[package]] -name = "pdqselect" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ec91767ecc0a0bbe558ce8c9da33c068066c57ecc8bb8477ef8c1ad3ef77c27" - -[[package]] -name = "pem" -version = "3.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" -dependencies = [ - "base64 0.22.1", - "serde_core", -] - [[package]] name = "pem" version = "4.0.0" @@ -2938,15 +1582,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "pem-rfc7468" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" -dependencies = [ - "base64ct", -] - [[package]] name = "percent-encoding" version = "2.3.2" @@ -2964,61 +1599,6 @@ dependencies = [ "getrandom 0.4.3", ] -[[package]] -name = "phf" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" -dependencies = [ - "phf_macros", - "phf_shared", - "serde", -] - -[[package]] -name = "phf_codegen" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" -dependencies = [ - "phf_generator", - "phf_shared", -] - -[[package]] -name = "phf_generator" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" -dependencies = [ - "fastrand", - "phf_shared", -] - -[[package]] -name = "phf_macros" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro2", - "quote", - "syn 2.0.119", - "unicase", -] - -[[package]] -name = "phf_shared" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" -dependencies = [ - "siphasher", - "unicase", -] - [[package]] name = "pin-project" version = "1.1.13" @@ -3045,38 +1625,11 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - -[[package]] -name = "pkcs1" -version = "0.7.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" -dependencies = [ - "der", - "pkcs8", - "spki", -] - -[[package]] -name = "pkcs8" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" -dependencies = [ - "der", - "spki", -] - [[package]] name = "pkg-config" -version = "0.3.33" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" [[package]] name = "portable-atomic" @@ -3084,15 +1637,6 @@ version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d20d5497ef88037a52ff98267d066e7f11fcc5e99bbfbd58a42336193aacec3" -[[package]] -name = "portable-atomic-util" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" -dependencies = [ - "portable-atomic", -] - [[package]] name = "potential_utf" version = "0.1.5" @@ -3117,30 +1661,6 @@ dependencies = [ "zerocopy", ] -[[package]] -name = "precomputed-hash" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" - -[[package]] -name = "primeorder" -version = "0.13.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" -dependencies = [ - "elliptic-curve", -] - -[[package]] -name = "proc-macro-crate" -version = "3.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" -dependencies = [ - "toml_edit", -] - [[package]] name = "proc-macro2" version = "1.0.107" @@ -3161,7 +1681,7 @@ dependencies = [ "bitflags", "num-traits", "rand 0.9.5", - "rand_chacha 0.9.0", + "rand_chacha", "rand_xorshift", "regex-syntax", "rusty-fork", @@ -3186,7 +1706,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" dependencies = [ "anyhow", - "itertools 0.14.0", + "itertools", "proc-macro2", "quote", "syn 2.0.119", @@ -3207,26 +1727,6 @@ version = "2.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac" -[[package]] -name = "ptr_meta" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0738ccf7ea06b608c10564b31debd4f5bc5e197fc8bfe088f68ae5ce81e7a4f1" -dependencies = [ - "ptr_meta_derive", -] - -[[package]] -name = "ptr_meta_derive" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "publicsuffix" version = "2.3.0" @@ -3243,18 +1743,6 @@ version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" -[[package]] -name = "quick_cache" -version = "0.6.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9c6658afe513a3b484e3abfdaa0d03ef3c0bbf017542c178dd55f94eb3051f9" -dependencies = [ - "ahash 0.8.12", - "equivalent", - "hashbrown 0.16.1", - "parking_lot", -] - [[package]] name = "quinn" version = "0.11.11" @@ -3321,33 +1809,16 @@ dependencies = [ ] [[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - -[[package]] -name = "radium" -version = "0.7.0" +name = "r-efi" +version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" [[package]] -name = "rand" -version = "0.8.7" +name = "r-efi" +version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" @@ -3355,7 +1826,7 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ - "rand_chacha 0.9.0", + "rand_chacha", "rand_core 0.9.5", ] @@ -3370,16 +1841,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.4", -] - [[package]] name = "rand_chacha" version = "0.9.0" @@ -3390,15 +1851,6 @@ dependencies = [ "rand_core 0.9.5", ] -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.17", -] - [[package]] name = "rand_core" version = "0.9.5" @@ -3414,16 +1866,6 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" -[[package]] -name = "rand_distr" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a8615d50dcf34fa31f7ab52692afec947c4dd0ab803cc87cb3b0b4570ff7463" -dependencies = [ - "num-traits", - "rand 0.9.5", -] - [[package]] name = "rand_pcg" version = "0.10.2" @@ -3442,39 +1884,13 @@ dependencies = [ "rand_core 0.9.5", ] -[[package]] -name = "rawpointer" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" - -[[package]] -name = "rayon" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" -dependencies = [ - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", -] - [[package]] name = "rcgen" version = "0.14.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" dependencies = [ - "pem 4.0.0", + "pem", "ring", "rustls-pki-types", "time", @@ -3482,12 +1898,6 @@ dependencies = [ "yasna", ] -[[package]] -name = "reblessive" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbc4a4ea2a66a41a1152c4b3d86e8954dc087bdf33af35446e6e176db4e73c8c" - [[package]] name = "redox_syscall" version = "0.5.18" @@ -3526,15 +1936,6 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" -[[package]] -name = "rend" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71fe3824f5629716b1589be05dacd749f6aa084c87e00e016714a8cdfccc997c" -dependencies = [ - "bytecheck", -] - [[package]] name = "reqwest" version = "0.13.4" @@ -3570,43 +1971,6 @@ dependencies = [ "web-sys", ] -[[package]] -name = "revision" -version = "0.30.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13b48b66c1cd4bf814516ea48f727d4b3697e3fa8841be99a7d9cbb8c9ac1666" -dependencies = [ - "bytes", - "chrono", - "geo", - "regex", - "revision-derive", - "roaring", - "rust_decimal", - "uuid", -] - -[[package]] -name = "revision-derive" -version = "0.30.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d266d798eaaa2921e14188dfe998bb7cc0528ec26e894b4be0e35fe2b19c89d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "rfc6979" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" -dependencies = [ - "hmac", - "subtle", -] - [[package]] name = "ring" version = "0.17.14" @@ -3617,156 +1981,10 @@ dependencies = [ "cfg-if", "getrandom 0.2.17", "libc", - "untrusted 0.9.0", + "untrusted", "windows-sys 0.52.0", ] -[[package]] -name = "rkyv" -version = "0.7.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2297bf9c81a3f0dc96bc9521370b88f054168c29826a75e89c55ff196e7ed6a1" -dependencies = [ - "bitvec", - "bytecheck", - "bytes", - "hashbrown 0.12.3", - "ptr_meta", - "rend", - "rkyv_derive", - "seahash", - "tinyvec", - "uuid", -] - -[[package]] -name = "rkyv_derive" -version = "0.7.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84d7b42d4b8d06048d3ac8db0eb31bcb942cbeb709f0b5f2b2ebde398d3038f5" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "rmp" -version = "0.8.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c" -dependencies = [ - "num-traits", -] - -[[package]] -name = "rmp-serde" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155" -dependencies = [ - "rmp", - "serde", -] - -[[package]] -name = "roaring" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dedc5658c6ecb3bdb5ef5f3295bb9253f42dcf3fd1402c03f6b1f7659c3c4a9" -dependencies = [ - "bytemuck", - "byteorder", - "serde", -] - -[[package]] -name = "robust" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e27ee8bb91ca0adcf0ecb116293afa12d393f9c2b9b9cd54d33e8078fe19839" - -[[package]] -name = "rsa" -version = "0.9.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" -dependencies = [ - "const-oid 0.9.6", - "digest 0.10.7", - "num-bigint-dig", - "num-integer", - "num-traits", - "pkcs1", - "pkcs8", - "rand_core 0.6.4", - "signature", - "spki", - "subtle", - "zeroize", -] - -[[package]] -name = "rstar" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a45c0e8804d37e4d97e55c6f258bc9ad9c5ee7b07437009dd152d764949a27c" -dependencies = [ - "heapless 0.6.1", - "num-traits", - "pdqselect", - "serde", - "smallvec", -] - -[[package]] -name = "rstar" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b40f1bfe5acdab44bc63e6699c28b74f75ec43afb59f3eda01e145aff86a25fa" -dependencies = [ - "heapless 0.7.17", - "num-traits", - "serde", - "smallvec", -] - -[[package]] -name = "rstar" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f39465655a1e3d8ae79c6d9e007f4953bfc5d55297602df9dc38f9ae9f1359a" -dependencies = [ - "heapless 0.7.17", - "num-traits", - "serde", - "smallvec", -] - -[[package]] -name = "rstar" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73111312eb7a2287d229f06c00ff35b51ddee180f017ab6dec1f69d62ac098d6" -dependencies = [ - "heapless 0.7.17", - "num-traits", - "serde", - "smallvec", -] - -[[package]] -name = "rstar" -version = "0.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "421400d13ccfd26dfa5858199c30a5d76f9c54e0dba7575273025b43c5175dbb" -dependencies = [ - "heapless 0.8.0", - "num-traits", - "serde", - "smallvec", -] - [[package]] name = "rust-embed" version = "8.12.0" @@ -3802,48 +2020,12 @@ dependencies = [ "walkdir", ] -[[package]] -name = "rust-stemmers" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e46a2036019fdb888131db7a4c847a1063a7493f971ed94ea82c67eada63ca54" -dependencies = [ - "serde", - "serde_derive", -] - -[[package]] -name = "rust_decimal" -version = "1.42.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be2a24f50780bc85f09cc6ac299bdf1424302742d77221106859c9d8b102126a" -dependencies = [ - "arrayvec", - "borsh", - "bytes", - "num-traits", - "rand 0.8.7", - "rkyv", - "serde", - "serde_json", - "wasm-bindgen", -] - [[package]] name = "rustc-hash" version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" -[[package]] -name = "rustc_version" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" -dependencies = [ - "semver", -] - [[package]] name = "rusticata-macros" version = "4.1.0" @@ -3906,111 +2088,50 @@ version = "0.103.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" dependencies = [ - "ring", - "rustls-pki-types", - "untrusted 0.9.0", -] - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "rusty-fork" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" -dependencies = [ - "fnv", - "quick-error", - "tempfile", - "wait-timeout", -] - -[[package]] -name = "ryu" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" - -[[package]] -name = "salsa20" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" -dependencies = [ - "cipher", -] - -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "scrypt" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" -dependencies = [ - "password-hash 0.5.0", - "pbkdf2", - "salsa20", - "sha2 0.10.9", + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] -name = "seahash" -version = "4.1.0" +name = "rustversion" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" [[package]] -name = "sec1" -version = "0.7.3" +name = "rusty-fork" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" dependencies = [ - "base16ct", - "der", - "generic-array 0.14.7", - "pkcs8", - "subtle", - "zeroize", + "fnv", + "quick-error", + "tempfile", + "wait-timeout", ] [[package]] -name = "seize" -version = "0.5.1" +name = "ryu" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b55fb86dfd3a2f5f76ea78310a88f96c4ea21a3031f8d212443d56123fd0521" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" [[package]] -name = "semver" -version = "1.0.28" +name = "same-file" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" dependencies = [ - "serde", - "serde_core", + "winapi-util", ] +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "serde" version = "1.0.229" @@ -4136,12 +2257,6 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" -[[package]] -name = "sif-itree" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7f45b8998ced5134fb1d75732c77842a3e888f19c1ff98481822e8fbfbf930b" - [[package]] name = "signal-hook-registry" version = "1.4.8" @@ -4152,46 +2267,12 @@ dependencies = [ "libc", ] -[[package]] -name = "signature" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" -dependencies = [ - "digest 0.10.7", - "rand_core 0.6.4", -] - [[package]] name = "simd-adler32" version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" -[[package]] -name = "simdutf8" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" - -[[package]] -name = "simple_asn1" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" -dependencies = [ - "num-bigint", - "num-traits", - "thiserror", - "time", -] - -[[package]] -name = "siphasher" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" - [[package]] name = "slab" version = "0.4.12" @@ -4217,18 +2298,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "spade" -version = "2.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9699399fd9349b00b184f5635b074f9ec93afffef30c853f8c875b32c0f8c7fa" -dependencies = [ - "hashbrown 0.16.1", - "num-traits", - "robust", - "smallvec", -] - [[package]] name = "spin" version = "0.9.9" @@ -4239,331 +2308,205 @@ dependencies = [ ] [[package]] -name = "spki" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" -dependencies = [ - "base64ct", - "der", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "storekey" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd9a94571bde7369ecaac47cec2e6844642d99166bd452fbd8def74b5b917b2f" -dependencies = [ - "bytes", - "storekey-derive", - "uuid", -] - -[[package]] -name = "storekey-derive" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6079d53242246522ec982de613c5c952cc7b1380ef2f8622fcdab9bfe73c0098" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "string_cache" +name = "sqlx" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901" -dependencies = [ - "new_debug_unreachable", - "parking_lot", - "phf_shared", - "precomputed-hash", -] - -[[package]] -name = "string_cache_codegen" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69" +checksum = "378620ccc25c62c89d8be1c819e76a88d59bdcc3304733330788948e619bfd71" dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro2", - "quote", + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", ] [[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - -[[package]] -name = "surrealdb" -version = "3.2.3" +name = "sqlx-core" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d1d636f9a9104f4446943111e0703e6d6668bfaba6c4415a31d0450dc46630b" +checksum = "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb" dependencies = [ - "anyhow", - "async-channel", - "boxcar", - "chrono", - "futures", - "getrandom 0.3.4", + "base64 0.22.1", + "bytes", + "cfg-if", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.16.1", + "hashlink", "indexmap", - "js-sys", - "path-clean", - "ring", - "rustls-pki-types", - "semver", + "log", + "memchr", + "percent-encoding", + "rustls", "serde", "serde_json", - "surrealdb-core", - "surrealdb-types", - "surrealdb-types-derive", + "sha2 0.10.9", + "smallvec", + "thiserror", "tokio", - "tokio-tungstenite 0.28.0", - "tokio-tungstenite-wasm", - "tokio-util", + "tokio-stream", "tracing", "url", "uuid", - "wasm-bindgen", - "wasm-bindgen-futures", - "wasmtimer", - "web-sys", + "webpki-roots", ] [[package]] -name = "surrealdb-collections" -version = "3.2.3" +name = "sqlx-macros" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6222572dc7354295ba8017603d0a5a3e493935a8ec2d7314b9c09152184cd2f" +checksum = "bd2b84f2bc39a5705ef27ec785a11c934a41bbd4a24941e257927cddc26b60bf" dependencies = [ - "revision", - "storekey", + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 2.0.119", ] [[package]] -name = "surrealdb-core" -version = "3.2.3" +name = "sqlx-macros-core" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6add99c7f91bda7acb5d3b9a1b7c0db81a1adebdaedd4b9145f9ccf65fa2a25" +checksum = "fb8d96de5fdc85a5c4ec813432b523ec637e80ba98f046555f75f7908ddac7c3" dependencies = [ - "addr", - "affinitypool", - "ahash 0.8.12", - "ammonia", - "anyhow", - "argon2 0.5.3", - "async-channel", - "async-stream", - "base64 0.22.1", - "bcrypt", - "blake3", - "bytes", - "chrono", - "ciborium", - "dashmap", - "deunicode", - "diskann", - "diskann-utils", - "diskann-vector", - "dmp", - "ext-sort", - "fastnum", - "fst", - "futures", - "fuzzy-matcher", - "geo", - "geo-types", - "getrandom 0.3.4", - "half", - "headers", + "cfg-if", + "dotenvy", + "either", + "heck", "hex", - "http", - "humantime", - "ipnet", - "jsonwebtoken", - "lexicmp", - "md-5", - "memchr", - "mime", - "ndarray", - "ndarray-stats", - "num-traits", - "num_cpus", - "object_store", - "parking_lot", - "path-clean", - "pbkdf2", - "phf", - "pin-project-lite", - "quick_cache", - "rand 0.9.5", - "rand_core 0.6.4", - "rayon", - "reblessive", - "regex", - "revision", - "ring", - "roaring", - "rust-stemmers", - "rust_decimal", - "scrypt", - "semver", + "proc-macro2", + "quote", "serde", "serde_json", - "sha1 0.10.7", "sha2 0.10.9", - "storekey", - "strsim", - "subtle", - "surrealdb-collections", - "surrealdb-protocol", - "surrealdb-strand", - "surrealdb-types", - "surrealmx", - "sysinfo", - "tempfile", + "sqlx-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn 2.0.119", "thiserror", "tokio", - "tokio-util", - "tracing", - "ulid 1.2.1", - "unicase", "url", - "uuid", - "vart", - "wasm-bindgen-futures", - "wasmtimer", - "web-time", ] [[package]] -name = "surrealdb-protocol" -version = "0.10.2" +name = "sqlx-mysql" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f4e06f586c9179a02349b88b0c18e3a0850c55431aa513e0cd66529c00da1af" +checksum = "90b8020fe17c5f2c245bfa2505d7ef59c5604839527c740266ad2214acebea27" dependencies = [ - "anyhow", - "async-trait", + "bitflags", + "byteorder", "bytes", - "chrono", - "flatbuffers", - "futures", - "geo", - "prost", - "prost-types", - "rust_decimal", - "semver", + "crc", + "digest 0.11.3", + "dotenvy", + "either", + "futures-core", + "futures-util", + "generic-array", + "log", + "percent-encoding", "serde", - "serde_json", - "tonic", - "tonic-prost", + "sha1 0.11.0", + "sha2 0.11.0", + "sqlx-core", + "thiserror", + "tracing", "uuid", ] [[package]] -name = "surrealdb-strand" -version = "3.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ebb973d3547dbd2384f841d2fefd8a65c57a6cba02759e82c65de248da28b65" -dependencies = [ - "revision", - "serde", - "storekey", -] - -[[package]] -name = "surrealdb-types" -version = "3.2.3" +name = "sqlx-postgres" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eac180b3201dbd6f809d3f07fa20ff953a03e06f92e051117e60f326a46160d1" +checksum = "87a2bdd6e83f6b3ea525ca9fee568030508b58355a43d0b2c1674d5f79dcd65e" dependencies = [ - "anyhow", - "async-channel", - "bytes", - "castaway", - "chrono", - "flatbuffers", - "geo", + "atoi", + "base64 0.22.1", + "bitflags", + "byteorder", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", "hex", - "http", - "papaya", - "rand 0.9.5", - "regex", - "rust_decimal", - "semver", + "hkdf", + "hmac", + "itoa", + "log", + "md-5", + "memchr", + "rand 0.10.2", "serde", "serde_json", - "surrealdb-protocol", - "surrealdb-types-derive", + "sha2 0.11.0", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", "tracing", - "ulid 1.2.1", - "url", "uuid", + "whoami", ] [[package]] -name = "surrealdb-types-derive" -version = "3.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7f204a3bd68ba7e1822b86091df5b184f6a674acb4d537f5480f3b7192b08b5" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "surrealmx" -version = "0.22.0" +name = "sqlx-sqlite" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e8a87f050a4860832ccf4a53e43ea264e98d27618983602b5c575e6df296054" +checksum = "488e99c397a62007e4229aec669a179816339afc6d2620ca6fa420dbee2e982c" dependencies = [ - "arc-swap", - "bincode", - "bytes", - "crossbeam-deque", - "crossbeam-queue", - "crossbeam-skiplist", - "lz4", - "papaya", - "parking_lot", + "atoi", + "flume", + "form_urlencoded", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", "serde", - "smallvec", + "sqlx-core", "thiserror", "tracing", - "web-time", + "url", + "uuid", ] [[package]] -name = "syn" -version = "1.0.109" +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stringprep" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", + "unicode-bidi", + "unicode-normalization", + "unicode-properties", ] +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -4606,26 +2549,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "sysinfo" -version = "0.37.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16607d5caffd1c07ce073528f9ed972d88db15dd44023fa57142963be3feb11f" -dependencies = [ - "libc", - "memchr", - "ntapi", - "objc2-core-foundation", - "objc2-io-kit", - "windows", -] - -[[package]] -name = "tap" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" - [[package]] name = "tempfile" version = "3.27.0" @@ -4639,15 +2562,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "tendril" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08" -dependencies = [ - "new_debug_unreachable", -] - [[package]] name = "thiserror" version = "2.0.20" @@ -4772,18 +2686,6 @@ dependencies = [ "tokio-util", ] -[[package]] -name = "tokio-tungstenite" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857" -dependencies = [ - "futures-util", - "log", - "tokio", - "tungstenite 0.28.0", -] - [[package]] name = "tokio-tungstenite" version = "0.29.0" @@ -4808,25 +2710,6 @@ dependencies = [ "tungstenite 0.30.0", ] -[[package]] -name = "tokio-tungstenite-wasm" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccecee909c02b8863f9bda87253127eb4da0e7e1342330b2583fbc4d1795c2f8" -dependencies = [ - "bytes", - "futures-channel", - "futures-util", - "http", - "httparse", - "js-sys", - "thiserror", - "tokio", - "tokio-tungstenite 0.28.0", - "wasm-bindgen", - "web-sys", -] - [[package]] name = "tokio-util" version = "0.7.19" @@ -4835,43 +2718,12 @@ checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" dependencies = [ "bytes", "futures-core", - "futures-io", "futures-sink", "libc", "pin-project-lite", "tokio", ] -[[package]] -name = "toml_datetime" -version = "1.1.1+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" -dependencies = [ - "serde_core", -] - -[[package]] -name = "toml_edit" -version = "0.25.13+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b" -dependencies = [ - "indexmap", - "toml_datetime", - "toml_parser", - "winnow", -] - -[[package]] -name = "toml_parser" -version = "1.1.2+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" -dependencies = [ - "winnow", -] - [[package]] name = "tonic" version = "0.14.6" @@ -4879,10 +2731,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" dependencies = [ "async-trait", - "axum", "base64 0.22.1", "bytes", - "h2", "http", "http-body", "http-body-util", @@ -4891,7 +2741,6 @@ dependencies = [ "hyper-util", "percent-encoding", "pin-project", - "socket2", "sync_wrapper", "tokio", "tokio-stream", @@ -5083,41 +2932,12 @@ dependencies = [ "tracing-serde", ] -[[package]] -name = "trice" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3aaab10ae9fac0b10f392752bf56f0fd20845f39037fec931e8537b105b515a" -dependencies = [ - "js-sys", - "wasm-bindgen", - "web-sys", -] - [[package]] name = "try-lock" version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" -[[package]] -name = "tungstenite" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442" -dependencies = [ - "bytes", - "data-encoding", - "http", - "httparse", - "log", - "rand 0.9.5", - "sha1 0.10.7", - "thiserror", - "url", - "utf-8", -] - [[package]] name = "tungstenite" version = "0.29.0" @@ -5156,27 +2976,6 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" -[[package]] -name = "ulid" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "470dbf6591da1b39d43c14523b2b469c86879a53e8b758c8e090a470fe7b1fbe" -dependencies = [ - "rand 0.9.5", - "serde", - "web-time", -] - -[[package]] -name = "ulid" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "947dde63b6d514cc5e044edad4e0ca7261afd1099d16c83d942cb2b2f348689c" -dependencies = [ - "rand 0.10.2", - "web-time", -] - [[package]] name = "unarray" version = "0.1.4" @@ -5189,6 +2988,12 @@ version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -5196,22 +3001,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] -name = "untrusted" -version = "0.7.1" +name = "unicode-normalization" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] [[package]] -name = "untrusted" -version = "0.9.0" +name = "unicode-properties" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" [[package]] -name = "unty" -version = "0.0.4" +name = "untrusted" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" @@ -5225,18 +3033,6 @@ dependencies = [ "serde", ] -[[package]] -name = "urlencoding" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" - -[[package]] -name = "utf-8" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" - [[package]] name = "utf8_iter" version = "1.0.4" @@ -5306,7 +3102,6 @@ checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" dependencies = [ "getrandom 0.4.3", "js-sys", - "serde_core", "wasm-bindgen", ] @@ -5317,10 +3112,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" [[package]] -name = "vart" -version = "0.9.3" +name = "vcpkg" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1982d899e57d646498709735f16e9224cf1e8680676ad687f930cf8b5b555ae" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" [[package]] name = "version_check" @@ -5328,12 +3123,6 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" -[[package]] -name = "virtue" -version = "0.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "051eb1abcf10076295e815102942cc58f9d5e3b4560e46e53c21e8ff6f3af7b1" - [[package]] name = "wait-timeout" version = "0.2.1" @@ -5386,7 +3175,6 @@ dependencies = [ "cfg-if", "once_cell", "rustversion", - "serde", "wasm-bindgen-macro", "wasm-bindgen-shared", ] @@ -5433,19 +3221,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "wasmtimer" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c598d6b99ea013e35844697fc4670d08339d5cda15588f193c6beedd12f644b" -dependencies = [ - "futures", - "js-sys", - "parking_lot", - "pin-utils", - "wasm-bindgen", -] - [[package]] name = "web-sys" version = "0.3.103" @@ -5467,32 +3242,19 @@ dependencies = [ ] [[package]] -name = "web_atoms" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "075474b12bcb3d2e3d4546580e9de478eeeead668a1761e2a8860c836b7ef297" -dependencies = [ - "phf", - "phf_codegen", - "string_cache", - "string_cache_codegen", -] - -[[package]] -name = "winapi" -version = "0.3.9" +name = "webpki-roots" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", + "rustls-pki-types", ] [[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" +name = "whoami" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" [[package]] name = "winapi-util" @@ -5503,47 +3265,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows" -version = "0.61.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" -dependencies = [ - "windows-collections", - "windows-core 0.61.2", - "windows-future", - "windows-link 0.1.3", - "windows-numerics", -] - -[[package]] -name = "windows-collections" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" -dependencies = [ - "windows-core 0.61.2", -] - -[[package]] -name = "windows-core" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link 0.1.3", - "windows-result 0.3.4", - "windows-strings 0.4.2", -] - [[package]] name = "windows-core" version = "0.62.2" @@ -5552,20 +3273,9 @@ checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ "windows-implement", "windows-interface", - "windows-link 0.2.1", - "windows-result 0.4.1", - "windows-strings 0.5.1", -] - -[[package]] -name = "windows-future" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" -dependencies = [ - "windows-core 0.61.2", - "windows-link 0.1.3", - "windows-threading", + "windows-link", + "windows-result", + "windows-strings", ] [[package]] @@ -5590,53 +3300,19 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "windows-link" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" - [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-numerics" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" -dependencies = [ - "windows-core 0.61.2", - "windows-link 0.1.3", -] - -[[package]] -name = "windows-result" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" -dependencies = [ - "windows-link 0.1.3", -] - [[package]] name = "windows-result" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" dependencies = [ - "windows-link 0.2.1", -] - -[[package]] -name = "windows-strings" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" -dependencies = [ - "windows-link 0.1.3", + "windows-link", ] [[package]] @@ -5645,7 +3321,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" dependencies = [ - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -5663,7 +3339,7 @@ version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -5682,15 +3358,6 @@ dependencies = [ "windows_x86_64_msvc", ] -[[package]] -name = "windows-threading" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" -dependencies = [ - "windows-link 0.1.3", -] - [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -5739,15 +3406,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "winnow" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" -dependencies = [ - "memchr", -] - [[package]] name = "wit-bindgen" version = "0.57.1" @@ -5760,15 +3418,6 @@ version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" -[[package]] -name = "wyz" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" -dependencies = [ - "tap", -] - [[package]] name = "x509-parser" version = "0.18.1" @@ -5866,20 +3515,6 @@ name = "zeroize" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" -dependencies = [ - "zeroize_derive", -] - -[[package]] -name = "zeroize_derive" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] [[package]] name = "zerotrie" diff --git a/Cargo.toml b/Cargo.toml index 7557966..aae823d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,14 +19,12 @@ tokio-stream = { version = "0.1", features = ["sync"] } axum = { version = "0.8.9", features = ["ws", "multipart"] } axum-extra = { version = "0.12", features = ["cookie"] } tower-http = { version = "0.7", features = ["trace", "cors", "request-id", "catch-panic"] } -surrealdb = { version = "3.2", default-features = false, features = ["protocol-ws", "kv-mem"] } serde = { version = "1", features = ["derive"] } serde_json = "1" chrono = "0.4" argon2 = "0.6" getrandom = "0.4" hex = "0.4" -ulid = "3" thiserror = "2" anyhow = "1" tracing = "0.1" @@ -49,10 +47,11 @@ tower = { version = "0.5", features = ["util"] } opentelemetry = "0.32.0" tracing-opentelemetry = "0.33.0" opentelemetry-semantic-conventions = "0.32.1" -uuid = { version = "1.26.1", features = ["v4"] } +uuid = { version = "1.26.1", features = ["v4", "v7"] } opentelemetry_sdk = { version = "0.32.1", features = ["rt-tokio"] } opentelemetry-otlp = { version = "0.32.0", default-features = false, features = ["trace", "metrics", "logs", "grpc-tonic", "http-proto", "reqwest-blocking-client", "internal-logs"] } opentelemetry-appender-tracing = "0.32.0" +sqlx = { version = "0.9.0", default-features = false, features = ["postgres", "runtime-tokio", "tls-rustls-ring", "migrate", "macros", "uuid", "json"] } [dev-dependencies] # test-util enables tokio::time::pause/advance for the rate limiter tests. diff --git a/Containerfile b/Containerfile index 11dc10c..b65d3c9 100644 --- a/Containerfile +++ b/Containerfile @@ -9,6 +9,10 @@ RUN apt-get update && \ WORKDIR /app COPY Cargo.toml Cargo.lock ./ COPY src ./src +# sqlx's compile-time macros verify every query against this committed cache, +# so the build must never reach for a live database. +ENV SQLX_OFFLINE=true +COPY .sqlx ./.sqlx # Cache mounts keep the registry and incremental build artifacts between # 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 USER hezarfen -# HOST must be 0.0.0.0 so the port mapping can reach the listener. DB_URL -# points at the SurrealDB server (the compose service); /data holds uploads. +# HOST must be 0.0.0.0 so the port mapping can reach the listener. DATABASE_URL +# points at the compose Postgres (the control database); /data holds uploads. ENV HOST=0.0.0.0 \ PORT=8080 \ - DB_URL=ws://surrealdb:8000 + DATABASE_URL=postgres://hezarfen:hezarfen@postgres:5432/hezarfen_control EXPOSE 8080 diff --git a/compose.yaml b/compose.yaml index 76b678b..386aeaa 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,25 +1,18 @@ services: - surrealdb: - image: docker.io/surrealdb/surrealdb:v3 - container_name: hezarfen-surrealdb - # Distroless image; its default `nonroot` user can't write a fresh named - # volume (created root-owned). Run as root — only this service touches - # surreal-data, the backend never mounts it. - user: "0" - command: - [ - "start", - "--user", "root", - "--pass", "root", - "surrealkv:/data/hezarfen.db", - ] + postgres: + image: docker.io/library/postgres:18-alpine + container_name: hezarfen-postgres + environment: + POSTGRES_USER: hezarfen + POSTGRES_PASSWORD: hezarfen + POSTGRES_DB: hezarfen_control ports: - - "127.0.0.1:8000:8000" + - "127.0.0.1:5432:5432" volumes: - - surreal-data:/data + - pgdata:/data restart: unless-stopped healthcheck: - test: ["CMD", "/surreal", "isready"] + test: ["CMD-SHELL", "pg_isready -U hezarfen -d hezarfen_control"] interval: 10s timeout: 5s retries: 5 @@ -38,13 +31,9 @@ services: environment: HOST: 0.0.0.0 PORT: "8080" - DB_URL: ws://surrealdb:8000 - DB_USER: root - DB_PASS: root - DB_NAMESPACE: hezarfen # The control database: the school registry + the builder accounts. Each - # school lives in a database of its own, named by its slug. - DB_DATABASE: control + # school lives in a Postgres database of its own, named from its slug. + DATABASE_URL: postgres://hezarfen:hezarfen@postgres:5432/hezarfen_control FILES_PATH: /data/files RUST_LOG: info,hezarfen_backend=debug # First-boot builder seed: the operator who creates and suspends schools, @@ -82,7 +71,7 @@ services: volumes: - hezarfen-data:/data depends_on: - surrealdb: + postgres: condition: service_healthy restart: unless-stopped healthcheck: @@ -133,5 +122,5 @@ services: volumes: hezarfen-data: - surreal-data: + pgdata: openobserve-data: diff --git a/migrations/control/20260912000001_control.sql b/migrations/control/20260912000001_control.sql new file mode 100644 index 0000000..79fb5a3 --- /dev/null +++ b/migrations/control/20260912000001_control.sql @@ -0,0 +1,60 @@ +-- Control-database schema (Postgres). +-- +-- DISJOINTNESS INVARIANT: the tables here (school, builder, builder_session, +-- rate_limit) and every table in migrations/school/*.sql together form ONE +-- union schema, applied to a single prepare database by +-- scripts/prepare_db.sh for sqlx's compile-time query macros. The two sets +-- must never collide on a table name; the prepare script fails loudly if they +-- do. +-- +-- Translated from src/migration_sql.rs CONTROL_MIGRATION (SurrealDB), per the +-- plan's schema translation rules. Entity ids are app-minted UUID v7 (no DB +-- default); timestamps stay BIGINT unix-ms. All FKs are ON DELETE NO ACTION — +-- cascades stay explicit application transactions. +-- +-- Renames (reserved words, never quoted): table `school` keeps its name (its +-- Surreal record id WAS the slug, so slug is the PRIMARY KEY, constraint +-- carrying the old index name school_slug). +-- +-- `rate_limit` exists ONLY here, not in the school schema: rate limiting is +-- billed against the control handle before any cookie names a school (see the +-- CONTROL_MIGRATION doc), and the school-side `rate_limit` DEFINE in the old +-- Surreal migration had no school-side reader. Its id is the derived +-- `tier:client:window` key, so the PK is TEXT. + +CREATE TABLE school ( + slug TEXT NOT NULL, + name TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('active', 'suspended')), + created_at BIGINT NOT NULL, + -- Which product modules this school has bought; names bound from + -- Module::ALL at write time, never spelled here. + modules TEXT[] NOT NULL DEFAULT '{}', + CONSTRAINT school_slug PRIMARY KEY (slug) +); + +CREATE TABLE builder ( + id uuid PRIMARY KEY, + username TEXT NOT NULL, + password_hash TEXT NOT NULL, + CONSTRAINT builder_username UNIQUE (username) +); + +CREATE TABLE builder_session ( + id uuid PRIMARY KEY, + builder uuid NOT NULL REFERENCES builder(id) ON DELETE NO ACTION, + token TEXT NOT NULL, + created_at BIGINT NOT NULL, + expires_at BIGINT NOT NULL, + CONSTRAINT builder_session_token UNIQUE (token) +); + +CREATE INDEX builder_session_expires ON builder_session (expires_at); + +-- One row per tier+client+window; the durable fold target of the in-memory +-- bucket (see src/rate_limit.rs). +CREATE TABLE rate_limit ( + id TEXT PRIMARY KEY, + hits BIGINT NOT NULL DEFAULT 0, + window_start BIGINT NOT NULL +); diff --git a/migrations/school/20260912000001_identity.sql b/migrations/school/20260912000001_identity.sql new file mode 100644 index 0000000..2dffc3b --- /dev/null +++ b/migrations/school/20260912000001_identity.sql @@ -0,0 +1,275 @@ +-- School-database schema, part 1: identity, sessions, notes, messages, +-- parent links, work, pomodoro, badges, boards, chatbot, settings, refcounts +-- (Postgres). +-- +-- DISJOINTNESS INVARIANT: the tables in migrations/school/*.sql and the ones +-- in migrations/control/*.sql together form ONE union schema, applied to a +-- single prepare database by scripts/prepare_db.sh for sqlx's compile-time +-- query macros. The two sets must never collide on a table name. +-- +-- Translated from src/migration_sql.rs MIGRATION (SurrealDB), per the plan's +-- schema translation rules. Binding renames (reserved words, never quoted): +-- table `user` -> app_user +-- table `session` -> user_session +-- every column named `user` -> `app_user` (PostgreSQL rejects the bare +-- word as a column name; the plan's fallback prefixes the domain noun) +-- `session` as a COLUMN name (session_attendance.session) is legal in +-- PostgreSQL (non-reserved) and stays. Entity ids are app-minted UUID v7 (no +-- DB default); timestamps stay BIGINT unix-ms; counter columns +-- (absent-reads-as-zero in Surreal) are BIGINT NOT NULL DEFAULT 0 and stay +-- out of the Rust structs. All FKs ON DELETE NO ACTION. +-- +-- Deliberately NOT translated from the Surreal source: `rate_limit` (control +-- only — see migrations/control), `migration_mark` + every `REMOVE ...` +-- retirement line, PRE_REPAIR, BACKFILL, migration_mark machinery (all dead, +-- preproduction). +-- +-- CHECK constraints carry exactly the `#[surreal(untagged, +-- rename_all = "lowercase")]` enums (role, folder, chatbot role/status, +-- ledger kinds, audience tags, school status). Validated-String newtypes +-- (course kind, exam kind/mode, homework status, attendance statuses, pool +-- status, board_stroke kind, bank visibility) keep NO CHECK — the repo +-- convention is that those enums live in Rust newtypes, and attendance +-- statuses / exam kinds are school-configurable at runtime, which a DDL +-- CHECK could not survive. + +CREATE TABLE app_user ( + id uuid PRIMARY KEY, + username TEXT NOT NULL, + password_hash TEXT NOT NULL, + role TEXT NOT NULL DEFAULT 'student' + CHECK (role IN ('ai', 'parent', 'student', 'teacher', 'manager', 'admin')), + name TEXT NULL, + surname TEXT NULL, + email TEXT NULL, + phone TEXT NULL, + birth_date TEXT NULL, + theme TEXT NULL CHECK (theme IN ('light', 'dark')), + language TEXT NULL CHECK (language IN ('tr', 'en')), + palette_color TEXT NULL, + display_name TEXT NULL, + bio TEXT NULL, + avatar_file TEXT NULL, + avatar_content_type TEXT NULL, + avatar_size BIGINT NULL, + -- Lifetime/claim counters: absent-reads-as-zero in Surreal, DEFAULT 0 + -- here, and (as today) carried by no Rust struct. + chatbot_thread_count BIGINT NOT NULL DEFAULT 0, + board_count BIGINT NOT NULL DEFAULT 0, + homework_submitted_total BIGINT NOT NULL DEFAULT 0, + homework_on_time_total BIGINT NOT NULL DEFAULT 0, + exam_sat_total BIGINT NOT NULL DEFAULT 0, + pomodoro_finished_total BIGINT NOT NULL DEFAULT 0, + pomodoro_focus_ms_total BIGINT NOT NULL DEFAULT 0, + marks_given_total BIGINT NOT NULL DEFAULT 0, + lessons_held_total BIGINT NOT NULL DEFAULT 0, + pool_approved_total BIGINT NOT NULL DEFAULT 0, + pool_published_total BIGINT NOT NULL DEFAULT 0, + lessons_attended_total BIGINT NOT NULL DEFAULT 0, + high_mark_total BIGINT NOT NULL DEFAULT 0, + study_streak_longest BIGINT NOT NULL DEFAULT 0, + study_streak_current BIGINT NOT NULL DEFAULT 0, + -- Day markers, not counts: absent means "no day yet", which NULL keeps + -- (DEFAULT 0 would mean the epoch day). + study_streak_last_day BIGINT NULL, + pomodoro_counted_today BIGINT NOT NULL DEFAULT 0, + pomodoro_counted_day BIGINT NULL, + CONSTRAINT app_user_username UNIQUE (username) +); + +CREATE TABLE user_session ( + id uuid PRIMARY KEY, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + token TEXT NOT NULL, + expires_at BIGINT NOT NULL, + CONSTRAINT session_token UNIQUE (token) +); + +CREATE INDEX session_expires ON user_session (expires_at); + +CREATE TABLE note ( + id uuid PRIMARY KEY, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + title TEXT NOT NULL, + content TEXT NOT NULL, + file_count BIGINT NOT NULL DEFAULT 0 +); + +CREATE INDEX note_user ON note (app_user); + +CREATE TABLE note_file ( + id uuid PRIMARY KEY, + note uuid NOT NULL REFERENCES note(id) ON DELETE NO ACTION, + name TEXT NOT NULL, + content_type TEXT NOT NULL, + size BIGINT NOT NULL +); + +CREATE INDEX note_file_note ON note_file (note); + +CREATE TABLE message ( + id uuid PRIMARY KEY, + sender uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + recipient uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + subject TEXT NOT NULL, + body TEXT NOT NULL, + label TEXT NULL, + sent_at BIGINT NOT NULL, + read BOOLEAN NOT NULL DEFAULT false, + sender_folder TEXT NOT NULL DEFAULT 'sent' + CHECK (sender_folder IN ('inbox', 'sent', 'archive', 'trash', 'deleted')), + recipient_folder TEXT NOT NULL DEFAULT 'inbox' + CHECK (recipient_folder IN ('inbox', 'sent', 'archive', 'trash', 'deleted')), + -- Where each side's copy sat before it was filed into archive/trash; + -- NULL while the copy is in its home folder. + sender_origin TEXT NULL, + recipient_origin TEXT NULL +); + +CREATE INDEX message_sender ON message (sender); +CREATE INDEX message_recipient ON message (recipient); + +CREATE TABLE parent_link ( + parent uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + linked_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + CONSTRAINT parent_link_parent_student PRIMARY KEY (parent, student) +); + +CREATE INDEX parent_link_parent ON parent_link (parent); +CREATE INDEX parent_link_student ON parent_link (student); + +CREATE TABLE work_entry ( + id uuid PRIMARY KEY, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + check_in BIGINT NOT NULL, + check_out BIGINT NULL +); + +CREATE INDEX work_entry_user ON work_entry (app_user); +-- At most one open stint per user: the deterministic `open_{user}` key of +-- `WorkEntryId::open_for`, now DB-enforced (closed entries keep minted ids). +CREATE UNIQUE INDEX work_entry_open ON work_entry (app_user) WHERE check_out IS NULL; + +CREATE TABLE pomodoro_session ( + id uuid PRIMARY KEY, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + started_at BIGINT NOT NULL, + finished_at BIGINT NULL, + -- The verdict `finish` reached for this stint, stamped at close; NULL on + -- a running stint, and on a stint closed before the rule existed. + counted BOOLEAN NULL, + -- The student's own name for what the stint is for ('math', 'TYT + -- denemesi') — free text given at start, not a subject link. + label TEXT NULL +); + +CREATE INDEX pomodoro_session_user ON pomodoro_session (app_user); +-- One open stint per user: the deterministic open-stint row of +-- `PomodoroSession::open_for`, now DB-enforced. +CREATE UNIQUE INDEX pomodoro_session_open_stint + ON pomodoro_session (app_user) WHERE finished_at IS NULL; + +-- One row per badge a user has earned; the deterministic {user}_{badge} +-- pair. Awards are permanent — nothing deletes a row here. +CREATE TABLE badge_award ( + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + badge TEXT NOT NULL, + earned_at BIGINT NULL, + CONSTRAINT badge_award_user_badge PRIMARY KEY (app_user, badge) +); + +CREATE INDEX badge_award_user ON badge_award (app_user); + +CREATE TABLE board ( + id uuid PRIMARY KEY, + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + title TEXT NOT NULL, + participants uuid[] NOT NULL DEFAULT '{}', + locked BOOLEAN NOT NULL DEFAULT false, + locked_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, + locked_at BIGINT NULL, + epoch BIGINT NOT NULL DEFAULT 0, + epoch_stroke_count BIGINT NOT NULL DEFAULT 0, + total_stroke_count BIGINT NOT NULL DEFAULT 0, + closed_at BIGINT NULL, + created_at BIGINT NOT NULL +); + +CREATE INDEX board_creator ON board (creator); +-- The board list asks `creator = $u OR participants CONTAINS $u`; the GIN +-- index covers the membership half ($1 = ANY(participants) at query sites). +CREATE INDEX board_participants ON board USING GIN (participants); + +CREATE TABLE board_stroke ( + id uuid PRIMARY KEY, + board uuid NOT NULL REFERENCES board(id) ON DELETE NO ACTION, + author uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + -- 'stroke' or 'clear'; payload NULL on a clear marker, count populated + -- only on a clear marker — the final stroke count of the epoch that + -- marker closed. + kind TEXT NOT NULL, + payload TEXT NULL, + count BIGINT NULL, + epoch BIGINT NOT NULL, + created_at BIGINT NOT NULL +); + +CREATE INDEX board_stroke_board_epoch ON board_stroke (board, epoch); +CREATE INDEX board_stroke_board_kind ON board_stroke (board, kind); + +CREATE TABLE chatbot_thread ( + id uuid PRIMARY KEY, + user_id uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + title TEXT NULL, + created_at BIGINT NOT NULL, + updated_at BIGINT NOT NULL +); + +CREATE INDEX chatbot_thread_user_updated ON chatbot_thread (user_id, updated_at); + +CREATE TABLE chatbot_message ( + id uuid PRIMARY KEY, + thread_id uuid NOT NULL REFERENCES chatbot_thread(id) ON DELETE NO ACTION, + user_id uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + role TEXT NOT NULL CHECK (role IN ('user', 'assistant')), + content TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('pending', 'complete', 'failed')), + truncated BOOLEAN NOT NULL DEFAULT false, + error_code TEXT NULL, + created_at BIGINT NOT NULL, + completed_at BIGINT NULL +); + +CREATE INDEX chatbot_message_thread_created ON chatbot_message (thread_id, created_at); +CREATE INDEX chatbot_message_user ON chatbot_message (user_id); +CREATE INDEX chatbot_message_status_created ON chatbot_message (status, created_at); + +CREATE TABLE settings ( + -- Singleton row: id = 'school'. + id TEXT PRIMARY KEY, + exam_kinds JSONB NOT NULL, + attendance_statuses TEXT[] NOT NULL, + grade_bands JSONB NOT NULL, + max_file_bytes BIGINT NULL, + chatbot_history_turns BIGINT NULL, + max_chatbot_message_len BIGINT NULL, + max_chatbot_threads BIGINT NULL, + meal_slots JSONB NULL, + dietary_tags TEXT[] NULL, + meal_cancel_cutoff_minutes BIGINT NULL +); + +-- Reference counters, one row per *name* the settings offer. Created by the +-- first claim; an absent row reads as zero references, in service. +CREATE TABLE kind_ref ( + name TEXT PRIMARY KEY, + count BIGINT NOT NULL DEFAULT 0, + retired BOOLEAN NOT NULL DEFAULT false +); + +CREATE TABLE slot_ref ( + name TEXT PRIMARY KEY, + count BIGINT NOT NULL DEFAULT 0, + retired BOOLEAN NOT NULL DEFAULT false +); diff --git a/migrations/school/20260912000002_courses.sql b/migrations/school/20260912000002_courses.sql new file mode 100644 index 0000000..a8f0b47 --- /dev/null +++ b/migrations/school/20260912000002_courses.sql @@ -0,0 +1,208 @@ +-- School-database schema, part 2: courses, terms, classes, enrollment, +-- events, attendance (Postgres). +-- +-- DISJOINTNESS INVARIANT: the tables in migrations/school/*.sql and the ones +-- in migrations/control/*.sql together form ONE union schema, applied to a +-- single prepare database by scripts/prepare_db.sh for sqlx's compile-time +-- query macros. The two sets must never collide on a table name. +-- +-- Same translation rules as part 1: table `user` -> app_user (and every +-- column named `user`), record refs -> uuid FKs ON DELETE NO ACTION, natural +-- composite PKs replace the old `{a}_{b}` text record keys (the PK constraint +-- carries the old unique-index name — it is what surfaces in SQLSTATE 23505), +-- counters are BIGINT NOT NULL DEFAULT 0 and stay out of the Rust structs. + +CREATE TABLE term ( + id uuid PRIMARY KEY, + name TEXT NOT NULL, + starts_at BIGINT NOT NULL, + ends_at BIGINT NOT NULL, + -- When the term was archived; NULL = open. + archived_at BIGINT NULL, + course_count BIGINT NOT NULL DEFAULT 0, + class_count BIGINT NOT NULL DEFAULT 0 +); + +CREATE TABLE course ( + id uuid PRIMARY KEY, + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + teachers uuid[] NOT NULL DEFAULT '{}', + title TEXT NOT NULL, + description TEXT NOT NULL, + kind TEXT NOT NULL DEFAULT 'course', + term uuid NULL REFERENCES term(id) ON DELETE NO ACTION, + capacity BIGINT NULL, + enrollment_count BIGINT NOT NULL DEFAULT 0 +); +-- No GIN on teachers, faithful to the Surreal schema: the teachers-membership +-- read stays a scan, exactly as today (see src/db/course.rs — the Surreal +-- per-element index form returned zero rows and was never defined). + +CREATE TABLE subject ( + id uuid PRIMARY KEY, + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, + name TEXT NOT NULL, + description TEXT NOT NULL, + exam_question_count BIGINT NOT NULL DEFAULT 0, + homework_count BIGINT NOT NULL DEFAULT 0 +); + +CREATE INDEX subject_course ON subject (course); + +CREATE TABLE course_note ( + id uuid PRIMARY KEY, + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, + author uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + title TEXT NOT NULL, + content TEXT NOT NULL, + file_count BIGINT NOT NULL DEFAULT 0 +); + +CREATE INDEX course_note_course ON course_note (course); + +CREATE TABLE course_note_file ( + id uuid PRIMARY KEY, + course_note uuid NOT NULL REFERENCES course_note(id) ON DELETE NO ACTION, + name TEXT NOT NULL, + content_type TEXT NOT NULL, + size BIGINT NOT NULL +); + +CREATE INDEX course_note_file_note ON course_note_file (course_note); + +-- What an AI service produced for a course note. Derived and disposable; +-- payload is JSONB because its shape belongs to the service, not this schema. +CREATE TABLE rag_output ( + id uuid PRIMARY KEY, + course_note uuid NOT NULL REFERENCES course_note(id) ON DELETE NO ACTION, + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, + sources uuid[] NOT NULL DEFAULT '{}', + payload JSONB NOT NULL, + generated_at BIGINT NOT NULL +); + +CREATE INDEX rag_output_note ON rag_output (course_note); +-- The source cascade asks `sources CONTAINS $file`; the GIN index makes it a +-- lookup instead of a scan. +CREATE INDEX rag_output_source ON rag_output USING GIN (sources); + +CREATE TABLE course_session ( + id uuid PRIMARY KEY, + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, + teacher uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + topic TEXT NOT NULL, + starts_at BIGINT NOT NULL, + ends_at BIGINT NULL, + -- The once-per-session guard behind lessons_held_total: stamped by the + -- first roll call taken for the lesson. + held_counted_at BIGINT NULL +); + +CREATE INDEX course_session_course ON course_session (course); + +CREATE TABLE session_attendance ( + session uuid NOT NULL REFERENCES course_session(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, + status TEXT NOT NULL, + marked_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + CONSTRAINT session_attendance_session_user PRIMARY KEY (session, app_user) +); + +CREATE INDEX session_attendance_session ON session_attendance (session); +CREATE INDEX session_attendance_user ON session_attendance (app_user); +CREATE INDEX session_attendance_course ON session_attendance (course); + +CREATE TABLE class_group ( + id uuid PRIMARY KEY, + name TEXT NOT NULL, + grade TEXT NULL, + term uuid NULL REFERENCES term(id) ON DELETE NO ACTION, + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + teacher uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, + class_member_count BIGINT NOT NULL DEFAULT 0, + class_course_count BIGINT NOT NULL DEFAULT 0 +); + +CREATE INDEX class_group_grade ON class_group (grade); + +-- A grade's course template. The grade label IS the record key in Surreal, so +-- the PK here is TEXT on grade itself (no id column, no uuid). +CREATE TABLE class_blueprint ( + grade TEXT PRIMARY KEY, + courses uuid[] NOT NULL DEFAULT '{}', + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION +); + +CREATE TABLE class_member ( + class uuid NOT NULL REFERENCES class_group(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + added_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + -- When the student was put in; NULL on rows of unknown age. + added_at BIGINT NULL, + CONSTRAINT class_member_class_user PRIMARY KEY (class, app_user) +); + +CREATE INDEX class_member_class ON class_member (class); +CREATE INDEX class_member_user ON class_member (app_user); + +CREATE TABLE class_course ( + class uuid NOT NULL REFERENCES class_group(id) ON DELETE NO ACTION, + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, + attached_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + attached_at BIGINT NULL, + -- The blueprint that attached this course; NULL = attached by hand, which + -- keeps a hand-attached course unreachable by every blueprint sweep. + source TEXT NULL REFERENCES class_blueprint(grade) ON DELETE NO ACTION, + CONSTRAINT class_course_class_course PRIMARY KEY (class, course) +); + +CREATE INDEX class_course_class ON class_course (class); +CREATE INDEX class_course_course ON class_course (course); + +CREATE TABLE enrollment ( + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + enrolled_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + -- The class that pumped this row; NULL when a human placed the student. + source uuid NULL REFERENCES class_group(id) ON DELETE NO ACTION, + CONSTRAINT enrollment_course_user PRIMARY KEY (course, app_user) +); + +CREATE INDEX enrollment_user ON enrollment (app_user); + +CREATE TABLE event ( + id uuid PRIMARY KEY, + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + title TEXT NOT NULL, + description TEXT NOT NULL, + -- The EventAudience enum flattened into columns (tag + per-variant data). + audience_kind TEXT NOT NULL + CHECK (audience_kind IN ('school', 'role', 'course', 'class', 'registration')), + audience_role TEXT NULL, + audience_course uuid NULL REFERENCES course(id) ON DELETE NO ACTION, + audience_class uuid NULL REFERENCES class_group(id) ON DELETE NO ACTION, + audience_capacity BIGINT NULL, + registration_count BIGINT NOT NULL DEFAULT 0, + starts_at BIGINT NULL, + ends_at BIGINT NULL +); + +CREATE TABLE attendance ( + event uuid NOT NULL REFERENCES event(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + status TEXT NOT NULL, + marked_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + CONSTRAINT attendance_event_user PRIMARY KEY (event, app_user) +); + +CREATE INDEX attendance_user ON attendance (app_user); + +CREATE TABLE registration ( + event uuid NOT NULL REFERENCES event(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + registered_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + CONSTRAINT registration_event_user PRIMARY KEY (event, app_user) +); + +CREATE INDEX registration_event ON registration (event); diff --git a/migrations/school/20260912000003_exams.sql b/migrations/school/20260912000003_exams.sql new file mode 100644 index 0000000..a3bb5e1 --- /dev/null +++ b/migrations/school/20260912000003_exams.sql @@ -0,0 +1,242 @@ +-- School-database schema, part 3: exams, question bank, pool, homework +-- (Postgres). +-- +-- DISJOINTNESS INVARIANT: the tables in migrations/school/*.sql and the ones +-- in migrations/control/*.sql together form ONE union schema, applied to a +-- single prepare database by scripts/prepare_db.sh for sqlx's compile-time +-- query macros. The two sets must never collide on a table name. +-- +-- Same translation rules as parts 1-2. Sitting-scoped tables +-- (exam_attempt / exam_answer / answer_image / exam_result) key on their +-- natural composite (…, app_user, seq); a retake's row is a new row, never an +-- overwrite of the prior sitting. `choices` is JSONB (array of {id, text} +-- objects); exam.kind / exam.mode / homework_result.status / +-- pool_question.status / bank_question.visibility carry NO CHECK — validated +-- String newtypes in Rust, and exam kinds are school-configurable at runtime. + +CREATE TABLE exam ( + id uuid PRIMARY KEY, + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, + title TEXT NOT NULL, + description TEXT NOT NULL, + kind TEXT NOT NULL, + mode TEXT NULL, + starts_at BIGINT NULL, + ends_at BIGINT NULL, + duration_ms BIGINT NULL, + max_attempts BIGINT NOT NULL DEFAULT 1, + allow_rejoin BOOLEAN NOT NULL DEFAULT true, + allow_review BOOLEAN NOT NULL DEFAULT false, + draft BOOLEAN NOT NULL DEFAULT false, + result_count BIGINT NOT NULL DEFAULT 0 +); + +CREATE INDEX exam_course ON exam (course); + +-- Created before exam_question: source_exam points back at exam. +CREATE TABLE bank_question ( + id uuid PRIMARY KEY, + owner uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + subject uuid NULL REFERENCES subject(id) ON DELETE NO ACTION, + text TEXT NOT NULL, + kind TEXT NOT NULL, + points BIGINT NOT NULL, + choices JSONB NULL, + correct TEXT NULL, + source_exam uuid NULL REFERENCES exam(id) ON DELETE NO ACTION, + -- 'private' | 'school'; DEFAULT so a partial write can never come out + -- published. + visibility TEXT NOT NULL DEFAULT 'private', + created_at BIGINT NOT NULL +); + +CREATE INDEX bank_question_owner ON bank_question (owner); +CREATE INDEX bank_question_subject ON bank_question (subject); + +CREATE TABLE exam_question ( + id uuid PRIMARY KEY, + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, + text TEXT NOT NULL, + kind TEXT NOT NULL, + points BIGINT NOT NULL, + choices JSONB NULL, + correct TEXT NULL, + subject uuid NOT NULL REFERENCES subject(id) ON DELETE NO ACTION, + -- Provenance, one column per direction: from_bank = the template this + -- question was inserted from, banked_as = the template most recently + -- minted by saving it into the bank. + from_bank uuid NULL REFERENCES bank_question(id) ON DELETE NO ACTION, + banked_as uuid NULL REFERENCES bank_question(id) ON DELETE NO ACTION +); + +CREATE INDEX exam_question_exam ON exam_question (exam); +CREATE INDEX exam_question_subject ON exam_question (subject); + +CREATE TABLE bank_question_image ( + bank_question uuid NOT NULL REFERENCES bank_question(id) ON DELETE NO ACTION, + -- NULL = the question's own illustration; otherwise the choice's id. A + -- (question, slot) pair holds at most one picture, and a question holds + -- at most one illustration — NULLS NOT DISTINCT is what makes the NULL + -- case count as taken. + slot TEXT NULL, + file TEXT NOT NULL, + content_type TEXT NOT NULL, + size BIGINT NOT NULL, + CONSTRAINT bank_question_image_question_slot UNIQUE NULLS NOT DISTINCT (bank_question, slot) +); + +CREATE TABLE question_image ( + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, + question uuid NOT NULL REFERENCES exam_question(id) ON DELETE NO ACTION, + -- NULL = the question's own illustration; otherwise the choice's id. A + -- (question, slot) pair holds at most one picture, and a question holds + -- at most one illustration — NULLS NOT DISTINCT is what makes the NULL + -- case count as taken. + slot TEXT NULL, + file TEXT NOT NULL, + content_type TEXT NOT NULL, + size BIGINT NOT NULL, + CONSTRAINT question_image_question_slot UNIQUE NULLS NOT DISTINCT (question, slot) +); + +CREATE INDEX question_image_exam ON question_image (exam); +CREATE INDEX question_image_question ON question_image (question); + +CREATE TABLE exam_attempt ( + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + seq BIGINT NOT NULL DEFAULT 1, + started_at BIGINT NOT NULL, + finished_at BIGINT NULL, + left_at BIGINT NULL, + CONSTRAINT exam_attempt_exam_user_seq PRIMARY KEY (exam, app_user, seq) +); + +CREATE INDEX exam_attempt_exam ON exam_attempt (exam); + +CREATE TABLE exam_answer ( + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, + question uuid NOT NULL REFERENCES exam_question(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + selected TEXT NULL, + text TEXT NULL, + updated_at BIGINT NOT NULL, + seq BIGINT NOT NULL DEFAULT 1, + CONSTRAINT exam_answer_question_user_seq PRIMARY KEY (question, app_user, seq) +); + +CREATE INDEX exam_answer_exam_user ON exam_answer (exam, app_user); +CREATE INDEX exam_answer_exam ON exam_answer (exam); + +CREATE TABLE answer_image ( + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, + question uuid NOT NULL REFERENCES exam_question(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + file TEXT NOT NULL, + content_type TEXT NOT NULL, + size BIGINT NOT NULL, + seq BIGINT NOT NULL DEFAULT 1, + CONSTRAINT answer_image_question_user_seq PRIMARY KEY (question, app_user, seq) +); + +CREATE INDEX answer_image_exam ON answer_image (exam); +CREATE INDEX answer_image_user ON answer_image (app_user); + +CREATE TABLE exam_result ( + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + mark BIGINT NOT NULL, + graded_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + seq BIGINT NOT NULL DEFAULT 1, + CONSTRAINT exam_result_exam_user_seq PRIMARY KEY (exam, app_user, seq) +); + +CREATE TABLE pool_question ( + id uuid PRIMARY KEY, + asker uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + title TEXT NOT NULL, + body TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + asked_at BIGINT NOT NULL, + approved_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, + image_file TEXT NULL, + image_content_type TEXT NULL, + image_size BIGINT NULL +); + +CREATE INDEX pool_question_status ON pool_question (status); +CREATE INDEX pool_question_asker ON pool_question (asker); + +CREATE TABLE solution ( + id uuid PRIMARY KEY, + question uuid NOT NULL REFERENCES pool_question(id) ON DELETE NO ACTION, + author uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + body TEXT NOT NULL, + offered_at BIGINT NOT NULL, + image_file TEXT NULL, + image_content_type TEXT NULL, + image_size BIGINT NULL +); + +CREATE INDEX solution_question ON solution (question); + +CREATE TABLE homework ( + id uuid PRIMARY KEY, + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, + subject uuid NOT NULL REFERENCES subject(id) ON DELETE NO ACTION, + title TEXT NOT NULL, + description TEXT NULL, + due_at BIGINT NOT NULL, + -- NULL/empty means the whole course. + assigned uuid[] NOT NULL DEFAULT '{}', + created_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + created_at BIGINT NOT NULL +); + +CREATE INDEX homework_course ON homework (course); + +CREATE TABLE homework_result ( + id uuid PRIMARY KEY, + homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + status TEXT NOT NULL, + mark BIGINT NULL, + graded_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + created_at BIGINT NOT NULL, + -- The deterministic {homework}_{user} pair: one grade per pair by + -- construction (grading is one atomic upsert against this constraint). + CONSTRAINT homework_result_homework_user UNIQUE (homework, app_user) +); + +CREATE INDEX homework_result_homework ON homework_result (homework); + +CREATE TABLE homework_submission ( + id uuid PRIMARY KEY, + homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + text TEXT NULL, + submitted_at BIGINT NOT NULL, + updated_at BIGINT NOT NULL, + file_count BIGINT NOT NULL DEFAULT 0, + -- The on-time verdict credited at the first hand-in, never re-judged. + counted_on_time BOOLEAN NULL, + -- The grade that froze this submission; NULL while it is still open. + graded_by_result uuid NULL REFERENCES homework_result(id) ON DELETE NO ACTION, + -- Same deterministic pair as homework_result: one submission per + -- (homework, user) by construction. + CONSTRAINT homework_submission_homework_user UNIQUE (homework, app_user) +); + +CREATE INDEX homework_submission_homework ON homework_submission (homework); + +CREATE TABLE homework_file ( + id uuid PRIMARY KEY, + submission uuid NOT NULL REFERENCES homework_submission(id) ON DELETE NO ACTION, + name TEXT NOT NULL, + content_type TEXT NOT NULL, + size BIGINT NOT NULL, + created_at BIGINT NOT NULL +); + +CREATE INDEX homework_file_submission ON homework_file (submission); diff --git a/migrations/school/20260912000004_food_appointments_fees.sql b/migrations/school/20260912000004_food_appointments_fees.sql new file mode 100644 index 0000000..867c2d2 --- /dev/null +++ b/migrations/school/20260912000004_food_appointments_fees.sql @@ -0,0 +1,205 @@ +-- School-database schema, part 4: appointments, food program, fees, payments +-- (Postgres). +-- +-- DISJOINTNESS INVARIANT: the tables in migrations/school/*.sql and the ones +-- in migrations/control/*.sql together form ONE union schema, applied to a +-- single prepare database by scripts/prepare_db.sh for sqlx's compile-time +-- query macros. The two sets must never collide on a table name. +-- +-- Same translation rules as parts 1-3. New DDL with no Surreal source: +-- the btree_gist extension and the appointment_slot EXCLUDE constraint — +-- the publish-overlap guard that replaces the old APPOINTMENT_LOCK publish +-- path (SQLSTATE 23505 maps to the overlap 409 at the call site). +-- +-- `menu` carries an app-minted uuid id plus the natural UNIQUE (date, slot): +-- its children (menu_dish, meal_booking, meal_attendance) reference it by a +-- single column, which a composite (date, slot) PK could not serve. The +-- publish upsert keys on the natural pair exactly as before. + +CREATE EXTENSION IF NOT EXISTS btree_gist; + +CREATE TABLE appointment_slot ( + id uuid PRIMARY KEY, + teacher uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + starts_at BIGINT NOT NULL, + ends_at BIGINT NOT NULL, + occupied BIGINT NOT NULL DEFAULT 0, + note TEXT NULL, + -- Groups the occurrences a weekly repeat expanded into; NULL on a + -- one-off slot. + series TEXT NULL, + created_at BIGINT NOT NULL, + -- Derived window for the exclusion constraint below. + span int8range GENERATED ALWAYS AS (int8range(starts_at, ends_at)) STORED, + -- A teacher cannot publish two overlapping windows: the old + -- APPOINTMENT_LOCK publish path, now a database guarantee (23505). + CONSTRAINT appointment_slot_teacher_span EXCLUDE USING gist (teacher WITH =, span WITH &&) +); + +CREATE INDEX appointment_slot_teacher_starts ON appointment_slot (teacher, starts_at); +CREATE INDEX appointment_slot_series ON appointment_slot (series); + +CREATE TABLE appointment ( + id uuid PRIMARY KEY, + slot uuid NOT NULL REFERENCES appointment_slot(id) ON DELETE NO ACTION, + requester uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + status TEXT NOT NULL DEFAULT 'pending' + CHECK (status IN ('pending', 'approved', 'rejected', 'cancelled')), + reason TEXT NOT NULL, + -- A teacher's counter-proposal on the same row, until the requester + -- accepts. + proposed_starts_at BIGINT NULL, + proposed_ends_at BIGINT NULL, + proposed_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, + decided_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, + cancelled_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, + cancel_reason TEXT NULL, + reject_reason TEXT NULL, + created_at BIGINT NOT NULL +); + +CREATE INDEX appointment_slot_ref ON appointment (slot); +CREATE INDEX appointment_requester ON appointment (requester); +CREATE INDEX appointment_status ON appointment (status); + +-- A published menu per day+slot. `date` is a calendar day as YYYY-MM-DD +-- text (an equality key, not a timestamp); `slot` is snapshotted text, so +-- retiring a slot in settings never rewrites a past menu. +CREATE TABLE menu ( + -- The {date}_{slot} derived key — it IS the URL segment — with the two + -- components kept as their own columns (the unique pair keeps the old + -- index name, which is what surfaces in SQLSTATE 23505). + id TEXT PRIMARY KEY, + date TEXT NOT NULL, + slot TEXT NOT NULL, + capacity BIGINT NULL, + seats_booked BIGINT NOT NULL DEFAULT 0, + -- The menu's revision: a booking claims its seat only while the menu + -- still stands at the revision it read the price at. A stamp, not a + -- counter: NULL reads as revision zero at the Rust boundary. + version BIGINT NULL, + created_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + created_at BIGINT NOT NULL, + CONSTRAINT menu_date_slot UNIQUE (date, slot) +); + +CREATE TABLE menu_dish ( + id uuid PRIMARY KEY, + menu TEXT NOT NULL REFERENCES menu(id) ON DELETE NO ACTION, + name TEXT NOT NULL, + description TEXT NULL, + -- Money is minor units (kuruş) as an integer, everywhere. Never decimal. + price_minor BIGINT NOT NULL, + tags TEXT[] NOT NULL DEFAULT '{}', + created_at BIGINT NOT NULL +); + +CREATE INDEX menu_dish_menu ON menu_dish (menu); + +CREATE TABLE dietary_profile ( + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + tags TEXT[] NOT NULL DEFAULT '{}', + note TEXT NULL, + updated_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + updated_at BIGINT NOT NULL, + CONSTRAINT dietary_profile_student PRIMARY KEY (student) +); + +-- A cancel flips `status` and stamps `cancelled_at`; the row stays so the +-- freed seat is still auditable against the ledger line it charged. +CREATE TABLE meal_booking ( + menu TEXT NOT NULL REFERENCES menu(id) ON DELETE NO ACTION, + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + booked_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + status TEXT NOT NULL DEFAULT 'booked' + CHECK (status IN ('booked', 'cancelled')), + -- How many times this seat has been taken, and what it cost when the + -- current attempt took it (NULL = the menu was free then). + attempt BIGINT NOT NULL DEFAULT 1, + price_minor BIGINT NULL, + cancelled_at BIGINT NULL, + created_at BIGINT NOT NULL, + -- One row per (menu, student); a re-booking re-uses the row and bumps + -- `attempt`. + CONSTRAINT meal_booking_menu_student PRIMARY KEY (menu, student) +); + +CREATE INDEX meal_booking_menu ON meal_booking (menu); +CREATE INDEX meal_booking_student ON meal_booking (student); + +CREATE TABLE meal_attendance ( + menu TEXT NOT NULL REFERENCES menu(id) ON DELETE NO ACTION, + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + status TEXT NOT NULL, + marked_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + marked_at BIGINT NOT NULL, + CONSTRAINT meal_attendance_menu_student PRIMARY KEY (menu, student) +); + +-- APPEND-ONLY by design: a mistake is corrected with an opposing reversal +-- line, never by editing or deleting one. `source` is deliberately FK-less — +-- a charge points at the booking that caused it, a reversal at the line it +-- undoes (polymorphic, so no single REFERENCES target exists). +CREATE TABLE meal_ledger ( + -- The {menu}_{student}_c{attempt} derived key: billing idempotence by + -- identity, not by scanning for an outstanding charge. + id TEXT PRIMARY KEY, + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + kind TEXT NOT NULL CHECK (kind IN ('charge', 'credit', 'reversal')), + amount_minor BIGINT NOT NULL, + -- Polymorphic pointer (booking row, or the line it undoes) — TEXT + -- because it can name a uuid-keyed or a derived-key row; no FK. + source TEXT NULL, + method TEXT NULL, + note TEXT NULL, + recorded_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + created_at BIGINT NOT NULL +); + +CREATE INDEX meal_ledger_student ON meal_ledger (student); + +-- A school fee plan: a name and its installments (embedded JSONB — a charge +-- line copies the amount it was assigned at, so child rows would buy +-- nothing). +CREATE TABLE fee_plan ( + id uuid PRIMARY KEY, + name TEXT NOT NULL, + installments JSONB NOT NULL, + created_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + created_at BIGINT NOT NULL, + assignment_count BIGINT NOT NULL DEFAULT 0 +); + +-- One plan on one student; the deterministic {plan}_{student} pair. +CREATE TABLE fee_plan_assignment ( + plan uuid NOT NULL REFERENCES fee_plan(id) ON DELETE NO ACTION, + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + assigned_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + created_at BIGINT NOT NULL, + CONSTRAINT fee_plan_assignment_plan PRIMARY KEY (plan, student) +); + +CREATE INDEX fee_plan_assignment_student ON fee_plan_assignment (student); + +-- School fees, APPEND-ONLY exactly like meal_ledger. `source` is FK-less for +-- the same polymorphic reason (charge -> assignment, credit -> charge, +-- refund -> credit, reversal -> line); `due_at` is set on charges alone. +CREATE TABLE payment_ledger ( + -- The {plan}_{student}_c{n} / {line}_r / {target}_k_{request_key} + -- derived key: append-only rows addressed by identity. + id TEXT PRIMARY KEY, + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + kind TEXT NOT NULL CHECK (kind IN ('charge', 'credit', 'reversal', 'refund')), + amount_minor BIGINT NOT NULL, + -- Polymorphic pointer (assignment, charge, credit, or line it undoes); + -- TEXT for the same reason as meal_ledger.source. No FK. + source TEXT NULL, + due_at BIGINT NULL, + method TEXT NULL, + note TEXT NULL, + recorded_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + created_at BIGINT NOT NULL +); + +CREATE INDEX payment_ledger_student ON payment_ledger (student); +CREATE INDEX payment_ledger_source ON payment_ledger (source); diff --git a/scripts/prepare_db.sh b/scripts/prepare_db.sh new file mode 100755 index 0000000..44a7f4f --- /dev/null +++ b/scripts/prepare_db.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# Refresh the sqlx "prepare" database: the ONE database whose schema is the +# union of migrations/control/*.sql + migrations/school/*.sql, against which +# sqlx's compile-time query macros check every query (`cargo sqlx prepare`, +# and plain `cargo check` with DATABASE_URL set — see .env.example). +# +# DISJOINTNESS INVARIANT: control tables (school, builder, builder_session, +# rate_limit) and school tables must never collide on a name — the union is +# applied to this single database. The loop below fails loudly (psql +# ON_ERROR_STOP=1) if a name ever collides. +# +# Raw apply, on purpose: no `sqlx migrate run`, so no `_sqlx_migrations` +# tracking rows exist and the control and school file sets never share a +# tracking table. The database is dropped and recreated on every run, so the +# result is deterministic. +# +# Requires the compose Postgres: `podman compose up -d postgres`. +set -euo pipefail + +CONTAINER="${HEZARFEN_PG_CONTAINER:-hezarfen-postgres}" +PREPARE_DB="${HEZARFEN_PREPARE_DB:-hezarfen_sqlx_prepare}" +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +psql() { + podman exec -i "$CONTAINER" psql -U hezarfen -v ON_ERROR_STOP=1 "$@" +} + +echo "== refreshing $PREPARE_DB on $CONTAINER" +psql -d postgres -q <` here means a -/// new session, and a matching `SessionId::Drop`, for each request served. -/// Under concurrency those lifecycle events race the queries riding on them: -/// sessions disappear ("Session not found"), and a session whose signin has -/// not been replayed answers "Anonymous access not allowed" / "Specify a -/// namespace" — the same strings [`crate::error::is_session_replay_error`] -/// treats as a transient reconnect, so the failures masquerade as one. +/// `PgPool` is an `Arc` around its internals, so cloning shares the one pool — +/// axum cloning the application state per request costs an atomic increment, +/// nothing more. +pub type Database = sqlx::PgPool; + +/// Connect to the **control** database, apply the control schema, seed the +/// builder account and ensure the school-template database. School databases +/// are brought up separately, one per school, by [`crate::tenant::Tenants`]. /// -/// Cloning the `Arc` shares the single session established at boot instead. -pub type Database = std::sync::Arc>; - -/// Connect to the **control** database, sign in as root, apply the control -/// schema and seed the builder account. School databases are brought up -/// separately, one per school, by [`crate::tenant::Tenants`]. +/// The dial is retried forever (one-second cadence): the database is normally +/// a sibling container booting in parallel, and a process that exits on the +/// first refusal gets restarted by the runtime, fails again in ~100ms, and +/// burns its whole restart budget inside a second — leaving the backend +/// permanently down over a startup skew that would have cleared on its own. +/// Only the *connection* is retried. Bad credentials or a broken migration +/// still fail hard, since no amount of waiting fixes those. pub async fn init(cfg: &Config) -> Result { // Validated before the connection, not after: half a credential pair is a // deployment mistake, and reporting it only after a successful dial buries // it under an outage that isn't one. let builder = builder_credentials(cfg)?; - let db = connect_with_retry(cfg).await; - db.signin(Root { - username: cfg.db_user.clone(), - password: cfg.db_pass.clone(), - }) - .await?; - db.use_ns(cfg.db_ns.clone()) - .use_db(cfg.db_name.clone()) - .await?; - let db = std::sync::Arc::new(db); - migrate_control(&db).await?; + + let (base, control_db) = parse_base(cfg)?; + + let control = loop { + match boot_control(&base).await { + Ok(pool) => break pool, + Err(err) if boot_failure_retryable(&err) => { + tracing::warn!( + "database at postgres://{}:{} unreachable ({err}) — retrying in 1s", + base.get_host(), + base.get_port(), + ); + tokio::time::sleep(Duration::from_secs(1)).await; + } + Err(err) => return Err(err.into()), + } + }; + if let Some((username, password)) = builder { - crate::service::builder::ensure(&db, username, password).await?; + crate::service::builder::ensure(&control, username, password).await?; } - Ok(Tenants::new_remote(db, cfg)) + + // The template every school schema is validated against at boot: created + // outside any transaction (`CREATE DATABASE` cannot run inside one — + // `Pool::execute` runs bare autocommit statements), migrated once, then + // closed. A first boot lost to a concurrent boot of the same deployment + // adopts the winner's template via the duplicate-database swallow. + let template = format!("{control_db}_school_template"); + ensure_template(&control, &base, &template).await?; + + Ok(Tenants::new(control, base, control_db)) } -/// The `BUILDER_USERNAME` / `BUILDER_PASSWORD` bootstrap pair, if configured. -/// Both-or-neither: half a pair aborts startup rather than silently running -/// without the seed — and without a builder, a fresh deployment has nobody who -/// can create the first school. -fn builder_credentials(cfg: &Config) -> Result, AppError> { - match (&cfg.builder_username, &cfg.builder_password) { - (Some(username), Some(password)) => Ok(Some(( - Username::try_new(username) - .map_err(|err| AppError::Internal(format!("invalid BUILDER_USERNAME: {err}")))?, - Password::try_new(password) - .map_err(|err| AppError::Internal(format!("invalid BUILDER_PASSWORD: {err}")))?, - ))), - (None, None) => Ok(None), - _ => Err(AppError::Internal( - "BUILDER_USERNAME and BUILDER_PASSWORD must be set together".into(), - )), +/// Parse `DATABASE_URL` into dial options plus the control database's name — +/// the name every school database hangs off (`{control}_school_{slug}`). +pub(crate) fn parse_base(cfg: &Config) -> Result<(PgConnectOptions, String), AppError> { + let opts: PgConnectOptions = cfg.database_url.parse().map_err(|err| { + AppError::Internal(format!("invalid DATABASE_URL ({}): {err}", cfg.database_url)) + })?; + let db = opts + .get_database() + .ok_or_else(|| { + AppError::Internal( + "DATABASE_URL names no database — the school databases are named after it".into(), + ) + })? + .to_string(); + Ok((opts, db)) +} + +/// The pool knobs. The control pool holds 10 connections; each school pool +/// holds 4 (a school's traffic is one building's worth, and every school pool +/// draws from the same server's connection budget). +fn pool_options(max_connections: u32) -> PgPoolOptions { + PgPoolOptions::new() + .max_connections(max_connections) + .min_connections(0) + .acquire_timeout(Duration::from_secs(10)) + .idle_timeout(Duration::from_secs(300)) + .max_lifetime(Duration::from_secs(1800)) +} + +/// A pool over one school database with the school pool sizing. The schema is +/// the caller's business — [`migrate_school`] for a mint, nothing for a +/// re-dial of an existing school. +pub(crate) async fn school_pool(base: &PgConnectOptions, db_name: &str) -> Result { + pool_options(4) + .connect_with(base.clone().database(db_name)) + .await + .map_err(Into::into) +} + +/// A `CREATE DATABASE` / `DROP DATABASE` statement for a quoted identifier. +/// The names passed here are the control database's name (from +/// `DATABASE_URL`), the template's (`{control}_school_template`) or +/// [`crate::tenant::school_db_name`]'s output — never user input: the slug +/// charset is `[a-z0-9-]` and an embedded quote is doubled, so the statement +/// cannot be escaped from. That manual audit is what licenses the +/// `AssertSqlSafe` wrapper every caller applies (sqlx refuses non-literal +/// query strings without it). +pub(crate) fn create_database_sql(statement: &str, name: &str) -> String { + format!("{statement} \"{}\"", name.replace('"', "\"\"")) +} + +async fn boot_control(base: &PgConnectOptions) -> Result { + let pool = pool_options(10).connect_with(base.clone()).await?; + // The migrator is built here rather than in [`migrator`]: its resolution + // failure must classify as a boot error (retry or abort), not skip + // straight to `AppError`. + let migrator = Migrator::new(migrations_path("control").as_path()) + .await + .map_err(sqlx::Error::from)?; + migrator.run(&pool).await?; + Ok(pool) +} + +/// Is this boot failure the database not being *there* yet — the only thing +/// a second of patience can fix? Everything else (a bad migration, a bad +/// credential, a missing migrations directory) aborts startup immediately. +fn boot_failure_retryable(err: &sqlx::Error) -> bool { + match err { + sqlx::Error::Migrate(migrate) => match migrate.as_ref() { + MigrateError::Execute(e) | MigrateError::ExecuteMigration(e, _) => is_dial_error(e), + _ => false, + }, + e => is_dial_error(e), } } -/// The two ways a rival's claim shows up as an error on ours: our `CREATE` hit -/// their row, or the key-value layer aborted our transaction because theirs -/// touched the same key first. -/// -/// Read from the *typed* error surface, not the message. Every conflict wording -/// the storage engines produce — surrealkv's "Transaction conflict: Write -/// conflict, retry the transaction. This transaction can be retried", -/// surrealmx's read-conflict variant, RocksDB's `Busy`/`TryAgain` — funnels -/// through one `KvsError::TransactionConflict` into -/// `QueryError::TransactionConflict` (surrealdb-core 3.2.3 -/// `err/to_types.rs:295`, `kvs/err.rs:64-179`), and a duplicate record id into -/// `AlreadyExistsError::Record` (`to_types.rs:206`). So the two checks below -/// cover all of them, where matching substrings covered only whichever wording -/// the engine of the day happened to use. -/// -/// The message fallback stays for one reason: these errors also travel over the -/// WebSocket, where the SDK rebuilds them from the wire (`Error::from_parts`), -/// and a server that omitted the typed details would otherwise turn a lost race -/// into a failed boot. Widest known wordings, cheap, and belt-and-braces. -pub(crate) fn lost_the_race(err: &surrealdb::Error) -> bool { - use surrealdb::types::{ErrorDetails, QueryError}; - if err.is_already_exists() - || matches!( - err.details(), - ErrorDetails::Query(Some(QueryError::TransactionConflict)) - ) +/// Connection-class errors: the server was unreachable or the pool could not +/// hand out a connection. A migrations statement that *failed* is not here — +/// its error is `Error::Database`, and no sleep rewrites SQL. +fn is_dial_error(err: &sqlx::Error) -> bool { + matches!( + err, + sqlx::Error::Io(_) + | sqlx::Error::Tls(_) + | sqlx::Error::PoolTimedOut + | sqlx::Error::PoolClosed + // A connection that died mid-handshake can present as protocol + // breakage; a fresh dial either works or reports something else. + | sqlx::Error::Protocol(_) + ) +} + +/// The `migrations/` directory under `CARGO_MANIFEST_DIR`. Two sets +/// cannot both feed the compile-time `migrate!` macro, so both are resolved +/// from their paths at runtime. +fn migrations_path(set: &str) -> std::path::PathBuf { + Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/migrations")).join(set) +} + +async fn migrator(set: &str) -> Result { + Migrator::new(migrations_path(set).as_path()) + .await + .map_err(|err| AppError::Internal(format!("cannot read the {set} migrations: {err}"))) +} + +/// Apply the school schema to a school database — the template at boot, every +/// newly minted school at create — then sweep the chatbot turns the previous +/// process owed an answer. Idempotent: an already-migrated database runs only +/// the sweep. +pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> { + migrator("school") + .await? + .run(pool) + .await + .map_err(|err| AppError::from(sqlx::Error::from(err)))?; + + // An assistant turn is answered by a task in this process, so a restart + // can leave its row `pending` with nobody left to complete it. Only rows + // past the stale horizon (`CHATBOT_PENDING_STALE_SECS`) are certainly + // abandoned though: a young one may still be being answered on the other + // side of the AI bridge, and a deploy must not shoot down a turn + // dispatched seconds ago. Nothing is lost by waiting — a reader already + // presents an over-age `pending` row as failed, and the next boot sweeps + // for real whatever crossed the horizon in the meantime. + let now = Timestamp::now().as_millis(); + sqlx::query( + "UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted', + completed_at = $1 + WHERE status = 'pending' AND created_at < $2", + ) + .bind(now) + .bind(now - CHATBOT_PENDING_STALE_SECS * 1_000) + .execute(pool) + .await?; + Ok(()) +} + +/// Ensure the school-template database exists and carries the current school +/// schema. `CREATE DATABASE` runs on the control pool outside any +/// transaction; the loser of a race adopts the winner's database. +async fn ensure_template( + control: &PgPool, + base: &PgConnectOptions, + name: &str, +) -> Result<(), AppError> { + if let Err(err) = + sqlx::query(sqlx::AssertSqlSafe(create_database_sql("CREATE DATABASE", name))) + .execute(control) + .await { - return true; + if !is_duplicate_database(&err) { + return Err(err.into()); + } } - let message = err.to_string(); - message.contains("already exists") || message.contains("can be retried") + // One migrator connection, made and closed: the template is never served. + let pool = pool_options(1).connect_with(base.clone().database(name)).await?; + let migrated = migrate_school(&pool).await; + pool.close().await; + migrated } -/// Send one guarded single-statement write, re-sending it while the store -/// answers "conflict, retry", and hand back the rows it returned. -/// -/// The guard on such a statement reads a column a rival writes, so the two -/// contend on one record *by design* — that contention is what makes the guard -/// atomic. Losing a round writes nothing at all, which makes re-sending the -/// whole of the recovery; without it an ordinary raced `PATCH` or `DELETE` -/// answers 500 instead of the 404 or 409 it owes. Only for statements that -/// cannot produce "already exists" (the other thing [`lost_the_race`] matches), -/// so `UPDATE` and `DELETE` and not `CREATE`. -pub(crate) async fn write_with_retry( - db: &Database, - sql: &str, - bindings: &[(String, surrealdb::types::Value)], -) -> Result, AppError> { - let mut last = None; - for attempt in 0..CAP_WRITE_TRIES { - backoff(attempt).await; - let mut query = db.query(sql); - for (name, value) in bindings { - query = query.bind((name.clone(), value.clone())); - } - match async { query.await?.check()?.take::>(0) }.await { - Ok(rows) => return Ok(rows), - Err(err) if lost_the_race(&err) => last = Some(err), - Err(err) => return Err(err.into()), - } +/// `42P04` — the database already exists. The other side of every +/// "create it unless a rival got there first" move. +pub(crate) fn is_duplicate_database(err: &sqlx::Error) -> bool { + err.as_database_error() + .is_some_and(|db| db.code().as_deref() == Some("42P04")) +} + +/// The violated `UNIQUE` constraint's name, when `err` is a unique violation +/// (`23505`). The constraint name is the stable handle call sites map +/// refusals onto — `unique_violation(&e) == Some("school_pkey")` — and it is +/// borrowed from the error, not `'static`: the server owns the text. +pub fn unique_violation(err: &sqlx::Error) -> Option<&str> { + let db = err.as_database_error()?; + if db.code().as_deref() == Some("23505") { + db.constraint() + } else { + None } - Err(last - .map(AppError::from) - .unwrap_or_else(|| AppError::Internal("a guarded write never ran".into()))) } -/// Send one guarded `BEGIN…COMMIT` cascade, re-sending it while the store -/// answers "conflict, retry", and hand back both the response and the errors -/// drained off it. +/// A foreign-key violation (`23503`): a parent row a statement names is gone. +pub fn foreign_key_violation(err: &sqlx::Error) -> bool { + err.as_database_error() + .is_some_and(|db| db.code().as_deref() == Some("23503")) +} + +/// Is this error the transaction *contended*, rather than decided? `40001` +/// (serialization failure) and `40P01` (deadlock) are Postgres telling two +/// writers to take turns — the whole reason the retry loop below exists. +pub fn is_retryable_tx(err: &sqlx::Error) -> bool { + err.as_database_error().is_some_and(|db| { + let code = db.code(); + code.as_deref() == Some("40001") || code.as_deref() == Some("40P01") + }) +} + +/// [`is_retryable_tx`] plus the foreign-key violation. For **cascade** +/// transactions only: a child insert whose parent vanished mid-cascade means +/// a racing cascade is still in flight and a re-run sees the settled state — +/// but to a plain insert a `23503` is a real refusal (the parent is simply +/// gone), and retrying it would only burn the budget before returning the +/// same verdict. +pub fn is_retryable_cascade(err: &sqlx::Error) -> bool { + is_retryable_tx(err) || foreign_key_violation(err) +} + +/// Send one guarded `BEGIN…COMMIT` transaction, re-running it while Postgres +/// answers "contended, retry", and hand back the closure's value. /// -/// [`write_with_retry`]'s story, for the cascades that cannot be one statement: -/// the guard reads a column a rival writes, so the two contend on one record by -/// design, and a lost round aborts the transaction having written *nothing* — -/// which is what makes re-sending the whole of the recovery. +/// The closure writes through the transaction's connection (`&mut +/// PgConnection`), returns its value, and reports refusals as ordinary `Err`s +/// carrying exactly the `AppError` the web layer owes the caller. A refusal +/// is a *decision*, so it outranks the retry loop — only `AppError::Db` +/// errors that [`is_retryable_tx`] (or, when `cascade`, [`is_retryable_cascade`]) +/// recognise are re-sent; everything else comes straight back. /// -/// Both halves come back because the caller needs both and `take_errors` -/// consumes: the response carries the result slots, and only the error map can -/// tell a deliberate `THROW` from a lost round. `refusals` are the caller's -/// `THROW` markers and they are matched *first* — a `THROW` is a decision, and -/// it outranks a conflict. Everything after that ordering is why this exists: -/// an aborted transaction errors *every* slot, and all but the failing one say -/// a generic "not executed", which is the consequence of the abort and never a -/// reason of its own. Picking one of those out of the unordered `HashMap` — or -/// taking the first via `check()` — retired a retryable round as a 500, measured -/// on `Course::delete` at 1-3 of 20 raced rounds. +/// Isolation is Postgres's default **READ COMMITTED** everywhere. Invariants +/// that span rows are enforced by single-statement CTEs or row locks +/// (`FOR UPDATE` / `FOR NO KEY UPDATE`) inside the closure, not by stronger +/// isolation. +/// The closure is an [`AsyncFnMut`] (edition-2024 async closure, or a plain +/// closure whose async block the compiler infers as such) because every real +/// call site's future borrows the connection — a named `Fut` generic cannot +/// express that lifetime relationship. /// -/// [`write_with_retry`]'s restriction carries over, and a cascade makes it -/// easier to trip: no statement inside may be able to answer "already exists", -/// because that is the other thing [`lost_the_race`] matches and re-sending it -/// would just fail the same way until the tries run out — turning a 409 into a -/// 500, which is the exact defect this exists to prevent. The test to apply to -/// every statement in the batch is not which verb it uses but whether the store -/// could *legitimately* answer "already exists" to it — that answer is a -/// decision, and this loop cannot tell one from a conflict, so it would burn all -/// the tries re-asking a question already settled. `UPDATE` and `DELETE` never -/// can. A `CREATE` can, unless the id is unreachable by any rival: a freshly -/// generated ULID on a table with no `UNIQUE` index is such an id. An `UPSERT` -/// can, unless its id is *bijective* with every unique tuple its table indexes — -/// then the index entry can only ever point at the row the id already names, and -/// the write resolves onto it instead of colliding with it -/// ([`crate::domain::exam_result::ExamResult`]'s composite id is that shape). -/// A statement that fails this test belongs in front of the cascade, where its -/// 409 can be read as the answer it is. -pub(crate) async fn transaction_with_retry( - db: &Database, - sql: &str, - bindings: &[(String, surrealdb::types::Value)], - refusals: &[&str], -) -> Result< - ( - surrealdb::IndexedResults, - std::collections::HashMap, - ), - AppError, -> { - let mut last = None; +/// Isolation is Postgres's default **READ COMMITTED** everywhere. Invariants +/// that span rows are enforced by single-statement CTEs or row locks +/// (`FOR UPDATE` / `FOR NO KEY UPDATE`) inside the closure, not by stronger +/// isolation; if a transaction genuinely cannot be row-locked, escalate that +/// one to `SERIALIZABLE` (the retry loop already covers the `40001` it can +/// then raise) and record the reason in its own call site's comment. +/// +/// The budget and backoff are the guard layer's usual: `CAP_WRITE_TRIES` +/// rounds, `backoff`'s exponential-with-jitter wait, attempt zero waiting +/// not at all. +pub async fn tx_with_retry(pool: &PgPool, cascade: bool, mut f: F) -> Result +where + F: AsyncFnMut(&mut PgConnection) -> Result, +{ + let mut last: Option = None; for attempt in 0..CAP_WRITE_TRIES { backoff(attempt).await; - let mut query = db.query(sql); - for (name, value) in bindings { - query = query.bind((name.clone(), value.clone())); - } - let mut result = match query.await { - Ok(result) => result, - Err(err) if lost_the_race(&err) => { + let mut tx = pool.begin().await?; + match f(&mut tx).await { + Ok(value) => { + // A commit can itself lose the race — `40001` fires at COMMIT + // in Postgres — so the commit sits inside the classification. + match tx.commit().await { + Ok(()) => return Ok(value), + Err(err) if is_retryable(&err, cascade) => last = Some(err), + Err(err) => return Err(err.into()), + } + } + Err(AppError::Db(err)) if is_retryable(&err, cascade) => { + // The losing round wrote nothing durable, which is what makes + // re-sending the whole of the recovery. Settle the abort + // before the wait, so a connection is not left + // idle-in-transaction across the backoff. + let _ = tx.rollback().await; last = Some(err); - continue; } - Err(err) => return Err(err.into()), - }; - let mut errors = result.take_errors(); - let refused = |error: &surrealdb::Error| { - let message = error.to_string(); - refusals.iter().any(|marker| message.contains(marker)) - }; - if errors.values().any(refused) || !errors.values().any(lost_the_race) { - return Ok((result, errors)); + // A refusal is a decision. Same shape for a `Db` error the + // classifier does not recognise: it failed for a reason waiting + // cannot fix. + Err(err) => return Err(err), } - last = errors.drain().map(|(_, error)| error).find(lost_the_race); } - Err(last - .map(AppError::from) - .unwrap_or_else(|| AppError::Internal("a guarded cascade never ran".into()))) + Err(last.map(AppError::Db).unwrap_or_else(|| { + AppError::Internal("a guarded transaction never ran".into()) + })) +} + +fn is_retryable(err: &sqlx::Error, cascade: bool) -> bool { + if cascade { + is_retryable_cascade(err) + } else { + is_retryable_tx(err) + } } /// Wait out one lost round. Exponential with jitter, because racers arrive in @@ -229,75 +373,25 @@ pub(crate) async fn backoff(attempt: usize) { tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await; } -/// Dial the database, retrying until it answers. -/// -/// Never gives up, because giving up is worse than waiting: the database is -/// normally a sibling container booting in parallel, and a process that exits -/// on the first refusal gets restarted by the runtime, fails again in ~100ms, -/// and burns its whole restart budget inside a second — leaving the backend -/// permanently down over a startup skew that would have cleared on its own. -/// -/// Only the dial is retried. Bad credentials or a broken migration still fail -/// hard, since no amount of waiting fixes those. -async fn connect_with_retry(cfg: &Config) -> Surreal { - let mut backoff = 1; - loop { - match surrealdb::engine::any::connect(cfg.db_url.clone()).await { - Ok(db) => return db, - Err(err) => { - tracing::warn!( - "database at {} unreachable ({err}) — retrying in {backoff}s", - cfg.db_url - ); - tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; - backoff = (backoff * 2).min(crate::constant::DB_CONNECT_BACKOFF_MAX_SECS); - } - } +/// The `BUILDER_USERNAME` / `BUILDER_PASSWORD` bootstrap pair, if configured. +/// Both-or-neither: half a pair aborts startup rather than silently running +/// without the seed — and without a builder, a fresh deployment has nobody who +/// can create the first school. +fn builder_credentials(cfg: &Config) -> Result, AppError> { + match (&cfg.builder_username, &cfg.builder_password) { + (Some(username), Some(password)) => Ok(Some(( + Username::try_new(username) + .map_err(|err| AppError::Internal(format!("invalid BUILDER_USERNAME: {err}")))?, + Password::try_new(password) + .map_err(|err| AppError::Internal(format!("invalid BUILDER_PASSWORD: {err}")))?, + ))), + (None, None) => Ok(None), + _ => Err(AppError::Internal( + "BUILDER_USERNAME and BUILDER_PASSWORD must be set together".into(), + )), } } -/// A fresh in-memory **school** database with the school schema applied. For -/// the unit tests whose subject is one school's own rows; a test that needs the -/// whole app (control database included) wants [`init_mem_tenants`]. -pub async fn init_mem() -> Result { - let db = surrealdb::engine::any::connect("memory").await?; - db.use_ns("hezarfen").use_db("hezarfen").await?; - migrate(&db).await?; - Ok(std::sync::Arc::new(db)) -} - -/// A fresh in-memory deployment: an empty control database plus one school, -/// [`crate::tenant::DEMO_SLUG`]. The bootstrap every router-level test uses. -pub async fn init_mem_tenants() -> Result { - let tenants = Tenants::new_mem().await?; - let demo = crate::tenant::Slug::try_new(crate::tenant::DEMO_SLUG) - .map_err(|err| AppError::Internal(format!("the demo slug is a slug: {err}")))?; - tenants - .create(&demo, "Demo School", crate::module::ModuleSet::all()) - .await?; - Ok(tenants) -} - -/// A handle on a **real** SurrealDB server, in a scratch namespace of its own -/// that is dropped and re-made on every call. For the tests whose subject is -/// the store's own conflict detection, which [`init_mem`]'s embedded engine -/// does not have: it drops one of two concurrent writes to a record and answers -/// `Ok` to both (see [`crate::db::cap`]), which *forges* the very -/// integrity failure those tests exist to catch — measured 2026-07-30 at 2 -/// failed runs in 36 on `memory`, against 0 in 10 000 rounds here. -/// -/// Every caller is `#[ignore]`d, so a machine with no server prints them as -/// `ignored` rather than passing: this is not a test that may quietly skip. -/// `HEZARFEN_TEST_DB` overrides the address; the credentials are `compose.yaml`'s. -/// -/// The guard handed back with the handle serializes these tests against each -/// other and must be held for the whole test — hence the tuple, which cannot be -/// forgotten the way a separate `lock()` line can. `cargo test -- --ignored` -/// runs them in parallel, and while each has a namespace to itself they all -/// burst against the *one* server: their beats are sub-millisecond, so a -/// sibling's burst pushes a delete clean out of the window it is meant to land -/// in (measured 4 runs in 4 at 3 of 6 failing their own "the race was reached" -/// guard). Serialized, the plain documented command works. #[cfg(test)] mod builder_seed_tests { use super::builder_credentials; @@ -330,1015 +424,3 @@ mod builder_seed_tests { } } -#[cfg(test)] -pub(crate) static RACE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); - -#[cfg(test)] -pub(crate) async fn init_test_server( - scratch: &str, -) -> (Database, tokio::sync::MutexGuard<'static, ()>) { - let serialized = RACE_LOCK.lock().await; - let url = - std::env::var("HEZARFEN_TEST_DB").unwrap_or_else(|_| "ws://127.0.0.1:8000".to_string()); - let db = surrealdb::engine::any::connect(url.clone()) - .await - .unwrap_or_else(|err| panic!("no SurrealDB server at {url} ({err})")); - db.signin(Root { - username: "root".into(), - password: "root".into(), - }) - .await - .expect("sign in to the test server"); - let ns = format!("test_{scratch}"); - db.query(format!("REMOVE NAMESPACE IF EXISTS {ns}")) - .await - .expect("clear the scratch namespace") - .check() - .expect("clear the scratch namespace"); - db.use_ns(ns.clone()).use_db(ns).await.expect("scratch ns"); - let db = std::sync::Arc::new(db); - migrate(&db).await.expect("migrate the scratch namespace"); - (db, serialized) -} - -/// Apply the schema + backfills. Idempotent — `init` runs it on every boot, -/// and tests re-run it on a live handle to simulate a second boot. -pub async fn migrate(db: &Surreal) -> Result<(), AppError> { - for sql in MIGRATION_BATCHES { - let mut query = db.query(sql); - for (name, value) in migration_binds() { - query = query.bind((name, value)); - } - query.await?.check()?; - } - Ok(()) -} - -/// Apply the **control** schema (schools, builders, the shared rate-limit -/// window). Idempotent, like [`migrate`]. -pub async fn migrate_control(db: &Surreal) -> Result<(), AppError> { - // The one data-driven parameter in this batch: the module list a school - // written before entitlements existed is backfilled to. - let all_modules = crate::module::ModuleSet::all().names(); - for sql in CONTROL_MIGRATION_BATCHES { - db.query(sql) - .bind(("all_modules", all_modules.clone())) - .await? - .check()?; - } - Ok(()) -} - -/// Parameters the batches are executed with. Bound, not baked into the SQL -/// string: a `const` cannot be interpolated into another `const`, and a -/// hand-copied 300000 would drift silently. The one-time blocks' fingerprints -/// ride along — see [`marked_blocks`]. Bound to all three batches, which is -/// free: an unused parameter is not an error. -fn migration_binds() -> Vec<(String, i64)> { - let mut binds = vec![("stale_ms".to_string(), CHATBOT_PENDING_STALE_SECS * 1_000)]; - binds.extend(marked_blocks()); - binds -} - -/// The line every one-time block in [`BACKFILL`] opens with. The name straight -/// after it is the block's `migration_mark` key, and `fp_` is the -/// parameter its fingerprint is bound to — so a block written in this idiom is -/// found, hashed and bound with nothing to keep by hand. A block written any -/// other way silently gets no fingerprint, which is what -/// `every_one_time_block_is_fingerprinted` exists to catch. -const MARK_GATE: &str = "IF array::len((SELECT VALUE id FROM migration_mark:"; - -/// Every one-time block in [`BACKFILL`], as (`fp_`, hash of its own SQL). -/// -/// A `migration_mark` used to say only *that* a block had run, which made a -/// marked block's content permanently uncorrectable: an edit to it never ran on -/// any volume that had booted once. The mark now stores this number and the -/// gate compares it against the number this binary computes, so an edited block -/// runs one more time and re-stamps. There is nothing to remember to bump — the -/// hash comes from the very string the server executes, which is the whole -/// point: a hand-kept version is the same discipline failure in a new place. -/// -/// Hashed from the gate through the stamp with comments and indentation -/// dropped: every re-run costs something (the `profile_counters` block says -/// what, in its own comment), so re-wording a comment must not trigger one. -fn marked_blocks() -> Vec<(String, i64)> { - let mut blocks = Vec::new(); - let mut rest = BACKFILL; - while let Some(at) = rest.find(MARK_GATE) { - let block = &rest[at..]; - let name: String = block[MARK_GATE.len()..] - .chars() - .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') - .collect(); - let stamp = format!("UPSERT migration_mark:{name}"); - let end = block - .find(&stamp) - .and_then(|from| block[from..].find(';').map(|to| from + to + 1)) - .unwrap_or_else(|| panic!("the `{name}` block never stamps its own mark")); - blocks.push((format!("fp_{name}"), block_fingerprint(&block[..end]))); - rest = &block[end..]; - } - blocks -} - -/// FNV-1a over a block's statements, comments and layout dropped. -/// -/// Hand-rolled rather than [`std::hash`]: this number is *stored*, so it has to -/// mean the same thing after a compiler upgrade, and `DefaultHasher` promises -/// nothing across versions — a hash that drifted on its own would re-run every -/// one-time block on every volume. -fn block_fingerprint(block: &str) -> i64 { - let mut hash: u64 = 0xcbf2_9ce4_8422_2325; - for line in block - .lines() - .map(str::trim) - .filter(|line| !line.is_empty() && !line.starts_with("--")) - { - for byte in line.bytes().chain(std::iter::once(b'\n')) { - hash = (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3); - } - } - hash as i64 -} - -#[cfg(test)] -mod tests { - - /// The fingerprint has to move when a *statement* moves and stay put when - /// prose does: a re-run is never free (see the `profile_counters` comment), - /// and a fingerprint that ignored an edit would put us back where this - /// mechanism started — a marked block nobody can correct. - #[test] - fn a_block_fingerprint_tracks_statements_not_prose() { - let block = "IF x = 0 {\n -- why this runs\n UPDATE t SET a = 1;\n};"; - let reworded = "IF x = 0 {\n -- why this runs, at length\n UPDATE t SET a = 1;\n};"; - let edited = "IF x = 0 {\n -- why this runs\n UPDATE t SET a = 2;\n};"; - assert_eq!( - super::block_fingerprint(block), - super::block_fingerprint(reworded), - "a re-worded comment or a re-indent must not re-run a one-time block" - ); - assert_ne!( - super::block_fingerprint(block), - super::block_fingerprint(edited), - "an edited statement must re-run its block" - ); - } - - /// The forcing function: a one-time block written outside the gate idiom - /// gets no fingerprint parameter, and its `$fp_…` would bind to nothing — a - /// gate that then matches every mark and skips forever. Nothing about the - /// compiler notices, so this does. - #[test] - fn every_one_time_block_is_fingerprinted() { - let blocks = super::marked_blocks(); - let names: Vec<&str> = blocks.iter().map(|(name, _)| name.as_str()).collect(); - assert_eq!( - names, - ["fp_board_roster", "fp_profile_counters"], - "{names:?}" - ); - assert_ne!(blocks[0].1, blocks[1].1, "two blocks, two fingerprints"); - // Two mentions of the mark table per block — its gate and its stamp. A - // third, or a block gated some other way, means a block the binder - // never saw. - assert_eq!( - super::BACKFILL.matches("migration_mark:").count(), - blocks.len() * 2, - "a one-time block outside the `{}…` idiom is invisible to the binder", - super::MARK_GATE - ); - for (param, _) in &blocks { - assert!( - super::BACKFILL.contains(&format!("${param}")), - "nothing reads ${param}" - ); - } - } - - /// The fingerprint the mark for `name` must carry once its block has run. - fn expected_fingerprint(name: &str) -> i64 { - super::marked_blocks() - .into_iter() - .find(|(param, _)| *param == format!("fp_{name}")) - .unwrap_or_else(|| panic!("no one-time block named {name}")) - .1 - } - - async fn stamped_fingerprint(db: &super::Database, name: &str) -> Vec> { - let mut rows = db - .query(format!( - "SELECT VALUE fingerprint FROM migration_mark:{name}" - )) - .await - .unwrap(); - rows.take(0).unwrap() - } - - /// The admin seed must not be interruptible into a state no later boot can - /// repair. `create` + `set_role` was: killed between the two writes it - /// leaves a *student* row holding ADMIN_USERNAME, which `ensure_admin` then - /// refuses to promote on every subsequent boot (rightly — it cannot tell - /// that row from a stranger who registered the name first). The row is - /// therefore minted with its role in one statement, and this pins that. - #[test] - fn the_admin_seed_mints_the_role_with_the_row() { - let source = - std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/service/user.rs")) - .expect("read service/user.rs"); - let start = source - .find("pub async fn ensure_admin") - .expect("ensure_admin is declared"); - let body = &source[start..start + source[start..].find("\n }\n").expect("body ends")]; - assert!( - !body.contains("set_role"), - "ensure_admin promotes after creating; an interruption between those two writes \ - leaves a student account on ADMIN_USERNAME that no boot can heal:\n{body}" - ); - assert!( - body.contains("create_with_role"), - "the seed must mint the row with Role::Admin in one statement" - ); - } - - #[tokio::test] - async fn boot_fails_chatbot_messages_left_pending() { - let db = super::init_mem().await.unwrap(); - db.query( - "CREATE user:u SET username = 'u', password_hash = 'x'; - CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1; - CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u, - role = 'assistant', content = '', status = 'pending', created_at = 1; - CREATE chatbot_message:done SET thread_id = chatbot_thread:c, user_id = user:u, - role = 'assistant', content = 'hi', status = 'complete', created_at = 1;", - ) - .await - .unwrap() - .check() - .unwrap(); - - // A second boot: the task that would have answered `m` died with the - // previous process, so the row is failed rather than left waiting. - super::migrate(&db).await.unwrap(); - - let mut rows = db - .query("SELECT id, status, error_code, completed_at FROM chatbot_message ORDER BY id") - .await - .unwrap(); - let rows: Vec = rows.take(0).unwrap(); - // An already-answered turn is untouched; the pending one is failed. - let done = &rows[0]; - let interrupted = &rows[1]; - assert_eq!(done["status"], "complete"); - assert_eq!(done["error_code"], serde_json::Value::Null); - assert_eq!(interrupted["status"], "failed"); - assert_eq!(interrupted["error_code"], "interrupted"); - assert!(interrupted["completed_at"].as_i64().unwrap() > 0); - } - - /// Stale-data path for the 2026-07-30 fee-plan refcount. A dev volume - /// carries plans and assignments written before the counter column existed, - /// and an absent counter reads as **zero** — which is exactly the value - /// that licenses an edit and a delete. Unseeded, every already-assigned - /// plan on every existing volume would go editable and deletable again, so - /// the backfill is the whole of the stale-data story, not a nicety. - #[tokio::test] - async fn a_plan_assigned_before_the_counter_existed_is_still_refused() { - use crate::db::fee_plan; - use crate::domain::fee_plan::{FeePlanId, FeePlanName}; - use crate::error::AppError; - - let db = super::init_mem().await.unwrap(); - // The old shape: rows stating every column the older binary knew, and - // no `assignment_count` at all. `used` carries an assignment, `free` - // does not — a plan nobody is on must stay editable. - db.query( - "CREATE user:m SET username = 'm', password_hash = 'x'; - CREATE user:s SET username = 's', password_hash = 'x'; - CREATE fee_plan:used SET name = 'Yearly', - installments = [{ amount_minor: 100, due_at: 1 }], - created_by = user:m, created_at = 1; - CREATE fee_plan:free SET name = 'Unused', - installments = [{ amount_minor: 100, due_at: 1 }], - created_by = user:m, created_at = 1; - CREATE fee_plan_assignment:used_s SET plan = fee_plan:used, - student = user:s, assigned_by = user:m, created_at = 1;", - ) - .await - .unwrap() - .check() - .unwrap(); - - // Twice: every boot runs the backfill, and a second pass must not - // double a counter it already seeded. - super::migrate(&db).await.unwrap(); - super::migrate(&db).await.unwrap(); - - let mut counts = db - .query("SELECT VALUE assignment_count FROM fee_plan ORDER BY id") - .await - .unwrap(); - let counts: Vec> = counts.take(0).unwrap(); - // `free` before `used` by id; the unused plan is deliberately left - // absent, which already reads as zero in the guard. - assert_eq!(counts, vec![None, Some(1)]); - - // The load-bearing half: the seeded plan is frozen, and the untouched - // one is not. - let used = fee_plan::read(&db, &FeePlanId::from_key("used")) - .await - .unwrap() - .unwrap(); - assert!(matches!( - fee_plan::update( - &db, - used.clone(), - Some(FeePlanName::try_new("Edited").unwrap()), - None - ) - .await, - Err(AppError::Conflict(_)) - )); - assert!(!fee_plan::delete(&db, used).await.unwrap()); - let free = fee_plan::read(&db, &FeePlanId::from_key("free")) - .await - .unwrap() - .unwrap(); - assert!( - fee_plan::update( - &db, - free.clone(), - Some(FeePlanName::try_new("Edited").unwrap()), - None - ) - .await - .is_ok() - ); - assert!(fee_plan::delete(&db, free).await.unwrap()); - } - - /// Stale-data path for the 2026-08-02 board-roster repair. `set_role` - /// sweeps a demoted user off every board going forward, but an existing - /// volume still names parents on rosters — and ids of users deleted before - /// any sweep existed. Both freeze the creator's roster `PATCH` at a 400 - /// (see `web::boards::resolve_participants`), so boot has to clean them. - #[tokio::test] - async fn a_board_roster_written_before_the_sweep_is_repaired_at_boot() { - let db = super::init_mem().await.unwrap(); - db.query( - "CREATE user:s SET username = 's', password_hash = 'x', role = 'student'; - CREATE user:p SET username = 'p', password_hash = 'x', role = 'parent'; - CREATE board:keep SET creator = user:s, title = 'B', - participants = [user:s, user:p, user:ghost], created_at = 1; - CREATE board:gone SET creator = user:s, title = 'C', - participants = [user:p], created_at = 1; - CREATE board:clean SET creator = user:s, title = 'D', - participants = [user:s], created_at = 1; - DELETE migration_mark:board_roster;", - ) - .await - .unwrap() - .check() - .unwrap(); - // `init_mem` boots a *migrated* database, so it has already marked the - // repair done on an empty store — which is right, and is exactly why the - // mark is dropped here: a volume written before the mark existed carries - // stale rosters and no mark at all, and that is the state under test. - // A write probe on the table under repair: the event fires *inside* the - // UPDATE, so it counts real writes rather than trusting a re-read. - db.query( - "DEFINE TABLE board_write_probe SCHEMALESS; - DEFINE EVENT board_write ON board WHEN $event = 'UPDATE' THEN { - UPSERT type::record('board_write_probe', 'n') SET n = (n ?? 0) + 1; - };", - ) - .await - .unwrap() - .check() - .unwrap(); - - super::migrate(&db).await.unwrap(); - - async fn rosters(db: &super::Database) -> Vec> { - let mut rows = db - .query("SELECT VALUE participants FROM board ORDER BY id") - .await - .unwrap(); - rows.take(0).unwrap() - } - let after_first = rosters(&db).await; - let s = surrealdb::types::RecordId::new("user", "s"); - // `clean`, `gone`, `keep` by id. The parent and the vanished user are - // both gone; a board whose whole roster was stale ends empty, which is - // the same shape a board opened without invites carries. - assert_eq!( - after_first, - vec![vec![s.clone()], vec![], vec![s.clone()]], - "{after_first:?}" - ); - - async fn writes(db: &super::Database) -> Vec { - let mut rows = db - .query("SELECT VALUE n FROM board_write_probe:n") - .await - .unwrap(); - rows.take(0).unwrap() - } - assert_eq!( - writes(&db).await, - vec![2], - "only the two stale rows repaired" - ); - - // The second boot: every boot runs the backfill, and a converged row - // must not be written again. - super::migrate(&db).await.unwrap(); - assert_eq!(rosters(&db).await, after_first); - assert_eq!(writes(&db).await, vec![2], "the second pass wrote nothing"); - - // …and it did not *look*, either, which is the whole point of the mark: - // the repair's cost is a `user` table scan per board, and writing - // nothing is not the same as scanning nothing. A roster made stale after - // the mark landed is the probe — it survives the next boot untouched, - // which no converging `WHERE` could produce. - let mut mark = db - .query("SELECT VALUE done_at FROM migration_mark:board_roster") - .await - .unwrap(); - assert_eq!( - mark.take::>(0).unwrap().len(), - 1, - "the repair marks itself finished" - ); - // …with the fingerprint of the text it ran, which is what a later edit - // to this block is compared against. - assert_eq!( - stamped_fingerprint(&db, "board_roster").await, - vec![Some(expected_fingerprint("board_roster"))] - ); - db.query("CREATE board:late SET creator = user:s, title = 'E', participants = [user:p], created_at = 1") - .await - .unwrap() - .check() - .unwrap(); - super::migrate(&db).await.unwrap(); - assert_eq!( - rosters(&db).await, - vec![ - vec![s.clone()], - vec![], - vec![s.clone()], - vec![surrealdb::types::RecordId::new("user", "p")] - ], - "a marked database skips the scan entirely" - ); - assert_eq!(writes(&db).await, vec![2]); - } - - /// Stale-data path for the 2026-08-04 badge counters. Every account on an - /// existing volume predates the columns, and a badge is decided off the - /// stored total — so a zero start would not lose a number, it would - /// permanently mis-award the student who really did the work. Boot seeds the - /// counters from the rows that exist, exactly once. - #[tokio::test] - async fn the_badge_counters_are_seeded_from_history_exactly_once() { - let db = super::init_mem().await.unwrap(); - db.query( - "CREATE user:a SET username = 'a', password_hash = 'x', role = 'student'; - CREATE user:b SET username = 'b', password_hash = 'x', role = 'student'; - CREATE user:c SET username = 'c', password_hash = 'x', role = 'student'; - CREATE homework:h SET course = course:c, subject = subject:s, title = 'H', - due_at = 100, created_by = user:a, created_at = 1; - -- Three on time (the equal case counts as on time) and one whose - -- homework was deleted out from under it: that last one is - -- submitted but not on time, because the traversal yields nothing. - CREATE homework_submission:s1 SET homework = homework:h, user = user:a, - submitted_at = 50, updated_at = 50; - CREATE homework_submission:s2 SET homework = homework:h, user = user:a, - submitted_at = 60, updated_at = 100; - -- Handed in before the deadline, then edited well after it — a - -- `touch()` from a single file add does this. On time, because the - -- live path credits the hand-in and debits by `submitted_at`; if - -- the seed judged this one by `updated_at` a later withdrawal - -- would decrement a credit that was never given. - CREATE homework_submission:s3 SET homework = homework:h, user = user:a, - submitted_at = 70, updated_at = 200; - CREATE homework_submission:s4 SET homework = homework:gone, user = user:a, - submitted_at = 80, updated_at = 1; - CREATE exam_attempt:e1 SET exam = exam:x, user = user:a, seq = 1, started_at = 1; - CREATE exam_attempt:e2 SET exam = exam:y, user = user:a, seq = 1, started_at = 2; - -- Two finished stints and one still open, which counts for neither. - CREATE pomodoro_session:p1 SET user = user:a, started_at = 1000, finished_at = 2000; - CREATE pomodoro_session:p2 SET user = user:a, started_at = 5000, finished_at = 7500; - CREATE pomodoro_session:p3 SET user = user:a, started_at = 9000; - -- One real stint beside one written with a backwards clock. The - -- floor is per row, like the live close, so the negative one - -- contributes zero and the real 1000ms survives; flooring the - -- per-user sum instead would seed 0 and lose the real stint. - CREATE pomodoro_session:p4 SET user = user:c, started_at = 0, finished_at = 1000; - CREATE pomodoro_session:p5 SET user = user:c, started_at = 9000, finished_at = 3000; - DELETE migration_mark:profile_counters;", - ) - .await - .unwrap() - .check() - .unwrap(); - // `init_mem` boots a *migrated* database, so the seed is already marked - // done on an empty store — which is right, and is exactly why the mark is - // dropped here: a volume written before the columns existed carries - // history and no mark at all, and that is the state under test. - // A write probe on the table being seeded: the event fires *inside* the - // UPDATE, so it counts real writes rather than trusting a re-read. - db.query( - "DEFINE TABLE user_write_probe SCHEMALESS; - DEFINE EVENT user_write ON user WHEN $event = 'UPDATE' THEN { - UPSERT type::record('user_write_probe', 'n') SET n = (n ?? 0) + 1; - };", - ) - .await - .unwrap() - .check() - .unwrap(); - - super::migrate(&db).await.unwrap(); - - async fn counters(db: &super::Database) -> Vec<(i64, i64, i64, i64, i64)> { - let mut rows = db - .query( - "SELECT VALUE [homework_submitted_total, homework_on_time_total, - exam_sat_total, pomodoro_finished_total, - pomodoro_focus_ms_total] - FROM user ORDER BY id", - ) - .await - .unwrap(); - rows.take::>>(0) - .unwrap() - .into_iter() - .map(|row| (row[0], row[1], row[2], row[3], row[4])) - .collect() - } - let after_first = counters(&db).await; - // `a`, `b`, `c` by id. `b` has no history at all and reads as a fresh - // account; `c` keeps the 1000ms real stint the -6000ms one sits beside. - assert_eq!( - after_first, - vec![(4, 3, 2, 2, 3500), (0, 0, 0, 0, 0), (0, 0, 0, 2, 1000)], - "{after_first:?}" - ); - - // The seed also stamps each submission with the verdict it was counted - // under, because `due_at` is mutable: a withdrawal after the teacher - // moves the deadline must debit what was credited, not what the - // deadline says by then. Asserted through `WHERE` rather than read back - // as a column, so an unstamped row would show up as belonging to - // neither set instead of deserializing as some default. - async fn stamped(db: &super::Database, cond: &str) -> Vec { - let mut rows = db - .query(format!( - "SELECT VALUE record::id(id) FROM homework_submission - WHERE {cond} ORDER BY id" - )) - .await - .unwrap(); - rows.take(0).unwrap() - } - // s1/s2/s3 beat the deadline (50, 60, 70 vs 100). s4 hangs off a - // deleted homework, so `submitted_at <= homework.due_at` compares - // against NONE and lands on `false` — which is exactly what the count - // above credited it as, so the stamp agrees with the counter rather - // than leaving the row to a fallback that could later disagree. - assert_eq!( - stamped(&db, "counted_on_time = true").await, - ["s1", "s2", "s3"] - ); - assert_eq!(stamped(&db, "counted_on_time = false").await, ["s4"]); - - async fn writes(db: &super::Database) -> Vec { - let mut rows = db - .query("SELECT VALUE n FROM user_write_probe:n") - .await - .unwrap(); - rows.take(0).unwrap() - } - let first_writes = writes(&db).await; - // Pinned non-zero, not just compared: "the second pass wrote nothing" - // would hold vacuously if the probe itself stopped firing, and then the - // test would pass on a seed that never ran. - assert!( - matches!(first_writes.as_slice(), [n] if *n > 0), - "{first_writes:?}" - ); - - // The second boot: every boot runs the backfill, and a recount here - // would not converge the way the counters above it do — these columns - // are maintained by the request path from now on, so a second pass would - // overwrite everything earned since. It must not write at all… - super::migrate(&db).await.unwrap(); - assert_eq!(counters(&db).await, after_first); - assert_eq!( - writes(&db).await, - first_writes, - "the second pass wrote nothing" - ); - - // …and it must not *look*, either, which is the whole point of the mark: - // writing nothing is not the same as scanning nothing. A submission that - // lands after the mark is the probe — its counter stays where the request - // path left it, which no recomputing backfill could produce. - let mut mark = db - .query("SELECT VALUE done_at FROM migration_mark:profile_counters") - .await - .unwrap(); - assert_eq!( - mark.take::>(0).unwrap().len(), - 1, - "the seed marks itself finished" - ); - assert_eq!( - stamped_fingerprint(&db, "profile_counters").await, - vec![Some(expected_fingerprint("profile_counters"))] - ); - db.query( - "CREATE homework_submission:late SET homework = homework:h, user = user:b, - submitted_at = 90, updated_at = 90;", - ) - .await - .unwrap() - .check() - .unwrap(); - super::migrate(&db).await.unwrap(); - assert_eq!( - counters(&db).await, - after_first, - "a mark carrying this binary's fingerprint skips the seed entirely" - ); - assert_eq!(writes(&db).await, first_writes); - } - - /// A marked block's *content* has to be correctable (2026-08-05). The mark - /// used to record only that the block had run, so an edit to a marked block - /// silently never ran on any volume that had booted once — which is how the - /// `exam_sat_total` seed below (fixed to count sittings, not attempts) - /// would have reached exactly nobody. The mark carries the fingerprint of - /// the text it ran, and a different fingerprint runs the block once more. - #[tokio::test] - async fn an_edited_one_time_block_runs_once_more_and_restamps() { - let db = super::init_mem().await.unwrap(); - // `init_mem` migrates an empty store, so the seed is already marked - // done — the state every booted volume is in. History written *after* - // that mark is the probe: a skip has to leave it uncounted, and a - // re-run has to pick it up. - db.query( - "CREATE user:a SET username = 'a', password_hash = 'x', role = 'student'; - -- One sitting, taken twice. The corrected seed counts the exam, - -- not the attempts, exactly as the request path credits it. - CREATE exam_attempt:e1 SET exam = exam:x, user = user:a, seq = 1, started_at = 1; - CREATE exam_attempt:e2 SET exam = exam:x, user = user:a, seq = 2, started_at = 2; - CREATE pomodoro_session:p1 SET user = user:a, started_at = 1000, finished_at = 2000;", - ) - .await - .unwrap() - .check() - .unwrap(); - - async fn counters(db: &super::Database) -> Vec<(i64, i64)> { - let mut rows = db - .query( - // `?? 0`, parenthesized: the columns are `option` and - // a row the seed has not touched holds neither. - "SELECT VALUE [(exam_sat_total ?? 0), (pomodoro_finished_total ?? 0)] - FROM user ORDER BY id", - ) - .await - .unwrap(); - rows.take::>>(0) - .unwrap() - .into_iter() - .map(|row| (row[0], row[1])) - .collect() - } - let fp = expected_fingerprint("profile_counters"); - - // Same binary, same fingerprint: the block does not run, and the - // history above stays uncounted. That is the mark still doing its job. - super::migrate(&db).await.unwrap(); - assert_eq!(counters(&db).await, vec![(0, 0)]); - assert_eq!( - stamped_fingerprint(&db, "profile_counters").await, - vec![Some(fp)] - ); - - // A write probe on the seeded table, defined now so it counts only the - // runs under test: the event fires *inside* the UPDATE, so "exactly - // once" is measured rather than inferred from the numbers. - db.query( - "DEFINE TABLE user_write_probe SCHEMALESS; - DEFINE EVENT user_write ON user WHEN $event = 'UPDATE' THEN { - UPSERT type::record('user_write_probe', 'n') SET n = (n ?? 0) + 1; - }; - -- A mark written by the binary before fingerprints existed: the - -- row is there, the column is not. This is the live volumes' - -- state, and it must run the corrected block exactly once. - UPDATE migration_mark:profile_counters UNSET fingerprint;", - ) - .await - .unwrap() - .check() - .unwrap(); - assert_eq!( - stamped_fingerprint(&db, "profile_counters").await, - vec![None] - ); - - super::migrate(&db).await.unwrap(); - // Two attempt rows, one exam: the corrected seed says one sitting, the - // number the request path would have given. The old text said two. - assert_eq!(counters(&db).await, vec![(1, 1)]); - assert_eq!( - stamped_fingerprint(&db, "profile_counters").await, - vec![Some(fp)] - ); - - async fn writes(db: &super::Database) -> Vec { - let mut rows = db - .query("SELECT VALUE n FROM user_write_probe:n") - .await - .unwrap(); - rows.take(0).unwrap() - } - let one_run = writes(&db).await; - // Pinned non-zero, not merely compared: "it did not run twice" holds - // vacuously if the probe stopped firing, and the test would then pass - // on a mechanism that never runs anything at all. - assert!(matches!(one_run.as_slice(), [n] if *n > 0), "{one_run:?}"); - - // Once more, not on every boot: the re-run re-stamped, so the next boot - // is a plain skip again. - super::migrate(&db).await.unwrap(); - assert_eq!(counters(&db).await, vec![(1, 1)]); - assert_eq!(writes(&db).await, one_run, "the re-run happened once"); - - // And now the edit this whole mechanism exists for: a mark whose stored - // fingerprint is some *other* text's. The block runs again and lands on - // the same numbers — every SET is absolute, so a re-run converges - // instead of doubling what the first pass wrote. - db.query("UPDATE migration_mark:profile_counters SET fingerprint = 1") - .await - .unwrap() - .check() - .unwrap(); - super::migrate(&db).await.unwrap(); - assert_eq!( - counters(&db).await, - vec![(1, 1)], - "a re-run recomputes, it does not add to what is there" - ); - assert_eq!( - writes(&db).await, - vec![one_run[0] * 2], - "the edited block did the same work a second time, and no more" - ); - assert_eq!( - stamped_fingerprint(&db, "profile_counters").await, - vec![Some(fp)] - ); - super::migrate(&db).await.unwrap(); - assert_eq!(writes(&db).await, vec![one_run[0] * 2], "and stopped again"); - } - - #[tokio::test] - async fn the_retired_claim_columns_are_dropped_off_a_live_row() { - // Stale-data path for the 2026-07-30 removal of the chat claim queue. - // A dev volume carries `chatbot_message` rows *with* claim values and an - // `ai_worker` table, so the boot has to clear the values while their - // definitions still stand (PRE_REPAIR) and only then retire the columns - // — SCHEMAFULL rejects every write to a row storing a column that no - // longer exists, which would make the row unanswerable forever. - let db = super::init_mem().await.unwrap(); - db.query( - "DEFINE FIELD claimed_by ON chatbot_message TYPE option; - DEFINE FIELD claimed_at ON chatbot_message TYPE option; - DEFINE TABLE ai_worker SCHEMAFULL; - DEFINE FIELD seen_at ON ai_worker TYPE int; - DEFINE TABLE migration_lock SCHEMALESS;", - ) - .await - .unwrap() - .check() - .unwrap(); - db.query( - "CREATE user:u SET username = 'u', password_hash = 'x'; - CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1; - CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u, - role = 'assistant', content = '', status = 'pending', - created_at = time::unix(time::now()) * 1000, - claimed_by = 'a-dead-replica', claimed_at = 1; - CREATE ai_worker:w SET seen_at = 1; - CREATE migration_lock:the_lock SET holder = 'a-dead-replica', expires_at = 1;", - ) - .await - .unwrap() - .check() - .unwrap(); - - // Twice: the repair and both removals have to be idempotent, since - // every boot runs them. - super::migrate(&db).await.unwrap(); - super::migrate(&db).await.unwrap(); - - let mut info = db.query("INFO FOR TABLE chatbot_message").await.unwrap(); - let table: serde_json::Value = info.take::>(0).unwrap().unwrap(); - let fields = table["fields"].as_object().expect("fields"); - assert!(!fields.contains_key("claimed_by"), "{table}"); - assert!(!fields.contains_key("claimed_at"), "{table}"); - let mut tables = db.query("INFO FOR DB").await.unwrap(); - let dbinfo: serde_json::Value = tables - .take::>(0) - .unwrap() - .unwrap(); - let tables = dbinfo["tables"].as_object().expect("tables"); - assert!(!tables.contains_key("ai_worker"), "{dbinfo}"); - // Same story one table over: the elected-boot lease, stale leader row - // and all. - assert!(!tables.contains_key("migration_lock"), "{dbinfo}"); - - // The load-bearing half: the row that carried a claim is still - // writable. A leftover value under no definition fails here. - db.query("UPDATE chatbot_message:m SET status = 'complete', content = 'ok'") - .await - .unwrap() - .check() - .unwrap(); - let mut row = db - .query("SELECT * FROM ONLY chatbot_message:m") - .await - .unwrap(); - let row: serde_json::Value = row.take::>(0).unwrap().unwrap(); - assert_eq!(row["status"], "complete", "{row}"); - assert!(row.get("claimed_by").is_none(), "{row}"); - } - - /// The other half of the sweep: a restart seconds after a dispatch must not - /// kill the turn — the answering task may still be alive on the other side - /// of the bridge, and the row is not yet past the stale horizon. - #[tokio::test] - async fn boot_spares_a_chatbot_message_pending_since_just_now() { - let db = super::init_mem().await.unwrap(); - db.query( - "CREATE user:u SET username = 'u', password_hash = 'x'; - CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1; - CREATE chatbot_message:fresh SET thread_id = chatbot_thread:c, user_id = user:u, - role = 'assistant', content = '', status = 'pending', - created_at = time::unix(time::now()) * 1000 - 2000; - CREATE chatbot_message:old SET thread_id = chatbot_thread:c, user_id = user:u, - role = 'assistant', content = '', status = 'pending', - created_at = time::unix(time::now()) * 1000 - - ($stale + 1) * 1000;", - ) - .bind(("stale", crate::constant::CHATBOT_PENDING_STALE_SECS)) - .await - .unwrap() - .check() - .unwrap(); - - super::migrate(&db).await.unwrap(); - - let mut res = db - .query( - "SELECT status, error_code FROM ONLY chatbot_message:fresh; - SELECT VALUE status FROM ONLY chatbot_message:old;", - ) - .await - .unwrap(); - let fresh: Option = res.take(0).unwrap(); - let fresh = fresh.unwrap(); - let old: Option = res.take(1).unwrap(); - assert_eq!( - fresh["status"], "pending", - "a two-second-old turn is still being answered" - ); - assert_eq!(fresh["error_code"], serde_json::Value::Null); - assert_eq!(old.as_deref(), Some("failed"), "past the horizon it goes"); - } - - /// A row written before choices had ids survives the retyped columns: it is - /// converted, it is writable again, and its stored *position* still names - /// the same option — a wrong remap here silently regrades exams. - #[tokio::test] - async fn boot_converts_positional_choices_and_keeps_the_same_option() { - let db = super::init_mem().await.unwrap(); - // Roll the columns back to their pre-2026-07-24 shapes and write the - // kind of row an older binary left behind, `source_bank` included. - db.query( - "REMOVE FIELD IF EXISTS choices[*].id ON TABLE exam_question; - REMOVE FIELD IF EXISTS choices[*].text ON TABLE exam_question; - REMOVE FIELD IF EXISTS choices[*].id ON TABLE bank_question; - REMOVE FIELD IF EXISTS choices[*].text ON TABLE bank_question; - DEFINE FIELD OVERWRITE choices ON exam_question TYPE option>; - DEFINE FIELD OVERWRITE correct ON exam_question TYPE option; - DEFINE FIELD OVERWRITE source_bank ON exam_question TYPE option; - DEFINE FIELD OVERWRITE slot ON question_image TYPE option; - DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option; - DEFINE FIELD OVERWRITE choices ON bank_question TYPE option>; - DEFINE FIELD OVERWRITE correct ON bank_question TYPE option; - DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option;", - ) - .await - .unwrap() - .check() - .unwrap(); - db.query( - "CREATE user:u SET username = 'u', password_hash = 'x'; - CREATE exam_question:q SET exam = exam:e, text = 'q', kind = 'multiple', - points = 5, subject = subject:s, choices = ['3', '4', '5'], correct = 1, - source_bank = 'bank_question:b'; - CREATE question_image:i SET exam = exam:e, question = exam_question:q, slot = 2, - file = 'f', content_type = 'image/png', size = 1; - CREATE question_image:whole SET exam = exam:e, question = exam_question:q, - file = 'w', content_type = 'image/png', size = 1; - CREATE exam_answer:a SET exam = exam:e, question = exam_question:q, user = user:u, - selected = 2, updated_at = 1; - CREATE bank_question:b SET owner = user:u, text = 'b', kind = 'multiple', - points = 3, choices = ['a', 'b'], correct = 0, created_at = 1; - CREATE bank_question_image:bi SET bank_question = bank_question:b, slot = 1, - file = 'bf', content_type = 'image/png', size = 1;", - ) - .await - .unwrap() - .check() - .unwrap(); - - super::migrate(&db).await.unwrap(); - - let mut res = db - .query( - "SELECT choices, correct FROM ONLY exam_question:q; - SELECT VALUE slot FROM ONLY question_image:i; - SELECT VALUE slot FROM ONLY question_image:whole; - SELECT VALUE selected FROM ONLY exam_answer:a; - SELECT choices, correct FROM ONLY bank_question:b; - SELECT VALUE slot FROM ONLY bank_question_image:bi;", - ) - .await - .unwrap(); - let q: Option = res.take(0).unwrap(); - let q = q.unwrap(); - let img_slot: Option = res.take(1).unwrap(); - let whole_slot: Option = res.take(2).unwrap(); - let selected: Option = res.take(3).unwrap(); - let bank: Option = res.take(4).unwrap(); - let bank = bank.unwrap(); - let bank_slot: Option = res.take(5).unwrap(); - - let ids: Vec<&str> = q["choices"] - .as_array() - .unwrap() - .iter() - .map(|c| c["id"].as_str().unwrap()) - .collect(); - assert_eq!( - q["choices"][0]["text"], "3", - "option order (and so the meaning of every stored index) is preserved" - ); - assert_eq!(q["correct"], ids[1], "correct was index 1"); - assert_eq!( - img_slot.as_deref(), - Some(ids[2]), - "option picture was slot 2" - ); - assert_eq!(selected.as_deref(), Some(ids[2]), "the answer was index 2"); - assert_eq!(whole_slot, None, "a question-level picture has no index"); - let bank_ids: Vec<&str> = bank["choices"] - .as_array() - .unwrap() - .iter() - .map(|c| c["id"].as_str().unwrap()) - .collect(); - assert_eq!(bank["correct"], bank_ids[0]); - assert_eq!(bank_slot.as_deref(), Some(bank_ids[1])); - - // Writable again — every one of these failed coercion before the - // backfill existed, and `source_bank` outlived its own column. - db.query( - "UPDATE exam_question:q SET points = 7; - UPDATE question_image:i SET size = 2; - UPDATE exam_answer:a SET updated_at = 2; - UPDATE bank_question:b SET points = 4; - UPDATE bank_question_image:bi SET size = 2;", - ) - .await - .unwrap() - .check() - .unwrap(); - - // A second boot re-mints nothing. - super::migrate(&db).await.unwrap(); - let mut res = db - .query("SELECT VALUE choices.map(|$c| $c.id) FROM ONLY exam_question:q") - .await - .unwrap(); - let again: Vec = res.take(0).unwrap(); - assert_eq!(again, ids, "conversion is idempotent"); - } -} diff --git a/src/db/cap.rs b/src/db/cap.rs index e13fb3f..488e147 100644 --- a/src/db/cap.rs +++ b/src/db/cap.rs @@ -1,132 +1,165 @@ //! Count caps the database enforces, not the process. //! //! Every "at most N children per parent" rule used to be a count-then-write -//! under a process-wide `Mutex`, because a `BEGIN…COMMIT` cannot enforce it: -//! SurrealDB does not conflict-check a cross-record `count()` against a -//! concurrent insert (write-skew), so two racing writers both saw a free slot. -//! A mutex serializes the writers, but only around whatever it wraps: every -//! one of those caps held a lock across a database round trip, and the count it -//! was protecting was already a guess by the time the insert landed. +//! under a process-wide `Mutex`, because the old store did not conflict-check +//! a cross-record `count()` against a concurrent insert (write-skew): two +//! racing writers both saw a free slot. A mutex serialized the writers, but +//! only around whatever it wrapped — every one of those caps held a lock +//! across a database round trip, and the count it was protecting was already +//! a guess by the time the insert landed. //! -//! The guard that does survive is a single-record conditional write: an -//! `UPDATE … SET n += 1 WHERE n < cap` on the *parent* row is atomic, so of N -//! concurrent claimers exactly `cap` get a non-empty result and the rest are -//! refused, with no lock and no window. The counter is therefore the +//! The guard that survives is a single-record conditional write: an +//! `UPDATE … SET n = n + 1 WHERE n < cap` on the *parent* row is atomic, so +//! of N concurrent claimers exactly `cap` get a non-empty result and the rest +//! are refused, with no lock and no window. The counter is therefore the //! authority on how many slots are taken, and the child rows follow it: the -//! claim and the child's insert land in one transaction ([`claim_and_create`] -//! and its variants), and a decrement rides the *same transaction* as every -//! delete of a child row. +//! claim and the child's insert land in one statement (the CTE recipes +//! below), and a decrement rides the *same transaction* as every delete of a +//! child row. //! -//! The counters are `option` columns on the parent table, absent meaning -//! zero, so no Rust struct carries them and no whole-row save can clobber one -//! (every parent's `.content()` write is a create of a fresh row). -// -// corner-cut: a counter can only drift if a future delete path forgets its -// decrement, and the boot backfill seeds most counters once rather than -// recomputing them. `enrollment_count` is the one that already drifted (the boot -// sweep of promoted users' rows kept their seats), so it is recomputed on every -// boot instead — see the repair in `migration_sql::BACKFILL`. That is the shape -// to copy for any other counter drift observed: a counter whose meaning is -// exactly "the live child rows" converges on a recompute, a lifetime tally does -// not and must stay seeded once. - -use surrealdb::types::{RecordId, SurrealValue}; -use tokio::sync::Mutex; - -use crate::constant::{CAP_WRITE_TRIES, REF_COUNT_FIELD, REF_RETIRED_FIELD, USER_ROLE_CLAIM_FIELD}; -use crate::database::{Database, backoff, lost_the_race, transaction_with_retry}; -use crate::error::AppError; - -/// One counter writer at a time, over every counter. -/// -/// Not the cap — the `WHERE` clause is the cap, and it holds with or without -/// this. What the lock buys is that the process sends its counter writes one at -/// a time, so the database never sees a parent row contended by every in-flight -/// request at once. That keeps the optimistic retry loop below to a beat or two -/// rather than a storm. -/// -/// It is also what keeps the test suite deterministic. The embedded in-memory -/// engine the tests run on does *not* have the real server's conflict -/// detection: under two concurrent writes to one record it can drop one and -/// still answer `Ok` (probed — the stored counter stays correct, but ~13% of a -/// 16-racer round had one more caller told it had won than the counter agreed -/// to). The real ws server never did this in 150 rounds of the same probe. -// -// corner-cut: one lock for every cap. Per-parent locks (a keyed map) if unrelated -// caps ever contend measurably — the counters are already independent, this is -// only about how many writes a process has in flight. -static CLAIM_LOCK: Mutex<()> = Mutex::const_new(()); +//! Postgres takes over the rest of what the old builders hand-rolled: +//! +//! * **Existence proof** — a real `FOREIGN KEY` refuses a child whose parent +//! is gone (SQLSTATE 23503), so the old bump-and-restore "touch" trick is +//! deleted. A gated variant ("parent must still be open") is +//! `INSERT … SELECT … WHERE EXISTS (SELECT 1 FROM parent WHERE id = $n AND )`. +//! * **Duplicate detection** — the child's primary key answers "another +//! writer placed this very row first" as SQLSTATE 23505 +//! (`crate::database::unique_violation`). +//! * **Retry** — `crate::database::tx_with_retry` owns the retry loop; a +//! refusal is an `Err` from the closure and is never retried, because a +//! refusal is a decision. +//! +//! ## The per-call-site recipes +//! +//! Table, column and cap names are crate constants, so every call site writes +//! its own static, macro-checkable statement (`sqlx::query!`). This module +//! keeps only the result types the call sites answer with, plus the one +//! genuinely shared mapping ([`full_kind`]). The shapes: +//! +//! ### Claim a seat and create the child (`claim_and_create` and its variants) +//! +//! ```sql +//! WITH seat AS ( +//! UPDATE +//! SET = + -- bump 0 for the uncounted create +//! WHERE id = $1 +//! AND < $2 -- or: < (SELECT …) (live cap) +//! -- AND () -- the guarded variant: one predicate decides cap and precondition +//! RETURNING 1) +//! INSERT INTO (id, ) +//! SELECT $3, $4, … WHERE EXISTS (SELECT 1 FROM seat) +//! RETURNING ; +//! ``` +//! +//! One statement is atomic: a refused insert takes its own seat bump back. +//! The verdict maps: one row → [`Claimed::Made`]; 23505 on the child key → +//! [`Claimed::Duplicate`] (read before the row count); zero rows → +//! [`Claimed::Full`] — deliberately still one marker for "full, guard failed, +//! parent gone", as before: the caller re-reads the parent to pick the +//! message, and only on that path. A live cap reads its capacity as a +//! subselect inside the same `WHERE`, so the write that lowers the cap and +//! the write that reads it still contend on one record; a lowered cap refuses +//! the very next claimer instead of admitting everyone whose snapshot predates +//! the edit. The uncounted create (`bump = 0`) still writes the seat +//! statement, so a missing parent row is refused as [`Claimed::Full`] on both +//! paths rather than silently writing a child of nobody. +//! +//! ### Two counters, one verdict (`claim_two_when_and_create`) +//! +//! ```sql +//! WITH bump AS ( +//! UPDATE board +//! SET total_stroke_count = total_stroke_count + 1, -- hard (lifetime) cap first +//! epoch_stroke_count = epoch_stroke_count + 1 -- soft (resettable) counter with it +//! WHERE id = $1 +//! AND total_stroke_count < $2 -- the hard cap carries the guard +//! AND epoch = $3 +//! AND epoch_stroke_count < $4 +//! RETURNING 1) +//! INSERT INTO board_stroke (id, ) +//! SELECT $5, … WHERE EXISTS (SELECT 1 FROM bump) +//! RETURNING ; +//! ``` +//! +//! One `UPDATE` moves both counters, so the row is written once and the +//! two-statement interleave the old process lock existed for cannot happen. +//! Zero rows means "hard full, guard failed, board gone, or soft full": the +//! caller re-reads both counters and maps them with [`full_kind`] — the +//! terminal cap outranks the recoverable one, as [`ClaimedTwo`] documents. +//! The child id is freshly minted, so no rival can aim at it and no 23505 +//! verdict exists on this path. +//! +//! ### Claim a reference on a name (`claim_ref_and_create`) +//! +//! In the caller's transaction, the duplicate gate stays *ahead* of the +//! retired check, so "you already have it" still outranks "the name is +//! retired": +//! +//! ```sql +//! SELECT 1 FROM WHERE ; -- found → ClaimedRef::Duplicate, stop +//! WITH ref AS ( +//! INSERT INTO (name, count) +//! VALUES ($1, $2) +//! ON CONFLICT (name) DO UPDATE +//! SET count = .count + EXCLUDED.count +//! WHERE .retired = false -- zero rows → ClaimedRef::Retired +//! RETURNING 1) +//! INSERT INTO (…) +//! SELECT … WHERE EXISTS (SELECT 1 FROM ref) +//! RETURNING …; -- 23505 on the child key → ClaimedRef::Duplicate +//! ``` +//! +//! The 23505 backstop covers the rival that passed the same gate a moment +//! ago (referential integrity keeps "row exists ∧ name retired" unreachable: +//! retiring requires count = 0, and a live row holds a count). The counted +//! row and the count still commit together or not at all — a name counted for +//! a row that does not exist is a name nobody can ever retire. +//! +//! ### Retire / un-retire a name (produces a [`Switched`]) +//! +//! Two statements in the caller's transaction; the row lock makes the read +//! and the write one switch, which is why the old process lock is gone: +//! +//! ```sql +//! SELECT retired FROM WHERE name = $1 FOR UPDATE; -- absent → treated as false +//! INSERT INTO (name, count, retired) +//! VALUES ($1, 0, $2) +//! ON CONFLICT (name) DO UPDATE +//! SET retired = $2 +//! WHERE .count = 0 -- retire only +//! AND .retired IS DISTINCT FROM $2 -- idempotence +//! RETURNING 1; -- empty result → the write did not land +//! ``` +//! +//! `(landed, was.unwrap_or(false))` maps exactly as [`Switched`] documents. +//! Retiring a never-claimed name still creates its ref row retired (the +//! `INSERT` arm), as before. +//! +//! ### Role-gated grants (the old `role_claim` handshake) +//! +//! The grant-survives-demotion handshake is now two statements in the +//! caller's transaction — the old counter bump-and-restore dance is dead: +//! +//! ```sql +//! SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE; +//! -- Rust checks the role it found; unfit → the call-site refusal (no retry). +//! INSERT INTO …; +//! ``` +//! +//! The demotion cascade's transaction `UPDATE`s that same user row before its +//! sweeps, so grant and demotion serialize on the row lock in both +//! directions: either the sweep sees the grant row, or the grant saw the new +//! role. -/// [`CLAIM_LOCK`], for a counter write that rides someone else's transaction -/// instead of [`write`]'s — [`crate::db::field_update::FieldUpdate`]'s term -/// move claims and releases inside the very `UPDATE`'s transaction, and still -/// owes the process one counter write at a time. -/// -/// **Is it load-bearing?** For the caps themselves, no — every one of them is a -/// single conditional write the store decides, and it decides it the same way -/// with a dozen writers in flight. So a counter write that skips this lock is -/// not a hole in a cap, and "every other site takes it" is not a correctness -/// argument. What the lock *is* load-bearing for is (a) the test suite, whose -/// in-memory engine forges wins under concurrency, and (b) any guard built out -/// of **two** statements that must not interleave with a rival's pair — -/// [`retire_name`] is exactly that, and it is why a skipped lock there would be -/// a real bug while a skipped lock around a lone `UPDATE … WHERE` is only -/// contention. -pub(crate) async fn counter_lock() -> tokio::sync::MutexGuard<'static, ()> { - CLAIM_LOCK.lock().await -} +#![allow(dead_code)] // the types below are the wave-2 lanes' verdict vocabulary /// "No cap" as a number, so the guard stays one comparison instead of a -/// nullable branch: `NONE`/`NULL` bind ambiguity is a worse trade than a -/// sentinel no roster will ever reach. +/// nullable branch: `NULL` bind ambiguity is a worse trade than a sentinel no +/// roster will ever reach. pub(crate) const UNLIMITED: i64 = i64::MAX; -/// Take one slot on `parent`'s `field` counter, and nothing else. `false` means -/// the cap is full (or the parent row is gone) and the caller must refuse — -/// nothing was written. `field` is always an in-crate constant, never user -/// input. -/// -/// **Test-only.** Every production claim now lands its child row in the same -/// transaction ([`claim_and_create`] and its variants); a bare claim followed by -/// a separate insert is the leak those exist to close. What survives is the -/// probe: the appointment tests put the double-book question to this `WHERE` -/// directly (a `join!` would ask the in-memory engine instead, which forges -/// wins), and staging a taken seat with *no* child row — exactly what a booking -/// mid-flight looks like — is a state no `*_and_create` can produce. -#[cfg(test)] -pub(crate) async fn claim( - parent: &RecordId, - field: &str, - cap: i64, - db: &Database, -) -> Result { - let sql = format!( - "UPDATE $parent SET {field} = ({field} ?? 0) + 1 \ - WHERE ({field} ?? 0) < $num RETURN VALUE id" - ); - Ok(!write(&sql, parent, cap, db).await?.is_empty()) -} - -/// The `THROW` markers the in-transaction gates below abort with: no room, and -/// this pair already holds its row. -const FULL_MARK: &str = "cap_full"; -const HELD_MARK: &str = "cap_held"; - -/// [`claim_ref_and_create`]'s third answer: the *name* is retired, which is not -/// a count being full — nothing empties it, and only putting the name back in -/// service lets a claim through. -const RETIRED_MARK: &str = "cap_retired"; - -/// The two markers [`claim_two_when_and_create`] aborts with, one per counter, -/// deliberately *not* shared: its two caps mean opposite things to the person -/// who hit one. The soft cap is a resettable working set (a whiteboard's live -/// canvas, emptied by a clear and drawn on again); the hard cap is the parent's -/// lifetime budget, and hitting it is terminal. One marker for both would tell -/// a caller a recoverable state is a permanent one. -const SOFT_FULL_MARK: &str = "cap_full_soft"; -const HARD_FULL_MARK: &str = "cap_full_hard"; - -/// What [`claim_and_create`] settled. +/// What the claim-and-create recipe (module docs) settled. pub(crate) enum Claimed { /// The seat and the row committed together. Made(T), @@ -137,607 +170,32 @@ pub(crate) enum Claimed { Duplicate, } -/// Take a slot on `parent`'s `field` counter *and* write the child that fills -/// it, in one transaction. -/// -/// A bare claim followed by a separate insert cannot promise this. Where the child -/// carries a deterministic id (one row per pair), two writers placing the *same* -/// pair both pass the claim — neither row exists yet — so on a tight cap the -/// second is told "full" for a seat it was never going to need, and a release -/// afterwards is too late to unsay it. A process-wide mutex could not hide that -/// either: it is released around the very round trip the two writes race in. -/// Here the duplicate `CREATE` aborts the transaction, which takes its own -/// increment with it, and the caller reads the winner's row back — so the -/// counter never counts a row that does not exist. -/// -/// The row is looked for *before* the seat is claimed, in that same -/// transaction, because on a tight cap the claim is the first thing to fail: a -/// member whose row a rival placed a moment ago would be told "full" about a -/// seat they already hold. The order makes "you are already in" outrank "there -/// is no room", which is what every caller's early return promises anyway. -pub(crate) async fn claim_and_create( - parent: &RecordId, - field: &str, - cap: i64, - id: &RecordId, - content: &T, - db: &Database, -) -> Result, AppError> { - claim_at_and_create(parent, field, "$num", cap, "", 1, None, id, content, db).await -} - -/// [`claim_and_create`] for a counter only *some* of a parent's children move: -/// the row lands either way, and `counts` decides whether the tally follows it. -/// -/// The one live user is `exam_sat_total`, which counts exams sat rather than -/// sittings — a retake writes a row and moves nothing. Splitting that into -/// "count and create" versus a bare create outside this module would put the -/// uncounted write on a different statement to the counted one, and a -/// deterministic child id needs the duplicate abort either way: whichever -/// branch runs, exactly one writer's `CREATE` commits, and only that one's -/// increment survives with it. `counts` false still writes the seat statement -/// (`+ 0`), so a missing parent row is refused as [`Claimed::Full`] on both -/// paths rather than silently writing a child of nobody. -pub(crate) async fn create_counting( - parent: &RecordId, - field: &str, - counts: bool, - id: &RecordId, - content: &T, - db: &Database, -) -> Result, AppError> { - let bump = i64::from(counts); - claim_at_and_create( - parent, field, "$num", UNLIMITED, "", bump, None, id, content, db, - ) - .await -} - -/// [`claim_and_create`] against a cap the *statement* reads rather than one the -/// caller snapshotted: `cap_expr` is SQL evaluated on the parent row at write -/// time (`audience.capacity ?? $num`, a subquery onto the settings singleton), -/// and `fallback` is the `$num` it coalesces to when the column is unset. -/// -/// A snapshotted cap is only ever a claim about the past. Bound as an integer, -/// a `PATCH` that *lowers* the cap while N requests are in flight admits all N -/// anyway — each one is measured against the number its own read saw, and the -/// single-record guard that makes concurrent claimers safe against each other -/// says nothing about the writer of the cap itself. Read inside the same -/// conditional write, the lowered cap refuses the very next claimer, because -/// the write that lowered it and the write that reads it contend on one record. -/// -/// `cap_expr` is always an in-crate SQL literal, never text from a client. -/// -/// `holder` is the child's *other* parent when that parent is a user whose live -/// role decides whether the row may exist at all: `(the user record, the role -/// it may not carry)`, claimed by [`role_claim`] in this same transaction. A -/// refusal from it arrives as [`Claimed::Full`], which already means "full, or -/// the guard failed, or the parent is gone" — the caller re-reads to pick the -/// message, and only on that path. -pub(crate) async fn claim_live_and_create( - parent: &RecordId, - field: &str, - cap_expr: &str, - fallback: i64, - holder: Option<(&RecordId, &str)>, - new: (&RecordId, &T), - db: &Database, -) -> Result, AppError> { - let (id, content) = new; - claim_at_and_create( - parent, field, cap_expr, fallback, "", 1, holder, id, content, db, - ) - .await -} - -/// [`claim_and_create`], but only while `guard` — an extra predicate on that -/// same parent row — also holds: one conditional write decides the cap *and* -/// the caller's second precondition (a homework submission's file add is -/// refused once the work is graded), so no read a concurrent write can outrun -/// sits between them. -/// -/// The contract that costs the caller something: [`Claimed::Full`] means "full -/// **or** the guard failed **or** the parent row is gone" — one marker for all -/// three, because the seat `UPDATE` matching nothing cannot say which clause -/// refused it. A caller that needs to tell them apart re-reads the parent, and -/// only to pick the message: none of the three is retryable into a success. -/// -/// `guard` is always an in-crate SQL literal or built in-crate out of numbers -/// this crate read back itself — never text from a client. -pub(crate) async fn claim_when_and_create( - parent: &RecordId, - field: &str, - cap: i64, - guard: &str, - id: &RecordId, - content: &T, - db: &Database, -) -> Result, AppError> { - claim_at_and_create(parent, field, "$num", cap, guard, 1, None, id, content, db).await -} - -#[allow(clippy::too_many_arguments)] -async fn claim_at_and_create( - parent: &RecordId, - field: &str, - cap_expr: &str, - cap: i64, - extra: &str, - bump: i64, - holder: Option<(&RecordId, &str)>, - id: &RecordId, - content: &T, - db: &Database, -) -> Result, AppError> { - let extra = if extra.is_empty() { - String::new() - } else { - format!(" AND ({extra})") - }; - // The holder's claim rides between the duplicate gate and the seat, so a - // caller whose row a rival placed is still told "you already have it", and - // a demotion outranks a full cap: `Full` on a list with room left sends - // nobody looking for a seat that is not the problem. - let held_by = holder.map_or_else(Vec::new, |(_, unfit)| { - role_claim("holder", unfit, FULL_MARK) - }); - let hold = if held_by.is_empty() { - String::new() - } else { - format!("{};\n", held_by.join(";\n")) - }; - let sql = format!( - "BEGIN TRANSACTION; - LET $held = (SELECT VALUE id FROM $id); - IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; - {hold}LET $seat = (UPDATE $parent SET {field} = ({field} ?? 0) + $bump \ - WHERE ({field} ?? 0) < ({cap_expr}){extra} RETURN VALUE id); - IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }}; - CREATE $id CONTENT $row; - COMMIT TRANSACTION;" - ); - let _guard = CLAIM_LOCK.lock().await; - let mut last = None; - for attempt in 0..CAP_WRITE_TRIES { - backoff(attempt).await; - let mut query = db - .query(sql.as_str()) - .bind(("parent", parent.clone())) - .bind(("num", cap)) - .bind(("bump", bump)) - .bind(("id", id.clone())) - .bind(("row", content.clone())); - if let Some((record, _)) = holder { - query = query.bind(("holder", record.clone())); - } - let attempted = query.await; - let mut result = match attempted { - Ok(result) => result, - Err(err) if lost_the_race(&err) => { - last = Some(err); - continue; - } - Err(err) => return Err(err.into()), - }; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the failing slot says why. - let mut errors = result.take_errors(); - // "Already a member" is read first: it outranks a full cap, and the two - // never both fire (the gate aborts before the seat is touched). - if errors - .values() - .any(|error| error.to_string().contains(HELD_MARK) || error.is_already_exists()) - { - return Ok(Claimed::Duplicate); - } - if errors - .values() - .any(|error| error.to_string().contains(FULL_MARK)) - { - return Ok(Claimed::Full); - } - // A conflict in *any* slot is the whole batch's verdict, and it is read - // before the arbitrary pick below: the siblings say only "not executed", - // which is the *consequence* of this abort and never a reason of its - // own. Picking one of those out of a `HashMap` — unordered, so it wins - // most rounds — retired a retryable round as a 500. - if errors.values().any(lost_the_race) { - last = errors.drain().map(|(_, error)| error).find(lost_the_race); - continue; - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5, plus - // the holder claim's own statements when one is carried — counted, not - // tallied by hand, so a statement added there cannot read back the - // wrong result. - let slot = 5 + held_by.len(); - return result - .take::>(slot)? - .into_iter() - .next() - .map(Claimed::Made) - .ok_or_else(|| AppError::Internal("cap claim wrote no row".into())); - } - Err(last - .map(AppError::from) - .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) -} - -/// The marker [`touch_and_create`] aborts with: the parent row is gone. -const GONE_MARK: &str = "cap_gone"; - -/// Write a child of `parent` while *colliding* with anything that removes the -/// parent — no seat spent, only the proof. `Ok(None)` = the parent is gone and -/// nothing was written. -/// -/// Reading the parent first and then inserting cannot promise this, and neither -/// can a `SELECT` inside the transaction: SurrealDB 3.2.3 conflict-checks write -/// sets, not read sets, so a create landing inside a parent delete's window -/// reads a row that is still there (removed, uncommitted) while the delete's -/// `DELETE WHERE parent = $parent` sweep already ran on a snapshot -/// without this row — both commit, and the child outlives its parent -/// unreachably, because every route to it goes through the parent. -/// -/// So the proof is a *write* on the parent's own record, which is the key the -/// delete writes. `field` is moved — bumped and put back by captured value, -/// `NONE` included, so the row is byte-identical afterwards — because an -/// `UPDATE` that leaves the document unchanged is elided and never enters the -/// write set: `SET x = x` sits on no key at all and collides with nothing -/// (measured on 3.2.3, and the reason -/// [`crate::db::class_pump::Axis::pivot_claim`] and -/// [`crate::db::exam_answer::save`] have the same shape). Both -/// statements are inside the transaction, so an abort between them cannot leave -/// the counter up. -/// -/// It lives here because it is [`claim_and_create`] with the cap removed: the -/// same single-record conditional write on the parent, asked "are you still -/// there?" instead of "is there room?". No [`CLAIM_LOCK`] either — the counter -/// nets zero, so no cap depends on the order these arrive in. -/// -/// Admissible for [`crate::database::transaction_with_retry`]: `UPDATE`s and a -/// `CREATE` whose id is a freshly minted ULID no rival can aim at, so no -/// statement can legitimately answer "already exists" and a lost round wrote -/// nothing. -pub(crate) async fn touch_and_create( - parent: &RecordId, - field: &str, - id: &RecordId, - content: &T, - db: &Database, -) -> Result, AppError> { - let sql = format!( - "BEGIN TRANSACTION; - LET $was = (SELECT VALUE {field} FROM ONLY $parent); - LET $alive = (UPDATE $parent SET {field} = ({field} ?? 0) + 1 RETURN VALUE id); - IF array::len($alive) = 0 {{ THROW '{GONE_MARK}' }}; - UPDATE $parent SET {field} = $was; - LET $made = (CREATE $id CONTENT $row RETURN AFTER); - RETURN $made[0]; - COMMIT TRANSACTION;" - ); - let (mut result, mut errors) = transaction_with_retry( - db, - &sql, - &[ - ("parent".into(), parent.clone().into_value()), - ("id".into(), id.clone().into_value()), - ("row".into(), content.clone().into_value()), - ], - &[GONE_MARK], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the marker. - if errors - .values() - .any(|error| error.to_string().contains(GONE_MARK)) - { - return Ok(None); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is the last statement before `COMMIT`, so its slot - // follows the statement count rather than a hand-kept number; - // `num_statements` counts BEGIN and COMMIT. - let slot = result.num_statements().saturating_sub(2); - result - .take::>(slot)? - .into_iter() - .next() - .map(Some) - .ok_or_else(|| AppError::Internal("the parent touch wrote no row".into())) -} - -/// The statements that put a transaction's write on a **user's own record** -/// while the role that row still carries may hold the grant being written — -/// [`touch_and_create`]'s trick pointed at the one key -/// [`crate::service::user::set_role`] writes. -/// -/// WHY: a demotion sheds every grant the old role implied, and it does that in -/// the role write's own transaction — but its sweeps are *snapshots* -/// (`DELETE WHERE user = $usr`), and SurrealDB 3.2.3 conflict-checks -/// write sets, not read sets. A seat, an enrollment or a class membership -/// created after that snapshot therefore survives the sweep, and nothing ever -/// re-sweeps: the grant stands forever under a role that may not hold it. Every -/// one of those creates writes its *other* parent (the event, the course, the -/// class), so it shares no key with the demotion and the store has nothing to -/// settle. -/// -/// So the counter named by [`USER_ROLE_CLAIM_FIELD`] is **moved** — bumped and -/// put back by captured value, `NONE` included, so the row is byte-identical -/// afterwards — because re-stating a value claims nothing: an `UPDATE` that -/// leaves the document unchanged is elided and enters no write set. The same -/// `UPDATE` hands back the role it found, so one statement is both the write -/// that collides and the read that decides. Either the sweep sees this row, or -/// this statement sees the demotion; and the caller that *loses* the conflict -/// re-sends into a fresh transaction that reads the new role, which is what -/// keeps the retry from turning a refusal into a success. -/// -/// A user row that is not there claims nothing and refuses nothing: the -/// `UPDATE` matches no key, and every caller has already answered a missing -/// target its own way. `holder` names the binding the user record is bound to, -/// and `unfit` is an in-crate comparison against the role that may *not* hold -/// this grant — never text from a client. -pub(crate) fn role_claim(holder: &str, unfit: &str, mark: &str) -> Vec { - vec![ - format!("LET $role_was = (SELECT VALUE {USER_ROLE_CLAIM_FIELD} FROM ONLY ${holder})"), - format!( - "LET $role_now = (UPDATE ${holder} SET {USER_ROLE_CLAIM_FIELD} = \ - ({USER_ROLE_CLAIM_FIELD} ?? 0) + 1 RETURN VALUE role)" - ), - format!("IF array::len($role_now) > 0 AND $role_now[0] {unfit} {{ THROW '{mark}' }}"), - format!("UPDATE ${holder} SET {USER_ROLE_CLAIM_FIELD} = $role_was"), - ] -} - -/// What [`claim_two_when_and_create`] settled. +/// What the two-counter recipe (module docs) settled. pub(crate) enum ClaimedTwo { /// Both seats and the row committed together. Made(T), - /// The *resettable* counter (`fields[0]`) is full — nothing was written, - /// and whatever empties it lets the caller through again. + /// The *resettable* counter (the soft, epoch-scoped one) is full — + /// nothing was written, and whatever empties it lets the caller through + /// again. FullSoft, - /// The *lifetime* counter (`fields[1]`) is full, the guard failed, or the - /// parent row is gone — nothing was written. The caller re-reads the parent - /// to tell those apart, and only to pick the message: both are refusals the + /// The *lifetime* counter is full, the guard failed, or the parent row is + /// gone — nothing was written. The caller re-reads the parent to tell + /// those apart, and only to pick the message: both are refusals the /// caller cannot retry into a success. FullHard, } -/// Take a slot on *two* of `parent`'s counters, while `guard` holds, and write -/// the child that fills them — one transaction, one verdict. -/// -/// Two separate guarded claims cannot promise this. A parent whose children are -/// counted twice — once against a resettable working set, once against a -/// lifetime budget — has the two counters describing the same rows, so a writer -/// that lands one increment and loses the other leaves them disagreeing -/// forever, and the lifetime cap stops bounding anything. Here either both -/// increments and the row commit, or the transaction aborts having written -/// nothing. -/// -/// The hard cap is claimed *first*, carrying the guard, so a terminal refusal -/// outranks a recoverable one: a parent that has spent its lifetime budget is -/// not helped by being told its resettable counter is also full. -/// -/// There is no `$held` gate — [`claim_and_create`]'s exists because its child -/// carries a deterministic id two writers can both aim at. This one's caller -/// mints a fresh monotonic ULID on a table with no `UNIQUE` index, so no rival -/// can target that id, and its absence is also what keeps the batch retryable: -/// no statement in it can legitimately answer "already exists" (see -/// [`crate::database::transaction_with_retry`]). -/// -/// The two counters are named one by one rather than passed as a pair of -/// arrays: which slot is the resettable one and which is terminal decides -/// whether a refusal is phrased "clear it and carry on" or "this is over", and -/// two `[i64; 2]` positions swapped by mistake compile, pass every test — both -/// slots are the same type — and misreport that forever. The names are the -/// guard against it. -/// -/// The fields are always in-crate constants, and `guard` is either one or -/// built in-crate out of numbers this crate read back itself -/// (`board_stroke::append` appends an `epoch` it took off the board row) — -/// never text from a client. -pub(crate) async fn claim_two_when_and_create( - parent: &RecordId, - soft: (&str, i64), - hard: (&str, i64), - guard: &str, - id: &RecordId, - content: &T, - db: &Database, -) -> Result, AppError> { - let (soft_field, soft_cap) = soft; - let (hard_field, hard_cap) = hard; - // Parenthesized `??` throughout: `n ?? 0 < $cap` parses as `n ?? (0 < $cap)`, - // which is truthy for every row and would claim past the cap. - let sql = format!( - "BEGIN TRANSACTION; - LET $lifetime = (UPDATE $parent SET {hard_field} = ({hard_field} ?? 0) + 1 \ - WHERE ({hard_field} ?? 0) < $hard AND ({guard}) RETURN VALUE id); - IF array::len($lifetime) = 0 {{ THROW '{HARD_FULL_MARK}' }}; - LET $seat = (UPDATE $parent SET {soft_field} = ({soft_field} ?? 0) + 1 \ - WHERE ({soft_field} ?? 0) < $soft RETURN VALUE id); - IF array::len($seat) = 0 {{ THROW '{SOFT_FULL_MARK}' }}; - CREATE $id CONTENT $row; - COMMIT TRANSACTION;" - ); - let _guard = CLAIM_LOCK.lock().await; - let mut last = None; - for attempt in 0..CAP_WRITE_TRIES { - backoff(attempt).await; - let attempted = db - .query(sql.as_str()) - .bind(("parent", parent.clone())) - .bind(("soft", soft_cap)) - .bind(("hard", hard_cap)) - .bind(("id", id.clone())) - .bind(("row", content.clone())) - .await; - let mut result = match attempted { - Ok(result) => result, - Err(err) if lost_the_race(&err) => { - last = Some(err); - continue; - } - Err(err) => return Err(err.into()), - }; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the failing slot says why. The two markers are read - // before the conflict check, because a `THROW` is a decision. - let mut errors = result.take_errors(); - if errors - .values() - .any(|error| error.to_string().contains(HARD_FULL_MARK)) - { - return Ok(ClaimedTwo::FullHard); - } - if errors - .values() - .any(|error| error.to_string().contains(SOFT_FULL_MARK)) - { - return Ok(ClaimedTwo::FullSoft); - } - if errors.values().any(lost_the_race) { - last = errors.drain().map(|(_, error)| error).find(lost_the_race); - continue; - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. - return result - .take::>(5)? - .into_iter() - .next() - .map(ClaimedTwo::Made) - .ok_or_else(|| AppError::Internal("cap claim wrote no row".into())); - } - Err(last - .map(AppError::from) - .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) -} - -// --- reference counters -------------------------------------------------- -// -// The same single-record guard, pointed the other way. A cap asks "is there -// room for one more child?"; a reference counter asks "may this *name* still be -// used, and does anything still use it?" — the shape behind "an exam kind -// nothing is graded under may leave the school's settings". Both questions are -// answered by one row per name (`kind_ref:`, `slot_ref:`), created -// on first use, so the removal and the last claim contend on a record rather -// than on a cross-table count no transaction serializes. -// -// The two writes are exact mirrors: a claim lands only while the name is not -// retired, a retirement lands only while the count is zero. Whichever reaches -// the record first, the other is refused — in any process. - -/// What [`claim_ref_and_create`] settled. +/// What the reference-counter recipe (module docs) settled. pub(crate) enum ClaimedRef { /// The reference and the row committed together. Made(T), - /// The name is retired — nothing was written, and no retry helps until the - /// name is put back in service. + /// The name is retired — nothing was written, and no retry helps until + /// the name is put back in service. Retired, /// Another writer placed this very row first, so this caller never owed a /// reference: nothing was written, and the winner's row is the answer. Duplicate, } -// -// A separate enum rather than a `Retired` variant on [`Claimed`]: that enum is -// matched exhaustively by a dozen callers in files this change does not touch, -// and a cap has no retired state to answer for anyway. - -/// Take one reference on `counter` *and* write the row that holds it, in one -/// transaction — [`claim_and_create`] pointed at a name instead of a cap. -/// -/// A bare reference claim followed by a separate insert cannot promise this: it -/// lands, the insert then fails or the process dies, and the name is counted as -/// used by a row that does not exist — which is a name nobody can ever retire. -/// Here the abort takes the increment with it. -/// -/// The `$held` gate comes first for [`claim_and_create`]'s reason: where the -/// child carries a deterministic id, a rival can place the very row this caller -/// is placing, and "you already have it" is the honest answer — one that must -/// not cost a reference. Which is also why this carries its own retry loop -/// rather than [`crate::database::transaction_with_retry`]'s: the `CREATE` can -/// legitimately answer "already exists", and that loop cannot tell that answer -/// from a lost round. The `UPSERT` cannot answer it — `kind_ref`/`slot_ref` -/// carry no `UNIQUE` index, so a write keyed by id resolves onto the row the id -/// names. -pub(crate) async fn claim_ref_and_create( - counter: &RecordId, - n: i64, - id: &RecordId, - content: &T, - db: &Database, -) -> Result, AppError> { - let sql = format!( - "BEGIN TRANSACTION; - LET $held = (SELECT VALUE id FROM $id); - IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; - LET $ref = (UPSERT $parent SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + $num \ - WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id); - IF array::len($ref) = 0 {{ THROW '{RETIRED_MARK}' }}; - CREATE $id CONTENT $row; - COMMIT TRANSACTION;" - ); - let _guard = CLAIM_LOCK.lock().await; - let mut last = None; - for attempt in 0..CAP_WRITE_TRIES { - backoff(attempt).await; - let attempted = db - .query(sql.as_str()) - .bind(("parent", counter.clone())) - .bind(("num", n)) - .bind(("id", id.clone())) - .bind(("row", content.clone())) - .await; - let mut result = match attempted { - Ok(result) => result, - Err(err) if lost_the_race(&err) => { - last = Some(err); - continue; - } - Err(err) => return Err(err.into()), - }; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the failing slot says why. The markers are read - // before the conflict check, because a `THROW` is a decision. - let mut errors = result.take_errors(); - if errors - .values() - .any(|error| error.to_string().contains(HELD_MARK) || error.is_already_exists()) - { - return Ok(ClaimedRef::Duplicate); - } - if errors - .values() - .any(|error| error.to_string().contains(RETIRED_MARK)) - { - return Ok(ClaimedRef::Retired); - } - if errors.values().any(lost_the_race) { - last = errors.drain().map(|(_, error)| error).find(lost_the_race); - continue; - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. - return result - .take::>(5)? - .into_iter() - .next() - .map(ClaimedRef::Made) - .ok_or_else(|| AppError::Internal("cap claim wrote no row".into())); - } - Err(last - .map(AppError::from) - .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) -} /// What a retire / un-retire write did to the name's bit. /// @@ -753,530 +211,58 @@ pub(crate) enum Switched { /// The bit already stood that way — this call wrote nothing, so there is /// nothing to take back, and taking it back would undo somebody else. Unchanged, - /// Retirement only: something still references the name and the caller must - /// refuse. Nothing was written. + /// Retirement only: something still references the name and the caller + /// must refuse. Nothing was written. InUse, } -/// Retire the name behind `id`: no further claim succeeds. Idempotent — a -/// retirement of an already-retired unused name lands again, and says so -/// ([`Switched::Unchanged`]) so the caller does not roll back a bit it never -/// set. -pub(crate) async fn retire_name(id: &RecordId, db: &Database) -> Result { - // Parenthesized `??`: `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which - // is truthy for *every* row and would retire a name still in use. - // - // The bit as it stood is read in the *same round trip* as the write, so the - // pair is one hold of `CLAIM_LOCK` (see [`switch`]) and no rival in this - // process can retire the name between them and be undone by this caller. - let sql = format!( - "SELECT VALUE ({REF_RETIRED_FIELD} ?? false) FROM $parent; - UPSERT $parent SET {REF_RETIRED_FIELD} = true \ - WHERE ({REF_COUNT_FIELD} ?? 0) = 0 RETURN VALUE id" - ); - let (was, landed) = switch(&sql, id, db).await?; - Ok(match (landed, was) { - (false, _) => Switched::InUse, - (true, true) => Switched::Unchanged, - (true, false) => Switched::Flipped, - }) -} - -/// Put a name back in service — it re-entered the list it was retired from, or -/// the edit that retired it never landed. [`Switched::Flipped`] only when the -/// name really was retired, for [`retire_name`]'s reason pointed the other way. -pub(crate) async fn unretire_name(id: &RecordId, db: &Database) -> Result { - let sql = format!( - "SELECT VALUE ({REF_RETIRED_FIELD} ?? false) FROM $parent; - UPSERT $parent SET {REF_RETIRED_FIELD} = false RETURN VALUE id" - ); - let (was, _) = switch(&sql, id, db).await?; - Ok(if was { - Switched::Flipped - } else { - Switched::Unchanged - }) -} - -/// [`retire_name`] as the yes/no the domain probes ask — did the name end up -/// retired? **Test-only**: production callers roll their edit back and need to -/// know which of the two "yes" answers they got. -#[cfg(test)] -pub(crate) async fn retire(id: &RecordId, db: &Database) -> Result { - Ok(!matches!(retire_name(id, db).await?, Switched::InUse)) +/// Which of [`ClaimedTwo`]'s caps refused a zero-row dual claim. +pub(crate) enum FullKind { + /// The resettable counter is full — recoverable by whatever empties it. + Soft, + /// The lifetime counter is full, the guard failed, or the parent row is + /// gone — terminal. + Hard, } -/// The read of the `retired` bit and the write that moves it, one round trip -/// under one [`CLAIM_LOCK`] hold: `(bit as it stood, did the write match)`. -async fn switch(sql: &str, parent: &RecordId, db: &Database) -> Result<(bool, bool), AppError> { - let _guard = CLAIM_LOCK.lock().await; - let mut last = None; - for attempt in 0..CAP_WRITE_TRIES { - backoff(attempt).await; - let attempted = async { - let mut result = db - .query(sql) - .bind(("parent", parent.clone())) - .await? - .check()?; - let was = result - .take::>(0)? - .first() - .copied() - .unwrap_or(false); - let landed = !result.take::>(1)?.is_empty(); - Ok::<_, surrealdb::Error>((was, landed)) - } - .await; - match attempted { - Ok(answer) => return Ok(answer), - Err(err) if lost_the_race(&err) => last = Some(err), - Err(err) => return Err(err.into()), - } - } - Err(last - .map(AppError::from) - .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) -} - -/// Run one conditional counter write, retrying while the store reports a write -/// conflict. -/// -/// Claimers contend on a single record by design — that contention *is* the -/// guard — and SurrealDB resolves it optimistically: the loser's transaction is -/// aborted with "can be retried" rather than queued, which the old mutex hid by -/// never letting two writers reach the database at once. So the queueing has to -/// happen here. Backoff is exponential with jitter, because racers arrive in -/// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them. -/// `num` is the statement's one number, bound as `$num` — the cap. +/// Map a zero-row dual-counter claim, re-read off the parent row, onto +/// [`ClaimedTwo`]'s two full states. /// -/// **Test-only**, like its one caller [`claim`]: every production counter write -/// now rides its child row's transaction and carries its own loop. -#[cfg(test)] -async fn write( - sql: &str, - parent: &RecordId, - num: i64, - db: &Database, -) -> Result, AppError> { - let _guard = CLAIM_LOCK.lock().await; - let mut last = None; - for attempt in 0..CAP_WRITE_TRIES { - backoff(attempt).await; - let attempted = async { - let mut result = db - .query(sql) - .bind(("parent", parent.clone())) - .bind(("num", num)) - .await? - .check()?; - result.take::>(0) - } - .await; - match attempted { - Ok(hit) => return Ok(hit), - // `lost_the_race` also matches "already exists", which an UPDATE - // cannot produce — what is being reused here is its transaction - // conflict detection, typed details first and wording second. - Err(err) if lost_the_race(&err) => last = Some(err), - Err(err) => return Err(err.into()), - } +/// The recipe bumps both counters in one `UPDATE` with the hard cap's +/// conditions first, so zero rows means "hard full, guard failed, parent +/// gone, or soft full". The terminal cap outranks the recoverable one +/// everywhere: [`FullKind::Soft`] only when the soft counter is full *while* +/// the hard one still has room — every other answer, including the ambiguous +/// guard/gone case, folds into [`FullKind::Hard`], whose contract already +/// covers it. This is the old claim order (hard claim, guard attached, before +/// the soft one) expressed as a re-read. +pub(crate) fn full_kind(soft_count: i64, soft_cap: i64, hard_count: i64, hard_cap: i64) -> FullKind { + if soft_count >= soft_cap && hard_count < hard_cap { + FullKind::Soft + } else { + FullKind::Hard } - Err(last - .map(AppError::from) - .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) } #[cfg(test)] mod tests { use super::*; - use crate::constant::{ - BOARD_EPOCH_STROKE_COUNT_FIELD, BOARD_OPEN_GUARD, BOARD_TOTAL_STROKE_COUNT_FIELD, - }; - - #[derive(Debug, Clone, SurrealValue)] - struct Stroke { - board: RecordId, - author: RecordId, - kind: String, - epoch: i64, - created_at: i64, - } - - /// The pair of counters, re-read out of the store — never off a return - /// value, which the in-memory engine forges wins on (see `CLAIM_LOCK`). - async fn stored(db: &Database) -> (i64, i64) { - let mut result = db - .query("SELECT VALUE [epoch_stroke_count ?? 0, total_stroke_count ?? 0] FROM board:b") - .await - .unwrap() - .check() - .unwrap(); - let rows: Vec> = result.take(0).unwrap(); - (rows[0][0], rows[0][1]) - } - - async fn strokes(db: &Database) -> usize { - let mut result = db - .query("SELECT VALUE id FROM board_stroke") - .await - .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap().len() - } - - async fn a_board(epoch: i64, total: i64, locked: bool) -> Database { - let db = crate::database::init_mem().await.unwrap(); - db.query( - "CREATE user:u SET username = 'u', password_hash = 'x'; - CREATE board:b SET creator = user:u, title = 't', participants = [user:u], - locked = $locked, epoch = 0, epoch_stroke_count = $epoch, - total_stroke_count = $total, created_at = 1;", - ) - .bind(("locked", locked)) - .bind(("epoch", epoch)) - .bind(("total", total)) - .await - .unwrap() - .check() - .unwrap(); - db - } - - fn a_stroke() -> Stroke { - Stroke { - board: RecordId::new("board", "b"), - author: RecordId::new("user", "u"), - kind: "stroke".into(), - epoch: 0, - created_at: 2, - } - } - - async fn claim(db: &Database, caps: [i64; 2], key: &str) -> ClaimedTwo { - claim_two_when_and_create( - &RecordId::new("board", "b"), - (BOARD_EPOCH_STROKE_COUNT_FIELD, caps[0]), - (BOARD_TOTAL_STROKE_COUNT_FIELD, caps[1]), - BOARD_OPEN_GUARD, - &RecordId::new("board_stroke", key), - &a_stroke(), - db, - ) - .await - .unwrap() - } - - #[tokio::test] - async fn both_counters_move_together_or_not_at_all() { - let db = a_board(0, 0, false).await; - assert!(matches!( - claim(&db, [2, 2], "s1").await, - ClaimedTwo::Made(_) - )); - assert_eq!(stored(&db).await, (1, 1)); - assert_eq!(strokes(&db).await, 1); - } - - /// One cap refuses; the *other* counter must not have advanced, asserted by - /// re-reading the row. A drift here would let the lifetime cap be passed. - #[tokio::test] - async fn a_refused_claim_advances_neither_counter() { - // Soft (epoch) full, hard (lifetime) with room to spare. - let db = a_board(5, 5, false).await; - assert!(matches!( - claim(&db, [5, 99], "s1").await, - ClaimedTwo::FullSoft - )); - assert_eq!(stored(&db).await, (5, 5)); - assert_eq!(strokes(&db).await, 0); - - // Hard full, soft with room to spare. - let db = a_board(5, 5, false).await; - assert!(matches!( - claim(&db, [99, 5], "s1").await, - ClaimedTwo::FullHard - )); - assert_eq!(stored(&db).await, (5, 5)); - assert_eq!(strokes(&db).await, 0); - } - - /// The two `THROW` markers must reach the caller as *different* answers: - /// one board is recoverable by a clear, the other is read-only for good. - #[tokio::test] - async fn the_two_caps_refuse_distinguishably() { - let db = a_board(5, 5, false).await; - let soft = claim(&db, [5, 99], "s1").await; - let hard = claim(&db, [99, 5], "s2").await; - assert!(matches!(soft, ClaimedTwo::FullSoft)); - assert!(matches!(hard, ClaimedTwo::FullHard)); - assert_eq!(stored(&db).await, (5, 5)); - } - - #[tokio::test] - async fn the_guard_refuses_a_locked_board() { - let db = a_board(0, 0, true).await; - assert!(matches!( - claim(&db, [9, 9], "s1").await, - ClaimedTwo::FullHard - )); - assert_eq!(stored(&db).await, (0, 0)); - assert_eq!(strokes(&db).await, 0); - } - - // --- claim_when_and_create ------------------------------------------ - - async fn claim_one(db: &Database, cap: i64, key: &str) -> Claimed { - claim_when_and_create( - &RecordId::new("board", "b"), - BOARD_EPOCH_STROKE_COUNT_FIELD, - cap, - BOARD_OPEN_GUARD, - &RecordId::new("board_stroke", key), - &a_stroke(), - db, - ) - .await - .unwrap() - } - - #[tokio::test] - async fn a_guarded_claim_advances_its_counter_exactly_once() { - let db = a_board(0, 0, false).await; - assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Made(_))); - assert_eq!(stored(&db).await, (1, 0)); - assert_eq!(strokes(&db).await, 1); - } - - /// A failed guard is refused as `Full` (the one marker covers full, guard - /// and missing parent), and must leave the counter and the table alone. - #[tokio::test] - async fn a_guard_refusal_advances_neither_counter_nor_row() { - let db = a_board(0, 0, true).await; - assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Full)); - assert_eq!(stored(&db).await, (0, 0)); - assert_eq!(strokes(&db).await, 0); - } - - /// The second writer at the same id owes no seat: the row is already there, - /// so the counter must not move a second time for it. - #[tokio::test] - async fn a_duplicate_row_claims_no_seat() { - let db = a_board(0, 0, false).await; - assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Made(_))); - assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Duplicate)); - assert_eq!(stored(&db).await, (1, 0)); - assert_eq!(strokes(&db).await, 1); - } - - // --- claim_ref_and_create ------------------------------------------- - - #[derive(Debug, Clone, SurrealValue)] - struct Menu { - date: String, - slot: String, - created_by: RecordId, - created_at: i64, - } - - async fn a_slot(count: i64, retired: bool) -> Database { - let db = crate::database::init_mem().await.unwrap(); - db.query( - "CREATE user:u SET username = 'u', password_hash = 'x'; - UPSERT slot_ref:lunch SET count = $count, retired = $retired;", - ) - .bind(("count", count)) - .bind(("retired", retired)) - .await - .unwrap() - .check() - .unwrap(); - db - } - - /// The reference count, re-read out of the store — never off a return - /// value, which the in-memory engine forges wins on (see `CLAIM_LOCK`). - async fn refs(db: &Database) -> i64 { - let mut result = db - .query("SELECT VALUE (count ?? 0) FROM slot_ref:lunch") - .await - .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap()[0] - } - - async fn menus(db: &Database) -> usize { - let mut result = db - .query("SELECT VALUE id FROM menu") - .await - .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap().len() - } - - async fn claim_slot(db: &Database, key: &str) -> ClaimedRef { - claim_ref_and_create( - &RecordId::new(crate::constant::SLOT_REF_TABLE, "lunch"), - 1, - &RecordId::new("menu", key), - &Menu { - date: "2026-08-02".into(), - slot: "lunch".into(), - created_by: RecordId::new("user", "u"), - created_at: 1, - }, - db, - ) - .await - .unwrap() - } - - #[tokio::test] - async fn a_reference_and_its_row_land_together() { - let db = a_slot(0, false).await; - assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Made(_))); - assert_eq!(refs(&db).await, 1); - assert_eq!(menus(&db).await, 1); - } - - /// A retired name refuses, and the refusal must cost nothing: no row, no - /// count — a counted row on a retired name is a name nobody can retire. - #[tokio::test] - async fn a_retired_name_refuses_with_no_row_and_no_count() { - let db = a_slot(0, true).await; - assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Retired)); - assert_eq!(refs(&db).await, 0); - assert_eq!(menus(&db).await, 0); - } - - /// The `retired` bit as the store holds it, `None` when the row is absent. - async fn bit(db: &Database) -> Option { - let mut result = db - .query("SELECT VALUE retired FROM slot_ref:lunch") - .await - .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap().first().copied() - } - - fn lunch() -> RecordId { - RecordId::new(crate::constant::SLOT_REF_TABLE, "lunch") - } - - /// Retirement is idempotent, so "it is retired now" is *not* "I retired - /// it" — and a caller that rolls back on the second answer un-retires a - /// name somebody else legitimately took out of service. That is the whole - /// settings-CAS wedge: the list drops the name, the counter says in - /// service, the name grades again and can then never be removed. - #[tokio::test] - async fn a_second_retirement_says_it_changed_nothing() { - let db = a_slot(0, false).await; - assert!(matches!( - retire_name(&lunch(), &db).await.unwrap(), - Switched::Flipped - )); - assert!(matches!( - retire_name(&lunch(), &db).await.unwrap(), - Switched::Unchanged - )); - assert_eq!(bit(&db).await, Some(true), "the winner's bit still stands"); - } - - /// The mirror: only the un-retire that really put a name back in service - /// owes a re-retirement, so a re-add that never lands cannot be undone - /// twice. - #[tokio::test] - async fn a_second_un_retirement_says_it_changed_nothing() { - let db = a_slot(0, true).await; - assert!(matches!( - unretire_name(&lunch(), &db).await.unwrap(), - Switched::Flipped - )); - assert!(matches!( - unretire_name(&lunch(), &db).await.unwrap(), - Switched::Unchanged - )); - assert_eq!(bit(&db).await, Some(false)); - } - - /// A referenced name is refused, and the refusal writes nothing — the - /// caller must not record an undo for it either. - #[tokio::test] - async fn a_referenced_name_refuses_and_leaves_the_bit_alone() { - let db = a_slot(1, false).await; - assert!(matches!( - retire_name(&lunch(), &db).await.unwrap(), - Switched::InUse - )); - assert_eq!(bit(&db).await, Some(false)); - } - - // --- claim_live_and_create ------------------------------------------ - - /// The cap the statement reads and the cap the caller remembers are - /// different numbers the moment anyone edits the cap. `epoch` stands in for - /// a capacity column here — any int on the parent row does. - #[tokio::test] - async fn a_live_cap_refuses_where_the_caller_s_snapshot_admits() { - let db = a_board(1, 0, false).await; - db.query("UPDATE board:b SET epoch = 1") - .await - .unwrap() - .check() - .unwrap(); - - // Live: one seat, one taken — full, and nothing written. - let live = claim_live_and_create( - &RecordId::new("board", "b"), - BOARD_EPOCH_STROKE_COUNT_FIELD, - "epoch ?? $num", - UNLIMITED, - None, - (&RecordId::new("board_stroke", "s1"), &a_stroke()), - &db, - ) - .await - .unwrap(); - assert!(matches!(live, Claimed::Full)); - assert_eq!(stored(&db).await, (1, 0)); - assert_eq!(strokes(&db).await, 0); - - // The same row, the same instant, against a cap of 5 the caller read - // before it was lowered: admitted. That gap is the over-admission. - assert!(matches!(claim_one(&db, 5, "s2").await, Claimed::Made(_))); - assert_eq!(stored(&db).await, (2, 0)); - } - - /// An unset capacity column means "no cap", which is the bound `$num` - /// fallback — not a cap of zero that refuses everything. - #[tokio::test] - async fn an_absent_live_cap_falls_back_to_the_bound_number() { - let db = a_board(0, 0, false).await; - let made = claim_live_and_create( - &RecordId::new("board", "b"), - BOARD_EPOCH_STROKE_COUNT_FIELD, - "capacity ?? $num", - UNLIMITED, - None, - (&RecordId::new("board_stroke", "s1"), &a_stroke()), - &db, - ) - .await - .unwrap(); - assert!(matches!(made, Claimed::Made(_))); - assert_eq!(stored(&db).await, (1, 0)); - } - #[tokio::test] - async fn a_duplicate_row_claims_no_reference() { - let db = a_slot(0, false).await; - assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Made(_))); - assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Duplicate)); - assert_eq!(refs(&db).await, 1); - assert_eq!(menus(&db).await, 1); + /// The terminal cap outranks the recoverable one: only a soft-full-with- + /// hard-room claim is recoverable, everything else answers Hard — the old + /// claim order (hard first, guard attached), preserved as a re-read. + #[test] + fn the_terminal_cap_outranks_the_recoverable_one() { + // Soft full, hard with room: the one recoverable answer. + assert!(matches!(full_kind(5, 5, 9, 10), FullKind::Soft)); + // Both full: terminal. + assert!(matches!(full_kind(5, 5, 9, 9), FullKind::Hard)); + // Hard full alone. + assert!(matches!(full_kind(4, 5, 9, 9), FullKind::Hard)); + // Neither full — the guard failed or the parent is gone, and both fold + // into the terminal answer, whose contract already covers them. + assert!(matches!(full_kind(4, 5, 8, 9), FullKind::Hard)); + // Boundaries: exactly-at-cap is full. + assert!(matches!(full_kind(5, 5, 10, 10), FullKind::Hard)); } } diff --git a/src/db/field_update.rs b/src/db/field_update.rs index b7b74f7..7f4f657 100644 --- a/src/db/field_update.rs +++ b/src/db/field_update.rs @@ -1,106 +1,131 @@ -//! One `UPDATE $id SET ... RETURN AFTER` built from *only* the fields a PATCH -//! actually carried. +//! One `UPDATE … WHERE id = $n RETURNING *` built from *only* the +//! fields a PATCH actually carried. //! //! WHY: a handler reads the row, then writes. Filling a field the request //! omitted from that snapshot re-sends a value the client never gave, so a //! concurrent PATCH of the *other* field that landed in between is silently -//! reverted — the same lost update a whole-row `.content(self)` save causes, -//! just spelled field by field. Scoping the `SET` is not enough; the *values* must come -//! from the request, so an absent field is never written at all. +//! reverted — the lost update a whole-row save causes, just spelled field by +//! field. Scoping the `SET` is not enough; the *values* must come from the +//! request, so an absent field is never written at all. //! -//! Callers therefore take `Option` per field (`None` = absent, keep) and -//! hand them straight here: +//! Callers take `Option` per field (`None` = absent, keep) and hand them +//! straight here: //! //! ```ignore -//! FieldUpdate::new(self.id.record()) +//! FieldUpdate::new("note", note.id.0) //! .set("title", title) //! .set("content", content) //! .run::(db) //! .await //! ``` //! -//! Clearing a nullable column is `Some(None)` on a `Option>` field -//! — pass it as `Some(value_or_none)` so `NONE` is written explicitly. +//! Clearing a nullable column is `Some(None)` on an `Option>` +//! field — pass it as `Some(value_or_none)` so `NULL` is written explicitly +//! (for a link column, `Param::OptUuid(None)`). +//! +//! Runtime-checked SQL by design (this module is the named exemption from the +//! compile-time `query!` rule): the `SET` list is the request's shape. All +//! emitted statements are plain Postgres — positional `$n` placeholders, the +//! row read back with `RETURNING *` (the old store's return-updated-document +//! spelling), and an explicit clear written as a bound `NULL`; there is no +//! remove-a-key statement a row needs a counterpart for. +//! +//! The dynamic parts of every statement here are table/column names (in-crate +//! `&'static str` constants, never client text) and the `$n` numbers this +//! builder prints itself; every value binds — which is the audit the +//! [`AssertSqlSafe`] wraps stand on. -use surrealdb::types::{RecordId, SurrealValue, Value}; +use sqlx::postgres::{PgArguments, PgRow}; +use sqlx::{AssertSqlSafe, FromRow}; +use uuid::Uuid; -use crate::database::{Database, transaction_with_retry, write_with_retry}; -use crate::db::cap; +use crate::database::{Database, tx_with_retry}; +use crate::db::page::Param; use crate::error::AppError; -/// The `THROW` markers [`FieldUpdate::refcount`]'s transaction aborts with: the -/// row the reference was to be claimed on is gone, the row being patched is -/// gone (or its guard bit), and the link this move started from is no longer -/// the one the handler read. -const CLAIM_MARK: &str = "ref_claim_gone"; -const ROW_MARK: &str = "ref_row_gone"; +/// The statement-shaped markers [`run_with_refcount`]'s transaction aborts +/// with, mapped to their answers right after [`tx_with_retry`] returns. They +/// never reach the wire: a refusal is a decision, never a retry, and the +/// marker `Internal` error is replaced before it can escape. +const REFUSAL_MARK: &str = "ref_claim_gone"; const STALE_MARK: &str = "ref_stale_move"; +const GONE_MARK: &str = "ref_row_gone"; -/// `(counter field, link column, expected link, claim, release, refusal)`. +/// The answer a moved link has always carried. +const STALE_MOVE: &str = "the link this update moves changed since it was read; re-read and retry"; + +/// An abort marker packed as the one error arm no caller ever observes. +fn mark(kind: &'static str) -> AppError { + AppError::Internal(kind.to_owned()) +} + +/// `(counter table, counter field, link column, expected link, claim, release, +/// refusal)`. type Refcount = ( &'static str, &'static str, - Option, - Option, - Option, + &'static str, + Option, + Option, + Option, AppError, ); -pub struct FieldUpdate { - id: RecordId, - /// `field = $field` fragments, in the order they were set. - assignments: Vec, - bindings: Vec<(String, Value)>, +pub(crate) struct FieldUpdate { + /// The row's own table — an in-crate constant, never user input. + table: &'static str, + id: Uuid, + /// `(field, value)` fragments, in the order they were set; a value's + /// placeholder number is its position here plus one. + sets: Vec<(&'static str, Param)>, /// `(low, high, refusal)` for [`FieldUpdate::ordered`]. ordered: Option<(&'static str, &'static str, AppError)>, /// `(condition, refusal)` for [`FieldUpdate::guard`]. guard: Option<(&'static str, AppError)>, - /// `(counter field, link column, expected link, claim, release, refusal)` - /// for [`FieldUpdate::refcount`]. + /// `(counter table, counter field, link column, expected link, claim, + /// release, refusal)` for [`FieldUpdate::refcount`]. refcount: Option, } impl FieldUpdate { - pub fn new(id: RecordId) -> Self { + /// `table` names the row's table; `id` is its uuid primary key. + pub(crate) fn new(table: &'static str, id: Uuid) -> Self { Self { + table, id, - assignments: Vec::new(), - bindings: Vec::new(), + sets: Vec::new(), ordered: None, guard: None, refcount: None, } } - /// Write `field` only when the request carried it. The bind variable is - /// named after the field, so `id` — and `ref_claim`/`ref_release`/ - /// `ref_expected`, which [`FieldUpdate::refcount`] binds — are the names a - /// caller must not use. + /// Write `field` only when the request carried it. The value binds as the + /// `SET` list's next positional parameter, in call order. #[must_use] - pub fn set(mut self, field: &'static str, value: Option) -> Self { + pub(crate) fn set>(mut self, field: &'static str, value: Option) -> Self { if let Some(value) = value { - self.assignments.push(format!("{field} = ${field}")); - self.bindings.push((field.to_string(), value.into_value())); + self.sets.push((field, value.into())); } self } /// Refuse the write unless `low <= high` still holds on the *merged* row — - /// the new value for an end this PATCH carries, the stored column for one it - /// omits. Emitted as a `WHERE` on the same `UPDATE`, so the comparison the - /// handler made against its snapshot is re-made by the database at write - /// time, against the row as it is *then*: two PATCHes each moving one end, - /// each fine on its own, cannot commit an inverted range between them. That - /// is what an in-process `Mutex` used to buy, without a window between the - /// snapshot and the write for a concurrent request to slip into. + /// the new value for an end this PATCH carries, the stored column for one + /// it omits. Emitted as a `WHERE` on the same `UPDATE`, so the comparison + /// the handler made against its snapshot is re-made by the database at + /// write time, against the row as it is *then*: two PATCHes each moving + /// one end, each fine on its own, cannot commit an inverted range between + /// them. That is what an in-process `Mutex` used to buy, without a window + /// between the snapshot and the write for a concurrent request to slip + /// into. /// /// Call it after the `.set()`s of both fields. A PATCH that moves neither - /// end emits no guard at all (nothing to race), matching the lock window it - /// replaces — so a pre-existing inverted row stays editable field by field. - /// `NONE` on either side passes, exactly like - /// [`crate::web::check_time_range`] skipping an absent end. + /// end emits no guard at all (nothing to race), so a pre-existing inverted + /// row stays editable field by field. `NULL` on either side passes, + /// exactly like [`crate::web::check_time_range`] skipping an absent end. #[must_use] - pub fn ordered(mut self, low: &'static str, high: &'static str, refused: AppError) -> Self { + pub(crate) fn ordered(mut self, low: &'static str, high: &'static str, refused: AppError) -> Self { self.ordered = Some((low, high, refused)); self } @@ -108,122 +133,158 @@ impl FieldUpdate { /// Refuse the write unless `condition` — a predicate on this same row — /// still holds at write time. The [`FieldUpdate::ordered`] guard for a /// precondition that is not about a range: a handler that read "nothing - /// references this yet" re-asks the database at the instant it writes, so a - /// reference landing in between refuses the edit instead of being edited - /// out from under. `condition` is always an in-crate SQL literal, never - /// user input. + /// references this yet" re-asks the database at the instant it writes, so + /// a reference landing in between refuses the edit instead of being + /// edited out from under. `condition` is always an in-crate SQL literal, + /// never user input. /// /// A request that carries no field at all emits no `UPDATE`, so it is not /// refused: it writes nothing, and reading the row back is a truthful /// answer to a PATCH that asked for no change. #[must_use] - pub fn guard(mut self, condition: &'static str, refused: AppError) -> Self { + pub(crate) fn guard(mut self, condition: &'static str, refused: AppError) -> Self { self.guard = Some((condition, refused)); self } - /// Move a reference counter *with* this write: `claim` takes one on the row - /// the link moves to, `release` gives one back on the row it moves off, and - /// both ride the same `BEGIN…COMMIT` as the `UPDATE` that moves the link. + /// Move a reference counter *with* this write: `claim` takes one on the + /// row the link moves to (in `counter_table`), `release` gives one back + /// on the row it moves off, and both ride the same transaction as the + /// `UPDATE` that moves the link. /// - /// That is the whole point. A claim sent as its own query leaves a window - /// where a crash strands a count on a row nothing links any more — and a - /// count is what a delete guard reads, so the stranded one makes its parent - /// undeletable forever. `refused` is the answer when the claimed row is gone - /// (the conditional write doubles as the existence check, as in - /// [`crate::db::cap`]); the transaction then aborts, so the release and - /// the row write never happened either. + /// That is the whole point. A claim sent as its own statement leaves a + /// window where a crash strands a count on a row nothing links any more — + /// and a count is what a delete guard reads, so the stranded one makes + /// its parent undeletable forever. `refused` is the answer when the + /// claimed row is gone (the conditional claim doubles as the existence + /// check); the transaction then aborts, so the release and the row write + /// never happened either. /// - /// Only ever called alongside a `.set()` of the very column that carries the - /// link, so the empty-request short-circuit below cannot swallow a move. + /// Only ever called alongside a `.set()` of the very column that carries + /// the link, so the empty-request short-circuit below cannot swallow a + /// move. /// - /// `link` is that column (never `field`: the counter lives on the *other* - /// row, `course_count` on the term against a `term` link) and `expected` is - /// what the handler's snapshot said it held — `None` for a link that was - /// absent. The pair becomes a CAS on the row write, because claim and - /// release are computed from that snapshot: two PATCHes moving the same link - /// A→B both read A, and both would claim B, leaving B counted twice for one - /// link — a count with no link is exactly what makes a term undeletable - /// forever. The loser's row write matches nothing and the whole transaction - /// aborts, so it claims nothing and answers 409. + /// `link` is that column (never a `.set()` field on this row: the counter + /// lives on the *other* table — `course_count` on the term against a + /// `term` link) and `expected` is what the handler's snapshot said it + /// held — `None` for a link that was absent. The pair becomes a CAS on + /// the row write, because claim and release are computed from that + /// snapshot: two PATCHes moving the same link A→B both read A, and both + /// would claim B, leaving B counted twice for one link — a count with no + /// link is exactly what makes a term undeletable forever. The loser's row + /// write matches nothing and the whole transaction aborts, so it claims + /// nothing and answers 409. /// - /// **Carrying the link and shifting a counter are separate questions**, and - /// the CAS keys off the first one — `run` arms it for any request that - /// `.set()` this column, `claim`/`release` both `None` included. A PATCH - /// *re-stating* the link its snapshot showed shifts no counter, but it is - /// the same stale read: run it against a row someone else has since moved - /// and the unguarded write silently drags the link back, stranding the - /// winner's claim on a term nothing points at (undeletable forever) and - /// leaving the reverted-to term linked at zero (deletable while linked). - /// Gating the CAS on the counters is what let that through. + /// **Carrying the link and shifting a counter are separate questions**, + /// and the CAS keys off the first one — `run` arms it for any request + /// that `.set()`s this column, `claim`/`release` both `None` included. A + /// PATCH *re-stating* the link its snapshot showed shifts no counter, but + /// it is the same stale read: run it against a row someone else has since + /// moved and the unguarded write silently drags the link back, stranding + /// the winner's claim on a term nothing points at (undeletable forever) + /// and leaving the reverted-to term linked at zero (deletable while + /// linked). Gating the CAS on the counters is what let that through. #[must_use] - pub fn refcount( + pub(crate) fn refcount( mut self, - field: &'static str, + counter_table: &'static str, + counter_field: &'static str, link: &'static str, - expected: Option, - claim: Option, - release: Option, + expected: Option, + claim: Option, + release: Option, refused: AppError, ) -> Self { - self.refcount = Some((field, link, expected, claim, release, refused)); + self.refcount = Some(( + counter_table, + counter_field, + link, + expected, + claim, + release, + refused, + )); self } /// Run the update and return the stored row. An empty request writes /// nothing at all and reads the row back unchanged. - pub async fn run(mut self, db: &Database) -> Result { - // Armed by the *request*, not by the counters: a PATCH that carries the - // link column gets the CAS even when it re-states the value it read and - // so shifts nothing. Decided here rather than in `refcount` so the - // builder's call order cannot silently disarm it — `run` is always last. - let moved = self.refcount.take(); - let moved = moved.filter(|(_, link, ..)| self.is_set(link)); - if self.assignments.is_empty() { - let row: Option = db.select(self.id).await?; + pub(crate) async fn run(mut self, db: &Database) -> Result + where + T: for<'r> FromRow<'r, PgRow> + Send + Unpin, + { + // Armed by the *request*, not by the counters: a PATCH that carries + // the link column gets the CAS even when it re-states the value it + // read and so shifts nothing. Decided here rather than in `refcount` + // so the builder's call order cannot silently disarm it — `run` is + // always last. + let moved = self.refcount.take().filter(|rc| self.is_set(rc.2)); + if self.sets.is_empty() { + let row: Option = sqlx::query_as(AssertSqlSafe(format!( + "SELECT * FROM {} WHERE id = $1", + self.table + ))) + .bind(self.id) + .fetch_optional(db) + .await?; return row.ok_or(AppError::NotFound); } + // The `SET` list, each value binding as the next positional + // parameter. + let mut binds: Vec = Vec::new(); + let mut set_sql = String::new(); + for (index, (field, value)) in self.sets.iter().enumerate() { + if index > 0 { + set_sql.push_str(", "); + } + set_sql.push_str(field); + set_sql.push_str(&format!(" = ${}", binds.len() + 1)); + binds.push(value.clone()); + } + // Both ends stored: name the placeholder for an end this request set, + // the column for one it left alone. let (ordered, mut refused) = match self.ordered.take() { - // Both ends stored: name the bound variable for an end this request - // set, the column for one it left alone. Some((low, high, err)) if self.is_set(low) || self.is_set(high) => { - let side = |field: &str, set| { + let side = |field: &str, set: bool| { if set { - format!("${field}") + format!("${}", self.number_of(field)) } else { - field.into() + field.to_owned() } }; - let low = side(low, self.is_set(low)); - let high = side(high, self.is_set(high)); ( Some(format!( - "({low} = NONE OR {high} = NONE OR {low} <= {high})" + "({} IS NULL OR {} IS NULL OR {} <= {})", + side(low, self.is_set(low)), + side(high, self.is_set(high)), + side(low, self.is_set(low)), + side(high, self.is_set(high)), )), Some(err), ) } _ => (None, None), }; - // Both guards land on the one `UPDATE`, ANDed. No caller sets both, so - // the refusal is whichever one is there. let (extra, extra_refused) = match self.guard.take() { - Some((condition, err)) => (Some(condition.to_string()), Some(err)), + Some((condition, err)) => (Some(condition.to_owned()), Some(err)), None => (None, None), }; + // No caller sets both, so the refusal is whichever one is there. refused = refused.or(extra_refused); - // A PATCH that does not carry the link at all writes the same unguarded - // `UPDATE` it always did — it re-states nothing and races nobody. Probed - // on the mem engine: - // a bound `None` comes through as `NONE` and `link = NONE` matches a row - // whose option column was never set, while failing one that holds a - // record, so the absent-link shape needs no `??`. - let cas = moved - .as_ref() - .map(|(_, link, ..)| format!("{link} = $ref_expected")); - // The caller's own guards, kept apart from the CAS: the split below has - // to ask "did *only* the link move?", and a probe that ignores them - // answers "the link moved" to a write its `.guard()` refused outright. + // A PATCH that does not carry the link at all writes the same + // unguarded `UPDATE` it always did — it re-states nothing and races + // nobody. The CAS is `IS NOT DISTINCT FROM`, so an absent link + // (bound `None`) still compares truthfully. + let mut expected_at: Option = None; + let cas = moved.as_ref().map(|rc| { + binds.push(Param::OptUuid(rc.3)); + expected_at = Some(binds.len()); + format!("{} IS NOT DISTINCT FROM ${}", rc.2, binds.len()) + }); + // The caller's own guards, kept apart from the CAS: the probe below + // has to ask "did *only* the link move?", and a probe that ignores + // them answers "the link moved" to a write its `.guard()` refused + // outright. let own = ordered .iter() .chain(extra.iter()) @@ -231,262 +292,158 @@ impl FieldUpdate { .collect::>() .join(" AND "); let conditions: Vec = ordered.into_iter().chain(extra).chain(cas).collect(); - let guard = if conditions.is_empty() { + let guard_sql = if conditions.is_empty() { String::new() } else { format!(" WHERE {}", conditions.join(" AND ")) }; - let sets = self.assignments.join(", "); - let sql = format!("UPDATE $id SET {sets}{guard} RETURN AFTER"); - self.bindings.push(("id".into(), self.id.into_value())); - // Retried on a write conflict: a guarded PATCH contends on the very row - // its guard reads, and the loser wrote nothing, so re-sending it is the - // recovery — see [`write_with_retry`]. + // The row id binds last, after the CAS value. + binds.push(Param::Uuid(self.id)); + let id_at = binds.len(); + let update = format!( + "UPDATE {} SET {}{} WHERE id = ${id_at} RETURNING *", + self.table, set_sql, guard_sql + ); let rows: Vec = match moved { - Some(moved) => run_with_refcount(db, &sql, &own, self.bindings, moved).await?, - None => write_with_retry(db, &sql, &self.bindings).await?, + Some(rc) => { + let still_mine = if own.is_empty() { + String::new() + } else { + format!("({own}) AND ") + }; + let probe = format!( + "SELECT 1 FROM {} WHERE id = ${id_at} AND {still_mine}{} \ + IS DISTINCT FROM ${} LIMIT 1", + self.table, + rc.2, + expected_at.expect("the CAS arms with its link"), + ); + run_with_refcount::(db, update, probe, binds, rc).await? + } + None => { + let mut args = PgArguments::default(); + for bind in binds { + bind.add_to(&mut args); + } + sqlx::query_as_with(AssertSqlSafe(update), args) + .fetch_all(db) + .await? + } }; - // No row back means the guard bit (or, in the window after the handler's - // read, the row was deleted — the guard cannot tell the two apart, and - // reports the refusal it was given). + // No row back means the guard bit failed (or, in the window after the + // handler's read, the row was deleted — the guard cannot tell the two + // apart, and reports the refusal it was given). rows.into_iter() .next() .ok_or_else(|| refused.take().unwrap_or(AppError::NotFound)) } + /// The `$n` the field's value bound as (set order is bind order). + fn number_of(&self, field: &str) -> usize { + self.sets + .iter() + .position(|(name, _)| *name == field) + .expect("ordered() sides are .set() fields") + + 1 + } + fn is_set(&self, field: &str) -> bool { - self.bindings.iter().any(|(name, _)| name == field) + self.sets.iter().any(|(name, _)| *name == field) } } -/// Send `update` with its counter move, as one transaction. An empty `Vec` back -/// means the row write matched nothing, exactly as [`write_with_retry`] would -/// have reported it, so the caller's refusal is unchanged. +/// Send the update with its counter move, as one transaction. /// /// A re-statement shifts no counter, so `claim` and `release` are both `None` -/// and the transaction is the CAS'd row write and its split alone — still a -/// transaction, because the split's probe must see the same snapshot the write -/// was refused against. +/// and the transaction is the CAS'd row write and its probe alone — still a +/// transaction, because the probe must see the same snapshot the write was +/// refused against. /// -/// Admissible for [`transaction_with_retry`]: every statement is an `UPDATE`, -/// an `IF`/`THROW` or a `RETURN`, and none of those can answer "already -/// exists" — a lost round writes nothing and re-sending it is the recovery. -async fn run_with_refcount( +/// Statement order is the old one, for the old reason: the release goes +/// first, so a move to a counter row that is gone decrements before the claim +/// refuses — and the rolled-back transaction demonstrably undid it. Every +/// abort takes the whole move back with it: nothing is committed unless the +/// row write landed. +async fn run_with_refcount( db: &Database, - update: &str, - own_guards: &str, - mut bindings: Vec<(String, Value)>, - (field, link, expected, claim, release, refused): Refcount, -) -> Result, AppError> { - // Parenthesized `??` throughout: `n ?? 0 + 1` parses as `n ?? (0 + 1)`. - // Both counter writes commit with the row write or neither does, so their - // order is free — the release goes first because that is what makes the - // rollback observable: a move to a term that is gone decrements before the - // claim throws, and the old count still being there proves the abort undid - // it (`a_term_move_to_a_dead_term_leaves_everything_untouched`). - let mut statements: Vec = Vec::new(); - if let Some(release) = release { - statements.push(format!( - "UPDATE $ref_release SET {field} = math::max([({field} ?? 0) - 1, 0])" - )); - bindings.push(("ref_release".into(), release.into_value())); - } - if let Some(claim) = claim { - statements.push(format!( - "LET $seat = (UPDATE $ref_claim SET {field} = ({field} ?? 0) + 1 RETURN VALUE id)" - )); - statements.push(format!( - "IF array::len($seat) = 0 {{ THROW '{CLAIM_MARK}' }}" - )); - bindings.push(("ref_claim".into(), claim.into_value())); - } - bindings.push(("ref_expected".into(), expected.into_value())); - statements.push(format!("LET $row = ({update})")); - // Without this the claim would outlive a row write that matched nothing — - // the very leak the transaction exists to close. Nothing was written yet - // either way, so the probe that tells the two empty cases apart is free to - // be another `UPDATE`: it matches only a row that is *there*, whose *own* - // guards still hold, and whose link has moved off what the handler read — - // which is the CAS, and nothing else, having bitten. A deleted row and a - // plain guard refusal both miss it and keep the answer they have always - // got. Carrying the caller's guards is what keeps that true when a write is - // refused for *both* reasons at once: a `.guard()`/`.ordered()` refusal is - // the caller's own answer to give, and reporting it as "the link moved" - // would send the client to re-read a link that was never its problem. - let still_mine = if own_guards.is_empty() { - String::new() - } else { - format!("({own_guards}) AND ") - }; - statements.push(format!( - "IF array::len($row) = 0 {{ \ - LET $live = (UPDATE $id WHERE {still_mine}{link} != $ref_expected RETURN VALUE id); \ - IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} ELSE {{ THROW '{STALE_MARK}' }} }}" - )); - statements.push("RETURN $row".into()); - let sql = format!( - "BEGIN TRANSACTION; {}; COMMIT TRANSACTION;", - statements.join("; ") - ); - // BEGIN is slot 0, so the trailing RETURN sits at `statements.len()`. - let slot = statements.len(); - - // One counter write in flight at a time, like every other counter write. - let _guard = cap::counter_lock().await; - let (mut result, mut errors) = - transaction_with_retry(db, &sql, &bindings, &[CLAIM_MARK, ROW_MARK, STALE_MARK]).await?; - if errors - .values() - .any(|error| error.to_string().contains(CLAIM_MARK)) - { - return Err(refused); - } - if errors - .values() - .any(|error| error.to_string().contains(STALE_MARK)) - { - return Err(AppError::Conflict( - "the link this update moves changed since it was read; re-read and retry", - )); - } - if errors - .values() - .any(|error| error.to_string().contains(ROW_MARK)) - { - return Ok(Vec::new()); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); + update: String, + probe: String, + binds: Vec, + (counter_table, counter_field, _link, _expected, claim, release, refused): Refcount, +) -> Result, AppError> +where + T: for<'r> FromRow<'r, PgRow> + Send + Unpin, +{ + let mut slot: Option = Some(refused); + let outcome = tx_with_retry(db, false, async |tx| { + let binds = binds.clone(); + if let Some(release) = release { + sqlx::query(AssertSqlSafe(format!( + "UPDATE {counter_table} \ + SET {counter_field} = GREATEST({counter_field} - 1, 0) WHERE id = $1" + ))) + .bind(release) + .execute(&mut *tx) + .await?; + } + // The conditional claim doubles as the existence check: zero rows + // is the claimed row being gone, the caller's own refusal. + if let Some(claim) = claim { + let seat: Option = sqlx::query_scalar(AssertSqlSafe(format!( + "UPDATE {counter_table} SET {counter_field} = {counter_field} + 1 \ + WHERE id = $1 RETURNING 1" + ))) + .bind(claim) + .fetch_optional(&mut *tx) + .await?; + if seat.is_none() { + return Err(slot.take().unwrap_or_else(|| mark(REFUSAL_MARK))); + } + } + let mut args = PgArguments::default(); + for bind in binds.iter().cloned() { + bind.add_to(&mut args); + } + let rows: Vec = sqlx::query_as_with(AssertSqlSafe(update.as_str()), args) + .fetch_all(&mut *tx) + .await?; + if !rows.is_empty() { + return Ok(rows); + } + // Zero rows: the caller's own guard bit, the row deleted in the + // window after the handler's read, or — the CAS only — the link + // moved since the handler read it. Nothing was written yet either + // way, so the probe that tells the cases apart is free: it matches + // only a row that is *there*, whose *own* guards still hold, and + // whose link has moved off what the handler read — which is the + // CAS, and nothing else, having bitten. Carrying the caller's + // guards is what keeps that true when a write is refused for + // *both* reasons at once: a `.guard()`/`.ordered()` refusal is the + // caller's own answer to give, and reporting it as "the link + // moved" would send the client to re-read a link that was never + // its problem. + let mut args = PgArguments::default(); + for bind in binds { + bind.add_to(&mut args); + } + let live: Option = sqlx::query_scalar_with(AssertSqlSafe(probe.as_str()), args) + .fetch_optional(&mut *tx) + .await?; + match live { + Some(_) => Err(mark(STALE_MARK)), + None => Err(mark(GONE_MARK)), + } + }) + .await; + match outcome { + Err(AppError::Internal(m)) if m == REFUSAL_MARK => { + Err(slot.take().unwrap_or_else(|| mark(REFUSAL_MARK))) + } + Err(AppError::Internal(m)) if m == STALE_MARK => Err(AppError::Conflict(STALE_MOVE)), + // The row is gone: exactly the "wrote nothing" answer the plain path + // reports, so the caller's refusal is unchanged. + Err(AppError::Internal(m)) if m == GONE_MARK => Ok(Vec::new()), + other => other, } - // Sound only because the error map came back empty: `take_errors` swap- - // removes errored slots, which would renumber the rest. - Ok(result.take::>(slot)?) } -#[cfg(test)] -mod tests { - use super::*; - use crate::constant::SUBJECT_HOMEWORK_COUNT_FIELD; - use crate::database::init_mem; - - /// Two subjects and one homework tagged with the first. The `course` and - /// `created_by` links point at rows that do not exist — a `record<…>` type - /// constrains the table, not the existence, and nothing here reads them. - async fn seeded() -> Database { - let db = init_mem().await.unwrap(); - db.query( - "CREATE subject:s1 SET course = course:c, name = 'a', description = ''; - CREATE subject:s2 SET course = course:c, name = 'b', description = ''; - CREATE homework:h1 SET course = course:c, subject = subject:s1, - title = 't', due_at = 1, created_by = user:u, created_at = 1;", - ) - .await - .unwrap() - .check() - .unwrap(); - db - } - - /// The two subjects' homework counters, re-read out of the store. - async fn counts(db: &Database) -> Vec { - let mut result = db - .query(format!( - "SELECT VALUE ({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) FROM subject ORDER BY id" - )) - .await - .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap() - } - - fn homework() -> RecordId { - RecordId::new("homework", "h1") - } - - fn subject(key: &str) -> RecordId { - RecordId::new("subject", key) - } - - /// A write refused by the caller's *own* guard must answer with the - /// caller's own refusal, even when the link it carries has also moved since - /// the handler read it. Both are true; only one is the client's problem, - /// and "re-read the link and retry" sends them chasing a `409` that a retry - /// cannot clear — the guard will refuse the next attempt exactly the same. - #[tokio::test] - async fn a_guard_refusal_outranks_a_link_that_also_moved() { - let db = seeded().await; - let refused = FieldUpdate::new(homework()) - .set("subject", Some(subject("s2"))) - .guard("title = 'never'", AppError::Conflict("the caller's own no")) - .refcount( - SUBJECT_HOMEWORK_COUNT_FIELD, - "subject", - // Stale: the row says `s1`, so the CAS bites too. - Some(subject("s9")), - Some(subject("s2")), - Some(subject("s9")), - AppError::Conflict("the subject is gone"), - ) - .run::(&db) - .await - .unwrap_err(); - assert_eq!(refused.to_string(), "conflict: the caller's own no"); - // The abort took the claim with it, and the link never moved. - assert_eq!(counts(&db).await, vec![0, 0]); - } - - /// ...and with the guard satisfied, a moved link is still reported as a - /// moved link — the answer every current caller relies on. - #[tokio::test] - async fn a_moved_link_alone_is_still_the_stale_move_409() { - let db = seeded().await; - let refused = FieldUpdate::new(homework()) - .set("subject", Some(subject("s2"))) - .guard("title = 't'", AppError::Conflict("the caller's own no")) - .refcount( - SUBJECT_HOMEWORK_COUNT_FIELD, - "subject", - Some(subject("s9")), - Some(subject("s2")), - Some(subject("s9")), - AppError::Conflict("the subject is gone"), - ) - .run::(&db) - .await - .unwrap_err(); - assert!( - refused - .to_string() - .contains("the link this update moves changed"), - "{refused}" - ); - assert_eq!(counts(&db).await, vec![0, 0]); - } - - /// The unguarded shape every production caller uses today: the link moves, - /// the counters move with it, in one transaction. - #[tokio::test] - async fn an_unguarded_move_still_lands_with_both_counters() { - let db = seeded().await; - db.query("UPDATE subject:s1 SET homework_count = 1") - .await - .unwrap() - .check() - .unwrap(); - FieldUpdate::new(homework()) - .set("subject", Some(subject("s2"))) - .refcount( - SUBJECT_HOMEWORK_COUNT_FIELD, - "subject", - Some(subject("s1")), - Some(subject("s2")), - Some(subject("s1")), - AppError::Conflict("the subject is gone"), - ) - .run::(&db) - .await - .unwrap(); - assert_eq!(counts(&db).await, vec![0, 1]); - } -} diff --git a/src/db/page.rs b/src/db/page.rs index ce2ba5d..26b9d1a 100644 --- a/src/db/page.rs +++ b/src/db/page.rs @@ -4,250 +4,253 @@ //! WHY: `?limit=10` used to run an unbounded `SELECT *`, hand the whole table //! to the web layer and slice ten rows off it. The scan (and the decode of //! every row) grew with the table no matter how small the page was. Here the -//! window is `LIMIT/START` in SQL, and `total` is a `count()` over the *same* -//! `WHERE`, so a page can never disagree with the count that pages it. +//! window is `LIMIT/OFFSET` in SQL, and `total` is a `count(*)` over the +//! *same* `WHERE` as a second statement, so a page can never disagree with +//! the count that pages it. //! //! ```ignore -//! PagedList::new("note WHERE user = $usr", "ORDER BY id DESC") -//! .bind("usr", owner.record()) +//! PagedList::new("note WHERE user_id = $1", "ORDER BY id DESC") +//! .bind(owner.0) //! .run::(limit, offset, db) //! .await //! ``` //! -//! Paging stays opt-in: `limit = None, offset = 0` is the unpaged read, and it -//! emits exactly one statement (no count — the rows in hand *are* the total), -//! so internal callers that just want the list pay nothing. +//! Paging stays opt-in: `limit = None, offset = 0` is the unpaged read, and +//! it runs exactly one statement (no count — the rows in hand *are* the +//! total), so internal callers that just want the list pay nothing. //! -//! The count's result shape is the planner's to choose (see [`total_of`]) — -//! both shapes decode to the same `total`. +//! Runtime-checked SQL by design: `from_where` is assembled per call site, +//! which is this module's named exemption from the compile-time `query!` +//! rule. Placeholders are positional (`$1, $2, …`) in [`.bind`] order, and +//! the window's own placeholders continue the numbering. The count is a plain +//! `count(*)`, which always answers one `NOT NULL` row — no planner-shape +//! decoding to preserve. +//! +//! The dynamic parts of every statement here are table/column names (in-crate +//! constants and literals, never client text) and the `$n` numbers this +//! builder prints itself; every value binds — which is the audit the +//! [`AssertSqlSafe`] wraps stand on. //! //! Only for lists the database can express whole. A handler that filters rows -//! in Rust after the read (visibility, audience resolution, a schedule window) -//! must keep slicing in the web layer: a DB `LIMIT` in front of a Rust filter -//! silently returns a short page. +//! in Rust after the read (visibility, audience resolution, a schedule +//! window) must keep slicing in the web layer: a DB `LIMIT` in front of a +//! Rust filter silently returns a short page. -use surrealdb::types::{SurrealValue, Value}; +use sqlx::postgres::{PgArguments, PgRow}; +use sqlx::{Arguments, AssertSqlSafe, FromRow}; +use uuid::Uuid; use crate::database::Database; use crate::error::AppError; -pub struct PagedList { - /// Everything after `FROM`, e.g. `note WHERE user = $usr`. Shared verbatim - /// by the page and the count. +/// One bound parameter of a runtime-checked builder's statement, in +/// `$1, $2, …` order. +/// +/// [`PagedList`] and [`crate::db::field_update::FieldUpdate`] are the named +/// exemptions from the compile-time `query!` rule: their SQL is assembled at +/// run time, so their parameters ride this closed enum — owned values, no +/// borrow to tie a builder's lifetime to, [`Clone`] because one builder run +/// can need the same `WHERE` bound twice (page, then count). A caller that +/// needs a type the enum lacks adds a variant here; sqlx's borrow-tied +/// dynamic binding does not survive being stored in a builder. +#[derive(Clone, Debug)] +pub(crate) enum Param { + I64(i64), + Text(String), + Uuid(Uuid), + /// A nullable column value: `None` binds SQL `NULL` with the uuid type + /// still named, so `IS NOT DISTINCT FROM $n` compares an absent link + /// truthfully. + OptUuid(Option), +} + +impl Param { + /// Push onto runtime-checked arguments. sqlx defers encode failures to + /// execution, so there is nothing to check here. + pub(crate) fn add_to(self, args: &mut PgArguments) { + let _ = match self { + Param::I64(value) => args.add(value), + Param::Text(value) => args.add(value), + Param::Uuid(value) => args.add(value), + Param::OptUuid(value) => args.add(value), + }; + } +} + +impl From for Param { + fn from(value: i64) -> Self { + Self::I64(value) + } +} + +impl From for Param { + fn from(value: String) -> Self { + Self::Text(value) + } +} + +impl From for Param { + fn from(value: Uuid) -> Self { + Self::Uuid(value) + } +} + +impl From> for Param { + fn from(value: Option) -> Self { + Self::OptUuid(value) + } +} + +pub(crate) struct PagedList { + /// Everything after `FROM`, e.g. `note WHERE user_id = $1`. Placeholders + /// are positional in [`PagedList::bind`] order; shared verbatim by the + /// page and the count. from_where: String, /// The full `ORDER BY ...`, applied to the page only. order: &'static str, - bindings: Vec<(String, Value)>, + binds: Vec, } impl PagedList { /// `from_where` is a whole-table read (`"term"`) or a filtered one - /// (`"note WHERE user = $usr"`). - pub fn new(from_where: impl Into, order: &'static str) -> Self { + /// (`"note WHERE user_id = $1"`). + pub(crate) fn new(from_where: impl Into, order: &'static str) -> Self { Self { from_where: from_where.into(), order, - bindings: Vec::new(), + binds: Vec::new(), } } - /// Bind one variable of the `WHERE`. `limit` and `offset` are the two names - /// a caller must not use. + /// Bind the next positional parameter: the first call fills `$1`, the + /// second `$2`, … — `from_where` must carry the placeholders in the same + /// order. #[must_use] - pub fn bind(mut self, name: &'static str, value: T) -> Self { - self.bindings.push((name.to_string(), value.into_value())); + pub(crate) fn bind>(mut self, value: T) -> Self { + self.binds.push(value.into()); self } - /// The statements to run, and whether the second one (the count) is among - /// them. Split out so a test can read the SQL: the whole point of this type - /// is that `LIMIT`/`START` reach the database instead of a `Vec` slice. - fn statements(&self, limit: Option, offset: i64) -> (String, bool) { - let from_where = &self.from_where; - let window = match limit { - Some(_) => "LIMIT $limit START $offset", - None => "START $offset", - }; - let mut sql = format!("SELECT * FROM {from_where} {} {window};", self.order); - // A window that can hide rows needs the count; an unpaged read from row - // zero already holds every row, so it stays a single statement. + /// The page statement and, when the window can hide rows, the count + /// statement. Split out so a test can read the SQL: the whole point of + /// this type is that `LIMIT/OFFSET` reach the database instead of a + /// `Vec` slice. + fn statements(&self, limit: Option, offset: i64) -> (String, Option) { + let mut next = self.binds.len(); + let mut sql = format!("SELECT * FROM {} {}", self.from_where, self.order); + if limit.is_some() { + next += 1; + sql.push_str(&format!(" LIMIT ${next}")); + } + // A window that can hide rows needs the count; an unpaged read from + // row zero already holds every row, so it stays a single statement. let counted = limit.is_some() || offset > 0; if counted { - sql.push_str(&format!( - "SELECT VALUE count() FROM {from_where} GROUP ALL;" - )); + next += 1; + sql.push_str(&format!(" OFFSET ${next}")); } - (sql, counted) + let count = counted.then(|| format!("SELECT count(*) FROM {}", self.from_where)); + (sql, count) } /// The page plus the full row count. `limit = None` runs from `offset` to /// the end, matching the unpaged envelope. - pub async fn run( + pub(crate) async fn run( self, limit: Option, offset: i64, db: &Database, - ) -> Result<(Vec, i64), AppError> { - let (sql, counted) = self.statements(limit, offset); - let mut query = db - .query(sql) - .bind(("offset", offset)) - .bind(("limit", limit.unwrap_or(0))); - for (name, value) in self.bindings { - query = query.bind((name, value)); + ) -> Result<(Vec, i64), AppError> + where + T: for<'r> FromRow<'r, PgRow> + Send + Unpin, + { + let (page_sql, count_sql) = self.statements(limit, offset); + let mut args = PgArguments::default(); + for bind in self.binds.iter().cloned() { + bind.add_to(&mut args); } - let mut result = query.await?.check()?; - let rows = result.take::>(0)?; - let total = match counted { - true => total_of(result.take::(1)?)?, - false => rows.len() as i64, + if let Some(limit) = limit { + Param::from(limit).add_to(&mut args); + } + if count_sql.is_some() { + Param::from(offset).add_to(&mut args); + } + let rows: Vec = + sqlx::query_as_with(AssertSqlSafe(page_sql), args).fetch_all(db).await?; + let total = match count_sql { + Some(count_sql) => { + let mut args = PgArguments::default(); + for bind in self.binds { + bind.add_to(&mut args); + } + let scalar: i64 = + sqlx::query_scalar_with(AssertSqlSafe(count_sql), args).fetch_one(db).await?; + scalar + } + None => rows.len() as i64, }; Ok((rows, total)) } } -/// The count statement's slot, in either shape the planner answers in. -/// -/// `SELECT VALUE count() ... GROUP ALL` normally yields the projected int, but -/// whenever the planner can answer the count straight out of an index or the -/// table count (`IndexCountScan` — an indexed field compared to a value known -/// at plan time, `grade IS NONE` or a *literal*, and any bare table read) it -/// returns `{ count: N }` and drops the `SELECT VALUE` projection. Decoding -/// only the int is where "Expected int, got object" came from; the number is -/// the same either way. The in-memory engine never rewrites the plan, so only -/// a real server ever produces the object. -fn total_of(count: Value) -> Result { - // `GROUP ALL` yields no row at all when nothing matched. - let row = match count { - Value::Array(rows) => rows.into_iter().next().unwrap_or_default(), - other => other, - }; - let row = match row { - Value::Object(mut object) => object.remove("count").unwrap_or_default(), - other => other, - }; - match row.is_nullish() { - true => Ok(0), - false => row - .into_t::() - .map_err(|e| AppError::Internal(format!("count decode: {e}"))), - } -} - #[cfg(test)] mod tests { use super::*; - use crate::database; - use crate::db::note; - use crate::domain::note::{NoteContent, NoteTitle}; - use crate::domain::user::UserId; - use ulid::Ulid; fn list() -> PagedList { - PagedList::new("note WHERE user = $usr", "ORDER BY id DESC") + PagedList::new("note WHERE user_id = $1", "ORDER BY id DESC").bind(Uuid::nil()) } - /// The window has to be SQL — a `Vec` slice would leave the scan unbounded, - /// which is the whole reason this type exists. + /// The window has to be SQL — a `Vec` slice would leave the scan + /// unbounded, which is the whole reason this type exists. #[test] fn a_paged_read_windows_and_counts_in_sql() { - let (sql, counted) = list().statements(Some(10), 20); - assert!(sql.contains("ORDER BY id DESC LIMIT $limit START $offset;")); - assert!(sql.contains("SELECT VALUE count() FROM note WHERE user = $usr GROUP ALL;")); - assert!(counted); + let (sql, count) = list().statements(Some(10), 20); + assert!(sql.contains("ORDER BY id DESC LIMIT $2 OFFSET $3")); + assert_eq!( + count.as_deref(), + Some("SELECT count(*) FROM note WHERE user_id = $1") + ); } - /// A whole-table read counts the table as it stands — no `WHERE true` to - /// force a scan, because [`total_of`] now takes the count-from-index shape - /// that hack existed to avoid. + /// A whole-table read counts the bare table. #[test] fn an_unfiltered_list_counts_the_bare_table() { - let (sql, _) = PagedList::new("term", "ORDER BY starts_at DESC").statements(Some(5), 0); - assert!(sql.contains("SELECT VALUE count() FROM term GROUP ALL;")); + let (sql, count) = + PagedList::new("term", "ORDER BY starts_at DESC").statements(Some(5), 0); + assert!(sql.contains("LIMIT $1 OFFSET $2")); + assert_eq!(count.as_deref(), Some("SELECT count(*) FROM term")); } - /// Both shapes of the count slot mean the same number. The object is what - /// a real server returns whenever it answers `count()` from an index or the - /// table count; the in-memory engine only ever produces the int, so this is - /// the only place the object arm can be pinned. Drop that arm and the - /// second assert fails with "count decode: Expected int, got object" — - /// which is the 500 `GET /classes?grade=&limit=1` served. - #[test] - fn a_count_decodes_from_either_shape() { - let projected = Value::Array([Value::from_t(7i64)].into_iter().collect()); - let from_index = Value::Array( - [Value::Object( - [("count".to_string(), Value::from_t(7i64))] - .into_iter() - .collect(), - )] - .into_iter() - .collect(), - ); - assert_eq!(total_of(projected).unwrap(), 7); - assert_eq!(total_of(from_index).unwrap(), 7); - // `GROUP ALL` yields no row at all when nothing matched. - assert_eq!(total_of(Value::Array(Default::default())).unwrap(), 0); - // Any other shape is an error, never a silently wrong `total`. - assert!(total_of(Value::Array([Value::from_t("7")].into_iter().collect())).is_err()); - } - - /// Unpaged from row zero: the rows in hand are the total, so no count runs. + /// Unpaged from row zero: the rows in hand are the total, so no count + /// runs. #[test] fn an_unpaged_read_stays_one_statement() { - let (sql, counted) = list().statements(None, 0); - assert!(sql.ends_with("ORDER BY id DESC START $offset;")); - assert!(!sql.contains("count()")); - assert!(!counted); + let (sql, count) = list().statements(None, 0); + assert_eq!( + sql, + "SELECT * FROM note WHERE user_id = $1 ORDER BY id DESC" + ); + assert_eq!(count, None); // An offset without a limit still hides rows, so it needs the count. - assert!(list().statements(None, 3).1); + let (sql, count) = list().statements(None, 3); + assert!(sql.contains("OFFSET $2")); + assert!(!sql.contains("LIMIT")); + assert!(count.is_some()); } - #[tokio::test] - async fn the_window_walks_the_rows_and_total_stays_the_whole_list() { - let db = database::init_mem().await.unwrap(); - let user = UserId::from_key(&Ulid::generate().to_string()); - for i in 0..5 { - note::create( - &db, - &user, - NoteTitle::try_new(&format!("n{i}")).unwrap(), - NoteContent::try_new("x").unwrap(), - ) - .await - .unwrap(); - } - - // Every page is `limit` long and `total` ignores the window. - let (page, total) = note::list_for(&db, &user, Some(2), 0).await.unwrap(); - assert_eq!((page.len(), total), (2, 5)); - let (tail, total) = note::list_for(&db, &user, Some(2), 4).await.unwrap(); - assert_eq!((tail.len(), total), (1, 5)); - // Offset past the end is an empty page, not an error. - assert_eq!( - note::list_for(&db, &user, Some(2), 9) - .await - .unwrap() - .0 - .len(), - 0 - ); - // Unpaged, and unpaged-from-an-offset: the count still covers everything. - let (all, total) = note::list_for(&db, &user, None, 0).await.unwrap(); - assert_eq!((all.len(), total), (5, 5)); - let (rest, total) = note::list_for(&db, &user, None, 3).await.unwrap(); - assert_eq!((rest.len(), total), (2, 5)); - - // The pages are consecutive slices of the unpaged list — page - // boundaries match the order the ORDER BY already produced. - let keys: Vec<&str> = all.iter().map(|note| note.get_id().key()).collect(); - assert_eq!( - page.iter().map(|n| n.get_id().key()).collect::>(), - keys[..2] - ); + /// The window's placeholders continue the caller's numbering, in emission + /// order. + #[test] + fn window_placeholders_continue_the_where_numbering() { + let (sql, count) = + PagedList::new("note WHERE user_id = $1 AND archived_at IS NULL", "ORDER BY id") + .bind(Uuid::nil()) + .statements(Some(2), 4); + assert!(sql.contains("LIMIT $2 OFFSET $3")); assert_eq!( - tail.iter().map(|n| n.get_id().key()).collect::>(), - keys[4..] + count.as_deref(), + Some("SELECT count(*) FROM note WHERE user_id = $1 AND archived_at IS NULL") ); } } diff --git a/src/domain/answer_image.rs b/src/domain/answer_image.rs index 9cca78d..19fad3c 100644 --- a/src/domain/answer_image.rs +++ b/src/domain/answer_image.rs @@ -2,48 +2,49 @@ //! one (exam, user, question), mirroring [`crate::domain::question_image`] but //! keyed by the answering student instead of a choice slot. The row carries //! metadata; the bytes live on disk under [`crate::config::Config::files_path`] -//! in a file named by `file` — a fresh server-generated ULID per upload, so no +//! in a file named by `file` — a fresh server-generated UUID per upload, so no //! user input ever shapes a disk path and a replace never overwrites bytes in -//! place. The row id is *deterministic* per (question, user, seq) — the same -//! shape as [`crate::domain::exam_attempt::ExamAttemptId::composite`] — so "one +//! place. The row is keyed by (question, user, seq) — the same shape as +//! [`crate::domain::exam_attempt::ExamAttemptId`] — so "one //! drawing per student per question per sitting" holds by construction and a -//! replace within a sitting is a plain UPSERT, while a retake (`seq + 1`) -//! accumulates its own rows instead of overwriting. The queries and -//! transactions over these rows live in [`crate::db::answer_image`]; the web -//! layer owns the blob I/O and its ordering (new blob before row, row before -//! old blob). +//! replace within a sitting is a plain UPSERT on the composite primary key, +//! while a retake (`seq + 1`) accumulates its own rows instead of +//! overwriting. The queries and transactions over these rows live in +//! [`crate::db::answer_image`]; the web layer owns the blob I/O and its +//! ordering (new blob before row, row before old blob). -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; - -use crate::constant::ANSWER_IMAGE_TABLE; use crate::domain::exam::ExamId; use crate::domain::exam_question::ExamQuestionId; use crate::domain::key; use crate::domain::note_file::FileContentType; use crate::domain::user::UserId; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct AnswerImageId(RecordId); +/// The identity of one (question, user, seq) triple — a sitting's drawing. +/// Not a row column: the table's primary key *is* the (question, user, seq) +/// triple, and this struct's job is the underscore-joined wire form at the +/// HTTP edge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AnswerImageId { + pub(crate) question: ExamQuestionId, + pub(crate) user: UserId, + pub(crate) seq: i64, +} impl AnswerImageId { /// The one id a (question, user, seq) triple can have, so "one drawing per /// student per question per sitting" needs no index. See [`key::sitting`] - /// for the key shape and why the first sitting stays bare. + /// for the wire shape and why the first sitting stays bare. pub fn composite(question: &ExamQuestionId, user: &UserId, seq: i64) -> Self { - let key = key::sitting(question.key(), user.key(), seq); - Self(RecordId::new(ANSWER_IMAGE_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self { + question: question.clone(), + user: user.clone(), + seq, + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The underscore-joined wire form (`{question}_{user}[_{seq}]`). + pub fn key(&self) -> String { + key::sitting(self.question.key().as_str(), self.user.key().as_str(), self.seq) } } @@ -51,16 +52,15 @@ impl AnswerImageId { /// [`crate::domain::exam_answer::ExamAnswer`]) so per-exam reads (cascade) and /// per-(exam, user) reads (sitting/grading views, retake blob-GC) don't fan out /// through `exam_question`. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct AnswerImage { - pub(crate) id: AnswerImageId, pub(crate) exam: ExamId, pub(crate) question: ExamQuestionId, pub(crate) user: UserId, /// Which sitting this drawing belongs to — 1 for the first attempt, /// counting up, so retakes accumulate instead of overwriting. pub(crate) seq: i64, - /// The blob's on-disk name — a fresh ULID every upload. + /// The blob's on-disk name — a fresh UUID every upload. pub(crate) file: String, pub(crate) content_type: FileContentType, pub(crate) size: i64, @@ -80,12 +80,11 @@ impl AnswerImage { size: i64, ) -> Self { Self { - id: AnswerImageId::composite(question, user, seq), exam: exam.clone(), question: question.clone(), user: user.clone(), seq, - file: Ulid::generate().to_string(), + file: uuid::Uuid::new_v4().to_string(), content_type, size, } diff --git a/src/domain/appointment.rs b/src/domain/appointment.rs index fb01ff0..9301baf 100644 --- a/src/domain/appointment.rs +++ b/src/domain/appointment.rs @@ -9,90 +9,59 @@ //! //! The *cross-record* invariants live one layer down: //! -//! - **One live booking per slot** — the `occupied` counter on the slot row, a -//! [`cap`](crate::db::cap) of one. [`crate::service::appointment::book`] -//! claims it *with* the booking row -//! ([`cap::claim_and_create`](crate::db::cap::claim_and_create)); rejecting -//! or cancelling gives it back in the *same transaction* as the status flip +//! - **One live booking per slot** — the `occupied` counter on the slot row, +//! a [`cap`](crate::db::cap) of one. [`crate::service::appointment::book`] +//! claims it *with* the booking row; rejecting or cancelling gives it back +//! in the *same transaction* as the status flip //! ([`crate::db::appointment::save_if_unchanged`]), so the slot frees itself -//! with nothing to sweep. Both are single-record conditional writes, so the -//! store decides it, not a lock. -//! - **No double-booked person.** An approved meeting may not overlap another -//! approved meeting of the same teacher *or* of the same requester. That is a -//! count-then-write over *many* rows, which a `BEGIN…COMMIT` does not -//! serialize in SurrealDB (write-skew), so booking and approval hold -//! [`crate::service::appointment::APPOINTMENT_LOCK`], which is the whole -//! guarantee behind it. +//! with nothing to sweep. +//! - **No double-booked teacher window.** Two overlapping published windows +//! cannot both exist — the `appointment_slot` exclusion constraint refuses +//! the second insert at the store, which is what replaced the +//! [`crate::service::appointment::APPOINTMENT_LOCK`] serialization. //! //! The *single-row* invariant — a decision must be written onto the state it -//! was validated against — is **not** the lock's job, and never was: a -//! whole-row save built on a snapshot read before the lock was taken would -//! silently drop whatever landed in between. That one is a compare-and-set -//! ([`crate::db::appointment::save_if_unchanged`]), decided by the store. -//! -//! Overlap therefore rests on the lock alone — it is a predicate over *other* -//! rows, with no single row to key a counter or a CAS on. That holds while -//! every approving write takes the lock; one that skips it puts two -//! meetings in one half-hour, so the rule is stated at the lock rather than -//! left to be noticed. The damage if it ever happens is one double-booked -//! half-hour, visible to both parties and fixable by cancelling either -//! side — no money, no grade, no data loss. - -use std::sync::LazyLock; +//! was validated against — is a compare-and-set +//! ([`crate::db::appointment::save_if_unchanged`]), decided by a conditional +//! `UPDATE`. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Generator; - -use crate::constant::{APPOINTMENT_TABLE, MAX_APPOINTMENT_REASON_LEN}; +use crate::constant::{MAX_APPOINTMENT_REASON_LEN}; use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId}; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::validate_required; -/// Mints booking ids in write order — `Ulid::generate()`'s random low bits sort -/// arbitrarily within one millisecond, which would scramble the `id` tie-break -/// of the newest-first listings ([`crate::db::appointment::list_for_requester`]). -static IDS: LazyLock> = - LazyLock::new(|| std::sync::Mutex::new(Generator::new())); - -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct AppointmentId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct AppointmentId(uuid::Uuid); impl AppointmentId { + /// Mints in write order — the `id` tie-break of the newest-first listings + /// ([`crate::db::appointment::list_for_requester`]) must not scramble rows + /// minted inside one millisecond. pub fn generate() -> Self { - let mut ids = IDS.lock().expect("appointment id generator poisoned"); - // The only error is exhausting the random bits within one millisecond - // (2^80 ids deep); it clears itself as the clock ticks, so retry. - let ulid = loop { - if let Ok(ulid) = ids.generate() { - break ulid; - } - }; - Self(RecordId::new(APPOINTMENT_TABLE, ulid.to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row — a malformed path param stays a 404, exactly + /// like a well-formed one that names nothing. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(APPOINTMENT_TABLE, key)) + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -/// Where a booking stands. `untagged` + `rename_all` store it as the bare -/// lowercase string the `status` column types as; an unknown value comes back -/// as a deserialization error, never a panic. -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] -#[surreal(untagged, rename_all = "lowercase")] +/// Where a booking stands. Stored as the bare lowercase string the `status` +/// column's CHECK allows; an unknown value comes back as a decode error, +/// never a panic. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] pub enum AppointmentStatus { Pending, Approved, @@ -123,7 +92,8 @@ impl AppointmentStatus { /// Why the requester wants the meeting. Required: a teacher approving a /// parent-teacher conference needs to know what it is about. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct AppointmentReason(String); impl AppointmentReason { @@ -140,7 +110,7 @@ impl AppointmentReason { /// Fields are crate-visible: [`crate::db::appointment`] reads the columns its /// compare-and-set discriminates on, and [`crate::service::appointment`] /// clones a fresh read and mutates the decision onto it. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Appointment { pub(crate) id: AppointmentId, pub(crate) slot: AppointmentSlotId, @@ -154,15 +124,10 @@ pub struct Appointment { pub(crate) proposed_ends_at: Option, pub(crate) proposed_by: Option, pub(crate) decided_by: Option, - /// Who called the meeting off, and why, once it is `cancelled`. Both - /// `#[surreal(default)]` so bookings written before cancellation records - /// existed still read back (they resolve to `None`). - #[surreal(default)] + /// Who called the meeting off, and why, once it is `cancelled`. pub(crate) cancelled_by: Option, - #[surreal(default)] pub(crate) cancel_reason: Option, /// Why the request was turned down; the rejecter is already on `decided_by`. - #[surreal(default)] pub(crate) reject_reason: Option, pub(crate) created_at: Timestamp, } @@ -259,7 +224,6 @@ impl Appointment { #[cfg(test)] mod tests { use super::*; - use surrealdb::types::Value; fn at(millis: i64) -> Timestamp { Timestamp::from_millis(millis) @@ -273,22 +237,19 @@ mod tests { assert!(AppointmentReason::try_new(&"x".repeat(MAX_APPOINTMENT_REASON_LEN + 1)).is_err()); } - /// The `status` column is `TYPE string`: an object-wrapped enum would be - /// rejected on write, and the `status IN ['pending','approved']` occupancy - /// query is written against exactly these spellings. - #[tokio::test] - async fn status_stores_as_a_bare_string() { - for status in [ - AppointmentStatus::Pending, - AppointmentStatus::Approved, - AppointmentStatus::Rejected, - AppointmentStatus::Cancelled, + /// The `status` column is `TEXT` with a CHECK listing exactly these + /// spellings: the occupancy query is written against them, so the storage + /// form may not drift from `as_str`. + #[test] + fn status_stores_as_a_bare_string() { + for (status, spelling) in [ + (AppointmentStatus::Pending, "pending"), + (AppointmentStatus::Approved, "approved"), + (AppointmentStatus::Rejected, "rejected"), + (AppointmentStatus::Cancelled, "cancelled"), ] { - let value = status.into_value(); - assert_eq!(value, Value::String(status.as_str().to_string())); - assert_eq!(AppointmentStatus::from_value(value).unwrap(), status); + assert_eq!(status.as_str(), spelling); } - assert!(AppointmentStatus::from_value(Value::String("declined".into())).is_err()); assert!(AppointmentStatus::Pending.is_live()); assert!(AppointmentStatus::Approved.is_live()); assert!(!AppointmentStatus::Rejected.is_live()); diff --git a/src/domain/appointment_slot.rs b/src/domain/appointment_slot.rs index 6e55f51..c220293 100644 --- a/src/domain/appointment_slot.rs +++ b/src/domain/appointment_slot.rs @@ -5,69 +5,65 @@ //! `series` id, so no recurrence rule is ever evaluated at read time and //! cancelling one week is a plain row delete. //! -//! The one piece of booking state a slot carries is the `occupied` counter (a -//! [`cap`](crate::db::cap) of one), taken when a booking is made and given +//! The one piece of booking state a slot carries is the `occupied` counter, a +//! [`cap`](crate::db::cap) of one, taken when a booking is made and given //! back in the same transaction as the reject or cancel that settles it — so //! the slot frees itself again, and unlike a UNIQUE index it does not keep a //! dead booking's seat. Stored rather than counted from the //! [appointment](crate::domain::appointment::Appointment) rows because a //! conditional write on one row is the only guard a concurrent booking cannot -//! outrun. The reads and writes behind it live in -//! [`crate::db::appointment_slot`]; the publish and delete workflows under -//! [`crate::service::appointment::APPOINTMENT_LOCK`] live in -//! [`crate::service::appointment_slot`]. - -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +//! outrun. Two overlapping windows of one teacher cannot both be published: +//! the `appointment_slot` span exclusion constraint refuses the second +//! insert, which is what replaced the +//! [`crate::service::appointment::APPOINTMENT_LOCK`]. The reads and writes +//! live in [`crate::db::appointment_slot`]; the publish and delete workflows +//! in [`crate::service::appointment_slot`]. use crate::constant::{ - APPOINTMENT_SLOT_TABLE, MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, + MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, }; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::validate_optional; // Slot ids come from [`crate::domain::monotonic_id`]: a recurring publish -// writes its whole expansion inside one millisecond, which random ULID low -// bits would scramble against the `id` tie-break of the `ORDER BY starts_at, -// id` listings. +// writes its whole expansion inside one millisecond, which random UUID +// low bits would scramble against the `id` tie-break of the +// `ORDER BY starts_at, id` listings. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct AppointmentSlotId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct AppointmentSlotId(uuid::Uuid); impl AppointmentSlotId { pub fn generate() -> Self { - Self(RecordId::new( - APPOINTMENT_SLOT_TABLE, - next_ulid().to_string(), - )) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row — a malformed path param stays a 404, exactly + /// like a well-formed one that names nothing. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(APPOINTMENT_SLOT_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } /// The id shared by every occurrence one recurring publish created. A plain -/// ULID string (not a record id): it names a group, never a row. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +/// UUID string (not a row id): it names a group, never a row — the column +/// stays `TEXT`, so cancelling one week is still `DELETE … WHERE series = $1`. +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct SlotSeries(String); impl SlotSeries { pub fn generate() -> Self { - Self(next_ulid().to_string()) + Self(next_uuid().to_string()) } pub fn from_key(key: &str) -> Self { @@ -79,7 +75,8 @@ impl SlotSeries { } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct SlotNote(String); impl SlotNote { @@ -95,8 +92,10 @@ impl SlotNote { /// The half-open window `[starts_at, ends_at)` a slot offers. Half-open is the /// whole point: back-to-back slots (10:00–10:30, 10:30–11:00) touch without -/// overlapping, which is exactly how a teacher's hour is carved up. -#[derive(Debug, Clone, SurrealValue)] +/// overlapping, which is exactly how a teacher's hour is carved up. The same +/// half-open semantics are what the stored `span` range and its exclusion +/// constraint enforce at publish time. +#[derive(Debug, Clone, sqlx::FromRow)] pub struct AppointmentSlot { pub(crate) id: AppointmentSlotId, pub(crate) teacher: UserId, diff --git a/src/domain/attendance.rs b/src/domain/attendance.rs index 6649f48..1306f2f 100644 --- a/src/domain/attendance.rs +++ b/src/domain/attendance.rs @@ -1,34 +1,29 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::ATTENDANCE_TABLE; use crate::domain::event::EventId; use crate::domain::user::UserId; use crate::error::ValidationError; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct AttendanceId(RecordId); +/// The identity of one (event, user) pair. Not a row column: the table's +/// primary key *is* the pair, which is what makes marking a single atomic +/// UPSERT (`ON CONFLICT (event, app_user)`) with no find-then-insert race, +/// one-row-per-pair by construction. This struct's job is the +/// underscore-joined wire form at the HTTP edge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AttendanceId { + pub(crate) event: EventId, + pub(crate) user: UserId, +} impl AttendanceId { - /// A deterministic id for the (event, user) pair. Because the same pair - /// always maps to the same record id, marking is a single atomic UPSERT with - /// no find-then-insert race, and one-row-per-pair holds by construction. - /// ULID keys are alphanumeric, so `_` is an unambiguous joiner. pub fn composite(event: &EventId, user: &UserId) -> Self { - Self(RecordId::new( - ATTENDANCE_TABLE, - format!("{}_{}", event.key(), user.key()), - )) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self { + event: event.clone(), + user: user.clone(), + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The underscore-joined wire form (`{event}_{user}`). + pub fn key(&self) -> String { + format!("{}_{}", self.event.key(), self.user.key()) } } @@ -36,7 +31,8 @@ impl AttendanceId { /// ([`crate::domain::settings::Settings::get_attendance_statuses`]): the core /// `present | absent | late | excused` plus any the school added. Stored rows /// keep their status even if the school later edits the list. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct AttendanceStatus(String); impl AttendanceStatus { @@ -55,9 +51,8 @@ impl AttendanceStatus { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Attendance { - pub(crate) id: AttendanceId, pub(crate) event: EventId, pub(crate) user: UserId, pub(crate) status: AttendanceStatus, @@ -65,8 +60,9 @@ pub struct Attendance { } impl Attendance { - pub fn get_id(&self) -> &AttendanceId { - &self.id + /// The row's identity, built back from its primary-key columns. + pub fn get_id(&self) -> AttendanceId { + AttendanceId::composite(&self.event, &self.user) } pub fn get_event(&self) -> &EventId { diff --git a/src/domain/badge.rs b/src/domain/badge.rs index f9fdfe6..451f185 100644 --- a/src/domain/badge.rs +++ b/src/domain/badge.rs @@ -14,8 +14,6 @@ //! table, so [`earned`] is a total function of [`BadgeStats`] with no I/O //! and no configuration behind it. -use surrealdb::types::SurrealValue; - use crate::constant::{ BADGES, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD, HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD, @@ -95,9 +93,11 @@ impl BadgeStat { } /// The lifetime counters one user has accumulated, as the badge rules see -/// them. Every field is a count and never an `Option`: no rows is a true zero, -/// and an account that predates the columns reads like a fresh one. -#[derive(Debug, Clone, Default, SurrealValue)] +/// them. Every field is a count and never an `Option`: the columns are +/// `BIGINT NOT NULL DEFAULT 0`, so no rows is a true zero. +/// Not a row shape of its own — it is a projection the user-row queries +/// select into (`SELECT homework_submitted, … FROM app_user WHERE id = $1`). +#[derive(Debug, Clone, Default, sqlx::FromRow)] pub struct BadgeStats { homework_submitted: i64, homework_on_time: i64, @@ -195,8 +195,10 @@ pub fn earned(stats: &BadgeStats) -> Vec<&'static str> { .collect() } -/// One badge one user has earned, and when. -#[derive(Debug, Clone, SurrealValue)] +/// One badge one user has earned, and when — a projection of the `badge_award` +/// row (whose identity is the (user, badge) pair) down to the two served +/// columns. +#[derive(Debug, Clone, sqlx::FromRow)] pub struct BadgeAward { badge: String, earned_at: Timestamp, @@ -240,8 +242,8 @@ mod tests { } } - #[tokio::test] - async fn the_rule_takes_every_threshold_at_or_below_the_count() { + #[test] + fn the_rule_takes_every_threshold_at_or_below_the_count() { let stats = BadgeStats { homework_submitted: 10, homework_on_time: 9, diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index eddc136..98c1821 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -10,14 +10,14 @@ //! Pure types only: the queries live in [`crate::db::bank_question`], the //! PATCH re-derive in [`crate::service::bank_question`]. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use sqlx::types::Json; -use crate::constant::{BANK_QUESTION_TABLE, BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL}; +use crate::constant::{BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL}; use crate::domain::exam::ExamId; use crate::domain::exam_question::{ Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, }; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::subject::SubjectId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -28,10 +28,11 @@ use crate::error::ValidationError; /// /// **The default is `private`, deliberately.** A template carries `correct`, the /// answer key, and its images: publishing one is an explicit act, never a side -/// effect of saving a question to the bank. `#[surreal(default)]` on the field -/// means rows written before this existed decode as `private` too, so the bank -/// can't retroactively broadcast anyone's answer keys. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +/// effect of saving a question to the bank. A new row defaults to `private` +/// (the column is `TEXT NOT NULL DEFAULT 'private'`), so the bank can't +/// retroactively broadcast anyone's answer keys. +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct BankVisibility(String); impl Default for BankVisibility { @@ -61,31 +62,28 @@ impl BankVisibility { } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct BankQuestionId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct BankQuestionId(uuid::Uuid); impl BankQuestionId { /// A write-ordered id. `list` sorts `id DESC` to mean "newest first", and - /// a random ULID is only millisecond-accurate — templates saved inside one - /// tick (a to-bank burst, a test loop) would come back shuffled, so the id - /// comes from [`crate::domain::monotonic_id`] instead. + /// a plain random UUID is only millisecond-accurate — templates saved + /// inside one tick (a to-bank burst, a test loop) would come back + /// shuffled, so the id comes from [`crate::domain::monotonic_id`] instead. pub fn generate() -> Self { - Self(RecordId::new(BANK_QUESTION_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row — a malformed path param stays a 404, exactly + /// like a well-formed one that names nothing. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(BANK_QUESTION_TABLE, key)) + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } @@ -95,30 +93,25 @@ impl BankQuestionId { /// subject when a template is copied into an exam, not here. /// /// `subject` is optional because it is *only* metadata: deleting a subject -/// clears it school-wide (see [`crate::db::subject::delete`]) +/// nulls it school-wide (see [`crate::db::subject::delete`]) /// rather than being blocked by the bank. Blocking would have been a dead end /// — the bank is owner-or-admin editable, so a manager could not resolve their /// own 409 — and an existence oracle, since another teacher's *private* /// template would have raised it. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct BankQuestion { pub(crate) id: BankQuestionId, pub(crate) owner: UserId, /// The origin subject, or `None` once that subject was deleted. - /// `#[surreal(default)]` for the same reason `visibility` has one: rows - /// written before the field went optional still decode. - #[surreal(default)] pub(crate) subject: Option, pub(crate) text: QuestionText, pub(crate) kind: QuestionKind, pub(crate) points: QuestionPoints, - pub(crate) choices: Option>, + pub(crate) choices: Option>>, pub(crate) correct: Option, /// The exam question this template was saved from, if any. pub(crate) source_exam: Option, - /// Who may read it. `#[surreal(default)]` (not serde — that doesn't compile - /// here): rows written before the field existed decode as `private`. - #[surreal(default)] + /// Who may read it; defaults to `private` at the column. pub(crate) visibility: BankVisibility, pub(crate) created_at: Timestamp, } @@ -148,10 +141,6 @@ impl BankQuestion { self.points } - pub fn get_choices(&self) -> Option<&[Choice]> { - self.choices.as_deref() - } - pub fn get_correct(&self) -> Option<&ChoiceId> { self.correct.as_ref() } @@ -176,7 +165,7 @@ impl BankQuestion { pub fn spec(&self) -> QuestionSpec { QuestionSpec::from_stored( self.kind.clone(), - self.choices.clone(), + self.choices.as_ref().map(|json| json.0.clone()), self.correct.clone(), ) } @@ -201,7 +190,7 @@ impl BankQuestion { text, kind, points, - choices, + choices: choices.map(Json), correct, source_exam, visibility, @@ -209,15 +198,3 @@ impl BankQuestion { } } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn visibility_rejects_anything_else() { - assert!(BankVisibility::try_new("public").is_err()); - assert!(BankVisibility::try_new("").is_err()); - assert!(BankVisibility::try_new("school").unwrap().is_school()); - } -} diff --git a/src/domain/bank_question_image.rs b/src/domain/bank_question_image.rs index 5e097a1..1467281 100644 --- a/src/domain/bank_question_image.rs +++ b/src/domain/bank_question_image.rs @@ -1,58 +1,56 @@ //! An image pinned to a bank question — the question's own illustration -//! (`slot = NONE`) or one choice's picture (`slot` = that choice's stable id, +//! (`slot = NULL`) or one choice's picture (`slot` = that choice's stable id, //! choice questions only). //! A structural copy of [`crate::domain::question_image`] with the exam FK //! dropped: a bank template belongs to no exam, and its owner is reachable //! through the `bank_question` row. The row carries metadata; the bytes live //! on disk under [`crate::config::Config::files_path`] in a file named by -//! `file` — a fresh server-generated ULID per upload. The row id is -//! *deterministic* per (question, slot), so "one image per slot" holds by -//! construction and a replace is a plain UPSERT. The web layer owns the blob -//! I/O and its ordering; the queries live in +//! `file` — a fresh server-generated UUID per upload. The row is keyed by +//! (question, slot) under a `NULLS NOT DISTINCT` unique constraint, so "one +//! image per slot" holds by construction and a replace is a plain UPSERT. The +//! web layer owns the blob I/O and its ordering; the queries live in //! [`crate::db::bank_question_image`]. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; - -use crate::constant::BANK_QUESTION_IMAGE_TABLE; use crate::domain::bank_question::BankQuestionId; use crate::domain::exam_question::ChoiceId; use crate::domain::key; use crate::domain::note_file::FileContentType; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct BankQuestionImageId(RecordId); +/// The identity of one (question, slot) pair. Not a row column: the table's +/// unique constraint *is* the pair, and this struct's job is the +/// underscore-joined wire form at the HTTP edge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BankQuestionImageId { + pub(crate) question: BankQuestionId, + pub(crate) slot: Option, +} impl BankQuestionImageId { - /// The one id a (question, slot) pair can have — see [`key::slot`] for the - /// key shape and why the two forms can never collide. + /// The one id a (question, slot) pair can have — see [`key::slot`] for + /// the wire shape and why the two forms can never collide. pub fn for_slot(question: &BankQuestionId, slot: Option<&ChoiceId>) -> Self { - Self(RecordId::new( - BANK_QUESTION_IMAGE_TABLE, - key::slot(question.key(), slot.map(|id| id.as_str())), - )) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self { + question: question.clone(), + slot: slot.cloned(), + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The underscore-joined wire form (`{question}_{slot|q}`). + pub fn key(&self) -> String { + key::slot( + self.question.key().as_str(), + self.slot.as_ref().map(|id| id.as_str()), + ) } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct BankQuestionImage { - pub(crate) id: BankQuestionImageId, pub(crate) bank_question: BankQuestionId, - /// `NONE` = the question's illustration; otherwise the id of the option + /// `NULL` = the question's illustration; otherwise the id of the option /// this picture belongs to. pub(crate) slot: Option, - /// The blob's on-disk name — a fresh ULID every upload. + /// The blob's on-disk name — a fresh UUID every upload. pub(crate) file: String, pub(crate) content_type: FileContentType, pub(crate) size: i64, @@ -70,17 +68,17 @@ impl BankQuestionImage { size: i64, ) -> Self { Self { - id: BankQuestionImageId::for_slot(question, slot), bank_question: question.clone(), slot: slot.cloned(), - file: Ulid::generate().to_string(), + file: uuid::Uuid::new_v4().to_string(), content_type, size, } } - pub fn get_id(&self) -> &BankQuestionImageId { - &self.id + /// The row's identity, built back from its unique-key columns. + pub fn get_id(&self) -> BankQuestionImageId { + BankQuestionImageId::for_slot(&self.bank_question, self.slot.as_ref()) } pub fn get_bank_question(&self) -> &BankQuestionId { @@ -135,15 +133,15 @@ mod tests { #[test] fn for_slot_keys_by_question_and_choice_id() { - let question = BankQuestionId::from_key("abc"); + let question = BankQuestionId::from_key("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"); let ids = choice_ids(); assert_eq!( BankQuestionImageId::for_slot(&question, None).key(), - "abc_q" + format!("{}_q", question.key()) ); assert_eq!( BankQuestionImageId::for_slot(&question, Some(&ids[0])).key(), - format!("abc_{}", ids[0].as_str()) + format!("{}_{}", question.key(), ids[0].as_str()) ); // Distinct options never share a row. assert_ne!( diff --git a/src/domain/board.rs b/src/domain/board.rs index 01efeea..671deaf 100644 --- a/src/domain/board.rs +++ b/src/domain/board.rs @@ -7,48 +7,44 @@ //! The marks themselves live in `board_stroke`, appended and never deleted: a //! clear bumps `epoch` so the canvas empties while the history stays //! replayable. The two stroke counters (`epoch_stroke_count`, -//! `total_stroke_count`) are `option` columns this struct deliberately -//! does NOT carry — they are written only by the stroke path's conditional -//! claim, so every mutation here is field-scoped `UPDATE … SET`. A whole-row -//! `CONTENT` save would silently wipe both (src/constant.rs:717-722). +//! `total_stroke_count`) are counter columns this struct deliberately does +//! NOT carry — they are written only by the stroke path's conditional claim, +//! so every mutation here is a field-scoped `UPDATE … SET`. A whole-row +//! rewrite would silently wipe both. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::{BOARD_TABLE, MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN}; -use crate::domain::monotonic_id::next_ulid; +use crate::constant::{MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN}; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::validate_required; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct BoardId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct BoardId(uuid::Uuid); impl BoardId { - /// Monotonic, not `Ulid::generate()`: boards list newest-first by id, and a - /// random low half scrambles rows minted in the same millisecond. + /// Monotonic, not a plain random UUID: boards list newest-first by id, and + /// a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(BOARD_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row — a malformed path param stays a 404, exactly + /// like a well-formed one that names nothing. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(BOARD_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct BoardTitle(pub(crate) String); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct BoardTitle(String); impl BoardTitle { pub fn try_new(value: &str) -> Result { @@ -83,7 +79,7 @@ pub(crate) fn checked_participants( Ok(unique) } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Board { pub(crate) id: BoardId, pub(crate) creator: UserId, @@ -162,10 +158,10 @@ mod tests { /// so no store is involved. fn a_board() -> Board { Board { - id: BoardId::from_key("b"), - creator: user("c"), + id: BoardId::from_key("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"), + creator: user("0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e"), title: BoardTitle::try_new("Geometri").unwrap(), - participants: vec![user("p")], + participants: vec![user("0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f")], locked: false, locked_by: None, locked_at: None, @@ -179,14 +175,14 @@ mod tests { fn the_two_predicates_are_the_permission_model() { let board = a_board(); // Creator: draws AND commands. - assert!(board.is_participant(&user("c"))); - assert!(board.is_creator(&user("c"))); + assert!(board.is_participant(&user("0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e"))); + assert!(board.is_creator(&user("0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e"))); // Invited: draws only. - assert!(board.is_participant(&user("p"))); - assert!(!board.is_creator(&user("p"))); + assert!(board.is_participant(&user("0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f"))); + assert!(!board.is_creator(&user("0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f"))); // Stranger: neither. - assert!(!board.is_participant(&user("s"))); - assert!(!board.is_creator(&user("s"))); + assert!(!board.is_participant(&user("0198f1a2-3b4c-7d5e-8f90-cccc4d5e6f7a"))); + assert!(!board.is_creator(&user("0198f1a2-3b4c-7d5e-8f90-cccc4d5e6f7a"))); } #[test] @@ -198,14 +194,12 @@ mod tests { #[test] fn participants_are_deduplicated_and_bounded() { - assert_eq!( - checked_participants(vec![user("p"), user("p")]) - .unwrap() - .len(), - 1 - ); - let many = (0..MAX_BOARD_PARTICIPANTS + 1) - .map(|n| UserId::from_key(&format!("u{n}"))) + let one = user("0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f"); + assert_eq!(checked_participants(vec![one.clone(), one]).unwrap().len(), 1); + // One over the ceiling is refused; each key must be a distinct + // *parseable* UUID, or the parser would collapse them all to nil. + let many = (0..=MAX_BOARD_PARTICIPANTS) + .map(|n| user(&format!("0198f1a2-3b4c-7d5e-8f90-{n:012x}"))) .collect(); assert!(checked_participants(many).is_err()); } diff --git a/src/domain/board_stroke.rs b/src/domain/board_stroke.rs index bba9db6..f94186f 100644 --- a/src/domain/board_stroke.rs +++ b/src/domain/board_stroke.rs @@ -8,21 +8,18 @@ //! transaction as the board's own delete. //! //! The `clear` marker row IS the epoch index: it carries the epoch it closed, -//! that epoch's final stroke count, who cleared and when — so replaying a whole -//! session needs no second table and no `GROUP BY` over the history. +//! that epoch's final stroke count, who cleared and when — so replaying a +//! whole session needs no second table and no `GROUP BY` over the history. //! -//! Writes funnel through [`crate::db::board_stroke`], and so do the board's -//! two stroke counters. Nothing else may write either, because two invariants -//! the schema cannot state depend on it: `count` is populated *only* on a -//! `clear` row (SCHEMAFULL types both kinds the same), and the two counters -//! must move together with the row they count (`cap::claim_two_when_and_create` -//! is what makes that one transaction). +//! two stroke counters. Nothing else may write either, because the invariant +//! the schema cannot state depends on it: `count` is populated *only* on a +//! `clear` row, and the two counters must move together with the row they +//! count (the stroke claim's dual-counter CTE is what makes that one +//! transaction). -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::{BOARD_STROKE_KINDS, BOARD_STROKE_TABLE}; +use crate::constant::BOARD_STROKE_KINDS; use crate::domain::board::Board; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -30,9 +27,9 @@ use crate::domain::user::UserId; pub(crate) const KIND_STROKE: &str = BOARD_STROKE_KINDS[0]; pub(crate) const KIND_CLEAR: &str = BOARD_STROKE_KINDS[1]; -/// The `THROW` the clear transaction refuses with: a blank canvas, not the +/// The refusal the clear transaction refuses with: a blank canvas, not the /// creator, or the board is locked or already closed. A decision, so it -/// outranks a lost round. +/// outranks a retryable failure. pub(crate) const CLEAR_REFUSED: &str = "board_clear_refused"; /// The public words of every refusal this module raises. `pub` because @@ -58,30 +55,30 @@ pub const REFUSALS: [&str; 5] = [ CANVAS_BLANK, ]; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct BoardStrokeId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct BoardStrokeId(uuid::Uuid); impl BoardStrokeId { - /// Monotonic, not `Ulid::generate()`: this id *is* the board's total order, and - /// a random low half scrambles every stroke drawn in the same millisecond — - /// which is what a burst of drawing looks like. + /// Monotonic, not a plain random UUID: this id *is* the board's total + /// order, and a random low half scrambles every stroke drawn in the same + /// millisecond — which is what a burst of drawing looks like. pub fn generate() -> Self { - Self(RecordId::new(BOARD_STROKE_TABLE, next_ulid().to_string())) + Self(next_uuid()) } - pub fn record(&self) -> RecordId { - self.0.clone() + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. + pub fn from_key(key: &str) -> Self { + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct BoardStroke { pub(crate) id: BoardStrokeId, pub(crate) board: crate::domain::board::BoardId, diff --git a/src/domain/builder.rs b/src/domain/builder.rs index aceebeb..4c6b94a 100644 --- a/src/domain/builder.rs +++ b/src/domain/builder.rs @@ -9,9 +9,9 @@ //! The credential newtypes are [`crate::domain::user`]'s — same rules, same //! argon2 discipline, deliberately not a second copy that could drift. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; +use uuid::Uuid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::session::SessionToken; use crate::domain::timestamp::Timestamp; use crate::domain::user::{PasswordHash, Username}; @@ -19,31 +19,29 @@ use crate::domain::user::{PasswordHash, Username}; pub const BUILDER_TABLE: &str = "builder"; pub const BUILDER_SESSION_TABLE: &str = "builder_session"; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct BuilderId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct BuilderId(Uuid); impl BuilderId { + /// A plain random UUID deliberately: builder rows are looked up by + /// username, never listed by id. pub fn generate() -> Self { - Self(RecordId::new(BUILDER_TABLE, Ulid::generate().to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(BUILDER_TABLE, key)) + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Builder { pub(crate) id: BuilderId, pub(crate) username: Username, @@ -67,9 +65,9 @@ impl Builder { /// A builder's login session. [`crate::domain::session::Session`]'s shape /// against the control database, with the token type shared so both cookies /// are the same 64 hex chars. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct BuilderSession { - pub(crate) id: RecordId, + pub(crate) id: Uuid, pub(crate) builder: BuilderId, pub(crate) token: SessionToken, pub(crate) created_at: Timestamp, diff --git a/src/domain/chatbot_message.rs b/src/domain/chatbot_message.rs index 4b65c45..df74005 100644 --- a/src/domain/chatbot_message.rs +++ b/src/domain/chatbot_message.rs @@ -7,72 +7,54 @@ //! `failed` by the task that owns the bridge round trip, and a read //! projects a long-stale `pending` as failed without writing //! ([`ChatbotMessage::projected`]) — the durable repair for a dead process -//! happens once, at boot, in `database.rs`. - -use std::sync::{LazyLock, Mutex}; - -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::{Generator, Ulid}; +//! happens once, at mint, in `database.rs`'s school migration sweep. use crate::constant::{ - CHAT_MESSAGE_TABLE, CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE, + CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE, }; use crate::domain::chatbot_thread::ChatbotThreadId; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::validate_required; -/// Mints message ids in write order. Unlike `Ulid::generate()`, whose 80 random -/// low bits sort arbitrarily among ids minted in the same millisecond, this -/// increments the previous id — so the `id` tie-break in the `ORDER BY` of -/// [`list_for_thread`](crate::db::chatbot_message::list_for_thread) / -/// [`list_tail`](crate::db::chatbot_message::list_tail) is the -/// order the rows were written. The user prompt and the assistant row one POST -/// writes back-to-back routinely share a millisecond, and a random tie-break -/// there renders the answer *above* its own question — and hands the AI -/// service a `[assistant, user]` history, breaking the oldest-first contract. -static IDS: LazyLock> = LazyLock::new(|| Mutex::new(Generator::new())); - -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ChatbotMessageId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct ChatbotMessageId(uuid::Uuid); impl ChatbotMessageId { + /// Mints in write order. Unlike a plain random UUID, whose random low bits + /// sort arbitrarily among ids minted in the same millisecond, the + /// process-wide context increments — so the `id` tie-break in the + /// `ORDER BY` of + /// [`list_for_thread`](crate::db::chatbot_message::list_for_thread) / + /// [`list_tail`](crate::db::chatbot_message::list_tail) is the + /// order the rows were written. The user prompt and the assistant row one + /// POST writes back-to-back routinely share a millisecond, and a random + /// tie-break there renders the answer *above* its own question — and + /// hands the AI service a `[assistant, user]` history, breaking the + /// oldest-first contract. pub fn generate() -> Self { - let mut ids = IDS.lock().expect("chat id generator poisoned"); - // The only error is overflow of the random bits *within* one - // millisecond — 2^80 ids deep, and it clears itself as soon as the - // clock ticks over, so retry rather than fall back to a random id - // (which would silently reintroduce the defect). - let ulid: Ulid = loop { - if let Ok(ulid) = ids.generate() { - break ulid; - } - }; - Self(RecordId::new(CHAT_MESSAGE_TABLE, ulid.to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(CHAT_MESSAGE_TABLE, key)) + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -/// Who said a turn. `untagged` + `rename_all` store it as the bare lowercase -/// string the `role` column types as, and a value the enum doesn't know comes -/// back as a deserialization error, never a panic. -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] -#[surreal(untagged, rename_all = "lowercase")] +/// Who said a turn. Stored as the bare lowercase string the `role` column's +/// CHECK allows; a value the enum doesn't know comes back as a decode error, +/// never a panic. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] pub enum MessageRole { User, Assistant, @@ -90,8 +72,8 @@ impl MessageRole { /// Where an assistant turn is in its lifecycle. A user turn is born /// `Complete` — nothing is ever awaited for it. -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] -#[surreal(untagged, rename_all = "lowercase")] +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] pub enum MessageStatus { Pending, Complete, @@ -110,8 +92,9 @@ impl MessageStatus { /// One turn's text. The hard ceiling only — the school-adjustable /// `max_chatbot_message_len` is the web layer's to enforce, below this. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ChatContent(pub(crate) String); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct ChatContent(String); impl ChatContent { pub fn try_new(value: &str) -> Result { @@ -131,7 +114,7 @@ impl ChatContent { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct ChatbotMessage { pub(crate) id: ChatbotMessageId, pub(crate) thread_id: ChatbotThreadId, @@ -196,7 +179,7 @@ impl ChatbotMessage { /// thread load) run on every page and must not write, a write-back would /// race the answering task that is merely slow — closing the door on a /// reply that is still coming — and the durable repair for the real cause - /// (a dead process) already happens once, at boot. The stored row stays + /// (a dead process) already happens once, at mint. The stored row stays /// truthful; only the answer handed to the caller is projected. pub(crate) fn projected(mut self) -> Self { let stale_at = self.created_at.as_millis() + CHATBOT_PENDING_STALE_SECS * 1_000; @@ -219,34 +202,16 @@ mod tests { assert!(ChatContent::try_new(&"x".repeat(MAX_CHATBOT_MESSAGE_LEN + 1)).is_err()); } - #[tokio::test] - async fn role_and_status_store_as_bare_strings() { - // `TYPE string` columns: an object-wrapped enum would be rejected on - // write, and a junk string must read back as an error, not a panic. - for role in [MessageRole::User, MessageRole::Assistant] { - let value = role.into_value(); - assert_eq!( - value, - surrealdb::types::Value::String(role.as_str().to_string()) - ); - assert_eq!(MessageRole::from_value(value).unwrap(), role); - } - for status in [ - MessageStatus::Pending, - MessageStatus::Complete, - MessageStatus::Failed, - ] { - let value = status.into_value(); - assert_eq!( - value, - surrealdb::types::Value::String(status.as_str().to_string()) - ); - assert_eq!(MessageStatus::from_value(value).unwrap(), status); - } - assert!(MessageRole::from_value(surrealdb::types::Value::String("system".into())).is_err()); - assert!( - MessageStatus::from_value(surrealdb::types::Value::String("queued".into())).is_err() - ); + /// The `role`/`status` columns are `TEXT` with CHECKs listing exactly + /// these spellings — queries match on them, so the storage form may not + /// drift from `as_str` (which `rename_all` mirrors). + #[test] + fn role_and_status_spellings_are_frozen() { + assert_eq!(MessageRole::User.as_str(), "user"); + assert_eq!(MessageRole::Assistant.as_str(), "assistant"); + assert_eq!(MessageStatus::Pending.as_str(), "pending"); + assert_eq!(MessageStatus::Complete.as_str(), "complete"); + assert_eq!(MessageStatus::Failed.as_str(), "failed"); } #[tokio::test] @@ -254,8 +219,8 @@ mod tests { let aged = |secs: i64| { ChatbotMessage { id: ChatbotMessageId::generate(), - thread_id: ChatbotThreadId::from_key("c"), - user_id: UserId::from_key("u"), + thread_id: ChatbotThreadId::from_key("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"), + user_id: UserId::from_key("0198f1a2-3b4c-7d5e-8f90-aa2b3c4d5e6f"), role: MessageRole::Assistant, content: ChatContent::empty(), status: MessageStatus::Pending, diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index 517965b..c58756c 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -4,46 +4,42 @@ //! [`crate::db::chatbot_message`], and deleting a thread cascades them; the //! threads' own persistence lives in [`crate::db::chatbot_thread`]. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::{CHATBOT_THREAD_TABLE, MAX_CHATBOT_THREAD_TITLE_LEN}; -use crate::domain::monotonic_id::next_ulid; +use crate::constant::{MAX_CHATBOT_THREAD_TITLE_LEN}; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::validate_required; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ChatbotThreadId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct ChatbotThreadId(uuid::Uuid); impl ChatbotThreadId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: - /// threads sort `updated_at DESC, id DESC` and the id breaks the tie + /// Mints from the process-wide monotonic generator, not a plain random + /// UUID: threads sort `updated_at DESC, id DESC` and the id breaks the tie /// between two threads last touched in the same millisecond, /// and a random low half sorts arbitrarily inside one millisecond. pub fn generate() -> Self { - Self(RecordId::new(CHATBOT_THREAD_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(CHATBOT_THREAD_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } + /// A user-chosen thread name. Required-and-bounded here; "untitled" is /// `Option` on the row. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ChatbotThreadTitle(pub(crate) String); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct ChatbotThreadTitle(String); impl ChatbotThreadTitle { pub fn try_new(value: &str) -> Result { @@ -56,7 +52,7 @@ impl ChatbotThreadTitle { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct ChatbotThread { pub(crate) id: ChatbotThreadId, pub(crate) user_id: UserId, diff --git a/src/domain/class_blueprint.rs b/src/domain/class_blueprint.rs index 69be878..9519ffa 100644 --- a/src/domain/class_blueprint.rs +++ b/src/domain/class_blueprint.rs @@ -9,7 +9,7 @@ //! `enrollment` rows, and an elective (seçmeli) placed by hand next to them is //! still an individual enrollment nothing here can see. //! -//! This module is the pure shape: the id (the grade label *is* the record +//! This module is the pure shape: the id (the grade label *is* the primary //! key, so "one blueprint per grade" holds by construction), the row, the //! pump's report types ([`Pumped`], [`Skip`], [`SectionStatus`]) and the //! shared skip vocabulary ([`skip_reason`]). @@ -19,9 +19,7 @@ //! in [`crate::service::class_blueprint`], the queries in //! [`crate::db::class_blueprint`]. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::{CLASS_BLUEPRINT_TABLE, MAX_CLASS_COURSES}; +use crate::constant::{MAX_CLASS_COURSES}; use crate::db::class_pump::{Attached, Axis}; use crate::domain::class_course::ClassCourse; use crate::domain::class_group::{ClassGrade, ClassGroupId}; @@ -29,37 +27,31 @@ use crate::domain::course::CourseId; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ClassBlueprintId(RecordId); +/// A grade label as the table's `TEXT` primary key — one blueprint per grade +/// by construction, like the settings singleton's `'school'` row: the key is +/// a name, not a minted entity id. +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct ClassBlueprintId(String); impl ClassBlueprintId { - /// The record one grade label always maps to. The label is the key, so - /// "one blueprint per grade" holds by construction rather than by a - /// find-then-insert that two managers can race — the shape - /// [`crate::domain::menu::MenuId::for_slot`] uses. + /// The key one grade label always maps to. pub fn for_grade(grade: &ClassGrade) -> Self { - Self(RecordId::new(CLASS_BLUEPRINT_TABLE, grade.as_str())) + Self(grade.as_str().to_string()) } pub fn from_key(key: &str) -> Self { - Self(RecordId::new(CLASS_BLUEPRINT_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(key.to_string()) } pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + &self.0 } } /// One grade's template. `grade` is stored beside the key it *is*, so a read /// never has to parse a record id back into a domain value. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct ClassBlueprint { pub(crate) id: ClassBlueprintId, pub(crate) grade: ClassGrade, @@ -147,13 +139,13 @@ impl ClassBlueprint { } /// The grade a blueprint may be keyed on. Non-empty, because the label is - /// the record id and there is no blueprint for "no grade"; and free of the - /// characters that would make that id unaddressable as a URL path segment, - /// the second gate [`crate::domain::menu::MenuSlot`] carries for the same - /// reason. Grades were never validated for this, so a *class* may already - /// carry a label refused here — it simply cannot have a blueprint until it - /// is renamed, which is a 400 the caller can read rather than a route - /// nobody can reach. + /// the primary key and there is no blueprint for "no grade"; and free of + /// the characters that would make that key unaddressable as a URL path + /// segment, the second gate [`crate::domain::menu::MenuSlot`] carries for + /// the same reason. Grades were never validated for this, so a *class* may + /// already carry a label refused here — it simply cannot have a blueprint + /// until it is renamed, which is a 400 the caller can read rather than a + /// route nobody can reach. pub fn grade_key(value: &str) -> Result { if value.is_empty() { return Err(AppError::Validation(ValidationError::Empty("grade"))); @@ -215,12 +207,14 @@ mod tests { /// spend two of the ceiling's places on one course. #[test] fn a_course_list_is_deduplicated_and_bounded() { - let algebra = CourseId::from_key("algebra"); + let algebra = CourseId::from_key("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"); let held = ClassBlueprint::course_list(vec![algebra.clone(), algebra.clone()]).unwrap(); assert_eq!(held, vec![algebra]); + // One over the ceiling is refused; each key must be a distinct + // *parseable* UUID, or the parser would collapse them all to nil. let too_many: Vec = (0..=MAX_CLASS_COURSES) - .map(|n| CourseId::from_key(&n.to_string())) + .map(|n| CourseId::from_key(&format!("0198f1a2-3b4c-7d5e-8f90-{n:012x}"))) .collect(); assert!(ClassBlueprint::course_list(too_many).is_err()); } diff --git a/src/domain/class_course.rs b/src/domain/class_course.rs index 3ec2313..f0f0a77 100644 --- a/src/domain/class_course.rs +++ b/src/domain/class_course.rs @@ -7,41 +7,39 @@ //! [`crate::db::class_course`] — this file is the row shape and its //! composite id. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::CLASS_COURSE_TABLE; -use crate::db::class_pump::link_id; use crate::domain::class_blueprint::ClassBlueprintId; use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ClassCourseId(RecordId); +/// The identity of one (class, course) pair. Not a row column: the table's +/// primary key *is* the pair, and this struct's job is the underscore-joined +/// wire form at the HTTP edge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ClassCourseId { + pub(crate) class: ClassGroupId, + pub(crate) course: CourseId, +} impl ClassCourseId { - /// The record one (class, course) pair always maps to. + /// The one id a (class, course) pair can have. pub fn composite(class: &ClassGroupId, course: &CourseId) -> Self { - Self(link_id(CLASS_COURSE_TABLE, class, course.key())) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self { + class: class.clone(), + course: course.clone(), + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The underscore-joined wire form (`{class}_{course}`). + pub fn key(&self) -> String { + format!("{}_{}", self.class.key(), self.course.key()) } } /// One course a class is attached to. `attached_by` is who attached it. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct ClassCourse { - pub(crate) id: ClassCourseId, pub(crate) class: ClassGroupId, pub(crate) course: CourseId, pub(crate) attached_by: UserId, @@ -49,19 +47,19 @@ pub struct ClassCourse { /// attached the course to this class directly — the mirror of /// [`crate::domain::enrollment`]'s `source`, and read the same way: only a /// row carrying the key is a blueprint's to take back, so a hand-attached - /// course survives every blueprint sweep. Rows written before the column - /// carry no key at all, which is exactly "hand-attached". + /// course survives every blueprint sweep. pub(crate) source: Option, - /// When it was attached, and the *only* thing "newest first" can mean here: - /// the row's id is the (class, course) pair, so ordering by it sorts the - /// list by the course's own ULID. Optional because rows written before this - /// column carry no stamp — see the migration note. + /// When it was attached, and the *only* thing "newest first" can mean + /// here: the row's primary key is the (class, course) pair, so ordering + /// falls to this stamp (or the attached course's id). Optional because + /// rows written before this column carry no stamp. pub(crate) attached_at: Option, } impl ClassCourse { - pub fn get_id(&self) -> &ClassCourseId { - &self.id + /// The row's identity, built back from its primary-key columns. + pub fn get_id(&self) -> ClassCourseId { + ClassCourseId::composite(&self.class, &self.course) } pub fn get_class(&self) -> &ClassGroupId { diff --git a/src/domain/class_group.rs b/src/domain/class_group.rs index 1f92ed1..1adbe11 100644 --- a/src/domain/class_group.rs +++ b/src/domain/class_group.rs @@ -14,40 +14,35 @@ //! the route-facing wrappers in [`crate::service::class_group`] — this file is //! the row shape, its newtypes and getters. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::{CLASS_GROUP_TABLE, MAX_CLASS_GRADE_LEN, MAX_CLASS_NAME_LEN}; -use crate::domain::monotonic_id::next_ulid; +use crate::constant::{MAX_CLASS_GRADE_LEN, MAX_CLASS_NAME_LEN}; +use crate::domain::monotonic_id::next_uuid; use crate::domain::term::TermId; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::{validate_optional, validate_required}; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ClassGroupId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct ClassGroupId(uuid::Uuid); impl ClassGroupId { pub fn generate() -> Self { - Self(RecordId::new(CLASS_GROUP_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(CLASS_GROUP_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct ClassName(String); impl ClassName { @@ -64,7 +59,8 @@ impl ClassName { /// The school's own label for the year a class sits in ("9", "10-A", /// "anaokulu"). Free text on purpose — no school's grade ladder is the next /// one's — and optional: a club-shaped class has no grade at all. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct ClassGrade(String); impl ClassGrade { @@ -85,9 +81,8 @@ impl ClassGrade { /// `teacher` is the section's homeroom teacher (sınıf öğretmeni): optional, not /// refcounted, and merely a label pointing at a teacher-or-higher account — the /// web layer holds that bar, and a demotion sweeps the column -/// ([`crate::db::class_group::unassign_everywhere`]). Rows written before the -/// column exists carry no key at all, which reads back as `None`. -#[derive(Debug, Clone, SurrealValue)] +/// ([`crate::db::class_group::unassign_everywhere`]). +#[derive(Debug, Clone, sqlx::FromRow)] pub struct ClassGroup { pub(crate) id: ClassGroupId, pub(crate) creator: UserId, diff --git a/src/domain/class_member.rs b/src/domain/class_member.rs index 3cee472..fcb623a 100644 --- a/src/domain/class_member.rs +++ b/src/domain/class_member.rs @@ -7,52 +7,51 @@ //! [`crate::db::class_member`] — this file is the row shape and its //! composite id. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::CLASS_MEMBER_TABLE; -use crate::db::class_pump::link_id; use crate::domain::class_group::ClassGroupId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ClassMemberId(RecordId); +/// The identity of one (class, user) pair. Not a row column: the table's +/// primary key *is* the pair, and this struct's job is the underscore-joined +/// wire form at the HTTP edge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ClassMemberId { + pub(crate) class: ClassGroupId, + pub(crate) user: UserId, +} impl ClassMemberId { - /// The record one (class, user) pair always maps to. + /// The one id a (class, user) pair can have. pub fn composite(class: &ClassGroupId, user: &UserId) -> Self { - Self(link_id(CLASS_MEMBER_TABLE, class, user.key())) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self { + class: class.clone(), + user: user.clone(), + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The underscore-joined wire form (`{class}_{user}`). + pub fn key(&self) -> String { + format!("{}_{}", self.class.key(), self.user.key()) } } /// One student in one class. `added_by` is who put them there. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct ClassMember { - pub(crate) id: ClassMemberId, pub(crate) class: ClassGroupId, pub(crate) user: UserId, pub(crate) added_by: UserId, - /// When they were added, and the *only* thing "newest first" can mean here: - /// the row's id is the (class, user) pair, so ordering by it sorts the - /// roster by the student's account ULID. Optional because rows written - /// before this column carry no stamp — see the migration note. + /// When they were added, and the *only* thing "newest first" can mean + /// here: the row's primary key is the (class, user) pair, so ordering + /// falls to this stamp. Optional because rows written before this column + /// carry no stamp. pub(crate) added_at: Option, } impl ClassMember { - pub fn get_id(&self) -> &ClassMemberId { - &self.id + /// The row's identity, built back from its primary-key columns. + pub fn get_id(&self) -> ClassMemberId { + ClassMemberId::composite(&self.class, &self.user) } pub fn get_class(&self) -> &ClassGroupId { diff --git a/src/domain/course.rs b/src/domain/course.rs index 4ff6a7a..50c69bb 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -1,40 +1,36 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::{COURSE_TABLE, MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN}; -use crate::domain::monotonic_id::next_ulid; +use crate::constant::{MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN}; +use crate::domain::monotonic_id::next_uuid; use crate::domain::term::TermId; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::{validate_course_kind, validate_optional, validate_required}; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct CourseId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct CourseId(uuid::Uuid); impl CourseId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: - /// courses list `id DESC` (newest first, [`crate::db::course::list_all`]), + /// Minted from the process-wide monotonic generator, not a plain random + /// UUID: courses list `id DESC` (newest first, + /// [`crate::db::course::list_all`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(COURSE_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(COURSE_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct CourseTitle(String); impl CourseTitle { @@ -48,7 +44,8 @@ impl CourseTitle { } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct CourseDescription(String); impl CourseDescription { @@ -65,7 +62,8 @@ impl CourseDescription { /// A validated course kind: `course` (a regular class — ders), `study` (a /// supervised study session — etüt), or `club` (a student club — kulüp). /// Purely a label; all kinds behave identically. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct CourseKind(String); impl CourseKind { @@ -88,21 +86,19 @@ impl CourseKind { /// course, each exam weighted by its kind's settings weight. May belong to an /// academic term. Comes in three behaviorally identical kinds: `course`, /// `study` (etüt), and `club` (kulüp). An optional `capacity` caps the roster -/// at enroll time (`None` = unlimited); rows written before the field existed -/// decode as uncapped. +/// at enroll time (`NULL` = unlimited). /// /// `creator` owns the course for good — only they (or a manager+) may delete /// it. `teachers` are the staff a manager assigned to run it: full management /// rights inside the course, no power to delete it or change the assignment -/// list. Rows written before the field existed decode with nobody assigned. +/// list. /// /// Fields are crate-visible: [`crate::db::course`] mints the rows on create /// and reads the id when updating and cascading a delete. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Course { pub(crate) id: CourseId, pub(crate) creator: UserId, - #[surreal(default)] pub(crate) teachers: Vec, pub(crate) title: CourseTitle, pub(crate) description: CourseDescription, @@ -181,59 +177,4 @@ mod tests { assert!(CourseKind::try_new("etut").is_err()); assert_eq!(CourseKind::course().as_str(), "course"); } - - /// The database strips `NONE`-valued optional columns, and every course - /// row written before the capacity field existed has no `capacity` key at - /// all — both must decode as an uncapped course. - #[tokio::test] - async fn course_decodes_without_capacity_key() { - use surrealdb::types::Value; - - let course = Course { - id: CourseId::generate(), - creator: UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"), - teachers: Vec::new(), - title: CourseTitle::try_new("chess").unwrap(), - description: CourseDescription::try_new("").unwrap(), - kind: CourseKind::try_new("club").unwrap(), - term: None, - capacity: Some(12), - }; - let Value::Object(mut object) = course.into_value() else { - panic!("course must encode as an object"); - }; - object.remove("capacity"); - let decoded = Course::from_value(Value::Object(object)).unwrap(); - assert_eq!(decoded.get_capacity(), None); - } - - /// Every course row written before teacher assignment existed has no - /// `teachers` key. The boot backfill fills them in, but a row read before - /// that lands must still decode — as a course nobody was assigned to, - /// never as a decode error that 500s the catalog. - #[tokio::test] - async fn course_decodes_without_teachers_key() { - use surrealdb::types::Value; - - let assigned = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U"); - let course = Course { - id: CourseId::generate(), - creator: UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"), - teachers: vec![assigned.clone()], - title: CourseTitle::try_new("chess").unwrap(), - description: CourseDescription::try_new("").unwrap(), - kind: CourseKind::try_new("club").unwrap(), - term: None, - capacity: None, - }; - assert!(course.is_assigned(&assigned)); - - let Value::Object(mut object) = course.into_value() else { - panic!("course must encode as an object"); - }; - object.remove("teachers"); - let decoded = Course::from_value(Value::Object(object)).unwrap(); - assert!(decoded.get_teachers().is_empty()); - assert!(!decoded.is_assigned(&assigned)); - } } diff --git a/src/domain/course_note.rs b/src/domain/course_note.rs index e75e5dd..d14fa68 100644 --- a/src/domain/course_note.rs +++ b/src/domain/course_note.rs @@ -1,41 +1,36 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::{COURSE_NOTE_TABLE, MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN}; +use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN}; use crate::domain::course::CourseId; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::{validate_optional, validate_required}; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct CourseNoteId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct CourseNoteId(uuid::Uuid); impl CourseNoteId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: - /// a course's notes list `id DESC` (newest first, + /// Minted from the process-wide monotonic generator, not a plain random + /// UUID: a course's notes list `id DESC` (newest first, /// [`crate::db::course_note::list_for_course`]), and a random low half /// scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(COURSE_NOTE_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(COURSE_NOTE_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct CourseNoteTitle(String); impl CourseNoteTitle { @@ -49,7 +44,8 @@ impl CourseNoteTitle { } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct CourseNoteContent(String); impl CourseNoteContent { @@ -63,7 +59,7 @@ impl CourseNoteContent { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct CourseNote { pub(crate) id: CourseNoteId, pub(crate) course: CourseId, diff --git a/src/domain/course_note_file.rs b/src/domain/course_note_file.rs index b4920f5..4366aca 100644 --- a/src/domain/course_note_file.rs +++ b/src/domain/course_note_file.rs @@ -1,53 +1,44 @@ //! A file attached to a course note. The row carries metadata only (original //! filename, MIME type, byte size); the bytes themselves live on disk under -//! [`crate::config::Config::files_path`], in a file named by this row's key — -//! a server-generated ULID, so no user input ever shapes a disk path. The web -//! layer owns the blob I/O and its ordering (blob before row on upload, row -//! before blob on delete); persistence lives in +//! [`crate::config::Config::files_path`], in a file named by this row's `file` +//! field — a server-generated UUID, so no user input ever shapes a disk path. +//! The web layer owns the blob I/O and its ordering (blob before row on +//! upload, row before blob on delete); persistence lives in //! [`crate::db::course_note_file`]. `FileName` and `FileContentType` are //! shared with [`crate::domain::note_file`] — same validation, no reason to //! duplicate it. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - pub use crate::domain::note_file::{FileContentType, FileName}; -use crate::constant::COURSE_NOTE_FILE_TABLE; use crate::domain::course_note::CourseNoteId; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct CourseNoteFileId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct CourseNoteFileId(uuid::Uuid); impl CourseNoteFileId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: - /// a note's files list `id DESC` (newest first, + /// Minted from the process-wide monotonic generator, not a plain random + /// UUID: a note's files list `id DESC` (newest first, /// [`crate::db::course_note_file::list_for`]), and a random low half /// scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new( - COURSE_NOTE_FILE_TABLE, - next_ulid().to_string(), - )) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(COURSE_NOTE_FILE_TABLE, key)) + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, SurrealValue)] + +#[derive(Debug, Clone, sqlx::FromRow)] pub struct CourseNoteFile { pub(crate) id: CourseNoteFileId, pub(crate) course_note: CourseNoteId, diff --git a/src/domain/course_session.rs b/src/domain/course_session.rs index 9b3c29e..1d28a16 100644 --- a/src/domain/course_session.rs +++ b/src/domain/course_session.rs @@ -1,42 +1,37 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::{COURSE_SESSION_TABLE, MAX_SESSION_TOPIC_LEN}; +use crate::constant::{MAX_SESSION_TOPIC_LEN}; use crate::domain::course::CourseId; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::validate_optional; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct CourseSessionId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct CourseSessionId(uuid::Uuid); impl CourseSessionId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: - /// a course's sessions sort `starts_at DESC, id DESC` and the id breaks - /// the tie between two sessions starting at the same instant, + /// Minted from the process-wide monotonic generator, not a plain random + /// UUID: a course's sessions sort `starts_at DESC, id DESC` and the id + /// breaks the tie between two sessions starting at the same instant, /// and a random low half sorts arbitrarily inside one millisecond. pub fn generate() -> Self { - Self(RecordId::new(COURSE_SESSION_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(COURSE_SESSION_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct SessionTopic(String); impl SessionTopic { @@ -53,7 +48,7 @@ impl SessionTopic { /// One scheduled lesson of a course: the unit roll call is taken on. Unlike a /// generic event, a session always has a start instant and belongs to a course, /// so its roster is the course's enrollment plus the assigned teacher. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct CourseSession { pub(crate) id: CourseSessionId, pub(crate) course: CourseId, diff --git a/src/domain/dietary_profile.rs b/src/domain/dietary_profile.rs index be77d4a..ecf603c 100644 --- a/src/domain/dietary_profile.rs +++ b/src/domain/dietary_profile.rs @@ -1,8 +1,8 @@ //! What one student may not eat: the school's record of their dietary tags //! plus a free-text note for the kitchen. //! -//! One row per student, so the record key **is** the student's key — no -//! generated id and no composite. Tags are validated against the same +//! One row per student, so the primary key **is** the student — no generated +//! id and no composite. Tags are validated against the same //! `dietary_tags` vocabulary a dish's tags come from ([`Settings::get_dietary_tags`]); //! that single shared list is what makes "this dish conflicts with this //! student" answerable as a set intersection, without the backend knowing any @@ -13,41 +13,42 @@ //! //! [`Settings::get_dietary_tags`]: crate::domain::settings::Settings::get_dietary_tags -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{DIETARY_PROFILE_TABLE, MAX_DIETARY_NOTE_LEN, MAX_DIETARY_TAGS}; +use crate::constant::{MAX_DIETARY_NOTE_LEN, MAX_DIETARY_TAGS}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::validate_optional; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct DietaryProfileId(RecordId); +/// The profile's identity: the student it belongs to. Not a row column of its +/// own — the table's primary key *is* `student`, so "read the caller's +/// profile" is a single `SELECT` by key and never a scan. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DietaryProfileId { + pub(crate) student: UserId, +} impl DietaryProfileId { - /// The profile of one student — deterministic, so "read the caller's - /// profile" is a single `SELECT` by id and never a scan. pub fn of(student: &UserId) -> Self { - Self(RecordId::new(DIETARY_PROFILE_TABLE, student.key())) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self { + student: student.clone(), + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The student's wire key, which is the profile's. + pub fn key(&self) -> String { + self.student.key() } } /// The tags a student's diet carries, drawn from the school's `dietary_tags` /// list — the same vocabulary a dish is tagged from, deduplicated and in the -/// order given. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct DietaryTags(pub(crate) Vec); +/// order given. Stored as a `TEXT[]` column. `no_pg_array` skips the derive's +/// element-array assertion (which a `Vec` inner cannot satisfy); the impls +/// still delegate to `Vec`. +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent, no_pg_array)] +pub struct DietaryTags(Vec); impl DietaryTags { pub fn try_new(values: &[String], allowed: &[String]) -> Result { @@ -79,12 +80,13 @@ impl DietaryTags { } /// Anything the tag list cannot say — "carries an EpiPen", "no pork". -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct DietaryNote(String); impl DietaryNote { /// Blank (or whitespace-only) means "no note" — `None`, not an empty - /// string, so the column is absent rather than falsely present. + /// string, so the column is NULL rather than falsely present. pub fn try_new(value: &str) -> Result, ValidationError> { validate_optional("note", value, MAX_DIETARY_NOTE_LEN)?; let value = value.trim(); @@ -96,9 +98,8 @@ impl DietaryNote { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct DietaryProfile { - pub(crate) id: DietaryProfileId, pub(crate) student: UserId, pub(crate) tags: DietaryTags, pub(crate) note: Option, diff --git a/src/domain/enrollment.rs b/src/domain/enrollment.rs index d1f13ba..2528194 100644 --- a/src/domain/enrollment.rs +++ b/src/domain/enrollment.rs @@ -1,34 +1,29 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::ENROLLMENT_TABLE; use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; use crate::domain::user::UserId; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct EnrollmentId(RecordId); +/// The identity of one (course, user) pair. Not a row column: the table's +/// primary key *is* the pair, which is what makes enrolling a single atomic +/// UPSERT (`ON CONFLICT (course, app_user)`) with no find-then-insert race +/// and one-row-per-pair by construction. This struct's job is the +/// underscore-joined wire form at the HTTP edge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EnrollmentId { + pub(crate) course: CourseId, + pub(crate) user: UserId, +} impl EnrollmentId { - /// A deterministic id for the (course, user) pair. The same pair always - /// maps to the same record id, so enrolling is a single atomic UPSERT with - /// no find-then-insert race and one-row-per-pair by construction. ULID keys - /// are alphanumeric, so `_` is an unambiguous joiner. pub fn composite(course: &CourseId, user: &UserId) -> Self { - Self(RecordId::new( - ENROLLMENT_TABLE, - format!("{}_{}", course.key(), user.key()), - )) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self { + course: course.clone(), + user: user.clone(), + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The underscore-joined wire form (`{course}_{user}`). + pub fn key(&self) -> String { + format!("{}_{}", self.course.key(), self.user.key()) } } @@ -36,13 +31,11 @@ impl EnrollmentId { /// user's marks from the report but never deletes result rows. /// /// `source` names the class ([`crate::domain::class_group::ClassGroup`]) that -/// pumped this row, and is absent when a human placed the student directly — -/// every row written before classes existed, and every row placed by hand since. -/// Absence *is* the meaning, so nothing backfills it: a class sweep may only take -/// back the rows it wrote. -#[derive(Debug, Clone, SurrealValue)] +/// pumped this row, and is NULL when a human placed the student directly — +/// every row placed by hand. Absence *is* the meaning, so nothing backfills +/// it: a class sweep may only take back the rows it wrote. +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Enrollment { - pub(crate) id: EnrollmentId, pub(crate) course: CourseId, pub(crate) user: UserId, pub(crate) enrolled_by: UserId, @@ -50,8 +43,9 @@ pub struct Enrollment { } impl Enrollment { - pub fn get_id(&self) -> &EnrollmentId { - &self.id + /// The row's identity, built back from its primary-key columns. + pub fn get_id(&self) -> EnrollmentId { + EnrollmentId::composite(&self.course, &self.user) } pub fn get_course(&self) -> &CourseId { @@ -71,35 +65,3 @@ impl Enrollment { self.source.as_ref() } } - -#[cfg(test)] -mod tests { - use super::*; - - /// The database strips `NONE`-valued optional columns, and every enrollment - /// row written before classes existed has no `source` key at all — both must - /// decode as a hand-placed row, never as a decode error that 500s a roster. - #[tokio::test] - async fn enrollment_decodes_without_source_key() { - use surrealdb::types::Value; - - let class = crate::domain::class_group::ClassGroupId::from_key("9a"); - let course = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); - let student = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U"); - let enrollment = Enrollment { - id: EnrollmentId::composite(&course, &student), - course, - user: student, - enrolled_by: UserId::from_key("mgr"), - source: Some(class.clone()), - }; - assert_eq!(enrollment.get_source(), Some(&class)); - - let Value::Object(mut object) = enrollment.into_value() else { - panic!("an enrollment must encode as an object"); - }; - object.remove("source"); - let decoded = Enrollment::from_value(Value::Object(object)).unwrap(); - assert_eq!(decoded.get_source(), None); - } -} diff --git a/src/domain/event.rs b/src/domain/event.rs index 107c676..74a508d 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -1,45 +1,39 @@ -// `Value` looks unused but is load-bearing: the `SurrealValue` derive on the -// tagged `EventAudience` enum expands to code that names `Value` unqualified. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; - -use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; +use crate::constant::{MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_optional, validate_required}; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct EventId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct EventId(uuid::Uuid); impl EventId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: - /// events list `id DESC` (newest first, [`crate::db::event::list_all`]), + /// Minted from the process-wide monotonic generator, not a plain random + /// UUID: events list `id DESC` (newest first, + /// [`crate::db::event::list_all`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(EVENT_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(EVENT_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct EventTitle(String); impl EventTitle { @@ -53,7 +47,8 @@ impl EventTitle { } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct EventDescription(String); impl EventDescription { @@ -67,51 +62,77 @@ impl EventDescription { } } -/// Who an event is aimed at: the expected-attendee roster. Membership is +/// Which shape of expected-attendee roster the event carries — the `kind` +/// discriminant of the old tagged value, now a flat column. Membership is /// resolved live against today's users/enrollments/registrations — never /// snapshotted — so a role change, (un)enrollment, or (un)registration moves /// people in and out of rosters by itself. The audience does not gate *seeing* /// the event (the calendar stays school-visible); it defines who counts as /// expected and who may be marked. /// -/// Stored internally tagged: `{kind: 'school'}`, `{kind: 'role', role: 'student'}`, -/// `{kind: 'course', course: course:…}`, `{kind: 'class', class: class_group:…}`, -/// `{kind: 'registration', capacity: 30}`. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -#[surreal(tag = "kind", rename_all = "lowercase")] -pub enum EventAudience { - /// Everybody — the pre-audience behavior and the backfill for old rows. +/// The payload lives in the sibling columns: `audience_role` for +/// [`EventAudienceKind::Role`], `audience_course` for +/// [`EventAudienceKind::Course`], `audience_class` for +/// [`EventAudienceKind::Class`], `audience_capacity` for +/// [`EventAudienceKind::Registration`]. A `School` event carries none. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] +pub enum EventAudienceKind { + /// Everybody — the pre-audience behavior. School, /// Every user holding exactly this role ("all students", "all teachers"). - Role { role: Role }, + Role, /// A course's enrolled students. Staff running the course are not implied /// members — a mixed gathering wants a registration or role audience. - Course { course: CourseId }, + Course, /// A class section's (şube) students, read live off `class_member` — the /// same live resolution `Course` and `Role` get, so adding a student to the /// class puts them on every one of its events' rosters at once. The /// homeroom teacher is not implied, matching `Course`. A deleted class /// leaves the event standing with an empty roster, exactly as a deleted /// course does (`Course::delete` never touches `event`). - Class { class: ClassGroupId }, + Class, /// A signup list built one person at a time through the register /// endpoints — teachers place students, staff take their own seat. The - /// list is capped at `capacity` seats when set (`None` = unlimited) and - /// closes once the event starts. Rows survive an audience change inertly. - Registration { capacity: Option }, + /// list is capped at the `audience_capacity` seats when set (`NULL` = + /// unlimited) and closes once the event starts. Rows survive an audience + /// change inertly. + Registration, } -#[derive(Debug, Clone, SurrealValue)] +/// Who an event is aimed at, as one flat row. The five audience columns +/// (kind + payload) are exactly the `audience_*` columns of the migration; +/// every write goes through one validated shape, so only the payload matching +/// `audience_kind` is ever non-NULL. +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Event { pub(crate) id: EventId, pub(crate) creator: UserId, pub(crate) title: EventTitle, pub(crate) description: EventDescription, - pub(crate) audience: EventAudience, + pub(crate) audience_kind: EventAudienceKind, + pub(crate) audience_role: Option, + pub(crate) audience_course: Option, + pub(crate) audience_class: Option, + pub(crate) audience_capacity: Option, pub(crate) starts_at: Option, pub(crate) ends_at: Option, } +impl EventAudienceKind { + /// The wire/storage spelling. Must stay in lockstep with `rename_all` — + /// the web layer publishes these as the audience `kind`. + pub fn as_str(self) -> &'static str { + match self { + EventAudienceKind::School => "school", + EventAudienceKind::Role => "role", + EventAudienceKind::Course => "course", + EventAudienceKind::Class => "class", + EventAudienceKind::Registration => "registration", + } + } +} + impl Event { pub fn get_id(&self) -> &EventId { &self.id @@ -129,8 +150,26 @@ impl Event { &self.description } - pub fn get_audience(&self) -> &EventAudience { - &self.audience + /// Which audience shape the event carries; the payload sits in the + /// matching sibling column. + pub fn get_audience_kind(&self) -> EventAudienceKind { + self.audience_kind + } + + pub fn get_audience_role(&self) -> Option { + self.audience_role + } + + pub fn get_audience_course(&self) -> Option<&CourseId> { + self.audience_course.as_ref() + } + + pub fn get_audience_class(&self) -> Option<&ClassGroupId> { + self.audience_class.as_ref() + } + + pub fn get_audience_capacity(&self) -> Option { + self.audience_capacity } pub fn get_starts_at(&self) -> Option { @@ -151,12 +190,12 @@ impl Event { /// deadline), the moment that end passes (a truly timeless event never /// closes). Returns the seat cap for the register path. pub fn registration_capacity(&self) -> Result, AppError> { - let EventAudience::Registration { capacity } = &self.audience else { + if self.audience_kind != EventAudienceKind::Registration { return Err(AppError::Validation(ValidationError::Invalid { field: "audience", reason: "this event does not take registrations", })); - }; + } // ends_at can't precede starts_at, so when both exist starts_at governs. if let Some(closes_at) = self.starts_at.or(self.ends_at) && Timestamp::now().as_millis() >= closes_at.as_millis() @@ -165,7 +204,7 @@ impl Event { "registration closed — the event has started or ended", )); } - Ok(*capacity) + Ok(self.audience_capacity) } } @@ -185,68 +224,35 @@ mod tests { assert!(EventDescription::try_new("").is_ok()); } - /// The audience stores as an internally tagged object — `{kind: '…', …}`. - /// The schema's `audience.kind`/`audience.role`/… field definitions and the - /// boot backfill (`{kind: 'school'}`) are written against exactly this - /// encoding; guard that it never drifts. - #[tokio::test] - async fn audience_encodes_internally_tagged_and_round_trips() { - use surrealdb::types::Value; - - let cases = [ - (EventAudience::School, "school"), - ( - EventAudience::Role { - role: Role::Student, - }, - "role", - ), - ( - EventAudience::Course { - course: CourseId::from_key("c1"), - }, - "course", - ), - ( - EventAudience::Class { - class: ClassGroupId::from_key("g1"), - }, - "class", - ), - ( - EventAudience::Registration { capacity: Some(30) }, - "registration", - ), - ( - EventAudience::Registration { capacity: None }, - "registration", - ), - ]; - for (audience, kind) in cases { - let value = audience.clone().into_value(); - let Value::Object(ref object) = value else { - panic!("audience must encode as an object, got {value:?}"); - }; - assert_eq!( - object.get("kind"), - Some(&Value::String(kind.to_string())), - "tag field must be `kind: '{kind}'`" - ); - assert_eq!(EventAudience::from_value(value).unwrap(), audience); - } + /// The `audience_kind` column is `TEXT` with a CHECK listing exactly + /// these spellings — audience-shaped queries match on them, so the + /// storage form may not drift (which `rename_all` mirrors). + #[test] + fn audience_kind_spellings_are_frozen() { + assert_eq!(EventAudienceKind::School.as_str(), "school"); + assert_eq!(EventAudienceKind::Role.as_str(), "role"); + assert_eq!(EventAudienceKind::Course.as_str(), "course"); + assert_eq!(EventAudienceKind::Class.as_str(), "class"); + assert_eq!(EventAudienceKind::Registration.as_str(), "registration"); } + /// The audience columns as a row writer would set them. fn event_with( - audience: EventAudience, + audience_kind: EventAudienceKind, + audience_capacity: Option, starts_at: Option, ends_at: Option, ) -> Event { Event { id: EventId::generate(), - creator: UserId::from_key("u1"), + creator: UserId::from_key("0198f1a2-3b4c-7d5e-8f90-aa2b3c4d5e6f"), title: EventTitle::try_new("signup").unwrap(), description: EventDescription::try_new("").unwrap(), - audience, + audience_kind, + audience_role: None, + audience_course: None, + audience_class: None, + audience_capacity, starts_at, ends_at, } @@ -254,21 +260,20 @@ mod tests { #[tokio::test] async fn registration_capacity_gates_and_echoes_cap() { - let open = |capacity| EventAudience::Registration { capacity }; let past = Some(Timestamp::from_millis(Timestamp::now().as_millis() - 1)); assert!(matches!( - event_with(EventAudience::School, None, None).registration_capacity(), + event_with(EventAudienceKind::School, None, None, None).registration_capacity(), Err(AppError::Validation(_)) )); assert_eq!( - event_with(open(None), None, None) + event_with(EventAudienceKind::Registration, None, None, None) .registration_capacity() .unwrap(), None ); assert_eq!( - event_with(open(Some(30)), None, None) + event_with(EventAudienceKind::Registration, Some(30), None, None) .registration_capacity() .unwrap(), Some(30) @@ -276,30 +281,14 @@ mod tests { // Started events close the list; an ends_at-only deadline in the past // does too. assert!(matches!( - event_with(open(Some(30)), past, None).registration_capacity(), + event_with(EventAudienceKind::Registration, Some(30), past, None) + .registration_capacity(), Err(AppError::Conflict(_)) )); assert!(matches!( - event_with(open(None), None, past).registration_capacity(), + event_with(EventAudienceKind::Registration, None, None, past) + .registration_capacity(), Err(AppError::Conflict(_)) )); } - - /// The database strips `NONE`-valued optional columns and the boot - /// conversion writes a bare `{kind: 'registration'}` — an object with no - /// `capacity` key at all must decode as an uncapped registration. - #[tokio::test] - async fn registration_audience_decodes_without_capacity_key() { - use surrealdb::types::Value; - - let value = EventAudience::Registration { capacity: None }.into_value(); - let Value::Object(mut object) = value else { - panic!("audience must encode as an object, got {value:?}"); - }; - object.remove("capacity"); - assert_eq!( - EventAudience::from_value(Value::Object(object)).unwrap(), - EventAudience::Registration { capacity: None } - ); - } } diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 27d75c2..3fbaca6 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -1,10 +1,8 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - use crate::constant::{ - EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS, + MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS, }; use crate::domain::course::CourseId; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::settings::ExamKindDef; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -24,34 +22,32 @@ use crate::validate::{ validate_required, }; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ExamId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct ExamId(uuid::Uuid); impl ExamId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: - /// exams list `id DESC` (newest first, [`crate::db::exam::list_all`]), + /// Minted from the process-wide monotonic generator, not a plain random + /// UUID: exams list `id DESC` (newest first, + /// [`crate::db::exam::list_all`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(EXAM_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(EXAM_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct ExamTitle(String); impl ExamTitle { @@ -65,7 +61,8 @@ impl ExamTitle { } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct ExamDescription(String); impl ExamDescription { @@ -84,7 +81,8 @@ impl ExamDescription { /// the exam's weight in the course average (set per kind in settings, not per /// exam). Stored exams keep their kind even if the school later edits the /// list; only new writes are held to the current one. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct ExamKind(String); impl ExamKind { @@ -106,7 +104,8 @@ impl ExamKind { /// A validated exam mode: `sync` (everyone sits inside one fixed window), /// `async` (each student starts inside the window and gets `duration_ms`), or /// `open` (no window — sit anytime, with an optional per-attempt duration). -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct ExamMode(String); impl ExamMode { @@ -122,7 +121,8 @@ impl ExamMode { /// A validated per-attempt time budget, milliseconds. Required for an `async` /// exam, optional for an `open` one (absent = unlimited time). -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct ExamDuration(i64); impl ExamDuration { @@ -140,7 +140,8 @@ impl ExamDuration { /// same spelling on the wire and in storage; `1` (the default) is the classic /// single sitting. Editable live: raising it mid-exam grants retakes, and /// lowering it only blocks *future* starts (existing attempts stand). -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct ExamAttemptLimit(i64); impl ExamAttemptLimit { @@ -269,7 +270,15 @@ impl ExamSchedule { } } -#[derive(Debug, Clone, SurrealValue)] +/// One exam. The schedule is flattened into columns, always written through +/// an [`ExamSchedule`], so the invariants above hold for every stored row. +/// +/// The `result_count` counter deliberately does NOT live on the struct: it is +/// a plain `BIGINT NOT NULL DEFAULT 0` column that only the mark-write and +/// mark-delete paths touch with conditional single statements, and every read +/// of it is its own `SELECT` — no whole-row rewrite can clobber it, and no +/// stale snapshot can pin it. +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Exam { pub(crate) id: ExamId, pub(crate) creator: UserId, @@ -277,31 +286,16 @@ pub struct Exam { pub(crate) title: ExamTitle, pub(crate) description: ExamDescription, pub(crate) kind: ExamKind, - // The schedule, flattened into columns (SCHEMAFULL keeps them typed). - // Always written through an `ExamSchedule`, so the invariants above hold - // for every stored row; pre-schedule rows read back as all-`None`. pub(crate) mode: Option, pub(crate) starts_at: Option, pub(crate) ends_at: Option, pub(crate) duration_ms: Option, - // Attempt policy. Rows predating these columns are backfilled by the boot - // migration (limit 1, rejoin open), so reads never see them missing. pub(crate) max_attempts: ExamAttemptLimit, pub(crate) allow_rejoin: bool, pub(crate) allow_review: bool, // Work-in-progress marker: a draft is visible only to its course's - // managers, cannot be sat, and cannot be graded. Rows predating the - // column are backfilled published (`false`). + // managers, cannot be sat, and cannot be graded. pub(crate) draft: bool, - /// How many marks the exam carries — a cap-style counter - /// ([`crate::db::cap::claim`] - /// from the grade, decremented by every delete of a mark), absent meaning - /// zero. Unlike every other counter it is carried *in the struct*, because - /// the save below is a whole-row `CONTENT` write: a column this type did - /// not know about would be wiped by the next exam PATCH. Being in the row - /// is also what makes it useful — the save pins it, so a grade landing - /// mid-PATCH refuses the save instead of slipping past its gates. - pub(crate) result_count: Option, } impl Exam { @@ -309,11 +303,6 @@ impl Exam { &self.id } - /// The marks this exam carries, as the counter reads (absent = none yet). - pub fn get_result_count(&self) -> i64 { - self.result_count.unwrap_or(0) - } - pub fn get_creator(&self) -> &UserId { &self.creator } diff --git a/src/domain/exam_answer.rs b/src/domain/exam_answer.rs index dabaa10..c603726 100644 --- a/src/domain/exam_answer.rs +++ b/src/domain/exam_answer.rs @@ -1,6 +1,4 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::{EXAM_ANSWER_TABLE, MAX_ANSWER_TEXT_LEN}; +use crate::constant::MAX_ANSWER_TEXT_LEN; use crate::domain::exam::ExamId; use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId}; use crate::domain::key; @@ -9,35 +7,38 @@ use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::validate_optional; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ExamAnswerId(RecordId); +/// The identity of one (question, user, seq) triple — a sitting's answer. Not +/// a row column: the table's primary key *is* the triple, which is what makes +/// saving a single atomic UPSERT keyed by seq: re-answering *within a sitting* +/// overwrites its one row, but a retake's `seq` writes a new row, so every +/// sitting keeps its own answer history. See [`key::sitting`] for the wire +/// shape and why the first sitting stays bare. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExamAnswerId { + pub(crate) question: ExamQuestionId, + pub(crate) user: UserId, + pub(crate) seq: i64, +} impl ExamAnswerId { - /// A deterministic id for the (question, user, seq) triple. Saving is a - /// single atomic UPSERT keyed by seq: re-answering *within a sitting* - /// overwrites its one row, but a retake's `seq` writes a new row, so every - /// sitting keeps its own answer history. See [`key::sitting`] for the key - /// shape and why the first sitting stays bare. pub fn composite(question: &ExamQuestionId, user: &UserId, seq: i64) -> Self { - let key = key::sitting(question.key(), user.key(), seq); - Self(RecordId::new(EXAM_ANSWER_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self { + question: question.clone(), + user: user.clone(), + seq, + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The underscore-joined wire form (`{question}_{user}[_{seq}]`). + pub fn key(&self) -> String { + key::sitting(self.question.key().as_str(), self.user.key().as_str(), self.seq) } } /// A free-text answer: may be empty (a student clearing their draft is a valid /// save), at most `MAX_ANSWER_TEXT_LEN` characters. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct AnswerText(String); impl AnswerText { @@ -54,9 +55,8 @@ impl AnswerText { /// One student's answer to one question, autosaved as they type or pick. /// `exam` is denormalized from the question so per-exam reads (live monitor, /// cascades) don't fan out through `exam_question`. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct ExamAnswer { - pub(crate) id: ExamAnswerId, pub(crate) exam: ExamId, pub(crate) question: ExamQuestionId, pub(crate) user: UserId, @@ -67,8 +67,9 @@ pub struct ExamAnswer { } impl ExamAnswer { - pub fn get_id(&self) -> &ExamAnswerId { - &self.id + /// The row's identity, built back from its primary-key columns. + pub fn get_id(&self) -> ExamAnswerId { + ExamAnswerId::composite(&self.question, &self.user, self.seq) } pub fn get_exam(&self) -> &ExamId { @@ -172,7 +173,6 @@ mod tests { fn answer(question: &ExamQuestion, user: &UserId, selected: Option) -> ExamAnswer { let selected = selected.map(|index| choice_id(question, index)); ExamAnswer { - id: ExamAnswerId::composite(question.get_id(), user, 1), exam: question.get_exam().clone(), question: question.get_id().clone(), user: user.clone(), @@ -186,12 +186,12 @@ mod tests { } fn student() -> UserId { - UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA") + UserId::from_key("0198f1a2-3b4c-7d5e-8f90-aa2b3c4d5e6f") } #[tokio::test] async fn seqs_key_distinct_rows_but_seq_one_keeps_the_bare_key() { - let question = ExamQuestionId::from_key("01TESTQUESTIONAAAAAAAAAAAA"); + let question = ExamQuestionId::from_key("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"); let user = student(); // seq 1 keeps the pre-history bare `{question}_{user}` key… let first = ExamAnswerId::composite(&question, &user, 1); @@ -215,7 +215,7 @@ mod tests { #[tokio::test] async fn auto_score_counts_correct_choices_only() { - let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); + let exam = ExamId::from_key("0198f1a2-3b4c-7d5e-8f90-be2b3c4d5e6f"); let user = student(); let q1 = choice_question(&exam, 10, 0); // answered right let q2 = choice_question(&exam, 20, 1); // answered wrong @@ -233,14 +233,14 @@ mod tests { #[tokio::test] async fn auto_score_of_nothing_is_zero() { assert_eq!(auto_score(&[], &[]), (0, 0)); - let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); + let exam = ExamId::from_key("0198f1a2-3b4c-7d5e-8f90-be2b3c4d5e6f"); let questions = vec![text_question(&exam, 50)]; assert_eq!(auto_score(&questions, &[]), (0, 0)); } #[tokio::test] async fn is_correct_judges_choice_questions_only() { - let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); + let exam = ExamId::from_key("0198f1a2-3b4c-7d5e-8f90-be2b3c4d5e6f"); let user = student(); let choice = choice_question(&exam, 10, 1); assert_eq!( diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index 6f8b5da..bc4b5de 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -1,34 +1,32 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::EXAM_ATTEMPT_TABLE; use crate::domain::exam::Exam; use crate::domain::exam::ExamId; use crate::domain::key; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -/// A deterministic id for the (exam, user, seq) triple, so sitting `seq` -/// exists at most once by construction — a concurrent double "start" races -/// on the same id and exactly one create wins. See [`key::sitting`] for the -/// key shape and why the first sitting stays bare. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ExamAttemptId(RecordId); +/// The identity of one (exam, user, seq) triple, so sitting `seq` exists at +/// most once by construction — a concurrent double "start" races on the same +/// primary key and exactly one insert wins. See [`key::sitting`] for the wire +/// shape and why the first sitting stays bare. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExamAttemptId { + pub(crate) exam: ExamId, + pub(crate) user: UserId, + pub(crate) seq: i64, +} impl ExamAttemptId { pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self { - let key = key::sitting(exam.key(), user.key(), seq); - Self(RecordId::new(EXAM_ATTEMPT_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self { + exam: exam.clone(), + user: user.clone(), + seq, + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The underscore-joined wire form (`{exam}_{user}[_{seq}]`). + pub fn key(&self) -> String { + key::sitting(self.exam.key().as_str(), self.user.key().as_str(), self.seq) } } @@ -60,12 +58,11 @@ impl AttemptStatus { /// exam allows retakes; `left_at` marks a student who walked out of the exam /// room mid-attempt. Grading stays a separate `exam_result` row. /// -/// Fields are crate-visible: [`crate::db::exam_attempt`] reads the id to -/// target its field-scoped writes and [`crate::service::exam_attempt::start`] -/// mints the rows on create. -#[derive(Debug, Clone, SurrealValue)] +/// Fields are crate-visible: [`crate::db::exam_attempt`] targets its +/// field-scoped writes by the primary-key triple and +/// [`crate::service::exam_attempt::start`] mints the rows on create. +#[derive(Debug, Clone, sqlx::FromRow)] pub struct ExamAttempt { - pub(crate) id: ExamAttemptId, pub(crate) exam: ExamId, pub(crate) user: UserId, pub(crate) seq: i64, @@ -75,8 +72,9 @@ pub struct ExamAttempt { } impl ExamAttempt { - pub fn get_id(&self) -> &ExamAttemptId { - &self.id + /// The row's identity, built back from its primary-key columns. + pub fn get_id(&self) -> ExamAttemptId { + ExamAttemptId::composite(&self.exam, &self.user, self.seq) } pub fn get_exam(&self) -> &ExamId { diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index cf28d2f..4b624ef 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -1,47 +1,43 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; +use sqlx::types::Json; use crate::constant::{ - EXAM_QUESTION_TABLE, MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, + MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, MIN_QUESTION_CHOICES, }; use crate::domain::bank_question::BankQuestionId; use crate::domain::exam::ExamId; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::subject::SubjectId; use crate::error::ValidationError; use crate::validate::{validate_question_kind, validate_question_points, validate_required}; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ExamQuestionId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct ExamQuestionId(uuid::Uuid); impl ExamQuestionId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: the - /// id *is* the question's presentation order + /// Minted from the process-wide monotonic generator, not a plain random + /// UUID: the id *is* the question's presentation order /// ([`crate::db::exam_question::list_for_exam`] /// sorts `id ASC`), and a random low half scrambles a burst of saves that /// lands inside one millisecond. pub fn generate() -> Self { - Self(RecordId::new(EXAM_QUESTION_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(EXAM_QUESTION_TABLE, key)) + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct QuestionText(String); impl QuestionText { @@ -57,7 +53,8 @@ impl QuestionText { /// A validated question kind: `choice` (pick one option, auto-scorable) or /// `text` (free text, judged by the grader). -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct QuestionKind(String); impl QuestionKind { @@ -73,7 +70,8 @@ impl QuestionKind { /// A validated question weight in the auto-score, held to /// `[MIN_QUESTION_POINTS, MAX_QUESTION_POINTS]`. -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct QuestionPoints(i64); impl QuestionPoints { @@ -88,7 +86,8 @@ impl QuestionPoints { } /// One option's text: non-blank, at most `MAX_CHOICE_TEXT_LEN` characters. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type, serde::Serialize, serde::Deserialize)] +#[sqlx(transparent)] pub struct ChoiceText(String); impl ChoiceText { @@ -102,8 +101,8 @@ impl ChoiceText { } } -/// An option's stable identity — a server-minted ULID, never reused, never -/// taken from client input (it becomes part of an image row's record id and of +/// An option's stable identity — a server-minted UUID, never reused, never +/// taken from client input (it becomes part of an image row's slot key and of /// a URL path, so a client-shaped value would be an injection surface). /// /// This id is the whole point of the choice remodel. `correct`, the per-option @@ -111,15 +110,19 @@ impl ChoiceText { /// reordering the list or deleting an option moves none of them. They used to /// be parallel arrays keyed by position, where any edit to the list silently /// re-pointed the others. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +/// +/// Stored as a bare string: it travels inside the choices JSON and names a +/// slot in the image tables' `TEXT` columns. +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type, serde::Serialize, serde::Deserialize)] +#[sqlx(transparent)] pub struct ChoiceId(String); impl ChoiceId { - /// Plain `Ulid::generate()` deliberately: options are ordered by their position - /// in the stored `Vec`, never by id, so nothing here reads the id as a - /// clock — it only has to be unique. + /// Plain `Uuid::new_v4()` deliberately: options are ordered by their + /// position in the stored `Vec`, never by id, so nothing here reads the id + /// as a clock — it only has to be unique. fn generate() -> Self { - Self(Ulid::generate().to_string()) + Self(uuid::Uuid::new_v4().to_string()) } pub fn as_str(&self) -> &str { @@ -127,8 +130,9 @@ impl ChoiceId { } } -/// One option of a choice question: its identity plus its text. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +/// One option of a choice question: its identity plus its text. Stored inside +/// the `choices` JSONB column, in list order. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Choice { id: ChoiceId, text: ChoiceText, @@ -277,12 +281,12 @@ impl QuestionSpec { } } -/// One question of an exam. Order within the exam is the id's ULID order -/// (creation order); the kind-dependent columns always satisfy the +/// One question of an exam. Order within the exam is the id's creation order; +/// the kind-dependent columns always satisfy the /// [`QuestionSpec`] invariants because every write goes through one. Every /// question links to a subject of the exam's course — the handlers verify the /// subject's course matches before any write. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct ExamQuestion { pub(crate) id: ExamQuestionId, pub(crate) exam: ExamId, @@ -290,11 +294,10 @@ pub struct ExamQuestion { pub(crate) text: QuestionText, pub(crate) kind: QuestionKind, pub(crate) points: QuestionPoints, - pub(crate) choices: Option>, + pub(crate) choices: Option>>, pub(crate) correct: Option, /// The bank template this question was created *from*, if it was inserted /// out of the bank. Written once, at insert. - #[surreal(default)] pub(crate) from_bank: Option, /// The bank template most recently created *by saving this question* into /// the bank, if any. Written by @@ -302,7 +305,6 @@ pub struct ExamQuestion { /// repeat save. Never set by an insert-from-bank: the two directions are /// separate columns precisely so "came from the bank" can't be misread as /// "already saved to the bank". - #[surreal(default)] pub(crate) banked_as: Option, } @@ -332,7 +334,7 @@ impl ExamQuestion { } pub fn get_choices(&self) -> Option<&[Choice]> { - self.choices.as_deref() + self.choices.as_ref().map(|json| json.0.as_slice()) } pub fn get_correct(&self) -> Option<&ChoiceId> { @@ -352,7 +354,7 @@ impl ExamQuestion { pub fn spec(&self) -> QuestionSpec { QuestionSpec::from_stored( self.kind.clone(), - self.choices.clone(), + self.choices.as_ref().map(|json| json.0.clone()), self.correct.clone(), ) } @@ -367,7 +369,7 @@ impl ExamQuestion { text: QuestionText::try_new(text).unwrap(), points: QuestionPoints::try_new(points).unwrap(), kind: spec.kind, - choices: spec.choices, + choices: spec.choices.map(Json), correct: spec.correct, from_bank: None, banked_as: None, @@ -407,13 +409,13 @@ mod tests { /// A teacher saving several questions back to back gets them back in that /// order: `list_for_exam` sorts `id ASC`, so the ids minted inside one - /// millisecond have to sort in mint order. Revert `generate` to - /// `Ulid::generate()` and this fails — the low 80 bits are redrawn per id, so a + /// millisecond have to sort in mint order. Revert `generate` to a plain + /// random UUID and this fails — the random bits are redrawn per id, so a /// same-tick burst comes out shuffled. #[tokio::test] async fn ids_sort_in_creation_order() { let ids: Vec = (0..500) - .map(|_| ExamQuestionId::generate().key().to_string()) + .map(|_| ExamQuestionId::generate().key()) .collect(); let mut sorted = ids.clone(); sorted.sort(); @@ -491,8 +493,8 @@ mod tests { let built = spec(two_choices(), Some("b")).unwrap(); let (_, choices, correct) = built.into_parts(); let choices = choices.unwrap(); - // Client labels never reach storage. - assert!(choices.iter().all(|c| c.get_id().as_str().len() == 26)); + // Client labels never reach storage; a minted id is a hyphenated UUID. + assert!(choices.iter().all(|c| c.get_id().as_str().len() == 36)); assert_ne!(choices[0].get_id(), choices[1].get_id()); // `correct` resolved to the *second* option's minted id, by label. assert_eq!(correct.as_ref(), Some(choices[1].get_id())); @@ -579,7 +581,7 @@ mod tests { use proptest::prelude::*; /// A stored question's options, built the only way they can be: through - /// `try_new` on create, so the ids are real minted ULIDs. + /// `try_new` on create, so the ids are real minted UUIDs. fn stored_set(n: usize) -> Vec { let inputs = (0..n) .map(|i| ChoiceInput { @@ -604,19 +606,21 @@ mod tests { } fn key() -> impl Strategy { + use proptest::prelude::*; prop_oneof![ 4 => (0usize..10).prop_map(Key::Stored), 3 => prop_oneof![ Just(String::new()), Just("new:1".to_string()), "[a-z0-9]{1,5}", - Just("01ARZ3NDEKTSV4RRFFQ69G5FAV".to_string()), + Just("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f".to_string()), ].prop_map(Key::Other), 1 => Just(Key::Null), ] } fn text() -> impl Strategy { + use proptest::prelude::*; prop_oneof![ 6 => "[a-z ]{1,6}", 1 => Just(String::new()), @@ -691,7 +695,7 @@ mod tests { // freshly minted, so it can never take over a stored // option's identity or its picture. None => { - prop_assert_eq!(choice.id.as_str().len(), 26); + prop_assert_eq!(choice.id.as_str().len(), 36); prop_assert!(!stored_ids.contains(&choice.id.as_str())); } } diff --git a/src/domain/exam_result.rs b/src/domain/exam_result.rs index c2b3512..8ea2764 100644 --- a/src/domain/exam_result.rs +++ b/src/domain/exam_result.rs @@ -1,8 +1,5 @@ use std::collections::HashMap; -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::{EXAM_RESULT_TABLE, KIND_REF_TABLE}; use crate::domain::exam::ExamId; use crate::domain::key; use crate::domain::user::UserId; @@ -16,19 +13,11 @@ pub(crate) fn draft_error() -> AppError { AppError::Conflict("this exam is a draft — publish it before grading") } -/// The reference counter for one exam kind — how many marks are written under -/// that name, and whether the school has retired it (see -/// [`crate::db::cap`]). Keyed by the name itself: the kind is snapshotted -/// text on the exam, and this row is what makes "a kind nothing is graded under -/// may be removed" a decision the database takes, not a count a concurrent mark -/// can invalidate. -pub(crate) fn kind_ref(kind: &str) -> RecordId { - RecordId::new(KIND_REF_TABLE, kind) -} - /// The refusal a mark meets once its kind has left the school's list. The /// mirror of the settings-side 409: whichever of the two writes reaches the -/// counter first, the other is told the name is no longer usable. +/// counter row (`kind_ref`) first, the other is told the name is no longer +/// usable. The ref-row key is the kind's own name — a `TEXT` primary key, +/// like the settings singleton. pub(crate) fn retired_kind_error(kind: &str) -> AppError { AppError::ConflictOwned(format!( "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 { )) } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ExamResultId(RecordId); +/// The identity of one (exam, user, seq) triple — one mark row per sitting, +/// so grading is a single atomic UPSERT on the composite primary key with no +/// find-then-insert race. See [`key::sitting`] for the wire shape and why the +/// first sitting stays bare. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExamResultId { + pub(crate) exam: ExamId, + pub(crate) user: UserId, + pub(crate) seq: i64, +} impl ExamResultId { - /// A deterministic id for the (exam, user, seq) triple — one mark row per - /// sitting, so grading is a single atomic UPSERT with no find-then-insert - /// race. See [`key::sitting`] for the key shape and why the first sitting - /// stays bare. pub fn composite(exam: &ExamId, user: &UserId, seq: i64) -> Self { - let key = key::sitting(exam.key(), user.key(), seq); - Self(RecordId::new(EXAM_RESULT_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self { + exam: exam.clone(), + user: user.clone(), + seq, + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The underscore-joined wire form (`{exam}_{user}[_{seq}]`). + pub fn key(&self) -> String { + key::sitting(self.exam.key().as_str(), self.user.key().as_str(), self.seq) } } -/// A validated exam mark. Stored as an `int`, held to `[MIN_MARK, MAX_MARK]`. +/// A validated exam mark. Stored as a `BIGINT`, held to +/// `[MIN_MARK, MAX_MARK]`. /// Kept in its own row — an exam result is never a course note. -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct Mark(i64); impl Mark { @@ -77,9 +69,8 @@ impl Mark { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct ExamResult { - pub(crate) id: ExamResultId, pub(crate) exam: ExamId, pub(crate) user: UserId, pub(crate) seq: i64, @@ -88,8 +79,9 @@ pub struct ExamResult { } impl ExamResult { - pub fn get_id(&self) -> &ExamResultId { - &self.id + /// The row's identity, built back from its primary-key columns. + pub fn get_id(&self) -> ExamResultId { + ExamResultId::composite(&self.exam, &self.user, self.seq) } pub fn get_exam(&self) -> &ExamId { @@ -117,14 +109,14 @@ impl ExamResult { /// The latest-seq mark per (exam, user) pair, preserving the outer list's /// row order (first appearance of each pair). Grade-of-record is the latest /// attempt's mark, so a pair with retakes collapses to its highest seq. Done -/// in Rust rather than SQL: SurrealDB's `GROUP BY` can't return the whole -/// row that carries the max, and id-order can't stand in for seq-order once -/// seq reaches two digits. +/// in Rust rather than SQL: it keeps the outer ordering stable without a +/// window-function dance, and id order can't stand in for seq order once seq +/// reaches two digits. pub(crate) fn latest_per_pair(rows: Vec) -> Vec { let mut order: Vec<(String, String)> = Vec::new(); let mut best: HashMap<(String, String), ExamResult> = HashMap::new(); for row in rows { - let key = (row.exam.key().to_string(), row.user.key().to_string()); + let key = (row.exam.key(), row.user.key()); match best.get(&key) { Some(existing) if existing.seq >= row.seq => {} Some(_) => { @@ -153,4 +145,34 @@ mod tests { assert!(Mark::try_new(-1).is_err()); assert!(Mark::try_new(101).is_err()); } + + /// Grade-of-record: a pair with retakes collapses to its highest seq, and + /// the outer list keeps its row order. + #[tokio::test] + async fn latest_per_pair_keeps_the_highest_seq_in_first_seen_order() { + let exam_of = |n: u16| ExamId::from_key(&format!("0198f1a2-0000-7000-8000-{n:012x}")); + let user_of = |n: u16| UserId::from_key(&format!("0198f1a2-1111-7000-8000-{n:012x}")); + let (exam, user, other) = (exam_of(1), user_of(1), user_of(2)); + let row = |user: UserId, seq: i64, mark: i64| ExamResult { + exam: exam.clone(), + user, + seq, + mark: Mark::try_new(mark).unwrap(), + graded_by: user_of(9), + }; + + let got = latest_per_pair(vec![ + row(user.clone(), 1, 60), + row(other.clone(), 1, 70), + row(user.clone(), 2, 85), // retake outranks the seq-1 mark + row(other, 3, 40), // third sitting of the second pair + ]); + assert_eq!(got.len(), 2); + assert_eq!(got[0].get_user(), &user); + assert_eq!(got[0].get_seq(), 2); + assert_eq!(got[0].get_mark().as_i64(), 85); + assert_eq!(got[1].get_user(), &other); + assert_eq!(got[1].get_seq(), 3); + assert_eq!(got[1].get_mark().as_i64(), 40); + } } diff --git a/src/domain/fee_plan.rs b/src/domain/fee_plan.rs index a3d074e..c18c073 100644 --- a/src/domain/fee_plan.rs +++ b/src/domain/fee_plan.rs @@ -4,51 +4,47 @@ //! //! The installments are **embedded** on the plan row rather than child rows: //! a charge line copies the amount and due date it was assigned at, so the -//! installment is a template, never a thing that has to be joined back to. No -//! field inside the object is optional — SurrealDB 3 drops an object key whose -//! value is `NONE`, which would make the stored shape differ from the written -//! one. +//! installment is a template, never a thing that has to be joined back to. +//! The embedded list rides a `JSONB` column in stored order. //! //! Due dates may be in the **past**: a school adopting the app mid-year //! legitimately assigns a plan whose first installments were already due, so //! the no-past rule that guards exams, lessons and events deliberately does not //! apply here. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use sqlx::types::Json; -use crate::constant::{FEE_PLAN_TABLE, MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN}; -use crate::domain::monotonic_id::next_ulid; +use crate::constant::{MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN}; +use crate::domain::monotonic_id::next_uuid; use crate::domain::payment_ledger::LedgerAmount; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::validate_required; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct FeePlanId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct FeePlanId(uuid::Uuid); impl FeePlanId { + /// A write-ordered id: plan listings read newest first. pub fn generate() -> Self { - Self(RecordId::new(FEE_PLAN_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(FEE_PLAN_TABLE, key)) + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct FeePlanName(String); impl FeePlanName { @@ -64,8 +60,8 @@ impl FeePlanName { } /// One instalment of a plan: what is owed, and when it falls due. Both fields -/// are required — see the module doc on `NONE` keys. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +/// are required, so the stored JSON shape always matches the written one. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Installment { amount_minor: LedgerAmount, due_at: Timestamp, @@ -101,11 +97,11 @@ pub fn validate_installments(installments: &[Installment]) -> Result<(), Validat Ok(()) } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct FeePlan { pub(crate) id: FeePlanId, pub(crate) name: FeePlanName, - pub(crate) installments: Vec, + pub(crate) installments: Json>, pub(crate) created_by: UserId, pub(crate) created_at: Timestamp, } @@ -158,4 +154,21 @@ mod tests { assert!(validate_installments(&vec![one.clone(); MAX_FEE_PLAN_INSTALLMENTS]).is_ok()); assert!(validate_installments(&vec![one; MAX_FEE_PLAN_INSTALLMENTS + 1]).is_err()); } + + /// The installments ride the row as JSON, so the storage contract is that + /// an installment round-trips through `serde_json` unchanged — the amount + /// stays an integer minor-unit count and the due date a bare millisecond + /// number. + #[test] + fn an_installment_survives_the_json_round_trip() { + let one = Installment::new( + LedgerAmount::try_new(12_345).unwrap(), + Timestamp::from_millis(1_700_000_000_000), + ); + let json = serde_json::to_value(&one).unwrap(); + assert_eq!(json["amount_minor"], serde_json::json!(12_345)); + assert_eq!(json["due_at"], serde_json::json!(1_700_000_000_000)); + let back: Installment = serde_json::from_value(json).unwrap(); + assert_eq!(back, one); + } } diff --git a/src/domain/fee_plan_assignment.rs b/src/domain/fee_plan_assignment.rs index 7462433..4552fbc 100644 --- a/src/domain/fee_plan_assignment.rs +++ b/src/domain/fee_plan_assignment.rs @@ -2,8 +2,8 @@ //! owed: assigning appends *every* installment of the plan as a charge line at //! once, each carrying its own due date. //! -//! The row is keyed `_`, and every charge it raises is keyed -//! from that same key plus the installment number, so the whole operation is +//! The row is keyed (plan, student), and every charge it raises is keyed from +//! that same pair plus the installment number, so the whole operation is //! idempotent **by identity**: assigning twice writes nothing the second time, //! however the two requests interleave, and an assign cut short after three of //! twelve charges landed completes itself when it is repeated. No scan decides @@ -15,47 +15,49 @@ //! its charges. That is also why the plan's assignment refcount is only ever //! claimed and never released — a plan, once assigned, stays frozen for good. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::FEE_PLAN_ASSIGNMENT_TABLE; use crate::domain::fee_plan::FeePlanId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct FeePlanAssignmentId(RecordId); +/// The identity of one (plan, student) pair. Not a row column: the table's +/// primary key *is* the pair — one assignment per pair by construction — and +/// this struct's job is the underscore-joined wire form at the HTTP edge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FeePlanAssignmentId { + pub(crate) plan: FeePlanId, + pub(crate) student: UserId, +} impl FeePlanAssignmentId { - /// A deterministic id for the (plan, student) pair — one assignment per - /// pair by construction, and the prefix every charge line of that - /// assignment is keyed from. ULID keys are alphanumeric, so `_` is an - /// unambiguous joiner. pub fn composite(plan: &FeePlanId, student: &UserId) -> Self { - Self(RecordId::new( - FEE_PLAN_ASSIGNMENT_TABLE, - format!("{}_{}", plan.key(), student.key()), - )) + Self { + plan: plan.clone(), + student: student.clone(), + } } + /// Splits a wire key back into its pair. A malformed key (no `_` joiner, + /// unparseable halves) yields nil components, which match no row — the + /// same 404 a well-formed but absent key gets. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(FEE_PLAN_ASSIGNMENT_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + let (plan, student) = match key.split_once('_') { + Some((plan, student)) => (plan, student), + None => ("", ""), + }; + Self { + plan: FeePlanId::from_key(plan), + student: UserId::from_key(student), + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The underscore-joined wire form (`{plan}_{student}`). + pub fn key(&self) -> String { + format!("{}_{}", self.plan.key(), self.student.key()) } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct FeePlanAssignment { - pub(crate) id: FeePlanAssignmentId, pub(crate) plan: FeePlanId, pub(crate) student: UserId, pub(crate) assigned_by: UserId, @@ -63,8 +65,9 @@ pub struct FeePlanAssignment { } impl FeePlanAssignment { - pub fn get_id(&self) -> &FeePlanAssignmentId { - &self.id + /// The row's identity, built back from its primary-key columns. + pub fn get_id(&self) -> FeePlanAssignmentId { + FeePlanAssignmentId::composite(&self.plan, &self.student) } pub fn get_plan(&self) -> &FeePlanId { @@ -83,3 +86,32 @@ impl FeePlanAssignment { self.created_at } } + +#[cfg(test)] +mod tests { + use super::*; + + const PLAN: &str = "0198f1a2-0000-7000-8000-000000000001"; + const STUDENT: &str = "0198f1a2-1111-7000-8000-000000000002"; + + /// The wire key is the pair, and the pair survives the round trip — this + /// is what lets a charge line's `assignment` reference travel as one path + /// segment. + #[test] + fn the_wire_key_round_trips_through_the_pair() { + let plan = FeePlanId::from_key(PLAN); + let student = UserId::from_key(STUDENT); + let id = FeePlanAssignmentId::composite(&plan, &student); + assert_eq!(id.key(), format!("{PLAN}_{STUDENT}")); + assert_eq!(FeePlanAssignmentId::from_key(&id.key()), id); + } + + /// A key that is not a pair cannot name an assignment: it decodes to nil + /// components, which match no row (a 404, never a panic). + #[test] + fn a_malformed_key_decodes_to_something_that_matches_nothing() { + let junk = FeePlanAssignmentId::from_key("not-a-pair"); + assert_eq!(junk.plan.key(), uuid::Uuid::nil().to_string()); + assert_eq!(junk.student.key(), uuid::Uuid::nil().to_string()); + } +} diff --git a/src/domain/homework.rs b/src/domain/homework.rs index 352bfa8..4d47d5d 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -6,51 +6,47 @@ //! ([`crate::domain::homework_result`]). Persistence lives in //! [`crate::db::homework`], workflows in [`crate::service::homework`]. //! -//! `course`, `created_by`, and `created_at` are fixed at creation (the schema -//! marks them `READONLY`): moving a homework between courses would strand the +//! `course`, `created_by`, and `created_at` are fixed at creation (READONLY +//! app discipline): moving a homework between courses would strand the //! submissions and grades of students not in the target course. `subject` is -//! deliberately *not* readonly — it is re-taggable through PATCH, validated +//! deliberately *not* fixed — it is re-taggable through PATCH, validated //! same-course by the web layer, exactly like an exam question's subject. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::{HOMEWORK_TABLE, MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN}; +use crate::constant::{MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN}; use crate::domain::course::CourseId; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::subject::SubjectId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::{validate_optional, validate_required}; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct HomeworkId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct HomeworkId(uuid::Uuid); impl HomeworkId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: - /// homework lists `id DESC` (newest first, [`Homework::list_all`]), - /// and a random low half scrambles rows minted in the same millisecond. + /// Minted from the process-wide monotonic generator, not a plain random + /// UUID: homework lists `id DESC` (newest first, [`HomeworkId`]-ordered + /// listings), and a random low half scrambles rows minted in the same + /// millisecond. pub fn generate() -> Self { - Self(RecordId::new(HOMEWORK_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(HOMEWORK_TABLE, key)) + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct HomeworkTitle(String); impl HomeworkTitle { @@ -64,7 +60,8 @@ impl HomeworkTitle { } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct HomeworkDescription(String); impl HomeworkDescription { @@ -78,12 +75,12 @@ impl HomeworkDescription { } } -/// A homework assignment. `assigned` is the optional student subset: `None` -/// (the column absent) and an empty list both mean "the whole course" — see +/// A homework assignment. `assigned` is the optional student subset (`uuid[] +/// NULL`): `NULL` and an empty list both mean "the whole course" — see /// [`Homework::student_sees`]. Because whole-course homework carries no roster, /// a student who enrolls later is covered automatically; a subset is a fixed /// snapshot of the students named at assign (or last PATCH) time. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Homework { pub(crate) id: HomeworkId, pub(crate) course: CourseId, @@ -135,7 +132,7 @@ impl Homework { } /// Whether `user` is in this homework's audience. A whole-course homework - /// (`assigned` absent or empty) is visible to every enrolled student; a + /// (`assigned` NULL or empty) is visible to every enrolled student; a /// subset homework only to the students it names. Callers pair this with an /// enrollment check — being named is visibility, not enrollment. pub fn student_sees(&self, user: &UserId) -> bool { @@ -150,6 +147,9 @@ impl Homework { mod tests { use super::*; + const A: &str = "0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e"; + const B: &str = "0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f"; + #[tokio::test] async fn title_is_required() { assert!(HomeworkTitle::try_new("Read chapter 3").is_ok()); @@ -166,12 +166,12 @@ mod tests { #[tokio::test] async fn student_sees_covers_whole_course_and_named_subsets() { - let a = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); - let b = UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"); + let a = UserId::from_key(A); + let b = UserId::from_key(B); let with = |assigned| Homework { id: HomeworkId::generate(), - course: CourseId::from_key("01TESTCOURSEAAAAAAAAAAAAAA"), - subject: SubjectId::from_key("01TESTSUBJECTAAAAAAAAAAAAA"), + course: CourseId::from_key("0198f1a2-3b4c-7d5e-8f90-cccc3c4d5e6f"), + subject: SubjectId::from_key("0198f1a2-3b4c-7d5e-8f90-dddd4c4d5e6f"), title: HomeworkTitle::try_new("hw").unwrap(), description: None, due_at: Timestamp::from_millis(1), @@ -179,7 +179,7 @@ mod tests { created_by: a.clone(), created_at: Timestamp::from_millis(1), }; - // Whole course: absent or empty list means everyone sees it. + // Whole course: NULL or empty list means everyone sees it. assert!(with(None).student_sees(&a)); assert!(with(Some(vec![])).student_sees(&b)); // Subset: only the named students. diff --git a/src/domain/homework_file.rs b/src/domain/homework_file.rs index 5fe0db6..c3d9a53 100644 --- a/src/domain/homework_file.rs +++ b/src/domain/homework_file.rs @@ -1,54 +1,46 @@ //! A file attached to a homework submission. Like a note file, the row carries //! metadata only (original filename, MIME type, byte size) and the bytes live //! on disk under [`crate::config::Config::files_path`] — but named by this -//! row's own `file` field (a fresh server-generated ULID per upload, like a +//! row's own `file` field (a fresh server-generated UUID per upload, like a //! question image), never by user input, so nothing a client sends shapes a //! disk path. Files are immutable: created and deleted, never updated, so the -//! `READONLY` `submission`/`file`/`created_at` columns are only ever set once. -//! The web layer owns the blob I/O and its ordering (blob before row on -//! upload, row before blob on delete); the rows are written and read by -//! [`crate::db::homework_file`], the upload/attach workflow by -//! [`crate::service::homework_file`]. +//! `submission`/`file`/`created_at` columns are only ever set once (READONLY +//! app discipline — single writer). The web layer owns the blob I/O and its +//! ordering (blob before row on upload, row before blob on delete); the rows +//! are written and read by [`crate::db::homework_file`], the upload/attach +//! workflow by [`crate::service::homework_file`]. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; - -use crate::constant::HOMEWORK_FILE_TABLE; use crate::domain::homework_submission::HomeworkSubmissionId; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::note_file::{FileContentType, FileName}; use crate::domain::timestamp::Timestamp; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct HomeworkFileId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct HomeworkFileId(uuid::Uuid); impl HomeworkFileId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: - /// a submission's files list `id DESC` (newest first, [`HomeworkFile::list_for_submission`]), - /// and a random low half scrambles rows minted in the same millisecond. + /// Minted from the process-wide monotonic generator, not a plain random + /// UUID: a submission's files list `id DESC` (newest first), and a random + /// low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(HOMEWORK_FILE_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(HOMEWORK_FILE_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } -/// An attachment row. `file` is the blob's on-disk name (a fresh ULID per +/// An attachment row. `file` is the blob's on-disk name (a fresh UUID per /// upload), independent of the row id and reused as the GC key on cascade. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct HomeworkFile { pub(crate) id: HomeworkFileId, pub(crate) submission: HomeworkSubmissionId, @@ -62,7 +54,8 @@ pub struct HomeworkFile { impl HomeworkFile { /// Assemble a row (fresh blob name generated here) without persisting it. /// The caller writes the blob under [`Self::get_file`] first, then calls - /// [`Self::insert`] — so a stored row always points at a real blob. + /// [`crate::db::homework_file::insert`] — so a stored row always points at + /// a real blob. pub fn new( submission: &HomeworkSubmissionId, name: FileName, @@ -75,7 +68,7 @@ impl HomeworkFile { name, content_type, size, - file: Ulid::generate().to_string(), + file: uuid::Uuid::new_v4().to_string(), created_at: Timestamp::now(), } } @@ -100,7 +93,7 @@ impl HomeworkFile { self.size } - /// The blob's on-disk name — a fresh ULID, so no user input shapes a path. + /// The blob's on-disk name — a fresh UUID, so no user input shapes a path. pub fn get_file(&self) -> &str { &self.file } diff --git a/src/domain/homework_result.rs b/src/domain/homework_result.rs index f6a0f8d..10ac02f 100644 --- a/src/domain/homework_result.rs +++ b/src/domain/homework_result.rs @@ -1,8 +1,9 @@ //! A teacher's grade on one student's homework: a status //! (`done`/`incomplete`/`missing`) plus an optional numeric [`Mark`] (0..=100, -//! reused from exam results). Like an exam result, the row id is the -//! deterministic `{homework}_{user}` composite, so grading is one atomic UPSERT -//! and there is exactly one grade per (homework, user) by construction. +//! reused from exam results). The row carries its own `id` primary key and a +//! `UNIQUE (homework, app_user)` constraint, so grading is one atomic UPSERT +//! (`ON CONFLICT (homework, app_user)`) and there is exactly one grade per +//! (homework, user) by construction. //! //! A stored result is what *freezes* a submission: while a grade exists the //! student's submission and files are locked (the web layer answers 409), @@ -13,40 +14,32 @@ //! [`crate::db::homework_result`], the grading gates in //! [`crate::service::homework_result`]. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::HOMEWORK_RESULT_TABLE; use crate::domain::exam_result::Mark; use crate::domain::homework::HomeworkId; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::validate_homework_status; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct HomeworkResultId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct HomeworkResultId(uuid::Uuid); impl HomeworkResultId { - /// The one id a (homework, user) pair can have — a deterministic composite, - /// so grading is a single atomic UPSERT with no find-then-insert race and - /// one grade per pair by construction. ULID keys are alphanumeric, so `_` - /// is an unambiguous joiner. - pub fn composite(homework: &HomeworkId, user: &UserId) -> Self { - Self(RecordId::new( - HOMEWORK_RESULT_TABLE, - format!("{}_{}", homework.key(), user.key()), - )) + /// A write-ordered id: grade listings read newest first. + pub fn generate() -> Self { + Self(next_uuid()) } - pub fn record(&self) -> RecordId { - self.0.clone() + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. + pub fn from_key(key: &str) -> Self { + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } @@ -54,12 +47,12 @@ impl HomeworkResultId { /// (submitted but lacking), or `missing` (not done). Held to the /// [`crate::constant::HOMEWORK_STATUSES`] set by [`HomeworkStatus::try_new`] — /// the same validated-string-against-a-const shape as -/// [`crate::domain::exam::ExamMode`], which is why the `status` column needs no -/// DDL `ASSERT` (repo convention: enums live in Rust newtypes, not the schema). -/// It stores as the bare string. A stored `missing` is a teacher's deliberate -/// verdict, distinct from the roster's *computed* missing (unsubmitted past due, -/// derived in the web layer, never stored). -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +/// [`crate::domain::exam::ExamMode`]. It stores as the bare string. A stored +/// `missing` is a teacher's deliberate verdict, distinct from the roster's +/// *computed* missing (unsubmitted past due, derived in the web layer, never +/// stored). +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct HomeworkStatus(String); impl HomeworkStatus { @@ -73,7 +66,7 @@ impl HomeworkStatus { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct HomeworkResult { pub(crate) id: HomeworkResultId, pub(crate) homework: HomeworkId, @@ -119,17 +112,15 @@ impl HomeworkResult { mod tests { use super::*; use crate::constant::HOMEWORK_STATUSES; - use surrealdb::types::Value; #[tokio::test] - async fn status_is_held_to_the_const_and_stores_as_a_bare_string() { - // Enforcement lives in the newtype against HOMEWORK_STATUSES (the DDL - // carries no ASSERT), and the stored value is the bare validated string - // the `status` column's `TYPE string` accepts. Guard both never drift. + async fn status_is_held_to_the_const() { + // Enforcement lives in the newtype against HOMEWORK_STATUSES, and the + // stored value is the bare validated string the `status` TEXT column + // accepts — queries match on these spellings, so they may not drift. for status in HOMEWORK_STATUSES { let parsed = HomeworkStatus::try_new(status).unwrap(); assert_eq!(parsed.as_str(), status); - assert_eq!(parsed.into_value(), Value::String(status.to_string())); } assert!(HomeworkStatus::try_new("late").is_err()); assert!(HomeworkStatus::try_new("").is_err()); diff --git a/src/domain/homework_submission.rs b/src/domain/homework_submission.rs index 15f2b58..9b6773d 100644 --- a/src/domain/homework_submission.rs +++ b/src/domain/homework_submission.rs @@ -1,12 +1,12 @@ //! One student's submission to a homework: an optional free-text note plus any -//! number of files ([`crate::domain::homework_file`]). The row id is the -//! deterministic `{homework}_{user}` composite, so a student has exactly one -//! submission per homework by construction and a re-submit is a single atomic -//! UPSERT. +//! number of files ([`crate::domain::homework_file`]). The row carries its own +//! `id` primary key and a `UNIQUE (homework, app_user)` constraint, so a +//! student has exactly one submission per homework by construction and a +//! re-submit is a single atomic UPSERT on the pair. //! -//! `submitted_at` — the first-submit stamp — is `READONLY` and survives every -//! re-submit; [`crate::db::homework_submission::upsert`] preserves it inside one -//! statement rather than through `.content()`, see there. `updated_at` moves to +//! `submitted_at` — the first-submit stamp — is write-once and survives every +//! re-submit; [`crate::db::homework_submission::upsert`] preserves it inside +//! one statement rather than overwriting the whole row. `updated_at` moves to //! now on every (re-)submit (and, later, on a file add/delete) and drives the //! computed "late" flag (`updated_at > homework.due_at`, judged in the web //! layer, never stored): `submitted_at` answers "was the first hand-in on @@ -14,45 +14,39 @@ //! live in [`crate::db::homework_submission`], the submit/withdraw workflows //! in [`crate::service::homework_submission`]. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::{HOMEWORK_SUBMISSION_TABLE, MAX_HOMEWORK_TEXT_LEN}; +use crate::constant::MAX_HOMEWORK_TEXT_LEN; use crate::domain::homework::HomeworkId; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::validate_optional; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct HomeworkSubmissionId(RecordId); +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct HomeworkSubmissionId(uuid::Uuid); impl HomeworkSubmissionId { - /// The one id a (homework, user) pair can have. A deterministic composite - /// means one submission per pair with no unique index and no - /// find-then-insert race — a re-submit UPSERTs the same row. ULID keys are - /// alphanumeric, so `_` is an unambiguous joiner. - pub fn composite(homework: &HomeworkId, user: &UserId) -> Self { - Self(RecordId::new( - HOMEWORK_SUBMISSION_TABLE, - format!("{}_{}", homework.key(), user.key()), - )) + /// A write-ordered id: submission listings read newest first. + pub fn generate() -> Self { + Self(next_uuid()) } - pub fn record(&self) -> RecordId { - self.0.clone() + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. + pub fn from_key(key: &str) -> Self { + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } /// A submission's optional free-text note: may be empty, at most /// `MAX_HOMEWORK_TEXT_LEN` characters. Files ride separately. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct SubmissionText(String); impl SubmissionText { @@ -66,7 +60,7 @@ impl SubmissionText { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct HomeworkSubmission { pub(crate) id: HomeworkSubmissionId, pub(crate) homework: HomeworkId, diff --git a/src/domain/key.rs b/src/domain/key.rs index 1d6ef6b..634f64e 100644 --- a/src/domain/key.rs +++ b/src/domain/key.rs @@ -1,18 +1,19 @@ -//! Deterministic record keys shared by the per-sitting exam tables and the +//! Deterministic wire keys shared by the per-sitting exam tables and the //! image-slot tables. +// +// With natural composite primary keys these are no longer storage ids — a +// row is keyed by its component columns. They are the **HTTP edge** form only: +// when a sitting key or a slot key crosses a path or body, it travels as one +// underscore-joined string, and these helpers are its single spelling. -/// The key for a `(scope, user, seq)` triple, where `scope` is whatever the row -/// hangs off — an exam for attempts and results, a question for answers and -/// drawings. The same triple always maps to the same key, so "one row per -/// student per sitting" holds by construction: a concurrent double write races -/// on one id instead of creating two rows, and no unique index is needed. -/// -/// The first sitting keeps the historical `{scope}_{user}` shape — rows written -/// before per-attempt history existed stay addressable, unchanged, forever — so -/// only later sittings carry their number. That bare-`seq == 1` case is -/// migration law, not a style choice: change it and every pre-history row -/// becomes unreachable. ULID keys are alphanumeric, so `_` is an unambiguous -/// joiner. +/// The wire key for a `(scope, user, seq)` triple, where `scope` is whatever +/// the row hangs off — an exam for attempts and results, a question for +/// answers and drawings. The first sitting keeps the historical +/// `{scope}_{user}` shape — rows written before per-attempt history existed +/// stay addressable, unchanged, forever — so only later sittings carry their +/// number. That bare-`seq == 1` case is migration law, not a style choice: +/// change it and every pre-history row becomes unreachable. UUID strings +/// contain only `-` and hex, so `_` is an unambiguous joiner. pub fn sitting(scope: &str, user: &str, seq: i64) -> String { if seq == 1 { format!("{scope}_{user}") @@ -21,12 +22,10 @@ pub fn sitting(scope: &str, user: &str, seq: i64) -> String { } } -/// The key for one image slot on `owner` — `{owner}_q` for the thing's own -/// illustration, `{owner}_{choice id}` for one option's picture. Uniqueness per -/// slot needs no index this way, and keying by the option's *stable id* means -/// reordering the choice list moves no picture. `_` is not in Crockford base32 -/// and a ULID is never `"q"`, so the two shapes can never collide — the rule -/// behind every image table's ids, spelled once. +/// The wire key for one image slot on `owner` — `{owner}_q` for the thing's +/// own illustration, `{owner}_{choice id}` for one option's picture. A UUID is +/// never `"q"` and never contains `_`, so the two shapes can never collide — +/// the rule behind every image table's slot keys, spelled once. pub fn slot(owner: &str, slot: Option<&str>) -> String { format!("{owner}_{}", slot.unwrap_or("q")) } @@ -35,20 +34,26 @@ pub fn slot(owner: &str, slot: Option<&str>) -> String { mod tests { use super::{sitting, slot}; + const QUESTION: &str = "0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"; + const STUDENT: &str = "0198f1a2-3b4c-7d5e-8f90-aa2b3c4d5e6f"; + #[test] fn a_slot_key_never_collides_with_the_illustration() { - assert_eq!(slot("Q", None), "Q_q"); - assert_eq!(slot("Q", Some("01J8XZ")), "Q_01J8XZ"); - // A choice id is a ULID, so it can never be the literal "q". - assert_ne!(slot("Q", Some("01J8XZ")), slot("Q", None)); + assert_eq!(slot(QUESTION, None), format!("{QUESTION}_q")); + assert_eq!(slot(QUESTION, Some(STUDENT)), format!("{QUESTION}_{STUDENT}")); + // A choice id is a UUID, so it can never be the literal "q". + assert_ne!(slot(QUESTION, Some(STUDENT)), slot(QUESTION, None)); } #[test] fn the_first_sitting_stays_bare_and_later_ones_are_numbered() { - // Byte-for-byte the shape the four exam id types wrote before this - // helper existed; a pre-history row is keyed by the bare pair. - assert_eq!(sitting("EXAM", "USER", 1), "EXAM_USER"); - assert_eq!(sitting("EXAM", "USER", 2), "EXAM_USER_2"); + // Byte-for-byte the shape the four sitting-keyed tables wrote before + // this helper existed; a pre-history row is keyed by the bare pair. + assert_eq!(sitting(QUESTION, STUDENT, 1), format!("{QUESTION}_{STUDENT}")); + assert_eq!( + sitting(QUESTION, STUDENT, 2), + format!("{QUESTION}_{STUDENT}_2") + ); assert_eq!(sitting("Q", "U", 11), "Q_U_11"); } } diff --git a/src/domain/meal_attendance.rs b/src/domain/meal_attendance.rs index 5fb267b..94c5d62 100644 --- a/src/domain/meal_attendance.rs +++ b/src/domain/meal_attendance.rs @@ -1,7 +1,7 @@ -//! Who actually ate. One row per (menu, student), keyed by a deterministic -//! composite id — the same pair always maps to the same record, so marking is a -//! single atomic UPSERT with no find-then-insert race, and re-marking flips the -//! status instead of stacking a second row. +//! Who actually ate. One row per (menu, student), keyed by the natural +//! composite primary key — the same pair always maps to the same row, so +//! marking is a single atomic upsert with no find-then-insert race, and +//! re-marking flips the status instead of stacking a second row. //! //! **Attendance is reporting only — it has zero billing effect.** Booking is //! the sole charge trigger: a student who booked and did not eat still pays, @@ -18,42 +18,63 @@ //! The queries live in [`crate::db::meal_attendance`]; the web layer reads //! through [`crate::service::meal_attendance`]. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use sqlx::Type; -use crate::constant::{MEAL_ATTENDANCE_STATUSES, MEAL_ATTENDANCE_TABLE}; +use crate::constant::MEAL_ATTENDANCE_STATUSES; use crate::domain::menu::MenuId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct MealAttendanceId(RecordId); +/// The (menu, student) pair — the table's natural composite primary key. The +/// same trick as +/// [`MealBookingId`](crate::domain::meal_booking::MealBookingId). UUID strings +/// carry only `-`, so `_` is an unambiguous joiner — and the student half is +/// last, so the menu key (a `{date}_{slot}` pair, itself underscored) reads +/// back whole. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MealAttendanceId { + menu: MenuId, + student: UserId, +} impl MealAttendanceId { - /// A deterministic id for the (menu, student) pair — same trick as - /// [`MealBookingId`](crate::domain::meal_booking::MealBookingId). ULID keys - /// are alphanumeric, so `_` is an unambiguous joiner. pub fn composite(menu: &MenuId, student: &UserId) -> Self { - Self(RecordId::new( - MEAL_ATTENDANCE_TABLE, - format!("{}_{}", menu.key(), student.key()), - )) + Self { + menu: menu.clone(), + student: *student, + } } - pub fn record(&self) -> RecordId { - self.0.clone() + /// Parse the `{menu}_{student}` wire form. A key that parses as no pair + /// reads as the nil pair, which matches no row — exactly the 404 a + /// dangling composite key produced under the old store, without turning a + /// typo into a panic. + pub fn from_key(key: &str) -> Self { + let (menu, student) = key.rsplit_once('_').unwrap_or(("", "")); + Self { + menu: MenuId::from_key(menu), + student: UserId::from_key(student), + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The `{menu}_{student}` wire form. + pub fn key(&self) -> String { + format!("{}_{}", self.menu.key(), self.student.key()) + } + + pub fn menu(&self) -> &MenuId { + &self.menu + } + + pub fn student(&self) -> UserId { + self.student } } /// `served` or `missed`, and nothing else — see the module header. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, Type)] +#[sqlx(transparent)] pub struct MealAttendanceStatus(String); impl MealAttendanceStatus { @@ -73,9 +94,8 @@ impl MealAttendanceStatus { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct MealAttendance { - pub(crate) id: MealAttendanceId, pub(crate) menu: MenuId, pub(crate) student: UserId, pub(crate) status: MealAttendanceStatus, @@ -84,10 +104,6 @@ pub struct MealAttendance { } impl MealAttendance { - pub fn get_id(&self) -> &MealAttendanceId { - &self.id - } - pub fn get_menu(&self) -> &MenuId { &self.menu } diff --git a/src/domain/meal_booking.rs b/src/domain/meal_booking.rs index cf4d7ee..c329eb5 100644 --- a/src/domain/meal_booking.rs +++ b/src/domain/meal_booking.rs @@ -1,6 +1,7 @@ //! A student's seat on a published [`Menu`]. One row per (menu, student), -//! keyed by a deterministic composite id — the same pair always maps to the -//! same record, so booking is a single atomic UPSERT with no find-then-insert +//! +//! keyed by the natural composite primary key — the same pair always maps to +//! the same row, so booking is a single atomic upsert with no find-then-insert //! race and one-row-per-pair by construction. //! //! This module is the pure row shape: the id and status, the booking row, and @@ -16,11 +17,11 @@ //! to `cancelled` with a `cancelled_at` stamp, so the freed seat is still //! auditable against the money it moved. Only `booked` rows count against //! the menu's capacity, which is what makes the seat genuinely free again — -//! and re-booking is the same UPSERT flipping it back. +//! and re-booking is the same upsert flipping it back. //! - **Capacity is the menu's `seats_booked` counter**, claimed by a -//! conditional single-record write ([`cap`](crate::db::cap)). Counting the rows instead is -//! write-skew — SurrealDB does not conflict-check a cross-record count -//! against a concurrent insert — and a process-wide lock around that count +//! conditional single-row write ([`cap`](crate::db::cap)). Counting the rows instead is +//! write-skew — a cross-row count checked outside the insert can always be +//! overtaken by a racing insert — and a process-wide lock around that count //! is released around the very round trip the racing insert lands in. //! Cancelling gives the seat back in the *same transaction* as the flip. //! - **The price is claimed, not just read.** The seat is taken at the menu @@ -36,9 +37,8 @@ //! trails the seat by one write can be overtaken by the next attempt and //! stranded forever: every ledger id carries the attempt it belongs to. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use sqlx::Type; -use crate::constant::MEAL_BOOKING_TABLE; use crate::domain::meal_ledger::LedgerAmount; use crate::domain::menu::{MenuDate, MenuId, MenuSlot}; use crate::domain::settings::{MealSlotDef, Settings}; @@ -46,56 +46,61 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct MealBookingId(RecordId); +/// The (menu, student) pair — the table's natural composite primary key. +/// UUID strings carry only `-`, so `_` is an unambiguous joiner — and the +/// student half is last, so the menu key (a `{date}_{slot}` pair, itself +/// underscored) reads back whole. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MealBookingId { + menu: MenuId, + student: UserId, +} impl MealBookingId { - /// A deterministic id for the (menu, student) pair — same trick as - /// `EnrollmentId`. ULID keys are alphanumeric, so `_` is an unambiguous - /// joiner. pub fn composite(menu: &MenuId, student: &UserId) -> Self { - Self(RecordId::new( - MEAL_BOOKING_TABLE, - format!("{}_{}", menu.key(), student.key()), - )) + Self { + menu: menu.clone(), + student: *student, + } } + /// Parse the `{menu}_{student}` wire form. A key that parses as no pair + /// reads as the nil pair, which matches no row — exactly the 404 a + /// dangling composite key produced under the old store, without turning a + /// typo into a panic. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(MEAL_BOOKING_TABLE, key)) + let (menu, student) = key.rsplit_once('_').unwrap_or(("", "")); + Self { + menu: MenuId::from_key(menu), + student: UserId::from_key(student), + } } - /// Who the seat is for, read straight back off the key: [`Self::composite`] - /// joins with `_` and a ULID user key carries none, so the last segment is - /// always the student (a slot name may well hold one, and the menu half is - /// in front). `None` for a key no `composite` ever minted. + /// The `{menu}_{student}` wire form. + pub fn key(&self) -> String { + format!("{}_{}", self.menu.key(), self.student.key()) + } + + /// Who the seat is for, read straight off the pair. /// /// This is what lets a cancel decide *whose* seat it is asked to free /// before reading the row — the id is fully derivable from a menu and a /// user id, both readable by a teacher, so a 403-or-404 answered off the /// row is an existence oracle for the manager-only booking list. - pub fn student(&self) -> Option { - self.key() - .rsplit_once('_') - .map(|(_, student)| UserId::from_key(student)) + pub fn student(&self) -> UserId { + self.student } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn menu(&self) -> &MenuId { + &self.menu } } -/// Where a booking stands. `untagged` + `rename_all` store it as the bare -/// lowercase string the `status` column types as, exactly like +/// Where a booking stands. Stored as the bare lowercase TEXT value the +/// `status` column carries, exactly like /// [`AppointmentStatus`](crate::domain::appointment::AppointmentStatus). -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] -#[surreal(untagged, rename_all = "lowercase")] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] pub enum MealBookingStatus { Booked, Cancelled, @@ -111,9 +116,8 @@ impl MealBookingStatus { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct MealBooking { - pub(crate) id: MealBookingId, pub(crate) menu: MenuId, pub(crate) student: UserId, pub(crate) booked_by: UserId, @@ -123,7 +127,7 @@ pub struct MealBooking { /// idempotence key, so a re-book bills afresh while a repeat `POST` of a /// seat already held bills nothing. pub(crate) attempt: i64, - /// What the menu cost when the current attempt took the seat; `None` means + /// What the menu cost when the current attempt took the seat; `NULL` means /// it was free *then*. Recorded rather than inferred: without it, "the menu /// was free" is indistinguishable from "not billed yet", and a dish added /// afterwards bills a seat that was free when taken. @@ -133,10 +137,6 @@ pub struct MealBooking { } impl MealBooking { - pub fn get_id(&self) -> &MealBookingId { - &self.id - } - pub fn get_menu(&self) -> &MenuId { &self.menu } @@ -168,6 +168,12 @@ impl MealBooking { pub fn get_created_at(&self) -> Timestamp { self.created_at } + + /// The id of the seat this row holds — the pair that is the row's primary + /// key. + pub fn id(&self) -> MealBookingId { + MealBookingId::composite(&self.menu, &self.student) + } } /// 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> { /// (the slot list is read live). /// /// A date no serving instant can be computed from **fails closed**. A menu on -/// an impossible day (a 31st of February — refused by [`MenuDate`] now, but -/// rows written before that rule are still on the volume) otherwise skipped the -/// deadline entirely, silently and forever, however large the school set it: -/// the one menu with no cutoff at all would be the one nobody meant to publish. -/// Refusing is the only answer that keeps "the deadline binds every menu" true; -/// the menu has to be republished on a real day to become bookable again. +/// an impossible day (a 31st of February — refused by [`MenuDate`]) otherwise +/// skipped the deadline entirely, silently and forever, however large the +/// school set it: the one menu with no cutoff at all would be the one nobody +/// meant to publish. Refusing is the only answer that keeps "the deadline +/// binds every menu" true; the menu has to be republished on a real day to +/// become bookable again. pub(crate) fn check_cutoff( date: &MenuDate, slot: &MenuSlot, cutoff: &MealCutoff, ) -> Result<(), AppError> { // A school with no cutoff configured closes nothing anyway, so an - // impossible date is not refused there either — that would take the canteen - // offline for a deadline the school never set. + // impossible date is not refused there either — that would take the + // canteen offline for a deadline the school never set. let Some(minutes) = cutoff.minutes else { return Ok(()); }; @@ -312,22 +318,8 @@ pub(crate) fn check_cutoff( #[cfg(test)] mod tests { - use surrealdb::types::Value; - use super::*; - /// The `status` column is `TYPE string`: an object-wrapped enum would be - /// rejected on write, and the `status = 'booked'` capacity count would - /// silently match nothing. - #[test] - fn status_stores_as_a_bare_string() { - for status in [MealBookingStatus::Booked, MealBookingStatus::Cancelled] { - let value = status.into_value(); - assert_eq!(value, Value::String(status.as_str().to_string())); - assert_eq!(MealBookingStatus::from_value(value).unwrap(), status); - } - } - fn cutoff(minutes: Option, serving_minute: Option) -> MealCutoff { MealCutoff { minutes, @@ -350,23 +342,6 @@ mod tests { assert!(check_cutoff(&past, &lunch(), &cutoff(Some(60), Some(720))).is_err()); } - /// A menu stored on a day that does not exist has no serving instant, so no - /// deadline can be counted back from it — and it must therefore refuse, not - /// pass. `MenuDate::try_new` rejects such a date now; this is a row written - /// before that rule, read back off the store exactly as the domain reads it - /// (the column is `TYPE string`), which is the only way one can still turn - /// up. Passing is what let it be booked and cancelled with no cutoff ever. - #[test] - fn an_impossible_day_has_no_open_deadline() { - let impossible = MenuDate::from_value(Value::String("2026-02-29".into())).unwrap(); - assert!(MenuDate::try_new(impossible.as_str()).is_err()); - assert!(check_cutoff(&impossible, &lunch(), &cutoff(Some(60), Some(720))).is_err()); - assert!(check_cutoff(&impossible, &lunch(), &cutoff(Some(60), None)).is_err()); - // A school that set no cutoff closes nothing anyway, impossible day or - // not: refusing there would take the canteen offline for no deadline. - assert!(check_cutoff(&impossible, &lunch(), &cutoff(None, Some(720))).is_ok()); - } - /// A slot with no serving hour has no instant to count a deadline back /// from, so nothing on it ever closes. It used to count from midnight UTC /// of the menu's day, which shut every same-day menu the moment a school @@ -411,11 +386,6 @@ mod tests { ) .is_ok() ); - // A day no calendar can place is left to the cutoff, which fails it - // closed when one is configured; guessing "past" here would shut the - // canteen for a school that set no deadline. - let impossible = MenuDate::from_value(Value::String("2026-02-29".into())).unwrap(); - assert!(check_day_not_past(&impossible).is_ok()); } /// The instant the deadline counts back from: midnight UTC of the day plus @@ -439,4 +409,49 @@ mod tests { ); assert_eq!(MealCutoff::default().serving_minute(&lunch()), None); } + + #[test] + fn status_as_str_is_the_storage_form() { + assert_eq!(MealBookingStatus::Booked.as_str(), "booked"); + assert_eq!(MealBookingStatus::Cancelled.as_str(), "cancelled"); + } + + /// The `status` column is `TEXT` with a CHECK on these exact words; the + /// sqlx encoding must never drift from `as_str`, or the `status = + /// 'booked'` capacity count silently matches nothing. + #[test] + fn sqlx_encodes_the_storage_form() { + let mut buf = sqlx::postgres::PgArgumentBuffer::default(); + for status in [MealBookingStatus::Booked, MealBookingStatus::Cancelled] { + buf.clear(); + sqlx::Encode::::encode_by_ref(&status, &mut buf); + assert_eq!(std::str::from_utf8(&buf).unwrap(), status.as_str()); + } + } + + /// The composite key round-trips: the menu half (itself underscored) reads + /// back whole, and a key that parses as no pair reads as the nil pair that + /// matches no row. + #[test] + fn the_booking_key_round_trips() { + let menu = MenuId::for_slot( + &MenuDate::try_new("2026-09-14").unwrap(), + &MenuSlot::try_new( + "öğle yemeği", + &[MealSlotDef::try_new("öğle yemeği", None).unwrap()], + ) + .unwrap(), + ); + let student = UserId::from_key("018f1a00-0000-7000-8000-000000000001"); + let id = MealBookingId::composite(&menu, &student); + assert_eq!(MealBookingId::from_key(&id.key()), id); + assert_eq!( + MealBookingId::from_key("no-pair-here").student(), + UserId::from_key("") + ); + assert_eq!( + MealBookingId::from_key("no-pair-here").menu.key(), + MenuId::from_key("").key() + ); + } } diff --git a/src/domain/meal_ledger.rs b/src/domain/meal_ledger.rs index de4ecc9..cdf2d0a 100644 --- a/src/domain/meal_ledger.rs +++ b/src/domain/meal_ledger.rs @@ -1,11 +1,11 @@ //! The food program's money: an **append-only** ledger of what a student was //! charged and what they paid. //! -//! Nothing here ever `UPDATE`s or `DELETE`s a row, and no such path exists — -//! every field is `READONLY` in the schema as well. A ledger line that can be -//! edited or dropped silently rewrites a student's financial history with no -//! trace of the rewrite; a mistake is corrected by appending the opposing -//! line, which leaves both the mistake and the correction visible. +//! Nothing here ever `UPDATE`s or `DELETE`s a row, and no such path exists. A +//! ledger line that can be edited or dropped silently rewrites a student's +//! financial history with no trace of the rewrite; a mistake is corrected by +//! appending the opposing line, which leaves both the mistake and the +//! correction visible. //! //! **The balance is never stored.** It is always the fold //! @@ -33,7 +33,7 @@ //! than its flip could be overtaken by that re-book and then never be //! writable at all. //! - **Every booking line is keyed by `(booking, attempt)`.** Both the charge -//! and its reversal derive their record id from the seat and the attempt +//! and its reversal derive their row id from the seat and the attempt //! number, so replaying either writes nothing at all. Money must never //! depend on a "has this been billed yet?" scan: two concurrent `POST`s of //! one seat can both read "no charge yet" and both append, which is how a @@ -42,7 +42,7 @@ //! client-chosen `request_key`, which lands in the line's id //! ([`MealLedgerId::for_request`]) and makes the call retry-safe by the same //! identity rule: a retry after a timeout resolves the line it already wrote. -//! Without one, a fresh ulid is minted and a resent request is a second +//! Without one, a fresh id is minted and a resent request is a second //! credit — which nothing here can edit or delete afterwards. //! - **A no-show still pays.** Meal attendance has zero billing effect — //! nothing in this file reads or writes it. Do not add a no-show penalty @@ -50,56 +50,51 @@ //! //! Money is `i64` minor units (kuruş) end to end. No float, no decimal, ever. //! +//! The ledger row ids are **derived TEXT keys**, not minted uuids — they are +//! the identity the store's uniqueness check enforces (`id TEXT PRIMARY +//! KEY`): a duplicate insert of the same key is the "already billed" answer. +//! Only the unkeyed-credit fallback mints a fresh (uuid-string) key. +//! //! The writes and the SUM/balance reads live in [`crate::db::meal_ledger`]; //! the charge/reversal and credit workflows in //! [`crate::service::meal_ledger`]. -use std::sync::LazyLock; - -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Generator; +use serde::{Deserialize, Serialize}; +use sqlx::Type; -use crate::constant::{ - MAX_LEDGER_AMOUNT_MINOR, MAX_LEDGER_METHOD_LEN, MAX_LEDGER_NOTE_LEN, MEAL_LEDGER_TABLE, -}; +use crate::constant::{MAX_LEDGER_AMOUNT_MINOR, MAX_LEDGER_METHOD_LEN, MAX_LEDGER_NOTE_LEN}; // The client-chosen idempotence key both ledgers take — one grammar, one // validator, one type, rather than a second newtype that could drift from it. +use crate::domain::monotonic_id::next_uuid; use crate::domain::payment_ledger::PaymentRequestKey; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::validate_optional; -/// Mints ledger ids in write order — `Ulid::generate()`'s random low bits sort -/// arbitrarily within one millisecond, which would scramble the `id` tie-break -/// of the newest-first statement below. -static IDS: LazyLock> = - LazyLock::new(|| std::sync::Mutex::new(Generator::new())); - -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct MealLedgerId(RecordId); +/// The ledger line's id — a derived TEXT key (`id TEXT PRIMARY KEY`): +/// `{booking-key}_c{attempt}` / `{booking-key}_r{attempt}` for the booking +/// lines, `{student-key}_k_{request_key}` for a keyed credit, or a fresh +/// uuid-string key for an unkeyed one. +#[derive(Debug, Clone, PartialEq, Eq, Type)] +#[sqlx(transparent)] +pub struct MealLedgerId(String); impl MealLedgerId { + /// A fresh key in write order — the process-wide uuid v7 generator's + /// string form, so the `id` tie-break of the newest-first statement below + /// still sorts in mint order. pub fn generate() -> Self { - let mut ids = IDS.lock().expect("meal ledger id generator poisoned"); - // The only error is exhausting the random bits within one millisecond - // (2^80 ids deep); it clears itself as the clock ticks, so retry. - let ulid = loop { - if let Ok(ulid) = ids.generate() { - break ulid; - } - }; - Self(RecordId::new(MEAL_LEDGER_TABLE, ulid.to_string())) + Self(next_uuid().to_string()) } /// The one line a booking attempt may ever write of this `kind` — a - /// deterministic id, exactly like [`MealBookingId::composite`](crate::domain::meal_booking::MealBookingId::composite). - /// Two racing - /// `POST`s of one seat derive the *same* id and so cannot become two + /// deterministic key, exactly like the booking pair itself. Two racing + /// `POST`s of one seat derive the *same* key and so cannot become two /// charges: idempotence rests on identity, never on a scan that a /// concurrent writer can slip past. The `attempt` counter is what keeps a /// re-book after a cancel a genuinely fresh charge. Booking keys are - /// `_`, so the `c`/`r` marker keeps the two kinds apart. + /// `_`, so the `c`/`r` marker keeps the two kinds apart. pub fn for_attempt( booking: &crate::domain::meal_booking::MealBookingId, attempt: i64, @@ -111,53 +106,34 @@ impl MealLedgerId { // A credit is money arriving out of the blue, tied to no booking. MealLedgerKind::Credit => 'k', }; - Self(RecordId::new( - MEAL_LEDGER_TABLE, - format!("{}_{marker}{attempt}", booking.key()), - )) + Self(format!("{}_{}{attempt}", booking.key(), marker)) } - /// The one credit a `(student, request_key)` pair may ever have. Same trick - /// as [`PaymentLedgerId::for_request`](crate::domain::payment_ledger::PaymentLedgerId::for_request), + /// The one credit a `(student, request_key)` pair may ever have. Same + /// identity trick as + /// [`PaymentLedgerId::for_request`](crate::domain::payment_ledger::PaymentLedgerId::for_request), /// scoped by the student because a credit points at no line of its own: one /// office's "receipt-114" cannot land on another student's account, and a /// key replayed for the wrong student cannot resolve to this line at all. /// - /// The grammar parses uniquely because `_` joins the parts. A booking line - /// is `___c`, whose first part carries the `-` of a - /// `YYYY-MM-DD` day, and an unkeyed line is a bare ULID; a credit's first - /// part is a student ULID (`[0-9A-Z]`) and a `request_key` is - /// [`crate::validate::validate_request_key`]'s `[A-Za-z0-9-]`, which cannot - /// spell a separator plus a marker. No key can therefore derive an id some - /// other line owns — a collision would hand money to the wrong row. + /// The grammar parses uniquely because `_` joins the parts: a student key + /// is a UUID (hex and `-` only) and a `request_key` is + /// [`crate::validate::validate_request_key`]'s `[A-Za-z0-9-]` — neither can + /// spell the `_k_` separator. No key can therefore derive an id some other + /// line owns — a collision would hand money to the wrong row. pub fn for_request(student: &UserId, key: &PaymentRequestKey) -> Self { - Self(RecordId::new( - MEAL_LEDGER_TABLE, - format!("{}_k_{}", student.key(), key.as_str()), - )) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(format!("{}_k_{}", student.key(), key.as_str())) } pub fn key(&self) -> &str { - key_of(&self.0) - } -} - -/// The bare key of a record id — how every id leaves this API. -fn key_of(record: &RecordId) -> &str { - match &record.key { - RecordIdKey::String(key) => key, - _ => "", + &self.0 } } -/// What a line means. `untagged` + `rename_all` store it as the bare lowercase -/// string the `kind` column types as, in lockstep with `MEAL_LEDGER_KINDS`. -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] -#[surreal(untagged, rename_all = "lowercase")] +/// What a line means. Stored as the bare lowercase TEXT value the `kind` +/// column carries, in lockstep with `MEAL_LEDGER_KINDS`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] pub enum MealLedgerKind { Charge, Credit, @@ -186,7 +162,11 @@ impl MealLedgerKind { /// One line's amount, always positive — the sign is the [`MealLedgerKind`]'s /// business. Capped so a slipped keystroke cannot book a fortune. -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +/// +/// `Serialize`/`Deserialize` ride along because the fee plan's installments +/// (a `Json>` column) embed this same money type. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)] +#[sqlx(transparent)] pub struct LedgerAmount(i64); impl LedgerAmount { @@ -207,7 +187,8 @@ impl LedgerAmount { /// How the money arrived ("cash", "havale", …). Free text: the backend never /// speaks to a payment gateway and stores no card data, ever. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, Type)] +#[sqlx(transparent)] pub struct LedgerMethod(String); impl LedgerMethod { @@ -224,7 +205,8 @@ impl LedgerMethod { /// The bookkeeper's own words about a line — a receipt number, whose envelope /// it came in. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, Type)] +#[sqlx(transparent)] pub struct LedgerNote(String); impl LedgerNote { @@ -239,15 +221,16 @@ impl LedgerNote { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct MealLedger { pub(crate) id: MealLedgerId, pub(crate) student: UserId, pub(crate) kind: MealLedgerKind, pub(crate) amount_minor: LedgerAmount, - /// What caused the line: a charge points at its `meal_booking`, a reversal - /// at the `meal_ledger` charge it undoes. Untyped, hence a bare `RecordId`. - pub(crate) source: Option, + /// What caused the line: a charge points at its `meal_booking` row's + /// `{menu}_{student}` key, a reversal at the `meal_ledger` charge it + /// undoes. Polymorphic by kind, hence a bare TEXT key — no foreign key. + pub(crate) source: Option, pub(crate) method: Option, pub(crate) note: Option, pub(crate) recorded_by: UserId, @@ -273,7 +256,7 @@ impl MealLedger { /// The cause's bare key; which table it lives in follows from the kind. pub fn get_source_key(&self) -> Option<&str> { - self.source.as_ref().map(key_of) + self.source.as_deref() } pub fn get_method(&self) -> Option<&LedgerMethod> { @@ -307,14 +290,14 @@ impl MealLedger { let amount = booking.get_price_minor()?; Some(MealLedger { id: MealLedgerId::for_attempt( - booking.get_id(), + &booking.id(), booking.get_attempt(), MealLedgerKind::Charge, ), student: booking.get_student().clone(), kind: MealLedgerKind::Charge, amount_minor: amount, - source: Some(booking.get_id().record()), + source: Some(booking.id().key()), method: None, note: None, recorded_by: recorded_by.clone(), @@ -323,34 +306,34 @@ impl MealLedger { } /// The refund `booking`'s current attempt owes, as `(the charge it undoes, - /// the reversal line)` — the two ids + /// the reversal line)` — the two keys /// [`release_seat`](crate::db::meal_booking::release_seat) needs to /// append the money back inside the transaction that frees the seat. /// `None` when the seat was never billed (a free menu), which owes no line. /// - /// Only the ids and the row are built here: whether the charge exists is a - /// read, and the caller that writes in one transaction has to make it there - /// rather than a round trip earlier. + /// Only the keys and the row are built here: whether the charge exists is + /// a read, and the caller that writes in one transaction has to make it + /// there rather than a round trip earlier. pub(crate) fn reversal_for( booking: &crate::domain::meal_booking::MealBooking, recorded_by: &UserId, ) -> Option<(MealLedgerId, MealLedger)> { let amount = booking.get_price_minor()?; let charge = MealLedgerId::for_attempt( - booking.get_id(), + &booking.id(), booking.get_attempt(), MealLedgerKind::Charge, ); let line = MealLedger { id: MealLedgerId::for_attempt( - booking.get_id(), + &booking.id(), booking.get_attempt(), MealLedgerKind::Reversal, ), student: booking.get_student().clone(), kind: MealLedgerKind::Reversal, amount_minor: amount, - source: Some(charge.record()), + source: Some(charge.key()), method: None, note: None, recorded_by: recorded_by.clone(), @@ -362,23 +345,23 @@ impl MealLedger { #[cfg(test)] mod tests { - use surrealdb::types::Value; - use super::*; - /// The `kind` column is `TYPE string`: an object-wrapped enum would be - /// rejected on write, and the `kind = 'charge'` lookup would silently - /// match nothing — which would double-charge every re-booking. + /// The `kind` column is `TEXT` with a CHECK on these exact words; the + /// sqlx encoding must never drift from `as_str`, or the `kind = 'charge'` + /// lookup would silently match nothing — which would double-charge every + /// re-booking. #[test] - fn kind_stores_as_a_bare_string() { + fn sqlx_encodes_the_storage_form() { + let mut buf = sqlx::postgres::PgArgumentBuffer::default(); for kind in [ MealLedgerKind::Charge, MealLedgerKind::Credit, MealLedgerKind::Reversal, ] { - let value = kind.into_value(); - assert_eq!(value, Value::String(kind.as_str().to_string())); - assert_eq!(MealLedgerKind::from_value(value).unwrap(), kind); + buf.clear(); + sqlx::Encode::::encode_by_ref(&kind, &mut buf); + assert_eq!(std::str::from_utf8(&buf).unwrap(), kind.as_str()); } } @@ -408,4 +391,18 @@ mod tests { assert!(LedgerAmount::try_new(MAX_LEDGER_AMOUNT_MINOR + 1).is_err()); assert_eq!(LedgerAmount::try_new(1).unwrap().as_minor(), 1); } + + /// A keyed credit's id is scoped by the student and stable across retries; + /// an unkeyed line mints a fresh uuid-string key. + #[test] + fn credit_keys_derive_deterministically() { + let student = UserId::from_key("018f1a00-0000-7000-8000-000000000001"); + let key = PaymentRequestKey::try_new("receipt-114").unwrap(); + let first = MealLedgerId::for_request(&student, &key); + assert_eq!(MealLedgerId::for_request(&student, &key), first); + assert_eq!(first.key(), format!("{}_k_receipt-114", student.key())); + // A key replayed for another student cannot resolve to the same line. + let other = UserId::from_key("018f1a00-0000-7000-8000-000000000002"); + assert_ne!(MealLedgerId::for_request(&other, &key), first); + } } diff --git a/src/domain/menu.rs b/src/domain/menu.rs index 48419ab..1978f91 100644 --- a/src/domain/menu.rs +++ b/src/domain/menu.rs @@ -13,9 +13,9 @@ //! The queries live in [`crate::db::menu`]; the kitchen workflows (and the //! dish-cap lock) in [`crate::service::menu`]. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use sqlx::Type; -use crate::constant::{MAX_MENU_CAPACITY, MENU_TABLE, SLOT_REF_TABLE}; +use crate::constant::MAX_MENU_CAPACITY; use crate::domain::settings::MealSlotDef; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -26,48 +26,45 @@ use crate::error::ValidationError; /// [`crate::db::cap`]). The mirror of /// [`kind_ref`](crate::domain::exam_result::kind_ref) for exam kinds: the slot /// is snapshotted text on the menu, so this row is the only place the two -/// tables' relationship is a single record concurrent writes can contend on. -pub(crate) fn slot_ref(slot: &str) -> RecordId { - RecordId::new(SLOT_REF_TABLE, slot) +/// tables' relationship is a single row concurrent writes can contend on. +/// The `slot_ref` row is keyed by the slot's name. +pub(crate) fn slot_ref(slot: &str) -> String { + slot.to_string() } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct MenuId(RecordId); +/// Typed menu row id — the `{date}_{slot}` pair joined with `_`. Not a minted +/// id: the pair *is* the identity, the same trick the enrollment tables use. +/// `date` is fixed-width `YYYY-MM-DD`, and slot names never carry `_`-breaking +/// ambiguity, so two requests publishing the same meal race on one row and the +/// loser is told "already exists" by the store. +#[derive(Debug, Clone, PartialEq, Eq, Type)] +#[sqlx(transparent)] +pub struct MenuId(String); impl MenuId { /// The one id a menu for this day and slot can have. Deterministic on - /// purpose (the `EnrollmentId` trick): two requests publishing the same - /// meal race on a single record instead of writing two rows, so the loser - /// is told "already exists" by the store and answered the same 409 the - /// pre-check gives. `date` is fixed-width `YYYY-MM-DD`, so the `_` joiner - /// cannot be read two ways however the school spells its slots. + /// purpose (the enrollment trick): two requests publishing the same meal + /// race on a single row instead of writing two, so the loser is told + /// "already exists" by the store and answered the same 409 the pre-check + /// gives. pub fn for_slot(date: &MenuDate, slot: &MenuSlot) -> Self { - Self(RecordId::new( - MENU_TABLE, - format!("{}_{}", date.as_str(), slot.as_str()), - )) + Self(format!("{}_{}", date.as_str(), slot.as_str())) } pub fn from_key(key: &str) -> Self { - Self(RecordId::new(MENU_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(key.to_string()) } pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + &self.0 } } /// A calendar day as `YYYY-MM-DD`. Zero-padded and fixed-width on purpose: /// that makes the text sort chronologically, so the `?from=&to=` range filter /// and the newest-first ordering are plain string comparisons. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Type)] +#[sqlx(transparent)] pub struct MenuDate(String); impl MenuDate { @@ -87,7 +84,7 @@ impl MenuDate { // rather than by two independent checks that can drift apart. They did: // a hand-rolled `"+1".parse::()` accepted a signed component (std // does), `from_ymd_opt` was then handed the normalized number and said - // yes, and `2026-+1-01` became a *second* record id for the 1st of + // yes, and `2026-+1-01` became a *second* row id for the 1st of // January — its own capacity and seat counter, invisible to every // `date >= $from` range read ('+' sorts below '0'), and unbookable // besides, since chrono refuses to parse it back. @@ -116,8 +113,7 @@ impl MenuDate { /// This is the whole day's deadline, not the meal's: a menu for *today* is /// still publishable and still bookable at any hour, whatever the slot's /// serving time says — that is [`MealCutoff`](crate::domain::meal_booking::MealCutoff)'s - /// separate business. `None` for a day that cannot be parsed (a row written - /// before `try_new` rejected impossible days). + /// separate business. `None` for a day that cannot be parsed. pub fn day_end(&self) -> Option { let day = chrono::NaiveDate::parse_from_str(&self.0, "%Y-%m-%d").ok()?; Some(Timestamp::from_millis( @@ -132,7 +128,8 @@ impl MenuDate { /// The meal slot a menu was published for, snapshotted as text. Validated /// against the school's *current* list at write time — that list is the only /// place slot names are defined, and this is the sole funnel into the column. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, Type)] +#[sqlx(transparent)] pub struct MenuSlot(String); impl MenuSlot { @@ -144,7 +141,7 @@ impl MenuSlot { reason: "not one of the school's meal slots (see GET /settings)", }); } - // The slot goes verbatim into the menu's record id ([`MenuId::for_slot`]), + // The slot goes verbatim into the menu's id ([`MenuId::for_slot`]), // and that id is a URL path segment: a slot named `a/b` publishes a menu // at `/meals/menus/2026-09-14_a/b`, which no route can ever address // again — the menu could not be read, edited or deleted. @@ -182,15 +179,14 @@ pub fn validate_capacity(value: Option) -> Result<(), ValidationError> { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Menu { pub(crate) id: MenuId, pub(crate) date: MenuDate, pub(crate) slot: MenuSlot, pub(crate) capacity: Option, - /// The menu's revision (see [`MENU_VERSION_FIELD`](crate::constant::MENU_VERSION_FIELD)). - /// Absent on rows written before the column existed, which reads as - /// revision zero — the same thing `(version ?? 0)` says in the claim's + /// The menu's revision. `NULL` (never written by the current code) reads + /// as revision zero — the same thing `(version ?? 0)` says in the claim's /// `WHERE`. The seat counter is deliberately *not* here: it is the /// database's to own, and a whole-row save must never carry a stale copy /// of it. @@ -217,8 +213,7 @@ impl Menu { } /// The revision a booking must still find on the row when it claims its - /// seat. Absent (a pre-column row) is revision zero, exactly as the `WHERE` - /// reads it. + /// seat. Absent is revision zero, exactly as the `WHERE` reads it. pub fn get_version(&self) -> i64 { self.version.unwrap_or(0) } @@ -235,7 +230,6 @@ impl Menu { #[cfg(test)] mod tests { use super::*; - use surrealdb::types::Value; #[test] fn date_accepts_only_padded_calendar_days() { @@ -268,7 +262,7 @@ mod tests { /// A signed component is not a calendar day, however willingly /// `"+1".parse::()` reads one out of it. Accepting one minted a - /// *second* record id for the same day — its own capacity and seat counter + /// *second* row id for the same day — its own capacity and seat counter /// — that sorted below every `?from=` bound (`+` is 0x2B, `0` is 0x30) and /// that the serving-instant parser could not read at all. #[test] @@ -314,9 +308,6 @@ mod tests { fn a_day_ends_at_the_next_midnight_utc() { let day = MenuDate::try_new("1970-01-01").unwrap(); assert_eq!(day.day_end().unwrap().as_millis(), 86_400_000); - // A row written before `try_new` refused impossible days has no end. - let impossible = MenuDate::from_value(Value::String("2026-02-29".into())).unwrap(); - assert!(impossible.day_end().is_none()); } #[test] @@ -327,29 +318,19 @@ mod tests { assert!(MenuSlot::try_new("lunch", &[]).is_err()); } - /// The slot becomes the menu's record id, and the id becomes a URL path + /// The slot becomes the menu's id, and the id becomes a URL path /// segment: a name carrying a separator publishes a menu at an address no /// route can match again. `MealSlotDef::try_new` refuses the name too, so - /// no school can define such a slot any more — this gate is what a settings - /// row written *before* that rule still runs into. Ordinary names — spaces - /// and Turkish letters included — are untouched; they percent-encode into - /// one segment as they always have. + /// no school can define such a slot any more — this gate is what a + /// settings row written *before* that rule still runs into. Ordinary names — + /// spaces and Turkish letters included — are untouched; they percent-encode + /// into one segment as they always have. #[test] fn a_slot_name_that_would_break_the_menu_url_is_refused() { // The only shape that can still carry such a name: a stored slot, - // decoded rather than constructed. - use surrealdb::types::Value; - let stale = |name: &str| { - let Value::Object(mut object) = - MealSlotDef::try_new("lunch", None).unwrap().into_value() - else { - panic!("a slot must encode as an object"); - }; - object.insert("name".to_string(), Value::String(name.into())); - vec![MealSlotDef::from_value(Value::Object(object)).unwrap()] - }; + // which `try_kept` admits exactly because it is already on the row. let named = |name: &str| { - MenuSlot::try_new(name, &stale(name)) + MenuSlot::try_new(name, &[MealSlotDef::try_kept(name, None).unwrap()]) .map(|slot| MenuId::for_slot(&MenuDate::try_new("2026-09-14").unwrap(), &slot)) }; for broken in ["a/b", "a\\b", "a?b", "a#b", "a%b"] { diff --git a/src/domain/menu_dish.rs b/src/domain/menu_dish.rs index 3694cdb..f4993d3 100644 --- a/src/domain/menu_dish.rs +++ b/src/domain/menu_dish.rs @@ -8,58 +8,48 @@ //! The queries live in [`crate::db::menu_dish`]; the dish-cap gate and the //! write lock in [`crate::service::menu`]. -use std::sync::LazyLock; - -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Generator; +use sqlx::Type; +use uuid::Uuid; use crate::constant::{ MAX_DISH_DESCRIPTION_LEN, MAX_DISH_NAME_LEN, MAX_DISH_PRICE_MINOR, MAX_DISH_TAGS, - MENU_DISH_TABLE, }; use crate::domain::menu::MenuId; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::error::ValidationError; use crate::validate::{validate_optional, validate_required}; -/// Mints dish ids in write order — see [`MenuId::generate`]; the listings below -/// order by `id` within a menu, which random low bits would scramble. -static IDS: LazyLock> = - LazyLock::new(|| std::sync::Mutex::new(Generator::new())); - -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct MenuDishId(RecordId); +/// Typed menu-dish row id. A UUIDv7 minted by the process-wide monotonic +/// generator, so `id` order is mint order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] +#[sqlx(transparent)] +pub struct MenuDishId(Uuid); impl MenuDishId { + /// Minted from the process-wide monotonic generator, not a random v4 — + /// the listings order by `id` within a menu, which random low bits would + /// scramble. pub fn generate() -> Self { - let mut ids = IDS.lock().expect("menu dish id generator poisoned"); - // The only error is exhausting the random bits within one millisecond - // (2^80 ids deep); it clears itself as the clock ticks, so retry. - let ulid = loop { - if let Ok(ulid) = ids.generate() { - break ulid; - } - }; - Self(RecordId::new(MENU_DISH_TABLE, ulid.to_string())) + Self(next_uuid()) } + /// Parse a wire key. A key that parses as no UUID — a malformed path + /// segment — reads as the nil id, which matches no row: exactly the 404 a + /// dangling record key produced under the old store, without turning a + /// typo into a panic. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(MENU_DISH_TABLE, key)) + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The hyphenated wire form. + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, Type)] +#[sqlx(transparent)] pub struct DishName(String); impl DishName { @@ -73,12 +63,13 @@ impl DishName { } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, Type)] +#[sqlx(transparent)] pub struct DishDescription(String); impl DishDescription { /// Blank (or whitespace-only) means "no description" — `None`, not an - /// empty string, so the column is absent rather than falsely present. + /// empty string, so the column is NULL rather than falsely present. pub fn try_new(value: &str) -> Result, ValidationError> { validate_optional("description", value, MAX_DISH_DESCRIPTION_LEN)?; let value = value.trim(); @@ -92,7 +83,8 @@ impl DishDescription { /// What one serving costs, in **minor units** (kuruş). Never negative — a /// giveaway dish is `0`, and money that flows the other way is a ledger line. -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] +#[sqlx(transparent)] pub struct DishPrice(i64); impl DishPrice { @@ -113,8 +105,10 @@ impl DishPrice { /// The dietary tags a dish carries, drawn from the school's `dietary_tags` /// list. Deduplicated, order preserved — the list is what a student's profile -/// is matched against, so a repeat carries no extra meaning. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +/// is matched against, so a repeat carries no extra meaning. Stored as a +/// `TEXT[]` column. +#[derive(Debug, Clone, PartialEq, Eq, Type)] +#[sqlx(transparent, no_pg_array)] pub struct DishTags(Vec); impl DishTags { @@ -146,7 +140,7 @@ impl DishTags { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct MenuDish { pub(crate) id: MenuDishId, pub(crate) menu: MenuId, diff --git a/src/domain/message.rs b/src/domain/message.rs index dd6975a..090336f 100644 --- a/src/domain/message.rs +++ b/src/domain/message.rs @@ -1,18 +1,11 @@ -//! One-to-one mail-style messages. A single row serves both ends: the -//! recipient's `read` flag plus one folder field per side, so each party -//! files (archive/trash) and deletes their copy without touching the -//! other's. Filing also stamps that side's origin folder, so a copy can be -//! put back where it came from. A side that permanently deletes goes to the -//! hidden `deleted` folder; once both sides are `deleted` the row itself is -//! removed. - -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use sqlx::Type; +use uuid::Uuid; use crate::constant::{ - MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN, MESSAGE_TABLE, + MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN, RECIPIENT_FOLDERS, SENDER_FOLDERS, }; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; @@ -23,11 +16,11 @@ use crate::validate::{validate_optional, validate_required}; /// query filter and the restore stamp all pass through this enum, so a typo /// is a compile error rather than a silently empty folder. /// -/// `#[surreal(untagged, rename_all = "lowercase")]` stores each variant as a -/// bare lowercase string (`"inbox"`, `"archive"`, …) in the `TYPE string` -/// columns, and round-trips straight back — same trick as `domain::role`. -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] -#[surreal(untagged, rename_all = "lowercase")] +/// Each variant stores as a bare lowercase TEXT value (`"inbox"`, +/// `"archive"`, …) and round-trips straight back — same trick as +/// `domain::role`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] pub enum Folder { Inbox, Sent, @@ -96,35 +89,37 @@ impl Folder { } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct MessageId(RecordId); +/// Typed message row id. A UUIDv7 minted by the process-wide monotonic +/// generator, so `id` order is mint order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct MessageId(Uuid); impl MessageId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: + /// Minted from the process-wide monotonic generator, not a random v4: /// the folder listings sort `id DESC` (newest first, /// [`crate::db::message::list_folder`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(MESSAGE_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parse a wire key. A key that parses as no UUID — a malformed path + /// segment — reads as the nil id, which matches no row: exactly the 404 a + /// dangling record key produced under the old store, without turning a + /// typo into a panic. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(MESSAGE_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The hyphenated wire form. + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct MessageSubject(String); impl MessageSubject { @@ -138,7 +133,8 @@ impl MessageSubject { } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct MessageBody(String); impl MessageBody { @@ -154,7 +150,8 @@ impl MessageBody { /// A sender-chosen tag ("Etüt", "Sınav", …) the UI renders as a badge. /// Required-and-bounded here; "no label" is `Option` on the row. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct MessageLabel(String); impl MessageLabel { @@ -168,7 +165,7 @@ impl MessageLabel { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Message { pub(crate) id: MessageId, pub(crate) sender: UserId, @@ -257,8 +254,8 @@ mod tests { #[tokio::test] async fn folder_sides_resolve_by_membership() { - let sender = UserId::from_key("a"); - let recipient = UserId::from_key("b"); + let sender = UserId::from_key("018f1a00-0000-7000-8000-000000000001"); + let recipient = UserId::from_key("018f1a00-0000-7000-8000-000000000002"); let message = Message { id: MessageId::generate(), sender: sender.clone(), @@ -293,4 +290,22 @@ mod tests { assert!(Folder::allowed_for(false).contains(&Folder::Archive)); assert!(!Folder::allowed_for(true).contains(&Folder::Inbox)); } + + #[test] + fn sqlx_encodes_the_storage_form() { + // The folder columns are TEXT with a CHECK on these exact words; the + // sqlx encoding must never drift from `as_str`. + let mut buf = sqlx::postgres::PgArgumentBuffer::default(); + for folder in [ + Folder::Inbox, + Folder::Sent, + Folder::Archive, + Folder::Trash, + Folder::Deleted, + ] { + buf.clear(); + sqlx::Encode::::encode_by_ref(&folder, &mut buf); + assert_eq!(std::str::from_utf8(&buf).unwrap(), folder.as_str()); + } + } } diff --git a/src/domain/mod.rs b/src/domain/mod.rs index c4f78a2..6f30b6a 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -1,6 +1,8 @@ //! Domain layer: every value is a validated newtype, and each entity owns its -//! own persistence. Types derive `surrealdb::types::SurrealValue` so the exact -//! same typed value flows from HTTP input all the way into the database. +//! own persistence. Row structs derive `sqlx::FromRow` so the exact same typed +//! value flows from HTTP input all the way into PostgreSQL; transparent +//! newtypes derive `sqlx::Type` so a column reads straight into the validated +//! wrapper. pub mod answer_image; pub mod appointment; @@ -66,3 +68,52 @@ pub mod text_fold; pub mod timestamp; pub mod user; pub mod work_entry; + +/// Fallback for lowercase-string enums whose `#[sqlx(type_name = "TEXT", +/// rename_all = "lowercase")]` derive the `sqlx::Type` macro rejects (an +/// exotic shape, not a plain C-like enum). Emits the same thing the derive +/// would: `Type` reporting `TEXT`, `Encode` writing the lowercase name, +/// `Decode` reading a TEXT value back and refusing an unknown one as a decode +/// error — never a panic. Unused today: every current enum derives fine; kept +/// so the fallback shape stays one `macro_rules!` away, identically across +/// the domain. +#[allow(unused_macros)] +macro_rules! text_enum { + ($name:ident { $($variant:ident),+ $(,)? }) => { + impl sqlx::Type for $name { + fn type_info() -> sqlx::postgres::PgTypeInfo { + sqlx::postgres::PgTypeInfo::with_name("TEXT") + } + } + + impl<'r> sqlx::Decode<'r, sqlx::Postgres> for $name { + fn decode( + value: sqlx::postgres::PgValueRef<'r>, + ) -> Result { + let text: &str = sqlx::Decode::::decode(value)?; + match text { + $(stringify!($variant) => Ok(Self::$variant),)+ + other => Err(format!( + concat!("unknown ", stringify!($name), " value: `{}`"), + other + ) + .into()), + } + } + } + + impl<'q> sqlx::Encode<'q, sqlx::Postgres> for $name { + fn encode_by_ref( + &self, + buf: &mut sqlx::postgres::PgArgumentBuffer, + ) -> Result { + sqlx::Encode::::encode( + match self { + $(Self::$variant => stringify!($variant),)+ + }, + buf, + ) + } + } + }; +} diff --git a/src/domain/monotonic_id.rs b/src/domain/monotonic_id.rs index 74f09e7..57a1f74 100644 --- a/src/domain/monotonic_id.rs +++ b/src/domain/monotonic_id.rs @@ -1,34 +1,38 @@ //! Ids that sort in write order, for tables whose listings lean on `id` to //! break ties (or to mean "newest first" outright). //! -//! `Ulid::generate()` fills the low 80 bits at random, so two ids minted in the -//! *same millisecond* sort arbitrarily against each other — millisecond- -//! accurate ordering only. That is not enough when a burst of writes lands -//! inside one tick (a recurring appointment publish expanding a series, a -//! teacher saving templates back to back, a test creating rows in a loop): -//! `ORDER BY id DESC` then scrambles them. [`next_ulid`] mints from one -//! process-wide [`Generator`], which keeps ids strictly increasing within a -//! millisecond by incrementing the random part instead of redrawing it. +//! A bare `Uuid::new_v7()` redraws its random bits per id, so two ids minted +//! in the *same millisecond* sort arbitrarily against each other — +//! millisecond-accurate ordering only. That is not enough when a burst of +//! writes lands inside one tick (a recurring appointment publish expanding a +//! series, a teacher saving templates back to back, a test creating rows in a +//! loop): `ORDER BY id DESC` then scrambles them. [`next_uuid`] mints through +//! one process-wide [`ContextV7`], which keeps ids strictly increasing within +//! a millisecond by incrementing its counter instead of redrawing it. use std::sync::{LazyLock, Mutex}; -use ulid::{Generator, Ulid}; +use uuid::{ContextV7, Uuid}; -static IDS: LazyLock> = LazyLock::new(|| Mutex::new(Generator::new())); +use crate::domain::timestamp::Timestamp; -/// The next id in write order. Process-wide: two processes writing the same -/// table still only get millisecond accuracy, which is what a distributed id -/// can promise anyway. -pub fn next_ulid() -> Ulid { - let mut ids = IDS.lock().expect("monotonic id generator poisoned"); - // The only error is exhausting the random bits *within* one millisecond - // (2^80 ids deep); it clears itself as the clock ticks, so retry rather - // than fall back to a random id and silently reintroduce the defect. - loop { - if let Ok(ulid) = ids.generate() { - break ulid; - } - } +/// `ContextV7` is `Send` but not `Sync` (interior `Cell`s), so the +/// process-wide context lives behind a mutex — the same serialization the id +/// generator always had, and the price of one process-wide mint order. +static CTX: LazyLock> = LazyLock::new(|| Mutex::new(ContextV7::new())); + +/// The next id in write order. The wall clock is the codebase's single read +/// ([`Timestamp::now`]); the context contributes the within-millisecond +/// counter. Process-wide: two processes writing the same table still only get +/// millisecond accuracy, which is what a distributed id can promise anyway. +pub fn next_uuid() -> Uuid { + let millis = Timestamp::now().as_millis(); + let context = CTX.lock().expect("uuid v7 context poisoned"); + Uuid::new_v7(uuid::Timestamp::from_unix( + &*context, + (millis / 1_000) as u64, + (millis % 1_000) as u32 * 1_000_000, + )) } #[cfg(test)] @@ -36,10 +40,11 @@ mod tests { use super::*; /// The defect this module exists for: ids minted back to back (well inside - /// one millisecond) must still sort in mint order. + /// one millisecond) must still sort in mint order. `Uuid`'s `Ord` is + /// big-endian byte order, exactly what a `uuid` column sorts by. #[test] fn ids_sort_in_mint_order_within_a_millisecond() { - let ids: Vec = (0..1000).map(|_| next_ulid().to_string()).collect(); + let ids: Vec = (0..1000).map(|_| next_uuid()).collect(); let mut sorted = ids.clone(); sorted.sort(); assert_eq!(ids, sorted); diff --git a/src/domain/note.rs b/src/domain/note.rs index fe81bed..f2c5e05 100644 --- a/src/domain/note.rs +++ b/src/domain/note.rs @@ -1,39 +1,41 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use uuid::Uuid; -use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN, NOTE_TABLE}; -use crate::domain::monotonic_id::next_ulid; +use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN}; +use crate::domain::monotonic_id::next_uuid; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::{validate_optional, validate_required}; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct NoteId(RecordId); +/// Typed note row id. A UUIDv7 minted by the process-wide monotonic +/// generator, so `id` order is mint order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct NoteId(Uuid); impl NoteId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: + /// Minted from the process-wide monotonic generator, not a random v4: /// notes list `id DESC` (newest first, [`crate::db::note::list_for`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(NOTE_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parse a wire key. A key that parses as no UUID — a malformed path + /// segment — reads as the nil id, which matches no row: exactly the 404 a + /// dangling record key produced under the old store, without turning a + /// typo into a panic. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(NOTE_TABLE, key)) + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The hyphenated wire form. + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct NoteTitle(String); impl NoteTitle { @@ -47,7 +49,8 @@ impl NoteTitle { } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct NoteContent(String); impl NoteContent { @@ -63,9 +66,10 @@ impl NoteContent { /// Fields are crate-visible: [`crate::db::note`] mints the rows on create and /// reads the id when updating and cascading a delete. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Note { pub(crate) id: NoteId, + #[sqlx(rename = "app_user")] pub(crate) user: UserId, pub(crate) title: NoteTitle, pub(crate) content: NoteContent, diff --git a/src/domain/note_file.rs b/src/domain/note_file.rs index b2c6cee..5497e36 100644 --- a/src/domain/note_file.rs +++ b/src/domain/note_file.rs @@ -1,49 +1,51 @@ //! A file attached to a note. The row carries metadata only (original //! filename, MIME type, byte size); the bytes themselves live on disk under //! [`crate::config::Config::files_path`], in a file named by this row's key — -//! a server-generated ULID, so no user input ever shapes a disk path. The web -//! layer owns the blob I/O and its ordering (blob before row on upload, row -//! before blob on delete); persistence lives in [`crate::db::note_file`]. +//! a server-generated UUIDv7, so no user input ever shapes a disk path. The +//! web layer owns the blob I/O and its ordering (blob before row on upload, +//! row before blob on delete); persistence lives in [`crate::db::note_file`]. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use uuid::Uuid; -use crate::constant::{MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN, NOTE_FILE_TABLE}; -use crate::domain::monotonic_id::next_ulid; +use crate::constant::{MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN}; +use crate::domain::monotonic_id::next_uuid; use crate::domain::note::NoteId; use crate::error::ValidationError; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct NoteFileId(RecordId); +/// Typed note-file row id. A UUIDv7 minted by the process-wide monotonic +/// generator, so `id` order is mint order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct NoteFileId(Uuid); impl NoteFileId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: + /// Minted from the process-wide monotonic generator, not a random v4: /// a note's files list `id DESC` (newest first, /// [`crate::db::note_file::list_for`]), and a random low half scrambles /// rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(NOTE_FILE_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parse a wire key. A key that parses as no UUID — a malformed path + /// segment — reads as the nil id, which matches no row: exactly the 404 a + /// dangling record key produced under the old store, without turning a + /// typo into a panic. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(NOTE_FILE_TABLE, key)) + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The hyphenated wire form. + pub fn key(&self) -> String { + self.0.to_string() } } /// The uploader's original filename, kept for display and download headers. /// Never used as a disk path — but path separators and control characters are /// refused anyway: they are not filenames, only header/log injection attempts. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct FileName(String); impl FileName { @@ -79,7 +81,8 @@ impl FileName { /// The MIME type the client declared for the file. Blank defaults to /// `application/octet-stream`; it is echoed back on download, so it is held /// to header-safe ASCII. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct FileContentType(String); impl FileContentType { @@ -112,7 +115,7 @@ impl FileContentType { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct NoteFile { pub(crate) id: NoteFileId, pub(crate) note: NoteId, diff --git a/src/domain/parent_link.rs b/src/domain/parent_link.rs index df36ed4..fa2d7fc 100644 --- a/src/domain/parent_link.rs +++ b/src/domain/parent_link.rs @@ -1,32 +1,46 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::PARENT_LINK_TABLE; use crate::domain::user::UserId; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ParentLinkId(RecordId); +/// The (parent, student) pair — the table's natural composite primary key. +/// The same pair always maps to the same row, so linking is a single atomic +/// upsert with no find-then-insert race and one-row-per-pair by construction. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ParentLinkId { + parent: UserId, + student: UserId, +} impl ParentLinkId { - /// A deterministic id for the (parent, student) pair — same trick as - /// `EnrollmentId`: the same pair always maps to the same record id, so - /// linking is a single atomic UPSERT with no find-then-insert race and - /// one-row-per-pair by construction. pub fn composite(parent: &UserId, student: &UserId) -> Self { - Self(RecordId::new( - PARENT_LINK_TABLE, - format!("{}_{}", parent.key(), student.key()), - )) + Self { + parent: *parent, + student: *student, + } } - pub fn record(&self) -> RecordId { - self.0.clone() + /// Parse the `{parent}_{student}` wire form. A key that parses as no pair + /// reads as the nil pair, which matches no row — exactly the 404 a + /// dangling composite key produced under the old store, without turning a + /// typo into a panic. UUID strings carry only `-`, so `_` is an + /// unambiguous joiner. + pub fn from_key(key: &str) -> Self { + let (parent, student) = key.rsplit_once('_').unwrap_or(("", "")); + Self { + parent: UserId::from_key(parent), + student: UserId::from_key(student), + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The `{parent}_{student}` wire form. + pub fn key(&self) -> String { + format!("{}_{}", self.parent.key(), self.student.key()) + } + + pub fn parent(&self) -> UserId { + self.parent + } + + pub fn student(&self) -> UserId { + self.student } } @@ -35,19 +49,14 @@ impl ParentLinkId { /// attendance, pomodoro). The single write it authorizes is the food program — /// a parent books and cancels a linked child's meals, since paying for lunch /// is a parent's job and a small child cannot do it themselves. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct ParentLink { - pub(crate) id: ParentLinkId, pub(crate) parent: UserId, pub(crate) student: UserId, pub(crate) linked_by: UserId, } impl ParentLink { - pub fn get_id(&self) -> &ParentLinkId { - &self.id - } - pub fn get_parent(&self) -> &UserId { &self.parent } diff --git a/src/domain/payment_ledger.rs b/src/domain/payment_ledger.rs index 4b3aff3..ee12efd 100644 --- a/src/domain/payment_ledger.rs +++ b/src/domain/payment_ledger.rs @@ -1,11 +1,11 @@ //! School fees: an **append-only** ledger of what a student was charged, what //! they paid against each charge, and what was paid back out. //! -//! Nothing here ever `UPDATE`s or `DELETE`s a row, and no such path exists — -//! every field is `READONLY` in the schema as well. A ledger line that can be -//! edited or dropped silently rewrites a family's financial history with no -//! trace of the rewrite; a mistake is corrected by appending the opposing line, -//! which leaves both the mistake and the correction visible. +//! Nothing here ever `UPDATE`s or `DELETE`s a row, and no such path exists. A +//! ledger line that can be edited or dropped silently rewrites a family's +//! financial history with no trace of the rewrite; a mistake is corrected by +//! appending the opposing line, which leaves both the mistake and the +//! correction visible. //! //! **The balance is never stored.** It is always the fold //! @@ -31,103 +31,103 @@ //! - **A reversal only undoes a negative-fold line** (a charge, or a refund). //! A mistaken *credit* is corrected by a refund pointing at it, so that the //! money leaving the school is always spelled the same way. A reversal itself -//! is never reversed (the id would collide with its own target's, and the +//! is never reversed (the key would collide with its own target's, and the //! kind check refuses it): a charge dropped by mistake is re-raised by //! assigning a fresh one-installment plan, which mints a new deterministic -//! charge id instead of resurrecting the old one. +//! charge key instead of resurrecting the old one. //! - **Every replayable line is keyed by its cause.** An installment charge's -//! id is `(plan, student, n)` and a reversal's is `_r`, so replaying -//! either writes nothing at all, and an assignment that crashed half-way -//! self-heals when it is repeated. Money must never depend on a "has this -//! been billed yet?" scan: two concurrent requests can both read "not yet" -//! and both append. +//! key is `{assignment-key}_c{n}` and a reversal's is `{line-key}_r`, so +//! replaying either writes nothing at all, and an assignment that crashed +//! half-way self-heals when it is repeated. Money must never depend on a +//! "has this been billed yet?" scan: two concurrent requests can both read +//! "not yet" and both append. +//! +//! The ledger row ids are **derived TEXT keys**, not minted uuids — they are +//! the identity the store's uniqueness check enforces (`id TEXT PRIMARY +//! KEY`): a duplicate insert of the same key is the "already billed" answer. +//! +//! The writes and the balance reads live in [`crate::db::payment_ledger`]; +//! the credit/refund/reversal workflows in +//! [`crate::service::payment_ledger`]. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use sqlx::Type; -use crate::constant::PAYMENT_LEDGER_TABLE; use crate::domain::fee_plan_assignment::FeePlanAssignmentId; // The three value types are the *same* money vocabulary the canteen ledger // speaks, so they are imported rather than copied: one cap, one trim rule, one // error message for both ledgers. pub use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote}; -use crate::domain::monotonic_id::next_ulid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct PaymentLedgerId(RecordId); +/// The ledger line's id — a derived TEXT key (`id TEXT PRIMARY KEY`): +/// `{assignment-key}_c{n}` for an installment charge, `{line-key}_r` for a +/// reversal, `{target-key}_{marker}_{request_key}` for a keyed payment or +/// refund, or a fresh uuid-string key otherwise. +#[derive(Debug, Clone, PartialEq, Eq, Type)] +#[sqlx(transparent)] +pub struct PaymentLedgerId(String); impl PaymentLedgerId { - /// A fresh id in write order — `Ulid::generate()`'s random low bits sort - /// arbitrarily within one millisecond, which would scramble the `id` - /// tie-break of the newest-first statement below. + /// A fresh key in write order — the process-wide uuid v7 generator's + /// string form, so the `id` tie-break of the newest-first statement below + /// still sorts in mint order. pub fn generate() -> Self { - Self(RecordId::new(PAYMENT_LEDGER_TABLE, next_ulid().to_string())) + Self(crate::domain::monotonic_id::next_uuid().to_string()) } + /// Parse a stored key back into an id. Ledger keys are TEXT, so any + /// string round-trips. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(PAYMENT_LEDGER_TABLE, key)) + Self(key.to_string()) } /// The one charge line installment `n` (1-based) of this assignment may - /// ever have. The assignment key is already `_`, so this is - /// `__c`: two concurrent assigns derive the *same* ids - /// and so cannot bill a plan twice. Idempotence rests on identity, never on - /// a scan a concurrent writer can slip past. + /// ever have. The assignment key is already `{plan}_{student}`, so this is + /// `{plan}_{student}_c{n}`: two concurrent assigns derive the *same* keys + /// and so cannot bill a plan twice. Idempotence rests on identity, never + /// on a scan a concurrent writer can slip past. pub fn for_installment(assignment: &FeePlanAssignmentId, n: usize) -> Self { - Self(RecordId::new( - PAYMENT_LEDGER_TABLE, - format!("{}_c{n}", assignment.key()), - )) + Self(format!("{}_c{n}", assignment.key())) } /// The one reversal a line may ever have — a retried undo appends nothing - /// the second time — the id decides that, not a scan. + /// the second time — the key decides that, not a scan. pub fn for_reversal(line: &PaymentLedgerId) -> Self { - Self(RecordId::new( - PAYMENT_LEDGER_TABLE, - format!("{}_r", line.key()), - )) + Self(format!("{}_r", line.key())) } - /// The one line a `(target, request_key)` pair may ever have: `_k_` - /// for a payment, `_kr_` for a refund. Scoping the key by the line - /// it targets is what keeps one office's "receipt-114" from colliding with - /// another charge's, and the two markers keep the kinds apart the same way - /// `_c` and `_r` do above. + /// The one line a `(target, request_key)` pair may ever have: + /// `{target}_k_{key}` for a payment, `{target}_kr_{key}` for a refund. + /// Scoping the key by the line it targets is what keeps one office's + /// "receipt-114" from colliding with another charge's, and the two markers + /// keep the kinds apart the same way `_c{n}` and `_r` do above. /// /// **The grammar parses uniquely because `_` joins the parts and cannot - /// appear inside one.** Every id here is `__c` optionally - /// followed by one `_k_`, `_kr_` or `_r` — plan and student keys - /// are ULIDs (`[0-9A-Z]` only) and a `request_key` is + /// appear inside one.** Every key here is `__c` optionally + /// followed by one `_k_`, `_kr_` or `_r` — uuid halves carry + /// only hex digits and `-`, and a `request_key` is /// [`crate::validate::validate_request_key`]'s `[A-Za-z0-9-]`, so no part /// can spell a separator plus a marker. That is not decoration: a key of - /// `abc_r` on a refund would derive exactly the id that refund's *reversal* - /// must own, and the loser of that collision would be handed a line of the - /// wrong kind and the wrong amount, with the real reversal impossible - /// forever after. The ban on `_` in a key is what makes the collision - /// unconstructible; `crate::db::payment_ledger::append` re-checks the - /// kind anyway. + /// `abc_r` on a refund would derive exactly the key that refund's + /// *reversal* must own, and the loser of that collision would be handed a + /// line of the wrong kind and the wrong amount, with the real reversal + /// impossible forever after. The ban on `_` in a key is what makes the + /// collision unconstructible; `crate::db::payment_ledger::append` re-checks + /// the kind anyway. pub fn for_request(target: &PaymentLedgerId, marker: &str, key: &PaymentRequestKey) -> Self { - Self(RecordId::new( - PAYMENT_LEDGER_TABLE, - format!("{}_{marker}_{}", target.key(), key.as_str()), - )) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(format!("{}_{marker}_{}", target.key(), key.as_str())) } pub fn key(&self) -> &str { - key_of(&self.0) + &self.0 } } /// A client-chosen idempotence key for one payment or refund. Never stored as -/// a column — it lives inside the line's record id, which is what makes a retry -/// derive the row it already wrote instead of a second one. +/// a column — it lives inside the line's derived key, which is what makes a +/// retry derive the row it already wrote instead of a second one. #[derive(Debug, Clone)] pub struct PaymentRequestKey(String); @@ -142,18 +142,10 @@ impl PaymentRequestKey { } } -/// The bare key of a record id — how every id leaves this API. -fn key_of(record: &RecordId) -> &str { - match &record.key { - RecordIdKey::String(key) => key, - _ => "", - } -} - -/// What a line means. `untagged` + `rename_all` store it as the bare lowercase -/// string the `kind` column types as, in lockstep with `PAYMENT_LEDGER_KINDS`. -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] -#[surreal(untagged, rename_all = "lowercase")] +/// What a line means. Stored as the bare lowercase TEXT value the `kind` +/// column carries, in lockstep with `PAYMENT_LEDGER_KINDS`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] pub enum PaymentLedgerKind { Charge, Credit, @@ -185,17 +177,18 @@ impl PaymentLedgerKind { /// Fields are crate-visible: [`crate::db::payment_ledger`] mints the charge /// rows, and [`crate::service::payment_ledger`] appends the credits, refunds, -/// and reversals the cap lock authorizes. -#[derive(Debug, Clone, SurrealValue)] +/// and reversals the guard authorizes. +#[derive(Debug, Clone, sqlx::FromRow)] pub struct PaymentLedger { pub(crate) id: PaymentLedgerId, pub(crate) student: UserId, pub(crate) kind: PaymentLedgerKind, pub(crate) amount_minor: LedgerAmount, - /// What caused the line: a charge points at its `fee_plan_assignment`, a - /// credit at the charge it pays, a refund at the credit it returns, a - /// reversal at the line it undoes. Untyped, hence a bare `RecordId`. - pub(crate) source: Option, + /// What caused the line: a charge points at its `fee_plan_assignment` + /// row's `{plan}_{student}` key, a credit at the charge it pays, a refund + /// at the credit it returns, a reversal at the line it undoes. + /// Polymorphic by kind, hence a bare TEXT key — no foreign key. + pub(crate) source: Option, /// When this installment falls due. Charges only — nothing else has one. pub(crate) due_at: Option, pub(crate) method: Option, @@ -223,7 +216,7 @@ impl PaymentLedger { /// The cause's bare key; which table it lives in follows from the kind. pub fn get_source_key(&self) -> Option<&str> { - self.source.as_ref().map(key_of) + self.source.as_deref() } pub fn get_due_at(&self) -> Option { @@ -268,26 +261,24 @@ impl PaymentLedger { #[cfg(test)] mod tests { - use surrealdb::types::Value; - use super::*; use crate::domain::fee_plan::FeePlanId; - use crate::domain::user::UserId; - /// The `kind` column is `TYPE string`: an object-wrapped enum would be - /// rejected on write, and a `kind = 'charge'` lookup would silently match - /// nothing. + /// The `kind` column is `TEXT` with a CHECK on these exact words; the + /// sqlx encoding must never drift from `as_str`, or a `kind = 'charge'` + /// lookup would silently match nothing. #[test] - fn kind_stores_as_a_bare_string() { + fn sqlx_encodes_the_storage_form() { + let mut buf = sqlx::postgres::PgArgumentBuffer::default(); for kind in [ PaymentLedgerKind::Charge, PaymentLedgerKind::Credit, PaymentLedgerKind::Reversal, PaymentLedgerKind::Refund, ] { - let value = kind.into_value(); - assert_eq!(value, Value::String(kind.as_str().to_string())); - assert_eq!(PaymentLedgerKind::from_value(value).unwrap(), kind); + buf.clear(); + sqlx::Encode::::encode_by_ref(&kind, &mut buf); + assert_eq!(std::str::from_utf8(&buf).unwrap(), kind.as_str()); } } @@ -335,49 +326,50 @@ mod tests { } /// Idempotence rests on identity: the same (plan, student, installment) - /// must always derive the same charge id, and a reversal must be the one + /// must always derive the same charge key, and a reversal must be the one /// line its target can ever have. #[test] - fn a_charge_id_is_the_plan_the_student_and_the_installment() { - let assignment = FeePlanAssignmentId::composite( - &FeePlanId::from_key("plan1"), - &UserId::from_key("stu1"), - ); + fn a_charge_key_is_the_plan_the_student_and_the_installment() { + const PLAN: &str = "018f1a00-0000-7000-8000-000000000001"; + const STU: &str = "018f1a00-0000-7000-8000-000000000002"; + let assignment = FeePlanAssignmentId::composite(&FeePlanId::from_key(PLAN), &UserId::from_key(STU)); let first = PaymentLedgerId::for_installment(&assignment, 1); - assert_eq!(first.key(), "plan1_stu1_c1"); + assert_eq!(first.key(), format!("{PLAN}_{STU}_c1")); assert_eq!( PaymentLedgerId::for_installment(&assignment, 1), first, - "a replayed assign must derive the same id, or it bills twice" + "a replayed assign must derive the same key, or it bills twice" ); assert_ne!(PaymentLedgerId::for_installment(&assignment, 2), first); assert_eq!( PaymentLedgerId::for_reversal(&first).key(), - "plan1_stu1_c1_r" + format!("{PLAN}_{STU}_c1_r") ); } - /// A `request_key` is only an idempotence key if it derives the same id + /// A `request_key` is only an idempotence key if it derives the same key /// every time, and only *safe* if it is scoped by the line it targets and /// tells a payment from a refund. #[test] fn a_request_key_is_scoped_by_its_target_and_its_kind() { - let charge = PaymentLedgerId::from_key("plan1_stu1_c1"); - let other = PaymentLedgerId::from_key("plan1_stu1_c2"); + const PLAN: &str = "018f1a00-0000-7000-8000-000000000001"; + const STU: &str = "018f1a00-0000-7000-8000-000000000002"; + let charge = PaymentLedgerId::from_key(format!("{PLAN}_{STU}_c1")); + let other = PaymentLedgerId::from_key(format!("{PLAN}_{STU}_c2")); let key = PaymentRequestKey::try_new("receipt-114").unwrap(); let credit = PaymentLedgerId::for_request(&charge, "k", &key); - assert_eq!(credit.key(), "plan1_stu1_c1_k_receipt-114"); + assert_eq!(credit.key(), format!("{PLAN}_{STU}_c1_k_receipt-114")); assert_eq!( PaymentLedgerId::for_request(&charge, "k", &key), credit, - "a retry must derive the same id, or it pays twice" + "a retry must derive the same key, or it pays twice" ); assert_ne!(PaymentLedgerId::for_request(&other, "k", &key), credit); assert_ne!(PaymentLedgerId::for_request(&charge, "kr", &key), credit); assert_eq!( PaymentLedgerId::for_request(&credit, "kr", &key).key(), - "plan1_stu1_c1_k_receipt-114_kr_receipt-114" + format!("{PLAN}_{STU}_c1_k_receipt-114_kr_receipt-114") ); } } diff --git a/src/domain/pomodoro.rs b/src/domain/pomodoro.rs index e3888c1..24e0e33 100644 --- a/src/domain/pomodoro.rs +++ b/src/domain/pomodoro.rs @@ -1,46 +1,34 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use uuid::Uuid; -use crate::constant::POMODORO_SESSION_TABLE; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct PomodoroSessionId(RecordId); +/// Typed pomodoro-session row id. A UUIDv7 minted by the process-wide +/// monotonic generator, so `id` order is mint order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct PomodoroSessionId(Uuid); impl PomodoroSessionId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: - /// the log sorts `started_at DESC, id DESC` and the id breaks the tie between - /// two sessions started at the same instant. The `open_` key below never ties - /// with itself (one running session per user), so it needs no ordering. + /// Minted from the process-wide monotonic generator, not a random v4: + /// the log sorts `started_at DESC, id DESC` and the id breaks the tie + /// between two sessions started at the same instant. pub fn generate() -> Self { - Self(RecordId::new( - POMODORO_SESSION_TABLE, - next_ulid().to_string(), - )) + Self(next_uuid()) } - /// The deterministic id of `user`'s *running* session. At most one runs - /// per user by construction: starting is a single `UPSERT` on this id - /// (atomic — a restart replaces the row in place), and finishing - /// atomically takes the row and re-files it under a ULID id. `open_` - /// cannot collide with a ULID key (ULIDs are bare alphanumerics). - pub fn open_for(user: &UserId) -> Self { - Self(RecordId::new( - POMODORO_SESSION_TABLE, - format!("open_{}", user.key()), - )) + /// Parse a wire key. A key that parses as no UUID — a malformed path + /// segment — reads as the nil id, which matches no row: exactly the 404 a + /// dangling record key produced under the old store, without turning a + /// typo into a panic. + pub fn from_key(key: &str) -> Self { + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The hyphenated wire form. + pub fn key(&self) -> String { + self.0.to_string() } } @@ -49,18 +37,27 @@ impl PomodoroSessionId { /// client can never supply its own instants, so the recorded focus time is /// honest. Breaks are not stored; the frontend owns the work/break rhythm and /// the backend records only the focus stint. -#[derive(Debug, Clone, SurrealValue)] +/// +/// "At most one running session per student" is no longer carried by a +/// deterministic key: it is a partial unique index on the table +/// (`pomodoro_session_open_stint`) over rows whose `finished_at` is NULL, so +/// the database itself refuses (or restarts) a second running stint. +#[derive(Debug, Clone, sqlx::FromRow)] pub struct PomodoroSession { - id: PomodoroSessionId, - user: UserId, - started_at: Timestamp, - finished_at: Option, - /// The student's own name for what this stint is for ("math", "TYT + pub(crate) id: PomodoroSessionId, + #[sqlx(rename = "app_user")] + pub(crate) user: UserId, + pub(crate) started_at: Timestamp, + pub(crate) finished_at: Option, + /// The verdict `finish` reached for this stint, stamped at close so a later + /// reader never re-derives it against thresholds that have since moved. + /// `NULL`: a running stint has no verdict yet, and a stint closed + /// before the rule existed carries none and cannot honestly be given one. + pub(crate) counted: Option, + /// The student's own name for what the stint is for ("math", "TYT /// denemesi") — free text given at start, not a subject reference. - /// `None` on an unnamed stint and on any row from before the field - /// existed, which reads exactly like an unnamed one. - label: Option, - counted: Option, + /// `NULL` on an unnamed stint. + pub(crate) label: Option, } impl PomodoroSession { @@ -89,7 +86,7 @@ impl PomodoroSession { } /// What the student called this stint when they started it. `None` when - /// they started it unnamed, and on rows that predate the field. + /// they started it unnamed. pub fn get_label(&self) -> Option<&str> { self.label.as_deref() } diff --git a/src/domain/pool_question.rs b/src/domain/pool_question.rs index 1d33530..7261d49 100644 --- a/src/domain/pool_question.rs +++ b/src/domain/pool_question.rs @@ -7,52 +7,53 @@ //! question's solutions with it. An optional photo of the problem rides on //! the row as metadata (`image_*`); the bytes live on disk under //! [`crate::config::Config::files_path`] in a file named by `image_file` — a -//! fresh server-generated ULID per upload. The web layer owns the blob I/O; +//! fresh server-generated id per upload. The web layer owns the blob I/O; //! the queries live in [`crate::db::pool_question`], the workflows in //! [`crate::service::pool_question`]. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use uuid::Uuid; use crate::constant::{ - MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN, POOL_QUESTION_TABLE, STATUS_APPROVED, - STATUS_PENDING, + MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN, STATUS_APPROVED, STATUS_PENDING, }; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::note_file::FileContentType; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::validate_required; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct PoolQuestionId(RecordId); +/// Typed pool-question row id. A UUIDv7 minted by the process-wide monotonic +/// generator, so `id` order is mint order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct PoolQuestionId(Uuid); impl PoolQuestionId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: + /// Minted from the process-wide monotonic generator, not a random v4: /// the pool sorts `asked_at DESC, id DESC` and the id *is* the tie-break /// ([`crate::db::pool_question::list_all`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(POOL_QUESTION_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parse a wire key. A key that parses as no UUID — a malformed path + /// segment — reads as the nil id, which matches no row: exactly the 404 a + /// dangling record key produced under the old store, without turning a + /// typo into a panic. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(POOL_QUESTION_TABLE, key)) + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The hyphenated wire form. + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct PoolQuestionTitle(String); impl PoolQuestionTitle { @@ -66,7 +67,8 @@ impl PoolQuestionTitle { } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct PoolQuestionBody(String); impl PoolQuestionBody { @@ -80,7 +82,7 @@ impl PoolQuestionBody { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct PoolQuestion { pub(crate) id: PoolQuestionId, pub(crate) asker: UserId, @@ -89,8 +91,8 @@ pub struct PoolQuestion { pub(crate) status: String, pub(crate) asked_at: Timestamp, pub(crate) approved_by: Option, - /// The photo's on-disk blob name — a fresh ULID every upload; `None` when - /// the question carries no image. + /// The photo's on-disk blob name — a fresh server-generated id every + /// upload; `None` when the question carries no image. pub(crate) image_file: Option, pub(crate) image_content_type: Option, pub(crate) image_size: Option, diff --git a/src/domain/preferences.rs b/src/domain/preferences.rs index 5350884..72f099e 100644 --- a/src/domain/preferences.rs +++ b/src/domain/preferences.rs @@ -3,18 +3,17 @@ //! and the frontend falls back to the device preference (`prefers-color-scheme`, //! browser language) or its own default accent. -use surrealdb::types::SurrealValue; +use sqlx::Type; use crate::constant::{LANGUAGES, PALETTE_COLOR_LEN, THEMES}; use crate::error::ValidationError; /// The frontend color scheme. /// -/// `#[surreal(untagged, rename_all = "lowercase")]` stores each variant as a -/// bare lowercase string (`"light"` / `"dark"`) — same encoding contract as -/// [`crate::domain::role::Role`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] -#[surreal(untagged, rename_all = "lowercase")] +/// Each variant stores as a bare lowercase TEXT value (`"light"` / +/// `"dark"`) — same encoding contract as [`crate::domain::role::Role`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] pub enum Theme { Light, Dark, @@ -43,8 +42,8 @@ impl Theme { /// The frontend interface language, as an ISO 639-1 code — the same values the /// frontend's locale switch uses (`"tr"` Turkish, `"en"` English). -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] -#[surreal(untagged, rename_all = "lowercase")] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] pub enum Language { Tr, En, @@ -77,8 +76,9 @@ impl Language { /// Unlike [`Theme`] and [`Language`] this is an **open** value set: any valid /// hex passes, so the frontend can grow its palette without a backend change. /// A plain newtype over `String`, which stores as a bare string — the same -/// `option` column contract the two enums encode into. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +/// `TEXT NULL` column contract the two enums encode into. +#[derive(Debug, Clone, PartialEq, Eq, Type)] +#[sqlx(transparent)] pub struct PaletteColor(String); impl PaletteColor { @@ -109,7 +109,6 @@ impl PaletteColor { mod tests { use super::*; use crate::constant::PALETTE_COLOR_PATTERN; - use surrealdb::types::Value; #[tokio::test] async fn theme_str_round_trips() { @@ -200,23 +199,25 @@ mod tests { } } - #[tokio::test] - async fn surreal_values_are_plain_strings() { - // `untagged` keeps the stored value a bare string so the `option` - // columns accept it. Guard that the encoding never regresses. + #[test] + fn sqlx_encodes_the_storage_form() { + // `rename_all` keeps the stored value the bare lowercase string the + // TEXT columns carry; the palette color stores as the string it + // validated to. Guard that the sqlx encoding never drifts. + let mut buf = sqlx::postgres::PgArgumentBuffer::default(); for theme in THEMES { - let value = theme.into_value(); - assert_eq!(value, Value::String(theme.as_str().to_string())); - assert_eq!(Theme::from_value(value).unwrap(), theme); + buf.clear(); + sqlx::Encode::::encode_by_ref(&theme, &mut buf); + assert_eq!(std::str::from_utf8(&buf).unwrap(), theme.as_str()); } for language in LANGUAGES { - let value = language.into_value(); - assert_eq!(value, Value::String(language.as_str().to_string())); - assert_eq!(Language::from_value(value).unwrap(), language); + buf.clear(); + sqlx::Encode::::encode_by_ref(&language, &mut buf); + assert_eq!(std::str::from_utf8(&buf).unwrap(), language.as_str()); } let color = PaletteColor::try_from_str("#fefae0").unwrap(); - let value = color.clone().into_value(); - assert_eq!(value, Value::String("#fefae0".to_string())); - assert_eq!(PaletteColor::from_value(value).unwrap(), color); + buf.clear(); + sqlx::Encode::::encode_by_ref(&color, &mut buf); + assert_eq!(std::str::from_utf8(&buf).unwrap(), "#fefae0"); } } diff --git a/src/domain/profile.rs b/src/domain/profile.rs index 2e0ff1d..ce76da6 100644 --- a/src/domain/profile.rs +++ b/src/domain/profile.rs @@ -1,8 +1,6 @@ //! Personal-info newtypes shared by every account role — student, teacher, //! manager, and admin records all carry the same optional contact fields. -use surrealdb::types::SurrealValue; - use crate::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN, MAX_NAME_LEN}; use crate::domain::badge::BadgeStats; use crate::domain::timestamp::Timestamp; @@ -12,7 +10,8 @@ use crate::validate::{validate_email, validate_optional, validate_phone, validat /// A person's given or family name. One type serves both fields — the `field` /// tag only steers the error message ("name …" vs "surname …"). Stored trimmed; /// unicode is welcome (names are not ASCII). -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct PersonName(String); impl PersonName { @@ -27,7 +26,8 @@ impl PersonName { } /// A plausibly-shaped email address (see [`validate_email`]). Stored trimmed. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct Email(String); impl Email { @@ -43,7 +43,8 @@ impl Email { /// A phone number: optional leading `+`, 7–15 digits, cosmetic separators /// allowed (see [`validate_phone`]). Stored trimmed, separators kept as given. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct Phone(String); impl Phone { @@ -65,7 +66,8 @@ impl Phone { /// UTC+14) legitimately submits a date the server's UTC calendar hasn't /// reached yet. Without the grace, "born today" entered from Istanbul or /// Auckland shortly after local midnight is wrongly rejected. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct BirthDate(String); impl BirthDate { @@ -96,7 +98,8 @@ impl BirthDate { /// The name a profile shows instead of the legal one — a nickname, a shortened /// form, whatever the person answers to. Stored trimmed; unicode is welcome, /// same as [`PersonName`] and unlike the ASCII-only username. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct DisplayName(String); impl DisplayName { @@ -113,7 +116,8 @@ impl DisplayName { /// A short self-description on the public profile. Free text within /// [`MAX_BIO_LEN`], blank allowed — an empty bio is a written-then-erased one, /// which is a legitimate state and not an error. Stored trimmed. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct Bio(String); impl Bio { @@ -136,7 +140,7 @@ impl Bio { /// One named struct on purpose: the auto-earned badge rules take a whole /// `ProfileStats` as their sole input, so a counter added here reaches them /// without touching a signature. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone)] pub struct ProfileStats { pub(crate) pomodoro_sessions: i64, pub(crate) pomodoro_focus_ms: i64, diff --git a/src/domain/question_image.rs b/src/domain/question_image.rs index 5b3c63f..bbcd4db 100644 --- a/src/domain/question_image.rs +++ b/src/domain/question_image.rs @@ -1,58 +1,66 @@ //! An image pinned to an exam question — the question's own illustration -//! (`slot = NONE`, any kind: a map above the prompt) or one choice's picture -//! (`slot` = that choice's stable id, choice questions only). The row carries metadata; the bytes -//! live on disk under [`crate::config::Config::files_path`] in a file named by -//! `file` — a fresh server-generated ULID per upload, so no user input ever -//! shapes a disk path and a replace never overwrites bytes in place. The row -//! id is *deterministic* per (question, slot), so "one image per slot" holds -//! by construction and a replace is a plain UPSERT. The queries and -//! transactions over these rows live in [`crate::db::question_image`]; the web -//! layer owns the blob I/O and its ordering (new blob before row, row before -//! old blob). +//! (`slot = NULL`, any kind: a map above the prompt) or one choice's picture +//! (`slot` = that choice's stable id, choice questions only). The row carries +//! metadata; the bytes live on disk under +//! [`crate::config::Config::files_path`] in a file named by `file` — a fresh +//! server-generated id per upload, so no user input ever shapes a disk path +//! and a replace never overwrites bytes in place. The row's identity is the +//! natural pair of its question and slot — "one image per slot" holds by +//! construction and a replace is a plain upsert. The queries and +//! transactions over these rows live in [`crate::db::question_image`]; the +//! web layer owns the blob I/O and its ordering (new blob before row, row +//! before old blob). -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; - -use crate::constant::QUESTION_IMAGE_TABLE; use crate::domain::exam::ExamId; use crate::domain::exam_question::{ChoiceId, ExamQuestionId}; -use crate::domain::key; +use crate::domain::monotonic_id::next_uuid; use crate::domain::note_file::FileContentType; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct QuestionImageId(RecordId); +/// The (question, slot) pair — the table's natural unique identity. The same +/// trick as the exam id types' composite keys: the slot sentinel `"q"` keeps +/// the illustration apart from every choice's picture, and a choice's stable +/// id can never be `"q"`, so the two shapes can never collide. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct QuestionImageId { + question: ExamQuestionId, + slot: Option, +} impl QuestionImageId { - /// The one id a (question, slot) pair can have — see [`key::slot`] for the - /// key shape and why the two forms can never collide. + /// The one identity a (question, slot) pair can have — see + /// [`crate::domain::key::slot`] for the key shape and why the two forms + /// can never collide. pub fn for_slot(question: &ExamQuestionId, slot: Option<&ChoiceId>) -> Self { - Self(RecordId::new( - QUESTION_IMAGE_TABLE, - key::slot(question.key(), slot.map(|id| id.as_str())), - )) + Self { + question: question.clone(), + slot: slot.cloned(), + } } - pub fn record(&self) -> RecordId { - self.0.clone() + /// The wire form, `None` spelled with the `"q"` sentinel — the same + /// spelling the stored key uses. + pub fn key(&self) -> String { + crate::domain::key::slot(&self.question.key(), self.slot.as_ref().map(|id| id.as_str())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn question(&self) -> &ExamQuestionId { + &self.question + } + + pub fn slot(&self) -> Option<&ChoiceId> { + self.slot.as_ref() } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct QuestionImage { - pub(crate) id: QuestionImageId, pub(crate) exam: ExamId, pub(crate) question: ExamQuestionId, - /// `NONE` = the question's illustration; otherwise the id of the option - /// this picture belongs to. + /// `NULL` = the question's illustration; otherwise the id of the option + /// this picture belongs to. Together with `question` this is the row's + /// `UNIQUE NULLS NOT DISTINCT` identity. pub(crate) slot: Option, - /// The blob's on-disk name — a fresh ULID every upload. + /// The blob's on-disk name — a fresh server-generated id every upload. pub(crate) file: String, pub(crate) content_type: FileContentType, pub(crate) size: i64, @@ -71,11 +79,10 @@ impl QuestionImage { size: i64, ) -> Self { Self { - id: QuestionImageId::for_slot(question, slot), exam: exam.clone(), question: question.clone(), slot: slot.cloned(), - file: Ulid::generate().to_string(), + file: next_uuid().to_string(), content_type, size, } @@ -101,3 +108,21 @@ impl QuestionImage { self.size } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The illustration (`None`) and a choice picture key apart — the `"q"` + /// sentinel can never be a choice's id. + #[test] + fn the_illustration_and_a_choice_never_collide() { + let question = ExamQuestionId::from_key("018f1a00-0000-7000-8000-000000000001"); + let illustration = QuestionImageId::for_slot(&question, None); + assert_eq!( + illustration.key(), + format!("{}_q", question.key()), + "the sentinel spelling is the stored key's spelling" + ); + } +} diff --git a/src/domain/rag_output.rs b/src/domain/rag_output.rs index 1fb9c56..f99e25a 100644 --- a/src/domain/rag_output.rs +++ b/src/domain/rag_output.rs @@ -14,43 +14,44 @@ //! connected. Persistence lives in [`crate::db::rag_output`]. use serde_json::Value; -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use sqlx::types::Json; +use uuid::Uuid; -use crate::constant::RAG_OUTPUT_TABLE; use crate::domain::course::CourseId; use crate::domain::course_note::CourseNoteId; use crate::domain::course_note_file::CourseNoteFileId; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct RagOutputId(RecordId); +/// Typed rag-output row id. A UUIDv7 minted by the process-wide monotonic +/// generator, so `id` order is mint order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct RagOutputId(Uuid); impl RagOutputId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: + /// Minted from the process-wide monotonic generator, not a random v4: /// a note's outputs list `id DESC` (newest first, /// [`list_for`](crate::db::rag_output::list_for)). pub fn generate() -> Self { - Self(RecordId::new(RAG_OUTPUT_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parse a wire key. A key that parses as no UUID — a malformed path + /// segment — reads as the nil id, which matches no row: exactly the 404 a + /// dangling record key produced under the old store, without turning a + /// typo into a panic. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(RAG_OUTPUT_TABLE, key)) + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The hyphenated wire form. + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct RagOutput { pub(crate) id: RagOutputId, pub(crate) course_note: CourseNoteId, @@ -61,10 +62,11 @@ pub struct RagOutput { /// ([`delete_with_source`](crate::db::rag_output::delete_with_source)) /// rather than leaving an output citing a file that no longer exists. pub(crate) sources: Vec, - /// The service's answer, stored verbatim. Opaque to the backend — it is a - /// service-owned shape, so this side neither validates nor interprets it, - /// beyond it having to be a JSON **object** (the stored column is one). - pub(crate) payload: Value, + /// The service's answer, stored verbatim in a JSONB column. Opaque to the + /// backend — it is a service-owned shape, so this side neither validates + /// nor interprets it, beyond it having to be a JSON **object** (the + /// stored column is one). + pub(crate) payload: Json, pub(crate) generated_at: Timestamp, } @@ -86,7 +88,7 @@ impl RagOutput { } pub fn get_payload(&self) -> &Value { - &self.payload + &self.payload.0 } pub fn get_generated_at(&self) -> Timestamp { diff --git a/src/domain/registration.rs b/src/domain/registration.rs index 4896976..cb9cce1 100644 --- a/src/domain/registration.rs +++ b/src/domain/registration.rs @@ -1,33 +1,48 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::REGISTRATION_TABLE; use crate::domain::event::EventId; use crate::domain::user::UserId; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct RegistrationId(RecordId); +/// The (event, user) pair — the table's natural composite primary key. The +/// same pair always maps to the same row, so one-row-per-pair holds by +/// construction (the enrollment trick) even if a write ever slipped past the +/// register lock. UUID strings carry only `-`, so `_` is an unambiguous +/// joiner. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RegistrationId { + event: EventId, + user: UserId, +} impl RegistrationId { - /// A deterministic id for the (event, user) pair — the same pair always - /// maps to the same record id, so one-row-per-pair holds by construction - /// (the enrollment trick) even if a write ever slipped past the register - /// lock. ULID keys are alphanumeric, so `_` is unambiguous. pub fn composite(event: &EventId, user: &UserId) -> Self { - Self(RecordId::new( - REGISTRATION_TABLE, - format!("{}_{}", event.key(), user.key()), - )) + Self { + event: *event, + user: *user, + } } - pub fn record(&self) -> RecordId { - self.0.clone() + /// Parse the `{event}_{user}` wire form. A key that parses as no pair + /// reads as the nil pair, which matches no row — exactly the 404 a + /// dangling composite key produced under the old store, without turning a + /// typo into a panic. + pub fn from_key(key: &str) -> Self { + let (event, user) = key.rsplit_once('_').unwrap_or(("", "")); + Self { + event: EventId::from_key(event), + user: UserId::from_key(user), + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The `{event}_{user}` wire form. + pub fn key(&self) -> String { + format!("{}_{}", self.event.key(), self.user.key()) + } + + pub fn event(&self) -> EventId { + self.event + } + + pub fn user(&self) -> UserId { + self.user } } @@ -35,19 +50,15 @@ impl RegistrationId { /// event's roster: whoever holds a row is expected (and markable), everyone /// else is not. Rows survive audience changes inertly — switching the event /// away from the registration kind hides them without deleting them. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Registration { - pub(crate) id: RegistrationId, pub(crate) event: EventId, + #[sqlx(rename = "app_user")] pub(crate) user: UserId, pub(crate) registered_by: UserId, } impl Registration { - pub fn get_id(&self) -> &RegistrationId { - &self.id - } - pub fn get_event(&self) -> &EventId { &self.event } @@ -65,7 +76,7 @@ impl Registration { // arm of [`crate::service::user::set_role`], so the seat comes back in // the same transaction as the role that invalidated it. The freeze it obeys // is [`crate::domain::event::Event::registration_capacity`]'s `Conflict` - // arm, re-spelled for SurrealQL as + // arm, re-spelled for the stored guard in // [`crate::constant::REGISTRATION_FROZEN_GUARD`] and held to it by // `event::tests::the_sql_freeze_guard_matches_the_rust_one`. } diff --git a/src/domain/role.rs b/src/domain/role.rs index 0e7a512..2e80a49 100644 --- a/src/domain/role.rs +++ b/src/domain/role.rs @@ -1,4 +1,4 @@ -use surrealdb::types::SurrealValue; +use sqlx::Type; use crate::constant::ROLES; use crate::error::ValidationError; @@ -20,12 +20,12 @@ use crate::error::ValidationError; /// exact `== Student` gate, so parents can't sit exams, enroll, or be marked on /// a roll call — they only read their own students' reports. /// -/// `#[surreal(untagged, rename_all = "lowercase")]` makes each variant serialize -/// to a bare lowercase string (`"student"`, `"teacher"`, …) instead of the -/// default object-wrapped form, so it stores in the `role` column's `TYPE string` -/// and round-trips straight back into the enum. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, SurrealValue)] -#[surreal(untagged, rename_all = "lowercase")] +/// [`Role`] derives [`sqlx::Type`] as a bare TEXT enum: each variant stores as +/// its lowercase name (`"student"`, `"teacher"`, …) and round-trips straight +/// back, which the `role` column's `CHECK` lists and every `role = 'teacher'` +/// filter spells. [`Role::as_str`] must stay in lockstep with it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Type)] +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] pub enum Role { Ai, Parent, @@ -92,7 +92,6 @@ impl Role { #[cfg(test)] mod tests { use super::*; - use surrealdb::types::Value; #[tokio::test] async fn hierarchy_orders_low_to_high() { @@ -167,14 +166,18 @@ mod tests { assert!(Role::try_from_str("").is_err()); } - #[tokio::test] - async fn surreal_value_is_a_plain_string() { - // The whole point of `untagged`: the stored value is a bare string, so a - // `TYPE string` column accepts it. Guard that the encoding never regresses. - for role in ROLES { - let value = role.into_value(); - assert_eq!(value, Value::String(role.as_str().to_string())); - assert_eq!(Role::from_value(value).unwrap(), role); + #[test] + fn sqlx_encodes_the_storage_form() { + // The whole point of the TEXT encoding: the stored value is the bare + // lowercase string, so the `role` column accepts it and every + // `role = 'teacher'` filter matches. Guard that the sqlx encoding + // never drifts from `as_str` — the CHECK constraint and the filters + // spell these same words. + let mut buf = sqlx::postgres::PgArgumentBuffer::default(); + for role in [Role::Ai, Role::Parent, Role::Student, Role::Teacher, Role::Manager, Role::Admin] { + buf.clear(); + sqlx::Encode::::encode_by_ref(&role, &mut buf); + assert_eq!(std::str::from_utf8(&buf).unwrap(), role.as_str()); } } } diff --git a/src/domain/session.rs b/src/domain/session.rs index 3fe4d51..fe37ad2 100644 --- a/src/domain/session.rs +++ b/src/domain/session.rs @@ -1,34 +1,32 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; +use uuid::Uuid; -use crate::constant::SESSION_TABLE; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct SessionId(RecordId); +/// Typed session row id. A UUIDv7 minted by the process-wide monotonic +/// generator. (The table is `user_session` in PostgreSQL — the Rust type +/// keeps its name.) +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct SessionId(Uuid); impl SessionId { pub fn generate() -> Self { - Self(RecordId::new(SESSION_TABLE, Ulid::generate().to_string())) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(next_uuid()) } + /// The hyphenated wire form. #[allow(dead_code)] - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + pub fn key(&self) -> String { + self.0.to_string() } } /// A random, opaque session token (64 hex chars). -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct SessionToken(String); impl SessionToken { @@ -44,9 +42,10 @@ impl SessionToken { } /// Fields are crate-visible: [`crate::db::session`] mints the rows on login. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Session { pub(crate) id: SessionId, + #[sqlx(rename = "app_user")] pub(crate) user: UserId, pub(crate) token: SessionToken, pub(crate) expires_at: Timestamp, diff --git a/src/domain/session_attendance.rs b/src/domain/session_attendance.rs index 0d90b6d..b0b6ee7 100644 --- a/src/domain/session_attendance.rs +++ b/src/domain/session_attendance.rs @@ -1,35 +1,49 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::SESSION_ATTENDANCE_TABLE; use crate::domain::attendance::AttendanceStatus; use crate::domain::course::CourseId; use crate::domain::course_session::CourseSessionId; use crate::domain::user::UserId; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct SessionAttendanceId(RecordId); +/// The (session, user) pair — the table's natural composite primary key. +/// Because the same pair always maps to the same row, marking is a single +/// atomic upsert with no find-then-insert race, and one-row-per-pair holds by +/// construction. UUID strings carry only `-`, so `_` is an unambiguous joiner. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SessionAttendanceId { + session: CourseSessionId, + user: UserId, +} impl SessionAttendanceId { - /// A deterministic id for the (session, user) pair. Because the same pair - /// always maps to the same record id, marking is a single atomic UPSERT with - /// no find-then-insert race, and one-row-per-pair holds by construction. - /// ULID keys are alphanumeric, so `_` is an unambiguous joiner. pub fn composite(session: &CourseSessionId, user: &UserId) -> Self { - Self(RecordId::new( - SESSION_ATTENDANCE_TABLE, - format!("{}_{}", session.key(), user.key()), - )) + Self { + session: *session, + user: *user, + } } - pub fn record(&self) -> RecordId { - self.0.clone() + /// Parse the `{session}_{user}` wire form. A key that parses as no pair + /// reads as the nil pair, which matches no row — exactly the 404 a + /// dangling composite key produced under the old store, without turning a + /// typo into a panic. + pub fn from_key(key: &str) -> Self { + let (session, user) = key.rsplit_once('_').unwrap_or(("", "")); + Self { + session: CourseSessionId::from_key(session), + user: UserId::from_key(user), + } } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The `{session}_{user}` wire form. + pub fn key(&self) -> String { + format!("{}_{}", self.session.key(), self.user.key()) + } + + pub fn session(&self) -> CourseSessionId { + self.session + } + + pub fn user(&self) -> UserId { + self.user } } @@ -51,22 +65,18 @@ pub(crate) fn counts_as_attended(status: &AttendanceStatus) -> bool { /// One person's roll-call state for one lesson. `course` is denormalized from /// the session so the per-course attendance report is a single indexed query -/// (`WHERE user = $u`) with no join. -#[derive(Debug, Clone, SurrealValue)] +/// (`WHERE app_user = $u`) with no join. +#[derive(Debug, Clone, sqlx::FromRow)] pub struct SessionAttendance { - pub(crate) id: SessionAttendanceId, pub(crate) session: CourseSessionId, pub(crate) course: CourseId, + #[sqlx(rename = "app_user")] pub(crate) user: UserId, pub(crate) status: AttendanceStatus, pub(crate) marked_by: UserId, } impl SessionAttendance { - pub fn get_id(&self) -> &SessionAttendanceId { - &self.id - } - pub fn get_session(&self) -> &CourseSessionId { &self.session } diff --git a/src/domain/settings.rs b/src/domain/settings.rs index 059da69..5334e1e 100644 --- a/src/domain/settings.rs +++ b/src/domain/settings.rs @@ -11,7 +11,9 @@ //! without a backfill (backfills crash boots — `DEFAULT` never rescues //! existing rows, and `UPDATE` re-validates whole records). -use surrealdb::types::{RecordId, SurrealValue}; + +use serde::{Deserialize, Serialize}; +use sqlx::types::Json; use crate::constant::{ DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_DIETARY_TAGS, @@ -21,7 +23,7 @@ use crate::constant::{ MAX_MAX_CHATBOT_THREADS, MAX_MAX_FILE_BYTES, MAX_MEAL_CANCEL_CUTOFF_MINUTES, MAX_MEAL_SERVING_MINUTE, MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN, - MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES, SETTINGS_KEY, SETTINGS_TABLE, + MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES, SETTINGS_KEY, }; use crate::domain::text_fold; use crate::error::ValidationError; @@ -30,7 +32,7 @@ use crate::error::ValidationError; /// how many times an exam of that kind counts into its course's average. /// Weight lives here, not on the exam — reweighting a kind reweights every /// exam of that kind at once. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ExamKindDef { name: String, weight: i64, @@ -77,7 +79,7 @@ impl ExamKindDef { /// `540` (09:00) for a meal served at noon locally. `None` — every slot /// written before the field existed — falls back to midnight UTC, the old /// behaviour. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct MealSlotDef { name: String, serving_minute: Option, @@ -152,7 +154,7 @@ impl MealSlotDef { /// One grade-display band: marks at or above `min` (and below the next band's /// `min`) render as `label`. Display only — storage and averaging stay numeric. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct GradeBand { min: i64, label: String, @@ -192,12 +194,12 @@ impl GradeBand { /// like every other entity, an existing `Settings` is always internally /// consistent). Fields are crate-visible because [`crate::db::settings`] /// binds them directly in the compare-and-set guard. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Settings { - id: RecordId, - pub(crate) exam_kinds: Vec, + pub(crate) id: String, + pub(crate) exam_kinds: Json>, pub(crate) attendance_statuses: Vec, - pub(crate) grade_bands: Vec, + pub(crate) grade_bands: Json>, /// Per-file byte cap for note uploads. `None` = the row predates the /// field (or the defaults) — reads as `DEFAULT_MAX_FILE_BYTES`. pub(crate) max_file_bytes: Option, @@ -209,7 +211,7 @@ pub struct Settings { /// the columns are `option<…>`, never `DEFAULT []`: `save_if_unchanged` /// writes the whole row, so a field this struct did not carry would coerce /// to `NONE` and abort the transaction. - pub(crate) meal_slots: Option>, + pub(crate) meal_slots: Option>>, pub(crate) dietary_tags: Option>, /// Minutes before a meal at which booking *and* cancelling close. One knob /// for both deadlines; `None` = no cutoff at all, which is also what an @@ -236,8 +238,9 @@ pub struct SettingsParams { } impl Settings { - pub(crate) fn record_id() -> RecordId { - RecordId::new(SETTINGS_TABLE, SETTINGS_KEY) + /// The singleton row's key (`settings.id` is `TEXT PRIMARY KEY`). + pub(crate) fn record_id() -> String { + SETTINGS_KEY.to_string() } /// The out-of-the-box policy — mirrors the constants that were previously @@ -245,14 +248,16 @@ impl Settings { pub fn defaults() -> Self { Self { id: Self::record_id(), - exam_kinds: DEFAULT_EXAM_KINDS - .map(|(name, weight)| ExamKindDef { - name: name.to_string(), - weight, - }) - .to_vec(), + exam_kinds: Json( + DEFAULT_EXAM_KINDS + .map(|(name, weight)| ExamKindDef { + name: name.to_string(), + weight, + }) + .to_vec(), + ), attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(), - grade_bands: Vec::new(), + grade_bands: Json(Vec::new()), max_file_bytes: None, chatbot_history_turns: None, max_chatbot_threads: None, @@ -267,9 +272,9 @@ impl Settings { /// value it currently reads as. pub fn params(&self) -> SettingsParams { SettingsParams { - exam_kinds: self.exam_kinds.clone(), + exam_kinds: self.exam_kinds.0.clone(), attendance_statuses: self.attendance_statuses.clone(), - grade_bands: self.grade_bands.clone(), + grade_bands: self.grade_bands.0.clone(), max_file_bytes: self.get_max_file_bytes(), chatbot_history_turns: self.get_chatbot_history_turns(), max_chatbot_threads: self.get_max_chatbot_threads(), @@ -396,21 +401,21 @@ impl Settings { Ok(Self { id: Self::record_id(), - exam_kinds, + exam_kinds: Json(exam_kinds), attendance_statuses, - grade_bands, + grade_bands: Json(grade_bands), max_file_bytes: Some(max_file_bytes), chatbot_history_turns: Some(chatbot_history_turns), max_chatbot_threads: Some(max_chatbot_threads), max_chatbot_message_len: Some(max_chatbot_message_len), - meal_slots: Some(meal_slots), + meal_slots: Some(Json(meal_slots)), dietary_tags: Some(dietary_tags), meal_cancel_cutoff_minutes, }) } pub fn get_exam_kinds(&self) -> &[ExamKindDef] { - &self.exam_kinds + &self.exam_kinds.0 } /// The weight of the kind named `kind` (exact match, like kind @@ -419,6 +424,7 @@ impl Settings { /// (settings edits never rewrite history), so it must still count. pub fn exam_kind_weight(&self, kind: &str) -> Option { self.exam_kinds + .0 .iter() .find(|def| def.get_name() == kind) .map(ExamKindDef::get_weight) @@ -429,7 +435,7 @@ impl Settings { } pub fn get_grade_bands(&self) -> &[GradeBand] { - &self.grade_bands + &self.grade_bands.0 } /// The per-file upload cap in bytes; the built-in default while the @@ -463,7 +469,7 @@ impl Settings { /// one (including rows saved before the field existed). An explicitly /// stored empty list stays empty — that is "no meal program", not "unset". pub fn get_meal_slots(&self) -> Vec { - self.meal_slots.clone().unwrap_or_else(|| { + self.meal_slots.as_ref().map(|slots| slots.0.clone()).unwrap_or_else(|| { DEFAULT_MEAL_SLOTS .map(|name| MealSlotDef { name: name.to_string(), @@ -497,6 +503,7 @@ impl Settings { /// `f64` so course averages label the same way plain marks do. pub fn grade_label(&self, mark: f64) -> Option<&str> { self.grade_bands + .0 .iter() .filter(|band| band.get_min() as f64 <= mark) .max_by_key(|band| band.get_min()) diff --git a/src/domain/solution.rs b/src/domain/solution.rs index e7756b0..56ae2e2 100644 --- a/src/domain/solution.rs +++ b/src/domain/solution.rs @@ -1,17 +1,7 @@ -//! A solution offered on an approved pool question (see -//! [`crate::domain::pool_question`]). Anyone in the school — student or staff -//! — may offer one; rows list oldest first, reading as a discussion thread. -//! Solutions die with their question (the question delete cascades here). -//! Like a question, a solution may carry one photo (`image_*` metadata on the -//! row, bytes on disk under a server-generated ULID) — but unlike a question -//! it has no moderation state, so its author may edit the body and swap the -//! photo at any time; there is nothing to freeze. The queries live in -//! [`crate::db::solution`], the funnels in [`crate::service::solution`]. - -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::{MAX_SOLUTION_BODY_LEN, SOLUTION_TABLE}; -use crate::domain::monotonic_id::next_ulid; +use uuid::Uuid; + +use crate::constant::MAX_SOLUTION_BODY_LEN; +use crate::domain::monotonic_id::next_uuid; use crate::domain::note_file::FileContentType; use crate::domain::pool_question::PoolQuestionId; use crate::domain::timestamp::Timestamp; @@ -19,35 +9,37 @@ use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::validate_required; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct SolutionId(RecordId); +/// Typed solution row id. A UUIDv7 minted by the process-wide monotonic +/// generator, so `id` order is mint order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct SolutionId(Uuid); impl SolutionId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: + /// Minted from the process-wide monotonic generator, not a random v4: /// solutions sort `offered_at ASC, id ASC` and the id *is* the tie-break /// ([`crate::db::solution::list_for`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(SOLUTION_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parse a wire key. A key that parses as no UUID — a malformed path + /// segment — reads as the nil id, which matches no row: exactly the 404 a + /// dangling record key produced under the old store, without turning a + /// typo into a panic. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(SOLUTION_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The hyphenated wire form. + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct SolutionBody(String); impl SolutionBody { @@ -61,15 +53,15 @@ impl SolutionBody { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Solution { pub(crate) id: SolutionId, pub(crate) question: PoolQuestionId, pub(crate) author: UserId, pub(crate) body: SolutionBody, pub(crate) offered_at: Timestamp, - /// The photo's on-disk blob name — a fresh ULID every upload; `None` when - /// the solution carries no image. + /// The photo's on-disk blob name — a fresh server-generated id every + /// upload; `None` when the solution carries no image. pub(crate) image_file: Option, pub(crate) image_content_type: Option, pub(crate) image_size: Option, diff --git a/src/domain/subject.rs b/src/domain/subject.rs index 4e8be6e..ce3690a 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -1,40 +1,43 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use sqlx::Type; +use uuid::Uuid; -use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN, SUBJECT_TABLE}; +use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN}; use crate::domain::course::CourseId; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::error::ValidationError; use crate::validate::{validate_optional, validate_required}; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct SubjectId(RecordId); +/// Typed subject row id. A UUIDv7 minted by the process-wide monotonic +/// generator, so `id` order is mint order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] +#[sqlx(transparent)] +pub struct SubjectId(Uuid); impl SubjectId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: the + /// Minted from the process-wide monotonic generator, not a random v4: the /// id *is* the curriculum's order ([`crate::db::subject::list_for_course`] /// sorts `id ASC`), and a random low half scrambles a burst of saves that /// lands inside one millisecond. pub fn generate() -> Self { - Self(RecordId::new(SUBJECT_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parse a wire key. A key that parses as no UUID — a malformed path + /// segment — reads as the nil id, which matches no row: exactly the 404 a + /// dangling record key produced under the old store, without turning a + /// typo into a panic. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(SUBJECT_TABLE, key)) + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The hyphenated wire form. + pub fn key(&self) -> String { + self.0.to_string() } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, Type)] +#[sqlx(transparent)] pub struct SubjectName(String); impl SubjectName { @@ -48,7 +51,8 @@ impl SubjectName { } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, Type)] +#[sqlx(transparent)] pub struct SubjectDescription(String); impl SubjectDescription { @@ -66,7 +70,7 @@ impl SubjectDescription { /// a subject of its exam's course, so results can later be read per topic. The /// course link is fixed at creation — a subject is course content, and moving /// it would strand the questions tagged with it. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Subject { pub(crate) id: SubjectId, pub(crate) course: CourseId, @@ -98,13 +102,13 @@ mod tests { /// A teacher entering a curriculum gets it back in the order they typed it: /// `list_for_course` sorts `id ASC`, so the ids minted inside one - /// millisecond have to sort in mint order. Revert `generate` to - /// `Ulid::generate()` and this fails — the low 80 bits are redrawn per id, so a - /// same-tick burst comes out shuffled. + /// millisecond have to sort in mint order. Revert `generate` to a random + /// v4 and this fails — the low bits are redrawn per id, so a same-tick + /// burst comes out shuffled. #[tokio::test] async fn ids_sort_in_creation_order() { let ids: Vec = (0..500) - .map(|_| SubjectId::generate().key().to_string()) + .map(|_| SubjectId::generate().key()) .collect(); let mut sorted = ids.clone(); sorted.sort(); diff --git a/src/domain/term.rs b/src/domain/term.rs index 0b393d3..7e1bec8 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -1,44 +1,38 @@ -//! An academic term — semester, trimester, quarter, whatever this school -//! runs; the structure is just rows, so it needs no code change per school. -//! Courses may link to one term. -//! -//! Terms are calendar structure, not schedules: a school adopting the app -//! mid-year legitimately creates a term that already started, so the no-past -//! rule that guards exams/lessons/events deliberately does not apply here. - -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; - -use crate::constant::{MAX_TERM_NAME_LEN, TERM_TABLE}; -use crate::domain::monotonic_id::next_ulid; +use sqlx::Type; +use uuid::Uuid; + +use crate::constant::MAX_TERM_NAME_LEN; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ValidationError}; use crate::validate::validate_required; -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct TermId(RecordId); +/// Typed term row id. A UUIDv7 minted by the process-wide monotonic +/// generator, so `id` order is mint order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)] +#[sqlx(transparent)] +pub struct TermId(Uuid); impl TermId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: + /// Minted from the process-wide monotonic generator, not a random v4: /// terms sort `starts_at DESC, id DESC` and the id breaks the tie between /// two terms starting at the same instant, /// and a random low half sorts arbitrarily inside one millisecond. pub fn generate() -> Self { - Self(RecordId::new(TERM_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parse a wire key. A key that parses as no UUID — a malformed path + /// segment — reads as the nil id, which matches no row: exactly the 404 a + /// dangling record key produced under the old store, without turning a + /// typo into a panic. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(TERM_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The hyphenated wire form. + pub fn key(&self) -> String { + self.0.to_string() } } @@ -69,18 +63,16 @@ pub fn archived_error() -> AppError { pub fn ref_move( current: Option<&TermId>, patch: &Option>, -) -> (Option, Option) { +) -> (Option, Option) { match patch { None => (None, None), Some(next) if next.as_ref() == current => (None, None), - Some(next) => ( - next.as_ref().map(TermId::record), - current.map(TermId::record), - ), + Some(next) => (*next, current.copied()), } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct TermName(String); impl TermName { @@ -96,16 +88,15 @@ impl TermName { /// One term on the school's academic calendar. Both ends are required — a /// term is a date range by definition. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Term { pub(crate) id: TermId, pub(crate) name: TermName, pub(crate) starts_at: Timestamp, pub(crate) ends_at: Timestamp, - /// When a manager archived this term; `None` = open. `#[surreal(default)]` - /// for the same reason `BankQuestion::subject` has one: rows written before - /// the column existed still decode, as open terms. - #[surreal(default)] + /// When a manager archived this term; `None` = open. The column is + /// nullable, so a term that predates archiving reads exactly like an + /// open one. pub(crate) archived_at: Option, } diff --git a/src/domain/text_fold.rs b/src/domain/text_fold.rs index 53df0c0..772ab26 100644 --- a/src/domain/text_fold.rs +++ b/src/domain/text_fold.rs @@ -8,12 +8,12 @@ //! conflate distinct letters (`tur` ≠ `tür`, `kir` ≠ `kır`). //! //! The search fold is shared by the needle (Rust side) and the column -//! (SurrealQL side) so the two can never disagree. +//! (PostgreSQL side) so the two can never disagree. //! -//! Rust's `to_lowercase` and SurrealQL's `string::lowercase` are both -//! locale-invariant: Turkish `İ` (U+0130) lowercases to `i` + U+0307 -//! (combining dot above), so plain `string::lowercase(text) CONTAINS $q` never -//! matched `İSTANBUL` for a teacher who typed `istanbul`. Folding strips that +//! Rust's `to_lowercase` and PostgreSQL's `lower()` are both +//! locale-invariant here: Turkish `İ` (U+0130) lowercases to `i` + U+0307 +//! (combining dot above), so plain `lower(text) LIKE '%q%'` never matched +//! `İSTANBUL` for a teacher who typed `istanbul`. Folding strips that //! leftover dot and maps the Turkish letters onto their ASCII base, which also //! makes the search work in both directions (`istanbul` ↔ `İSTANBUL`, //! `ıgdır` ↔ `Iğdır`). @@ -31,13 +31,13 @@ pub fn search_fold(text: &str) -> String { folded } -/// The same folding as a SurrealQL expression over `column`, for use inside a -/// `WHERE`. `column` is always a literal field name we wrote — never user +/// The same folding as a PostgreSQL expression over `column`, for use inside +/// a `WHERE`. `column` is always a literal field name we wrote — never user /// input. pub fn search_fold_sql(column: &str) -> String { - let mut expr = format!("string::lowercase({column})"); + let mut expr = format!("lower({column})"); for (from, to) in TEXT_FOLD_REPLACEMENTS { - expr = format!("string::replace({expr}, '{from}', '{to}')"); + expr = format!("replace({expr}, '{from}', '{to}')"); } expr } @@ -89,16 +89,37 @@ mod tests { } /// `search_fold` and `search_fold_sql` are one table, two consumers — the - /// SQL must emit a `string::replace` for every rule, or the column and the + /// SQL must emit a `replace()` for every rule, or the column and the /// needle drift apart and a search silently stops matching. #[test] fn sql_covers_every_replacement() { let sql = search_fold_sql("name"); assert_eq!( - sql.matches("string::replace").count(), + sql.matches("replace(").count(), TEXT_FOLD_REPLACEMENTS.len(), - "one string::replace per rule" + "one replace() per rule" ); + // The base is PostgreSQL's locale-invariant lower(), applied before + // any letter folding, over the exact column named. + assert!(sql.starts_with(&format!("lower({})", "name"))); + } + + /// The expression folds a sample exactly like the Rust side does: same + /// table, same order. (The old engine-checked variant of this test ran + /// the SQL against a live store; the string shape above plus this fold + /// pin the generator, and the live round-trip belongs to the integration + /// suite.) + #[test] + fn sql_folding_mirrors_rust_folding_rules() { + let sql = search_fold_sql("name"); + for (from, to) in TEXT_FOLD_REPLACEMENTS { + assert!( + sql.contains(&format!("replace(")) + && sql.contains(&format!("'{from}', '{to}'")), + "rule {from} -> {to} missing from the emitted expression" + ); + assert_eq!(search_fold(&from.to_string()), to); + } } /// The identity fold folds case (Turkish rules) and *nothing else* — the @@ -137,22 +158,4 @@ mod tests { // Decomposed `İ` (i + combining dot) is still plain `i`. assert_eq!(case_fold_tr("i\u{307}zin"), "izin"); } - - /// The SQL side must fold a literal exactly like the Rust side does, or the - /// needle and the column disagree again. - #[tokio::test] - async fn sql_folding_matches_rust_folding() { - let db = crate::database::init_mem().await.unwrap(); - for sample in ["İSTANBUL", "Iğdır", "ÇÖZÜM", "istanbul"] { - let mut result = db - .query(format!("RETURN {};", search_fold_sql("$text"))) - .bind(("text", sample.to_string())) - .await - .unwrap() - .check() - .unwrap(); - let got = result.take::>(0).unwrap().unwrap(); - assert_eq!(got, search_fold(sample), "sql fold disagrees for {sample}"); - } - } } diff --git a/src/domain/timestamp.rs b/src/domain/timestamp.rs index b93460f..a28eea7 100644 --- a/src/domain/timestamp.rs +++ b/src/domain/timestamp.rs @@ -1,9 +1,9 @@ //! Time policy for the whole backend, in one place. //! -//! - Every instant is a **unix-millisecond `i64`, always UTC** — stored as an -//! `int`, sent over the wire as a plain number. No timezone is ever stored -//! or parsed, so the server's `TZ`, the client's locale, and the container's -//! clock configuration cannot change what a value means. +//! - Every instant is a **unix-millisecond `i64`, always UTC** — stored as a +//! `BIGINT`, sent over the wire as a plain number. No timezone is ever +//! stored or parsed, so the server's `TZ`, the client's locale, and the +//! container's clock configuration cannot change what a value means. //! - [`Timestamp::now`] is the **only wall-clock read in the codebase**. The //! clippy `disallowed-methods` config (clippy.toml) rejects every other //! `now()` source (`chrono::Utc/Local`, `SystemTime`, `time::OffsetDateTime`) @@ -12,7 +12,6 @@ //! `Instant` clock instead, which NTP adjustments cannot move backwards. use chrono::Datelike; -use surrealdb::types::SurrealValue; use crate::constant::MILLIS_PER_DAY; use crate::error::{AppError, ValidationError}; @@ -27,8 +26,11 @@ pub(crate) fn range_error() -> AppError { }) } -/// A unix-millisecond instant (UTC by construction). Stored as an `int`. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, SurrealValue)] +/// A unix-millisecond instant (UTC by construction). Stored as a `BIGINT`. +/// Also serializes as its bare number: the fee plan's installments ride the +/// row as JSON, and a due date must stay a plain millisecond count there too. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, sqlx::Type, serde::Serialize, serde::Deserialize)] +#[sqlx(transparent)] pub struct Timestamp(i64); impl Timestamp { @@ -160,4 +162,17 @@ mod tests { // boundary crossing between them would still satisfy `<=`. assert!(today <= from_millis); } + + /// JSON is part of the storage contract now (embedded installments ride a + /// JSONB column): the instant must stay a bare millisecond number, never + /// a string or an object. + #[test] + fn json_form_is_the_bare_millisecond_number() { + assert_eq!( + serde_json::to_value(Timestamp::from_millis(1_700_000_000_000)).unwrap(), + serde_json::json!(1_700_000_000_000) + ); + let back: Timestamp = serde_json::from_value(serde_json::json!(1_700_000_000_000)).unwrap(); + assert_eq!(back.as_millis(), 1_700_000_000_000); + } } diff --git a/src/domain/user.rs b/src/domain/user.rs index 8bcd236..fa06ee1 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -7,10 +7,10 @@ use std::sync::OnceLock; use argon2::password_hash::phc::PasswordHash as PhcHash; use argon2::{Argon2, PasswordHasher, PasswordVerifier}; -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use uuid::Uuid; -use crate::constant::{AI_PRINCIPAL_KEY, DECOY_PASSWORD, USER_TABLE}; -use crate::domain::monotonic_id::next_ulid; +use crate::constant::{AI_PRINCIPAL_KEY, DECOY_PASSWORD}; +use crate::domain::monotonic_id::next_uuid; use crate::domain::note_file::FileContentType; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; @@ -18,33 +18,34 @@ use crate::domain::role::Role; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_password, validate_username}; -/// Typed user record id (`user:`). -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct UserId(RecordId); +/// Typed user row id. A UUIDv7 minted by the process-wide monotonic +/// generator, so `id` order is mint order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct UserId(Uuid); impl UserId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: - /// users list `id DESC` (newest first, [`crate::db::user::list_all`]) and page by - /// offset over that order, and a random low half scrambles rows minted in - /// the same millisecond. Not a secret: the session token is separate - /// (32-byte CSPRNG, `web::auth`), so id order carries no authority. + /// Minted from the process-wide monotonic generator, not a random v4: + /// users list `id DESC` (newest first, [`crate::db::user::list_all`]) and + /// page by offset over that order, and a random low half scrambles rows + /// minted in the same millisecond. Not a secret: the session token is + /// separate (32-byte CSPRNG, `web::auth`), so id order carries no + /// authority. pub fn generate() -> Self { - Self(RecordId::new(USER_TABLE, next_ulid().to_string())) + Self(next_uuid()) } + /// Parse a wire key. A key that parses as no UUID — a malformed path + /// segment — reads as the nil id, which matches no row: exactly the 404 a + /// dangling record key produced under the old store, without turning a + /// typo into a panic. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(USER_TABLE, key)) + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) } - pub fn record(&self) -> RecordId { - self.0.clone() - } - - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The hyphenated wire form. + pub fn key(&self) -> String { + self.0.to_string() } } @@ -52,7 +53,8 @@ impl UserId { /// canonicalizes the value: the stored string is trimmed, since the unique /// index and the login lookup key on it — `"ali "` must be `"ali"`, not a /// second, visually identical account. -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] pub struct Username(String); impl Username { @@ -116,7 +118,8 @@ impl Password { } /// An argon2 PHC hash, safe to persist. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::Type)] +#[sqlx(transparent)] pub struct PasswordHash(String); /// A process-wide decoy hash, computed once on first use. Verifying against it @@ -189,7 +192,7 @@ impl PasswordHash { } } -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] /// Fields are crate-visible: [`crate::db::user`] mints rows and the role /// cascade reads the id, exactly as the other split domains do. pub struct User { @@ -226,15 +229,14 @@ pub struct User { impl User { /// The in-memory principal an AI service acts as over the QUIC bridge. /// - /// Never written to the database, and never read back from one: the id key - /// is the literal `"ai_service"`, which no minted row can collide with - /// ([`UserId::generate`] only ever produces ULIDs). Every other field is - /// inert — the empty password hash parses as no argon2 hash, so it verifies - /// against nothing, and [`Role::Ai`] clears no `at_least` bar and fails - /// every exact `== Role::Student` / `== Role::Parent` gate. + /// Never written to the database, and never read back from one: the id is + /// the nil UUID, which no minted id (always a v7) can ever equal. Every + /// other field is inert — the empty password hash parses as no argon2 hash, + /// so it verifies against nothing, and [`Role::Ai`] clears no `at_least` + /// bar and fails every exact `== Role::Student` / `== Role::Parent` gate. pub(crate) fn ai_principal() -> User { User { - id: UserId::from_key(AI_PRINCIPAL_KEY), + id: UserId(Uuid::nil()), username: Username(AI_PRINCIPAL_KEY.to_string()), password_hash: PasswordHash(String::new()), role: Role::Ai, @@ -374,7 +376,7 @@ mod tests { #[tokio::test] async fn user_id_key_roundtrips() { let id = UserId::generate(); - let key = id.key().to_string(); + let key = id.key(); assert!(!key.is_empty()); assert_eq!(UserId::from_key(&key).key(), key); } diff --git a/src/domain/work_entry.rs b/src/domain/work_entry.rs index 549af8c..e390eb6 100644 --- a/src/domain/work_entry.rs +++ b/src/domain/work_entry.rs @@ -1,58 +1,34 @@ -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use uuid::Uuid; -use crate::constant::WORK_ENTRY_TABLE; -use crate::domain::monotonic_id::next_ulid; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; -/// The one spelling of "this stint is inverted", shared by the handler's -/// pre-flight check and the write-time `WHERE` guard that re-makes it against -/// the stored row. -pub(crate) fn out_before_in_error() -> AppError { - AppError::Validation(ValidationError::Invalid { - field: "check_out", - reason: "must be at or after check_in", - }) -} - -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct WorkEntryId(RecordId); +/// Typed work-entry row id. A UUIDv7 minted by the process-wide monotonic +/// generator, so `id` order is mint order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct WorkEntryId(Uuid); impl WorkEntryId { - /// Minted from the process-wide monotonic generator, not `Ulid::generate()`: + /// Minted from the process-wide monotonic generator, not a random v4: /// the log sorts `check_in DESC, id DESC` and the id breaks the tie between - /// two stints checked in at the same instant. The `open_` key below never - /// ties with itself (one open stint per user), so it needs no ordering. + /// two stints checked in at the same instant. pub fn generate() -> Self { - Self(RecordId::new(WORK_ENTRY_TABLE, next_ulid().to_string())) - } - - /// The deterministic id of `user`'s *open* entry. At most one open stint - /// per user holds by construction: checking in is a single `INSERT IGNORE` - /// on this id (atomic — a second check-in changes nothing), and checking - /// out atomically takes the row and re-files it under a ULID id. - /// `open_` cannot collide with a ULID key (ULIDs are bare alphanumerics). - pub fn open_for(user: &UserId) -> Self { - Self(RecordId::new( - WORK_ENTRY_TABLE, - format!("open_{}", user.key()), - )) + Self(next_uuid()) } + /// Parse a wire key. A key that parses as no UUID — a malformed path + /// segment — reads as the nil id, which matches no row: exactly the 404 a + /// dangling record key produced under the old store, without turning a + /// typo into a panic. pub fn from_key(key: &str) -> Self { - Self(RecordId::new(WORK_ENTRY_TABLE, key)) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) } - pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + /// The hyphenated wire form. + pub fn key(&self) -> String { + self.0.to_string() } } @@ -60,9 +36,15 @@ impl WorkEntryId { /// `check_out` once closed. The wall clock is read server-side only — a /// client can never supply its own instants (managers correct closed entries /// through an explicit endpoint instead). -#[derive(Debug, Clone, SurrealValue)] +/// +/// "At most one open stint per staff member" is no longer carried by a +/// deterministic key: it is a partial unique index on the table +/// (`work_entry_open`) over rows whose `check_out` is NULL, so the database +/// itself refuses a second check-in. +#[derive(Debug, Clone, sqlx::FromRow)] pub struct WorkEntry { pub(crate) id: WorkEntryId, + #[sqlx(rename = "app_user")] pub(crate) user: UserId, pub(crate) check_in: Timestamp, pub(crate) check_out: Option, diff --git a/src/error.rs b/src/error.rs index dd3ab70..f457e4c 100644 --- a/src/error.rs +++ b/src/error.rs @@ -93,48 +93,46 @@ pub enum AppError { #[error("too many requests")] TooManyRequests { retry_after_secs: u64 }, #[error("database error")] - Db(#[source] surrealdb::Error), - /// The database WebSocket dropped and is mid-reconnect. Covers a query in - /// flight when the socket died (the SDK fails it as a connection error) - /// and a query racing the SDK's replay of session state (signin, - /// namespace), which the server refuses before execution. Transient, - /// self-healing, retryable. + Db(#[source] sqlx::Error), + /// The pool refused before the statement ran: the pool timed out waiting + /// for a connection, was closed, or TLS to the server failed to come up. + /// Nothing executed, so a retry is safe. Transient, self-healing, + /// retryable. #[error("database unavailable")] DbUnavailable, - /// The request outran [`crate::constant::REQUEST_TIMEOUT_SECS`], which in - /// practice means it reached the database in the window between the socket - /// dying and the keepalive noticing, and got parked in the SDK's queue. + /// The request outran [`crate::constant::REQUEST_TIMEOUT_SECS`], or the + /// connection it rode died mid-flight (Postgres reports that as an I/O + /// error, not a verdict). /// - /// Deliberately NOT `DbUnavailable`: that one promises the query was - /// refused before execution, so a retry is safe. A parked query is still - /// queued and *does* execute once the socket heals (verified: pings - /// abandoned during an outage all fire on reconnect), so retrying can - /// apply the same write twice. Same 503, honest message. + /// Deliberately NOT `DbUnavailable`: that one promises the statement was + /// refused before it executed, so a retry is safe. A request that died on + /// the wire may still have applied server-side (the commit can race the + /// connection dropping), so retrying can apply the same write twice. + /// Same 503, honest message. #[error("request timed out")] DbTimeout, #[error("internal error: {0}")] Internal(String), } -/// Is this database error a query refused during the SDK's post-reconnect -/// session replay? Two signatures, matched narrowly: "Specify a namespace" -/// (signin replayed, namespace not yet) and "Anonymous access not allowed" -/// (signin not yet). The backend signs in as root, so neither can be a real -/// authorization verdict — but a bare "Not enough permissions" could be, so -/// that alone must never match. -pub(crate) fn is_session_replay_error(message: &str) -> bool { - message.contains("Specify a namespace") || message.contains("Anonymous access not allowed") -} -impl From for AppError { - fn from(e: surrealdb::Error) -> Self { - // `is_connection()`: the SDK's own verdict that the socket itself - // failed ("Connection reset", "WebSocket error: ..."). Structurally - // distinct from query/permission errors, so it can't misfile one. - if e.is_connection() || is_session_replay_error(&e.to_string()) { - AppError::DbUnavailable - } else { - AppError::Db(e) +impl From for AppError { + fn from(e: sqlx::Error) -> Self { + match e { + // A `fetch_one` that found nothing is the caller's 404, not a 500. + sqlx::Error::RowNotFound => AppError::NotFound, + // Pool problems refuse on the acquire path: nothing was queued, + // let alone executed, so a retry cannot double-apply a write. + sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed | sqlx::Error::Tls(_) => { + AppError::DbUnavailable + } + // A connection that died under a request. The statement may or + // may not have applied — the honest, retry-unsafe 503. + sqlx::Error::Io(_) => AppError::DbTimeout, + // Everything else is a verdict (or a bug) the server returned — + // refusals included; the helpers in [`crate::database`] read the + // SQLSTATE off it. + _ => AppError::Db(e), } } } @@ -291,26 +289,6 @@ impl AppError { mod tests { use super::*; - #[test] - fn replay_signatures_classify_as_unavailable() { - // The two exact refusals a query racing the post-reconnect session - // replay gets, as they appear in the wire error. - assert!(is_session_replay_error("Specify a namespace to use")); - assert!(is_session_replay_error( - "Anonymous access not allowed: Not enough permissions to perform this action" - )); - } - - #[test] - fn connection_errors_classify_as_unavailable() { - // What the SDK fails an in-flight query with when the socket dies — - // same wire error `clear_pending_requests` produces. - let e = surrealdb::Error::connection( - "Connection reset".to_string(), - surrealdb::types::ConnectionError::ConnectionFailed, - ); - assert!(matches!(AppError::from(e), AppError::DbUnavailable)); - } /// The refusal a gated nest answers with. Both keys, and the `403` — a /// client switches on `module`, so neither may drift. @@ -328,14 +306,28 @@ mod tests { } #[test] - fn real_errors_stay_db_errors() { - // A genuine authorization verdict shares the suffix but must not match. - assert!(!is_session_replay_error( - "Not enough permissions to perform this action" + fn sqlx_errors_split_into_honest_classes() { + use sqlx::Error; + // Pool problems refuse on the acquire path: nothing executed, so a + // retry is safe. + assert!(matches!( + AppError::from(Error::PoolTimedOut), + AppError::DbUnavailable )); - assert!(!is_session_replay_error("Parse error: unexpected token")); - assert!(!is_session_replay_error( - "Database index `user_username` already contains 'admin'" + assert!(matches!( + AppError::from(Error::PoolClosed), + AppError::DbUnavailable )); + assert!(matches!( + AppError::from(Error::Tls("tls".into())), + AppError::DbUnavailable + )); + // A connection that died under a request: the honest 503 — the write + // may or may not have applied, so a retry is NOT advertised as safe. + let io = std::io::Error::new(std::io::ErrorKind::ConnectionReset, "gone"); + assert!(matches!(AppError::from(Error::Io(io)), AppError::DbTimeout)); + // A query that found no row is the caller's 404, never a 500. + assert!(matches!(AppError::from(Error::RowNotFound), AppError::NotFound)); } + } diff --git a/src/lib.rs b/src/lib.rs index 82f96f7..882f03f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,7 +5,6 @@ pub mod database; pub mod db; pub mod domain; pub mod error; -pub mod migration_sql; pub mod module; pub mod rate_limit; pub mod service; @@ -219,12 +218,8 @@ pub fn build_router(state: AppState) -> Router { // Every tier's budget outlives the process it was spent in (see // [`rate_limit::RateLimiter::share`]). The chatbot tier is shared here too // rather than in `main`, so a router built anywhere gets the same behaviour. - api_limiter.share("api", state.db.clone(), state.db_up.clone()); - state - .chatbot_limit - .share("chatbot", state.db.clone(), state.db_up.clone()); - - let db_up = state.db_up.clone(); + api_limiter.share("api", state.db.clone()); + state.chatbot_limit.share("chatbot", state.db.clone()); let metrics = state.metrics.clone(); let cors_allowlist = cors_allowlist_from_env(); @@ -242,13 +237,12 @@ pub fn build_router(state: AppState) -> Router { // request from a service is not a browser request from an IP: it has no // client address to bill the per-IP limiter (it would drain the shared // unknown-client budget), and `ETag`/CORS are browser concerns. Skipping the - // layers means skipping the db guard too, so the bridge runs the liveness - // check and the request timeout itself (see `ai::server`). + // layers means skipping the request deadline too, so the bridge applies the + // same deadline to its own dispatch (see `ai::server`). if let Some(ai) = &state.ai { ai.arm_api( service.clone(), state.tenants.clone(), - state.db_up.clone(), state.files_path.clone(), metrics.clone(), ); @@ -259,10 +253,7 @@ pub fn build_router(state: AppState) -> Router { // matching `If-None-Match`. Innermost, so it sees the handler's own // response (mutations and errors pass straight through untouched). .layer(middleware::from_fn(web::etag::etag)) - .layer(middleware::from_fn(move |req: Request, next: Next| { - let health = db_up.clone(); - async move { db_guard(health, req, next).await } - })) + .layer(middleware::from_fn(request_timeout)) .layer(middleware::from_fn(move |req: Request, next: Next| { let limiter = api_limiter.clone(); async move { limiter.enforce(req, next).await } @@ -463,39 +454,32 @@ impl Drop for InFlight<'_> { } } -/// Refuse work the database cannot currently do, and cap how long any request -/// may wait on it. -/// -/// Both halves exist because a query issued while the database socket is down -/// never fails — the SDK parks it until the connection returns, so without a -/// guard a handler waits out the entire outage holding a connection open. +/// Cap how long any request may wait on the database. The deadline covers both +/// the pool wait for a connection and the query run on it. /// -/// Order matters. The liveness check comes first and is the honest path: it -/// answers before the request touches the database, so nothing is queued and -/// the caller's retry cannot double-apply a write. The timeout only catches -/// requests that slipped through in the window between the socket dying and -/// the keepalive noticing — those are already queued, hence the weaker -/// [`AppError::DbTimeout`] verdict. +/// The health half this guard used to carry is gone with the engine that +/// needed it: a sqlx query issued on a dead pool fails with an error instead +/// of being parked until the socket returns, so there is no known-outage +/// verdict to publish and no queued work to refuse up front. What stays is +/// the honest [`AppError::DbTimeout`] semantics: a request that outlives the +/// deadline may or may not have applied its write, so a caller must not +/// blind-retry it. /// /// Long-lived responses are unaffected: a WebSocket upgrade and an SSE stream /// both return their response immediately and do the work afterwards, so /// neither is measured against the timeout. -async fn db_guard(health: state::DbHealth, req: Request, next: Next) -> Response { +async fn request_timeout(req: Request, next: Next) -> Response { // `/limits` never touches the database — it serializes constants and this - // process's own configuration. Refusing it during an outage would be a - // pure own-goal: a frontend booting into a degraded backend is exactly - // when it needs the validation contract, and answering `503` would push it - // back to the hard-coded copy this endpoint exists to delete. - // `/health` and its `/` mirror are exempt for the same reason and one - // more: refusing them with the guard's own 503 would replace the probe's - // answer ("degraded, the database is down") with a generic body that names - // nothing. They read the keepalive's verdict and touch no database. + // process's own configuration. Holding it to the deadline would be a pure + // own-goal: a frontend booting into a degraded backend is exactly when it + // needs the validation contract. `/health` and its `/` mirror are exempt + // for the same reason and one more: their own probe is bounded at 2s, far + // inside this deadline, and the generic timeout body would replace the + // probe's answer ("degraded, the database is down") with one that names + // nothing. if matches!(req.uri().path(), "/limits" | "/health" | "/") { return next.run(req).await; } - if !health.is_up() { - return AppError::DbUnavailable.into_response(); - } let timeout = std::time::Duration::from_secs(constant::REQUEST_TIMEOUT_SECS); match tokio::time::timeout(timeout, next.run(req)).await { Ok(response) => response, @@ -561,7 +545,7 @@ struct HealthResponse { /// one is not (today: the database). #[schema(example = "ok")] status: &'static str, - /// Did the database socket answer its last keepalive ping? + /// Did the bounded database probe (`SELECT 1`) answer? #[schema(example = "up")] db: &'static str, /// The optional AI bridge (see the `ai` tag). @@ -580,9 +564,10 @@ struct AiHealth { /// Health probe: the database verdict and the AI bridge, `503` when degraded. /// -/// Answers even while the database is down — it reads the keepalive's verdict -/// and touches nothing — which is the whole point: a probe that 503s with an -/// empty body says "down" without saying what is down. +/// Probes the database with a `SELECT 1` bounded to 2s — far inside the +/// request deadline — so a dead or wedged database answers `503` with a body +/// that says what is down, instead of the poll hanging on a full request +/// timeout. #[utoipa::path( get, path = "/health", @@ -593,7 +578,14 @@ struct AiHealth { ), )] async fn health(axum::extract::State(state): axum::extract::State) -> Response { - let up = state.db_up.is_up(); + let up = matches!( + tokio::time::timeout( + std::time::Duration::from_secs(2), + sqlx::query("SELECT 1").execute(&state.db), + ) + .await, + Ok(Ok(_)) + ); let status = if up { axum::http::StatusCode::OK } else { diff --git a/src/main.rs b/src/main.rs index 5d29d1a..9e94a79 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,7 @@ use anyhow::Context; use hezarfen_backend::config::Config; -use hezarfen_backend::database::Database; use hezarfen_backend::rate_limit::UserRateLimiter; -use hezarfen_backend::state::{AppState, DbHealth}; +use hezarfen_backend::state::AppState; use hezarfen_backend::{build_router, database}; #[tokio::main] @@ -29,10 +28,6 @@ async fn main() -> anyhow::Result<()> { // all of it idempotent and unconditional on every boot. School databases // come up lazily, one connection each, on first use. let tenants = database::init(&cfg).await?; - let db_up = DbHealth::default(); - // The control connection is the one every request touches (the school - // lookup rides it), so it is the socket worth watching. - keepalive(tenants.control().clone(), db_up.clone()); tokio::fs::create_dir_all(&cfg.files_path) .await .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?; @@ -46,7 +41,6 @@ async fn main() -> anyhow::Result<()> { chatbot_limit: UserRateLimiter::per_user_minute(cfg.chatbot_per_minute), exam_presence: Default::default(), board_hub: Default::default(), - db_up, ai, metrics, }); @@ -66,76 +60,6 @@ async fn main() -> anyhow::Result<()> { Ok(()) } -/// Ping the database forever so the WebSocket never sits idle long enough to -/// be dropped, and publish each verdict to `health` so the request guard can -/// refuse callers while the socket is down. -/// -/// The ping needs its own deadline. A query issued while the socket is down -/// does not fail — the SDK parks it until the connection returns, so an -/// un-deadlined ping hangs exactly as long as the outage and never reports the -/// outage it exists to detect. -fn keepalive(db: Database, health: DbHealth) { - tokio::spawn(async move { - let mut interval = tokio::time::interval(std::time::Duration::from_secs( - hezarfen_backend::constant::DB_KEEPALIVE_INTERVAL_SECS, - )); - interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); - let ping_timeout = - std::time::Duration::from_secs(hezarfen_backend::constant::DB_PING_TIMEOUT_SECS); - let metrics = hezarfen_backend::telemetry::Metrics::global(); - // The transitions are what an operator is paged about; a line per tick - // would bury them. `None` until the first verdict, so that one always - // announces itself. - let mut was_up: Option = None; - let mut down_since: Option = None; - loop { - interval.tick().await; - // corner-cut: an abandoned ping stays queued in the SDK and replays - // when the socket heals, so a long outage lands a burst of no-op - // `RETURN 1`s on recovery. Harmless; probe over a raw TCP dial - // instead if that burst ever shows up in a profile. - let started = tokio::time::Instant::now(); - let outcome = tokio::time::timeout(ping_timeout, db.query("RETURN 1")).await; - let elapsed = started.elapsed(); - metrics.db_ping_duration.record(elapsed.as_secs_f64(), &[]); - let up = match &outcome { - Ok(Ok(_)) => { - tracing::debug!("database keepalive ping ok"); - true - } - Ok(Err(err)) => { - tracing::debug!("database keepalive ping failed: {err}"); - false - } - Err(_) => { - tracing::debug!("database keepalive ping timed out"); - false - } - }; - health.set(up); - metrics.db_up.record(u64::from(up), &[]); - match (was_up, up) { - // The first verdict announces itself either way, so an operator - // reading the log can tell "healthy since boot" from "we never - // logged anything yet". - (None, true) => tracing::info!(db_up = true, "database reachable"), - (Some(true) | None, false) => { - down_since = Some(started); - tracing::warn!("database is down: the keepalive ping did not answer"); - } - (Some(false), true) => { - let outage_secs = down_since - .take() - .map_or(0.0, |since| since.elapsed().as_secs_f64()); - tracing::warn!(outage_secs, "database is back"); - } - _ => {} - } - was_up = Some(up); - } - }); -} - /// Resolve on SIGINT (Ctrl-C) or SIGTERM. As PID 1 in a container the process /// gets no default signal handling, so without this a `podman stop` waits out /// its grace period and SIGKILLs us — dropping in-flight requests mid-write. diff --git a/src/migration_sql.rs b/src/migration_sql.rs deleted file mode 100644 index 1445735..0000000 --- a/src/migration_sql.rs +++ /dev/null @@ -1,1524 +0,0 @@ -//! The boot migration, as SurrealQL text. -//! -//! Split out of [`crate::constant`] purely for size: these three batches are -//! ~700 lines of schema, and left in the constants file they buried the -//! validation bounds that file exists to hold. Nothing else changed — they are -//! still `pub const`, still the only migration text, and -//! [`crate::database::migrate`] still reads [`MIGRATION_BATCHES`] and nothing -//! else. -//! -//! Numbers stay in `constant.rs`: `tests/limits_completeness.rs` sweeps `src/` -//! for stray bounds, and a bound hidden here would reach neither `GET /limits` -//! nor the OpenAPI spec. Only SurrealQL strings live in this file. - -/// Repairs that must run *before* the DDL batch, because the DDL is what makes -/// them impossible. -/// -/// `MIGRATION` retires `exam_question.source_bank` with `REMOVE FIELD`, and -/// once the column is gone SCHEMAFULL rejects every write to a row that still -/// stores it ("Found field 'source_bank', but no such field exists") — an -/// UNSET included. So the value has to go while its definition is still -/// standing. Runs as its own query for the usual reason (see `MIGRATION`). -/// -/// `chatbot_message.claimed_by` / `claimed_at` (retired 2026-07-30 with the -/// chat claim queue) are the same story, one table over. -/// -/// The table-exists guard is load-bearing: on a fresh database `MIGRATION` has -/// not run yet, and an UPDATE against an undefined table is an error, not an -/// empty result. On a database that has the table but never had the column the -/// `WHERE` simply matches nothing. -pub const PRE_REPAIR: &str = " - IF 'exam_question' IN object::keys((INFO FOR DB).tables) { - UPDATE exam_question UNSET source_bank WHERE source_bank != NONE - }; - IF 'chatbot_message' IN object::keys((INFO FOR DB).tables) { - UPDATE chatbot_message UNSET claimed_by, claimed_at - WHERE claimed_by != NONE OR claimed_at != NONE - }; -"; - -/// SCHEMAFULL schema: every column is typed, references use `record<..>`. -/// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the -/// definitions and `REMOVE ... IF EXISTS` retires schema (like the -/// single-attempt unique index) exactly once. DDL only — data backfills live -/// in `BACKFILL`, which runs as a *separate* query: statements inside one -/// batch see the schema as it stood when the batch started, so an UPDATE next -/// to a fresh `DEFINE FIELD audience.*` writes against the old field set and -/// SCHEMAFULL silently strips the very keys being backfilled. -pub const MIGRATION: &str = " - DEFINE TABLE IF NOT EXISTS user SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS username ON user TYPE string; - DEFINE FIELD IF NOT EXISTS password_hash ON user TYPE string; - DEFINE FIELD IF NOT EXISTS role ON user TYPE string DEFAULT 'student'; - DEFINE FIELD IF NOT EXISTS name ON user TYPE option; - DEFINE FIELD IF NOT EXISTS surname ON user TYPE option; - DEFINE FIELD IF NOT EXISTS email ON user TYPE option; - DEFINE FIELD IF NOT EXISTS phone ON user TYPE option; - DEFINE FIELD IF NOT EXISTS birth_date ON user TYPE option; - DEFINE FIELD IF NOT EXISTS theme ON user TYPE option; - DEFINE FIELD IF NOT EXISTS language ON user TYPE option; - DEFINE FIELD IF NOT EXISTS palette_color ON user TYPE option; - DEFINE FIELD IF NOT EXISTS display_name ON user TYPE option; - DEFINE FIELD IF NOT EXISTS bio ON user TYPE option; - DEFINE FIELD IF NOT EXISTS avatar_file ON user TYPE option; - DEFINE FIELD IF NOT EXISTS avatar_content_type ON user TYPE option; - DEFINE FIELD IF NOT EXISTS avatar_size ON user TYPE option; - DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option; - DEFINE FIELD IF NOT EXISTS board_count ON user TYPE option; - -- Lifetime badge counters (2026-08-04). Not caps and never released: each - -- counts something the student *did*, so a badge earned off one stands even - -- if the counter later drops. `option` and absent reads as zero, so a - -- row written before them needs no repair to be *readable* — but it does - -- need one to be *right*, which is what the BACKFILL seeding is for. - DEFINE FIELD IF NOT EXISTS homework_submitted_total ON user TYPE option; - DEFINE FIELD IF NOT EXISTS homework_on_time_total ON user TYPE option; - DEFINE FIELD IF NOT EXISTS exam_sat_total ON user TYPE option; - DEFINE FIELD IF NOT EXISTS pomodoro_finished_total ON user TYPE option; - DEFINE FIELD IF NOT EXISTS pomodoro_focus_ms_total ON user TYPE option; - -- Pass 3 (2026-08-04): the staff-side counters, two more student ones, and - -- the study streak. `study_streak_longest` is the badge counter; the other - -- two streak columns are bookkeeping the write site needs to compute it and - -- are read by nothing else. Definitions only — the seeding of the - -- row-derivable ones is a BACKFILL under its own migration mark, never in - -- this batch (same-batch DDL + backfill reads a stale schema). - DEFINE FIELD IF NOT EXISTS marks_given_total ON user TYPE option; - DEFINE FIELD IF NOT EXISTS lessons_held_total ON user TYPE option; - DEFINE FIELD IF NOT EXISTS pool_approved_total ON user TYPE option; - DEFINE FIELD IF NOT EXISTS pool_published_total ON user TYPE option; - DEFINE FIELD IF NOT EXISTS lessons_attended_total ON user TYPE option; - DEFINE FIELD IF NOT EXISTS high_mark_total ON user TYPE option; - DEFINE FIELD IF NOT EXISTS study_streak_longest ON user TYPE option; - DEFINE FIELD IF NOT EXISTS study_streak_current ON user TYPE option; - DEFINE FIELD IF NOT EXISTS study_streak_last_day ON user TYPE option; - -- The counted-stint quota (2026-08-05): which UTC day the student last had - -- a pomodoro stint counted on, and how many counted that day. Bookkeeping - -- for the daily cap, read by nothing else; absent reads as no day yet, - -- which is what makes the first finish after this deploy open a fresh - -- bucket with no backfill. - DEFINE FIELD IF NOT EXISTS pomodoro_counted_day ON user TYPE option; - DEFINE FIELD IF NOT EXISTS pomodoro_counted_today ON user TYPE option; - DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; - - DEFINE TABLE IF NOT EXISTS session SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS user ON session TYPE record; - DEFINE FIELD IF NOT EXISTS token ON session TYPE string; - DEFINE FIELD IF NOT EXISTS expires_at ON session TYPE int; - DEFINE INDEX IF NOT EXISTS session_token ON session FIELDS token UNIQUE; - DEFINE INDEX IF NOT EXISTS session_expires ON session FIELDS expires_at; - - DEFINE TABLE IF NOT EXISTS note SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS user ON note TYPE record; - DEFINE FIELD IF NOT EXISTS title ON note TYPE string; - DEFINE FIELD IF NOT EXISTS content ON note TYPE string; - DEFINE FIELD IF NOT EXISTS file_count ON note TYPE option; - DEFINE INDEX IF NOT EXISTS note_user ON note FIELDS user; - - DEFINE TABLE IF NOT EXISTS message SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS sender ON message TYPE record; - DEFINE FIELD IF NOT EXISTS recipient ON message TYPE record; - DEFINE FIELD IF NOT EXISTS subject ON message TYPE string; - DEFINE FIELD IF NOT EXISTS body ON message TYPE string; - DEFINE FIELD IF NOT EXISTS label ON message TYPE option; - DEFINE FIELD IF NOT EXISTS sent_at ON message TYPE int; - DEFINE FIELD IF NOT EXISTS read ON message TYPE bool DEFAULT false; - DEFINE FIELD IF NOT EXISTS sender_folder ON message TYPE string DEFAULT 'sent'; - DEFINE FIELD IF NOT EXISTS recipient_folder ON message TYPE string DEFAULT 'inbox'; - -- Where each side's copy sat before it was filed into archive/trash, so a - -- restore lands where it came from. NONE while the copy is in its home - -- folder — and on rows filed before this field existed (2026-07-23), which - -- restore to the home folder just as they always did. - DEFINE FIELD IF NOT EXISTS sender_origin ON message TYPE option; - DEFINE FIELD IF NOT EXISTS recipient_origin ON message TYPE option; - DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender; - DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient; - - -- Collaborative whiteboard (2026-07-31): one `board` is a room, one - -- `board_stroke` is one append-only mark. A clear NEVER deletes — it bumps - -- `epoch`, so the canvas empties while the whole history stays replayable. - -- `locked` is a plain bool, not an option: the open-board guard asks for - -- `locked = false`, which a NONE would never match. `locked_by`/`locked_at`/ - -- `closed_at` are three top-level option columns rather than one nested - -- object, because SurrealDB 3 drops an object key valued NONE. - DEFINE TABLE IF NOT EXISTS board SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS creator ON board TYPE record; - DEFINE FIELD IF NOT EXISTS title ON board TYPE string; - DEFINE FIELD IF NOT EXISTS participants ON board TYPE array>; - DEFINE FIELD IF NOT EXISTS locked ON board TYPE bool DEFAULT false; - DEFINE FIELD IF NOT EXISTS locked_by ON board TYPE option>; - DEFINE FIELD IF NOT EXISTS locked_at ON board TYPE option; - DEFINE FIELD IF NOT EXISTS epoch ON board TYPE int DEFAULT 0; - -- Resets to 0 on every clear (recoverable); never resets (stamps closed_at). - DEFINE FIELD IF NOT EXISTS epoch_stroke_count ON board TYPE option; - DEFINE FIELD IF NOT EXISTS total_stroke_count ON board TYPE option; - -- Stamped once, when the lifetime cap is hit: permanently read-only. - DEFINE FIELD IF NOT EXISTS closed_at ON board TYPE option; - DEFINE FIELD IF NOT EXISTS created_at ON board TYPE int; - DEFINE INDEX IF NOT EXISTS board_creator ON board FIELDS creator; - -- Listing a user's boards asks `creator = $u OR participants CONTAINS $u`; - -- without this the CONTAINS half is a full scan. SurrealDB indexes an - -- array field per element, so it covers the membership test directly. - DEFINE INDEX IF NOT EXISTS board_participants ON board FIELDS participants; - - DEFINE TABLE IF NOT EXISTS board_stroke SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS board ON board_stroke TYPE record; - DEFINE FIELD IF NOT EXISTS author ON board_stroke TYPE record; - -- 'stroke' or 'clear'; `payload` is the opaque blob, absent on a clear - -- marker, and `count` is populated only on a clear marker — the final - -- stroke count of the epoch that marker closed. - DEFINE FIELD IF NOT EXISTS kind ON board_stroke TYPE string; - DEFINE FIELD IF NOT EXISTS payload ON board_stroke TYPE option; - DEFINE FIELD IF NOT EXISTS count ON board_stroke TYPE option; - DEFINE FIELD IF NOT EXISTS epoch ON board_stroke TYPE int; - DEFINE FIELD IF NOT EXISTS created_at ON board_stroke TYPE int; - -- Keeps a socket's join-replay scoped to the current epoch instead of - -- scanning the board's whole history. - DEFINE INDEX IF NOT EXISTS board_stroke_board_epoch ON board_stroke FIELDS board, epoch; - -- The clear markers ARE the epoch index, so listing them is a hot read. - DEFINE INDEX IF NOT EXISTS board_stroke_board_kind ON board_stroke FIELDS board, kind; - - DEFINE TABLE IF NOT EXISTS note_file SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS note ON note_file TYPE record; - DEFINE FIELD IF NOT EXISTS name ON note_file TYPE string; - DEFINE FIELD IF NOT EXISTS content_type ON note_file TYPE string; - DEFINE FIELD IF NOT EXISTS size ON note_file TYPE int; - DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note; - - DEFINE TABLE IF NOT EXISTS course_note SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS course ON course_note TYPE record; - DEFINE FIELD IF NOT EXISTS author ON course_note TYPE record; - DEFINE FIELD IF NOT EXISTS title ON course_note TYPE string; - DEFINE FIELD IF NOT EXISTS content ON course_note TYPE string; - DEFINE FIELD IF NOT EXISTS file_count ON course_note TYPE option; - DEFINE INDEX IF NOT EXISTS course_note_course ON course_note FIELDS course; - - DEFINE TABLE IF NOT EXISTS course_note_file SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS course_note ON course_note_file TYPE record; - DEFINE FIELD IF NOT EXISTS name ON course_note_file TYPE string; - DEFINE FIELD IF NOT EXISTS content_type ON course_note_file TYPE string; - DEFINE FIELD IF NOT EXISTS size ON course_note_file TYPE int; - DEFINE INDEX IF NOT EXISTS course_note_file_note ON course_note_file FIELDS course_note; - - -- What an AI service produced for a course note (rag.index, 2026-09-05). - -- Derived and disposable: the note is the source of truth, so the rows - -- cascade from the note AND from any attachment they were built from. - -- `payload` is FLEXIBLE because its shape belongs to the service, not to - -- this schema — SCHEMAFULL would otherwise strip every key inside it. - DEFINE TABLE IF NOT EXISTS rag_output SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS course_note ON rag_output TYPE record; - DEFINE FIELD IF NOT EXISTS course ON rag_output TYPE record; - DEFINE FIELD IF NOT EXISTS sources ON rag_output TYPE array>; - DEFINE FIELD IF NOT EXISTS payload ON rag_output TYPE object FLEXIBLE; - DEFINE FIELD IF NOT EXISTS generated_at ON rag_output TYPE int; - DEFINE INDEX IF NOT EXISTS rag_output_note ON rag_output FIELDS course_note; - -- Retire the course index: nothing queries rag_output by course. - REMOVE INDEX IF EXISTS rag_output_course ON rag_output; - -- Indexed per element, so the source cascade's `sources CONTAINS $file` - -- is a lookup rather than a table scan. - DEFINE INDEX IF NOT EXISTS rag_output_source ON rag_output FIELDS sources; - - -- Chatbot relay (2026-07-23): a `thread` groups the turns, one - -- `chatbot_message` is one turn. `user_id` rides on the message too so an - -- ownership check needs no join. An assistant turn is born `pending` and - -- is completed (or failed) by the task holding the AI-bridge stream — - -- hence the BACKFILL sweep, since that task dies with the process. - DEFINE TABLE IF NOT EXISTS chatbot_thread SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS user_id ON chatbot_thread TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS title ON chatbot_thread TYPE option; - DEFINE FIELD IF NOT EXISTS created_at ON chatbot_thread TYPE int READONLY; - DEFINE FIELD IF NOT EXISTS updated_at ON chatbot_thread TYPE int; - DEFINE INDEX IF NOT EXISTS chatbot_thread_user_updated ON chatbot_thread FIELDS user_id, updated_at; - - DEFINE TABLE IF NOT EXISTS chatbot_message SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS thread_id ON chatbot_message TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS user_id ON chatbot_message TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS role ON chatbot_message TYPE string READONLY; - DEFINE FIELD IF NOT EXISTS content ON chatbot_message TYPE string; - DEFINE FIELD IF NOT EXISTS status ON chatbot_message TYPE string; - DEFINE FIELD IF NOT EXISTS truncated ON chatbot_message TYPE bool DEFAULT false; - DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option; - DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY; - DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option; - -- The chat claim queue is gone (2026-07-30): one process answers its own - -- turns, so nothing claims them. PRE_REPAIR clears the values first — - -- SCHEMAFULL rejects every write to a row still storing a column that no - -- longer exists. - REMOVE FIELD IF EXISTS claimed_by ON TABLE chatbot_message; - REMOVE FIELD IF EXISTS claimed_at ON TABLE chatbot_message; - DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at; - DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id; - -- The boot sweep asks for pending rows by age. - DEFINE INDEX IF NOT EXISTS chatbot_message_status_created ON chatbot_message FIELDS status, created_at; - - -- The AI worker presence table is gone (2026-07-30): one process holds - -- every worker socket, so its in-process registry is the whole truth and - -- nothing needed publishing. - REMOVE TABLE IF EXISTS ai_worker; - - -- The elected-boot lease is gone with it (2026-07-30): one process migrates, - -- so nothing takes the lock. SCHEMALESS and read by nobody, so unlike the - -- claim columns it needs no PRE_REPAIR — the table just goes. - REMOVE TABLE IF EXISTS migration_lock; - - -- How much of a rate-limit budget one client has spent in one wall window - -- (2026-07-27). One row per tier+client+window, id-keyed so a restart of - -- the process lands back on the same record; `hits` is the durable total - -- the in-memory bucket folds its local admits into (see - -- `crate::rate_limit`), which is what carries a window across a restart. - -- Rows are swept by the same task once their window is past. - DEFINE TABLE IF NOT EXISTS rate_limit SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS hits ON rate_limit TYPE int DEFAULT 0; - DEFINE FIELD IF NOT EXISTS window_start ON rate_limit TYPE int; - - DEFINE TABLE IF NOT EXISTS event SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS creator ON event TYPE record; - DEFINE FIELD IF NOT EXISTS title ON event TYPE string; - DEFINE FIELD IF NOT EXISTS description ON event TYPE string; - DEFINE FIELD IF NOT EXISTS audience ON event TYPE object; - DEFINE FIELD IF NOT EXISTS audience.kind ON event TYPE string; - DEFINE FIELD IF NOT EXISTS audience.role ON event TYPE option; - DEFINE FIELD IF NOT EXISTS audience.course ON event TYPE option>; - DEFINE FIELD IF NOT EXISTS audience.class ON event TYPE option>; - DEFINE FIELD IF NOT EXISTS audience.capacity ON event TYPE option; - -- Seats taken on the signup list, the stored capacity guard that closes - -- write-skew between concurrent request tasks (see `crate::db::cap`). - -- Absent reads as zero, so no Rust struct needs it. - DEFINE FIELD IF NOT EXISTS registration_count ON event TYPE option; - REMOVE FIELD IF EXISTS audience.users ON TABLE event; - DEFINE FIELD IF NOT EXISTS starts_at ON event TYPE option; - DEFINE FIELD IF NOT EXISTS ends_at ON event TYPE option; - - DEFINE TABLE IF NOT EXISTS attendance SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS event ON attendance TYPE record; - DEFINE FIELD IF NOT EXISTS user ON attendance TYPE record; - DEFINE FIELD IF NOT EXISTS status ON attendance TYPE string; - DEFINE FIELD IF NOT EXISTS marked_by ON attendance TYPE record; - DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE; - DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user; - - DEFINE TABLE IF NOT EXISTS registration SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS event ON registration TYPE record; - DEFINE FIELD IF NOT EXISTS user ON registration TYPE record; - DEFINE FIELD IF NOT EXISTS registered_by ON registration TYPE record; - DEFINE INDEX IF NOT EXISTS registration_event_user ON registration FIELDS event, user UNIQUE; - DEFINE INDEX IF NOT EXISTS registration_event ON registration FIELDS event; - - DEFINE TABLE IF NOT EXISTS term SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS name ON term TYPE string; - DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int; - DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int; - -- When the term was archived; absent = open. `option` and no - -- BACKFILL: every term that exists predates archiving and is open, which - -- is exactly what an absent stamp already means. - DEFINE FIELD IF NOT EXISTS archived_at ON term TYPE option; - -- Courses still linking this term, the stored delete guard that closes - -- write-skew between concurrent request tasks (see `crate::db::cap`). - -- Absent reads as zero, so no Rust struct needs it. - DEFINE FIELD IF NOT EXISTS course_count ON term TYPE option; - -- Classes linking this term, the other half of the same guard. A column of - -- its own because `course_count` is seeded from the course rows alone. - DEFINE FIELD IF NOT EXISTS class_count ON term TYPE option; - - DEFINE TABLE IF NOT EXISTS course SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS creator ON course TYPE record; - DEFINE FIELD IF NOT EXISTS teachers ON course TYPE array> DEFAULT []; - DEFINE FIELD IF NOT EXISTS teachers[*] ON course TYPE record; - DEFINE FIELD IF NOT EXISTS title ON course TYPE string; - DEFINE FIELD IF NOT EXISTS description ON course TYPE string; - DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course'; - DEFINE FIELD IF NOT EXISTS term ON course TYPE option>; - DEFINE FIELD IF NOT EXISTS capacity ON course TYPE option; - DEFINE FIELD IF NOT EXISTS enrollment_count ON course TYPE option; - - DEFINE TABLE IF NOT EXISTS subject SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS course ON subject TYPE record; - DEFINE FIELD IF NOT EXISTS name ON subject TYPE string; - DEFINE FIELD IF NOT EXISTS description ON subject TYPE string; - -- How many exam questions and how many homework still point here. The - -- delete is conditioned on both reading zero, which is what makes the - -- guard hold against a question created by a concurrent request task. - DEFINE FIELD IF NOT EXISTS exam_question_count ON subject TYPE option; - DEFINE FIELD IF NOT EXISTS homework_count ON subject TYPE option; - DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course; - - -- A class section (şube) is a named set of students that bulk-manages real - -- `enrollment` rows: `class_member` is one student in it, `class_course` one - -- course it is attached to. Both counters gate the class delete. - DEFINE TABLE IF NOT EXISTS class_group SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS name ON class_group TYPE string; - DEFINE FIELD IF NOT EXISTS grade ON class_group TYPE option; - DEFINE FIELD IF NOT EXISTS term ON class_group TYPE option>; - DEFINE FIELD IF NOT EXISTS creator ON class_group TYPE record; - DEFINE FIELD IF NOT EXISTS teacher ON class_group TYPE option>; - DEFINE FIELD IF NOT EXISTS class_member_count ON class_group TYPE option; - DEFINE FIELD IF NOT EXISTS class_course_count ON class_group TYPE option; - -- Every class at one grade is what a blueprint pumps, so the grade label is - -- that read's whole `WHERE`. - DEFINE INDEX IF NOT EXISTS class_group_grade ON class_group FIELDS grade; - - -- A grade's course template: the courses every class section at that grade - -- carries. The grade label *is* the record key, so a second blueprint for - -- one grade cannot exist and no find-then-insert has to race for it (the shape - -- `menu` uses for its date+slot). It holds no term — the class names its - -- own — and `courses` carries no DEFAULT: a defaulted array on a SCHEMAFULL - -- row is what broke every settings PATCH. - DEFINE TABLE IF NOT EXISTS class_blueprint SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS grade ON class_blueprint TYPE string; - DEFINE FIELD IF NOT EXISTS courses ON class_blueprint TYPE array>; - DEFINE FIELD IF NOT EXISTS creator ON class_blueprint TYPE record; - - DEFINE TABLE IF NOT EXISTS class_member SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS class ON class_member TYPE record; - DEFINE FIELD IF NOT EXISTS user ON class_member TYPE record; - DEFINE FIELD IF NOT EXISTS added_by ON class_member TYPE record; - -- When the student was put in. Both link tables key on the *pair* - -- (`_`), so ordering a roster by its record id sorts it by the - -- member's account ULID — an arbitrary order the routes nevertheless - -- documented as newest-first. `option` and no BACKFILL: rows written - -- before this column are of unknown age, and an absent stamp is NONE, which - -- SurrealDB sorts *last* under DESC — already the honest place for them, so - -- there is no number to invent. - DEFINE FIELD IF NOT EXISTS added_at ON class_member TYPE option; - DEFINE INDEX IF NOT EXISTS class_member_class_user ON class_member FIELDS class, user UNIQUE; - DEFINE INDEX IF NOT EXISTS class_member_class ON class_member FIELDS class; - DEFINE INDEX IF NOT EXISTS class_member_user ON class_member FIELDS user; - - DEFINE TABLE IF NOT EXISTS class_course SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS class ON class_course TYPE record; - DEFINE FIELD IF NOT EXISTS course ON class_course TYPE record; - DEFINE FIELD IF NOT EXISTS attached_by ON class_course TYPE record; - -- The mirror of `class_member.added_at`, for the same reason: without it - -- the course list is ordered by the *course's* ULID. - DEFINE FIELD IF NOT EXISTS attached_at ON class_course TYPE option; - -- The blueprint that attached this course, absent when a human attached it - -- by hand — the same shape, and the same meaning, as `enrollment.source` - -- one table down. The line is not optional bookkeeping: `class_course` is - -- SCHEMAFULL with a definition per key, so an undefined column is silently - -- stripped on write and a blueprint could never take back what it placed. - -- Absence *is* the meaning, so there is nothing to backfill: a row written - -- before this column reads back as hand-attached, and `source = $blueprint` - -- is false for an absent key, which is what keeps a hand-attached course - -- unreachable by every blueprint sweep. - DEFINE FIELD IF NOT EXISTS source ON class_course TYPE option>; - DEFINE INDEX IF NOT EXISTS class_course_class_course ON class_course FIELDS class, course UNIQUE; - DEFINE INDEX IF NOT EXISTS class_course_class ON class_course FIELDS class; - DEFINE INDEX IF NOT EXISTS class_course_course ON class_course FIELDS course; - - DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record; - DEFINE FIELD IF NOT EXISTS user ON enrollment TYPE record; - DEFINE FIELD IF NOT EXISTS enrolled_by ON enrollment TYPE record; - -- The class that pumped this row, absent when a human placed the student - -- directly. Absence is the meaning, so there is nothing to backfill: a class - -- sweep may only take back the rows it wrote. - DEFINE FIELD IF NOT EXISTS source ON enrollment TYPE option>; - DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE; - DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user; - - DEFINE TABLE IF NOT EXISTS parent_link SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS parent ON parent_link TYPE record; - DEFINE FIELD IF NOT EXISTS student ON parent_link TYPE record; - DEFINE FIELD IF NOT EXISTS linked_by ON parent_link TYPE record; - DEFINE INDEX IF NOT EXISTS parent_link_parent_student ON parent_link FIELDS parent, student UNIQUE; - DEFINE INDEX IF NOT EXISTS parent_link_parent ON parent_link FIELDS parent; - DEFINE INDEX IF NOT EXISTS parent_link_student ON parent_link FIELDS student; - - DEFINE TABLE IF NOT EXISTS course_session SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS course ON course_session TYPE record; - DEFINE FIELD IF NOT EXISTS teacher ON course_session TYPE record; - DEFINE FIELD IF NOT EXISTS topic ON course_session TYPE string; - DEFINE FIELD IF NOT EXISTS starts_at ON course_session TYPE int; - DEFINE FIELD IF NOT EXISTS ends_at ON course_session TYPE option; - -- The once-per-session guard behind `lessons_held_total` (2026-08-04): - -- stamped by the first roll call taken for the lesson, read by nothing but - -- that guard. Definition only, and deliberately no backfill — a session - -- that predates it carries no stamp, so the next roll call taken on it - -- credits its teacher once, which is the rule this column encodes anyway. - DEFINE FIELD IF NOT EXISTS held_counted_at ON course_session TYPE option; - DEFINE INDEX IF NOT EXISTS course_session_course ON course_session FIELDS course; - - DEFINE TABLE IF NOT EXISTS session_attendance SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS session ON session_attendance TYPE record; - DEFINE FIELD IF NOT EXISTS course ON session_attendance TYPE record; - DEFINE FIELD IF NOT EXISTS user ON session_attendance TYPE record; - DEFINE FIELD IF NOT EXISTS status ON session_attendance TYPE string; - DEFINE FIELD IF NOT EXISTS marked_by ON session_attendance TYPE record; - DEFINE INDEX IF NOT EXISTS session_attendance_session_user ON session_attendance FIELDS session, user UNIQUE; - DEFINE INDEX IF NOT EXISTS session_attendance_session ON session_attendance FIELDS session; - DEFINE INDEX IF NOT EXISTS session_attendance_user ON session_attendance FIELDS user; - DEFINE INDEX IF NOT EXISTS session_attendance_course ON session_attendance FIELDS course; - - DEFINE TABLE IF NOT EXISTS work_entry SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS user ON work_entry TYPE record; - DEFINE FIELD IF NOT EXISTS check_in ON work_entry TYPE int; - DEFINE FIELD IF NOT EXISTS check_out ON work_entry TYPE option; - DEFINE INDEX IF NOT EXISTS work_entry_user ON work_entry FIELDS user; - - DEFINE TABLE IF NOT EXISTS pomodoro_session SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS user ON pomodoro_session TYPE record; - DEFINE FIELD IF NOT EXISTS started_at ON pomodoro_session TYPE int; - DEFINE FIELD IF NOT EXISTS finished_at ON pomodoro_session TYPE option; - -- The verdict `finish` reached for this stint, stamped at close so a later - -- reader never re-derives it against thresholds that have since moved. - -- `option`: a running stint has no verdict yet, and a stint closed - -- before the rule existed carries none and cannot honestly be given one. - DEFINE FIELD IF NOT EXISTS counted ON pomodoro_session TYPE option; - -- The student's own name for what the stint is for ('math', 'TYT - -- denemesi') — free text given at start, not a subject link. Shipped in - -- the same deploy as the code that writes it: on a SCHEMAFULL table a - -- write naming an undefined field fails, and `option` lets rows from - -- before the field read as none. - DEFINE FIELD IF NOT EXISTS label ON pomodoro_session TYPE option; - DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user; - - DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record; - DEFINE FIELD IF NOT EXISTS course ON exam TYPE record; - DEFINE FIELD IF NOT EXISTS title ON exam TYPE string; - DEFINE FIELD IF NOT EXISTS description ON exam TYPE string; - DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string; - DEFINE FIELD IF NOT EXISTS mode ON exam TYPE option; - DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option; - DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option; - DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option; - DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1; - DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true; - DEFINE FIELD IF NOT EXISTS allow_review ON exam TYPE bool DEFAULT false; - DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false; - -- How many marks the exam carries (2026-07-27). A kind change is refused - -- against it, and the exam's own compare-and-set pins it, so a grade - -- landing mid-PATCH refuses that save instead of slipping past its gates. - DEFINE FIELD IF NOT EXISTS result_count ON exam TYPE option; - DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course; - - DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS exam ON exam_attempt TYPE record; - DEFINE FIELD IF NOT EXISTS user ON exam_attempt TYPE record; - DEFINE FIELD IF NOT EXISTS seq ON exam_attempt TYPE int DEFAULT 1; - DEFINE FIELD IF NOT EXISTS started_at ON exam_attempt TYPE int; - DEFINE FIELD IF NOT EXISTS finished_at ON exam_attempt TYPE option; - DEFINE FIELD IF NOT EXISTS left_at ON exam_attempt TYPE option; - DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user_seq ON exam_attempt FIELDS exam, user, seq UNIQUE; - DEFINE INDEX IF NOT EXISTS exam_attempt_exam ON exam_attempt FIELDS exam; - - DEFINE TABLE IF NOT EXISTS exam_question SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS exam ON exam_question TYPE record; - DEFINE FIELD IF NOT EXISTS text ON exam_question TYPE string; - DEFINE FIELD IF NOT EXISTS kind ON exam_question TYPE string; - DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int; - -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices - -- gained stable ids (`array`/`int` -> `array`/`string`), - -- and IF NOT EXISTS would leave an existing database on the old types. - DEFINE FIELD OVERWRITE choices ON exam_question TYPE option>; - -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice - -- object's own fields are declared too (same shape as `settings.exam_kinds`). - DEFINE FIELD OVERWRITE choices.*.id ON exam_question TYPE string; - DEFINE FIELD OVERWRITE choices.*.text ON exam_question TYPE string; - DEFINE FIELD OVERWRITE correct ON exam_question TYPE option; - DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record; - -- Provenance, one column per direction: `from_bank` is the template this - -- question was inserted from, `banked_as` the template most recently minted - -- by saving it into the bank. They replace the single `source_bank`, which - -- both directions wrote — so a question inserted from the bank read as - -- already-saved. OVERWRITE (not IF NOT EXISTS): the old column has to - -- actually go on an existing database, or SCHEMAFULL keeps accepting it - -- while the struct no longer writes it. - DEFINE FIELD OVERWRITE from_bank ON exam_question TYPE option>; - DEFINE FIELD OVERWRITE banked_as ON exam_question TYPE option>; - REMOVE FIELD IF EXISTS source_bank ON TABLE exam_question; - DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam; - DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject; - - DEFINE TABLE IF NOT EXISTS question_image SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS exam ON question_image TYPE record; - DEFINE FIELD IF NOT EXISTS question ON question_image TYPE record; - -- OVERWRITE: `slot` is now the choice's id, not its position. - DEFINE FIELD OVERWRITE slot ON question_image TYPE option; - DEFINE FIELD IF NOT EXISTS file ON question_image TYPE string; - DEFINE FIELD IF NOT EXISTS content_type ON question_image TYPE string; - DEFINE FIELD IF NOT EXISTS size ON question_image TYPE int; - DEFINE INDEX IF NOT EXISTS question_image_exam ON question_image FIELDS exam; - DEFINE INDEX IF NOT EXISTS question_image_question ON question_image FIELDS question; - - DEFINE TABLE IF NOT EXISTS bank_question SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS owner ON bank_question TYPE record; - -- OVERWRITE, not IF NOT EXISTS: the field started life as a required - -- `record` and has to actually change type on an existing database, - -- otherwise the subject-delete cascade (`SET subject = NONE`) is rejected. - DEFINE FIELD OVERWRITE subject ON bank_question TYPE option>; - DEFINE FIELD IF NOT EXISTS text ON bank_question TYPE string; - DEFINE FIELD IF NOT EXISTS kind ON bank_question TYPE string; - DEFINE FIELD IF NOT EXISTS points ON bank_question TYPE int; - -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices - -- gained stable ids (`array`/`int` -> `array`/`string`), - -- and IF NOT EXISTS would leave an existing database on the old types. - DEFINE FIELD OVERWRITE choices ON bank_question TYPE option>; - -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice - -- object's own fields are declared too (same shape as `settings.exam_kinds`). - DEFINE FIELD OVERWRITE choices.*.id ON bank_question TYPE string; - DEFINE FIELD OVERWRITE choices.*.text ON bank_question TYPE string; - DEFINE FIELD OVERWRITE correct ON bank_question TYPE option; - DEFINE FIELD IF NOT EXISTS source_exam ON bank_question TYPE option>; - -- 'private' | 'school'. DEFAULT so a row that predates the field (or any - -- partial write) can never come out published: the answer key stays the - -- owner's until they publish it. - DEFINE FIELD IF NOT EXISTS visibility ON bank_question TYPE string DEFAULT 'private'; - DEFINE FIELD IF NOT EXISTS created_at ON bank_question TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS bank_question_owner ON bank_question FIELDS owner; - DEFINE INDEX IF NOT EXISTS bank_question_subject ON bank_question FIELDS subject; - - DEFINE TABLE IF NOT EXISTS bank_question_image SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS bank_question ON bank_question_image TYPE record; - -- OVERWRITE: `slot` is now the choice's id, not its position. - DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option; - DEFINE FIELD IF NOT EXISTS file ON bank_question_image TYPE string; - DEFINE FIELD IF NOT EXISTS content_type ON bank_question_image TYPE string; - DEFINE FIELD IF NOT EXISTS size ON bank_question_image TYPE int; - DEFINE INDEX IF NOT EXISTS bank_question_image_question ON bank_question_image FIELDS bank_question; - - DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record; - DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record; - DEFINE FIELD IF NOT EXISTS user ON exam_answer TYPE record; - -- OVERWRITE: `selected` now names the picked option by id. - DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option; - DEFINE FIELD IF NOT EXISTS text ON exam_answer TYPE option; - DEFINE FIELD IF NOT EXISTS updated_at ON exam_answer TYPE int; - -- `seq` numbers the sitting an answer belongs to (1, 2, …), mirroring - -- exam_attempt. It rides the record key too, so a retake's answer is a new - -- row, not an overwrite of the prior sitting. - DEFINE FIELD IF NOT EXISTS seq ON exam_answer TYPE int DEFAULT 1; - -- Retire the pre-history unique index: (question, user) is no longer unique - -- once a student re-sits; (question, user, seq) is. - REMOVE INDEX IF EXISTS exam_answer_question_user ON exam_answer; - DEFINE INDEX IF NOT EXISTS exam_answer_question_user_seq ON exam_answer FIELDS question, user, seq UNIQUE; - DEFINE INDEX IF NOT EXISTS exam_answer_exam_user ON exam_answer FIELDS exam, user; - DEFINE INDEX IF NOT EXISTS exam_answer_exam ON exam_answer FIELDS exam; - - DEFINE TABLE IF NOT EXISTS answer_image SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS exam ON answer_image TYPE record; - DEFINE FIELD IF NOT EXISTS question ON answer_image TYPE record; - DEFINE FIELD IF NOT EXISTS user ON answer_image TYPE record; - DEFINE FIELD IF NOT EXISTS file ON answer_image TYPE string; - DEFINE FIELD IF NOT EXISTS content_type ON answer_image TYPE string; - DEFINE FIELD IF NOT EXISTS size ON answer_image TYPE int; - -- `seq` numbers the sitting this drawing belongs to; it rides the record - -- key so a retake's image never overwrites the prior sitting's. - DEFINE FIELD IF NOT EXISTS seq ON answer_image TYPE int DEFAULT 1; - DEFINE INDEX IF NOT EXISTS answer_image_exam ON answer_image FIELDS exam; - DEFINE INDEX IF NOT EXISTS answer_image_user ON answer_image FIELDS user; - - DEFINE TABLE IF NOT EXISTS exam_result SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS exam ON exam_result TYPE record; - DEFINE FIELD IF NOT EXISTS user ON exam_result TYPE record; - DEFINE FIELD IF NOT EXISTS mark ON exam_result TYPE int; - DEFINE FIELD IF NOT EXISTS graded_by ON exam_result TYPE record; - -- `seq` numbers the sitting a mark belongs to; a retake earns its own mark - -- row, and the latest seq is the student's standing. - DEFINE FIELD IF NOT EXISTS seq ON exam_result TYPE int DEFAULT 1; - REMOVE INDEX IF EXISTS exam_result_exam_user ON exam_result; - DEFINE INDEX IF NOT EXISTS exam_result_exam_user_seq ON exam_result FIELDS exam, user, seq UNIQUE; - - DEFINE TABLE IF NOT EXISTS pool_question SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS asker ON pool_question TYPE record; - DEFINE FIELD IF NOT EXISTS title ON pool_question TYPE string; - DEFINE FIELD IF NOT EXISTS body ON pool_question TYPE string; - DEFINE FIELD IF NOT EXISTS status ON pool_question TYPE string DEFAULT 'pending'; - DEFINE FIELD IF NOT EXISTS asked_at ON pool_question TYPE int; - DEFINE FIELD IF NOT EXISTS approved_by ON pool_question TYPE option>; - DEFINE FIELD IF NOT EXISTS image_file ON pool_question TYPE option; - DEFINE FIELD IF NOT EXISTS image_content_type ON pool_question TYPE option; - DEFINE FIELD IF NOT EXISTS image_size ON pool_question TYPE option; - DEFINE INDEX IF NOT EXISTS pool_question_status ON pool_question FIELDS status; - DEFINE INDEX IF NOT EXISTS pool_question_asker ON pool_question FIELDS asker; - - DEFINE TABLE IF NOT EXISTS solution SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS question ON solution TYPE record; - DEFINE FIELD IF NOT EXISTS author ON solution TYPE record; - DEFINE FIELD IF NOT EXISTS body ON solution TYPE string; - DEFINE FIELD IF NOT EXISTS offered_at ON solution TYPE int; - DEFINE FIELD IF NOT EXISTS image_file ON solution TYPE option; - DEFINE FIELD IF NOT EXISTS image_content_type ON solution TYPE option; - DEFINE FIELD IF NOT EXISTS image_size ON solution TYPE option; - DEFINE INDEX IF NOT EXISTS solution_question ON solution FIELDS question; - - DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array; - DEFINE FIELD IF NOT EXISTS exam_kinds.*.name ON settings TYPE string; - DEFINE FIELD IF NOT EXISTS exam_kinds.*.weight ON settings TYPE int; - DEFINE FIELD IF NOT EXISTS attendance_statuses ON settings TYPE array; - DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array; - DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int; - DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string; - DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option; - DEFINE FIELD IF NOT EXISTS chatbot_history_turns ON settings TYPE option; - DEFINE FIELD IF NOT EXISTS max_chatbot_threads ON settings TYPE option; - DEFINE FIELD IF NOT EXISTS max_chatbot_message_len ON settings TYPE option; - -- Food program (2026-07-26). `meal_slots` mirrors the `exam_kinds` shape — - -- a named list a menu snapshots from — and `dietary_tags` mirrors - -- `attendance_statuses`. `meal_cancel_cutoff_minutes` is ONE knob for both - -- the booking and the cancel deadline; absent means no cutoff at all. All - -- three are `option<>`, exactly like `max_file_bytes`: NOT `DEFAULT []`. - -- `DEFAULT` fires on create only, and `PATCH /settings` writes the whole - -- row with `UPDATE ... CONTENT`, so a required-with-default field a writer - -- omits coerces to NONE and fails every settings write until the domain - -- struct carries it. `option<>` also means the existing singleton reads - -- fine, which is why the food program needs no BACKFILL anywhere. - DEFINE FIELD IF NOT EXISTS meal_slots ON settings TYPE option>; - DEFINE FIELD IF NOT EXISTS meal_slots.*.name ON settings TYPE string; - -- Minutes past midnight UTC at which the slot is served (2026-07-26). - -- `option` for the same reason the list itself is: slots written - -- before the field existed simply have no key, and read back as NONE -> - -- the booking cutoff falls back to midnight UTC, its old meaning. No - -- BACKFILL, and no DEFAULT — see the note above. - DEFINE FIELD IF NOT EXISTS meal_slots.*.serving_minute ON settings TYPE option; - DEFINE FIELD IF NOT EXISTS dietary_tags ON settings TYPE option>; - DEFINE FIELD IF NOT EXISTS meal_cancel_cutoff_minutes ON settings TYPE option; - - -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students - -- submit files + optional text, a teacher grades a status + optional mark. - -- `course`/`created_by`/`created_at` are READONLY (a homework never moves - -- course, and stamps never rewrite); `subject` is NOT — it is re-taggable - -- via PATCH. `assigned` NONE/empty means the whole course. No BACKFILL: the - -- tables are new, so the whole migration stays additive and idempotent. - DEFINE TABLE IF NOT EXISTS homework SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS course ON homework TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS subject ON homework TYPE record; - DEFINE FIELD IF NOT EXISTS title ON homework TYPE string; - DEFINE FIELD IF NOT EXISTS description ON homework TYPE option; - DEFINE FIELD IF NOT EXISTS due_at ON homework TYPE int; - DEFINE FIELD IF NOT EXISTS assigned ON homework TYPE option>>; - DEFINE FIELD IF NOT EXISTS assigned[*] ON homework TYPE record; - DEFINE FIELD IF NOT EXISTS created_by ON homework TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS created_at ON homework TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS homework_course ON homework FIELDS course; - - DEFINE TABLE IF NOT EXISTS homework_submission SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS homework ON homework_submission TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS user ON homework_submission TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS text ON homework_submission TYPE option; - DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY; - DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int; - DEFINE FIELD IF NOT EXISTS file_count ON homework_submission TYPE option; - -- The on-time verdict the badge counter was actually credited with, stamped - -- at the first hand-in and never re-judged. `due_at` is mutable (a teacher - -- moves a deadline with `PATCH /homework/{id}`), so re-deriving the verdict - -- at withdrawal read a *different* deadline than the credit did and gave - -- back the wrong thing in both directions — extend the deadline after a late - -- hand-in and the withdrawal debited an on-time credit that was never given; - -- pull it back after a punctual one and it debited nothing, leaving on_time - -- above submitted. `option<>` because every row predating 2026-08-04 has no - -- stored verdict and cannot be given one for a credit that already happened: - -- those fall back to the old comparison (see - -- [`crate::db::homework_submission::delete`]). - DEFINE FIELD IF NOT EXISTS counted_on_time ON homework_submission TYPE option; - -- The grade that froze this submission, absent while it is still open. The - -- freeze used to be a cross-table read (does a homework_result exist?) - -- followed by a write here, which no lock can hold across replicas; the - -- stamp turns every submission edit into a conditional single-record write - -- (`WHERE graded_by_result = NONE`), the one guard that survives. Set by - -- grading, cleared by un-grading, never by the student. - DEFINE FIELD IF NOT EXISTS graded_by_result ON homework_submission TYPE option>; - DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework; - - DEFINE TABLE IF NOT EXISTS homework_file SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS submission ON homework_file TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS name ON homework_file TYPE string; - DEFINE FIELD IF NOT EXISTS content_type ON homework_file TYPE string; - DEFINE FIELD IF NOT EXISTS size ON homework_file TYPE int; - DEFINE FIELD IF NOT EXISTS file ON homework_file TYPE string READONLY; - DEFINE FIELD IF NOT EXISTS created_at ON homework_file TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS homework_file_submission ON homework_file FIELDS submission; - - DEFINE TABLE IF NOT EXISTS homework_result SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS homework ON homework_result TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS user ON homework_result TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS status ON homework_result TYPE string; - DEFINE FIELD IF NOT EXISTS mark ON homework_result TYPE option; - DEFINE FIELD IF NOT EXISTS graded_by ON homework_result TYPE record; - DEFINE FIELD IF NOT EXISTS created_at ON homework_result TYPE int; - DEFINE INDEX IF NOT EXISTS homework_result_homework ON homework_result FIELDS homework; - - -- Appointments (greenfield, 2026-07-23): a teacher publishes availability - -- slots, a student or parent books one. `series` groups the occurrences a - -- weekly repeat expanded into, so one cancel deletes one row and a series - -- delete finds the rest. A booking's live/dead state is the `status` - -- string; `occupied` is the cap-1 counter that says whether the slot is - -- taken (2026-07-27 — it used to be counted from the booking rows under a - -- process-local lock, which two replicas could each pass), decremented in - -- the same transaction as the reject/cancel that frees it. - -- The `proposed_*` fields carry a teacher's counter-proposal on the same - -- row until the requester accepts. - DEFINE TABLE IF NOT EXISTS appointment_slot SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS teacher ON appointment_slot TYPE record; - DEFINE FIELD IF NOT EXISTS starts_at ON appointment_slot TYPE int; - DEFINE FIELD IF NOT EXISTS ends_at ON appointment_slot TYPE int; - DEFINE FIELD IF NOT EXISTS occupied ON appointment_slot TYPE option; - DEFINE FIELD IF NOT EXISTS note ON appointment_slot TYPE option; - DEFINE FIELD IF NOT EXISTS series ON appointment_slot TYPE option; - DEFINE FIELD IF NOT EXISTS created_at ON appointment_slot TYPE int; - DEFINE INDEX IF NOT EXISTS appointment_slot_teacher_starts ON appointment_slot FIELDS teacher, starts_at; - DEFINE INDEX IF NOT EXISTS appointment_slot_series ON appointment_slot FIELDS series; - - DEFINE TABLE IF NOT EXISTS appointment SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS slot ON appointment TYPE record; - DEFINE FIELD IF NOT EXISTS requester ON appointment TYPE record; - DEFINE FIELD IF NOT EXISTS status ON appointment TYPE string DEFAULT 'pending'; - DEFINE FIELD IF NOT EXISTS reason ON appointment TYPE string; - DEFINE FIELD IF NOT EXISTS proposed_starts_at ON appointment TYPE option; - DEFINE FIELD IF NOT EXISTS proposed_ends_at ON appointment TYPE option; - DEFINE FIELD IF NOT EXISTS proposed_by ON appointment TYPE option>; - DEFINE FIELD IF NOT EXISTS decided_by ON appointment TYPE option>; - DEFINE FIELD IF NOT EXISTS cancelled_by ON appointment TYPE option>; - DEFINE FIELD IF NOT EXISTS cancel_reason ON appointment TYPE option; - DEFINE FIELD IF NOT EXISTS reject_reason ON appointment TYPE option; - DEFINE FIELD IF NOT EXISTS created_at ON appointment TYPE int; - DEFINE INDEX IF NOT EXISTS appointment_slot_ref ON appointment FIELDS slot; - DEFINE INDEX IF NOT EXISTS appointment_requester ON appointment FIELDS requester; - DEFINE INDEX IF NOT EXISTS appointment_status ON appointment FIELDS status; - - -- Food program (greenfield, 2026-07-26): a published menu per day+slot, - -- dishes on it, a dietary profile per student, bookings against a menu's - -- capacity, who actually ate, and the money that moved. `date` is a - -- calendar day as `YYYY-MM-DD` text, not a timestamp: the unique index is - -- an equality test and a midnight-in-millis day is only unique for one - -- timezone. `slot` is snapshotted text, not a link, so retiring a slot in - -- settings never rewrites a past menu. Stamps stay `int` millis like the - -- rest of the schema. No BACKFILL: all six tables are new. - DEFINE TABLE IF NOT EXISTS menu SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS date ON menu TYPE string READONLY; - DEFINE FIELD IF NOT EXISTS slot ON menu TYPE string READONLY; - DEFINE FIELD IF NOT EXISTS capacity ON menu TYPE option; - -- `seats_booked` is the seat cap's counter (see `db::cap`) and - -- `version` the menu's revision: a booking claims its seat only while the - -- menu still stands at the revision it read the price at, so a dish - -- re-priced mid-booking cannot be billed as the old price. Both absent - -- means zero, which is what `(x ?? 0)` reads on a row written before them. - DEFINE FIELD IF NOT EXISTS seats_booked ON menu TYPE option; - DEFINE FIELD IF NOT EXISTS version ON menu TYPE option; - DEFINE FIELD IF NOT EXISTS created_by ON menu TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS created_at ON menu TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE; - - DEFINE TABLE IF NOT EXISTS menu_dish SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS menu ON menu_dish TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS name ON menu_dish TYPE string; - DEFINE FIELD IF NOT EXISTS description ON menu_dish TYPE option; - -- Money is minor units (kuruş) as an integer, everywhere. Never decimal. - DEFINE FIELD IF NOT EXISTS price_minor ON menu_dish TYPE int; - DEFINE FIELD IF NOT EXISTS tags ON menu_dish TYPE array DEFAULT []; - DEFINE FIELD IF NOT EXISTS tags[*] ON menu_dish TYPE string; - DEFINE FIELD IF NOT EXISTS created_at ON menu_dish TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS menu_dish_menu ON menu_dish FIELDS menu; - - DEFINE TABLE IF NOT EXISTS dietary_profile SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS student ON dietary_profile TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS tags ON dietary_profile TYPE array DEFAULT []; - DEFINE FIELD IF NOT EXISTS tags[*] ON dietary_profile TYPE string; - DEFINE FIELD IF NOT EXISTS note ON dietary_profile TYPE option; - DEFINE FIELD IF NOT EXISTS updated_by ON dietary_profile TYPE record; - DEFINE FIELD IF NOT EXISTS updated_at ON dietary_profile TYPE int; - DEFINE INDEX IF NOT EXISTS dietary_profile_student ON dietary_profile FIELDS student UNIQUE; - - -- A cancel flips `status` and stamps `cancelled_at`; the row stays so the - -- freed seat is still auditable against the ledger line it charged. - DEFINE TABLE IF NOT EXISTS meal_booking SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS menu ON meal_booking TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS student ON meal_booking TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS booked_by ON meal_booking TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS status ON meal_booking TYPE string DEFAULT 'booked'; - -- How many times this seat has been taken, and what it cost when the - -- *current* attempt took it (NONE = the menu was free then). Together they - -- key the attempt's ledger lines, which is what makes billing idempotent - -- by identity rather than by scanning for an outstanding charge. - DEFINE FIELD IF NOT EXISTS attempt ON meal_booking TYPE int DEFAULT 1; - DEFINE FIELD IF NOT EXISTS price_minor ON meal_booking TYPE option; - DEFINE FIELD IF NOT EXISTS cancelled_at ON meal_booking TYPE option; - DEFINE FIELD IF NOT EXISTS created_at ON meal_booking TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS meal_booking_menu ON meal_booking FIELDS menu; - DEFINE INDEX IF NOT EXISTS meal_booking_student ON meal_booking FIELDS student; - - DEFINE TABLE IF NOT EXISTS meal_attendance SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS menu ON meal_attendance TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS student ON meal_attendance TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS status ON meal_attendance TYPE string; - DEFINE FIELD IF NOT EXISTS marked_by ON meal_attendance TYPE record; - DEFINE FIELD IF NOT EXISTS marked_at ON meal_attendance TYPE int; - DEFINE INDEX IF NOT EXISTS meal_attendance_menu_student ON meal_attendance FIELDS menu, student UNIQUE; - - -- APPEND-ONLY by design: a mistake is corrected with an opposing - -- `reversal` line, never by editing or deleting one. Hence every field is - -- READONLY. `source` is untyped on purpose — a charge points at the - -- booking that caused it, a reversal at the line it undoes. - DEFINE TABLE IF NOT EXISTS meal_ledger SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS student ON meal_ledger TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS kind ON meal_ledger TYPE string READONLY; - DEFINE FIELD IF NOT EXISTS amount_minor ON meal_ledger TYPE int READONLY; - DEFINE FIELD IF NOT EXISTS source ON meal_ledger TYPE option READONLY; - DEFINE FIELD IF NOT EXISTS method ON meal_ledger TYPE option READONLY; - DEFINE FIELD IF NOT EXISTS note ON meal_ledger TYPE option READONLY; - DEFINE FIELD IF NOT EXISTS recorded_by ON meal_ledger TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS created_at ON meal_ledger TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS meal_ledger_student ON meal_ledger FIELDS student; - - -- A school fee plan: a name and its installments, each an amount and the - -- day it falls due. The installments are embedded (SCHEMAFULL, so the - -- object's own fields are declared too, same shape as `settings.exam_kinds`) - -- because a charge line copies the amount it was assigned at — child rows - -- would buy nothing. Neither field inside the object is optional: a NONE - -- value would be dropped from the stored object entirely. - DEFINE TABLE IF NOT EXISTS fee_plan SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS name ON fee_plan TYPE string; - DEFINE FIELD IF NOT EXISTS installments ON fee_plan TYPE array; - DEFINE FIELD IF NOT EXISTS installments.*.amount_minor ON fee_plan TYPE int; - DEFINE FIELD IF NOT EXISTS installments.*.due_at ON fee_plan TYPE int; - DEFINE FIELD IF NOT EXISTS created_by ON fee_plan TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS created_at ON fee_plan TYPE int READONLY; - -- How many students are on the plan. The edit and delete guards read it, - -- an assignment's own transaction increments it, and nothing decrements it - -- (assignments are never removed). `option` and no DEFAULT, like every - -- other counter: no Rust struct carries it, so the plan's create must not - -- be expected to state it. - DEFINE FIELD IF NOT EXISTS assignment_count ON fee_plan TYPE option; - - -- One plan on one student, keyed `_`: assigning twice is the - -- same record id, so a replay writes nothing and an assignment cut short - -- half-way self-heals when it is repeated. Nothing here is ever edited. - DEFINE TABLE IF NOT EXISTS fee_plan_assignment SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS plan ON fee_plan_assignment TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS student ON fee_plan_assignment TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS assigned_by ON fee_plan_assignment TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS created_at ON fee_plan_assignment TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS fee_plan_assignment_plan ON fee_plan_assignment FIELDS plan; - DEFINE INDEX IF NOT EXISTS fee_plan_assignment_student ON fee_plan_assignment FIELDS student; - - -- School fees, APPEND-ONLY by design exactly like `meal_ledger`: a mistake - -- is corrected with an opposing line, never by editing or deleting one, - -- hence every field is READONLY. `source` is untyped on purpose — a charge - -- points at the `fee_plan_assignment` that raised it, a credit at the charge - -- it pays, a refund at the credit it returns, a reversal at the line it - -- undoes. `due_at` is set on charges alone. - DEFINE TABLE IF NOT EXISTS payment_ledger SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS student ON payment_ledger TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS kind ON payment_ledger TYPE string READONLY; - DEFINE FIELD IF NOT EXISTS amount_minor ON payment_ledger TYPE int READONLY; - DEFINE FIELD IF NOT EXISTS source ON payment_ledger TYPE option READONLY; - DEFINE FIELD IF NOT EXISTS due_at ON payment_ledger TYPE option READONLY; - DEFINE FIELD IF NOT EXISTS method ON payment_ledger TYPE option READONLY; - DEFINE FIELD IF NOT EXISTS note ON payment_ledger TYPE option READONLY; - DEFINE FIELD IF NOT EXISTS recorded_by ON payment_ledger TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS created_at ON payment_ledger TYPE int READONLY; - DEFINE INDEX IF NOT EXISTS payment_ledger_student ON payment_ledger FIELDS student; - DEFINE INDEX IF NOT EXISTS payment_ledger_source ON payment_ledger FIELDS source; - - -- One row per badge a user has earned, keyed `{user}_{badge}` so the award - -- is written by an UPSERT that can never double (domain::badge). `earned_at` - -- is `option` because that is what makes the stamp write-once: the - -- UPSERT carries `WHERE earned_at = NONE`, so a re-sync of a badge already - -- held leaves the original date standing. Awards are permanent — nothing - -- deletes a row here — so the table needs no repair and no BACKFILL. - DEFINE TABLE IF NOT EXISTS badge_award SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS user ON badge_award TYPE record; - DEFINE FIELD IF NOT EXISTS badge ON badge_award TYPE string; - DEFINE FIELD IF NOT EXISTS earned_at ON badge_award TYPE option; - -- A plain field index, never `FIELDS user[*]`: the per-element form is used - -- by the planner and then returns zero rows (see the `course.teachers` note). - DEFINE INDEX IF NOT EXISTS badge_award_user ON badge_award FIELDS user; - - -- Reference counters, one row per *name* the settings offer, keyed by the - -- name itself (2026-07-27). They are how 'a kind nothing is graded under - -- may be removed' survives a second replica: the guard used to be a - -- count-then-write across two tables under a process-wide lock, and the - -- database serializes neither half of that. Both columns are `option<…>` - -- so an absent row reads as zero references, in service — the counter is - -- created by the first claim, never seeded per name. - DEFINE TABLE IF NOT EXISTS kind_ref SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS count ON kind_ref TYPE option; - DEFINE FIELD IF NOT EXISTS retired ON kind_ref TYPE option; - - DEFINE TABLE IF NOT EXISTS slot_ref SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS count ON slot_ref TYPE option; - DEFINE FIELD IF NOT EXISTS retired ON slot_ref TYPE option; - - -- One row per backfill that is genuinely *one-time*, keyed by the backfill's - -- own name (2026-08-02). Most of `BACKFILL` is a `WHERE` that matches no row - -- once it has converged, so re-running it is free — but a repair whose cost - -- is the *scan* rather than the write pays that cost on every boot forever, - -- and the board-roster sweep's scan is one full `user` pass per board. A - -- marker row is the smallest thing that can say 'this one is finished': the - -- boot loop carries no lock and no fingerprint any more (2026-07-30), so - -- there is nowhere else for that fact to live. A database that never ran the - -- repair holds no row and runs it; the row is written by the same query. - -- - -- `fingerprint` is *which* text ran (2026-08-05), and it is what makes a - -- marked block correctable. Saying only 'this ran' meant an edit to a block - -- that was already marked could never reach a volume that had booted once: - -- the `exam_sat_total` correction below shipped inside one and would have - -- been dead on arrival on every existing database. The gate compares the - -- stored number against the hash of the text *this* binary would run - -- (`database::marked_blocks`), so an edited block runs once more and - -- re-stamps, and an unedited one still costs a single record read. - -- `option`: a mark written before this column existed carries none, - -- which matches no fingerprint and so re-runs its block exactly once. - DEFINE TABLE IF NOT EXISTS migration_mark SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS done_at ON migration_mark TYPE int; - DEFINE FIELD IF NOT EXISTS fingerprint ON migration_mark TYPE option; -"; - -/// Data backfills for rows written by older binaries. Runs *after* (and apart -/// from) the DDL batch so every statement sees the freshly defined schema — -/// see the `MIGRATION` doc for why sharing the batch corrupts the writes. -/// Idempotent: each backfill's `WHERE` only matches unconverted rows. -pub const BACKFILL: &str = " - UPDATE user SET role = 'student' WHERE role = NONE; - - UPDATE course SET kind = 'course' WHERE kind = NONE; - - -- Courses predate assignable teachers (2026-07-21): every existing course - -- was run by its creator alone, so it starts with nobody else assigned. - UPDATE course SET teachers = [] WHERE teachers = NONE; - - -- Exams predate the draft flag (2026-07-19): everything already out there - -- was live for its course, so it stays published. - UPDATE exam SET draft = false WHERE draft = NONE; - - -- Exams predate the review toggle (2026-07-24): default it closed (opt-in). - UPDATE exam SET allow_review = false WHERE allow_review = NONE; - - UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {}; - - -- Questions written before subjects existed (2026-07-17) are destroyed, not - -- backfilled: a subject is mandatory and there is nothing truthful to - -- assign. Their answers go first so no answer row outlives its question. - DELETE exam_answer WHERE question IN (SELECT VALUE id FROM exam_question WHERE subject = NONE); - DELETE exam_question WHERE subject = NONE; - - -- The hand-picked `users` audience retired into `registration` (2026-07-16): - -- each listed user becomes a signup row credited to the event's creator, and - -- the event becomes an uncapped registration list. Runs once — converted - -- events no longer match the `kind = 'users'` filter. (`?? []`: an empty - -- statement-subquery evaluates to NONE, which FOR refuses to iterate.) - FOR $ev IN ((SELECT id, creator, audience FROM event WHERE audience.kind = 'users') ?? []) { - FOR $usr IN ($ev.audience.users ?? []) { - UPSERT type::record('registration', string::concat(record::id($ev.id), '_', record::id($usr))) CONTENT { - event: $ev.id, - user: $usr, - registered_by: $ev.creator, - }; - }; - UPDATE $ev.id SET audience = { kind: 'registration' }; - }; - - -- Turns written before the clipped-answer flag existed (2026-07-23): the - -- clip was silent then, so nothing can be recovered — they read as whole, - -- which is what they were presented as all along. - UPDATE chatbot_message SET truncated = false WHERE truncated = NONE; - - -- An assistant turn is answered by a task in this process, so a restart can - -- leave its row `pending` with nobody left to complete it. Only rows past - -- the stale horizon ($stale_ms, from `CHATBOT_PENDING_STALE_SECS`) are - -- certainly abandoned though: a young one may still be being answered on - -- the other side of the AI bridge, and a deploy must not shoot down a turn - -- dispatched seconds ago. Nothing is lost by waiting — a reader already - -- presents an over-age `pending` row as failed, and the next boot sweeps - -- for real whatever crossed the horizon in the meantime. - -- - -- The claim half of this guard went with the claim queue (2026-07-30): it - -- only ever spared a row a *live peer* was answering, and there is no peer. - -- The rows selected are otherwise the same ones — an unclaimed row past the - -- horizon was always swept, and a claim of this process's own could not - -- outlive the process whose boot is running this. - UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted', - completed_at = time::unix(time::now()) * 1000 - WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms; - - -- The seats the sweep below spent every past boot *not* giving back: until - -- today it deleted those rows without touching the course's counter, so - -- every course it ever swept carries a phantom seat — one that denies a real - -- student a place, and that `Course::delete` refuses to let anyone past, - -- forever (its guard is `(enrollment_count ?? 0) = 0` on the course row). - -- This recomputes the counter for every course whose stored number disagrees - -- with the enrollment rows it actually has. - -- - -- Counting the rows cannot read *low*. The counter has exactly one meaning — - -- the live enrollment rows of this course — and every writer moves it with - -- the row in one transaction (`db::enrollment`'s `enroll`/`remove`, `set_role`'s - -- demotion sweep, the class pump's attach and detach); `Course::delete` takes - -- the rows *and* the course together, so no cascade leaves counted rows - -- behind. That is what separates it from the lifetime tallies below, which - -- are seeded once precisely because their rows do die under them. The claims - -- that borrow this column as a collision device (`cap::touch_and_create`, - -- `Axis::pivot_claim`) bump and restore it inside their own transaction, so - -- no other reader ever sees the raised value — and `migrate` runs to - -- completion before the router is bound, one process per volume, so there is - -- no concurrent writer to see it from anyway. - -- - -- Neither `= NONE`-guarded nor marked, for the board-stroke repair's reason: - -- this is not an opinion the live system maintains, it is the course's row - -- count, so recomputing converges instead of overwriting and the `!=` guard - -- writes nothing on the next boot. It runs *before* the sweep, so the two - -- own separate halves of the same invariant — this one clears the drift the - -- volume arrived with, the sweep's own decrement leaves none behind — and it - -- does not fight the `= NONE` seeding further down either: a pre-counter - -- course with rows gets the same number here that the seeding would have - -- given it, and one with no rows stays absent for the zero pass to fill. - -- - -- Per course rather than `GROUP BY course`, because the case that matters - -- most forms no group: a course whose last enrollment the sweep took away has - -- zero rows and a counter above zero, and a grouped pass would never visit - -- it. `array::len` over ids rather than `count()`, because an aggregate over - -- an indexed field (`enrollment` is indexed on `course`) can come back as - -- `{ count: n }` from the server — a shape the in-memory engine never - -- produces and `option` would refuse. - FOR $c IN ((SELECT VALUE id FROM course) ?? []) { - LET $live = array::len((SELECT VALUE id FROM enrollment WHERE course = $c)); - UPDATE $c SET enrollment_count = $live WHERE (enrollment_count ?? 0) != $live; - }; - - -- Promotion out of student now deletes the user's enrollments (2026-07-18); - -- this sweeps rows promoted before that fix. A deleted user reads as - -- `user.role = NONE`, which is also != 'student' — those rows go too. - -- - -- The course's seat goes back with the row, per course, exactly the way - -- `User::set_role`'s own demotion sweep releases it: the counter is the - -- roster's authority, so a swept row that kept its seat denies a real - -- student a place *and* makes the course undeletable for good - -- (`Course::delete` refuses on `(enrollment_count ?? 0) = 0`). Several rows - -- of one course each take their own turn through the loop, so the counter - -- comes down by exactly as many rows as went. - LET $swept = (DELETE enrollment WHERE user.role != 'student' RETURN BEFORE); - FOR $row IN ($swept ?? []) { - UPDATE $row.course SET enrollment_count = - math::max([(enrollment_count ?? 0) - 1, 0]); - }; - - -- Choices gained stable ids (2026-07-24): `choices` held bare strings and - -- `correct`/`selected`/`slot` held the option's *position*. The DDL above - -- retypes those columns, which leaves every old-shaped row readable but - -- unwritable ('Expected `none | array` but found `[..]`'), so this - -- conversion is repair, not cosmetics. - -- - -- Ids are minted in array order, so the id at position i *is* the id for - -- old index i — that identity is what keeps a stored answer, and an option - -- picture, pointing at the option the student actually saw. Hence the - -- dependent rows are remapped inside the loop that mints `$new`, against - -- that same array: once the ids are stored the positions are still - -- recoverable, but nothing guarantees a later pass would look them up the - -- same way. `WHERE choices[0] != NONE AND type::is_string(choices[0])` - -- matches only unconverted rows, so a second boot re-mints nothing; an - -- empty or absent `choices` needs no conversion at all. A question-level - -- picture (`slot = NONE`) is not an index and is left alone. - -- - -- Runs *before* every other backfill that writes these rows (the `seq` - -- stamps below): a write coerces the whole record, so touching a row for - -- any reason fails while its choices are still positional. For the same - -- reason the answer's remap stamps `seq` itself — the two legacy gaps sit - -- on the same row, and a write that fixes only one of them is rejected for - -- the other. `seq ?? 1` leaves an already-numbered sitting alone (DEFAULT - -- fills a CREATE, not an UPDATE of a row that predates the column). - FOR $q IN ((SELECT id, choices, correct FROM exam_question - WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) { - LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c }); - UPDATE $q.id SET choices = $new, - correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id }; - FOR $img IN ((SELECT id, slot FROM question_image - WHERE question = $q.id AND type::is_int(slot)) ?? []) { - UPDATE $img.id SET slot = $new[$img.slot].id; - }; - FOR $ans IN ((SELECT id, selected FROM exam_answer - WHERE question = $q.id AND type::is_int(selected)) ?? []) { - UPDATE $ans.id SET selected = $new[$ans.selected].id, seq = seq ?? 1; - }; - }; - - FOR $q IN ((SELECT id, choices, correct FROM bank_question - WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) { - LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c }); - UPDATE $q.id SET choices = $new, - correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id }; - FOR $img IN ((SELECT id, slot FROM bank_question_image - WHERE bank_question = $q.id AND type::is_int(slot)) ?? []) { - UPDATE $img.id SET slot = $new[$img.slot].id; - }; - }; - - -- Per-attempt history (2026-07-24): sittings, answers, drawings, and marks - -- written before retakes stopped wiping belong to the student's first - -- sitting. They already use the bare (seq==1) record key, so only the - -- denormalized `seq` field needs stamping. - -- - -- `exam_attempt` was left out of this list when the other three were added - -- and that is not a decision, it is a gap: `DEFAULT 1` fills a CREATE, never - -- a row stored before the column was defined, and 3.2.3 does not synthesize - -- it on read either — such a row comes back with no `seq` key at all, which - -- makes `ExamAttempt` (a non-`option` `i64`) fail to deserialize *and* makes - -- every later write to the row fail coercion, so finishing or leaving that - -- sitting 500s forever. Ungated like its siblings and for the same reason: - -- the cost here is the write, not a scan, and `WHERE seq = NONE` matches - -- nothing the moment it has converged. - UPDATE exam_attempt SET seq = 1 WHERE seq = NONE; - UPDATE exam_answer SET seq = 1 WHERE seq = NONE; - UPDATE answer_image SET seq = 1 WHERE seq = NONE; - UPDATE exam_result SET seq = 1 WHERE seq = NONE; - - -- The homework freeze became cross-replica (2026-07-27): a grade that - -- predates the stamp column has to put it on the submission it already - -- froze, or that submission would read as open and be editable again. - -- Result and submission share the deterministic `{homework}_{user}` key, so - -- the owning row is addressed directly rather than searched for; an UPDATE - -- of a record that isn't there (graded absent work) is an empty no-op. The - -- `= NONE` guard keeps it one-time, for the same reason the counters below - -- are one-time — migrate() runs again on every boot against a volume the - -- live system has been writing to since. - FOR $r IN ((SELECT VALUE id FROM homework_result) ?? []) { - UPDATE type::record('homework_submission', record::id($r)) - SET graded_by_result = $r WHERE graded_by_result = NONE; - }; - - -- Count caps became cross-replica (2026-07-27): the authority moved from a - -- process-wide mutex to a counter column on the parent row, so every parent - -- that predates the column is seeded from the children it actually has. - -- Runs LAST, after the sweeps above have deleted whatever they delete. - -- - -- Deliberately one-time (`= NONE` guards every write): migrate() reruns on - -- every boot of an existing volume, and recounting a seeded counter would - -- overwrite what the live system has maintained since. An absent - -- counter reads as zero, so the group pass runs before the zero pass. - FOR $row IN ((SELECT course, count() AS n FROM enrollment GROUP BY course) ?? []) { - UPDATE $row.course SET enrollment_count = $row.n WHERE enrollment_count = NONE; - }; - UPDATE course SET enrollment_count = 0 WHERE enrollment_count = NONE; - - -- The one refcount among them: courses per term, not children per parent. - -- Same one-time `= NONE` guard, and `WHERE term != NONE` keeps the - -- unlinked courses out of the group (they would form a NONE bucket). - FOR $row IN ((SELECT term, count() AS n FROM course WHERE term != NONE GROUP BY term) ?? []) { - UPDATE $row.term SET course_count = $row.n WHERE course_count = NONE; - }; - UPDATE term SET course_count = 0 WHERE course_count = NONE; - - FOR $row IN ((SELECT event, count() AS n FROM registration GROUP BY event) ?? []) { - UPDATE $row.event SET registration_count = $row.n WHERE registration_count = NONE; - }; - UPDATE event SET registration_count = 0 WHERE registration_count = NONE; - - FOR $row IN ((SELECT note, count() AS n FROM note_file GROUP BY note) ?? []) { - UPDATE $row.note SET file_count = $row.n WHERE file_count = NONE; - }; - UPDATE note SET file_count = 0 WHERE file_count = NONE; - - FOR $row IN ((SELECT submission, count() AS n FROM homework_file GROUP BY submission) ?? []) { - UPDATE $row.submission SET file_count = $row.n WHERE file_count = NONE; - }; - UPDATE homework_submission SET file_count = 0 WHERE file_count = NONE; - - FOR $row IN ((SELECT user_id, count() AS n FROM chatbot_thread GROUP BY user_id) ?? []) { - UPDATE $row.user_id SET chatbot_thread_count = $row.n WHERE chatbot_thread_count = NONE; - }; - UPDATE user SET chatbot_thread_count = 0 WHERE chatbot_thread_count = NONE; - - -- The appointment slot's counter is the odd one out: it counts only the - -- bookings that are still *live*, because a rejected or cancelled one gave - -- the slot back long before this column existed. - FOR $row IN ((SELECT slot, count() AS n FROM appointment - WHERE status IN ['pending', 'approved'] GROUP BY slot) ?? []) { - UPDATE $row.slot SET occupied = $row.n WHERE occupied = NONE; - }; - UPDATE appointment_slot SET occupied = 0 WHERE occupied = NONE; - - -- A menu's seats, counted from the bookings still *held* — a cancelled one - -- gave its seat back before this column existed, exactly like the slot - -- above. `version` gets no pass at all: absent already reads as revision - -- zero everywhere it is compared, so writing it would be a no-op that - -- touches every menu row. - FOR $row IN ((SELECT menu, count() AS n FROM meal_booking - WHERE status = 'booked' GROUP BY menu) ?? []) { - UPDATE $row.menu SET seats_booked = $row.n WHERE seats_booked = NONE; - }; - UPDATE menu SET seats_booked = 0 WHERE seats_booked = NONE; - - -- A subject's two reference counters, seeded from what actually points at - -- it. This must run *after* the legacy sweep above destroys the questions - -- that predate subjects, or a subject would be seeded with rows that are - -- about to vanish and could then never be deleted. No zero pass, for the - -- same reason `version` gets none: absent already reads as zero in the - -- delete's `(count ?? 0) = 0` guard, so writing it would touch every - -- subject row to say what it already says. - FOR $row IN ((SELECT subject, count() AS n FROM exam_question GROUP BY subject) ?? []) { - UPDATE $row.subject SET exam_question_count = $row.n WHERE exam_question_count = NONE; - }; - - FOR $row IN ((SELECT subject, count() AS n FROM homework GROUP BY subject) ?? []) { - UPDATE $row.subject SET homework_count = $row.n WHERE homework_count = NONE; - }; - - -- The settings guards became cross-replica the same way (2026-07-27): an - -- exam kind counts the marks written under it, a meal slot the menus - -- published for it, and a name is removable exactly while its counter reads - -- zero. Rows written before the counters existed are counted once here. - -- - -- Same `= NONE` guard and the same reason as the caps above: migrate() - -- reruns on every boot of an existing volume, and recounting a seeded - -- counter would overwrite what the live system has maintained since, handing - -- back a reference that is still held. No zero pass either — an - -- absent counter already reads as zero, and a name nobody ever used needs - -- no row at all. - -- - -- Marks predate the counter but so may their *kind*: an exam whose kind was - -- removed from the list long ago is counted too, which only ever refuses a - -- removal that already happened. `slot` is text on the menu, so its group - -- needs no join; `kind` lives on the exam, one hop from the mark. - FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result GROUP BY kind) ?? []) { - UPSERT type::record('kind_ref', $row.kind) SET count = $row.n WHERE count = NONE; - }; - - FOR $row IN ((SELECT slot, count() AS n FROM menu GROUP BY slot) ?? []) { - UPSERT type::record('slot_ref', $row.slot) SET count = $row.n WHERE count = NONE; - }; - - -- Same one-time seeding for the per-exam mark counter: an exam graded by an - -- older binary must read as graded, or its kind could be changed under the - -- marks it already carries. - FOR $row IN ((SELECT exam, count() AS n FROM exam_result GROUP BY exam) ?? []) { - UPDATE $row.exam SET result_count = $row.n WHERE result_count = NONE; - }; - - -- The fee-plan guard became a refcount (2026-07-30): editing or deleting a - -- plan is now refused by `(assignment_count ?? 0) = 0` on the plan row - -- itself, instead of by a scan a concurrent assign could land behind. - -- - -- This seeding is what keeps a *stale* volume safe: a plan written by an - -- older binary carries no counter, an absent counter reads as zero, and a - -- zero would make an already-assigned plan editable and deletable again — - -- the exact thing the 409 exists to prevent. Boot seeds it from the - -- assignment rows that actually exist, and `migrate` runs to completion - -- before the router is bound, so no request is ever served against the - -- unseeded shape. `= NONE` keeps it one-time, so a second boot recomputes - -- nothing. - -- - -- No zero pass, for the same reason the subject counters get none: a plan - -- nobody is on has no assignment rows, and absent already reads as zero in - -- the guard — writing it would touch every plan row to say what it says. - FOR $row IN ((SELECT plan, count() AS n FROM fee_plan_assignment GROUP BY plan) ?? []) { - UPDATE $row.plan SET assignment_count = $row.n WHERE assignment_count = NONE; - }; - - -- The clear marker began paying the board's lifetime counter (2026-08-02): - -- it is a real `board_stroke` row, so a marker that charged nothing left - -- `total_stroke_count` counting marks *drawn* instead of rows *stored*, and - -- every board an older binary cleared is short exactly one per past clear. - -- - -- The only repair here that is NOT `= NONE`-guarded, and the one counter - -- that may be: it is not an opinion the live system maintains, it is the - -- board's row count — every stroke and every marker charges 1, and a stroke - -- row is only ever deleted with the board itself (domain::board_stroke). - -- So recomputing converges instead of overwriting, and `!= $row.n` writes - -- nothing on the next boot, when every counter already equals its count. - -- No zero pass: a board nobody drew on forms no group, and an absent - -- counter already reads as zero through the `?? 0` every reader applies. - FOR $row IN ((SELECT board, count() AS n FROM board_stroke GROUP BY board) ?? []) { - UPDATE $row.board SET total_stroke_count = $row.n WHERE total_stroke_count != $row.n; - }; - - -- Board rosters became self-repairing (2026-08-02). `set_role` sweeps a - -- demoted user off every board *going forward*, but a volume written before - -- that sweep still holds rosters naming parents — and ids of users who have - -- since been deleted outright, which no sweep ever covered. - -- - -- It is not a cosmetic staleness: the roster is served back on every read - -- and `resolve_participants` refuses an id that no longer resolves to a - -- student-or-above, so the creator's next read-modify-write roster PATCH - -- echoes the stale id and takes a 400 — the board's invite list is frozen - -- until the row is repaired. - -- - -- `parent` is the only role below `student` (domain::role), so `!= 'parent'` - -- is the same cut `Role::at_least(Student)` makes; a missing user matches no - -- row and so falls out of `$keep` for free. A board whose whole roster is - -- stale ends with `participants = []` — the creator alone on it, which is - -- the same shape a board created without invites carries. Not `= NONE` - -- guarded and it need not be: `$keep` is derived from the rows that exist, - -- so it converges, and `WHERE participants != $keep` writes nothing on the - -- next boot. `$keep` comes back deduped and in record-id order, so a - -- repaired row can be *reordered* relative to what it stored, never - -- duplicated — and the roster is a set to every reader. - -- - -- Marked one-time (`migration_mark`), unlike every backfill above it. Those - -- converge to a `WHERE` that matches nothing, so their second run is a cheap - -- index probe; this one's cost is the *scan* — a `board` table scan whose - -- body runs a full `user` scan per row, measured at 773ms for 300 boards - -- over 2000 users on a boot with nothing left to write. That is paid on - -- every restart forever, and it buys nothing: `set_role` sweeps rosters - -- going forward and a deleted user is swept with its row, so no new stale id - -- is ever created. The mark is written *after* the loop and in the same - -- statement batch, so a boot killed mid-repair writes no mark and the next - -- one redoes the whole sweep — which is free, because the sweep is - -- idempotent. `UPSERT`, not `CREATE`: re-marking must never be an error. - -- - -- Editing this block is therefore safe at any time: the fingerprint gate - -- re-runs it once and the sweep converges on whatever it finds, exactly as - -- a boot killed mid-repair would. The mark buys the scan back, not - -- correctness. - IF array::len((SELECT VALUE id FROM migration_mark:board_roster - WHERE fingerprint = $fp_board_roster)) = 0 { - FOR $row IN ((SELECT id, participants FROM board WHERE array::len(participants ?? []) > 0) ?? []) { - LET $keep = (SELECT VALUE id FROM user WHERE id IN $row.participants AND role != 'parent'); - UPDATE $row.id SET participants = $keep WHERE participants != $keep; - }; - UPSERT migration_mark:board_roster SET done_at = time::unix(time::now()) * 1000, - fingerprint = $fp_board_roster; - }; - - -- The badge counters, seeded from the history that already exists - -- (2026-08-04). Badges are earned off stored lifetime totals, and every - -- account on an existing volume predates the columns — so starting them all - -- at zero would not merely lose a number, it would mis-award every student - -- permanently: someone who really handed in 40 homeworks would owe 10 *more* - -- than a new account does to reach the same badge. The counts below are the - -- rows that exist, so the seed says exactly what the student did. - -- - -- Marked one-time, like the board-roster sweep above and unlike every other - -- backfill in this file — but for the opposite reason. Those recompute a - -- number the live system does not own; these columns are maintained by the - -- request path from here on (a submission increments as it lands), so a - -- second recount would not converge, it would *overwrite* everything earned - -- since boot. The mark is the only thing that makes that safe. - -- - -- The reset is inside the mark and comes first, so the whole block is - -- recompute-from-scratch: a boot killed mid-seed writes no mark and the next - -- one redoes it from a clean slate, and an operator who clears the mark to - -- force a re-seed gets the counts as they stand rather than a stale high - -- water mark. It is the one place a *zero pass* is right: it writes over - -- whatever a half-finished pass left, and it runs exactly once per volume. - -- - -- Every counter here has to *mean* what the request path means, or a - -- pre-existing student diverges from a new one forever. So the on-time cut - -- is `submitted_at <= due_at`, the stamp both live sites use: the create - -- credits on the first hand-in and the delete debits by `submitted_at`, so - -- judging the seed by `updated_at` would let a withdrawal decrement a - -- submission the seed never credited and drive the counter *below* the - -- truth — and `touch()` moves `updated_at` on every file add or delete, so - -- merely attaching a file after the deadline would have done it. A dangling - -- `homework` link still falls out of the pass rather than counting as on - -- time (the traversal yields no value, so the comparison fails). - -- - -- The focus sum floors *per row*, like the live close does - -- (`math::max([started_at, done])`), not per user: a legacy stint written - -- with a backwards clock is negative, and flooring the total instead would - -- let one such row swallow the real stints beside it. `math::max` *around* - -- the aggregate is the spelling that is rejected ('nested aggregate - -- functions are not supported'); inside it, per row, is fine. - -- - -- Two counters the seed cannot make whole, for the same reason: - -- `exam_sat_total` (deleting an exam or a course deletes its `exam_attempt` - -- rows) and `homework_submitted_total` (deleting a homework cascades its - -- `homework_submission` rows away). Neither delete decrements — deliberate, - -- a lifetime 'did it' tally must not shrink because a teacher tidied up — so - -- the live count stands where the request path left it while a re-seed of - -- the same volume would read *lower*: the rows do not exist to be counted. - -- Do not 'repair' this by making the live path decrement; that breaks the - -- tally for everyone to patch history for a few. - -- - -- `counted_on_time` is stamped here too, for every row the pass looks at and - -- by the very same cut, so a submission that predates this seed debits at - -- withdrawal exactly what the seed credited it. Absolute like every SET - -- below, so it converges on a forced re-seed. - -- - -- corner-cut: editing this block re-runs it (the fingerprint gate), and unlike - -- the board sweep above this one is only *mostly* re-runnable. Every SET is - -- absolute, so a re-run converges on the rows that exist — but two of the - -- counters are lifetime tallies the request path never decrements while the - -- rows behind them can be deleted (`exam_sat_total`, - -- `homework_submitted_total`, see the paragraph above). On a volume where a - -- teacher has deleted an exam or a homework since the last seed, a re-run - -- reads *lower* than the live count and the student's tally walks backwards - -- — badges already awarded are permanent, so nothing is revoked, but the - -- next one moves further away. Correcting this block is a deliberate trade, - -- not a free edit. The upgrade path, if it ever needs to be free: keep the - -- deleted rows' contribution on the row (a `*_retired` column the delete - -- bumps) so the recount can add it back. - IF array::len((SELECT VALUE id FROM migration_mark:profile_counters - WHERE fingerprint = $fp_profile_counters)) = 0 { - UPDATE user SET homework_submitted_total = 0, homework_on_time_total = 0, - exam_sat_total = 0, pomodoro_finished_total = 0, pomodoro_focus_ms_total = 0; - FOR $row IN ((SELECT user, count() AS n FROM homework_submission GROUP BY user) ?? []) { - UPDATE $row.user SET homework_submitted_total = $row.n; - }; - FOR $row IN ((SELECT user, count() AS n FROM homework_submission - WHERE submitted_at <= homework.due_at GROUP BY user) ?? []) { - UPDATE $row.user SET homework_on_time_total = $row.n; - }; - UPDATE homework_submission SET counted_on_time = submitted_at <= homework.due_at; - -- `(seq ?? 1) = 1` is one row per (exam, student) pair, so this counts - -- *exams sat* — what the request path credits (a retake writes a higher - -- seq and moves nothing). Counting every row instead would seed a - -- pre-existing student above a new one for the same work, and above - -- what the live path would ever give them again. - FOR $row IN ((SELECT user, count() AS n FROM exam_attempt - WHERE (seq ?? 1) = 1 GROUP BY user) ?? []) { - UPDATE $row.user SET exam_sat_total = $row.n; - }; - FOR $row IN ((SELECT user, count() AS sessions, - math::sum(math::max([finished_at - started_at, 0])) AS focus_ms - FROM pomodoro_session WHERE finished_at != NONE GROUP BY user) ?? []) { - UPDATE $row.user SET pomodoro_finished_total = $row.sessions, - pomodoro_focus_ms_total = $row.focus_ms; - }; - UPSERT migration_mark:profile_counters SET done_at = time::unix(time::now()) * 1000, - fingerprint = $fp_profile_counters; - }; -"; - -/// The **control** database's schema — the one database per deployment that -/// knows which schools exist and who may create them. Everything else lives in -/// a school database, whose schema is [`MIGRATION_BATCHES`] and is applied -/// per school by [`crate::tenant::Tenants::create`]. -/// -/// The `rate_limit` copy is deliberate: the shared per-IP window -/// (`crate::rate_limit::RateLimiter::share`) is billed against the control -/// handle, because the limiter runs in front of the router — before any cookie -/// has named a school. One budget per deployment is also the honest one for an -/// unauthenticated brute-forcer, who has not picked a school yet either. -pub const CONTROL_MIGRATION: &str = " - DEFINE TABLE IF NOT EXISTS school SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS slug ON school TYPE string; - DEFINE FIELD IF NOT EXISTS name ON school TYPE string; - DEFINE FIELD IF NOT EXISTS status ON school TYPE string; - DEFINE FIELD IF NOT EXISTS created_at ON school TYPE int; - -- Which product modules this school has bought (see `crate::module`). The - -- names are bound from `Module::ALL`, never spelled here, so a new module - -- cannot be forgotten in this string. - DEFINE FIELD IF NOT EXISTS modules ON school TYPE array DEFAULT []; - -- Only `NONE` — a row written before the field existed, which predates the - -- idea of buying modules and so had all of them. An empty array is a - -- deliberate \"nothing enabled\" and must never be re-widened by a boot. - UPDATE school SET modules = $all_modules WHERE modules = NONE; - -- Redundant with the `school:` id, and kept anyway: the id is the - -- fast path, the index is what makes a second row on the same slug - -- impossible if a future write ever mints an id some other way. - DEFINE INDEX IF NOT EXISTS school_slug ON school FIELDS slug UNIQUE; - - DEFINE TABLE IF NOT EXISTS builder SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS username ON builder TYPE string; - DEFINE FIELD IF NOT EXISTS password_hash ON builder TYPE string; - DEFINE INDEX IF NOT EXISTS builder_username ON builder FIELDS username UNIQUE; - - DEFINE TABLE IF NOT EXISTS builder_session SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS builder ON builder_session TYPE record; - DEFINE FIELD IF NOT EXISTS token ON builder_session TYPE string; - DEFINE FIELD IF NOT EXISTS created_at ON builder_session TYPE int; - DEFINE FIELD IF NOT EXISTS expires_at ON builder_session TYPE int; - DEFINE INDEX IF NOT EXISTS builder_session_token ON builder_session FIELDS token UNIQUE; - DEFINE INDEX IF NOT EXISTS builder_session_expires ON builder_session FIELDS expires_at; - - -- Verbatim from `MIGRATION`; see the note above this constant. - DEFINE TABLE IF NOT EXISTS rate_limit SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS hits ON rate_limit TYPE int DEFAULT 0; - DEFINE FIELD IF NOT EXISTS window_start ON rate_limit TYPE int; -"; - -pub const CONTROL_MIGRATION_BATCHES: [&str; 1] = [CONTROL_MIGRATION]; - -/// The migration batches, in the order a boot applies them — and the *only* -/// list of them. [`crate::database::migrate`] runs exactly these. They stay -/// three separate queries: statements in one batch see the schema as it stood -/// when the batch started (see `MIGRATION`). -pub const MIGRATION_BATCHES: [&str; 3] = [PRE_REPAIR, MIGRATION, BACKFILL]; diff --git a/src/rate_limit.rs b/src/rate_limit.rs index 46826f4..2dd6a25 100644 --- a/src/rate_limit.rs +++ b/src/rate_limit.rs @@ -86,7 +86,6 @@ use std::time::Duration; use axum::extract::{ConnectInfo, Request}; use axum::middleware::Next; use axum::response::Response; -use surrealdb::types::RecordId; // tokio's `Instant` wraps `std::time::Instant` in production but obeys // `tokio::time::pause`/`advance` under `start_paused` tests, which makes the // window arithmetic below testable without sleeping. @@ -99,7 +98,6 @@ use crate::constant::{ use crate::database::Database; use crate::domain::timestamp::Timestamp; use crate::error::AppError; -use crate::state::DbHealth; use crate::telemetry::Metrics; /// Per-IP rate-limit knobs, sourced from the environment (see `.env.example`) and @@ -221,7 +219,7 @@ impl RateLimiter { } } -/// The per-user tier, keyed by user record key instead of client IP. Lives in +/// The per-user tier, keyed by user id instead of client IP. Lives in /// [`crate::state::AppState`] and is called from inside a handler, after /// `CurrentUser` has identified the caller. pub type UserRateLimiter = RateLimiter; @@ -433,8 +431,8 @@ where /// The task holds a *weak* reference to the buckets, so it stops with the /// limiter rather than keeping a dropped one alive (test suites build /// dozens). - pub fn share(&self, tier: &'static str, db: Database, db_up: DbHealth) { - self.share_windowed(tier, db, db_up, None); + pub fn share(&self, tier: &'static str, db: Database) { + self.share_windowed(tier, db, None); } /// [`RateLimiter::share`] with the wall window pinned, for tests only. @@ -445,17 +443,11 @@ where /// would see the other's spend. An accidental relationship to the wall /// clock is precisely what kept the epoch-roll double-charge out of /// `tests/rate_limit.rs`, so the sharing tests choose their window instead. - pub fn share_pinned(&self, tier: &'static str, db: Database, db_up: DbHealth, epoch: i64) { - self.share_windowed(tier, db, db_up, Some(epoch)); + pub fn share_pinned(&self, tier: &'static str, db: Database, epoch: i64) { + self.share_windowed(tier, db, Some(epoch)); } - fn share_windowed( - &self, - tier: &'static str, - db: Database, - db_up: DbHealth, - pinned: Option, - ) { + fn share_windowed(&self, tier: &'static str, db: Database, pinned: Option) { // Before the early return: a disabled tier still wants its name, so a // limiter turned on later reports under it. let _ = self.tier.set(tier); @@ -473,20 +465,19 @@ where let Some(buckets) = buckets.upgrade() else { return; }; - // Never queue work on a database that is down: the SDK parks a - // query instead of failing it, so this task would sit on a - // round for the whole outage and then apply a stale total. - if !db_up.is_up() { - continue; - } + // `with_deadline` bounds every round, so an outage costs the + // sharing nothing but skipped rounds: local budgets keep + // admitting and the deltas ride the first round after recovery. let epoch = pinned.unwrap_or_else(|| current_epoch(window)); sync_once(tier, &buckets, window, epoch, &db).await; // Piggybacked cleanup, once per window: rows for a window that // has passed can never be read again. if swept != epoch { swept = epoch; - let sql = format!("DELETE {RATE_LIMIT_TABLE} WHERE window_start < $cutoff"); - if let Err(err) = with_deadline(db.query(sql).bind(("cutoff", epoch))).await { + let sql = format!("DELETE FROM {RATE_LIMIT_TABLE} WHERE window_start < $1"); + if let Err(err) = + with_deadline(sqlx::query(&sql).bind(epoch).execute(&db)).await + { tracing::warn!(%err, "rate-limit sweep failed; retrying next window"); } } @@ -495,14 +486,17 @@ where } } -/// Fold every live bucket's new admits into its shared row and take the -/// window's total back. +/// Fold every live bucket's new admits into their shared rows and take the +/// window's totals back. /// -/// One statement per bucket in one query, and each statement is its own -/// transaction — so a statement that loses a write race fails alone. Its bucket -/// simply keeps the delta unreported and the next round (2s later) carries it, -/// which is why no retry loop is needed here: retrying the *query* would -/// double-apply the statements that did land, since `hits` accumulates. +/// The whole round is one statement: `INSERT … ON CONFLICT (id) DO UPDATE SET +/// hits = rate_limit.hits + EXCLUDED.hits RETURNING id, hits`, so a fold is +/// atomic — the old engine could fail one bucket's statement inside a round, +/// Postgres cannot fail half a statement. A round that fails (deadline, +/// outage) lands nothing: every bucket keeps its delta unreported and the +/// next round (2s later) carries it, which is why no retry loop is needed +/// here. Retrying the *statement* would double-apply the hits that landed, +/// since the fold accumulates — skipping a round is the only honest failure. async fn sync_once( tier: &str, buckets: &Mutex>, @@ -551,34 +545,38 @@ async fn sync_once( return; } - let sql: String = (0..pending.len()) - .map(|i| { - format!("UPSERT $id{i} SET hits = (hits ?? 0) + $delta{i}, window_start = $window RETURN VALUE hits;") - }) - .collect(); - let mut query = db.query(sql).bind(("window", epoch)); - for (i, p) in pending.iter().enumerate() { - let id = RecordId::new(RATE_LIMIT_TABLE, row_key(tier, &p.key, epoch)); - query = query - .bind((format!("id{i}"), id)) - .bind((format!("delta{i}"), i64::from(p.delta))); - } - let mut response = match with_deadline(query).await { - Ok(response) => response, + // One statement for the whole round. A row's id pins its wall window + // (`row_key` folds the epoch in), so a conflict can only be another + // limiter of the same tier folding the same client inside the same window + // — the ON CONFLICT fold is exactly the replay that must add, not clobber. + let mut fold = sqlx::QueryBuilder::::new(); + fold.push("INSERT INTO ") + .push(RATE_LIMIT_TABLE) + .push(" (id, hits, window_start) "); + fold.push_values(pending.iter(), |mut b, p| { + b.push_bind(row_key(tier, &p.key, epoch)) + .push_bind(i64::from(p.delta)) + .push_bind(epoch); + }); + fold.push(" ON CONFLICT (id) DO UPDATE SET hits = rate_limit.hits + EXCLUDED.hits RETURNING id, hits"); + let rows: Vec<(String, i64)> = match with_deadline(fold.build_query_as()).await { + Ok(rows) => rows, Err(err) => { tracing::warn!(%err, tier, "rate-limit sync failed; counting locally until it recovers"); return; } }; + let totals: HashMap = rows.into_iter().collect(); let mut guard = buckets.lock().expect("rate limiter mutex poisoned"); - for (i, p) in pending.iter().enumerate() { - // A statement that failed (a lost write race) leaves its bucket - // untouched: the delta stays unreported and the next round carries it. - let Ok(total) = response.take::>(i) else { + for p in &pending { + // A row missing from the fold's answer stands in for the failed + // statement it replaces: its bucket stays untouched, the delta stays + // unreported, and the next round carries it. + let Some(total) = totals.get(&row_key(tier, &p.key, epoch)) else { continue; }; - let (Some(total), Some(bucket)) = (total.first(), guard.get_mut(&p.key)) else { + let Some(bucket) = guard.get_mut(&p.key) else { continue; }; // The window may have rolled while the query was in flight, in which @@ -617,20 +615,19 @@ impl std::fmt::LowerHex for ByteSlice<'_> { } } -/// Run a sync query under a deadline. The liveness flag catches a *known* -/// outage; this catches the socket that died between the last ping and now, -/// which the SDK would otherwise park until the database returned — wedging -/// the one task every tier's sharing depends on. -async fn with_deadline( - query: impl std::future::IntoFuture>, -) -> Result { - tokio::time::timeout( - Duration::from_secs(RATE_SYNC_TIMEOUT_SECS), - query.into_future(), - ) - .await - .map_err(|_| AppError::Internal("rate-limit sync timed out".into()))? - .map_err(AppError::from) +/// Run one sync statement under a deadline. Postgres fails a dead connection +/// instead of parking the query, but a slow or overloaded server can still +/// stall a round past what the sharing can afford — every tier's budget rides +/// this one task, so a wedged round would stall all of them. A dropped round +/// leaves its deltas unreported and the next round carries them. +async fn with_deadline(query: Fut) -> Result +where + Fut: Future>, +{ + tokio::time::timeout(Duration::from_secs(RATE_SYNC_TIMEOUT_SECS), query) + .await + .map_err(|_| AppError::Internal("rate-limit sync timed out".into()))? + .map_err(AppError::from) } /// Resolve the client IP a request is billed against. @@ -901,66 +898,6 @@ mod tests { ); } - /// The wall window rolls under a live local one — every local window - /// straddles exactly one boundary, since both are 60s and only the shared - /// one is clock-aligned. Each request must land in exactly one shared row: - /// re-reporting the whole local count to the new row charges the client - /// twice and spends the next window's budget before it starts. - /// - /// `sync_once` takes the epoch, so the boundary is driven here instead of - /// waited for — the sharing tests in `tests/rate_limit.rs` all run inside - /// one real wall window (`current_epoch` reads the wall clock, which - /// `tokio::time::pause` does not touch), which is why this path had no - /// coverage at all. - #[tokio::test] - async fn a_wall_epoch_roll_charges_no_request_twice() { - const MAX: u32 = 5; - let db = crate::database::init_mem().await.expect("in-memory db"); - let limiter = UserRateLimiter::per_user_minute(MAX); - let window = Duration::from_secs(60); - let epoch = current_epoch(window); - assert_eq!(window.as_millis() as i64, 60_000, "epochs are 60s apart"); - - // A burst early in the client's local window, folded into row `epoch`. - for _ in 0..MAX { - assert!(limiter.enforce_user("user:a").is_ok()); - } - sync_once("test", &limiter.buckets, window, epoch, &db).await; - - // The wall clock rolls while that local window is still running. - sync_once("test", &limiter.buckets, window, epoch + 60_000, &db).await; - - // The local window lapses, so the client opens a fresh one — inside the - // *same* new wall window — and spends one request in it. - tokio::time::pause(); - tokio::time::advance(Duration::from_secs(61)).await; - tokio::time::resume(); - assert_eq!(admits(&limiter, "user:a", 1), 1, "a fresh local window"); - sync_once("test", &limiter.buckets, window, epoch + 60_000, &db).await; - - let mut rows = db - .query("SELECT VALUE hits FROM rate_limit ORDER BY window_start") - .await - .expect("read shared counters"); - assert_eq!( - rows.take::>(0).unwrap(), - vec![i64::from(MAX), 1], - "the new wall row may hold only what was admitted inside it" - ); - assert_eq!( - admits(&limiter, "user:a", 4), - 4, - "the client spent 1 of {MAX} in this window and must keep the rest" - ); - } - - /// How many of `tries` requests the limiter admits for `user`. - fn admits(limiter: &UserRateLimiter, user: &str, tries: usize) -> usize { - (0..tries) - .filter(|_| limiter.enforce_user(user).is_ok()) - .count() - } - /// The flood above was cheap to tell apart. This one is not: every flood /// key is driven to *exactly* the spend of the bucket it is trying to /// free, so a cheapest-first cutoff of `<=` puts the victim inside the tie diff --git a/src/state.rs b/src/state.rs index fe1b3bb..f1720f9 100644 --- a/src/state.rs +++ b/src/state.rs @@ -1,6 +1,5 @@ use std::collections::HashMap; use std::path::PathBuf; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use tokio::sync::broadcast; @@ -40,8 +39,6 @@ pub struct AppState { pub exam_presence: ExamPresence, /// Live stroke fan-out for the shared whiteboards (see [`BoardHub`]). pub board_hub: BoardHub, - /// Whether the database socket answered its last ping (see [`DbHealth`]). - pub db_up: DbHealth, /// The QUIC bridge to the AI services, when one is configured /// (`AI_QUIC_ADDR`). `None` means AI features are off for this deployment /// — handlers must degrade rather than fail, since the core API has never @@ -53,45 +50,6 @@ pub struct AppState { pub metrics: crate::telemetry::Metrics, } -/// Last known state of the database WebSocket, published by the keepalive task -/// in `main` and read by the guard layer in [`crate::build_router`]. -/// -/// It exists because a query issued while the socket is down does not fail — -/// it hangs. The SDK's reconnect loop stops draining its request channel while -/// it retries, so the query is parked until the database returns, and *then* -/// executes. Refusing at the edge is what keeps a 503 honest: nothing was -/// queued, so the caller's retry cannot double-apply a write. -/// -/// Starts up: `init` only returns once a connection and the migration -/// succeeded, so the first ping has nothing to correct. -#[derive(Clone)] -pub struct DbHealth(Arc); - -impl Default for DbHealth { - fn default() -> Self { - Self(Arc::new(AtomicBool::new(true))) - } -} - -impl DbHealth { - /// Did the last ping answer? - pub fn is_up(&self) -> bool { - self.0.load(Ordering::Relaxed) - } - - /// Publish the latest ping verdict, logging only the transitions — a long - /// outage should not print a line every [`crate::constant::DB_KEEPALIVE_INTERVAL_SECS`]. - pub fn set(&self, up: bool) { - if self.0.swap(up, Ordering::Relaxed) != up { - if up { - tracing::info!("database socket recovered — serving requests again"); - } else { - tracing::error!("database socket down — refusing requests with 503"); - } - } - } -} - /// The map key for `key` inside `slug`'s school. One process serves every /// school, but record keys are only unique *within* a database, so an /// unscoped key would put two schools' identical attempts (or boards) in the diff --git a/src/tenant.rs b/src/tenant.rs index 163ffba..5fcd74d 100644 --- a/src/tenant.rs +++ b/src/tenant.rs @@ -1,61 +1,57 @@ -//! Multi-school tenancy: one SurrealDB **database** per school inside one -//! namespace, plus a **control** database holding the school registry, the -//! builder accounts that manage it, and the deployment-wide rate-limit window. +//! Multi-school tenancy: one PostgreSQL **database** per school on one +//! server, plus a **control** database holding the school registry, the +//! builder accounts that manage it, and the deployment-wide rate-limit +//! window. //! -//! Isolation is the store's, not ours. A school database sees only its own +//! Isolation is the server's, not ours. A school database sees only its own //! rows, so no handler needs a `WHERE school = …` it could forget: the school //! is chosen once, at the edge (`crate::web::tenant_state::State`), and every //! query underneath runs against that handle. //! -//! # One connection per school, never a clone +//! # One pool per school, cached //! -//! [`crate::database::Database`] is `Arc>` for the reason spelled -//! out there — `Surreal::clone()` mints a racing server-side session — and the -//! same reasoning forbids the obvious shortcut here: switching `use_db` on the -//! control handle would repoint *every* in-flight query on it. So a cache miss -//! dials a **new** connection, signs it in, and pins it to the school's -//! database for its lifetime. -//! -//! In-memory mode (tests) has no server to define databases on: each -//! `connect("memory")` is an independent datastore, so a school *is* its own -//! store and the cache is the only thing that finds it again. +//! `crate::database::Database` is a `PgPool`, and a school's pool is its own +//! dial — switching databases on a shared connection is not a thing the pool +//! API offers, which is just as well: a cache miss dials a fresh pool +//! (`max_connections(4)`) pinned to the school's database for its lifetime, +//! and the cache is the only thing that finds it again. use std::collections::HashMap; use std::sync::{Arc, RwLock}; use serde::Serialize; -use surrealdb::opt::auth::Root; -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use sqlx::postgres::PgConnectOptions; -use crate::config::Config; use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN}; -use crate::database::{Database, lost_the_race, migrate, migrate_control}; -use crate::db::page::PagedList; +use crate::database::{ + create_database_sql, is_duplicate_database, migrate_school, school_pool, unique_violation, + Database, +}; use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ValidationError}; use crate::module::ModuleSet; use crate::telemetry::Metrics; use crate::web::tenant_state::ResolvedTenant; -pub(crate) const SCHOOL_TABLE: &str = "school"; - -/// The school every in-memory test bootstrap gets. Not special to the code — -/// just the one name the test harness and the suites agree on. +/// The school every in-memory test bootstrap got and every test suite still +/// names. Not special to the code — just the one name the test harness and +/// the suites agree on. pub const DEMO_SLUG: &str = "demo"; /// Slugs that name something other than a school: the builder cookie prefix and /// the control database itself. Refused at construction, so neither a login nor -/// a `DEFINE DATABASE` can ever be aimed at them. +/// a `CREATE DATABASE` can ever be aimed at them. pub const RESERVED_SLUGS: [&str; 2] = ["builder", "control"]; /// A school's identity everywhere it is named: the cookie prefix, the database /// name, and the files subdirectory. The character set is deliberately the /// intersection of what all three accept — lowercase alphanumerics and `-`, -/// starting with an alphanumeric — which is also what makes it safe to -/// interpolate into `DEFINE DATABASE` / `REMOVE DATABASE`, the two statements -/// SurrealQL gives no way to bind a name into. -#[derive(Debug, Clone, PartialEq, Eq, Hash, SurrealValue, Serialize)] +/// starting with an alphanumeric. It is also what makes the database names +/// injective: `school_db_name` maps `-` to `_`, and `_` is not in the slug +/// charset, so two slugs can never collide onto one database. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, sqlx::Type)] #[serde(transparent)] +#[sqlx(transparent)] pub struct Slug(String); /// `^[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 { } } -/// A school slug as a SurrealQL identifier. A database name cannot be bound -/// as a parameter, so it is interpolated — and it MUST be backtick-quoted: an -/// unquoted `ata-koleji` parses as a subtraction, `2024school` as a duration, -/// `12345` as a number (SurrealDB 3.2). The `Slug` charset (`[a-z0-9-]`) can -/// never contain a backtick, so the quoting cannot be escaped from. -pub fn quoted_ident(slug: &Slug) -> String { - format!("`{}`", slug.as_str()) +/// A school database's name: `{control_db}_school_{slug}`, the slug's `-` +/// spelled `_` (Postgres identifiers allow `-` only quoted, and the name is +/// built, not user-typed). Injective — see [`Slug`]'s charset note. +pub fn school_db_name(control_db: &str, slug: &Slug) -> String { + format!("{}_school_{}", control_db, slug.as_str().replace('-', "_")) } /// Whether a school may be reached at all. Suspension is immediate and total: /// [`Tenants::get`] refuses before any handler runs, and login is no exception. /// /// Stored as a bare lowercase string, like [`crate::domain::role::Role`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue, Serialize)] -#[surreal(untagged, rename_all = "lowercase")] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, sqlx::Type)] +#[sqlx(type_name = "TEXT", rename_all = "lowercase")] #[serde(rename_all = "lowercase")] pub enum SchoolStatus { Active, @@ -142,32 +136,24 @@ impl SchoolStatus { } } -#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct SchoolId(RecordId); +/// A school's id **is** its slug — the registry can never hold two rows for +/// one school, and the database name is derived from the same word. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct SchoolId(Slug); impl SchoolId { - /// The id **is** the slug, so the registry can never hold two rows for one - /// school even if the unique index were dropped. pub fn from_slug(slug: &Slug) -> Self { - Self(RecordId::new(SCHOOL_TABLE, slug.as_str())) - } - - pub fn record(&self) -> RecordId { - self.0.clone() + Self(slug.clone()) } pub fn key(&self) -> &str { - match &self.0.key { - RecordIdKey::String(key) => key, - _ => "", - } + self.0.as_str() } } /// A row in the control database's school registry. -#[derive(Debug, Clone, SurrealValue)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct School { - id: SchoolId, slug: Slug, name: String, status: SchoolStatus, @@ -180,8 +166,9 @@ pub struct School { } impl School { - pub fn get_id(&self) -> &SchoolId { - &self.id + /// The id is the slug; rebuilt rather than stored a second copy. + pub fn get_id(&self) -> SchoolId { + SchoolId::from_slug(&self.slug) } pub fn slug(&self) -> &Slug { @@ -218,20 +205,36 @@ impl School { } pub async fn read(slug: &Slug, control: &Database) -> Result, AppError> { - Ok(control.select(SchoolId::from_slug(slug).record()).await?) + sqlx::query_as::<_, School>( + "SELECT slug, name, status, created_at, modules FROM school WHERE slug = $1", + ) + .bind(slug.as_str()) + .fetch_optional(control) + .await + .map_err(Into::into) } /// One page of the registry, newest first. Same `(rows, total)` shape every /// other list domain returns, so the builder API can wrap it in the usual - /// [`crate::web::Page`] envelope. + /// [`crate::web::Page`] envelope. `None` limits to every row. pub async fn list( limit: Option, offset: i64, control: &Database, ) -> Result<(Vec, i64), AppError> { - PagedList::new(SCHOOL_TABLE, "ORDER BY created_at DESC, id DESC") - .run::(limit, offset, control) - .await + let rows = sqlx::query_as::<_, School>( + "SELECT slug, name, status, created_at, modules FROM school + ORDER BY created_at DESC, slug DESC + LIMIT $1 OFFSET $2", + ) + .bind(limit) + .bind(offset) + .fetch_all(control) + .await?; + let (total,): (i64,) = sqlx::query_as("SELECT count(*) FROM school") + .fetch_one(control) + .await?; + Ok((rows, total)) } /// Rename a school. The slug is immutable — it names a database and a @@ -241,104 +244,45 @@ impl School { name: &str, control: &Database, ) -> Result { - let updated: Option = control - .query("UPDATE $id SET name = $name RETURN AFTER") - .bind(("id", SchoolId::from_slug(slug).record())) - .bind(("name", name.to_string())) - .await? - .check()? - .take::>(0)? - .into_iter() - .next(); - updated.ok_or(AppError::NotFound) + sqlx::query_as::<_, School>( + "UPDATE school SET name = $1 WHERE slug = $2 + RETURNING slug, name, status, created_at, modules", + ) + .bind(name) + .bind(slug.as_str()) + .fetch_optional(control) + .await? + .ok_or(AppError::NotFound) } } -/// How a school handle is minted. Remote dials the server the control handle -/// came from; `Mem` mints an independent embedded datastore per school. -#[derive(Debug)] -enum Mode { - Remote { - url: String, - user: String, - pass: String, - ns: String, - }, - Mem, -} - -/// The school registry plus its live connections. +/// The school registry plus its live pools. #[derive(Clone)] pub struct Tenants { control: Database, cache: Arc>>, - mode: Arc, + /// Dial options for the Postgres server the control pool came from — a + /// school pool is the same dial with only the database swapped. + base: PgConnectOptions, + /// The control database's name; every school database is + /// [`school_db_name`] of it. + control_db: String, } impl Tenants { - /// Wrap an already-connected, already-migrated control handle. - pub fn new_remote(control: Database, cfg: &Config) -> Tenants { + /// Wrap an already-connected, already-migrated control pool. Production + /// constructor — [`crate::database::init`] calls it once at boot. + pub fn new(control: Database, base: PgConnectOptions, control_db: String) -> Tenants { Tenants { control, cache: Arc::new(RwLock::new(HashMap::new())), - mode: Arc::new(Mode::Remote { - url: cfg.db_url.clone(), - user: cfg.db_user.clone(), - pass: cfg.db_pass.clone(), - ns: cfg.db_ns.clone(), - }), + base, + control_db, } } - /// A fresh in-memory control database with the control schema applied, and - /// no schools. For tests. - pub async fn new_mem() -> Result { - let control = surrealdb::engine::any::connect("memory").await?; - control.use_ns("hezarfen").use_db("control").await?; - migrate_control(&control).await?; - Ok(Tenants { - control: Arc::new(control), - cache: Arc::new(RwLock::new(HashMap::new())), - mode: Arc::new(Mode::Mem), - }) - } - - /// A fresh in-memory registry that already knows `slug`, backed by a handle - /// that already exists rather than a new store. - /// - /// This is how a suite simulates a reboot: the process (and so the registry, - /// the connection cache and the control database) is new, while the school's - /// data is the very data the previous process wrote. - pub async fn new_mem_adopting( - slug: &Slug, - name: &str, - db: Database, - ) -> Result { - let tenants = Tenants::new_mem().await?; - let school = School { - id: SchoolId::from_slug(slug), - slug: slug.clone(), - name: name.to_string(), - status: SchoolStatus::Active, - created_at: Timestamp::now(), - modules: ModuleSet::all().names(), - }; - let _: Option = tenants - .control - .create(school.id.record()) - .content(school) - .await?; - let size = { - let mut cache = tenants.cache.write().expect("tenant cache lock"); - cache.insert(slug.as_str().to_string(), db); - cache.len() - }; - Self::report_size(size); - Ok(tenants) - } - /// The control database: schools, builders, the shared rate-limit window. - /// Never `use_db`-switched — see this module's header. + /// It is never re-purposed for a school's rows — see this module's header. pub fn control(&self) -> &Database { &self.control } @@ -363,7 +307,7 @@ impl Tenants { match School::read(slug, &self.control).await? { None => Err(AppError::Unauthorized), Some(school) if school.status == SchoolStatus::Suspended => { - self.evict(slug); + self.evict(slug).await; Err(AppError::Forbidden("school is suspended")) } Some(school) => Ok(ResolvedTenant { @@ -386,7 +330,7 @@ impl Tenants { /// Register a school and bring its database into being: registry row first /// (so a lost race is a `409` and not a half-made database), then - /// `DEFINE DATABASE`, then the school schema. + /// `CREATE DATABASE`, then the school schema. pub async fn create( &self, slug: &Slug, @@ -397,42 +341,38 @@ impl Tenants { // every violation at once), but the registry refuses an unsatisfiable // set too, so no future caller can persist one. modules.validate()?; - let school = School { - id: SchoolId::from_slug(slug), - slug: slug.clone(), - name: name.to_string(), - status: SchoolStatus::Active, - created_at: Timestamp::now(), - modules: modules.names(), - }; - let created: Result, surrealdb::Error> = self - .control - .create(school.id.record()) - .content(school.clone()) - .await; - match created { - Ok(Some(_)) => {} - Ok(None) => return Err(AppError::Internal("failed to create the school".into())), - // The id is the slug, so "already exists" is exactly "taken" — and - // a lost transaction race is the same verdict reached differently. - Err(err) if lost_the_race(&err) => { + let inserted = sqlx::query( + "INSERT INTO school (slug, name, status, created_at, modules) + VALUES ($1, $2, $3, $4, $5)", + ) + .bind(slug.as_str()) + .bind(name) + .bind(SchoolStatus::Active) + .bind(Timestamp::now().as_millis()) + .bind(modules.names()) + .execute(&self.control) + .await; + if let Err(err) = inserted { + // The slug is the table's only unique key, so a unique violation + // here is exactly "taken" — a rival's row, or the row already + // stood. Same verdict either way, as it always was. + if unique_violation(&err).is_some() { return Err(AppError::Conflict("school slug already taken")); } - Err(err) => return Err(err.into()), + return Err(err.into()); } // Everything past the registry row rolls that row back on failure: // the row is what makes the slug "taken", and a slug taken by a - // school that never came to exist is wedged for good (found by the - // delete-path verifier: `ata-koleji` failed `DEFINE DATABASE` unquoted - // and could then be neither re-created nor deleted). + // school that never came to exist is wedged for good. (A database + // created before the failure is not a wedge: the adopt branch in + // [`Self::bring_up`] picks it up, migrations being idempotent.) let db = match self.bring_up(slug).await { Ok(db) => db, Err(err) => { - let _ = self - .control - .query("DELETE $id") - .bind(("id", SchoolId::from_slug(slug).record())) + let _ = sqlx::query("DELETE FROM school WHERE slug = $1") + .bind(slug.as_str()) + .execute(&self.control) .await; return Err(err); } @@ -446,113 +386,121 @@ impl Tenants { Ok(db) } - /// Define (remote) or mint (memory) the school's database and apply the - /// school schema to it. Split out of [`Tenants::create`] so one `?` chain - /// can be rolled back as a unit. + /// Create (or adopt) the school's database and apply the school schema to + /// it. Split out of [`Tenants::create`] so one `?` chain can be rolled + /// back as a unit. async fn bring_up(&self, slug: &Slug) -> Result { - let db = match &*self.mode { - Mode::Remote { .. } => { - self.control - .query(format!( - "DEFINE DATABASE IF NOT EXISTS {}", - quoted_ident(slug) - )) - .await? - .check()?; - self.connect(slug).await? + let db_name = school_db_name(&self.control_db, slug); + // `CREATE DATABASE` cannot run inside a transaction; `Pool::execute` + // sends it as a bare autocommit statement. A name left over by a + // create that died before its rollback is adopted, not fought. + if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(create_database_sql( + "CREATE DATABASE", + &db_name, + ))) + .execute(&self.control) + .await + { + if !is_duplicate_database(&err) { + return Err(err.into()); } - Mode::Mem => self.connect(slug).await?, - }; - migrate(&db).await?; - Ok(db) + } + let pool = school_pool(&self.base, &db_name).await?; + let migrated = migrate_school(&pool).await; + if migrated.is_err() { + pool.close().await; + migrated?; + } + Ok(pool) } /// Flip a school between active and suspended. Suspending also drops the - /// cached handle, so nothing that already resolved keeps serving. + /// cached pool, so nothing that already resolved keeps serving. pub async fn set_status(&self, slug: &Slug, status: SchoolStatus) -> Result<(), AppError> { - let updated: Vec = self - .control - .query("UPDATE $id SET status = $status RETURN AFTER") - .bind(("id", SchoolId::from_slug(slug).record())) - .bind(("status", status)) - .await? - .check()? - .take(0)?; - if updated.is_empty() { + let updated = sqlx::query_as::<_, School>( + "UPDATE school SET status = $1 WHERE slug = $2 + RETURNING slug, name, status, created_at, modules", + ) + .bind(status) + .bind(slug.as_str()) + .fetch_optional(&self.control) + .await?; + if updated.is_none() { return Err(AppError::NotFound); } if status == SchoolStatus::Suspended { - self.evict(slug); + self.evict(slug).await; } Ok(()) } /// Sell (or take back) modules. Mirrors [`Tenants::set_status`] minus the /// eviction: entitlements are read off the registry row on every request, - /// so a change takes effect on the next call and no cached handle carries a + /// so a change takes effect on the next call and no cached pool carries a /// stale answer. pub async fn set_modules(&self, slug: &Slug, modules: &ModuleSet) -> Result<(), AppError> { modules.validate()?; - let updated: Vec = self - .control - .query("UPDATE $id SET modules = $modules RETURN AFTER") - .bind(("id", SchoolId::from_slug(slug).record())) - .bind(("modules", modules.names())) - .await? - .check()? - .take(0)?; - if updated.is_empty() { + let updated = sqlx::query_as::<_, School>( + "UPDATE school SET modules = $1 WHERE slug = $2 + RETURNING slug, name, status, created_at, modules", + ) + .bind(modules.names()) + .bind(slug.as_str()) + .fetch_optional(&self.control) + .await?; + if updated.is_none() { return Err(AppError::NotFound); } Ok(()) } /// Delete a school outright: its data, then its registry row, then its - /// handle. Irreversible on purpose — there is no soft-delete state, that is + /// pool. Irreversible on purpose — there is no soft-delete state, that is /// what [`SchoolStatus::Suspended`] is for. pub async fn drop(&self, slug: &Slug) -> Result<(), AppError> { - if let Mode::Remote { .. } = &*self.mode { - self.control - .query(format!("REMOVE DATABASE IF EXISTS {}", quoted_ident(slug))) - .await? - .check()?; - } - self.control - .query("DELETE $id") - .bind(("id", SchoolId::from_slug(slug).record())) - .await? - .check()?; - self.forget(slug); + // Close the pool first: nothing should be dialling a school whose + // database is about to go away, and `WITH (FORCE)` should never find + // one of our connections to kill. + self.evict(slug).await; + sqlx::query("DELETE FROM school WHERE slug = $1") + .bind(slug.as_str()) + .execute(&self.control) + .await?; + let db_name = school_db_name(&self.control_db, slug); + sqlx::query(sqlx::AssertSqlSafe( + create_database_sql("DROP DATABASE IF EXISTS", &db_name) + " WITH (FORCE)", + )) + .execute(&self.control) + .await?; Ok(()) } - /// Forget a school's connection. The next request dials a fresh one. + /// Forget a school's pool and close it. The next request dials a fresh + /// one. /// - /// A no-op in memory mode, where the cached handle *is* the school's - /// datastore and dropping it would delete the school's data rather than its - /// connection. Nothing depends on eviction for correctness — [`Tenants::get`] + /// Nothing depends on eviction for correctness — [`Tenants::get`] /// re-reads the registry row on every request, so a suspension is refused - /// whether or not a handle survived it. [`Tenants::drop`], which does mean to - /// destroy the store, forgets it unconditionally. - pub fn evict(&self, slug: &Slug) { - if matches!(&*self.mode, Mode::Mem) { - return; + /// whether or not a pool survived it. [`Tenants::drop`], which does mean + /// to destroy the store, evicts unconditionally. + pub async fn evict(&self, slug: &Slug) { + if let Some(pool) = self.forget(slug) { + pool.close().await; } - self.forget(slug); } - fn forget(&self, slug: &Slug) { + fn forget(&self, slug: &Slug) -> Option { let (removed, size) = { let mut cache = self.cache.write().expect("tenant cache lock"); - (cache.remove(slug.as_str()).is_some(), cache.len()) + (cache.remove(slug.as_str()), cache.len()) }; - if removed { - tracing::info!(school = %slug, "tenant connection evicted"); + if removed.is_some() { + tracing::info!(school = %slug, "tenant pool evicted"); Self::report_size(size); } + removed } - /// The cached handle, or a freshly dialled one. + /// The cached pool, or a freshly dialled one. async fn handle(&self, slug: &Slug) -> Result { if let Some(db) = self .cache @@ -562,20 +510,15 @@ impl Tenants { { return Ok(db.clone()); } - let db = self.connect(slug).await?; - // In-memory mode has nowhere for a school's rows to have survived a - // cache miss, so a fresh store needs the schema. Remote already has it. - if matches!(&*self.mode, Mode::Mem) { - migrate(&db).await?; - } - // Losing the race here is harmless — both handles are equivalent — but - // the winner is kept so two requests never diverge onto two sessions. + let db = school_pool(&self.base, &school_db_name(&self.control_db, slug)).await?; + // Losing the race here is harmless — both pools are equivalent — but + // the winner is kept so two requests never diverge onto two pools. let (db, size) = { let mut cache = self.cache.write().expect("tenant cache lock"); let db = cache.entry(slug.as_str().to_string()).or_insert(db).clone(); (db, cache.len()) }; - tracing::info!(school = %slug, "tenant connection opened"); + tracing::info!(school = %slug, "tenant pool opened"); Self::report_size(size); Ok(db) } @@ -586,33 +529,6 @@ impl Tenants { fn report_size(size: usize) { Metrics::global().tenant_cache_size.record(size as u64, &[]); } - - /// One new connection, pinned to `slug`'s database for its lifetime. - async fn connect(&self, slug: &Slug) -> Result { - let db = match &*self.mode { - Mode::Remote { - url, - user, - pass, - ns, - } => { - let db = surrealdb::engine::any::connect(url.clone()).await?; - db.signin(Root { - username: user.clone(), - password: pass.clone(), - }) - .await?; - db.use_ns(ns.clone()).use_db(slug.as_str()).await?; - db - } - Mode::Mem => { - let db = surrealdb::engine::any::connect("memory").await?; - db.use_ns("hezarfen").use_db(slug.as_str()).await?; - db - } - }; - Ok(Arc::new(db)) - } } #[cfg(test)] @@ -623,20 +539,8 @@ mod tests { Slug::try_new(value).expect(value) } - async fn count(db: &Database, table: &str) -> usize { - let mut rows = db - .query(format!("SELECT id FROM {table}")) - .await - .unwrap() - .check() - .unwrap(); - rows.take::>(0) - .unwrap() - .len() - } - - #[tokio::test] - async fn a_slug_names_a_school_and_nothing_reserved() { + #[test] + fn a_slug_names_a_school_and_nothing_reserved() { for good in ["demo", "a1", "ata-koleji", &"x".repeat(32)] { assert!(Slug::try_new(good).is_ok(), "{good:?} should be a slug"); } @@ -658,151 +562,37 @@ mod tests { } } - #[tokio::test] - async fn two_schools_do_not_see_each_others_rows() { - let tenants = Tenants::new_mem().await.unwrap(); - let (a, b) = (slug("alpha"), slug("beta")); - let one = tenants.create(&a, "Alpha", ModuleSet::all()).await.unwrap(); - let two = tenants.create(&b, "Beta", ModuleSet::all()).await.unwrap(); - - one.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'") - .await - .unwrap() - .check() - .unwrap(); - assert_eq!(count(&one, "user").await, 1); + /// The database-per-school model lives or dies by this mapping: two + /// schools sharing a database name would share every row in it. `-` + /// becoming `_` is the only rewrite, and `_` is not in the slug charset, + /// so no two slugs can land on one name. + #[test] + fn school_db_names_are_injective() { + let control = "hezarfen_control"; assert_eq!( - count(&two, "user").await, - 0, - "a row written in one school must be invisible in the other" + school_db_name(control, &slug("demo")), + "hezarfen_control_school_demo" ); - // A second `create` on a taken slug is a conflict, not a second school. - assert!(matches!( - tenants.create(&a, "Alpha again", ModuleSet::all()).await, - Err(AppError::Conflict(_)) - )); - } - - #[tokio::test] - async fn suspending_refuses_the_school_and_the_handle_it_already_had() { - let tenants = Tenants::new_mem().await.unwrap(); - let s = slug("alpha"); - tenants.create(&s, "Alpha", ModuleSet::all()).await.unwrap(); - // Cached by the first resolve; the suspension must beat the cache. - tenants.get(&s).await.expect("active school resolves"); - - tenants - .set_status(&s, SchoolStatus::Suspended) - .await - .unwrap(); - assert!(matches!( - tenants.get(&s).await, - Err(AppError::Forbidden("school is suspended")) - )); - // Builder tooling still reaches it, which is how it gets un-suspended. - let (_, status) = tenants.get_any_status(&s).await.unwrap(); - assert_eq!(status, SchoolStatus::Suspended); - - tenants.set_status(&s, SchoolStatus::Active).await.unwrap(); - assert!(tenants.get(&s).await.is_ok()); - // An unknown school is a bad credential, never a `404`. - assert!(matches!( - tenants.get(&slug("ghost")).await, - Err(AppError::Unauthorized) - )); - assert!(matches!( - tenants.get_any_status(&slug("ghost")).await, - Err(AppError::NotFound) - )); - } - - #[tokio::test] - async fn dropping_a_school_takes_its_rows_with_it() { - let tenants = Tenants::new_mem().await.unwrap(); - let s = slug("alpha"); - let db = tenants.create(&s, "Alpha", ModuleSet::all()).await.unwrap(); - db.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'") - .await - .unwrap() - .check() - .unwrap(); - assert_eq!(count(&db, "user").await, 1); - - tenants.drop(&s).await.unwrap(); - assert!(matches!(tenants.get(&s).await, Err(AppError::Unauthorized))); - - let fresh = tenants - .create(&s, "Alpha reborn", ModuleSet::all()) - .await - .unwrap(); - assert_eq!( - count(&fresh, "user").await, - 0, - "a re-created school must not inherit the dropped one's rows" - ); - } - - #[tokio::test] - async fn the_registry_lists_and_renames() { - let tenants = Tenants::new_mem().await.unwrap(); - tenants - .create(&slug("alpha"), "Alpha", ModuleSet::all()) - .await - .unwrap(); - tenants - .create(&slug("beta"), "Beta", ModuleSet::all()) - .await - .unwrap(); - - let (rows, total) = School::list(None, 0, tenants.control()).await.unwrap(); - assert_eq!(total, 2); - assert_eq!(rows.len(), 2); - - let renamed = School::update_name(&slug("alpha"), "Alpha Koleji", tenants.control()) - .await - .unwrap(); - assert_eq!(renamed.name(), "Alpha Koleji"); assert_eq!( - renamed.slug().as_str(), - "alpha", - "a rename never moves the slug" + school_db_name(control, &slug("ata-koleji")), + "hezarfen_control_school_ata_koleji" ); - assert!(matches!( - School::update_name(&slug("ghost"), "Nope", tenants.control()).await, - Err(AppError::NotFound) - )); - } - /// The builder API validates a set before it calls here (its message names - /// every violation at once), but the registry is the last gate: no caller, - /// present or future, may persist a set a school could not run on. - #[tokio::test] - async fn the_registry_refuses_an_unsatisfiable_set_on_create_and_on_sale() { - let tenants = Tenants::new_mem().await.unwrap(); - let s = slug("alpha"); - let mut lone = ModuleSet::empty(); - lone.insert(crate::module::Module::Exams); - - assert!( - matches!( - tenants.create(&s, "Alpha", lone.clone()).await, - Err(AppError::ConflictOwned(_)) - ), - "exams alone is unsatisfiable, so the school must not come into being" - ); - assert!( - matches!(tenants.get(&s).await, Err(AppError::Unauthorized)), - "a refused create leaves no registry row behind" - ); - - tenants.create(&s, "Alpha", ModuleSet::all()).await.unwrap(); - assert!(matches!( - tenants.set_modules(&s, &lone).await, - Err(AppError::ConflictOwned(_)) - )); - assert_eq!( - tenants.resolve(&s).await.unwrap().modules, - ModuleSet::all(), - "the refused sale must not have touched the row" + for a in ["a", "a-b", "ab", "a1b", "1a", "x-y-z"] { + for b in ["a", "a-b", "ab", "a1b", "1a", "x-y-z"] { + if a != b { + assert_ne!( + school_db_name(control, &slug(a)), + school_db_name(control, &slug(b)), + "{a:?} and {b:?} must not share a database" + ); + } + } + } + // The control database's own name is never a school's name: the + // suffix keeps the namespaces apart. + assert_ne!( + school_db_name(control, &slug("school")), + control ); } } diff --git a/src/web/auth.rs b/src/web/auth.rs index e3f157e..ab8c3d8 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -31,7 +31,7 @@ pub fn routes(state: &AppState) -> OpenApiRouter { let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy); // The budget survives a restart — the tier only means something if a // brute-forcer cannot reset it by waiting out a deploy. - limiter.share("auth", state.db.clone(), state.db_up.clone()); + limiter.share("auth", state.db.clone()); OpenApiRouter::new() .routes(routes!(register)) .routes(routes!(login)) diff --git a/src/web/builder.rs b/src/web/builder.rs index 74ec340..e297cbc 100644 --- a/src/web/builder.rs +++ b/src/web/builder.rs @@ -48,7 +48,7 @@ pub fn routes(state: &AppState) -> OpenApiRouter { // budget, since a school's brute-forcer must not spend the vendor's. let rate_limit: &RateLimitConfig = &state.rate_limit; let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy); - limiter.share("builder", state.db.clone(), state.db_up.clone()); + limiter.share("builder", state.db.clone()); OpenApiRouter::new() .routes(routes!(builder_login)) .route_layer(middleware::from_fn(move |req: Request, next: Next| { diff --git a/src/web/tenant_state.rs b/src/web/tenant_state.rs index 6ce9ec7..556b2a2 100644 --- a/src/web/tenant_state.rs +++ b/src/web/tenant_state.rs @@ -243,7 +243,6 @@ mod tests { chatbot_limit: Default::default(), exam_presence: Default::default(), board_hub: Default::default(), - db_up: Default::default(), ai: None, metrics: crate::telemetry::Metrics::noop(), }; @@ -355,7 +354,6 @@ mod tests { chatbot_limit: Default::default(), exam_presence: Default::default(), board_hub: Default::default(), - db_up: Default::default(), ai: None, metrics: crate::telemetry::Metrics::noop(), };