forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

limits_completeness.rs673 lines, 26.8 KiBHistoryRawDownload
1//! The forcing function behind `GET /limits`.
2//!
3//! `src/web/limits.rs` is a hand-written mapping of `src/constant.rs` into a
4//! JSON document. That is a mirror, and mirrors drift: the day someone adds a
5//! constant, nothing about the compiler or the test suite would notice that
6//! the endpoint promising "every fixed bound" quietly stopped being complete.
7//! The frontend would then be back to guessing that one value — the exact
8//! problem the endpoint exists to remove.
9//!
10//! So this test reads both files as text and asserts every `pub const` in
11//! `constant.rs` is either referenced by `limits.rs` or listed below as a
12//! deliberate exclusion with a reason. A new constant fails the suite until
13//! someone makes that call consciously.
14//!
15//! Text, not reflection, because Rust cannot enumerate a module's constants at
16//! runtime. The trade-off is that this proves a constant is *mentioned*, not
17//! that it lands on a sensible JSON key — `integration::limits_publishes_the_
18//! bounds_the_api_actually_enforces` covers the values themselves.
19
20use std::collections::BTreeSet;
21use std::fs;
22
23/// Constants that deliberately stay out of `GET /limits`, each with the reason
24/// it is not a client-facing bound. Adding a name here is a decision, not a
25/// formality: it says a frontend has no business knowing this number.
26const EXCLUDED: &[(&str, &str)] = &[
27 // Server-internal operational timing. A client cannot act on any of these,
28 // and publishing them would invite a frontend to build its own retry or
29 // liveness logic against numbers we want free to change.
30 (
31 "DB_CONNECT_BACKOFF_MAX_SECS",
32 "boot reconnect backoff ceiling",
33 ),
34 ("CAS_UPDATE_RETRIES", "internal compare-and-set retry count"),
35 (
36 "CAP_WRITE_TRIES",
37 "internal retry count for a contended cap counter",
38 ),
39 (
40 "CAP_WRITE_BACKOFF_MS",
41 "internal backoff between cap counter retries",
42 ),
43 (
44 "SUBMISSION_OPEN_GUARD",
45 "SQL fragment: the condition every homework-submission write carries so \
46 a grade freezes it in the database; the client sees the freeze as a 409, \
47 never as a number",
48 ),
49 (
50 "FEE_PLAN_UNASSIGNED_GUARD",
51 "SQL fragment: the condition a fee plan's edit and delete carry so an \
52 assigned plan freezes in the database; the client sees the freeze as a \
53 409, never as a number",
54 ),
55 (
56 "REGISTRATION_FROZEN_GUARD",
57 "SQL fragment: the condition the role cascade carries so a frozen signup \
58 list is left exactly as it stands; the client sees the freeze as a 409, \
59 never as a number",
60 ),
61 (
62 "BOARD_REPLAY_CHUNK",
63 "how the board-room socket batches its join replay; the client reads the \
64 strokes, not the batch size",
65 ),
66 (
67 "BOARD_HUB_CAPACITY",
68 "depth of one board room's fan-out channel; a lagging socket is dropped \
69 and rejoins, which the client handles as a reconnect, not as a number",
70 ),
71 (
72 "UPLOAD_BODY_OVERHEAD_BYTES",
73 "multipart headroom over max_file_bytes; the client sizes against \
74 max_file_bytes itself, which /limits does publish",
75 ),
76 // The AI bridge is a backend↔AI-service contract over QUIC. No browser
77 // ever speaks it; the services that do are configured out of band.
78 ("AI_PROTOCOL", "QUIC bridge wire identifier"),
79 ("AI_ALPN", "QUIC bridge ALPN"),
80 ("AI_MAX_FRAME_BYTES", "QUIC bridge frame ceiling"),
81 ("AI_DEFAULT_REQUEST_TIMEOUT_SECS", "AI inference deadline"),
82 (
83 "AI_MAX_REQUEST_TIMEOUT_SECS",
84 "ceiling on the configured AI inference deadline",
85 ),
86 ("AI_MAX_CONCURRENT_PER_WORKER", "AI worker concurrency cap"),
87 (
88 "AI_DEFAULT_CONCURRENT_PER_WORKER",
89 "AI worker concurrency default",
90 ),
91 ("AI_IDLE_TIMEOUT_SECS", "QUIC connection idle timeout"),
92 ("AI_KEEPALIVE_SECS", "QUIC connection keepalive"),
93 (
94 "AI_BLOB_WRITE_STALL_SECS",
95 "how long a blob body may stall before its QUIC stream is reset",
96 ),
97 ("AI_HANDSHAKE_TIMEOUT_SECS", "AI service handshake deadline"),
98 (
99 "AI_API_ALLOWLIST",
100 "the AI services' read scope; a service contract in README, and \
101 publishing it would hand every browser the map",
102 ),
103 (
104 "AI_CHAT_CAPABILITY",
105 "capability string an AI service declares",
106 ),
107 (
108 "AI_RAG_INDEX_CAPABILITY",
109 "capability string an AI service declares",
110 ),
111 (
112 "AI_RAG_INDEX_TIMEOUT_SECS",
113 "deadline on a background course-note indexing round trip; no client \
114 waits on it",
115 ),
116 (
117 "AI_RAG_CHAT_CAPABILITY",
118 "capability string an AI service declares",
119 ),
120 (
121 "AI_RAG_CHAT_TIMEOUT_SECS",
122 "deadline on one RAG ask round trip; the browser waits on its message \
123 stream, never on this number",
124 ),
125 (
126 "AI_RAG_SUMMARIZE_CAPABILITY",
127 "capability string an AI service declares",
128 ),
129 (
130 "AI_RAG_SUMMARIZE_TIMEOUT_SECS",
131 "deadline on one one-shot summary of a range; the caller waits on the \
132 artifact itself and acts on the door's 200/400/403/503, never on this \
133 number",
134 ),
135 (
136 "AI_RAG_QUESTIONS_CAPABILITY",
137 "capability string an AI service declares",
138 ),
139 (
140 "AI_RAG_QUESTIONS_TIMEOUT_SECS",
141 "deadline on one one-shot question set over a range; the caller waits \
142 on the artifact itself and acts on the door's 200/400/403/503, never \
143 on this number",
144 ),
145 (
146 "AI_INSIGHT_STUDENT_CAPABILITY",
147 "capability string an AI service declares",
148 ),
149 (
150 "AI_INSIGHT_STUDENT_TIMEOUT_SECS",
151 "deadline on one student's compute; the dispatch is off the request \
152 path and a reader polls the stored rows",
153 ),
154 (
155 "AI_INSIGHT_CLASS_CAPABILITY",
156 "capability string an AI service declares (declared for the contract; \
157 no door dispatches it yet)",
158 ),
159 (
160 "AI_INSIGHT_REFRESH_CAPABILITY",
161 "capability string an AI service declares",
162 ),
163 (
164 "AI_INSIGHT_REFRESH_TIMEOUT_SECS",
165 "deadline on one school-wide recompute; the run's own ledger is \
166 `zeka_run`, which the client polls",
167 ),
168 (
169 "AI_INSIGHT_REPORT_CAPABILITY",
170 "capability string an AI service declares",
171 ),
172 (
173 "AI_INSIGHT_REPORT_TIMEOUT_SECS",
174 "deadline on one school-level report render; the manager waits on the \
175 artifact itself and a client acts on the door's 200/409/503, never on \
176 this number",
177 ),
178 // The storage surface ZEKA's rows are written through (the service calls
179 // these; the backend runs them). A browser never speaks the bridge, and
180 // the HTTP doors that mirror them publish what a client can act on.
181 (
182 "AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY",
183 "capability string the backend serves to an AI service",
184 ),
185 (
186 "AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY",
187 "capability string the backend serves to an AI service",
188 ),
189 (
190 "AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY",
191 "capability string the backend serves to an AI service",
192 ),
193 (
194 "AI_INSIGHT_PROFILE_UPSERT_CAPABILITY",
195 "capability string the backend serves to an AI service",
196 ),
197 (
198 "AI_INSIGHT_RUN_UPSERT_CAPABILITY",
199 "capability string the backend serves to an AI service",
200 ),
201 (
202 "AI_INSIGHT_PENDING_LIST_CAPABILITY",
203 "capability string the backend serves to an AI service",
204 ),
205 (
206 "AI_INSIGHT_RETENTION_SWEEP_CAPABILITY",
207 "capability string the backend serves to an AI service",
208 ),
209 (
210 "AI_INSIGHT_DEPARTED_PURGE_CAPABILITY",
211 "capability string the backend serves to an AI service",
212 ),
213 (
214 "AI_INSIGHT_SCHOOLS_LIST_CAPABILITY",
215 "capability string the backend serves to an AI service",
216 ),
217 (
218 "MAX_INSIGHT_BATCH_ROWS",
219 "rows per bridge call: the AI service's own batch size, enforced by the \
220 doors as a 413 and by the bridge as `too_many_rows`; a client of \
221 neither cannot act on it",
222 ),
223 (
224 "MAX_INSIGHT_PENDING_STUDENTS",
225 "students one bridge answer may carry; over it the call is refused \
226 (`too_many_rows`) rather than clipped, so there is no client-side \
227 value to size against",
228 ),
229 (
230 "MAX_INSIGHT_PURGE_STUDENTS",
231 "students one bridge purge call may name; the roster is the AI \
232 service's own list, not something a browser assembles",
233 ),
234 (
235 "MAX_INSIGHT_REFRESH_STUDENTS",
236 "students one school-wide refresh may carry when its door fills the \
237 roster itself; the refresh batch is the AI service's own work unit, \
238 not a client-facing bound",
239 ),
240 (
241 "AI_PODCAST_SUBMIT_CAPABILITY",
242 "capability string an AI service declares",
243 ),
244 (
245 "AI_PODCAST_REPORT_CAPABILITY",
246 "capability string the backend serves; the AI service calls it",
247 ),
248 (
249 "AI_PODCAST_CANCEL_CAPABILITY",
250 "capability string an AI service declares",
251 ),
252 (
253 "PODCAST_AUDIO_MAX_BYTES",
254 "the largest episode the backend ingests from a service; a service-side \
255 ingest bound a browser never assembles a body for",
256 ),
257 (
258 "PODCAST_JOB_RETENTION_SECS",
259 "how long a finished podcast job stays readable; the doors answer 410 \
260 past it, which is the whole client-visible behavior — the number is \
261 the operator's policy, not a value a client sizes against",
262 ),
263 (
264 "PODCAST_JOB_STALE_FLOOR_SECS",
265 "floor of the read-side staleness window a dead job is projected \
266 failed in; a client reads the projected state, never sets this",
267 ),
268 (
269 "PODCAST_JOB_STALE_ETA_FACTOR",
270 "how many times its own ETA a podcast job may exceed before the read \
271 side stops believing it runs; same as the floor — the projection is \
272 the visible behavior",
273 ),
274 (
275 "PODCAST_INTERRUPTED_CODE",
276 "error_code value the backend writes for a job it concluded died; a \
277 client reads it off the job, it is not a tunable",
278 ),
279 (
280 "CHAT_STREAM_POLL_MS",
281 "server-side poll cadence behind the SSE stream",
282 ),
283 (
284 "CHATBOT_PENDING_STALE_SECS",
285 "when a stuck answer is declared failed",
286 ),
287 (
288 "RAG_PENDING_STALE_SECS",
289 "when a stuck answer is declared failed",
290 ),
291 // Seed data for the settings singleton, not a bound. The live list is on
292 // `GET /settings`, which is where a client must read it — publishing the
293 // default too would invite rendering it instead of the school's actual one.
294 (
295 "DEFAULT_EXAM_KINDS",
296 "settings seed; the live list is on GET /settings",
297 ),
298 (
299 "DEFAULT_MEAL_SLOTS",
300 "settings seed; the live list is on GET /settings",
301 ),
302 (
303 "DEFAULT_DIETARY_TAGS",
304 "settings seed; the live list is on GET /settings",
305 ),
306 (
307 "DEFAULT_GRADE_BANDS",
308 "settings seed; the school's own bands are on GET /settings",
309 ),
310 // The school's zone is a settings *value*, not a bound: `GET /settings`
311 // serves what this school runs on, and a client renders that, never a
312 // default or the allow-list behind it. (`MAX_ABSENCE_DAYS` below is the
313 // one settings bound this list still owes /limits.)
314 (
315 "DEFAULT_TIMEZONE",
316 "settings fallback; the school's live zone is on GET /settings",
317 ),
318 (
319 "TIMEZONES",
320 "settings allow-list; the school's live zone is on GET /settings",
321 ),
322 // A settings field's own range (the office types an absence ceiling as a
323 // number). It belongs beside `max_grade_bands` in the /limits settings
324 // group — excluded here rather than silently, so the day a frontend needs
325 // the range the decision is already written down.
326 (
327 "MAX_ABSENCE_DAYS",
328 "settings field bound; /limits should carry it beside max_grade_bands",
329 ),
330 (
331 "DECOY_PASSWORD",
332 "login-decoy input, never a real credential",
333 ),
334 ("STALE_ERROR_CODE", "error_code a stuck answer projects as"),
335 ("TEXT_FOLD_REPLACEMENTS", "server-side search folding table"),
336 // Accepted-value lists that stay off /limits deliberately: unlike roles,
337 // themes and languages (which the endpoint does publish), these are read
338 // back from the resource itself — a question carries its status, a message
339 // its folder — so a client never has to know the set up front.
340 ("STATUS_PENDING", "pool-question lifecycle state"),
341 ("STATUS_APPROVED", "pool-question lifecycle state"),
342 ("POOL_QUESTION_STATUSES", "pool-question lifecycle states"),
343 // Which folders a copy may be filed into is carried by the message itself
344 // (its `folder` field), so the client reads the accepted set off the
345 // resource it is acting on — never a public list, and /limits has no
346 // message-folder group to place them in.
347 (
348 "SENDER_FOLDERS",
349 "folders a sender may file their side into",
350 ),
351 (
352 "RECIPIENT_FOLDERS",
353 "folders a recipient may file their side into",
354 ),
355 ("BANK_VISIBILITY_PRIVATE", "bank-question visibility value"),
356 ("BANK_VISIBILITY_SCHOOL", "bank-question visibility value"),
357 // Client-facing, but deliberately not compile-time contracts: these are
358 // per-deployment defaults an operator overrides by environment variable.
359 // `GET /limits` publishes the running server's ACTUAL tiers (from
360 // AppState) in its `rate` group, which is strictly better than publishing
361 // a default a deployment may not use.
362 (
363 "DEFAULT_AUTH_RATE_LIMIT",
364 "env-tunable; live value served in /limits `rate`",
365 ),
366 (
367 "DEFAULT_API_RATE_LIMIT",
368 "env-tunable; live value served in /limits `rate`",
369 ),
370 (
371 "DEFAULT_CHATBOT_RATE_LIMIT",
372 "env-tunable; live value served in /limits `rate`",
373 ),
374 (
375 "DEFAULT_RAG_RATE_LIMIT",
376 "env-tunable; live value served in /limits `rate`",
377 ),
378 ("MILLIS_PER_DAY", "unit conversion, not a limit"),
379 ("MILLIS_PER_WEEK", "unit conversion, not a limit"),
380 (
381 "MAX_ETAG_BODY_BYTES",
382 "ETag middleware's own buffering ceiling",
383 ),
384 ("PURGE_AT", "rate-limiter bucket eviction threshold"),
385 // Not a per-client budget: one fleet-wide counter that only exists while
386 // the bucket map is saturated. A client cannot compute its own allowance
387 // from it, and publishing it would advertise the flood threshold.
388 (
389 "RATE_LIMIT_OVERFLOW_MAX",
390 "aggregate budget for keyless clients while the bucket map is full",
391 ),
392 // How a tier's window is carried through a restart. A client is held to
393 // the tier itself (published live in /limits `rate`), never to the cadence
394 // it is reconciled at — publishing that would invite pacing against it.
395 (
396 "RATE_SYNC_INTERVAL_SECS",
397 "how often the process folds its counters into the database",
398 ),
399 ("RATE_SYNC_TIMEOUT_SECS", "deadline on one sync round"),
400 (
401 "RATE_SYNC_MAX_KEYS",
402 "client buckets one sync round carries",
403 ),
404 (
405 "MAX_ERROR_CODE_LEN",
406 "bounds a code the SERVER writes from an AI service's reply; no client sends it",
407 ),
408 (
409 "AI_PRINCIPAL_KEY",
410 "record key of the in-memory AI service principal; a client can neither \
411 assign nor address it",
412 ),
413 ("REPLY_CHUNKS", "how the SSE stream slices an answer"),
414 ("MIN_CHUNK_CHARS", "how the SSE stream slices an answer"),
415];
416
417/// A `*_TABLE` constant is a SurrealDB table name and a `*_FIELD` one a column
418/// name, not a bound. Listing all 37 by hand would bury the deliberate
419/// exclusions above in boilerplate, so the whole shape is excused once — the
420/// naming convention *is* the decision.
421fn is_storage_identifier(name: &str) -> bool {
422 (name.ends_with("_TABLE") || name.ends_with("_FIELD"))
423 && !["MAX_", "MIN_", "DEFAULT_"]
424 .iter()
425 .any(|prefix| name.starts_with(prefix))
426}
427
428/// Every `pub const` declared in `source`, in declaration order.
429fn declared_constants(source: &str) -> BTreeSet<String> {
430 source
431 .lines()
432 .filter_map(|line| line.strip_prefix("pub const "))
433 .filter_map(|rest| rest.split(&[':', ' '][..]).next())
434 .filter(|name| !name.is_empty())
435 .map(str::to_string)
436 .collect()
437}
438
439/// True when `limits.rs` mentions the constant as a whole word in its *body* —
440/// the response is built by naming each constant directly, so a mention there
441/// is the reference. `use` lines are skipped: an import proves a name is in
442/// scope, not that anything publishes it, and reading it as a reference would
443/// let deleting a table from the response keep the guard green.
444fn references(source: &str, name: &str) -> bool {
445 source
446 .lines()
447 .filter(|line| !line.trim_start().starts_with("use "))
448 .any(|line| {
449 line.match_indices(name).any(|(at, _)| {
450 let before = line[..at].chars().next_back();
451 let after = line[at + name.len()..].chars().next();
452 let boundary =
453 |c: Option<char>| !matches!(c, Some(c) if c.is_alphanumeric() || c == '_');
454 boundary(before) && boundary(after)
455 })
456 })
457}
458
459#[test]
460fn every_constant_is_published_or_deliberately_excluded() {
461 let root = env!("CARGO_MANIFEST_DIR");
462 let constants =
463 fs::read_to_string(format!("{root}/src/constant.rs")).expect("read constant.rs");
464 let limits = fs::read_to_string(format!("{root}/src/web/limits.rs")).expect("read limits.rs");
465
466 let declared = declared_constants(&constants);
467 assert!(
468 declared.len() > 50,
469 "parsed only {} constants — the `pub const` parse broke, not the mapping",
470 declared.len()
471 );
472
473 let excluded: BTreeSet<&str> = EXCLUDED.iter().map(|(name, _)| *name).collect();
474 let missing: Vec<&String> = declared
475 .iter()
476 .filter(|name| {
477 !excluded.contains(name.as_str())
478 && !is_storage_identifier(name)
479 && !references(&limits, name)
480 })
481 .collect();
482
483 assert!(
484 missing.is_empty(),
485 "these constants are in src/constant.rs but reach neither GET /limits nor the \
486 EXCLUDED list in this test:\n {}\n\nAdd each to src/web/limits.rs so clients \
487 stop guessing it, or to EXCLUDED with the reason it is not client-facing.",
488 missing
489 .iter()
490 .map(|name| name.as_str())
491 .collect::<Vec<_>>()
492 .join("\n ")
493 );
494}
495
496/// The accepted-value tables that moved out of `src/constant.rs` into their
497/// domain modules (which is also their only legal home — `validation_bounds_
498/// live_in_constant_rs` below bans the bound-shaped ones elsewhere, but an
499/// array of enum values is neither a `MAX_`/`MIN_` bound nor numeric, so it
500/// escapes that sweep). Each is either published by `GET /limits` or excused
501/// with a reason; both are consumed by the test below.
502const MOVED_TABLES: &[(&str, &str)] = &[
503 ("src/domain/role.rs", "ROLES"),
504 ("src/domain/preferences.rs", "THEMES"),
505 ("src/domain/preferences.rs", "LANGUAGES"),
506 ("src/domain/profile.rs", "GENDERS"),
507 ("src/domain/message.rs", "SENDER_FOLDERS"),
508 ("src/domain/message.rs", "RECIPIENT_FOLDERS"),
509 ("src/domain/badge.rs", "BADGES"),
510];
511
512#[test]
513fn moved_value_tables_are_still_published_or_deliberately_excluded() {
514 // The sweep above only reads `src/constant.rs`, so the day the accepted-
515 // value tables moved into their domain modules they left its scan: nothing
516 // then failed if a future edit dropped one from `src/web/limits.rs`. This
517 // re-establishes that guarantee for the tables that moved — but for that
518 // table list alone, not the whole modules, so the many server-side bounds
519 // that also live there are not dragged in and do not each need an
520 // EXCLUDED entry of their own.
521 let root = env!("CARGO_MANIFEST_DIR");
522 let limits = fs::read_to_string(format!("{root}/src/web/limits.rs")).expect("read limits.rs");
523 let excluded: BTreeSet<&str> = EXCLUDED.iter().map(|(name, _)| *name).collect();
524
525 let mut missing = Vec::new();
526 for (module, name) in MOVED_TABLES {
527 let source = fs::read_to_string(format!("{root}/{module}"))
528 .unwrap_or_else(|_| panic!("read {module}"));
529 assert!(
530 declared_constants(&source).contains(*name),
531 "{name} is no longer a `pub const` in {module} — MOVED_TABLES is stale"
532 );
533 if !excluded.contains(name) && !references(&limits, name) {
534 missing.push(format!(" {name} ({module})"));
535 }
536 }
537
538 assert!(
539 missing.is_empty(),
540 "these accepted-value tables left src/constant.rs and now reach neither GET /limits \
541 nor the EXCLUDED list in this test:\n{}\n\nAdd each to src/web/limits.rs so clients \
542 stop guessing it, or to EXCLUDED with the reason it is not client-facing.",
543 missing.join("\n")
544 );
545}
546
547/// Constants outside `constant.rs` that the sweep below may ignore — either
548/// because they are not a client-facing bound at all, or because they are
549/// published by a route that reads the *live* value instead of the constant.
550///
551/// Empty since the consolidation that made `constant.rs` the only home for any
552/// constant: every former entry now lives there and is excused (or published)
553/// through `EXCLUDED` above instead. A new name here is a claim that a bound
554/// belongs somewhere else, which needs an argument.
555const NOT_A_CLIENT_BOUND: &[(&str, &str)] = &[
556 (
557 "MAX_CODE_LEN",
558 "bound on the length of a podcast report's `stage`/`error_code` — values \
559 the AI *service* writes onto the job row; a browser reads the stored \
560 string back, it never sizes one against this",
561 ),
562 (
563 "MAX_TRANSCRIPT_LEN",
564 "bound on a podcast report's `transcript` — the AI service writes it, \
565 the result door returns the stored text; a browser never sizes a \
566 transcript against this",
567 ),
568 (
569 "MAX_ZONE_OFFSET_MINUTES",
570 "the largest shift `calendar::zoned_day` applies — internal arithmetic \
571 for a checked pre-flight in the materialize route, not a value a client \
572 sizes a request against",
573 ),
574];
575
576#[test]
577fn validation_bounds_live_in_constant_rs() {
578 // The completeness test above only guards `constant.rs`, so a bound
579 // declared anywhere else is invisible to it — it reaches neither `/limits`
580 // nor the OpenAPI spec, and no test notices. That is not hypothetical:
581 // `MAX_CHATBOT_THREAD_TITLE_LEN` sat private in `domain/chatbot_thread.rs`
582 // and escaped both surfaces until this sweep found it. This test makes the
583 // constants file the only legal home for a client-facing bound.
584 let root = env!("CARGO_MANIFEST_DIR");
585 let allowed: BTreeSet<&str> = NOT_A_CLIENT_BOUND.iter().map(|(name, _)| *name).collect();
586
587 let mut strays = Vec::new();
588 let mut stack = vec![format!("{root}/src")];
589 while let Some(dir) = stack.pop() {
590 for entry in fs::read_dir(&dir).expect("read src dir") {
591 let path = entry.expect("dir entry").path();
592 if path.is_dir() {
593 stack.push(path.to_string_lossy().into_owned());
594 continue;
595 }
596 if path.extension().is_none_or(|ext| ext != "rs") || path.ends_with("constant.rs") {
597 continue;
598 }
599 let source = fs::read_to_string(&path).expect("read source");
600 for line in source.lines() {
601 let trimmed = line.trim_start();
602 // Only `const NAME: <numeric> = <digit>` — a bound. Arrays of
603 // accepted values (`ROLES`) and string constants are not.
604 let Some(rest) = trimmed
605 .strip_prefix("pub const ")
606 .or_else(|| trimmed.strip_prefix("const "))
607 else {
608 continue;
609 };
610 let Some((name, tail)) = rest.split_once(':') else {
611 continue;
612 };
613 let looks_numeric = ["usize", "i64", "u64", "i32", "u32", "u16", "u8", "f64"]
614 .iter()
615 .any(|ty| tail.trim_start().starts_with(ty));
616 // `DEFAULT_` and the `_LIMIT`/`_CAP` suffixes matter as much as
617 // the `MAX_`/`MIN_` prefixes: the rate-limit tiers are named
618 // `DEFAULT_API_RATE_LIMIT`, and a sweep keyed only on prefixes
619 // walked straight past a budget every client is held to.
620 let bound_shaped = name.starts_with("MAX_")
621 || name.starts_with("MIN_")
622 || name.starts_with("DEFAULT_")
623 || name.ends_with("_LIMIT")
624 || name.ends_with("_CAP");
625 if looks_numeric && bound_shaped && !allowed.contains(name) {
626 let file = path.strip_prefix(root).unwrap_or(&path);
627 strays.push(format!(" {name} in {}", file.display()));
628 }
629 }
630 }
631 }
632
633 assert!(
634 strays.is_empty(),
635 "these validation bounds live outside src/constant.rs, so they reach neither \
636 GET /limits nor the OpenAPI spec and no test guards them:\n{}\n\nMove each into \
637 src/constant.rs (and map it in src/web/limits.rs), or add it to \
638 NOT_A_CLIENT_BOUND with the reason it is not a client-facing limit.",
639 strays.join("\n")
640 );
641}
642
643#[test]
644fn exclusions_are_real_constants() {
645 // An exclusion for a deleted constant is dead weight that also silently
646 // widens the allowlist if the name is ever reused for something public.
647 // A name is real when it is declared in `src/constant.rs` or is one of the
648 // accepted-value tables that moved into its domain module — the two homes
649 // the completeness test above reads.
650 let root = env!("CARGO_MANIFEST_DIR");
651 let constants =
652 fs::read_to_string(format!("{root}/src/constant.rs")).expect("read constant.rs");
653 let mut declared = declared_constants(&constants);
654 for (module, name) in MOVED_TABLES {
655 let source = fs::read_to_string(format!("{root}/{module}"))
656 .unwrap_or_else(|_| panic!("read {module}"));
657 if declared_constants(&source).contains(*name) {
658 declared.insert((*name).to_string());
659 }
660 }
661
662 let stale: Vec<&str> = EXCLUDED
663 .iter()
664 .map(|(name, _)| *name)
665 .filter(|name| !declared.contains(*name))
666 .collect();
667
668 assert!(
669 stale.is_empty(),
670 "EXCLUDED names constants that no longer exist (neither in src/constant.rs nor in \
671 the modules listed in MOVED_TABLES): {stale:?} — drop them"
672 );
673}