forge
Explore
Log in

Don't you dare go Hollow

Give ResolvedTenant its core home and make constant.rs a leaf

Browse files at this commit

d0dce85502af0d38335a85afdfc8074de8398517Ahmet Kaan GümüşParent: bcadcad
  • chore
    • give ResolvedTenant its core home and make constant.rs a leaf
Show full message
🔧 chore: give ResolvedTenant its core home and make constant.rs a leaf

Two structural defects a knowledge-graph pass over src/+tests/+migrations
surfaced. Both were verified against the real `use` lines before being called
defects — a module cycle is legal Rust, so only the layering facts count.
No behavior change: every moved item is byte-identical in name, type, value,
element order and doc text.

- `ResolvedTenant` was *declared* in `src/web/tenant_state.rs` but *built and
  returned* by `Tenants::resolve` (`src/tenant.rs`), so the core tenant
  registry imported the web layer. The struct moves to `src/tenant.rs`; its
  `impl FromRequestParts` stays in the web module (same crate, local type).
  That deletes the crate's only core→web import edge, and with it the three
  module cycles running through `state.rs` and `ai::server`.
- `constant.rs` is documented "Validation limits, in one place" but imported
  four domain enums to hold non-limit vocabularies: `ROLES` → `domain/role.rs`,
  `THEMES`/`LANGUAGES` → `domain/preferences.rs`, `SENDER_FOLDERS`/
  `RECIPIENT_FOLDERS` → `domain/message.rs`, and the 34-row `BADGES` catalogue
  → `domain/badge.rs`. Each now lives in the module that owns its type, so
  `constant.rs` imports nothing from `crate::domain` and ten
  `constant ↔ domain` cycles disappear. `AI_PRINCIPAL_KEY` and
  `PALETTE_COLOR_*` stayed put.

Measured on the same corpus: 20 → 7 reported import cycles — all ten
constant↔domain and all three tenant↔web cycles gone. The surviving seven are
intra-layer domain cycles plus the ai↔web pair; the AI bridge is a peer
front-end reusing web authorization helpers, which is deliberate, not an
inversion.

Tests: the published-or-excluded guard in `limits_completeness` read only
`src/constant.rs`, so the five moved tables silently left its scan — the one
place this move weakened coverage. It now covers them by name, and its
`references()` check no longer counts a bare `use` line as "published", which
the first witness attempt proved had made the guard vacuous. Witnessed by
mutating BADGES and then ROLES out of `/limits`: each FAILs naming the moved
table, and each restore is sha256-identical.

Gates: no SQL touched (.sqlx and migrations clean), prepare DB unchanged;
SQLX_OFFLINE=true cargo check --all-targets, clippy -D warnings,
limits_completeness, spec_bounds all green; cargo nextest run 1386/1386 across
47 binaries (doc_sync included).
src/ai/chat.rsmodified+1 -1
@@ -143,7 +143,7 @@ mod tests {
143143 );
144144 // Every role reaches the wire as its documented lowercase slug — the
145145 // one `Role::as_str` already publishes, not a second spelling.
146- for role in crate::constant::ROLES {
146+ for role in crate::domain::role::ROLES {
147147 let encoded = serde_json::to_value(ChatRequestPayload {
148148 message: "hi".into(),
149149 asker_role: role.as_str().to_string(),
src/ai/rag.rsmodified+1 -1
@@ -20,7 +20,7 @@ use crate::domain::course_note::CourseNote;
2020 use crate::domain::course_note_file::CourseNoteFile;
2121 use crate::module::Module;
2222 use crate::state::AppState;
23-use crate::web::tenant_state::ResolvedTenant;
23+use crate::tenant::ResolvedTenant;
2424
2525 /// The capability string routed to an indexing service. Defined once, in
2626 /// [`crate::constant`]; re-exported here so a reader of the payload contract
src/ai/server.rsmodified+2 -2
@@ -32,11 +32,11 @@ use crate::domain::user::{User, UserId};
3232 use crate::error::AppError;
3333 use crate::module::Module;
3434 use crate::telemetry::Metrics;
35-use crate::tenant::{Slug, Tenants};
35+use crate::tenant::{ResolvedTenant, Slug, Tenants};
3636 use crate::web::blob_path;
3737 use crate::web::courses::can_view_course;
3838 use crate::web::extractor::AiPrincipal;
39-use crate::web::tenant_state::{ResolvedTenant, TenantExt, school_files_path};
39+use crate::web::tenant_state::{TenantExt, school_files_path};
4040
4141 /// What the bridge needs to come up.
4242 #[derive(Clone, Debug)]
src/constant.rsmodified+0 -88
@@ -1,10 +1,5 @@
11 //! Validation limits, in one place.
22
3-use crate::domain::badge::BadgeStat;
4-use crate::domain::message::Folder;
5-use crate::domain::preferences::{Language, Theme};
6-use crate::domain::role::Role;
7-
83 /// A school slug's length bounds — the name in front of the dot in the session
94 /// cookie, which is also the school's database name and its blob directory
105 /// (see [`crate::tenant::Slug`]).
@@ -749,28 +744,10 @@ pub const MILLIS_PER_DAY: i64 = 24 * 60 * 60 * 1000;
749744 /// One week, the only recurrence step this backend expands.
750745 pub const MILLIS_PER_WEEK: i64 = 7 * MILLIS_PER_DAY;
751746
752-// --- enum value tables -------------------------------------------------
753-
754-/// Every *assignable* role, lowest privilege first. `Role::Ai` is deliberately
755-/// absent: it is a service principal, so leaving it out of this table is what
756-/// keeps `Role::try_from_str` (and every surface that lists roles) from ever
757-/// handing it to a user.
758-pub const ROLES: [Role; 5] = [
759- Role::Parent,
760- Role::Student,
761- Role::Teacher,
762- Role::Manager,
763- Role::Admin,
764-];
765-
766747 /// The record key `User::ai_principal` carries. A literal, not a ULID, so it
767748 /// can never collide with a minted user row — and the row is never written.
768749 pub const AI_PRINCIPAL_KEY: &str = "ai_service";
769750
770-pub const THEMES: [Theme; 2] = [Theme::Light, Theme::Dark];
771-
772-pub const LANGUAGES: [Language; 2] = [Language::Tr, Language::En];
773-
774751 /// A `palette_color` preference is `#` plus exactly six hex digits — the length
775752 /// of the whole string, `#` included.
776753 pub const PALETTE_COLOR_LEN: usize = 7;
@@ -786,11 +763,6 @@ pub const PALETTE_COLOR_LEN: usize = 7;
786763 /// change.
787764 pub const PALETTE_COLOR_PATTERN: &str = "^#[0-9a-fA-F]{6}$";
788765
789-/// Folders a sender may file their side into (`Sent` is their home).
790-pub const SENDER_FOLDERS: [Folder; 3] = [Folder::Sent, Folder::Archive, Folder::Trash];
791-/// Folders a recipient may file their side into (`Inbox` is their home).
792-pub const RECIPIENT_FOLDERS: [Folder; 3] = [Folder::Inbox, Folder::Archive, Folder::Trash];
793-
794766 /// The two lifecycle states of a pool question. `pending`: awaiting teacher+
795767 /// approval, visible only to the asker and to teacher+. `approved`: in the
796768 /// pool, school-wide. Rejection is not a state — a teacher+ simply deletes the
@@ -1064,66 +1036,6 @@ pub const LESSON_COUNTED_AT_FIELD: &str = "held_counted_at";
10641036 /// every deployment, forever.
10651037 pub const HIGH_MARK_MIN: i64 = 90;
10661038
1067-/// The badge catalog: every badge the system can award, as
1068-/// `(id, the counter it reads, the value that earns it)`. Hardcoded on
1069-/// purpose — moving a threshold is a deploy, which is what keeps
1070-/// [`crate::domain::badge::earned`] a pure function of the stats and makes the
1071-/// rules reviewable in a diff instead of editable in a settings row.
1072-///
1073-/// The ids are the API: the frontend maps them to a label and an icon, and an
1074-/// award row stores one forever. So an id is never reused for a different
1075-/// meaning; retiring one is done by deleting the line, and the awards that
1076-/// carry it simply stop being served (no data migration —
1077-/// [`crate::db::badge::list_for`] filters to the live
1078-/// catalog).
1079-pub const BADGES: [(&str, BadgeStat, i64); 34] = [
1080- ("homework_submitted_1", BadgeStat::HomeworkSubmitted, 1),
1081- ("homework_submitted_10", BadgeStat::HomeworkSubmitted, 10),
1082- ("homework_submitted_50", BadgeStat::HomeworkSubmitted, 50),
1083- ("homework_on_time_10", BadgeStat::HomeworkOnTime, 10),
1084- ("homework_on_time_25", BadgeStat::HomeworkOnTime, 25),
1085- ("exam_sat_1", BadgeStat::ExamSat, 1),
1086- ("exam_sat_10", BadgeStat::ExamSat, 10),
1087- ("exam_sat_25", BadgeStat::ExamSat, 25),
1088- ("pomodoro_finished_10", BadgeStat::PomodoroFinished, 10),
1089- ("pomodoro_finished_50", BadgeStat::PomodoroFinished, 50),
1090- ("pomodoro_finished_200", BadgeStat::PomodoroFinished, 200),
1091- // Ten and fifty hours of focus, in the milliseconds the counter stores.
1092- (
1093- "pomodoro_focus_ms_36000000",
1094- BadgeStat::PomodoroFocusMs,
1095- 36_000_000,
1096- ),
1097- (
1098- "pomodoro_focus_ms_180000000",
1099- BadgeStat::PomodoroFocusMs,
1100- 180_000_000,
1101- ),
1102- ("marks_given_10", BadgeStat::MarksGiven, 10),
1103- ("marks_given_50", BadgeStat::MarksGiven, 50),
1104- ("marks_given_250", BadgeStat::MarksGiven, 250),
1105- ("lessons_held_10", BadgeStat::LessonsHeld, 10),
1106- ("lessons_held_50", BadgeStat::LessonsHeld, 50),
1107- ("lessons_held_200", BadgeStat::LessonsHeld, 200),
1108- ("pool_approved_5", BadgeStat::PoolApproved, 5),
1109- ("pool_approved_25", BadgeStat::PoolApproved, 25),
1110- ("pool_approved_100", BadgeStat::PoolApproved, 100),
1111- ("pool_published_1", BadgeStat::PoolPublished, 1),
1112- ("pool_published_10", BadgeStat::PoolPublished, 10),
1113- ("pool_published_50", BadgeStat::PoolPublished, 50),
1114- ("lessons_attended_10", BadgeStat::LessonsAttended, 10),
1115- ("lessons_attended_50", BadgeStat::LessonsAttended, 50),
1116- ("lessons_attended_200", BadgeStat::LessonsAttended, 200),
1117- // Exam marks at or above `HIGH_MARK_MIN`, counted per graded sitting.
1118- ("high_mark_1", BadgeStat::HighMark, 1),
1119- ("high_mark_10", BadgeStat::HighMark, 10),
1120- ("high_mark_25", BadgeStat::HighMark, 25),
1121- // Consecutive study days, read off the longest run ever held — so these
1122- // are earned once and never lost when the run breaks.
1123- ("study_streak_3", BadgeStat::StudyStreak, 3),
1124- ("study_streak_7", BadgeStat::StudyStreak, 7),
1125- ("study_streak_30", BadgeStat::StudyStreak, 30),
1126-];
11271039 /// Cap 1, not N: an appointment slot holds at most one live booking, so this
11281040 /// counter is really an "is it taken" flag kept in the shape every other cap
11291041 /// uses (`claim`/`release`), which is what makes rejecting or cancelling a
src/db/badge.rsmodified+2 -2
@@ -6,9 +6,9 @@
66
77 use sqlx::AssertSqlSafe;
88
9-use crate::constant::{BADGE_AWARD_TABLE, BADGES};
9+use crate::constant::BADGE_AWARD_TABLE;
1010 use crate::database::Database;
11-use crate::domain::badge::{BadgeAward, BadgeStats};
11+use crate::domain::badge::{BADGES, BadgeAward, BadgeStats};
1212 use crate::domain::timestamp::Timestamp;
1313 use crate::domain::user::UserId;
1414 use crate::error::AppError;
src/domain/badge.rsmodified+65 -4
@@ -10,12 +10,12 @@
1010 //! counter that later drops below the threshold — a submission withdrawn,
1111 //! say — leaves the badge standing, because it records that the student did
1212 //! the thing, not that they still have it.
13-//! - **Pure rules.** The catalog is [`crate::constant::BADGES`], a hardcoded
14-//! table, so [`earned`] is a total function of [`BadgeStats`] with no I/O
15-//! and no configuration behind it.
13+//! - **Pure rules.** The catalog is [`BADGES`], a hardcoded table, so
14+//! [`earned`] is a total function of [`BadgeStats`] with no I/O and no
15+//! configuration behind it.
1616
1717 use crate::constant::{
18- BADGES, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD, HOMEWORK_ON_TIME_TOTAL_FIELD,
18+ EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD, HOMEWORK_ON_TIME_TOTAL_FIELD,
1919 HOMEWORK_SUBMITTED_TOTAL_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD,
2020 MARKS_GIVEN_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD,
2121 POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, STUDY_STREAK_LONGEST_FIELD,
@@ -92,6 +92,67 @@ impl BadgeStat {
9292 }
9393 }
9494
95+/// The badge catalog: every badge the system can award, as
96+/// `(id, the counter it reads, the value that earns it)`. Hardcoded on
97+/// purpose — moving a threshold is a deploy, which is what keeps
98+/// [`crate::domain::badge::earned`] a pure function of the stats and makes the
99+/// rules reviewable in a diff instead of editable in a settings row.
100+///
101+/// The ids are the API: the frontend maps them to a label and an icon, and an
102+/// award row stores one forever. So an id is never reused for a different
103+/// meaning; retiring one is done by deleting the line, and the awards that
104+/// carry it simply stop being served (no data migration —
105+/// [`crate::db::badge::list_for`] filters to the live
106+/// catalog).
107+pub const BADGES: [(&str, BadgeStat, i64); 34] = [
108+ ("homework_submitted_1", BadgeStat::HomeworkSubmitted, 1),
109+ ("homework_submitted_10", BadgeStat::HomeworkSubmitted, 10),
110+ ("homework_submitted_50", BadgeStat::HomeworkSubmitted, 50),
111+ ("homework_on_time_10", BadgeStat::HomeworkOnTime, 10),
112+ ("homework_on_time_25", BadgeStat::HomeworkOnTime, 25),
113+ ("exam_sat_1", BadgeStat::ExamSat, 1),
114+ ("exam_sat_10", BadgeStat::ExamSat, 10),
115+ ("exam_sat_25", BadgeStat::ExamSat, 25),
116+ ("pomodoro_finished_10", BadgeStat::PomodoroFinished, 10),
117+ ("pomodoro_finished_50", BadgeStat::PomodoroFinished, 50),
118+ ("pomodoro_finished_200", BadgeStat::PomodoroFinished, 200),
119+ // Ten and fifty hours of focus, in the milliseconds the counter stores.
120+ (
121+ "pomodoro_focus_ms_36000000",
122+ BadgeStat::PomodoroFocusMs,
123+ 36_000_000,
124+ ),
125+ (
126+ "pomodoro_focus_ms_180000000",
127+ BadgeStat::PomodoroFocusMs,
128+ 180_000_000,
129+ ),
130+ ("marks_given_10", BadgeStat::MarksGiven, 10),
131+ ("marks_given_50", BadgeStat::MarksGiven, 50),
132+ ("marks_given_250", BadgeStat::MarksGiven, 250),
133+ ("lessons_held_10", BadgeStat::LessonsHeld, 10),
134+ ("lessons_held_50", BadgeStat::LessonsHeld, 50),
135+ ("lessons_held_200", BadgeStat::LessonsHeld, 200),
136+ ("pool_approved_5", BadgeStat::PoolApproved, 5),
137+ ("pool_approved_25", BadgeStat::PoolApproved, 25),
138+ ("pool_approved_100", BadgeStat::PoolApproved, 100),
139+ ("pool_published_1", BadgeStat::PoolPublished, 1),
140+ ("pool_published_10", BadgeStat::PoolPublished, 10),
141+ ("pool_published_50", BadgeStat::PoolPublished, 50),
142+ ("lessons_attended_10", BadgeStat::LessonsAttended, 10),
143+ ("lessons_attended_50", BadgeStat::LessonsAttended, 50),
144+ ("lessons_attended_200", BadgeStat::LessonsAttended, 200),
145+ // Exam marks at or above `HIGH_MARK_MIN`, counted per graded sitting.
146+ ("high_mark_1", BadgeStat::HighMark, 1),
147+ ("high_mark_10", BadgeStat::HighMark, 10),
148+ ("high_mark_25", BadgeStat::HighMark, 25),
149+ // Consecutive study days, read off the longest run ever held — so these
150+ // are earned once and never lost when the run breaks.
151+ ("study_streak_3", BadgeStat::StudyStreak, 3),
152+ ("study_streak_7", BadgeStat::StudyStreak, 7),
153+ ("study_streak_30", BadgeStat::StudyStreak, 30),
154+];
155+
95156 /// The lifetime counters one user has accumulated, as the badge rules see
96157 /// them. Every field is a count and never an `Option`: the columns are
97158 /// `BIGINT NOT NULL DEFAULT 0`, so no rows is a true zero.
src/domain/message.rsmodified+6 -4
@@ -1,10 +1,7 @@
11 use sqlx::Type;
22 use uuid::Uuid;
33
4-use crate::constant::{
5- MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN, RECIPIENT_FOLDERS,
6- SENDER_FOLDERS,
7-};
4+use crate::constant::{MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN};
85 use crate::domain::monotonic_id::next_uuid;
96 use crate::domain::timestamp::Timestamp;
107 use crate::domain::user::UserId;
@@ -89,6 +86,11 @@ impl Folder {
8986 }
9087 }
9188
89+/// Folders a sender may file their side into (`Sent` is their home).
90+pub const SENDER_FOLDERS: [Folder; 3] = [Folder::Sent, Folder::Archive, Folder::Trash];
91+/// Folders a recipient may file their side into (`Inbox` is their home).
92+pub const RECIPIENT_FOLDERS: [Folder; 3] = [Folder::Inbox, Folder::Archive, Folder::Trash];
93+
9294 /// Typed message row id. A UUIDv7 minted by the process-wide monotonic
9395 /// generator, so `id` order is mint order.
9496 #[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
src/domain/preferences.rsmodified+5 -1
@@ -5,7 +5,7 @@
55
66 use sqlx::Type;
77
8-use crate::constant::{LANGUAGES, PALETTE_COLOR_LEN, THEMES};
8+use crate::constant::PALETTE_COLOR_LEN;
99 use crate::error::ValidationError;
1010
1111 /// The frontend color scheme.
@@ -40,6 +40,8 @@ impl Theme {
4040 }
4141 }
4242
43+pub const THEMES: [Theme; 2] = [Theme::Light, Theme::Dark];
44+
4345 /// The frontend interface language, as an ISO 639-1 code — the same values the
4446 /// frontend's locale switch uses (`"tr"` Turkish, `"en"` English).
4547 #[derive(Debug, Clone, Copy, PartialEq, Eq, Type)]
@@ -70,6 +72,8 @@ impl Language {
7072 }
7173 }
7274
75+pub const LANGUAGES: [Language; 2] = [Language::Tr, Language::En];
76+
7377 /// The frontend accent color, a 6-digit hex with a leading `#`, stored
7478 /// lowercase (`"#fefae0"`).
7579 ///
src/domain/role.rsmodified+12 -1
@@ -1,6 +1,5 @@
11 use sqlx::Type;
22
3-use crate::constant::ROLES;
43 use crate::error::ValidationError;
54
65 /// The access levels, in ascending order of privilege.
@@ -89,6 +88,18 @@ impl Role {
8988 }
9089 }
9190
91+/// Every *assignable* role, lowest privilege first. `Role::Ai` is deliberately
92+/// absent: it is a service principal, so leaving it out of this table is what
93+/// keeps `Role::try_from_str` (and every surface that lists roles) from ever
94+/// handing it to a user.
95+pub const ROLES: [Role; 5] = [
96+ Role::Parent,
97+ Role::Student,
98+ Role::Teacher,
99+ Role::Manager,
100+ Role::Admin,
101+];
102+
92103 #[cfg(test)]
93104 mod tests {
94105 use super::*;
src/tenant.rsmodified+12 -1
@@ -33,7 +33,6 @@ use crate::domain::timestamp::Timestamp;
3333 use crate::error::{AppError, ValidationError};
3434 use crate::module::ModuleSet;
3535 use crate::telemetry::Metrics;
36-use crate::web::tenant_state::ResolvedTenant;
3736
3837 /// The school every in-memory test bootstrap got and every test suite still
3938 /// names. Not special to the code — just the one name the test harness and
@@ -335,6 +334,18 @@ pub struct Tenants {
335334 leases: Option<crate::database::TestDatabases>,
336335 }
337336
337+/// Everything one registry read tells us about the school behind a request:
338+/// its handle and what it has bought. Cached in the request's extensions by
339+/// [`crate::web::tenant_state::resolve_tenant`], so a request that needs the
340+/// school twice (the shadow [`crate::web::tenant_state::State`] *and*
341+/// [`crate::web::CurrentUser`], which is most of them) reads the registry once.
342+#[derive(Clone)]
343+pub struct ResolvedTenant {
344+ pub slug: Slug,
345+ pub db: Database,
346+ pub modules: ModuleSet,
347+}
348+
338349 impl Tenants {
339350 /// Wrap an already-connected, already-migrated control pool. Production
340351 /// constructor — [`crate::database::init`] calls it once at boot.
src/web/chatbot.rsmodified+2 -1
@@ -20,7 +20,8 @@
2020
2121 use std::time::Duration;
2222
23-use crate::web::tenant_state::{ResolvedTenant, SchoolSlug, State, TenantExt};
23+use crate::tenant::ResolvedTenant;
24+use crate::web::tenant_state::{SchoolSlug, State, TenantExt};
2425 use axum::Json;
2526 use axum::extract::{Path, Query};
2627 use axum::http::StatusCode;
src/web/course_notes.rsmodified+2 -1
@@ -6,7 +6,8 @@
66 //! [`super::courses::can_view_course`] (the above, or anyone the course
77 //! reaches).
88
9-use crate::web::tenant_state::{ResolvedTenant, State};
9+use crate::tenant::ResolvedTenant;
10+use crate::web::tenant_state::State;
1011 use axum::Json;
1112 use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
1213 use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
src/web/dto.rsmodified+1 -1
@@ -38,7 +38,7 @@ pub enum Role {
3838 }
3939
4040 /// The roles a request may ask for: the five human ones, exactly
41-/// [`crate::constant::ROLES`]. Documentation only — the handlers still take the
41+/// [`crate::domain::role::ROLES`]. Documentation only — the handlers still take the
4242 /// role as a string and funnel it through
4343 /// [`crate::domain::role::Role::try_from_str`], so an unknown value is a uniform
4444 /// `400` rather than a deserialization error. It exists because [`Role`] (the
src/web/limits.rsmodified+3 -1
@@ -19,7 +19,9 @@ use utoipa_axum::router::OpenApiRouter;
1919 use utoipa_axum::routes;
2020
2121 use crate::constant::*;
22-use crate::constant::{LANGUAGES, ROLES, THEMES};
22+use crate::domain::badge::BADGES;
23+use crate::domain::preferences::{LANGUAGES, THEMES};
24+use crate::domain::role::ROLES;
2325 use crate::state::AppState;
2426
2527 pub fn routes() -> OpenApiRouter<AppState> {
src/web/modules.rsmodified+1 -1
@@ -21,8 +21,8 @@ use utoipa_axum::routes;
2121 use crate::error::ErrorResponse;
2222 use crate::module::{Module, ModuleSet, Package};
2323 use crate::state::AppState;
24+use crate::tenant::ResolvedTenant;
2425 use crate::web::CurrentUser;
25-use crate::web::tenant_state::ResolvedTenant;
2626
2727 pub fn routes() -> OpenApiRouter<AppState> {
2828 OpenApiRouter::new()
src/web/tenant_state.rsmodified+1 -13
@@ -21,19 +21,7 @@ use crate::database::Database;
2121 use crate::error::AppError;
2222 use crate::module::ModuleSet;
2323 use crate::state::AppState;
24-use crate::tenant::Slug;
25-
26-/// Everything one registry read tells us about the school behind a request:
27-/// its handle and what it has bought. Cached in the request's extensions by
28-/// [`resolve_tenant`], so a request that needs the school twice (the shadow
29-/// [`State`] *and* [`crate::web::CurrentUser`], which is most of them) reads
30-/// the registry once.
31-#[derive(Clone)]
32-pub struct ResolvedTenant {
33- pub slug: Slug,
34- pub db: Database,
35- pub modules: ModuleSet,
36-}
24+use crate::tenant::{ResolvedTenant, Slug};
3725
3826 /// The school a request has already been resolved into, injected as a request
3927 /// extension by an in-process caller that has no cookie — today only the AI
tests/integration.rsmodified+1 -1
@@ -5217,7 +5217,7 @@ async fn admin_creates_a_user() {
52175217 /// hold. `Role` carries no `serde` derive (`src/domain/role.rs:21`), so no
52185218 /// handler can bind a role straight out of a body — every request-supplied role
52195219 /// passes `Role::try_from_str`, which answers only with a member of
5220-/// `constant::ROLES` (`src/constant.rs:674`, the five human roles).
5220+/// `domain::role::ROLES` (`src/domain/role.rs`, the five human roles).
52215221 ///
52225222 /// Grep-verified 2026-08-12, the complete set of role paths a request can reach:
52235223 /// * `src/web/users.rs:453` — `PATCH /users/{id}/role`, the *only* path that
tests/limits_completeness.rsmodified+93 -13
@@ -173,10 +173,20 @@ const EXCLUDED: &[(&str, &str)] = &[
173173 ("STATUS_PENDING", "pool-question lifecycle state"),
174174 ("STATUS_APPROVED", "pool-question lifecycle state"),
175175 ("POOL_QUESTION_STATUSES", "pool-question lifecycle states"),
176+ // Which folders a copy may be filed into is carried by the message itself
177+ // (its `folder` field), so the client reads the accepted set off the
178+ // resource it is acting on — never a public list, and /limits has no
179+ // message-folder group to place them in.
180+ (
181+ "SENDER_FOLDERS",
182+ "folders a sender may file their side into",
183+ ),
184+ (
185+ "RECIPIENT_FOLDERS",
186+ "folders a recipient may file their side into",
187+ ),
176188 ("BANK_VISIBILITY_PRIVATE", "bank-question visibility value"),
177189 ("BANK_VISIBILITY_SCHOOL", "bank-question visibility value"),
178- ("SENDER_FOLDERS", "folders a sender may file into"),
179- ("RECIPIENT_FOLDERS", "folders a recipient may file into"),
180190 // Client-facing, but deliberately not compile-time contracts: these are
181191 // per-deployment defaults an operator overrides by environment variable.
182192 // `GET /limits` publishes the running server's ACTUAL tiers (from
@@ -244,7 +254,7 @@ fn is_storage_identifier(name: &str) -> bool {
244254 .any(|prefix| name.starts_with(prefix))
245255 }
246256
247-/// Every `pub const` declared in `src/constant.rs`.
257+/// Every `pub const` declared in `source`, in declaration order.
248258 fn declared_constants(source: &str) -> BTreeSet<String> {
249259 source
250260 .lines()
@@ -255,15 +265,24 @@ fn declared_constants(source: &str) -> BTreeSet<String> {
255265 .collect()
256266 }
257267
258-/// True when `limits.rs` mentions the constant as a whole word — the response
259-/// is built by naming each constant directly, so a mention is the reference.
268+/// True when `limits.rs` mentions the constant as a whole word in its *body* —
269+/// the response is built by naming each constant directly, so a mention there
270+/// is the reference. `use` lines are skipped: an import proves a name is in
271+/// scope, not that anything publishes it, and reading it as a reference would
272+/// let deleting a table from the response keep the guard green.
260273 fn references(source: &str, name: &str) -> bool {
261- source.match_indices(name).any(|(at, _)| {
262- let before = source[..at].chars().next_back();
263- let after = source[at + name.len()..].chars().next();
264- let boundary = |c: Option<char>| !matches!(c, Some(c) if c.is_alphanumeric() || c == '_');
265- boundary(before) && boundary(after)
266- })
274+ source
275+ .lines()
276+ .filter(|line| !line.trim_start().starts_with("use "))
277+ .any(|line| {
278+ line.match_indices(name).any(|(at, _)| {
279+ let before = line[..at].chars().next_back();
280+ let after = line[at + name.len()..].chars().next();
281+ let boundary =
282+ |c: Option<char>| !matches!(c, Some(c) if c.is_alphanumeric() || c == '_');
283+ boundary(before) && boundary(after)
284+ })
285+ })
267286 }
268287
269288 #[test]
@@ -303,6 +322,56 @@ fn every_constant_is_published_or_deliberately_excluded() {
303322 );
304323 }
305324
325+/// The accepted-value tables that moved out of `src/constant.rs` into their
326+/// domain modules (which is also their only legal home — `validation_bounds_
327+/// live_in_constant_rs` below bans the bound-shaped ones elsewhere, but an
328+/// array of enum values is neither a `MAX_`/`MIN_` bound nor numeric, so it
329+/// escapes that sweep). Each is either published by `GET /limits` or excused
330+/// with a reason; both are consumed by the test below.
331+const MOVED_TABLES: &[(&str, &str)] = &[
332+ ("src/domain/role.rs", "ROLES"),
333+ ("src/domain/preferences.rs", "THEMES"),
334+ ("src/domain/preferences.rs", "LANGUAGES"),
335+ ("src/domain/message.rs", "SENDER_FOLDERS"),
336+ ("src/domain/message.rs", "RECIPIENT_FOLDERS"),
337+ ("src/domain/badge.rs", "BADGES"),
338+];
339+
340+#[test]
341+fn moved_value_tables_are_still_published_or_deliberately_excluded() {
342+ // The sweep above only reads `src/constant.rs`, so the day the accepted-
343+ // value tables moved into their domain modules they left its scan: nothing
344+ // then failed if a future edit dropped one from `src/web/limits.rs`. This
345+ // re-establishes that guarantee for the tables that moved — but for that
346+ // table list alone, not the whole modules, so the many server-side bounds
347+ // that also live there are not dragged in and do not each need an
348+ // EXCLUDED entry of their own.
349+ let root = env!("CARGO_MANIFEST_DIR");
350+ let limits = fs::read_to_string(format!("{root}/src/web/limits.rs")).expect("read limits.rs");
351+ let excluded: BTreeSet<&str> = EXCLUDED.iter().map(|(name, _)| *name).collect();
352+
353+ let mut missing = Vec::new();
354+ for (module, name) in MOVED_TABLES {
355+ let source = fs::read_to_string(format!("{root}/{module}"))
356+ .unwrap_or_else(|_| panic!("read {module}"));
357+ assert!(
358+ declared_constants(&source).contains(*name),
359+ "{name} is no longer a `pub const` in {module} — MOVED_TABLES is stale"
360+ );
361+ if !excluded.contains(name) && !references(&limits, name) {
362+ missing.push(format!(" {name} ({module})"));
363+ }
364+ }
365+
366+ assert!(
367+ missing.is_empty(),
368+ "these accepted-value tables left src/constant.rs and now reach neither GET /limits \
369+ nor the EXCLUDED list in this test:\n{}\n\nAdd each to src/web/limits.rs so clients \
370+ stop guessing it, or to EXCLUDED with the reason it is not client-facing.",
371+ missing.join("\n")
372+ );
373+}
374+
306375 /// Constants outside `constant.rs` that the sweep below may ignore — either
307376 /// because they are not a client-facing bound at all, or because they are
308377 /// published by a route that reads the *live* value instead of the constant.
@@ -384,10 +453,20 @@ fn validation_bounds_live_in_constant_rs() {
384453 fn exclusions_are_real_constants() {
385454 // An exclusion for a deleted constant is dead weight that also silently
386455 // widens the allowlist if the name is ever reused for something public.
456+ // A name is real when it is declared in `src/constant.rs` or is one of the
457+ // accepted-value tables that moved into its domain module — the two homes
458+ // the completeness test above reads.
387459 let root = env!("CARGO_MANIFEST_DIR");
388460 let constants =
389461 fs::read_to_string(format!("{root}/src/constant.rs")).expect("read constant.rs");
390- let declared = declared_constants(&constants);
462+ let mut declared = declared_constants(&constants);
463+ for (module, name) in MOVED_TABLES {
464+ let source = fs::read_to_string(format!("{root}/{module}"))
465+ .unwrap_or_else(|_| panic!("read {module}"));
466+ if declared_constants(&source).contains(*name) {
467+ declared.insert((*name).to_string());
468+ }
469+ }
391470
392471 let stale: Vec<&str> = EXCLUDED
393472 .iter()
@@ -397,6 +476,7 @@ fn exclusions_are_real_constants() {
397476
398477 assert!(
399478 stale.is_empty(),
400- "EXCLUDED names constants that no longer exist in src/constant.rs: {stale:?} — drop them"
479+ "EXCLUDED names constants that no longer exist (neither in src/constant.rs nor in \
480+ the modules listed in MOVED_TABLES): {stale:?} — drop them"
401481 );
402482 }
tests/regress_badges.rsmodified+2 -1
@@ -26,9 +26,10 @@ use common::{
2626 send, set_role, taught_under,
2727 };
2828 use hezarfen_backend::constant::{
29- BADGES, HIGH_MARK_MIN, MIN_COUNTED_POMODORO_MS, STUDY_STREAK_LAST_DAY_FIELD,
29+ HIGH_MARK_MIN, MIN_COUNTED_POMODORO_MS, STUDY_STREAK_LAST_DAY_FIELD,
3030 };
3131 use hezarfen_backend::database::Database;
32+use hezarfen_backend::domain::badge::BADGES;
3233 use hezarfen_backend::domain::timestamp::Timestamp;
3334 use serde_json::{Value, json};
3435