forge
Explore
Log in

Don't you dare go Hollow

hezarfen_zeka

Clone
★ 0

0 watching0 forksPython1.9 MiBe01a4faAhmet Kaan Gümüş2 months ago25 commits

source.py835 lines, 30.6 KiBHistoryRawDownload
1"""VERI ERISIM CEPHESI -- hesap modullerinin gorecegi TEK veri yuzeyi.
2
3Bu dosyanin varlik sebebi bir kisitlamadir, bir kolaylik degil.
4
5--- YAPISAL KAPI ---
6`Source` arayuzunde yemek, odeme, diyet, mesaj ve sohbet verisine erisen HICBIR
7yontem YOKTUR. Bu bir yorum ya da bir kural degil, bir YAPI: hesap modulu o
8veriyi isteyemez, cunku cagiracagi fonksiyon yoktur. "Istemeyin" demek yerine
9"soyleyemezsiniz" demek, zamanla sapmayan tek yontemdir.
10
11Bu ayni zamanda backend'in kendi cizgisiyle de ortusur: `AI_API_ALLOWLIST`
12(`constant.rs:650-676`) "yalnizca bir calisma arkadasinin ihtiyaci olan sey"
13diye belgelenir -- kimlik, notlar, dersin notlari, odevler ve ogrencinin kendi
14ilerleme raporlari. Yemek, odeme ve mesajlasma yollari o listede zaten YOKTUR.
15Yani bu cephe backend'in kapisini gevsetmez, ONU KENDI TARAFIMIZDA TEKRARLAR:
16izin listesi degisip bir gun genislerse, ZEKA yine de bu sekiz yontemin disina
17cikamaz.
18
19Testte pinlenir: `tests/test_source.py::test_no_forbidden_data_methods`.
20
21--- IKI UYGULAMA ---
22* `BridgeSource` -- canli kopru uzerinden `api_get` ile okur. Her yontemin
23 kullandigi yol `_TEMPLATES` icinde sabittir ve modul yuklenirken backend'in
24 izin listesiyle karsilastirilir. Izin listesinde olmayan bir yolu cagirmayi
25 DENEYEN kod yoktur.
26* `FileSource` -- JSON fiksturlerden okur. Testlerde ve kopru yokken kullanilir.
27 Imza birebir aynidir, boylece hesap modulu hangisiyle kostugunu bilmez.
28"""
29
30from __future__ import annotations
31
32import json
33import re
34from pathlib import Path
35from typing import Any, Protocol, runtime_checkable
36
37from . import config
38from .protocol import AI_API_ALLOWLIST, ApiErrorCode, ApiRefused, path_allowed
39
40
41# --- arayuz ----------------------------------------------------------------
42
43
44@runtime_checkable
45class Source(Protocol):
46 """Hesap modullerinin gorecegi tek veri yuzeyi.
47
48 Her yontem tek bir okul icin calisir; okul cerceve seviyesinde tasinir ve
49 varsayilani yoktur (`ai/protocol.rs:36-47`).
50
51 `on_behalf_of`: okumanin backend'de KIM olarak kosacagi. Kopruda bu alan
52 zorunludur -- verilmezse okuma sentetik `ai` rolu olarak gider ve o rol
53 hicbir dersi goremez (`ai/server.rs:853-867`), yani sonuc bos ya da 403
54 olur. Bir yetenek gonderiminde (dispatch) cagri sahibinin (`requested_by`)
55 kimligi tasinir; hedefi ogrencinin KENDISI olan okumalar (or. kisisel
56 `/homework`) o ogrenci olarak gider. Ayrinti: `pipeline._fetch_student`.
57 """
58
59 async def profile(
60 self, school: str, user_id: str, *, on_behalf_of: str | None = None
61 ) -> dict | None: ...
62
63 async def marks(
64 self, school: str, user_id: str, *, on_behalf_of: str | None = None
65 ) -> list[dict]: ...
66
67 async def attendance(
68 self, school: str, user_id: str, *, on_behalf_of: str | None = None
69 ) -> list[dict]: ...
70
71 async def pomodoro(
72 self, school: str, user_id: str, *, on_behalf_of: str | None = None
73 ) -> list[dict]: ...
74
75 async def homework_report(
76 self, school: str, user_id: str, *, on_behalf_of: str | None = None
77 ) -> dict | None: ...
78
79 async def homework_list(
80 self, school: str, on_behalf_of: str | None = None
81 ) -> list[dict]: ...
82
83 async def notes(self, school: str, on_behalf_of: str) -> list[dict]: ...
84
85 async def course_notes(
86 self,
87 school: str,
88 course_id: str | None = None,
89 *,
90 on_behalf_of: str | None = None,
91 ) -> list[dict]: ...
92
93
94#: Cephede ASLA bulunmamasi gereken veri alanlari. Koruma testi bu parcalari
95#: `Source` uyelerinin adlarinda arar; biri eklenirse test kirilir.
96FORBIDDEN_DATA_TERMS: tuple[str, ...] = (
97 "meal", # yemek menusu / rezervasyon / yoklama
98 "menu",
99 "dish",
100 "payment", # odeme, borc, defter
101 "invoice",
102 "ledger",
103 "diet", # diyet profili
104 "dietary",
105 "message", # birebir mesajlasma
106 "chat", # sohbet gecmisi
107 "conversation",
108)
109
110#: Cephenin tam yuzeyi. Buraya bir ad eklemek bilincli bir karardir.
111SOURCE_METHODS: tuple[str, ...] = (
112 "profile",
113 "marks",
114 "attendance",
115 "pomodoro",
116 "homework_report",
117 "homework_list",
118 "notes",
119 "course_notes",
120)
121
122
123# --- yol defteri -----------------------------------------------------------
124# Her yontemin karsilik geldigi IZIN LISTESI SABLONU. Somut yol degil, sablon:
125# somut yol kayit kimligi tasir (`ai/api.rs:24-28`).
126
127_TEMPLATES: dict[str, str] = {
128 "profile": "/users/{id}/profile",
129 "marks": "/marks/{user}",
130 "attendance": "/attendance/{user}",
131 "pomodoro": "/pomodoro/{user}",
132 "homework_report": "/homework/report/{user}",
133 "homework_list": "/homework",
134 "notes": "/notes",
135 "course_notes": "/course-notes",
136}
137
138# Modul yuklenirken denetlenir: bu defterdeki her sablon backend'in izin
139# listesinde OLMAK ZORUNDA. Izin listesi daralirsa servis import aninda
140# patlar -- calisma zamaninda sessizce `path_not_allowed` toplamaktansa.
141for _name, _template in _TEMPLATES.items():
142 if _template not in AI_API_ALLOWLIST:
143 raise RuntimeError(
144 f"source.{_name} '{_template}' yolunu kullaniyor ama bu yol backend'in "
145 "AI_API_ALLOWLIST listesinde yok (constant.rs:656-676)"
146 )
147if set(_TEMPLATES) != set(SOURCE_METHODS):
148 raise RuntimeError("yol defteri ile cephe yuzeyi ayristi")
149
150
151#: Bir okumanin "kimligi yetmedi" reddi. HTTP 401/403 -- yani istek ROUTER'a
152#: ulasti ve yetki kapisinda durdu -- bu koda duser. `http_error`'dan ayri
153#: tutulur, cunku cagri sahibi ikisini AYIRT ETMEK ZORUNDADIR: "istek sahibi
154#: bunu okuyamiyor" bir yetki sonucudur, "servis bozuldu" degil.
155NOT_PERMITTED = "not_permitted"
156
157
158class SourceError(Exception):
159 """Veri okunamadi. `code` makine okunabilirdir.
160
161 `path` ve `status` yalniz bir HTTP reddinde dolar; cagri sahibi cevaba
162 "hangi yol, hangi kod" diye yazabilsin diye tasinirlar. Bir bicim hatasi
163 (`unexpected_shape`) ya da fikstur hatasinda bos/0 kalirlar.
164 """
165
166 def __init__(
167 self, code: str, message: str, *, path: str = "", status: int = 0
168 ) -> None:
169 super().__init__(message)
170 self.code = code
171 self.path = path
172 self.status = status
173
174
175def _require_id(value: Any, name: str) -> str:
176 if not isinstance(value, str) or not value.strip():
177 raise SourceError(ApiErrorCode.MALFORMED, f"'{name}' bos olmayan bir metin olmali")
178 return value.strip()
179
180
181# --- govde cikarimi --------------------------------------------------------
182#
183# BURADA GENEL BIR NORMALIZE FONKSIYONU YOKTUR, KASITLI OLARAK.
184#
185# Onceki surumde tek bir `_as_list()` vardi: duz listeyi ve `{"items": ...}`
186# zarfini acar, BASKA HER SEY ICIN BOS LISTE donerdi. Bu sessiz bir hataydi ve
187# gercekten isliyordu: backend'in `/marks/{user}` ve `/attendance/{user}` uclari
188# `items` DEGIL `courses` tasiyan rapor nesneleri dondurur, dolayisiyla kopru
189# modunda o iki yontem HER ZAMAN bos liste donuyordu. Hata mesaji yoktu, gunluk
190# satiri yoktu; not ve devam hesabinin tamami sessizce bosaliyordu. Fikstur modu
191# etkilenmedigi icin testler de yakalamiyordu.
192#
193# Bu yuzden artik HER yontem kendi ucunun gercek bicimini bilir ve bekledigi
194# anahtari adiyla ister. Beklenmeyen bicim SESSIZ BOS degil, `warn` gunlugu +
195# ayirt edilebilir `SourceError("unexpected_shape")` uretir.
196
197
198def _row_dicts(rows: list) -> list[dict]:
199 return [row for row in rows if isinstance(row, dict)]
200
201
202def _extract_rows(
203 body: Any,
204 key: str,
205 *,
206 method: str,
207 path: str,
208 reference: str,
209) -> list[dict]:
210 """Bir uctan gelen govdeden `key` altindaki satir listesini cikar.
211
212 `body is None` yalnizca 404 demektir (`_get` onu oraya cevirir): router
213 calisti ve "boyle bir sey yok" dedi. Bu bir bicim sorunu degildir, bos
214 sonuctur.
215
216 Baska her sapma gorunur olur:
217 * `key` yoksa -> `warn` + `SourceError("unexpected_shape")`,
218 * govde duz liste ise -> kabul edilir ama `warn` yazilir (belgelenen bicim
219 zarftir; duz liste gelmesi backend'in degistigini gosterir).
220 """
221 if body is None:
222 return []
223 if isinstance(body, dict):
224 rows = body.get(key)
225 if isinstance(rows, list):
226 return _row_dicts(rows)
227 config.log(
228 "warn",
229 f"source.{method}: {path} govdesinde beklenen '{key}' listesi yok "
230 f"(gelen anahtarlar: {sorted(body)[:8]}); beklenen bicim {reference}",
231 )
232 raise SourceError(
233 "unexpected_shape",
234 f"{path} -> '{key}' listesi yok; beklenen bicim {reference}",
235 )
236 if isinstance(body, list):
237 config.log(
238 "warn",
239 f"source.{method}: {path} duz liste dondurdu ama belgelenen bicim "
240 f"{reference}; backend sapmis olabilir, liste yine de kullaniliyor",
241 )
242 return _row_dicts(body)
243 config.log(
244 "warn",
245 f"source.{method}: {path} ne nesne ne liste dondurdu ({type(body).__name__}); "
246 f"beklenen bicim {reference}",
247 )
248 raise SourceError(
249 "unexpected_shape",
250 f"{path} -> {type(body).__name__} dondu; beklenen bicim {reference}",
251 )
252
253
254def _extract_object(
255 body: Any,
256 *,
257 method: str,
258 path: str,
259 reference: str,
260 require: tuple[str, ...] = (),
261) -> dict | None:
262 """Tek bir nesne dondurun uclar icin. 404 -> `None`.
263
264 `require` verilirse o anahtarlarin hepsi bulunmak zorundadir; biri yoksa
265 sessizce yarim bir sozluk dondurmek yerine `warn` + `unexpected_shape`.
266 """
267 if body is None:
268 return None
269 if not isinstance(body, dict):
270 config.log(
271 "warn",
272 f"source.{method}: {path} nesne yerine {type(body).__name__} dondurdu; "
273 f"beklenen bicim {reference}",
274 )
275 raise SourceError(
276 "unexpected_shape",
277 f"{path} -> {type(body).__name__} dondu; beklenen bicim {reference}",
278 )
279 missing = [name for name in require if name not in body]
280 if missing:
281 config.log(
282 "warn",
283 f"source.{method}: {path} govdesinde {missing} alan(lar)i yok "
284 f"(gelen anahtarlar: {sorted(body)[:8]}); beklenen bicim {reference}",
285 )
286 raise SourceError(
287 "unexpected_shape",
288 f"{path} -> {missing} alan(lar)i yok; beklenen bicim {reference}",
289 )
290 return body
291
292
293# --- kopru uygulamasi ------------------------------------------------------
294
295
296class BridgeSource:
297 """`Source`'un canli uygulamasi: her okuma bir `ApiRequest` akisidir.
298
299 `client` yalnizca `api_get(school, path, query=None, on_behalf_of=None)`
300 imzasini saglamak zorundadir; testte sahtesi konur.
301 """
302
303 def __init__(self, client: Any) -> None:
304 self._client = client
305
306 async def _get(
307 self,
308 method_name: str,
309 school: str,
310 path: str,
311 query: str | None = None,
312 on_behalf_of: str | None = None,
313 ) -> Any:
314 school = _require_id(school, "school")
315 # Ikinci kemer: yol, defterden turetilse bile tele cikmadan once
316 # izin listesine karsi denetlenir.
317 if not path_allowed(path):
318 raise SourceError(
319 ApiErrorCode.PATH_NOT_ALLOWED,
320 f"source.{method_name} izin listesi disinda bir yol uretti: {path!r}",
321 )
322 try:
323 response = await self._client.api_get(
324 school, path, query=query, on_behalf_of=on_behalf_of
325 )
326 except ApiRefused as exc:
327 raise SourceError(exc.code, str(exc)) from exc
328 if response.status == 404:
329 # Router calisti ve "yok" dedi. Bu bir tasima hatasi degil
330 # (`ai/protocol.rs:196-198`); bos sonuc olarak gecer.
331 return None
332 if response.status in (401, 403):
333 # Router calisti ve yetki kapisi durdurdu. Bu `http_error` DEGILDIR:
334 # istek sahibinin kimligi bu okuma icin yetmiyor. Kod ve durum
335 # tasinir ki cagri sahibi cevaba "hangi yol, hangi kod" yazabilsin.
336 raise SourceError(
337 NOT_PERMITTED,
338 f"{path} -> HTTP {response.status}",
339 path=path,
340 status=response.status,
341 )
342 if not response.ok:
343 raise SourceError(
344 "http_error",
345 f"{path} -> HTTP {response.status}",
346 path=path,
347 status=response.status,
348 )
349 return response.body
350
351 async def profile(
352 self, school: str, user_id: str, *, on_behalf_of: str | None = None
353 ) -> dict | None:
354 """Izin listesi yolu: `/users/{id}/profile` (`constant.rs:659`).
355
356 YANIT BICIMI -- `ProfileResponse`, DUZ NESNE (`web/users.rs:707`,
357 handler `web/users.rs:1112` -> `Json<ProfileResponse>`):
358
359 { id, username, display_name, ..., stats: {...} }
360
361 Zarf YOKTUR. Nesne oldugu gibi dondurulur; `id` alani zorunlu tutulur
362 ki bicim degisirse sessizce yarim bir sozluk gecmesin.
363
364 404 -> `None` (kullanici yok).
365 """
366 user_id = _require_id(user_id, "user_id")
367 path = f"/users/{user_id}/profile"
368 body = await self._get("profile", school, path, on_behalf_of=on_behalf_of)
369 return _extract_object(
370 body,
371 method="profile",
372 path=path,
373 reference="ProfileResponse duz nesnesi (web/users.rs:707)",
374 require=("id",),
375 )
376
377 async def marks(
378 self, school: str, user_id: str, *, on_behalf_of: str | None = None
379 ) -> list[dict]:
380 """Izin listesi yolu: `/marks/{user}` (`constant.rs:670`).
381
382 YANIT BICIMI -- `MarksReport`, RAPOR NESNESI (`web/marks.rs:65`,
383 handler `Json<MarksReport>`):
384
385 { user, courses: [CourseMarks], overall_average, overall_grade }
386
387 DIKKAT: burada `items` YOKTUR, `courses` vardir. Sayfalama zarfi degil,
388 rapor nesnesidir.
389
390 DONEN SEY: `courses` listesi -- her ogesi bir `CourseMarks`
391 (`web/marks.rs:50`):
392
393 { course: CourseResponse, results: [MarkEntry],
394 average, average_grade }
395
396 Yani ders blogu listesi; tek tek sinav notlari her blogun `results`
397 alanindadir.
398
399 TASINMAYAN: `overall_average` ve `overall_grade`. Arayuz `list[dict]`
400 donduruyor, bu yuzden rapor duzeyindeki bu iki alan disarida kalir --
401 ikisi de `courses` uzerinden yeniden hesaplanabilir (duz ortalama).
402 """
403 user_id = _require_id(user_id, "user_id")
404 path = f"/marks/{user_id}"
405 body = await self._get("marks", school, path, on_behalf_of=on_behalf_of)
406 return _extract_rows(
407 body,
408 "courses",
409 method="marks",
410 path=path,
411 reference="MarksReport{user, courses, overall_average, overall_grade} "
412 "(web/marks.rs:65)",
413 )
414
415 async def attendance(
416 self, school: str, user_id: str, *, on_behalf_of: str | None = None
417 ) -> list[dict]:
418 """Izin listesi yolu: `/attendance/{user}` (`constant.rs:672`).
419
420 YANIT BICIMI -- `AttendanceReport`, RAPOR NESNESI
421 (`web/attendance.rs:84`, handler `Json<AttendanceReport>`):
422
423 { user,
424 events: StatusCounts,
425 sessions: StatusCounts,
426 courses: [CourseAttendance] }
427
428 DIKKAT: burada da `items` YOKTUR, `courses` vardir.
429
430 DONEN SEY: `courses` listesi -- her ogesi bir `CourseAttendance`
431 (`web/attendance.rs:76`):
432
433 { course: CourseResponse, counts: StatusCounts }
434
435 --- HESAP TARAFINA UYARI: BU UC SAYAC DONDURUR, SATIR DEGIL ---
436 `StatusCounts` (`web/attendance.rs:31`) sudur:
437
438 { present, absent, late, excused, custom: {...}, total, rate }
439
440 Yani ders basina TOPLAM sayimlardir. Tek tek yoklama SATIRLARI ve
441 onlarin TARIHLERI bu uctan GELMEZ. Dolayisiyla:
442
443 * "hangi gun", "hafta ici mi", "haftanin gunu deseni", "son 30 gunde
444 kac devamsizlik" gibi ZAMAN EKSENLI hicbir olcu bu veriyle
445 hesaplanamaz;
446 * hesaplanabilen sey ders basina oran ve kohort karsilastirmasidir.
447
448 `rate` alani backend'de `(present + late) / (present + absent + late)`
449 diye hesaplanir (`web/attendance.rs:66-70`); `excused` ve okulun kendi
450 ekledigi statuler paydaya GIRMEZ, yalnizca `total`'a girer.
451
452 TASINMAYAN: rapor duzeyindeki `events` ve `sessions` toplam sayaclari.
453 Arayuz `list[dict]` donduruyor ve bu iki alan ders blogu degil; ders
454 bloklari uzerinden `sessions` toplami yeniden toplanabilir, `events`
455 (etkinlik yoklamasi) ise ders verisi olmadigi icin bu cephenin disinda
456 kalir.
457 """
458 user_id = _require_id(user_id, "user_id")
459 path = f"/attendance/{user_id}"
460 body = await self._get("attendance", school, path, on_behalf_of=on_behalf_of)
461 return _extract_rows(
462 body,
463 "courses",
464 method="attendance",
465 path=path,
466 reference="AttendanceReport{user, events, sessions, courses} "
467 "(web/attendance.rs:84)",
468 )
469
470 async def pomodoro(
471 self, school: str, user_id: str, *, on_behalf_of: str | None = None
472 ) -> list[dict]:
473 """Izin listesi yolu: `/pomodoro/{user}` (`constant.rs:674`).
474
475 YANIT BICIMI -- `PomodoroLog`, SAYFA ZARFI + EK ALAN
476 (`web/pomodoro.rs:78`, handler `web/pomodoro.rs:225` ->
477 `Json<PomodoroLog>`):
478
479 { items: [PomodoroResponse], total, limit, offset, total_focus_ms }
480
481 Standart `Page<T>` DEGILDIR: uzerine bir de `total_focus_ms` ekler.
482 Anahtar yine de `items`tir, bu dogrulanarak istenir.
483
484 DONEN SEY: `items` listesi -- her ogesi bir `PomodoroResponse`
485 (`web/pomodoro.rs:40`):
486
487 { id, user, started_at, finished_at, duration_ms, counted }
488
489 `started_at` / `finished_at` UTC unix-MILISANIYEDIR (saniye degil).
490 `counted`, seansin omur boyu sayaclara girip girmedigidir ve devam eden
491 seansta `null`'dur.
492
493 TASINMAYAN: `total_focus_ms`. Arayuz `list[dict]` donduruyor; ayni sayi
494 `items` uzerindeki `duration_ms` toplamindan elde edilir -- ancak
495 dikkat, backend'inki SAYFALANMAMIS butun gunlugun toplamidir, satirlar
496 ise yalnizca bu sayfadir.
497 """
498 user_id = _require_id(user_id, "user_id")
499 path = f"/pomodoro/{user_id}"
500 body = await self._get("pomodoro", school, path, on_behalf_of=on_behalf_of)
501 return _extract_rows(
502 body,
503 "items",
504 method="pomodoro",
505 path=path,
506 reference="PomodoroLog{items, total, limit, offset, total_focus_ms} "
507 "(web/pomodoro.rs:78)",
508 )
509
510 async def homework_report(
511 self, school: str, user_id: str, *, on_behalf_of: str | None = None
512 ) -> dict | None:
513 """Izin listesi yolu: `/homework/report/{user}` (`constant.rs:668`).
514
515 YANIT BICIMI -- `Page<HomeworkReportEntry>`, SAYFA ZARFI
516 (`web/homework.rs:1166` girdi tipi, handler `web/homework.rs:1206` ->
517 `Json<Page<HomeworkReportEntry>>`, zarf `web/page.rs:129`):
518
519 { items: [HomeworkReportEntry], total, limit, offset }
520
521 Her `HomeworkReportEntry` (`web/homework.rs:1166`):
522
523 { course, homework, title, subject, due_at,
524 submitted, late, missing, result }
525
526 `due_at` UTC unix-MILISANIYEDIR. `missing`, "teslim yok VE tarih
527 gecmis" demektir ve ogretmenin elle isaretledigi durumdan bagimsizdir.
528
529 DONEN SEY: ZARFIN KENDISI (arayuz `dict | None` diyor), satirlar degil.
530 `items` anahtarinin varligi dogrulanir; yoksa sessizce yarim zarf
531 gecmez, `unexpected_shape` firlar.
532
533 404 -> `None` (kullanici yok).
534 """
535 user_id = _require_id(user_id, "user_id")
536 path = f"/homework/report/{user_id}"
537 body = await self._get("homework_report", school, path, on_behalf_of=on_behalf_of)
538 return _extract_object(
539 body,
540 method="homework_report",
541 path=path,
542 reference="Page<HomeworkReportEntry>{items, total, limit, offset} "
543 "(web/homework.rs:1206)",
544 require=("items",),
545 )
546
547 async def homework_list(
548 self, school: str, on_behalf_of: str | None = None
549 ) -> list[dict]:
550 """Izin listesi yolu: `/homework` (`constant.rs:664`).
551
552 YANIT BICIMI -- `Page<HomeworkResponse>`, SAYFA ZARFI (handler
553 `web/homework.rs:160` -> `Json<Page<HomeworkResponse>>`):
554
555 { items: [HomeworkResponse], total, limit, offset }
556
557 DONEN SEY: `items` listesi.
558
559 `on_behalf_of` verilmezse okuma servisin kendisi -- sentetik `ai` rolu --
560 olarak kosar; o rol hicbir dersi goremedigi icin sonuc pratikte bostur
561 (`ai/server.rs:694-711`). Yani bu alan burada opsiyonel gorunse de
562 gercek kullanimda doldurulur.
563 """
564 body = await self._get("homework_list", school, "/homework", on_behalf_of=on_behalf_of)
565 return _extract_rows(
566 body,
567 "items",
568 method="homework_list",
569 path="/homework",
570 reference="Page<HomeworkResponse>{items, total, limit, offset} "
571 "(web/homework.rs:160)",
572 )
573
574 async def notes(self, school: str, on_behalf_of: str) -> list[dict]:
575 """Izin listesi yolu: `/notes` (`constant.rs:660`).
576
577 YANIT BICIMI -- `Page<NoteResponse>`, SAYFA ZARFI
578 (`web/notes.rs:106` -> `body = Page<NoteResponse>`):
579
580 { items: [NoteResponse], total, limit, offset }
581
582 DONEN SEY: `items` listesi.
583
584 Kisisel notlar sahibine bagli oldugu icin `on_behalf_of` ZORUNLUDUR.
585 """
586 on_behalf_of = _require_id(on_behalf_of, "on_behalf_of")
587 body = await self._get("notes", school, "/notes", on_behalf_of=on_behalf_of)
588 return _extract_rows(
589 body,
590 "items",
591 method="notes",
592 path="/notes",
593 reference="Page<NoteResponse>{items, total, limit, offset} "
594 "(web/notes.rs:106)",
595 )
596
597 async def course_notes(
598 self,
599 school: str,
600 course_id: str | None = None,
601 *,
602 on_behalf_of: str | None = None,
603 ) -> list[dict]:
604 """Izin listesi yolu: `/course-notes` (`constant.rs:661`).
605
606 Backend `GET /course-notes` icin `?course=` ZORUNLU kilar ve yalnizca o
607 dersin notlarini listeler (`lib.rs`, `course-notes` etiket aciklamasi).
608 `course_id` verilmezse listelenecek bir sey yoktur: uydurma bir istek
609 gondermek yerine bos donup uyari yaziyoruz.
610
611 YANIT BICIMI -- `Page<CourseNoteResponse>`, SAYFA ZARFI (handler
612 `web/course_notes.rs:182` -> `Json<Page<CourseNoteResponse>>`):
613
614 { items: [CourseNoteResponse], total, limit, offset }
615
616 DONEN SEY: `items` listesi.
617 """
618 if not course_id:
619 config.log(
620 "warn",
621 "course_notes: ders kimligi verilmedi; backend '?course=' zorunlu "
622 "kildigi icin istek gonderilmedi",
623 )
624 return []
625 course_id = _require_id(course_id, "course_id")
626 body = await self._get(
627 "course_notes",
628 school,
629 "/course-notes",
630 query=f"course={course_id}",
631 on_behalf_of=on_behalf_of,
632 )
633 return _extract_rows(
634 body,
635 "items",
636 method="course_notes",
637 path="/course-notes",
638 reference="Page<CourseNoteResponse>{items, total, limit, offset} "
639 "(web/course_notes.rs:182)",
640 )
641
642
643# --- dosya uygulamasi ------------------------------------------------------
644
645_SAFE_KEY = re.compile(r"[^A-Za-z0-9_.-]")
646
647
648def _safe(value: str) -> str:
649 """Kimligi dosya adina cevirirken yol kacisini imkansiz kil.
650
651 `..` ve `/` gibi parcalar `_` olur; boylece fikstur koku disina cikan bir ad
652 uretilemez.
653 """
654 return _SAFE_KEY.sub("_", value) or "_"
655
656
657class FileSource:
658 """`Source`'un fikstur uygulamasi: JSON dosyalarindan okur.
659
660 Kopru yokken ve testlerde kullanilir. Dizin duzeni:
661
662 <kok>/<okul>/profile/<user_id>.json -> nesne
663 <kok>/<okul>/marks/<user_id>.json -> liste
664 <kok>/<okul>/attendance/<user_id>.json -> liste
665 <kok>/<okul>/pomodoro/<user_id>.json -> liste
666 <kok>/<okul>/homework_report/<user_id>.json -> nesne
667 <kok>/<okul>/homework/<kim>.json -> liste
668 <kok>/<okul>/notes/<kim>.json -> liste
669 <kok>/<okul>/course_notes/<ders>.json -> liste
670
671 `<kim>` yoksa `_service`, `<ders>` yoksa `_all` kullanilir. Olmayan dosya
672 hata degildir: nesne dondurenler `None`, liste dondurenler `[]` verir --
673 kopru tarafinda 404'un karsiligi.
674
675 Govde bicimi kopruyle AYNI normalizasyondan gecer: hem duz liste hem
676 `{items: [...]}` zarfi kabul edilir, boylece gercek bir cevabi dosyaya
677 oldugu gibi kaydedip fikstur yapmak mumkundur.
678 """
679
680 #: Yontem adi -> fikstur alt dizini.
681 DIRECTORIES: dict[str, str] = {
682 "profile": "profile",
683 "marks": "marks",
684 "attendance": "attendance",
685 "pomodoro": "pomodoro",
686 "homework_report": "homework_report",
687 "homework_list": "homework",
688 "notes": "notes",
689 "course_notes": "course_notes",
690 }
691
692 def __init__(self, root: str | Path) -> None:
693 self._root = Path(root)
694
695 def _read(self, school: str, kind: str, key: str) -> Any:
696 school = _require_id(school, "school")
697 path = self._root / _safe(school) / self.DIRECTORIES[kind] / f"{_safe(key)}.json"
698 if not path.is_file():
699 return None
700 try:
701 with path.open("r", encoding="utf-8") as handle:
702 return json.load(handle)
703 except (OSError, ValueError) as exc:
704 raise SourceError("fixture_unreadable", f"{path} okunamadi: {exc}") from exc
705
706 def _rows(self, school: str, kind: str, key: str, envelope_key: str) -> list[dict]:
707 """Fikstur govdesinden satirlari cikar.
708
709 Fikstur iki bicimde yazilabilir:
710 * GERCEK zarf (`{"courses": [...]}` / `{"items": [...]}`) -- gercek bir
711 cevabi dosyaya oldugu gibi kaydetmek icin,
712 * duz liste -- elle yazilan kucuk fiksturler icin.
713
714 Duz liste burada UYARI URETMEZ (kopru tarafinin aksine): fikstur
715 yazilmis bir seydir, telden gelmis degil. Ama yanlis anahtarli bir
716 SOZLUK yine sessizce bos donmez, `unexpected_shape` firlatir -- fikstur
717 modunda da sessiz bos yoktur.
718 """
719 body = self._read(school, kind, key)
720 if body is None:
721 return []
722 if isinstance(body, list):
723 return _row_dicts(body)
724 if isinstance(body, dict):
725 rows = body.get(envelope_key)
726 if isinstance(rows, list):
727 return _row_dicts(rows)
728 config.log(
729 "warn",
730 f"fikstur {school}/{self.DIRECTORIES[kind]}/{key}.json bir sozluk ama "
731 f"'{envelope_key}' listesi tasimiyor (anahtarlar: {sorted(body)[:8]})",
732 )
733 raise SourceError(
734 "unexpected_shape",
735 f"fikstur {kind}/{key}: '{envelope_key}' listesi yok",
736 )
737 config.log(
738 "warn",
739 f"fikstur {school}/{self.DIRECTORIES[kind]}/{key}.json ne liste ne sozluk "
740 f"({type(body).__name__})",
741 )
742 raise SourceError(
743 "unexpected_shape", f"fikstur {kind}/{key}: {type(body).__name__} okundu"
744 )
745
746 async def profile(
747 self, school: str, user_id: str, *, on_behalf_of: str | None = None
748 ) -> dict | None:
749 """Kopru karsiligi: `/users/{id}/profile` -> `ProfileResponse` duz nesnesi."""
750 return _extract_object(
751 self._read(school, "profile", _require_id(user_id, "user_id")),
752 method="profile",
753 path="fixture:profile",
754 reference="ProfileResponse duz nesnesi (web/users.rs:707)",
755 )
756
757 async def marks(
758 self, school: str, user_id: str, *, on_behalf_of: str | None = None
759 ) -> list[dict]:
760 """Kopru karsiligi: `/marks/{user}` -> `MarksReport.courses` listesi."""
761 return self._rows(school, "marks", _require_id(user_id, "user_id"), "courses")
762
763 async def attendance(
764 self, school: str, user_id: str, *, on_behalf_of: str | None = None
765 ) -> list[dict]:
766 """Kopru karsiligi: `/attendance/{user}` -> `AttendanceReport.courses` listesi.
767
768 Kopru surumunde oldugu gibi, her satirdaki `counts` bir SAYAC
769 kumesidir; tek tek yoklama satiri ve tarihi icermez.
770 """
771 return self._rows(
772 school, "attendance", _require_id(user_id, "user_id"), "courses"
773 )
774
775 async def pomodoro(
776 self, school: str, user_id: str, *, on_behalf_of: str | None = None
777 ) -> list[dict]:
778 """Kopru karsiligi: `/pomodoro/{user}` -> `PomodoroLog.items` listesi."""
779 return self._rows(school, "pomodoro", _require_id(user_id, "user_id"), "items")
780
781 async def homework_report(
782 self, school: str, user_id: str, *, on_behalf_of: str | None = None
783 ) -> dict | None:
784 """Kopru karsiligi: `/homework/report/{user}` -> `Page` ZARFININ KENDISI."""
785 return _extract_object(
786 self._read(school, "homework_report", _require_id(user_id, "user_id")),
787 method="homework_report",
788 path="fixture:homework_report",
789 reference="Page<HomeworkReportEntry>{items, total, limit, offset} "
790 "(web/homework.rs:1206)",
791 require=("items",),
792 )
793
794 async def homework_list(
795 self, school: str, on_behalf_of: str | None = None
796 ) -> list[dict]:
797 """Kopru karsiligi: `/homework` -> `Page.items` listesi."""
798 return self._rows(
799 school, "homework_list", on_behalf_of or "_service", "items"
800 )
801
802 async def notes(self, school: str, on_behalf_of: str) -> list[dict]:
803 """Kopru karsiligi: `/notes` -> `Page.items` listesi."""
804 return self._rows(
805 school, "notes", _require_id(on_behalf_of, "on_behalf_of"), "items"
806 )
807
808 async def course_notes(
809 self,
810 school: str,
811 course_id: str | None = None,
812 *,
813 on_behalf_of: str | None = None,
814 ) -> list[dict]:
815 """Kopru karsiligi: `/course-notes?course=...` -> `Page.items` listesi."""
816 return self._rows(school, "course_notes", course_id or "_all", "items")
817
818
819#: Fikstur uygulamasinin ikinci adi; iki isim de ayni sinifi gosterir.
820FixtureSource = FileSource
821
822
823def build(settings: config.Config, client: Any | None = None) -> Source:
824 """Yapilandirmaya gore cepheyi kur.
825
826 `ZEKA_SOURCE=bridge` ise kopru istemcisi ZORUNLUDUR; sessizce fiksture
827 dusmek, uretimde sahte veriyle hesap kosturmak olurdu.
828 """
829 if settings.source_mode == "bridge":
830 if client is None:
831 raise SourceError(
832 "no_client", "ZEKA_SOURCE=bridge ama kopru istemcisi verilmedi"
833 )
834 return BridgeSource(client)
835 return FileSource(settings.fixture_root)