From d0dce85502af0d38335a85afdfc8074de8398517 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 17 Sep 2026 04:29:25 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20chore:=20give=20ResolvedTenant?= =?UTF-8?q?=20its=20core=20home=20and=20make=20constant.rs=20a=20leaf?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.rs | 2 +- src/ai/rag.rs | 2 +- src/ai/server.rs | 4 +- src/constant.rs | 88 ----------------------------- src/db/badge.rs | 4 +- src/domain/badge.rs | 69 +++++++++++++++++++++-- src/domain/message.rs | 10 ++-- src/domain/preferences.rs | 6 +- src/domain/role.rs | 13 ++++- src/tenant.rs | 13 ++++- src/web/chatbot.rs | 3 +- src/web/course_notes.rs | 3 +- src/web/dto.rs | 2 +- src/web/limits.rs | 4 +- src/web/modules.rs | 2 +- src/web/tenant_state.rs | 14 +---- tests/integration.rs | 2 +- tests/limits_completeness.rs | 106 ++++++++++++++++++++++++++++++----- tests/regress_badges.rs | 3 +- 19 files changed, 212 insertions(+), 138 deletions(-) diff --git a/src/ai/chat.rs b/src/ai/chat.rs index 3a673f2..12f7920 100644 --- a/src/ai/chat.rs +++ b/src/ai/chat.rs @@ -143,7 +143,7 @@ mod tests { ); // Every role reaches the wire as its documented lowercase slug — the // one `Role::as_str` already publishes, not a second spelling. - for role in crate::constant::ROLES { + for role in crate::domain::role::ROLES { let encoded = serde_json::to_value(ChatRequestPayload { message: "hi".into(), asker_role: role.as_str().to_string(), diff --git a/src/ai/rag.rs b/src/ai/rag.rs index 8430915..25a466b 100644 --- a/src/ai/rag.rs +++ b/src/ai/rag.rs @@ -20,7 +20,7 @@ use crate::domain::course_note::CourseNote; use crate::domain::course_note_file::CourseNoteFile; use crate::module::Module; use crate::state::AppState; -use crate::web::tenant_state::ResolvedTenant; +use crate::tenant::ResolvedTenant; /// The capability string routed to an indexing service. Defined once, in /// [`crate::constant`]; re-exported here so a reader of the payload contract diff --git a/src/ai/server.rs b/src/ai/server.rs index fbc4f27..92e7633 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -32,11 +32,11 @@ use crate::domain::user::{User, UserId}; use crate::error::AppError; use crate::module::Module; use crate::telemetry::Metrics; -use crate::tenant::{Slug, Tenants}; +use crate::tenant::{ResolvedTenant, Slug, Tenants}; use crate::web::blob_path; use crate::web::courses::can_view_course; use crate::web::extractor::AiPrincipal; -use crate::web::tenant_state::{ResolvedTenant, TenantExt, school_files_path}; +use crate::web::tenant_state::{TenantExt, school_files_path}; /// What the bridge needs to come up. #[derive(Clone, Debug)] diff --git a/src/constant.rs b/src/constant.rs index 7bd2304..d069c14 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -1,10 +1,5 @@ //! Validation limits, in one place. -use crate::domain::badge::BadgeStat; -use crate::domain::message::Folder; -use crate::domain::preferences::{Language, Theme}; -use crate::domain::role::Role; - /// A school slug's length bounds — the name in front of the dot in the session /// cookie, which is also the school's database name and its blob directory /// (see [`crate::tenant::Slug`]). @@ -749,28 +744,10 @@ pub const MILLIS_PER_DAY: i64 = 24 * 60 * 60 * 1000; /// One week, the only recurrence step this backend expands. pub const MILLIS_PER_WEEK: i64 = 7 * MILLIS_PER_DAY; -// --- enum value tables ------------------------------------------------- - -/// Every *assignable* role, lowest privilege first. `Role::Ai` is deliberately -/// absent: it is a service principal, so leaving it out of this table is what -/// keeps `Role::try_from_str` (and every surface that lists roles) from ever -/// handing it to a user. -pub const ROLES: [Role; 5] = [ - Role::Parent, - Role::Student, - Role::Teacher, - Role::Manager, - Role::Admin, -]; - /// The record key `User::ai_principal` carries. A literal, not a ULID, so it /// can never collide with a minted user row — and the row is never written. pub const AI_PRINCIPAL_KEY: &str = "ai_service"; -pub const THEMES: [Theme; 2] = [Theme::Light, Theme::Dark]; - -pub const LANGUAGES: [Language; 2] = [Language::Tr, Language::En]; - /// A `palette_color` preference is `#` plus exactly six hex digits — the length /// of the whole string, `#` included. pub const PALETTE_COLOR_LEN: usize = 7; @@ -786,11 +763,6 @@ pub const PALETTE_COLOR_LEN: usize = 7; /// change. pub const PALETTE_COLOR_PATTERN: &str = "^#[0-9a-fA-F]{6}$"; -/// Folders a sender may file their side into (`Sent` is their home). -pub const SENDER_FOLDERS: [Folder; 3] = [Folder::Sent, Folder::Archive, Folder::Trash]; -/// Folders a recipient may file their side into (`Inbox` is their home). -pub const RECIPIENT_FOLDERS: [Folder; 3] = [Folder::Inbox, Folder::Archive, Folder::Trash]; - /// The two lifecycle states of a pool question. `pending`: awaiting teacher+ /// approval, visible only to the asker and to teacher+. `approved`: in the /// 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"; /// every deployment, forever. pub const HIGH_MARK_MIN: i64 = 90; -/// The badge catalog: every badge the system can award, as -/// `(id, the counter it reads, the value that earns it)`. Hardcoded on -/// purpose — moving a threshold is a deploy, which is what keeps -/// [`crate::domain::badge::earned`] a pure function of the stats and makes the -/// rules reviewable in a diff instead of editable in a settings row. -/// -/// The ids are the API: the frontend maps them to a label and an icon, and an -/// award row stores one forever. So an id is never reused for a different -/// meaning; retiring one is done by deleting the line, and the awards that -/// carry it simply stop being served (no data migration — -/// [`crate::db::badge::list_for`] filters to the live -/// catalog). -pub const BADGES: [(&str, BadgeStat, i64); 34] = [ - ("homework_submitted_1", BadgeStat::HomeworkSubmitted, 1), - ("homework_submitted_10", BadgeStat::HomeworkSubmitted, 10), - ("homework_submitted_50", BadgeStat::HomeworkSubmitted, 50), - ("homework_on_time_10", BadgeStat::HomeworkOnTime, 10), - ("homework_on_time_25", BadgeStat::HomeworkOnTime, 25), - ("exam_sat_1", BadgeStat::ExamSat, 1), - ("exam_sat_10", BadgeStat::ExamSat, 10), - ("exam_sat_25", BadgeStat::ExamSat, 25), - ("pomodoro_finished_10", BadgeStat::PomodoroFinished, 10), - ("pomodoro_finished_50", BadgeStat::PomodoroFinished, 50), - ("pomodoro_finished_200", BadgeStat::PomodoroFinished, 200), - // Ten and fifty hours of focus, in the milliseconds the counter stores. - ( - "pomodoro_focus_ms_36000000", - BadgeStat::PomodoroFocusMs, - 36_000_000, - ), - ( - "pomodoro_focus_ms_180000000", - BadgeStat::PomodoroFocusMs, - 180_000_000, - ), - ("marks_given_10", BadgeStat::MarksGiven, 10), - ("marks_given_50", BadgeStat::MarksGiven, 50), - ("marks_given_250", BadgeStat::MarksGiven, 250), - ("lessons_held_10", BadgeStat::LessonsHeld, 10), - ("lessons_held_50", BadgeStat::LessonsHeld, 50), - ("lessons_held_200", BadgeStat::LessonsHeld, 200), - ("pool_approved_5", BadgeStat::PoolApproved, 5), - ("pool_approved_25", BadgeStat::PoolApproved, 25), - ("pool_approved_100", BadgeStat::PoolApproved, 100), - ("pool_published_1", BadgeStat::PoolPublished, 1), - ("pool_published_10", BadgeStat::PoolPublished, 10), - ("pool_published_50", BadgeStat::PoolPublished, 50), - ("lessons_attended_10", BadgeStat::LessonsAttended, 10), - ("lessons_attended_50", BadgeStat::LessonsAttended, 50), - ("lessons_attended_200", BadgeStat::LessonsAttended, 200), - // Exam marks at or above `HIGH_MARK_MIN`, counted per graded sitting. - ("high_mark_1", BadgeStat::HighMark, 1), - ("high_mark_10", BadgeStat::HighMark, 10), - ("high_mark_25", BadgeStat::HighMark, 25), - // Consecutive study days, read off the longest run ever held — so these - // are earned once and never lost when the run breaks. - ("study_streak_3", BadgeStat::StudyStreak, 3), - ("study_streak_7", BadgeStat::StudyStreak, 7), - ("study_streak_30", BadgeStat::StudyStreak, 30), -]; /// Cap 1, not N: an appointment slot holds at most one live booking, so this /// counter is really an "is it taken" flag kept in the shape every other cap /// uses (`claim`/`release`), which is what makes rejecting or cancelling a diff --git a/src/db/badge.rs b/src/db/badge.rs index ce289ae..33ecc40 100644 --- a/src/db/badge.rs +++ b/src/db/badge.rs @@ -6,9 +6,9 @@ use sqlx::AssertSqlSafe; -use crate::constant::{BADGE_AWARD_TABLE, BADGES}; +use crate::constant::BADGE_AWARD_TABLE; use crate::database::Database; -use crate::domain::badge::{BadgeAward, BadgeStats}; +use crate::domain::badge::{BADGES, BadgeAward, BadgeStats}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; diff --git a/src/domain/badge.rs b/src/domain/badge.rs index b3e0392..5aa3353 100644 --- a/src/domain/badge.rs +++ b/src/domain/badge.rs @@ -10,12 +10,12 @@ //! counter that later drops below the threshold — a submission withdrawn, //! say — leaves the badge standing, because it records that the student did //! the thing, not that they still have it. -//! - **Pure rules.** The catalog is [`crate::constant::BADGES`], a hardcoded -//! table, so [`earned`] is a total function of [`BadgeStats`] with no I/O -//! and no configuration behind it. +//! - **Pure rules.** The catalog is [`BADGES`], a hardcoded table, so +//! [`earned`] is a total function of [`BadgeStats`] with no I/O and no +//! configuration behind it. use crate::constant::{ - BADGES, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD, HOMEWORK_ON_TIME_TOTAL_FIELD, + 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, MARKS_GIVEN_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, STUDY_STREAK_LONGEST_FIELD, @@ -92,6 +92,67 @@ impl BadgeStat { } } +/// The badge catalog: every badge the system can award, as +/// `(id, the counter it reads, the value that earns it)`. Hardcoded on +/// purpose — moving a threshold is a deploy, which is what keeps +/// [`crate::domain::badge::earned`] a pure function of the stats and makes the +/// rules reviewable in a diff instead of editable in a settings row. +/// +/// The ids are the API: the frontend maps them to a label and an icon, and an +/// award row stores one forever. So an id is never reused for a different +/// meaning; retiring one is done by deleting the line, and the awards that +/// carry it simply stop being served (no data migration — +/// [`crate::db::badge::list_for`] filters to the live +/// catalog). +pub const BADGES: [(&str, BadgeStat, i64); 34] = [ + ("homework_submitted_1", BadgeStat::HomeworkSubmitted, 1), + ("homework_submitted_10", BadgeStat::HomeworkSubmitted, 10), + ("homework_submitted_50", BadgeStat::HomeworkSubmitted, 50), + ("homework_on_time_10", BadgeStat::HomeworkOnTime, 10), + ("homework_on_time_25", BadgeStat::HomeworkOnTime, 25), + ("exam_sat_1", BadgeStat::ExamSat, 1), + ("exam_sat_10", BadgeStat::ExamSat, 10), + ("exam_sat_25", BadgeStat::ExamSat, 25), + ("pomodoro_finished_10", BadgeStat::PomodoroFinished, 10), + ("pomodoro_finished_50", BadgeStat::PomodoroFinished, 50), + ("pomodoro_finished_200", BadgeStat::PomodoroFinished, 200), + // Ten and fifty hours of focus, in the milliseconds the counter stores. + ( + "pomodoro_focus_ms_36000000", + BadgeStat::PomodoroFocusMs, + 36_000_000, + ), + ( + "pomodoro_focus_ms_180000000", + BadgeStat::PomodoroFocusMs, + 180_000_000, + ), + ("marks_given_10", BadgeStat::MarksGiven, 10), + ("marks_given_50", BadgeStat::MarksGiven, 50), + ("marks_given_250", BadgeStat::MarksGiven, 250), + ("lessons_held_10", BadgeStat::LessonsHeld, 10), + ("lessons_held_50", BadgeStat::LessonsHeld, 50), + ("lessons_held_200", BadgeStat::LessonsHeld, 200), + ("pool_approved_5", BadgeStat::PoolApproved, 5), + ("pool_approved_25", BadgeStat::PoolApproved, 25), + ("pool_approved_100", BadgeStat::PoolApproved, 100), + ("pool_published_1", BadgeStat::PoolPublished, 1), + ("pool_published_10", BadgeStat::PoolPublished, 10), + ("pool_published_50", BadgeStat::PoolPublished, 50), + ("lessons_attended_10", BadgeStat::LessonsAttended, 10), + ("lessons_attended_50", BadgeStat::LessonsAttended, 50), + ("lessons_attended_200", BadgeStat::LessonsAttended, 200), + // Exam marks at or above `HIGH_MARK_MIN`, counted per graded sitting. + ("high_mark_1", BadgeStat::HighMark, 1), + ("high_mark_10", BadgeStat::HighMark, 10), + ("high_mark_25", BadgeStat::HighMark, 25), + // Consecutive study days, read off the longest run ever held — so these + // are earned once and never lost when the run breaks. + ("study_streak_3", BadgeStat::StudyStreak, 3), + ("study_streak_7", BadgeStat::StudyStreak, 7), + ("study_streak_30", BadgeStat::StudyStreak, 30), +]; + /// The lifetime counters one user has accumulated, as the badge rules see /// 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. diff --git a/src/domain/message.rs b/src/domain/message.rs index f2aef4f..37fc333 100644 --- a/src/domain/message.rs +++ b/src/domain/message.rs @@ -1,10 +1,7 @@ use sqlx::Type; use uuid::Uuid; -use crate::constant::{ - MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN, RECIPIENT_FOLDERS, - SENDER_FOLDERS, -}; +use crate::constant::{MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN}; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -89,6 +86,11 @@ impl Folder { } } +/// Folders a sender may file their side into (`Sent` is their home). +pub const SENDER_FOLDERS: [Folder; 3] = [Folder::Sent, Folder::Archive, Folder::Trash]; +/// Folders a recipient may file their side into (`Inbox` is their home). +pub const RECIPIENT_FOLDERS: [Folder; 3] = [Folder::Inbox, Folder::Archive, Folder::Trash]; + /// 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)] diff --git a/src/domain/preferences.rs b/src/domain/preferences.rs index 0366e56..42c0647 100644 --- a/src/domain/preferences.rs +++ b/src/domain/preferences.rs @@ -5,7 +5,7 @@ use sqlx::Type; -use crate::constant::{LANGUAGES, PALETTE_COLOR_LEN, THEMES}; +use crate::constant::PALETTE_COLOR_LEN; use crate::error::ValidationError; /// The frontend color scheme. @@ -40,6 +40,8 @@ impl Theme { } } +pub const THEMES: [Theme; 2] = [Theme::Light, Theme::Dark]; + /// 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, Type)] @@ -70,6 +72,8 @@ impl Language { } } +pub const LANGUAGES: [Language; 2] = [Language::Tr, Language::En]; + /// The frontend accent color, a 6-digit hex with a leading `#`, stored /// lowercase (`"#fefae0"`). /// diff --git a/src/domain/role.rs b/src/domain/role.rs index d050109..b0fdf62 100644 --- a/src/domain/role.rs +++ b/src/domain/role.rs @@ -1,6 +1,5 @@ use sqlx::Type; -use crate::constant::ROLES; use crate::error::ValidationError; /// The access levels, in ascending order of privilege. @@ -89,6 +88,18 @@ impl Role { } } +/// Every *assignable* role, lowest privilege first. `Role::Ai` is deliberately +/// absent: it is a service principal, so leaving it out of this table is what +/// keeps `Role::try_from_str` (and every surface that lists roles) from ever +/// handing it to a user. +pub const ROLES: [Role; 5] = [ + Role::Parent, + Role::Student, + Role::Teacher, + Role::Manager, + Role::Admin, +]; + #[cfg(test)] mod tests { use super::*; diff --git a/src/tenant.rs b/src/tenant.rs index fa8cb24..2c2ec0f 100644 --- a/src/tenant.rs +++ b/src/tenant.rs @@ -33,7 +33,6 @@ use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ValidationError}; use crate::module::ModuleSet; use crate::telemetry::Metrics; -use crate::web::tenant_state::ResolvedTenant; /// 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 @@ -335,6 +334,18 @@ pub struct Tenants { leases: Option, } +/// Everything one registry read tells us about the school behind a request: +/// its handle and what it has bought. Cached in the request's extensions by +/// [`crate::web::tenant_state::resolve_tenant`], so a request that needs the +/// school twice (the shadow [`crate::web::tenant_state::State`] *and* +/// [`crate::web::CurrentUser`], which is most of them) reads the registry once. +#[derive(Clone)] +pub struct ResolvedTenant { + pub slug: Slug, + pub db: Database, + pub modules: ModuleSet, +} + impl Tenants { /// Wrap an already-connected, already-migrated control pool. Production /// constructor — [`crate::database::init`] calls it once at boot. diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index 2e82864..ee00e78 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -20,7 +20,8 @@ use std::time::Duration; -use crate::web::tenant_state::{ResolvedTenant, SchoolSlug, State, TenantExt}; +use crate::tenant::ResolvedTenant; +use crate::web::tenant_state::{SchoolSlug, State, TenantExt}; use axum::Json; use axum::extract::{Path, Query}; use axum::http::StatusCode; diff --git a/src/web/course_notes.rs b/src/web/course_notes.rs index cfe17d1..84a7be7 100644 --- a/src/web/course_notes.rs +++ b/src/web/course_notes.rs @@ -6,7 +6,8 @@ //! [`super::courses::can_view_course`] (the above, or anyone the course //! reaches). -use crate::web::tenant_state::{ResolvedTenant, State}; +use crate::tenant::ResolvedTenant; +use crate::web::tenant_state::State; use axum::Json; use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; diff --git a/src/web/dto.rs b/src/web/dto.rs index d79f3cf..cbbbb8d 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -38,7 +38,7 @@ pub enum Role { } /// The roles a request may ask for: the five human ones, exactly -/// [`crate::constant::ROLES`]. Documentation only — the handlers still take the +/// [`crate::domain::role::ROLES`]. Documentation only — the handlers still take the /// role as a string and funnel it through /// [`crate::domain::role::Role::try_from_str`], so an unknown value is a uniform /// `400` rather than a deserialization error. It exists because [`Role`] (the diff --git a/src/web/limits.rs b/src/web/limits.rs index cecb9ad..b9a7e2e 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -19,7 +19,9 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::constant::*; -use crate::constant::{LANGUAGES, ROLES, THEMES}; +use crate::domain::badge::BADGES; +use crate::domain::preferences::{LANGUAGES, THEMES}; +use crate::domain::role::ROLES; use crate::state::AppState; pub fn routes() -> OpenApiRouter { diff --git a/src/web/modules.rs b/src/web/modules.rs index b37e84e..be206e9 100644 --- a/src/web/modules.rs +++ b/src/web/modules.rs @@ -21,8 +21,8 @@ use utoipa_axum::routes; use crate::error::ErrorResponse; use crate::module::{Module, ModuleSet, Package}; use crate::state::AppState; +use crate::tenant::ResolvedTenant; use crate::web::CurrentUser; -use crate::web::tenant_state::ResolvedTenant; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() diff --git a/src/web/tenant_state.rs b/src/web/tenant_state.rs index c7ad8c6..ece2322 100644 --- a/src/web/tenant_state.rs +++ b/src/web/tenant_state.rs @@ -21,19 +21,7 @@ use crate::database::Database; use crate::error::AppError; use crate::module::ModuleSet; use crate::state::AppState; -use crate::tenant::Slug; - -/// Everything one registry read tells us about the school behind a request: -/// its handle and what it has bought. Cached in the request's extensions by -/// [`resolve_tenant`], so a request that needs the school twice (the shadow -/// [`State`] *and* [`crate::web::CurrentUser`], which is most of them) reads -/// the registry once. -#[derive(Clone)] -pub struct ResolvedTenant { - pub slug: Slug, - pub db: Database, - pub modules: ModuleSet, -} +use crate::tenant::{ResolvedTenant, Slug}; /// The school a request has already been resolved into, injected as a request /// extension by an in-process caller that has no cookie — today only the AI diff --git a/tests/integration.rs b/tests/integration.rs index 96fd902..568a929 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -5217,7 +5217,7 @@ async fn admin_creates_a_user() { /// hold. `Role` carries no `serde` derive (`src/domain/role.rs:21`), so no /// handler can bind a role straight out of a body — every request-supplied role /// passes `Role::try_from_str`, which answers only with a member of -/// `constant::ROLES` (`src/constant.rs:674`, the five human roles). +/// `domain::role::ROLES` (`src/domain/role.rs`, the five human roles). /// /// Grep-verified 2026-08-12, the complete set of role paths a request can reach: /// * `src/web/users.rs:453` — `PATCH /users/{id}/role`, the *only* path that diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index bae3f3a..f39243e 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -173,10 +173,20 @@ const EXCLUDED: &[(&str, &str)] = &[ ("STATUS_PENDING", "pool-question lifecycle state"), ("STATUS_APPROVED", "pool-question lifecycle state"), ("POOL_QUESTION_STATUSES", "pool-question lifecycle states"), + // Which folders a copy may be filed into is carried by the message itself + // (its `folder` field), so the client reads the accepted set off the + // resource it is acting on — never a public list, and /limits has no + // message-folder group to place them in. + ( + "SENDER_FOLDERS", + "folders a sender may file their side into", + ), + ( + "RECIPIENT_FOLDERS", + "folders a recipient may file their side into", + ), ("BANK_VISIBILITY_PRIVATE", "bank-question visibility value"), ("BANK_VISIBILITY_SCHOOL", "bank-question visibility value"), - ("SENDER_FOLDERS", "folders a sender may file into"), - ("RECIPIENT_FOLDERS", "folders a recipient may file into"), // Client-facing, but deliberately not compile-time contracts: these are // per-deployment defaults an operator overrides by environment variable. // `GET /limits` publishes the running server's ACTUAL tiers (from @@ -244,7 +254,7 @@ fn is_storage_identifier(name: &str) -> bool { .any(|prefix| name.starts_with(prefix)) } -/// Every `pub const` declared in `src/constant.rs`. +/// Every `pub const` declared in `source`, in declaration order. fn declared_constants(source: &str) -> BTreeSet { source .lines() @@ -255,15 +265,24 @@ fn declared_constants(source: &str) -> BTreeSet { .collect() } -/// True when `limits.rs` mentions the constant as a whole word — the response -/// is built by naming each constant directly, so a mention is the reference. +/// True when `limits.rs` mentions the constant as a whole word in its *body* — +/// the response is built by naming each constant directly, so a mention there +/// is the reference. `use` lines are skipped: an import proves a name is in +/// scope, not that anything publishes it, and reading it as a reference would +/// let deleting a table from the response keep the guard green. fn references(source: &str, name: &str) -> bool { - source.match_indices(name).any(|(at, _)| { - let before = source[..at].chars().next_back(); - let after = source[at + name.len()..].chars().next(); - let boundary = |c: Option| !matches!(c, Some(c) if c.is_alphanumeric() || c == '_'); - boundary(before) && boundary(after) - }) + source + .lines() + .filter(|line| !line.trim_start().starts_with("use ")) + .any(|line| { + line.match_indices(name).any(|(at, _)| { + let before = line[..at].chars().next_back(); + let after = line[at + name.len()..].chars().next(); + let boundary = + |c: Option| !matches!(c, Some(c) if c.is_alphanumeric() || c == '_'); + boundary(before) && boundary(after) + }) + }) } #[test] @@ -303,6 +322,56 @@ fn every_constant_is_published_or_deliberately_excluded() { ); } +/// The accepted-value tables that moved out of `src/constant.rs` into their +/// domain modules (which is also their only legal home — `validation_bounds_ +/// live_in_constant_rs` below bans the bound-shaped ones elsewhere, but an +/// array of enum values is neither a `MAX_`/`MIN_` bound nor numeric, so it +/// escapes that sweep). Each is either published by `GET /limits` or excused +/// with a reason; both are consumed by the test below. +const MOVED_TABLES: &[(&str, &str)] = &[ + ("src/domain/role.rs", "ROLES"), + ("src/domain/preferences.rs", "THEMES"), + ("src/domain/preferences.rs", "LANGUAGES"), + ("src/domain/message.rs", "SENDER_FOLDERS"), + ("src/domain/message.rs", "RECIPIENT_FOLDERS"), + ("src/domain/badge.rs", "BADGES"), +]; + +#[test] +fn moved_value_tables_are_still_published_or_deliberately_excluded() { + // The sweep above only reads `src/constant.rs`, so the day the accepted- + // value tables moved into their domain modules they left its scan: nothing + // then failed if a future edit dropped one from `src/web/limits.rs`. This + // re-establishes that guarantee for the tables that moved — but for that + // table list alone, not the whole modules, so the many server-side bounds + // that also live there are not dragged in and do not each need an + // EXCLUDED entry of their own. + let root = env!("CARGO_MANIFEST_DIR"); + let limits = fs::read_to_string(format!("{root}/src/web/limits.rs")).expect("read limits.rs"); + let excluded: BTreeSet<&str> = EXCLUDED.iter().map(|(name, _)| *name).collect(); + + let mut missing = Vec::new(); + for (module, name) in MOVED_TABLES { + let source = fs::read_to_string(format!("{root}/{module}")) + .unwrap_or_else(|_| panic!("read {module}")); + assert!( + declared_constants(&source).contains(*name), + "{name} is no longer a `pub const` in {module} — MOVED_TABLES is stale" + ); + if !excluded.contains(name) && !references(&limits, name) { + missing.push(format!(" {name} ({module})")); + } + } + + assert!( + missing.is_empty(), + "these accepted-value tables left src/constant.rs and now reach neither GET /limits \ + nor the EXCLUDED list in this test:\n{}\n\nAdd each to src/web/limits.rs so clients \ + stop guessing it, or to EXCLUDED with the reason it is not client-facing.", + missing.join("\n") + ); +} + /// Constants outside `constant.rs` that the sweep below may ignore — either /// because they are not a client-facing bound at all, or because they are /// published by a route that reads the *live* value instead of the constant. @@ -384,10 +453,20 @@ fn validation_bounds_live_in_constant_rs() { fn exclusions_are_real_constants() { // An exclusion for a deleted constant is dead weight that also silently // widens the allowlist if the name is ever reused for something public. + // A name is real when it is declared in `src/constant.rs` or is one of the + // accepted-value tables that moved into its domain module — the two homes + // the completeness test above reads. let root = env!("CARGO_MANIFEST_DIR"); let constants = fs::read_to_string(format!("{root}/src/constant.rs")).expect("read constant.rs"); - let declared = declared_constants(&constants); + let mut declared = declared_constants(&constants); + for (module, name) in MOVED_TABLES { + let source = fs::read_to_string(format!("{root}/{module}")) + .unwrap_or_else(|_| panic!("read {module}")); + if declared_constants(&source).contains(*name) { + declared.insert((*name).to_string()); + } + } let stale: Vec<&str> = EXCLUDED .iter() @@ -397,6 +476,7 @@ fn exclusions_are_real_constants() { assert!( stale.is_empty(), - "EXCLUDED names constants that no longer exist in src/constant.rs: {stale:?} — drop them" + "EXCLUDED names constants that no longer exist (neither in src/constant.rs nor in \ + the modules listed in MOVED_TABLES): {stale:?} — drop them" ); } diff --git a/tests/regress_badges.rs b/tests/regress_badges.rs index 9d3cc53..f5a405d 100644 --- a/tests/regress_badges.rs +++ b/tests/regress_badges.rs @@ -26,9 +26,10 @@ use common::{ send, set_role, taught_under, }; use hezarfen_backend::constant::{ - BADGES, HIGH_MARK_MIN, MIN_COUNTED_POMODORO_MS, STUDY_STREAK_LAST_DAY_FIELD, + HIGH_MARK_MIN, MIN_COUNTED_POMODORO_MS, STUDY_STREAK_LAST_DAY_FIELD, }; use hezarfen_backend::database::Database; +use hezarfen_backend::domain::badge::BADGES; use hezarfen_backend::domain::timestamp::Timestamp; use serde_json::{Value, json};