forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB69d4295Ahmet Kaan Gümüş2 months ago536 commits

partial_patch_terms.rs305 lines, 11.0 KiBHistoryRawDownload
1//! Two concurrent partial PATCHes on the same term must not revert each
2//! other: each writes only the field it carried, so `name` and `ends_at`
3//! survive together no matter which write lands last.
4
5mod common;
6
7use axum::http::StatusCode;
8use common::*;
9use serde_json::json;
10
11#[tokio::test]
12async fn concurrent_partial_patches_keep_both_fields() {
13 let (app, db) = app_and_db().await;
14 let manager = login_as(&app, &db, "term_race_manager", "manager").await;
15 // A dönem is a slice of an academic year since the K12 remodel, so every
16 // create in this file names one.
17 let year = create_year(&app, &manager, "2026-2027").await;
18
19 for round in 0..20 {
20 let created = send(
21 &app,
22 "POST",
23 "/terms",
24 Some(&manager),
25 Some(json!({
26 "name": "before",
27 "year": year,
28 "starts_at": 1_780_000_000_000_i64,
29 "ends_at": 1_790_000_000_000_i64,
30 })),
31 )
32 .await;
33 assert_eq!(created.status, StatusCode::CREATED, "round {round} create");
34 let id = id_of(&created.body);
35 let uri = format!("/terms/{id}");
36
37 let name_patch = json!({ "name": "after" });
38 let ends_patch = json!({ "ends_at": 1_795_000_000_000_i64 });
39 let (a, b) = tokio::join!(
40 send(&app, "PATCH", &uri, Some(&manager), Some(name_patch)),
41 send(&app, "PATCH", &uri, Some(&manager), Some(ends_patch)),
42 );
43 assert_eq!(a.status, StatusCode::OK, "round {round} name patch");
44 assert_eq!(b.status, StatusCode::OK, "round {round} ends_at patch");
45
46 let after = send(&app, "GET", &uri, Some(&manager), None).await.body;
47 assert_eq!(after["name"], "after", "round {round}: name reverted");
48 assert_eq!(
49 after["ends_at"], 1_795_000_000_000_i64,
50 "round {round}: ends_at reverted"
51 );
52 }
53}
54
55/// The range check is cross-field, so a partial PATCH validates the arriving
56/// end against the *stored* other end. Two PATCHes that are each fine against
57/// the stored row must not be able to commit an inverted range between them.
58#[tokio::test]
59async fn concurrent_range_patches_never_invert_the_term() {
60 let (app, db) = app_and_db().await;
61 let manager = login_as(&app, &db, "term_range_manager", "manager").await;
62 let year = create_year(&app, &manager, "2026-2027").await;
63
64 for round in 0..20 {
65 let created = send(
66 &app,
67 "POST",
68 "/terms",
69 Some(&manager),
70 Some(json!({
71 "name": "range",
72 "year": year,
73 "starts_at": 1_000_000_000_000_i64,
74 "ends_at": 2_000_000_000_000_i64,
75 })),
76 )
77 .await;
78 assert_eq!(created.status, StatusCode::CREATED, "round {round} create");
79 let uri = format!("/terms/{}", id_of(&created.body));
80
81 // Each is valid against the stored row on its own: 1.9e12 < 2e12 and
82 // 1.1e12 > 1e12. Together they would leave starts_at > ends_at.
83 let (a, b) = tokio::join!(
84 send(
85 &app,
86 "PATCH",
87 &uri,
88 Some(&manager),
89 Some(json!({ "starts_at": 1_900_000_000_000_i64 })),
90 ),
91 send(
92 &app,
93 "PATCH",
94 &uri,
95 Some(&manager),
96 Some(json!({ "ends_at": 1_100_000_000_000_i64 })),
97 ),
98 );
99 assert!(
100 a.status == StatusCode::OK || a.status == StatusCode::BAD_REQUEST,
101 "round {round} starts_at patch: {}",
102 a.status
103 );
104 assert!(
105 b.status == StatusCode::OK || b.status == StatusCode::BAD_REQUEST,
106 "round {round} ends_at patch: {}",
107 b.status
108 );
109
110 let after = send(&app, "GET", &uri, Some(&manager), None).await.body;
111 let starts = after["starts_at"].as_i64().expect("starts_at");
112 let ends = after["ends_at"].as_i64().expect("ends_at");
113 assert!(
114 starts <= ends,
115 "round {round}: stored range inverted — starts_at {starts} > ends_at {ends}"
116 );
117 }
118}
119
120/// Archiving a dönem freezes it: its own row takes no PATCH or DELETE, and the
121/// karne it issued on the way in is the snapshot `GET /marks/karne` serves from
122/// then on. Reads stay open — a past dönem is read-only, not hidden.
123///
124/// What a closed dönem no longer freezes is the structure around it, and this
125/// pins that too: a şube hangs off the academic *year* and the catalog off
126/// nothing at all, so neither create is refused by a past dönem — the bar moved
127/// up to the year when the class became the academic anchor. A test that still
128/// expected `term_archived` here would be pinning the old world.
129#[tokio::test]
130async fn an_archived_term_is_frozen_for_writes_and_open_for_reads() {
131 let (app, db) = app_and_db().await;
132 let manager = login_as(&app, &db, "archive_manager", "manager").await;
133 let teacher = login_as(&app, &db, "archive_teacher", "teacher").await;
134 let student = login_as(&app, &db, "archive_student", "student").await;
135
136 let year = create_year(&app, &manager, "2024-2025").await;
137 let created = send(
138 &app,
139 "POST",
140 "/terms",
141 Some(&manager),
142 Some(json!({
143 "name": "2024",
144 "year": year,
145 "starts_at": 1_700_000_000_000_i64,
146 "ends_at": 1_710_000_000_000_i64,
147 })),
148 )
149 .await;
150 assert_eq!(created.status, StatusCode::CREATED);
151 assert!(created.body["archived_at"].is_null(), "born open");
152 let id = id_of(&created.body);
153 let uri = format!("/terms/{id}");
154 let archive = format!("/terms/{id}/archive");
155
156 // Only manager+ may flip it.
157 for (who, cookie) in [("teacher", &teacher), ("student", &student)] {
158 let res = send(&app, "POST", &archive, Some(cookie), None).await;
159 assert_eq!(res.status, StatusCode::FORBIDDEN, "{who} archive");
160 }
161
162 let archived = send(&app, "POST", &archive, Some(&manager), None).await;
163 assert_eq!(archived.status, StatusCode::OK);
164 let stamp = archived.body["archived_at"].as_i64().expect("archived_at");
165
166 // Idempotent: a repeat keeps the original stamp, the year is not re-dated.
167 let again = send(&app, "POST", &archive, Some(&manager), None).await;
168 assert_eq!(again.status, StatusCode::OK);
169 assert_eq!(
170 again.body["archived_at"].as_i64(),
171 Some(stamp),
172 "re-stamped"
173 );
174
175 // Frozen: edit and delete both refuse with the coded 409.
176 for (method, body) in [
177 ("PATCH", Some(json!({ "name": "renamed" }))),
178 ("DELETE", None),
179 ] {
180 let res = send(&app, method, &uri, Some(&manager), body).await;
181 assert_eq!(
182 res.status,
183 StatusCode::CONFLICT,
184 "{method} on archived term"
185 );
186 assert_eq!(res.body["code"], "term_archived", "{method} code");
187 }
188
189 // The structure around a past dönem is *not* frozen by it any more: a şube
190 // is written against the year, and the catalog against nothing, so both go
191 // through — the refusal the old shape answered here lives on the year now
192 // (`regress_classes` drives it).
193 let new_course = send(
194 &app,
195 "POST",
196 "/courses",
197 Some(&manager),
198 Some(json!({ "title": "algebra" })),
199 )
200 .await;
201 assert_eq!(
202 new_course.status,
203 StatusCode::CREATED,
204 "the catalog has no dönem to be frozen by: {}",
205 new_course.body
206 );
207 let new_class = send(
208 &app,
209 "POST",
210 "/classes",
211 Some(&manager),
212 Some(json!({ "name": "9-A", "year": year })),
213 )
214 .await;
215 assert_eq!(
216 new_class.status,
217 StatusCode::CREATED,
218 "a şube is frozen by its academic year, never by a dönem: {}",
219 new_class.body
220 );
221
222 // Reads keep working and carry the stamp, single and listed.
223 let one = send(&app, "GET", &uri, Some(&student), None).await;
224 assert_eq!(one.status, StatusCode::OK);
225 assert_eq!(one.body["archived_at"].as_i64(), Some(stamp));
226 let listed = send(&app, "GET", "/terms", Some(&student), None).await;
227 assert_eq!(listed.status, StatusCode::OK);
228 let row = listed.body["items"]
229 .as_array()
230 .expect("items")
231 .iter()
232 .find(|row| row["id"] == id.as_str())
233 .expect("the archived term is still listed");
234 assert_eq!(row["archived_at"].as_i64(), Some(stamp));
235
236 // Re-opening thaws it, and is idempotent too.
237 let unarchive = format!("/terms/{id}/unarchive");
238 let reopened = send(&app, "POST", &unarchive, Some(&manager), None).await;
239 assert_eq!(reopened.status, StatusCode::OK);
240 assert!(reopened.body["archived_at"].is_null(), "reopened");
241 let twice = send(&app, "POST", &unarchive, Some(&manager), None).await;
242 assert_eq!(twice.status, StatusCode::OK);
243 assert!(twice.body["archived_at"].is_null());
244 let patched = send(
245 &app,
246 "PATCH",
247 &uri,
248 Some(&manager),
249 Some(json!({ "name": "renamed" })),
250 )
251 .await;
252 assert_eq!(patched.status, StatusCode::OK, "open again, edits land");
253
254 // An id nobody minted is a 404 on both flips, not a 409.
255 for route in ["/terms/nope/archive", "/terms/nope/unarchive"] {
256 let res = send(&app, "POST", route, Some(&manager), None).await;
257 assert_eq!(res.status, StatusCode::NOT_FOUND, "{route}");
258 }
259}
260
261/// A term row with no `archived_at` (NULL = open) must decode and stay
262/// archivable — the row a pre-port database arrives with is not special.
263#[tokio::test]
264async fn a_pre_migration_term_row_still_decodes_as_open() {
265 let (app, db) = app_and_db().await;
266 let manager = login_as(&app, &db, "archive_legacy_manager", "manager").await;
267
268 let year = create_year(&app, &manager, "2026-2027").await;
269 let legacy = hezarfen_backend::domain::term::TermId::generate();
270 // The row a pre-`year` database arrives with: its year came from the
271 // backfill (`migrations/school/20260916000001_k12_remodel.sql`), which is
272 // why `year` is NOT NULL and this insert names one.
273 sqlx::query(
274 "INSERT INTO term (id, name, year, starts_at, ends_at) VALUES ($1, 'old', $2, 100, 200)",
275 )
276 .bind(legacy)
277 .bind(uuid::Uuid::parse_str(&year).unwrap())
278 .execute(&db)
279 .await
280 .expect("legacy term query");
281
282 let res = send(
283 &app,
284 "GET",
285 &format!("/terms/{}", legacy.key()),
286 Some(&manager),
287 None,
288 )
289 .await;
290 assert_eq!(res.status, StatusCode::OK, "pre-migration row must decode");
291 assert_eq!(res.body["name"], "old");
292 assert!(res.body["archived_at"].is_null(), "absent = open");
293
294 // And it is still writable, archiving included.
295 let archived = send(
296 &app,
297 "POST",
298 &format!("/terms/{}/archive", legacy.key()),
299 Some(&manager),
300 None,
301 )
302 .await;
303 assert_eq!(archived.status, StatusCode::OK);
304 assert!(archived.body["archived_at"].as_i64().is_some());
305}