🏫 ZEKA'yı çok okullu yap: kontrol DSN'i, okul başına veritabanı
Browse files at this commit1fd69602a63b5708982d65ffa9fe506648de77bfParent: afe2136- feat
- 🏫 ZEKA'yı çok okullu yap: kontrol DSN'i, okul başına veritabanı
25 changed files +1778 -137
- DEMO-KURULUM.md +1 -1
- README.md +5 -4
- deploy/hezarfen_zeka.env.example +26 -9
- scripts/ci-compose.sh +5 -5
- scripts/ci-konteyner-kanit.sh +25 -1
- scripts/ci-sir-tara.py +1 -1
- scripts/ci-yerel.sh +2 -2
- service/.env.example +23 -11
- service/compose.yaml +10 -4
- service/docs/BACKEND-GEREKSINIMLERI.md +3 -2
- service/src/bridge.py +41 -30
- service/src/capabilities.py +24 -0
- service/src/cli.py +50 -14
- service/src/config.py +29 -5
- service/src/pg_client.py +18 -4
- service/src/scheduler.py +66 -21
- service/src/segment/config.py +36 -8
- service/src/segment/provider.py +3 -3
- service/src/store_factory.py +14 -3
- service/src/tenants.py +557 -0
- service/tests/test_config.py +21 -0
- service/tests/test_scheduler.py +101 -8
- service/tests/test_segment_config.py +104 -0
- service/tests/test_segment_provider.py +1 -1
- service/tests/test_tenants.py +612 -0
DEMO-KURULUM.mdmodified+1 -1
| @@ -104,7 +104,7 @@ Bu kurulmasaydı veri görünür, sistem kullanılamaz olurdu. | |||
| 104 | ## 5. ZEKA servisi | 104 | ## 5. ZEKA servisi |
| 105 | 105 | ||
| 106 | ``` | 106 | ``` |
| 107 | -ZEKA_PG_DSN=postgresql://<kullanici>:<parola>@<host>:5432/hezarfen_control_school_0193000000007000800000000000de70 | 107 | +ZEKA_PG_DSN=postgresql://<kullanici>:<parola>@<host>:5432/hezarfen_control |
| 108 | ``` | 108 | ``` |
| 109 | 109 | ||
| 110 | Üretimde bu kullanıcı **yalnız dokuz `zeka_*` tablosuna yazma, kalan 77 tabloya | 110 | Üretimde bu kullanıcı **yalnız dokuz `zeka_*` tablosuna yazma, kalan 77 tabloya |
README.mdmodified+5 -4
| @@ -16,8 +16,8 @@ Bağlamak için gereken üç şey: | |||
| 16 | 16 | ||
| 17 | ```sh | 17 | ```sh |
| 18 | AI_SHARED_TOKEN=<backend ile aynı sır> | 18 | AI_SHARED_TOKEN=<backend ile aynı sır> |
| 19 | -ZEKA_PG_DSN=postgres://<kullanıcı>:<parola>@<host>:5432/<okul_veritabanı> | 19 | +ZEKA_PG_DSN=postgres://<kullanıcı>:<parola>@<host>:5432/<kontrol_veritabanı> |
| 20 | -DEEPSEEK_API_KEY=<segment hattı için> | 20 | +LLM_API_KEY=<segment hattı için; OpenAI uyumlu her sağlayıcı olur> |
| 21 | ``` | 21 | ``` |
| 22 | 22 | ||
| 23 | ```sh | 23 | ```sh |
| @@ -291,7 +291,8 @@ isabeti: `service/docs/SEGMENT-CIKTI.md`. | |||
| 291 | 291 | ||
| 292 | `.env` gitignore'ludur ve depoya **girmez**. `compose.yaml` yalnızca | 292 | `.env` gitignore'ludur ve depoya **girmez**. `compose.yaml` yalnızca |
| 293 | interpolasyon içerir, literal sır taşımaz. `AI_SHARED_TOKEN`, `ZEKA_PG_DSN` ve | 293 | interpolasyon içerir, literal sır taşımaz. `AI_SHARED_TOKEN`, `ZEKA_PG_DSN` ve |
| 294 | -`DEEPSEEK_API_KEY` `:?` ile **zorunludur**: adressiz ya da anahtarsız bir servis | 294 | +`LLM_API_KEY` `:?` ile **zorunludur**; eski `DEEPSEEK_API_KEY` adı artık |
| 295 | +**reddedilir** (temiz kesim): adressiz ya da anahtarsız bir servis | ||
| 295 | ayağa kalkıp hiçbir şey yazmadan "çalışıyor" görünürdü. Açılışta bir satır hata, | 296 | ayağa kalkıp hiçbir şey yazmadan "çalışıyor" görünürdü. Açılışta bir satır hata, |
| 296 | günler sonra boş bir tablo yerine. | 297 | günler sonra boş bir tablo yerine. |
| 297 | 298 | ||
| @@ -336,7 +337,7 @@ request'ler** beş katmanı `ci.yml`'den alır (aynı kapı iki kez koşmaz). | |||
| 336 | ```bash | 337 | ```bash |
| 337 | mkdir -p ~/hezarfen_zeka | 338 | mkdir -p ~/hezarfen_zeka |
| 338 | cp deploy/hezarfen_zeka.env.example ~/hezarfen_zeka/hezarfen_zeka.env | 339 | cp deploy/hezarfen_zeka.env.example ~/hezarfen_zeka/hezarfen_zeka.env |
| 339 | - # AI_SHARED_TOKEN / ZEKA_PG_DSN / DEEPSEEK_API_KEY zorunlu | 340 | + # AI_SHARED_TOKEN / ZEKA_PG_DSN / LLM_API_KEY zorunlu |
| 340 | chmod 0600 ~/hezarfen_zeka/hezarfen_zeka.env | 341 | chmod 0600 ~/hezarfen_zeka/hezarfen_zeka.env |
| 341 | ``` | 342 | ``` |
| 342 | 343 | ||
deploy/hezarfen_zeka.env.examplemodified+26 -9
| @@ -30,20 +30,37 @@ | |||
| 30 | # kopru bekler). | 30 | # kopru bekler). |
| 31 | AI_SHARED_TOKEN= | 31 | AI_SHARED_TOKEN= |
| 32 | 32 | ||
| 33 | -# ZEKA ciktilarini yazacagi veritabani. OKULUN kendi veritabanidir; ayri bir | 33 | +# KONTROL veritabani. Okul ciktilari BURAYA yazilmaz: her okul KENDI |
| 34 | -# ZEKA veritabani YOKTUR. Adi okulun uuid'sinden turer (`tenant.rs:112`), slug'dan | 34 | +# veritabanina yazar ve adi okulun uuid'sinden turer (backend `tenant.rs:112`): |
| 35 | -# DEGIL: | 35 | +# {kontrol_db}_school_{uuid_tiresiz} |
| 36 | -# hezarfen_control_school_0193000000007000800000000000de70 | 36 | +# Okul slug'i -> veritabani cozumlemesi kontrol satirindan yapilir |
| 37 | -# Parola tasir: dosya 0600, DSN hicbir yere loglanmaz. | 37 | +# (`school` tablosu); DSN'e sabit bir okul yazmak tek-okullu kuruluma donmek |
| 38 | +# olurdu (bkz. src/tenants.py). | ||
| 39 | +# | ||
| 40 | +# Bu degiskenin dolu olmasi Postgres'i secer; bos olmasi eski tek veritabani | ||
| 41 | +# (SurrealDB) moduna duser (bkz. src/store_factory.py). | ||
| 38 | ZEKA_PG_DSN= | 42 | ZEKA_PG_DSN= |
| 43 | +# Parola tasir: dosya 0600, DSN hicbir yere loglanmaz. | ||
| 39 | 44 | ||
| 40 | -# Segment hattinin LLM saglayicisi. Kopru bu anahtari OKUMAZ; yalnizca | 45 | +# Segment hattinin LLM anahtari. Kopru bu anahtari OKUMAZ; yalnizca |
| 41 | -# `src/segment/` okur (oncelik: DEEPSEEK_API_KEY -> LLM_API_KEY -> | 46 | +# `src/segment/` okur. Yine de zorunlu tutuluyor: anahtarsiz bir servis ayaga |
| 42 | -# SEGMENT_API_KEY). Yine de zorunlu tutuluyor: anahtarsiz bir servis ayaga | ||
| 43 | # kalkar, segment hatti kosuldugunda patlardi. Hatayi dagitim anina cekiyoruz. | 47 | # kalkar, segment hatti kosuldugunda patlardi. Hatayi dagitim anina cekiyoruz. |
| 48 | +# | ||
| 49 | +# ADLAR (2026-09-17 temiz kesim -- eski adlar DESTEKLENMEZ, gorulurlerse | ||
| 50 | +# yapilandirma acilista REDDEDILIR): | ||
| 51 | +# LLM_API_KEY anahtar (zorunlu) | ||
| 52 | +# LLM_BASE_URL taban adres (varsayilan https://api.deepseek.com) | ||
| 53 | +# LLM_MODEL_FLASH / LLM_MODEL_PRO / LLM_MODEL_REASONER rol basina model | ||
| 54 | +# LLM_MODEL_ROLE varsayilan rol secimi | ||
| 55 | +# Kaldirilan adlar: DEEPSEEK_API_KEY, SEGMENT_API_KEY, SEGMENT_BASE_URL, | ||
| 56 | +# SEGMENT_MODEL_FLASH/PRO/REASONER, SEGMENT_MODEL_ROLE. | ||
| 57 | +# | ||
| 58 | +# SAGLAYICI: DeepSeek varsayilandir, ZORUNLULUK DEGILDIR. OpenAI uyumlu her | ||
| 59 | +# ag gecidi calisir: LLM_BASE_URL'i gecidinize verin ve model kimliklerini | ||
| 60 | +# LLM_MODEL_* ile o saglayicinin adlariyla degistirin. | ||
| 61 | +LLM_API_KEY= | ||
| 44 | # (Yalnizca kopruyu kosturan bir dagitimda bilincli olarak sahte bir deger | 62 | # (Yalnizca kopruyu kosturan bir dagitimda bilincli olarak sahte bir deger |
| 45 | # verilebilir; segment o zaman hata verir, kopru calisir.) | 63 | # verilebilir; segment o zaman hata verir, kopru calisir.) |
| 46 | -DEEPSEEK_API_KEY= | ||
| 47 | 64 | ||
| 48 | # ============================================================================ | 65 | # ============================================================================ |
| 49 | # KOPRU | 66 | # KOPRU |
scripts/ci-compose.shmodified+5 -5
| @@ -4,7 +4,7 @@ | |||
| 4 | # Uc sey denetlenir ve UCU DE cift yonludur; yalnizca "gecerli mi" diye | 4 | # Uc sey denetlenir ve UCU DE cift yonludur; yalnizca "gecerli mi" diye |
| 5 | # sormak, asil kusurlari kacirir: | 5 | # sormak, asil kusurlari kacirir: |
| 6 | # | 6 | # |
| 7 | -# 1. Zorunlu sirlar gercekten zorunlu mu? (AI_SHARED_TOKEN, DEEPSEEK_API_KEY, | 7 | +# 1. Zorunlu sirlar gercekten zorunlu mu? (AI_SHARED_TOKEN, LLM_API_KEY, |
| 8 | # ZEKA_PG_DSN -- tam liste compose.yaml'da.) | 8 | # ZEKA_PG_DSN -- tam liste compose.yaml'da.) |
| 9 | # `${VAR:?}` yerine `${VAR:-}` yazilirsa compose yine gecerli olur ama | 9 | # `${VAR:?}` yerine `${VAR:-}` yazilirsa compose yine gecerli olur ama |
| 10 | # servis bos bir token'la ayaga kalkar ve backend'e kaydolamaz. Bu | 10 | # servis bos bir token'la ayaga kalkar ve backend'e kaydolamaz. Bu |
| @@ -40,19 +40,19 @@ kal() { echo " [HATA] $1"; HATA=1; } | |||
| 40 | 40 | ||
| 41 | # --- 1a. zorunlu env EKSIKKEN patlamali ----------------------------------- | 41 | # --- 1a. zorunlu env EKSIKKEN patlamali ----------------------------------- |
| 42 | # ZORUNLU SIRLAR LISTESI compose.yaml'DAN OKUNUR -- su an uctur | 42 | # ZORUNLU SIRLAR LISTESI compose.yaml'DAN OKUNUR -- su an uctur |
| 43 | -# (AI_SHARED_TOKEN, DEEPSEEK_API_KEY, ZEKA_PG_DSN). Ucuncusu eklendiginde bu | 43 | +# (AI_SHARED_TOKEN, LLM_API_KEY, ZEKA_PG_DSN). Ucuncusu eklendiginde bu |
| 44 | # betik ve `ci.yml`'in konteyner katmani iki sirla kalmis, ikisi de "sirlar | 44 | # betik ve `ci.yml`'in konteyner katmani iki sirla kalmis, ikisi de "sirlar |
| 45 | # verilse bile patliyor" diyerek KIRMIZI kalmisti. Sir eklerseniz bu listeyi | 45 | # verilse bile patliyor" diyerek KIRMIZI kalmisti. Sir eklerseniz bu listeyi |
| 46 | # ve ci.yml/main.yml adimini BIRLIKTE guncelleyin. | 46 | # ve ci.yml/main.yml adimini BIRLIKTE guncelleyin. |
| 47 | -if env -u AI_SHARED_TOKEN -u DEEPSEEK_API_KEY -u ZEKA_PG_DSN \ | 47 | +if env -u AI_SHARED_TOKEN -u LLM_API_KEY -u ZEKA_PG_DSN \ |
| 48 | "${COMPOSE[@]}" config >/dev/null 2>&1; then | 48 | "${COMPOSE[@]}" config >/dev/null 2>&1; then |
| 49 | kal "zorunlu sirlar olmadan gecti -- \${VAR:?} yerine \${VAR:-} yazilmis olabilir" | 49 | kal "zorunlu sirlar olmadan gecti -- \${VAR:?} yerine \${VAR:-} yazilmis olabilir" |
| 50 | else | 50 | else |
| 51 | - gec "zorunlu sirlar olmadan REDDEDILDI (AI_SHARED_TOKEN / DEEPSEEK_API_KEY / ZEKA_PG_DSN)" | 51 | + gec "zorunlu sirlar olmadan REDDEDILDI (AI_SHARED_TOKEN / LLM_API_KEY / ZEKA_PG_DSN)" |
| 52 | fi | 52 | fi |
| 53 | 53 | ||
| 54 | # --- 1b. zorunlu env VARKEN gecerli olmali -------------------------------- | 54 | # --- 1b. zorunlu env VARKEN gecerli olmali -------------------------------- |
| 55 | -ZORUNLU_ENV=(AI_SHARED_TOKEN=ci-sahte DEEPSEEK_API_KEY=ci-sahte ZEKA_PG_DSN=postgres://ci:ci@127.0.0.1:5432/ci) | 55 | +ZORUNLU_ENV=(AI_SHARED_TOKEN=ci-sahte LLM_API_KEY=ci-sahte ZEKA_PG_DSN=postgres://ci:ci@127.0.0.1:5432/ci) |
| 56 | CIKTI="$(env "${ZORUNLU_ENV[@]}" "${COMPOSE[@]}" config 2>&1)" | 56 | CIKTI="$(env "${ZORUNLU_ENV[@]}" "${COMPOSE[@]}" config 2>&1)" |
| 57 | if [ $? -ne 0 ]; then | 57 | if [ $? -ne 0 ]; then |
| 58 | kal "zorunlu sirlar verildiginde bile config basarisiz:" | 58 | kal "zorunlu sirlar verildiginde bile config basarisiz:" |
scripts/ci-konteyner-kanit.shmodified+25 -1
| @@ -144,11 +144,20 @@ else | |||
| 144 | fi | 144 | fi |
| 145 | 145 | ||
| 146 | # Kopru surecinin KENDI icinden depo yolunu bir kez daha aciyoruz: "env'i | 146 | # Kopru surecinin KENDI icinden depo yolunu bir kez daha aciyoruz: "env'i |
| 147 | -# gectim" degil, "O env ile depo ACILIYOR" kaniti budur (ayni `open_store`). | 147 | +# gectim" degil, "O env ile depo ACILIYOR" kaniti budur. |
| 148 | +# | ||
| 149 | +# IKINCI YARISI (cok okullu sekil): `open_store` tek veritabani yoludur; | ||
| 150 | +# URETIMDE kosan yol `tenants.open_directory`dir. Kanit onu da acar ve | ||
| 151 | +# SUNU olcer: kanit Postgres'i BOS bir veritabanidir (ne `school` tablosu ne | ||
| 152 | +# okul satiri var) -- servis yine de acilir. Okul LISTESI bu yuzden burada | ||
| 153 | +# hata verebilir; verirse bu bir cokme degil, tik basina bir uyari olur | ||
| 154 | +# (`scheduler._listing`). Beklenen tek sey acilisin TAMAMLANMASIDIR. | ||
| 148 | DEPO_CIKTI="$(MSYS_NO_PATHCONV=1 "$MOTOR" exec -i "$KAP" python - 2>&1 <<'PY' | 155 | DEPO_CIKTI="$(MSYS_NO_PATHCONV=1 "$MOTOR" exec -i "$KAP" python - 2>&1 <<'PY' |
| 149 | import asyncio | 156 | import asyncio |
| 150 | 157 | ||
| 158 | +from src import config | ||
| 151 | from src.store_factory import open_store | 159 | from src.store_factory import open_store |
| 160 | +from src.tenants import TenantError, open_directory | ||
| 152 | 161 | ||
| 153 | 162 | ||
| 154 | async def main() -> None: | 163 | async def main() -> None: |
| @@ -156,6 +165,17 @@ async def main() -> None: | |||
| 156 | await db.close() | 165 | await db.close() |
| 157 | print("DEPO_ACILDI") | 166 | print("DEPO_ACILDI") |
| 158 | 167 | ||
| 168 | + directory = await open_directory(config.load(require_token=False)) | ||
| 169 | + try: | ||
| 170 | + print("OKUL_DIZINI_ACILDI") | ||
| 171 | + try: | ||
| 172 | + aktif = await directory.active_schools() | ||
| 173 | + print("OKUL_SAYISI=%d" % len(aktif)) | ||
| 174 | + except TenantError as exc: | ||
| 175 | + print("OKUL_LISTESI_YOK (beklenen: kanit DB'si bos) %s" % exc) | ||
| 176 | + finally: | ||
| 177 | + await directory.close() | ||
| 178 | + | ||
| 159 | 179 | ||
| 160 | asyncio.run(main()) | 180 | asyncio.run(main()) |
| 161 | PY | 181 | PY |
| @@ -164,6 +184,10 @@ case "$DEPO_CIKTI" in | |||
| 164 | *DEPO_ACILDI*) gec "zorunlu env ile depo GERCEKTEN aciliyor (open_store -> kapat)" ;; | 184 | *DEPO_ACILDI*) gec "zorunlu env ile depo GERCEKTEN aciliyor (open_store -> kapat)" ;; |
| 165 | *) kal "depo acilamadi: $(echo "$DEPO_CIKTI" | tail -2 | tr '\n' ' ')" ;; | 185 | *) kal "depo acilamadi: $(echo "$DEPO_CIKTI" | tail -2 | tr '\n' ' ')" ;; |
| 166 | esac | 186 | esac |
| 187 | +case "$DEPO_CIKTI" in | ||
| 188 | + *OKUL_DIZINI_ACILDI*) gec "cok okullu acilis tamamlaniyor (kontrol DB'si BOSKEN bile)" ;; | ||
| 189 | + *) kal "okul dizini acilamadi: $(echo "$DEPO_CIKTI" | tail -2 | tr '\n' ' ')" ;; | ||
| 190 | +esac | ||
| 167 | 191 | ||
| 168 | # --- 2. geri cekilme ustel mi? -------------------------------------------- | 192 | # --- 2. geri cekilme ustel mi? -------------------------------------------- |
| 169 | # Log satiri: "[zeka] 3.5s sonra yeniden denenecek" | 193 | # Log satiri: "[zeka] 3.5s sonra yeniden denenecek" |
scripts/ci-sir-tara.pymodified+1 -1
| @@ -248,7 +248,7 @@ def main() -> int: | |||
| 248 | compose = KOK / "service" / "compose.yaml" | 248 | compose = KOK / "service" / "compose.yaml" |
| 249 | if compose.exists(): | 249 | if compose.exists(): |
| 250 | icerik = io.open(compose, encoding="utf-8").read() | 250 | icerik = io.open(compose, encoding="utf-8").read() |
| 251 | - for degisken in ("AI_SHARED_TOKEN", "DEEPSEEK_API_KEY", "ZEKA_PG_DSN"): | 251 | + for degisken in ("AI_SHARED_TOKEN", "LLM_API_KEY", "ZEKA_PG_DSN"): |
| 252 | satirlar = [s for s in icerik.splitlines() if s.strip().startswith(degisken + ":")] | 252 | satirlar = [s for s in icerik.splitlines() if s.strip().startswith(degisken + ":")] |
| 253 | if not satirlar: | 253 | if not satirlar: |
| 254 | uyarilar.append(f"compose.yaml icinde {degisken} tanimli degil") | 254 | uyarilar.append(f"compose.yaml icinde {degisken} tanimli degil") |
scripts/ci-yerel.shmodified+2 -2
| @@ -103,8 +103,8 @@ if [ "$KONTEYNER" -eq 1 ]; then | |||
| 103 | if [ -n "$MOTOR" ]; then | 103 | if [ -n "$MOTOR" ]; then |
| 104 | kosu "imaj derlemesi" bash -c \ | 104 | kosu "imaj derlemesi" bash -c \ |
| 105 | "cd '$SERVIS' && MSYS_NO_PATHCONV=1 $MOTOR build -t hezarfen-zeka:ci -f Containerfile ." | 105 | "cd '$SERVIS' && MSYS_NO_PATHCONV=1 $MOTOR build -t hezarfen-zeka:ci -f Containerfile ." |
| 106 | - kosu "kosu kaniti" bash -c "'$KOK/scripts/ci-konteyner-kanit.sh' '$MOTOR' hezarfen-zeka:ci" | 106 | + kosu "kosu kaniti" bash -c "bash '$KOK/scripts/ci-konteyner-kanit.sh' '$MOTOR' hezarfen-zeka:ci" |
| 107 | - kosu "compose denetimi" bash -c "'$KOK/scripts/ci-compose.sh'" | 107 | + kosu "compose denetimi" bash -c "bash '$KOK/scripts/ci-compose.sh'" |
| 108 | fi | 108 | fi |
| 109 | else | 109 | else |
| 110 | echo "" | 110 | echo "" |
service/.env.examplemodified+23 -11
| @@ -14,22 +14,34 @@ | |||
| 14 | # AI_SHARED_TOKEN degeriyle birebir ayni olmali. | 14 | # AI_SHARED_TOKEN degeriyle birebir ayni olmali. |
| 15 | AI_SHARED_TOKEN= | 15 | AI_SHARED_TOKEN= |
| 16 | 16 | ||
| 17 | -# ZEKA ciktilarini yazacagi veritabani. OKULUN kendi veritabanidir; ayri bir | 17 | +# KONTROL veritabani. Okul ciktilari BURAYA yazilmaz: her okul KENDI |
| 18 | -# ZEKA veritabani YOKTUR. | 18 | +# veritabanina yazar ve adi okulun uuid'sinden turer (backend `tenant.rs:112`): |
| 19 | +# {kontrol_db}_school_{uuid_tiresiz} | ||
| 20 | +# Okul slug'i -> veritabani cozumlemesi kontrol satirindan yapilir | ||
| 21 | +# (`school` tablosu); DSN'e sabit bir okul yazmak tek-okullu kuruluma donmek | ||
| 22 | +# olurdu (bkz. src/tenants.py). | ||
| 19 | # | 23 | # |
| 20 | -# Adi okulun uuid'sinden turer (`tenant.rs:112`), slug'dan DEGIL: | 24 | +# Bu degiskenin dolu olmasi Postgres'i secer; bos olmasi eski tek veritabani |
| 21 | -# {control_db}_school_{uuid_tiresiz} | 25 | +# (SurrealDB) moduna duser (bkz. src/store_factory.py). |
| 22 | -# Demo okulu icin: | ||
| 23 | -# hezarfen_control_school_0193000000007000800000000000de70 | ||
| 24 | -# | ||
| 25 | -# Bu degiskenin dolu olmasi Postgres'i secer; bos olmasi eski SurrealDB | ||
| 26 | -# kurulumuna duser (bkz. src/store_factory.py). | ||
| 27 | ZEKA_PG_DSN= | 26 | ZEKA_PG_DSN= |
| 28 | 27 | ||
| 29 | -# Segment hattinin LLM saglayicisi. Kopru bu anahtari OKUMAZ; yalnizca | 28 | +# Segment hattinin LLM anahtari. Kopru bu anahtari OKUMAZ; yalnizca |
| 30 | # `src/segment/` okur. Yine de zorunlu tutuluyor: anahtarsiz bir servis ayaga | 29 | # `src/segment/` okur. Yine de zorunlu tutuluyor: anahtarsiz bir servis ayaga |
| 31 | # kalkar, segment hatti kosuldugunda patlardi. Hatayi dagitim anina cekiyoruz. | 30 | # kalkar, segment hatti kosuldugunda patlardi. Hatayi dagitim anina cekiyoruz. |
| 32 | -DEEPSEEK_API_KEY= | 31 | +# |
| 32 | +# ADLAR (2026-09-17 temiz kesim -- eski adlar DESTEKLENMEZ, gorulurlerse | ||
| 33 | +# yapilandirma acilista REDDEDILIR): | ||
| 34 | +# LLM_API_KEY anahtar (zorunlu) | ||
| 35 | +# LLM_BASE_URL taban adres (varsayilan https://api.deepseek.com) | ||
| 36 | +# LLM_MODEL_FLASH / LLM_MODEL_PRO / LLM_MODEL_REASONER rol basina model | ||
| 37 | +# LLM_MODEL_ROLE varsayilan rol secimi | ||
| 38 | +# Kaldirilan adlar: DEEPSEEK_API_KEY, SEGMENT_API_KEY, SEGMENT_BASE_URL, | ||
| 39 | +# SEGMENT_MODEL_FLASH/PRO/REASONER, SEGMENT_MODEL_ROLE. | ||
| 40 | +# | ||
| 41 | +# SAGLAYICI: DeepSeek varsayilandir, ZORUNLULUK DEGILDIR. OpenAI uyumlu her | ||
| 42 | +# ag gecidi calisir: LLM_BASE_URL'i gecidinize verin ve model kimliklerini | ||
| 43 | +# LLM_MODEL_* ile o saglayicinin adlariyla degistirin. | ||
| 44 | +LLM_API_KEY= | ||
| 33 | 45 | ||
| 34 | # ============================================================================ | 46 | # ============================================================================ |
| 35 | # KOPRU | 47 | # KOPRU |
service/compose.yamlmodified+10 -4
| @@ -7,8 +7,12 @@ services: | |||
| 7 | build: | 7 | build: |
| 8 | context: . | 8 | context: . |
| 9 | dockerfile: Containerfile | 9 | dockerfile: Containerfile |
| 10 | - # HEZARFEN_TAG deploy tarafindan yazilan stack.env'den gelir (--env-file | 10 | + # HEZARFEN_TAG deploy tarafindan yazilan stack.env'den gelir: unit ve deploy |
| 11 | - # sirasi onu kazanan yapar). Yerelde/elle `up` icin varsayilan `current`: | 11 | + # tek `--env-file stack.env` verir, operator sirlari ise ORTAMDAN gelir |
| 12 | + # (systemd `EnvironmentFile=` / deploy'un surece almasi) -- bu | ||
| 13 | + # saglayicida `--env-file` yalniz SON dosyayi cozer, iki dosyali cagri | ||
| 14 | + # operator dosyasini dusurur (podman_compose.py:2941-2946, :2559). | ||
| 15 | + # Yerelde/elle `up` icin varsayilan `current`: | ||
| 12 | # yani `podman compose up -d --build` yine calisiyor. Sabit bir `:current` | 16 | # yani `podman compose up -d --build` yine calisiyor. Sabit bir `:current` |
| 13 | # yazilsaydi deploy yeni imaji yukleyip ESKI imaji kosmaya devam ederdi -- | 17 | # yazilsaydi deploy yeni imaji yukleyip ESKI imaji kosmaya devam ederdi -- |
| 14 | # tag rotasyonu ve geri donus (previous_tag) bu satira baglidir. | 18 | # tag rotasyonu ve geri donus (previous_tag) bu satira baglidir. |
| @@ -29,14 +33,16 @@ services: | |||
| 29 | # --- LLM saglayicisi (segment hatti) --- | 33 | # --- LLM saglayicisi (segment hatti) --- |
| 30 | # Zorunlu tutuluyor. DIKKAT, durust not: `src/bridge.py` bu anahtari | 34 | # Zorunlu tutuluyor. DIKKAT, durust not: `src/bridge.py` bu anahtari |
| 31 | # OKUMAZ; yalnizca `src/segment/config.py` okur (oradaki oncelik sirasi | 35 | # OKUMAZ; yalnizca `src/segment/config.py` okur (oradaki oncelik sirasi |
| 32 | - # DEEPSEEK_API_KEY -> LLM_API_KEY -> SEGMENT_API_KEY). Yani anahtarsiz | 36 | + # LLM_API_KEY -- TEMIZ KESIM (2026-09-17): eski adlar (DEEPSEEK_API_KEY, |
| 37 | + # SEGMENT_API_KEY, SEGMENT_BASE_URL, SEGMENT_MODEL_*) KALDIRILDI; dolu | ||
| 38 | + # bulunurlarsa yapilandirma acilista reddedilir). Yani anahtarsiz | ||
| 33 | # bir kopru teknik olarak ayaga kalkardi, segment hatti kosulunca | 39 | # bir kopru teknik olarak ayaga kalkardi, segment hatti kosulunca |
| 34 | # patlardi. `:?` ile hatayi DAGITIM anina cekiyoruz: acilista bir satir | 40 | # patlardi. `:?` ile hatayi DAGITIM anina cekiyoruz: acilista bir satir |
| 35 | # hata, uretimde saatler sonra sasirtici bir cokme yerine. | 41 | # hata, uretimde saatler sonra sasirtici bir cokme yerine. |
| 36 | # Sir DOSYAYA GOMULMEZ: burada yalnizca interpolasyon vardir, deger | 42 | # Sir DOSYAYA GOMULMEZ: burada yalnizca interpolasyon vardir, deger |
| 37 | # operatorun ortamindan ya da `--env-file` ile verilen (gitignore'lu) | 43 | # operatorun ortamindan ya da `--env-file` ile verilen (gitignore'lu) |
| 38 | # `.env` dosyasindan gelir. | 44 | # `.env` dosyasindan gelir. |
| 39 | - DEEPSEEK_API_KEY: ${DEEPSEEK_API_KEY:?DEEPSEEK_API_KEY gerekli -- segment hatti LLM saglayicisina bu anahtarla baglanir} | 45 | + LLM_API_KEY: ${LLM_API_KEY:?LLM_API_KEY gerekli -- segment hatti LLM saglayicisina bu anahtarla baglanir} |
| 40 | # Sertifika pinleme. BOS BIRAKILIRSA TOFU: backend'in HTTP ile verdigi | 46 | # Sertifika pinleme. BOS BIRAKILIRSA TOFU: backend'in HTTP ile verdigi |
| 41 | # sertifikaya sorgusuz guvenilir (podcast ve Celebi'nin bugunku hali, | 47 | # sertifikaya sorgusuz guvenilir (podcast ve Celebi'nin bugunku hali, |
| 42 | # denetimde zafiyet olarak isaretlendi). Uretimde backend'in acilista | 48 | # denetimde zafiyet olarak isaretlendi). Uretimde backend'in acilista |
service/docs/BACKEND-GEREKSINIMLERI.mdmodified+3 -2
| @@ -197,8 +197,9 @@ gerekiyor ve kendi kendine kosmak icin bir liste gerekiyor. | |||
| 197 | 197 | ||
| 198 | **Yapilandirmadan.** `service/src/config.py` icinde: | 198 | **Yapilandirmadan.** `service/src/config.py` icinde: |
| 199 | 199 | ||
| 200 | -- `ZEKA_SCHOOLS` -- islenecek okul sluglari, virgulle ayrilmis | 200 | +- `ZEKA_SCHOOLS` -- islenecek okul sluglari, virgulle ayrilmis. Artik bir |
| 201 | - (varsayilan: `ataturk-anadolu`), | 201 | + FILTREDIR: bos birakilirsa kontrol veritabanindaki (`school` tablosu) |
| 202 | + butun aktif okullar islenir (varsayilan: bos), | ||
| 202 | - `ZEKA_STUDENT_SOURCE` = `config` | `file`, | 203 | - `ZEKA_STUDENT_SOURCE` = `config` | `file`, |
| 203 | - `ZEKA_STUDENTS` -- kullanici kimlikleri, virgulle ayrilmis, | 204 | - `ZEKA_STUDENTS` -- kullanici kimlikleri, virgulle ayrilmis, |
| 204 | - `ZEKA_STUDENT_FILE` -- ayni listenin dosya hali. | 205 | - `ZEKA_STUDENT_FILE` -- ayni listenin dosya hali. |
service/src/bridge.pymodified+41 -30
| @@ -50,6 +50,7 @@ from .protocol import ( | |||
| 50 | FrameStream, | 50 | FrameStream, |
| 51 | HandshakeRejected, | 51 | HandshakeRejected, |
| 52 | ) | 52 | ) |
| 53 | +from .tenants import TenantError | ||
| 53 | 54 | ||
| 54 | RequestHandler = Callable[[protocol.Request], Any] | 55 | RequestHandler = Callable[[protocol.Request], Any] |
| 55 | """Backend'den gelen bir `Request`'i karsilayan kanca. | 56 | """Backend'den gelen bir `Request`'i karsilayan kanca. |
| @@ -424,7 +425,11 @@ class BridgeProtocol(QuicConnectionProtocol): | |||
| 424 | self._handle(request), timeout=request.timeout_secs | 425 | self._handle(request), timeout=request.timeout_secs |
| 425 | ) | 426 | ) |
| 426 | response = protocol.ok_response(request_id, school, result) | 427 | response = protocol.ok_response(request_id, school, result) |
| 427 | - except CapabilityError as exc: | 428 | + except (CapabilityError, TenantError) as exc: |
| 429 | + # Okul cozumlemesi redleri (`unknown_school`, `school_suspended`, | ||
| 430 | + # `school_not_migrated`) backend'e AYNEN gider: hepsi beklenen | ||
| 431 | + # durumlardir ve ayrimlari backend'in yeniden deneme kararini | ||
| 432 | + # etkiler. `internal` yalnizca TANINMAYAN hatalar icin. | ||
| 428 | response = protocol.err_response(request_id, school, exc.code, str(exc)) | 433 | response = protocol.err_response(request_id, school, exc.code, str(exc)) |
| 429 | except asyncio.TimeoutError: | 434 | except asyncio.TimeoutError: |
| 430 | response = protocol.err_response( | 435 | response = protocol.err_response( |
| @@ -621,41 +626,47 @@ async def _serve(settings: config.Config) -> int: | |||
| 621 | """ | 626 | """ |
| 622 | from .scheduler import Scheduler | 627 | from .scheduler import Scheduler |
| 623 | from .source import BridgeSource | 628 | from .source import BridgeSource |
| 624 | - from .store_factory import describe, open_store | 629 | + from .store_factory import describe |
| 625 | - | 630 | + from .tenants import open_directory |
| 626 | - if settings.refresh_interval_secs <= 0: | 631 | + |
| 627 | - config.log("info", "gece zamanlayicisi KAPALI (ZEKA_REFRESH_INTERVAL_SECS=0)") | 632 | + # Okul dizini ACILISTA kurulur ve isleyicilere baglanir; okul LISTESI |
| 628 | - return await run_forever(settings) | 633 | + # acilista okunmaz (kontrol veritabaninda hic okul olmayabilir) ve okul |
| 629 | - | 634 | + # VERITABANLARINA acilista baglanilmaz (biri eksikse bu bir istek |
| 630 | - config.log("info", describe()) | 635 | + # hatasidir, acilis hatasi degil -- `tenants.py`). |
| 631 | - store, db = await open_store() | 636 | + directory = await open_directory(settings) |
| 632 | - kopru: dict[str, Any] = {"protocol": None} | 637 | + capabilities.bind_directory(directory) |
| 633 | - | ||
| 634 | - def hazir(proto: BridgeProtocol) -> None: | ||
| 635 | - kopru["protocol"] = proto | ||
| 636 | - | ||
| 637 | - # Zamanlayici her okul icin bir `Source` ister. Baglanti kopmussa | ||
| 638 | - # `BridgeSource` cagrisi hata verir ve zamanlayici o okulu duser -- | ||
| 639 | - # dogru davranis: veri cekilemeden hesap yapilmaz. | ||
| 640 | - def source_for(_school: str) -> Any: | ||
| 641 | - proto = kopru["protocol"] | ||
| 642 | - if proto is None: | ||
| 643 | - raise RuntimeError("kopru henuz bagli degil") | ||
| 644 | - return BridgeSource(proto) | ||
| 645 | - | ||
| 646 | - scheduler = Scheduler( | ||
| 647 | - source_for, | ||
| 648 | - store, | ||
| 649 | - settings.schools, | ||
| 650 | - budget_ms=int(settings.refresh_interval_secs * 1000), | ||
| 651 | - ) | ||
| 652 | try: | 638 | try: |
| 639 | + config.log("info", describe()) | ||
| 640 | + config.log("info", directory.describe()) | ||
| 641 | + if settings.refresh_interval_secs <= 0: | ||
| 642 | + config.log("info", "gece zamanlayicisi KAPALI (ZEKA_REFRESH_INTERVAL_SECS=0)") | ||
| 643 | + return await run_forever(settings) | ||
| 644 | + kopru: dict[str, Any] = {"protocol": None} | ||
| 645 | + | ||
| 646 | + def hazir(proto: BridgeProtocol) -> None: | ||
| 647 | + kopru["protocol"] = proto | ||
| 648 | + | ||
| 649 | + # Zamanlayici her okul icin bir `Source` ister. Baglanti kopmussa | ||
| 650 | + # `BridgeSource` cagrisi hata verir ve zamanlayici o okulu duser -- | ||
| 651 | + # dogru davranis: veri cekilemeden hesap yapilmaz. | ||
| 652 | + def source_for(_school: str) -> Any: | ||
| 653 | + proto = kopru["protocol"] | ||
| 654 | + if proto is None: | ||
| 655 | + raise RuntimeError("kopru henuz bagli degil") | ||
| 656 | + return BridgeSource(proto) | ||
| 657 | + | ||
| 658 | + scheduler = Scheduler( | ||
| 659 | + source_for, | ||
| 660 | + directory, | ||
| 661 | + only=settings.schools, | ||
| 662 | + budget_ms=int(settings.refresh_interval_secs * 1000), | ||
| 663 | + ) | ||
| 653 | await asyncio.gather( | 664 | await asyncio.gather( |
| 654 | run_forever(settings, on_ready=hazir), | 665 | run_forever(settings, on_ready=hazir), |
| 655 | scheduler.serve(tick_seconds=settings.refresh_interval_secs), | 666 | scheduler.serve(tick_seconds=settings.refresh_interval_secs), |
| 656 | ) | 667 | ) |
| 657 | finally: | 668 | finally: |
| 658 | - await db.close() | 669 | + await directory.close() |
| 659 | return 0 | 670 | return 0 |
| 660 | 671 | ||
| 661 | 672 | ||
service/src/capabilities.pymodified+24 -0
| @@ -135,6 +135,30 @@ Handler = Callable[[str, dict[str, Any]], dict[str, Any]] | |||
| 135 | 135 | ||
| 136 | _handlers: dict[str, Handler] = {} | 136 | _handlers: dict[str, Handler] = {} |
| 137 | 137 | ||
| 138 | +#: Servisin okul dizini (`tenants.Directory`). Isleyiciler okulun deposunu | ||
| 139 | +#: BURADAN cozer: `capabilities.directory().store_for(school)`. Cercevenin | ||
| 140 | +#: `school` alani tek kimlik kaynagidir; ikinci bir yol (ortam degiskeni, | ||
| 141 | +#: varsayilan okul) olmamasi bilincli -- yanlis okulun veritabanindan cevap | ||
| 142 | +#: veren bir okuma, bu alanin kapatmak istedigi tek arizadir. | ||
| 143 | +_directory: Any = None | ||
| 144 | + | ||
| 145 | + | ||
| 146 | +def bind_directory(directory: Any) -> None: | ||
| 147 | + """Acilista bir kez cagrilir (`bridge._serve`); testler de kullanir.""" | ||
| 148 | + global _directory | ||
| 149 | + _directory = directory | ||
| 150 | + | ||
| 151 | + | ||
| 152 | +def directory() -> Any: | ||
| 153 | + """Bagli okul dizini. Baglanmamisken okul cozulemez -- sessizce | ||
| 154 | + varsayilana dusmek yerine acik hata.""" | ||
| 155 | + if _directory is None: | ||
| 156 | + raise CapabilityError( | ||
| 157 | + "unavailable", | ||
| 158 | + "okul dizini bagli degil; isleyici okul veritabanini cozemez", | ||
| 159 | + ) | ||
| 160 | + return _directory | ||
| 161 | + | ||
| 138 | 162 | ||
| 139 | def names() -> list[str]: | 163 | def names() -> list[str]: |
| 140 | """`Hello.capabilities` icine yazilacak adlar.""" | 164 | """`Hello.capabilities` icine yazilacak adlar.""" |
service/src/cli.pymodified+50 -14
| @@ -222,10 +222,32 @@ async def _cmd_schedule(args: argparse.Namespace) -> int: | |||
| 222 | 222 | ||
| 223 | `--ticks` verilirse tam `serve()` dongusu kosar (test kipi); verilmezse | 223 | `--ticks` verilirse tam `serve()` dongusu kosar (test kipi); verilmezse |
| 224 | tek tur (`run_once`) kosar. Ikisi de ayni kod yolunu kullanir. | 224 | tek tur (`run_once`) kosar. Ikisi de ayni kod yolunu kullanir. |
| 225 | + | ||
| 226 | + Iki depo yolu vardir ve ikisi de URETIMDEKI ayni kodu kullanir: | ||
| 227 | + | ||
| 228 | + * `--pg-dsn` (ya da `ZEKA_PG_DSN`) verilirse KONTROL veritabanidir; | ||
| 229 | + okullar oradan cozulur (`tenants.open_postgres`) ve `--schools` FILTRE | ||
| 230 | + olur (verilmezse butun aktif okullar kosar). | ||
| 231 | + * verilmezse eski tek veritabani modu; `--schools` ZORUNLUDUR. | ||
| 225 | """ | 232 | """ |
| 226 | - client = _build_client(args) | 233 | + from .tenants import OneDatabase |
| 227 | - store = Store(client) | 234 | + |
| 228 | - schools = [s.strip() for s in args.schools.split(",") if s.strip()] | 235 | + schools = [s.strip() for s in (args.schools or "").split(",") if s.strip()] |
| 236 | + dsn = (args.pg_dsn or os.environ.get("ZEKA_PG_DSN", "")).strip() | ||
| 237 | + if dsn: | ||
| 238 | + from .tenants import open_postgres | ||
| 239 | + | ||
| 240 | + directory = await open_postgres(dsn) | ||
| 241 | + only = schools or None | ||
| 242 | + else: | ||
| 243 | + if not schools: | ||
| 244 | + raise SystemExit( | ||
| 245 | + "--schools zorunlu (tek veritabani modu). Postgres icin " | ||
| 246 | + "--pg-dsn verin; orada okullar kontrol veritabanindan gelir." | ||
| 247 | + ) | ||
| 248 | + client = _build_client(args) | ||
| 249 | + directory = OneDatabase(Store(client), schools, teardown=[client.close]) | ||
| 250 | + only = None | ||
| 229 | budgets: dict[str, int] = {} | 251 | budgets: dict[str, int] = {} |
| 230 | for pair in (args.budget or "").split(","): | 252 | for pair in (args.budget or "").split(","): |
| 231 | if "=" in pair: | 253 | if "=" in pair: |
| @@ -239,27 +261,31 @@ async def _cmd_schedule(args: argparse.Namespace) -> int: | |||
| 239 | stamp = args.now or int(time.time() * 1000) | 261 | stamp = args.now or int(time.time() * 1000) |
| 240 | scheduler = Scheduler( | 262 | scheduler = Scheduler( |
| 241 | lambda school: FileSource(root), | 263 | lambda school: FileSource(root), |
| 242 | - store, | 264 | + directory, |
| 243 | - schools, | 265 | + only=only, |
| 244 | budget_ms=args.budget_ms, | 266 | budget_ms=args.budget_ms, |
| 245 | budgets=budgets, | 267 | budgets=budgets, |
| 246 | term_start_ms=args.term_start, | 268 | term_start_ms=args.term_start, |
| 247 | clock_fn=lambda: stamp, | 269 | clock_fn=lambda: stamp, |
| 248 | ) | 270 | ) |
| 249 | - if args.ticks: | 271 | + try: |
| 250 | - await scheduler.serve( | 272 | + if args.ticks: |
| 251 | - tick_seconds=args.tick_seconds, ignore_window=True, max_ticks=args.ticks | 273 | + await scheduler.serve( |
| 252 | - ) | 274 | + tick_seconds=args.tick_seconds, ignore_window=True, max_ticks=args.ticks |
| 253 | - results = [] | 275 | + ) |
| 254 | - else: | 276 | + results = [] |
| 255 | - results = await scheduler.run_once(stamp) | 277 | + else: |
| 278 | + results = await scheduler.run_once(stamp) | ||
| 279 | + finally: | ||
| 280 | + await directory.close() | ||
| 281 | + gorulen = sorted({*schools, *(r.school for r in results)}) | ||
| 256 | print( | 282 | print( |
| 257 | json.dumps( | 283 | json.dumps( |
| 258 | { | 284 | { |
| 259 | "kosulan_okullar": [r.school for r in results], | 285 | "kosulan_okullar": [r.school for r in results], |
| 260 | "sonuclar": [dataclasses.asdict(r) for r in results], | 286 | "sonuclar": [dataclasses.asdict(r) for r in results], |
| 261 | "dusen_okullar": scheduler._failures, | 287 | "dusen_okullar": scheduler._failures, |
| 262 | - "bekleyen": {s: scheduler.pending_for(s) for s in schools}, | 288 | + "bekleyen": {s: scheduler.pending_for(s) for s in gorulen}, |
| 263 | }, | 289 | }, |
| 264 | ensure_ascii=False, | 290 | ensure_ascii=False, |
| 265 | indent=2, | 291 | indent=2, |
| @@ -397,7 +423,17 @@ def build_parser() -> argparse.ArgumentParser: | |||
| 397 | schedule = sub.add_parser( | 423 | schedule = sub.add_parser( |
| 398 | "schedule", help="zamanlayıcıyı elle tetikle (gece penceresini beklemeden)" | 424 | "schedule", help="zamanlayıcıyı elle tetikle (gece penceresini beklemeden)" |
| 399 | ) | 425 | ) |
| 400 | - schedule.add_argument("--schools", required=True, help="virgülle ayrılmış slug") | 426 | + schedule.add_argument( |
| 427 | + "--schools", | ||
| 428 | + help="virgülle ayrılmış slug listesi. Postgres modunda (--pg-dsn) " | ||
| 429 | + "FİLTREDİR: verilmezse bütün aktif okullar koşar; eski tek veritabanı " | ||
| 430 | + "modunda zorunludur", | ||
| 431 | + ) | ||
| 432 | + schedule.add_argument( | ||
| 433 | + "--pg-dsn", | ||
| 434 | + help="KONTROL veritabanı DSN'i (verilmezse ZEKA_PG_DSN). Verilirse " | ||
| 435 | + "okullar kontrol veritabanındaki `school` tablosundan çözülür", | ||
| 436 | + ) | ||
| 401 | schedule.add_argument("--fixtures", required=True) | 437 | schedule.add_argument("--fixtures", required=True) |
| 402 | schedule.add_argument("--now", type=int) | 438 | schedule.add_argument("--now", type=int) |
| 403 | schedule.add_argument("--term-start", type=int) | 439 | schedule.add_argument("--term-start", type=int) |
service/src/config.pymodified+29 -5
| @@ -168,13 +168,31 @@ class Config: | |||
| 168 | 168 | ||
| 169 | # --- kapsam ----------------------------------------------------------- | 169 | # --- kapsam ----------------------------------------------------------- |
| 170 | # Her frame kendi okulunu adlandirir (`ai/protocol.rs:36-47`); `Hello` | 170 | # Her frame kendi okulunu adlandirir (`ai/protocol.rs:36-47`); `Hello` |
| 171 | - # okul tasimaz. Filo paylasimlidir, bu yuzden hangi okullari isleyecegimizi | 171 | + # okul tasimaz. Filo paylasimlidir: ZEKA butun okullara hizmet eder. |
| 172 | - # yapilandirmadan ogreniyoruz -- backend'de okul listeleme yolu yok. | 172 | + # |
| 173 | - self.schools = env_list("ZEKA_SCHOOLS", ("hezarfen-demo",)) | 173 | + # Okul KUTUGU kontrol veritabanindadir (`tenants.py`); burasi yalnizca |
| 174 | + # bir FILTREDIR. Bos liste = butun aktif okullar. Sabit bir varsayilan | ||
| 175 | + # okul yoktur: "hangi okullar var" sorusunun cevabi yapilandirma | ||
| 176 | + # degil, kontrol veritabani olmalidir. | ||
| 177 | + self.schools = env_list("ZEKA_SCHOOLS", ()) | ||
| 174 | self.student_source = env_choice("ZEKA_STUDENT_SOURCE", "config", STUDENT_SOURCES) | 178 | self.student_source = env_choice("ZEKA_STUDENT_SOURCE", "config", STUDENT_SOURCES) |
| 175 | self.students = env_list("ZEKA_STUDENTS", ()) | 179 | self.students = env_list("ZEKA_STUDENTS", ()) |
| 176 | self.student_file = _absolute(env_str("ZEKA_STUDENT_FILE", "")) | 180 | self.student_file = _absolute(env_str("ZEKA_STUDENT_FILE", "")) |
| 177 | 181 | ||
| 182 | + # --- okul havuzlari --------------------------------------------------- | ||
| 183 | + # Okul sayisi sinirsiz; acik baglanti sayisi sinirli olmali. Havuz | ||
| 184 | + # tavani ve TTL'i `tenants.TenantStores` uygular. | ||
| 185 | + self.max_school_pools = env_int("ZEKA_MAX_SCHOOL_POOLS", 8, 1, 256) | ||
| 186 | + self.school_pool_ttl_secs = env_float( | ||
| 187 | + "ZEKA_SCHOOL_POOL_TTL_SECS", 900.0, 0.0, 86400.0 | ||
| 188 | + ) | ||
| 189 | + self.school_registry_ttl_secs = env_float( | ||
| 190 | + "ZEKA_SCHOOL_REGISTRY_TTL_SECS", 30.0, 0.0, 3600.0 | ||
| 191 | + ) | ||
| 192 | + self.school_connect_timeout_secs = env_float( | ||
| 193 | + "ZEKA_SCHOOL_CONNECT_TIMEOUT_SECS", 10.0, 1.0, 120.0 | ||
| 194 | + ) | ||
| 195 | + | ||
| 178 | # --- veri cephesi ------------------------------------------------------ | 196 | # --- veri cephesi ------------------------------------------------------ |
| 179 | self.source_mode = env_choice("ZEKA_SOURCE", "bridge", SOURCE_MODES) | 197 | self.source_mode = env_choice("ZEKA_SOURCE", "bridge", SOURCE_MODES) |
| 180 | self.fixture_root = _absolute(env_str("ZEKA_FIXTURE_ROOT", "/data/zeka/fixtures")) | 198 | self.fixture_root = _absolute(env_str("ZEKA_FIXTURE_ROOT", "/data/zeka/fixtures")) |
| @@ -223,7 +241,8 @@ class Config: | |||
| 223 | f"token={'tanimli' if self.has_token else 'TANIMSIZ'} " | 241 | f"token={'tanimli' if self.has_token else 'TANIMSIZ'} " |
| 224 | f"max_es_zamanli={self.max_concurrent} " | 242 | f"max_es_zamanli={self.max_concurrent} " |
| 225 | f"yeniden_baglanma={self.reconnect_secs}s..{self.reconnect_max_secs}s " | 243 | f"yeniden_baglanma={self.reconnect_secs}s..{self.reconnect_max_secs}s " |
| 226 | - f"okullar={','.join(self.schools)} " | 244 | + f"okullar={','.join(self.schools) if self.schools else 'hepsi(kontrol)'} " |
| 245 | + f"okul_havuzu=en fazla {self.max_school_pools} TTL {self.school_pool_ttl_secs:g}s " | ||
| 227 | f"ogrenci_kaynagi={self.student_source} ogrenci_sayisi={students} " | 246 | f"ogrenci_kaynagi={self.student_source} ogrenci_sayisi={students} " |
| 228 | f"veri_cephesi={self.source_mode} fikstur_kok={self.fixture_root} " | 247 | f"veri_cephesi={self.source_mode} fikstur_kok={self.fixture_root} " |
| 229 | f"api_zaman_asimi={self.api_timeout_secs}s " | 248 | f"api_zaman_asimi={self.api_timeout_secs}s " |
| @@ -240,6 +259,11 @@ def _depo_ozeti_impl(self) -> str: | |||
| 240 | yazilirken bile "db=ws://hezarfen-surrealdb:8000/rpc" diyordu. Acilis | 259 | yazilirken bile "db=ws://hezarfen-surrealdb:8000/rpc" diyordu. Acilis |
| 241 | logunun yanlis depoyu gostermesi, bir arizayi tesbit ederken insani | 260 | logunun yanlis depoyu gostermesi, bir arizayi tesbit ederken insani |
| 242 | saatlerce yanlis yere baktirir. | 261 | saatlerce yanlis yere baktirir. |
| 262 | + | ||
| 263 | + `ZEKA_PG_DSN` artik KONTROL veritabanidir; okul verileri okul basina | ||
| 264 | + ayri veritabanlarindadir (`tenants.py`). Satir bunu soyler, yoksa "depo= | ||
| 265 | + postgres /hezarfen_control" okuyan operator okul verisinin oraya | ||
| 266 | + yazildigini sanirdi. | ||
| 243 | """ | 267 | """ |
| 244 | import os | 268 | import os |
| 245 | 269 | ||
| @@ -252,7 +276,7 @@ def _depo_ozeti_impl(self) -> str: | |||
| 252 | yer = f"{parsed.hostname or '?'}{parsed.path}" | 276 | yer = f"{parsed.hostname or '?'}{parsed.path}" |
| 253 | except Exception: # noqa: BLE001 | 277 | except Exception: # noqa: BLE001 |
| 254 | yer = "<cozumlenemedi>" | 278 | yer = "<cozumlenemedi>" |
| 255 | - return f"depo=postgres {yer}" | 279 | + return f"depo=postgres kontrol {yer} (okullar kendi veritabanlarinda)" |
| 256 | return ( | 280 | return ( |
| 257 | f"depo=surrealdb(eski) {self.db_url} ns={self.db_namespace} " | 281 | f"depo=surrealdb(eski) {self.db_url} ns={self.db_namespace} " |
| 258 | f"db_ad={self.db_database} " | 282 | f"db_ad={self.db_database} " |
service/src/pg_client.pymodified+18 -4
| @@ -21,6 +21,10 @@ Baglanti bilgisi | |||
| 21 | `ZEKA_PG_DSN` ortam degiskeninden gelir. Bu bir **sirdir**: hicbir kosulda | 21 | `ZEKA_PG_DSN` ortam degiskeninden gelir. Bu bir **sirdir**: hicbir kosulda |
| 22 | loglanmaz. `PgPool.describe()` yalnizca host/port/veritabani doner, kullanici | 22 | loglanmaz. `PgPool.describe()` yalnizca host/port/veritabani doner, kullanici |
| 23 | adi ve parola asla. | 23 | adi ve parola asla. |
| 24 | + | ||
| 25 | +DSN artik **kontrol** veritabanini adlandirir (`tenants.py`); okul | ||
| 26 | +veritabanlarina ayni sunucuda, `dbname` degistirilmis DSN'lerle baglanilir. | ||
| 27 | +Bu modul ikisini de bilmez: eline verilen DSN'e baglanir. | ||
| 24 | """ | 28 | """ |
| 25 | 29 | ||
| 26 | from __future__ import annotations | 30 | from __future__ import annotations |
| @@ -57,8 +61,15 @@ class PsycopgClient: | |||
| 57 | self._conn = conn | 61 | self._conn = conn |
| 58 | 62 | ||
| 59 | @classmethod | 63 | @classmethod |
| 60 | - async def connect(cls, dsn: str | None = None) -> "PsycopgClient": | 64 | + async def connect( |
| 61 | - """`ZEKA_PG_DSN` ile baglanir. DSN loglanmaz.""" | 65 | + cls, dsn: str | None = None, *, connect_timeout: float | None = None |
| 66 | + ) -> "PsycopgClient": | ||
| 67 | + """`ZEKA_PG_DSN` ile baglanir. DSN loglanmaz. | ||
| 68 | + | ||
| 69 | + `connect_timeout` saniyedir ve libpq'ye gecer: okul havuzlari istek | ||
| 70 | + aninda acildigi icin, ulasilamayan bir veritabani sonsuza kadar | ||
| 71 | + beklenmez (bkz. `tenants.py`). | ||
| 72 | + """ | ||
| 62 | import psycopg | 73 | import psycopg |
| 63 | 74 | ||
| 64 | target = dsn or os.environ.get("ZEKA_PG_DSN", "") | 75 | target = dsn or os.environ.get("ZEKA_PG_DSN", "") |
| @@ -67,8 +78,11 @@ class PsycopgClient: | |||
| 67 | "ZEKA_PG_DSN tanimli degil; okul veritabanina baglanilamaz" | 78 | "ZEKA_PG_DSN tanimli degil; okul veritabanina baglanilamaz" |
| 68 | ) | 79 | ) |
| 69 | # autocommit: transaction sinirlarini PgStore belirler, surucu degil. | 80 | # autocommit: transaction sinirlarini PgStore belirler, surucu degil. |
| 70 | - conn = await psycopg.AsyncConnection.connect(target, autocommit=True) | 81 | + kwargs: dict[str, Any] = {"autocommit": True} |
| 71 | - log.info("okul veritabanina baglanildi (%s)", _describe(target)) | 82 | + if connect_timeout is not None: |
| 83 | + kwargs["connect_timeout"] = max(1, int(connect_timeout)) | ||
| 84 | + conn = await psycopg.AsyncConnection.connect(target, **kwargs) | ||
| 85 | + log.info("veritabanina baglanildi (%s)", _describe(target)) | ||
| 72 | return cls(conn) | 86 | return cls(conn) |
| 73 | 87 | ||
| 74 | async def execute(self, sql: str, params: Sequence[Any] = ()) -> None: | 88 | async def execute(self, sql: str, params: Sequence[Any] = ()) -> None: |
service/src/scheduler.pymodified+66 -21
| @@ -28,6 +28,12 @@ Tasarım kararları (`MODULLER.md` §2.12) | |||
| 28 | sıradaki okul bütçesiz kalır" durumu **görünür** olur; dönüşümlü sıra bunu | 28 | sıradaki okul bütçesiz kalır" durumu **görünür** olur; dönüşümlü sıra bunu |
| 29 | gizlerdi. Tek istisna: geçen gece `partial` biten okullar **öne alınır** | 29 | gizlerdi. Tek istisna: geçen gece `partial` biten okullar **öne alınır** |
| 30 | (`MODULLER.md` §3.4). | 30 | (`MODULLER.md` §3.4). |
| 31 | +* **Okul listesi her tikte dizinden okunur**: hangi okulların var olduğunu | ||
| 32 | + kontrol veritabanı bilir (`tenants.py`), yapılandırma değil. `ZEKA_SCHOOLS` | ||
| 33 | + artık yalnızca bir filtredir; boşsa bütün aktif okullar işlenir. | ||
| 34 | +* **Her okul KENDİ veritabanına yazar**: depo, okulun slug'ından çözülür. | ||
| 35 | + Tek bir `store` nesnesi paylaşılmaz — paylaşılsaydı bütün okulların satırı | ||
| 36 | + ilk okulun veritabanına düşerdi. | ||
| 31 | * **Günde bir kez.** Bir okul için o TR gününde koşu yapıldıysa tekrar | 37 | * **Günde bir kez.** Bir okul için o TR gününde koşu yapıldıysa tekrar |
| 32 | yapılmaz. | 38 | yapılmaz. |
| 33 | * **Tek koşu güvencesi.** Süreç içi `asyncio.Lock`; tek süreç olduğu için | 39 | * **Tek koşu güvencesi.** Süreç içi `asyncio.Lock`; tek süreç olduğu için |
| @@ -41,12 +47,11 @@ import asyncio | |||
| 41 | import contextlib | 47 | import contextlib |
| 42 | import logging | 48 | import logging |
| 43 | import time | 49 | import time |
| 44 | -from collections.abc import Callable | 50 | +from collections.abc import Callable, Sequence |
| 45 | from typing import Any | 51 | from typing import Any |
| 46 | 52 | ||
| 47 | from .compute import clock | 53 | from .compute import clock |
| 48 | from .pipeline import DEFAULT_BUDGET_MS, RunResult, run_school | 54 | from .pipeline import DEFAULT_BUDGET_MS, RunResult, run_school |
| 49 | -from .store import Store | ||
| 50 | 55 | ||
| 51 | log = logging.getLogger(__name__) | 56 | log = logging.getLogger(__name__) |
| 52 | 57 | ||
| @@ -74,19 +79,26 @@ class Scheduler: | |||
| 74 | def __init__( | 79 | def __init__( |
| 75 | self, | 80 | self, |
| 76 | source_factory: Callable[[str], Any], | 81 | source_factory: Callable[[str], Any], |
| 77 | - store: Store, | 82 | + stores: Any, |
| 78 | - schools: list[str], | ||
| 79 | *, | 83 | *, |
| 84 | + only: Sequence[str] | None = None, | ||
| 80 | budget_ms: int = DEFAULT_BUDGET_MS, | 85 | budget_ms: int = DEFAULT_BUDGET_MS, |
| 81 | budgets: dict[str, int] | None = None, | 86 | budgets: dict[str, int] | None = None, |
| 82 | term_start_ms: int | None = None, | 87 | term_start_ms: int | None = None, |
| 83 | clock_fn: Callable[[], int] = now_ms, | 88 | clock_fn: Callable[[], int] = now_ms, |
| 84 | monotonic_fn: Callable[[], float] = time.monotonic, | 89 | monotonic_fn: Callable[[], float] = time.monotonic, |
| 85 | ) -> None: | 90 | ) -> None: |
| 86 | - # Sabit sıra: slug alfabetik (`MODULLER.md` §2.12 adım 3). | 91 | + # Okul listesi ARTIK yapilandirmadan gelmiyor: her tikte dizinden |
| 87 | - self._schools = sorted(schools) | 92 | + # (`stores.active_schools()`) okunur. `only` yalnizca bir FILTREdir -- |
| 93 | + # daraltir, uretmez. Bos liste = butun aktif okullar. | ||
| 94 | + self._stores = stores | ||
| 95 | + self._only = tuple(sorted({str(s) for s in (only or ()) if str(s).strip()})) | ||
| 88 | self._source_factory = source_factory | 96 | self._source_factory = source_factory |
| 89 | - self._store = store | 97 | + # Turun okul listesi; `run_once` her cagrildiginda tazelenir. |
| 98 | + self._schools: list[str] = [] | ||
| 99 | + # Filtrede olup dizinde olmayan okullar bir kez uyarilir (tik basina | ||
| 100 | + # tekrar tekrar ayni satiri basmak gunlugu okunmaz kilar). | ||
| 101 | + self._missing_filter: set[str] = set() | ||
| 90 | self._budget_ms = budget_ms | 102 | self._budget_ms = budget_ms |
| 91 | # Okul başına bütçe. Bir okulun öğrenci sayısı çok farklıysa ortak | 103 | # Okul başına bütçe. Bir okulun öğrenci sayısı çok farklıysa ortak |
| 92 | # bütçe ya küçük okula savurgan ya büyük okula cimri davranır; bu | 104 | # bütçe ya küçük okula savurgan ya büyük okula cimri davranır; bu |
| @@ -115,6 +127,33 @@ class Scheduler: | |||
| 115 | """Bu okulda bir sonraki koşuya devredilen öğrenciler.""" | 127 | """Bu okulda bir sonraki koşuya devredilen öğrenciler.""" |
| 116 | return list(self._pending.get(school, [])) | 128 | return list(self._pending.get(school, [])) |
| 117 | 129 | ||
| 130 | + async def _listing(self) -> list[str]: | ||
| 131 | + """Bu turun okul listesi: dizindeki aktif okullar ∩ filtre. | ||
| 132 | + | ||
| 133 | + Dizin okunamazsa (kontrol veritabani kapali, `school` tablosu yok) | ||
| 134 | + tur DUSMEZ: o tur okulsuz kosar, sonraki tik yeniden dener. Acilista | ||
| 135 | + kutuk okunmadigi icin (bkz. `tenants.py`) bu, okul satiri olmayan bir | ||
| 136 | + kurulumun da normal hali. | ||
| 137 | + """ | ||
| 138 | + try: | ||
| 139 | + active = await self._stores.active_schools() | ||
| 140 | + except Exception as exc: # noqa: BLE001 — tik dusmez, okul yok | ||
| 141 | + log.warning("okul listesi okunamadi, tur okulsuz kosuyor: %s", exc) | ||
| 142 | + return [] | ||
| 143 | + listing = sorted(s for s in active if not self._only or s in set(self._only)) | ||
| 144 | + if self._only: | ||
| 145 | + seen = set(listing) | ||
| 146 | + for slug in self._only: | ||
| 147 | + if slug not in active and slug not in self._missing_filter: | ||
| 148 | + self._missing_filter.add(slug) | ||
| 149 | + log.warning( | ||
| 150 | + "ZEKA_SCHOOLS'teki '%s' bu dagitimda aktif bir okul degil; " | ||
| 151 | + "atlanacak", | ||
| 152 | + slug, | ||
| 153 | + ) | ||
| 154 | + self._missing_filter &= seen | ||
| 155 | + return listing | ||
| 156 | + | ||
| 118 | def _order(self) -> list[str]: | 157 | def _order(self) -> list[str]: |
| 119 | """Sabit sıra + `partial` önceliği (`MODULLER.md` §2.12 adım 3 uyarısı).""" | 158 | """Sabit sıra + `partial` önceliği (`MODULLER.md` §2.12 adım 3 uyarısı).""" |
| 120 | rest = [s for s in self._schools if s not in self._priority] | 159 | rest = [s for s in self._schools if s not in self._priority] |
| @@ -132,25 +171,31 @@ class Scheduler: | |||
| 132 | self._failures = [] | 171 | self._failures = [] |
| 133 | async with self._lock: | 172 | async with self._lock: |
| 134 | partial_now: list[str] = [] | 173 | partial_now: list[str] = [] |
| 174 | + self._schools = await self._listing() | ||
| 135 | for school in self._order(): | 175 | for school in self._order(): |
| 136 | if self._last_run_day.get(school) == day: | 176 | if self._last_run_day.get(school) == day: |
| 137 | continue | 177 | continue |
| 138 | - # Süreç yeniden başladıysa bellek içi `pending` boştur; | 178 | + # Her okul KENDI deposundan yazar: okulun veritabani, |
| 139 | - # devreden liste `insight_run` satırından okunur. | 179 | + # cercevedeki slug'dan cozulur (`tenants.py`). Deposu |
| 140 | - if school not in self._pending: | 180 | + # acilamayan okul dusen okuldur -- tur devam eder, `internal` |
| 141 | - carried = await self._store.last_pending(school) | 181 | + # diye bir seye donusmez. |
| 142 | - if carried: | ||
| 143 | - self._pending[school] = carried | ||
| 144 | - log.info( | ||
| 145 | - "önceki koşudan devralındı: okul=%s bekleyen=%d", | ||
| 146 | - school, | ||
| 147 | - len(carried), | ||
| 148 | - ) | ||
| 149 | try: | 182 | try: |
| 183 | + store = await self._stores.store_for(school) | ||
| 184 | + # Süreç yeniden başladıysa bellek içi `pending` boştur; | ||
| 185 | + # devreden liste `insight_run` satırından okunur. | ||
| 186 | + if school not in self._pending: | ||
| 187 | + carried = await store.last_pending(school) | ||
| 188 | + if carried: | ||
| 189 | + self._pending[school] = carried | ||
| 190 | + log.info( | ||
| 191 | + "önceki koşudan devralındı: okul=%s bekleyen=%d", | ||
| 192 | + school, | ||
| 193 | + len(carried), | ||
| 194 | + ) | ||
| 150 | source = self._source_factory(school) | 195 | source = self._source_factory(school) |
| 151 | result = await run_school( | 196 | result = await run_school( |
| 152 | source, | 197 | source, |
| 153 | - self._store, | 198 | + store, |
| 154 | school, | 199 | school, |
| 155 | now_ms=stamp, | 200 | now_ms=stamp, |
| 156 | term_start_ms=self._term_start_ms, | 201 | term_start_ms=self._term_start_ms, |
| @@ -207,11 +252,11 @@ class Scheduler: | |||
| 207 | stop = stop or asyncio.Event() | 252 | stop = stop or asyncio.Event() |
| 208 | ticks = 0 | 253 | ticks = 0 |
| 209 | log.info( | 254 | log.info( |
| 210 | - "zamanlayıcı açıldı: pencere %02d:00–%02d:00 TR, tik %ds, okul=%d", | 255 | + "zamanlayıcı açıldı: pencere %02d:00–%02d:00 TR, tik %ds, okul filtresi=%s", |
| 211 | WINDOW_START_HOUR, | 256 | WINDOW_START_HOUR, |
| 212 | WINDOW_END_HOUR, | 257 | WINDOW_END_HOUR, |
| 213 | TICK_SECONDS, | 258 | TICK_SECONDS, |
| 214 | - len(self._schools), | 259 | + ",".join(self._only) if self._only else "hepsi (dizinden)", |
| 215 | ) | 260 | ) |
| 216 | while not stop.is_set(): | 261 | while not stop.is_set(): |
| 217 | stamp = self._now() | 262 | stamp = self._now() |
service/src/segment/config.pymodified+36 -8
| @@ -22,6 +22,20 @@ _LEVELS = {"debug": 10, "info": 20, "warn": 30, "error": 40} | |||
| 22 | _active = _LEVELS["info"] | 22 | _active = _LEVELS["info"] |
| 23 | 23 | ||
| 24 | 24 | ||
| 25 | +#: KALDIRILAN LLM adlari. Dolu bulunurlarsa yapilandirma reddedilir: yarim | ||
| 26 | +#: kalan bir adi sessizce yok saymak, operatorun kendi ayar dosyasinin artik | ||
| 27 | +#: okunmadigini fark etmemesi demek olurdu. | ||
| 28 | +ESKI_LLM_ADLARI: tuple[str, ...] = ( | ||
| 29 | + "DEEPSEEK_API_KEY", | ||
| 30 | + "SEGMENT_API_KEY", | ||
| 31 | + "SEGMENT_BASE_URL", | ||
| 32 | + "SEGMENT_MODEL_FLASH", | ||
| 33 | + "SEGMENT_MODEL_PRO", | ||
| 34 | + "SEGMENT_MODEL_REASONER", | ||
| 35 | + "SEGMENT_MODEL_ROLE", | ||
| 36 | +) | ||
| 37 | + | ||
| 38 | + | ||
| 25 | class SegmentConfigError(Exception): | 39 | class SegmentConfigError(Exception): |
| 26 | """Yapilandirma hatasi.""" | 40 | """Yapilandirma hatasi.""" |
| 27 | 41 | ||
| @@ -188,20 +202,34 @@ class SegmentConfig: | |||
| 188 | `root` verilirse tum goreli yollar onun altinda cozulur (depo koku). | 202 | `root` verilirse tum goreli yollar onun altinda cozulur (depo koku). |
| 189 | """ | 203 | """ |
| 190 | cfg = cls() | 204 | cfg = cls() |
| 191 | - cfg.base_url = (_env("SEGMENT_BASE_URL") or _env("LLM_BASE_URL") | 205 | + # --- LLM adlari: TEMIZ KESIM (2026-09-17) -------------------------- |
| 192 | - or cfg.base_url).rstrip("/") | 206 | + # Eski adlar KALDIRILDI: anahtar `LLM_API_KEY`, adres `LLM_BASE_URL`, |
| 193 | - # Anahtar arama sirasi: rag servisindeki desenle ayni (oku, kopyalama). | 207 | + # modeller `LLM_MODEL_FLASH/PRO/REASONER`, rol `LLM_MODEL_ROLE`. |
| 194 | - cfg.api_key = (_env("DEEPSEEK_API_KEY") or _env("LLM_API_KEY") | 208 | + # Bir "eski ad da calissin" dali birakmak "hangi ad kazandi" sorusunu |
| 195 | - or _env("SEGMENT_API_KEY")) | 209 | + # kodun icine tasirdi; onun yerine eski ad gorulunce yapilandirma |
| 210 | + # ACIKCA REDDEDILIR -- sessizce calisan bir kurulum, adi degismemis | ||
| 211 | + # bir operatoru fark ettirmez. | ||
| 212 | + eski = [ad for ad in ESKI_LLM_ADLARI if (os.environ.get(ad) or "").strip()] | ||
| 213 | + if eski: | ||
| 214 | + raise SegmentConfigError( | ||
| 215 | + "su adlar artik DESTEKLENMIYOR: %s. Yeni adlar: LLM_API_KEY, " | ||
| 216 | + "LLM_BASE_URL, LLM_MODEL_FLASH / LLM_MODEL_PRO / " | ||
| 217 | + "LLM_MODEL_REASONER, LLM_MODEL_ROLE." | ||
| 218 | + % ", ".join(eski)) | ||
| 219 | + # Varsayilan adres DeepSeek'tir ama bu bir ZORUNLULUK degildir: | ||
| 220 | + # OpenAI uyumlu her ag gecidi LLM_BASE_URL ile bu hatayi kosturur. | ||
| 221 | + cfg.base_url = (_env("LLM_BASE_URL") or cfg.base_url).rstrip("/") | ||
| 222 | + # Anahtar yoksa anahtar YOKTUR -- sessiz bir varsayilan yoktur. | ||
| 223 | + cfg.api_key = _env("LLM_API_KEY") | ||
| 196 | for role in ("flash", "pro", "reasoner"): | 224 | for role in ("flash", "pro", "reasoner"): |
| 197 | - override = _env(f"SEGMENT_MODEL_{role.upper()}") | 225 | + override = _env(f"LLM_MODEL_{role.upper()}") |
| 198 | if override: | 226 | if override: |
| 199 | cfg.model_ids[role] = override | 227 | cfg.model_ids[role] = override |
| 200 | - role = _env("SEGMENT_MODEL_ROLE") | 228 | + role = _env("LLM_MODEL_ROLE") |
| 201 | if role: | 229 | if role: |
| 202 | if role not in cfg.model_ids: | 230 | if role not in cfg.model_ids: |
| 203 | raise SegmentConfigError( | 231 | raise SegmentConfigError( |
| 204 | - f"SEGMENT_MODEL_ROLE gecersiz: {role!r} " | 232 | + f"LLM_MODEL_ROLE gecersiz: {role!r} " |
| 205 | f"(beklenen: {', '.join(sorted(cfg.model_ids))})") | 233 | f"(beklenen: {', '.join(sorted(cfg.model_ids))})") |
| 206 | cfg.model_role = role | 234 | cfg.model_role = role |
| 207 | 235 | ||
service/src/segment/provider.pymodified+3 -3
| @@ -394,7 +394,7 @@ def cache_key(model: str, system: str | None, prompt: str, temperature: float, | |||
| 394 | class DeepSeekProvider(BaseProvider): | 394 | class DeepSeekProvider(BaseProvider): |
| 395 | """OpenAI-uyumlu `/chat/completions` istemcisi. | 395 | """OpenAI-uyumlu `/chat/completions` istemcisi. |
| 396 | 396 | ||
| 397 | - Anahtar ortamdan (`DEEPSEEK_API_KEY`). Anahtar yokken de ORNEKLENEBILIR; | 397 | + Anahtar ortamdan (`LLM_API_KEY`). Anahtar yokken de ORNEKLENEBILIR; |
| 398 | hata yalnizca gercek cagri aninda yukselir — boylece tum boru hatti | 398 | hata yalnizca gercek cagri aninda yukselir — boylece tum boru hatti |
| 399 | anahtarsiz ithal edilebilir. | 399 | anahtarsiz ithal edilebilir. |
| 400 | """ | 400 | """ |
| @@ -441,7 +441,7 @@ class DeepSeekProvider(BaseProvider): | |||
| 441 | **kw) -> ChatResult: | 441 | **kw) -> ChatResult: |
| 442 | if not self.cfg.api_key: | 442 | if not self.cfg.api_key: |
| 443 | raise ProviderError( | 443 | raise ProviderError( |
| 444 | - "DEEPSEEK_API_KEY tanimsiz. Gercek kosu icin ortama anahtari yaz " | 444 | + "LLM_API_KEY tanimsiz. Gercek kosu icin ortama anahtari yaz " |
| 445 | "ya da MockProvider kullan.") | 445 | "ya da MockProvider kullan.") |
| 446 | payload = self.build_payload(prompt, system, temperature, model, | 446 | payload = self.build_payload(prompt, system, temperature, model, |
| 447 | kind=kind, role=role) | 447 | kind=kind, role=role) |
| @@ -740,7 +740,7 @@ def build_provider(cfg: SegmentConfig, *, mock: bool = False, cache=None, | |||
| 740 | if mock: | 740 | if mock: |
| 741 | return MockProvider(cfg, cache=cache, budget=budget) | 741 | return MockProvider(cfg, cache=cache, budget=budget) |
| 742 | if not cfg.api_key: | 742 | if not cfg.api_key: |
| 743 | - log("warn", "DEEPSEEK_API_KEY yok -> MockProvider'a dusuluyor. " | 743 | + log("warn", "LLM_API_KEY yok -> MockProvider'a dusuluyor. " |
| 744 | "Mock ciktilari GERCEK MODEL KALITESI DEGILDIR.") | 744 | "Mock ciktilari GERCEK MODEL KALITESI DEGILDIR.") |
| 745 | return MockProvider(cfg, cache=cache, budget=budget) | 745 | return MockProvider(cfg, cache=cache, budget=budget) |
| 746 | return DeepSeekProvider(cfg, cache=cache, budget=budget) | 746 | return DeepSeekProvider(cfg, cache=cache, budget=budget) |
service/src/store_factory.pymodified+14 -3
| @@ -36,7 +36,12 @@ def is_postgres() -> bool: | |||
| 36 | 36 | ||
| 37 | 37 | ||
| 38 | async def open_store(dsn: str | None = None) -> tuple[Any, Any]: | 38 | async def open_store(dsn: str | None = None) -> tuple[Any, Any]: |
| 39 | - """Yapilandirmaya gore depoyu acar. | 39 | + """TEK veritabanina baglanir (eski mod / araclar). |
| 40 | + | ||
| 41 | + Coklu okul uretim yolu bu fonksiyon DEGILDIR: `tenants.open_directory` | ||
| 42 | + kontrol veritabanindan okul dizinini kurar ve her okul icin ayri havuz | ||
| 43 | + acar. Burada DSN neyi adlandiriyorsa ona baglanilir -- okul veritabani da | ||
| 44 | + olabilir, kontrol veritabani da; karar cagiranindir. | ||
| 40 | 45 | ||
| 41 | `(store, client)` doner; cagiran taraf isi bitince `client.close()` | 46 | `(store, client)` doner; cagiran taraf isi bitince `client.close()` |
| 42 | cagirmalidir. | 47 | cagirmalidir. |
| @@ -72,9 +77,15 @@ async def open_store(dsn: str | None = None) -> tuple[Any, Any]: | |||
| 72 | 77 | ||
| 73 | 78 | ||
| 74 | def describe() -> str: | 79 | def describe() -> str: |
| 75 | - """Acilista loglanacak tek satir. DSN'in kendisi ASLA loglanmaz.""" | 80 | + """Acilista loglanacak tek satir. DSN'in kendisi ASLA loglanmaz. |
| 81 | + | ||
| 82 | + Doluysa DSN KONTROL veritabanidir; okul ciktilari okul basina ayri | ||
| 83 | + veritabanlarina yazilir (`tenants.py`). Satir bunu soyler. | ||
| 84 | + """ | ||
| 76 | if not is_postgres(): | 85 | if not is_postgres(): |
| 77 | return "depo: SurrealDB (eski kurulum)" | 86 | return "depo: SurrealDB (eski kurulum)" |
| 78 | from .pg_client import _describe | 87 | from .pg_client import _describe |
| 79 | 88 | ||
| 80 | - return "depo: PostgreSQL (%s)" % _describe(os.environ["ZEKA_PG_DSN"]) | 89 | + return "depo: PostgreSQL kontrol (%s) — okullar kendi veritabanlarinda" % _describe( |
| 90 | + os.environ["ZEKA_PG_DSN"] | ||
| 91 | + ) | ||
service/src/tenants.pyadded+557 -0
| @@ -0,0 +1,557 @@ | |||
| 1 | +"""Okul cozumlemesi: slug'dan o okulun veritabanina, ve okul basina havuz. | ||
| 2 | + | ||
| 3 | +--------------------------------------------------------------------------- | ||
| 4 | +NEDEN VAR | ||
| 5 | +--------------------------------------------------------------------------- | ||
| 6 | +`ZEKA_PG_DSN` artik **KONTROL** veritabanini adlandirir. Okulun verisi her | ||
| 7 | +okulun KENDI veritabanindadir ve adi backend'in kendi kuralindan turer | ||
| 8 | +(`hezarfen_backend/src/tenant.rs:111-112`): | ||
| 9 | + | ||
| 10 | + {kontrol_db}_school_{okul_uuid, tiresiz} | ||
| 11 | + | ||
| 12 | +Ad **desenden tahmin edilmez**; slug'i uuid'ye yalnizca kontrol | ||
| 13 | +veritabanindaki `school` satiri cevirir. Satir yoksa istek reddedilir | ||
| 14 | +(`unknown_school`), desene uyan bir veritabani var olsa bile: kutukte olmayan | ||
| 15 | +bir veritabanina yazmak, "hangi okulun verisi bu" sorusunu cevapsiz birakirdi | ||
| 16 | +(`paket/apply_zeka_tables.sh` de tam bu yuzden okullari control'den cozer). | ||
| 17 | + | ||
| 18 | +--------------------------------------------------------------------------- | ||
| 19 | +SINIR NEDEN VAR | ||
| 20 | +--------------------------------------------------------------------------- | ||
| 21 | +Okul sayisi sinirsiz buyur; her okul icin bir baglanti acik tutmak, okul | ||
| 22 | +sayisiyla birlikte Postgres'in baglanti tavanini yakardı. Bu yuzden okul | ||
| 23 | +havuzlari **sinirli** bir onbellekte tutulur: en fazla `max_pools` havuz | ||
| 24 | +(varsayilan 8), her havuz en son kullanimdan `ttl_secs` sonra kapatilir. | ||
| 25 | +Sinir asilinca **en eski kullanilan** havuz kapatilir (LRU). Tavan ve TTL | ||
| 26 | +`ZEKA_MAX_SCHOOL_POOLS` / `ZEKA_SCHOOL_POOL_TTL_SECS` ile ayarlanir. | ||
| 27 | + | ||
| 28 | +--------------------------------------------------------------------------- | ||
| 29 | +HATA SINIFLARI AYRIDIR | ||
| 30 | +--------------------------------------------------------------------------- | ||
| 31 | +`unknown_school` (kutukte yok) ile `school_suspended` (kapatilmis) ve | ||
| 32 | +`school_not_migrated` (veritabani var, `zeka_*` tablolari yok) uc ayri | ||
| 33 | +durumdur ve ayri kodlarla doner: birincisinde yeniden denemek anlamsizdir, | ||
| 34 | +ikincisinde sabretmek gerekir, ucuncusunde operatorun bir sey yapmasi | ||
| 35 | +gerekir. Hicbiri `internal` degildir -- hepsi beklenen redlerdir. | ||
| 36 | + | ||
| 37 | +Kontrol veritabani okunamazsa (ulasilamaz ya da `school` tablosu yok) bu | ||
| 38 | +`TenantError` olarak yukari cikar ve ZAMANLAYICI onu o tik icin "okul yok" | ||
| 39 | +sayar: acilis cokmez, sonraki tik yeniden dener. | ||
| 40 | +""" | ||
| 41 | + | ||
| 42 | +from __future__ import annotations | ||
| 43 | + | ||
| 44 | +import asyncio | ||
| 45 | +import logging | ||
| 46 | +import time | ||
| 47 | +import uuid as uuid_mod | ||
| 48 | +from collections.abc import Awaitable, Callable, Sequence | ||
| 49 | +from dataclasses import dataclass | ||
| 50 | +from typing import Any, NamedTuple, Protocol | ||
| 51 | + | ||
| 52 | +log = logging.getLogger(__name__) | ||
| 53 | + | ||
| 54 | +#: Okul veritabaninda bulunmasi ZORUNLU tablolar. Tek kaynak: | ||
| 55 | +#: `service/schema/postgres/school/20260916000001_zeka.sql` (backend'de | ||
| 56 | +#: `migrations/school/20260917000002_zeka.sql`). `tests/test_tenants.py` bu | ||
| 57 | +#: listeyi DDL dosyasiyla KARSILASTIRIR; biri digerinden kopamaz. | ||
| 58 | +REQUIRED_TABLES: tuple[str, ...] = ( | ||
| 59 | + "zeka_student_summary", | ||
| 60 | + "zeka_attention_item", | ||
| 61 | + "zeka_recommendation", | ||
| 62 | + "zeka_run", | ||
| 63 | + "zeka_run_pending", | ||
| 64 | + "zeka_run_failed_module", | ||
| 65 | + "zeka_question_segment", | ||
| 66 | + "zeka_question_segment_dimension", | ||
| 67 | + "zeka_student_segment_profile", | ||
| 68 | +) | ||
| 69 | + | ||
| 70 | +#: Kontrol okuma: butun kutuk tek sorguda. Okul sayisi binler olsa bile bu | ||
| 71 | +#: tablo kucuktur; `resolve` icin okul basina sorgu atmak N+1 olurdu. | ||
| 72 | +CONTROL_SQL = "SELECT slug, id::text, status FROM school ORDER BY created_at" | ||
| 73 | + | ||
| 74 | +#: Okul veritabaninda hangi zeka tablolari var? `pg_class` uzerinden, cunku | ||
| 75 | +#: SQLSTATE ile "tablo yok" ayrimi tek tabloda kalirdi: 9 tablodan 3'u olan | ||
| 76 | +#: yarim uygulanmis bir veritabani da "migrate edilmemis" sayilmalidir. | ||
| 77 | +SCHOOL_TABLES_SQL = """ | ||
| 78 | +SELECT c.relname | ||
| 79 | + FROM pg_class c | ||
| 80 | + JOIN pg_namespace n ON n.oid = c.relnamespace | ||
| 81 | + WHERE n.nspname = 'public' AND c.relkind = 'r' AND c.relname = ANY(%s) | ||
| 82 | +""" | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +class TenantError(Exception): | ||
| 86 | + """Okul cozumlemesi reddi. | ||
| 87 | + | ||
| 88 | + `code` alanlari backend'in `ApiErrorCode` sozluguyle ayni adlari kullanir | ||
| 89 | + (`ai/server.rs:75-99`); `school` cerceveden gelen slug'dir. | ||
| 90 | + """ | ||
| 91 | + | ||
| 92 | + code = "unavailable" | ||
| 93 | + | ||
| 94 | + def __init__(self, message: str, *, school: str = "") -> None: | ||
| 95 | + super().__init__(message) | ||
| 96 | + self.school = school | ||
| 97 | + | ||
| 98 | + | ||
| 99 | +class UnknownSchool(TenantError): | ||
| 100 | + """Kutukte boyle bir okul yok. Kapali kume: yeniden denemek ogretmez.""" | ||
| 101 | + | ||
| 102 | + code = "unknown_school" | ||
| 103 | + | ||
| 104 | + | ||
| 105 | +class SchoolSuspended(TenantError): | ||
| 106 | + """Okul var ama kapatilmis. Sonradan acilabilir; yeniden denenebilir.""" | ||
| 107 | + | ||
| 108 | + code = "school_suspended" | ||
| 109 | + | ||
| 110 | + | ||
| 111 | +class SchoolDatabaseGone(TenantError): | ||
| 112 | + """Okul kutukte var, veritabani yok ya da baglanilamiyor.""" | ||
| 113 | + | ||
| 114 | + code = "unavailable" | ||
| 115 | + | ||
| 116 | + | ||
| 117 | +class SchoolNotMigrated(TenantError): | ||
| 118 | + """Okul veritabani var ama `zeka_*` tablolarini tasimiyor.""" | ||
| 119 | + | ||
| 120 | + code = "school_not_migrated" | ||
| 121 | + | ||
| 122 | + | ||
| 123 | +@dataclass(frozen=True) | ||
| 124 | +class SchoolRef: | ||
| 125 | + """Kontrol satirinin cozulmus hali: slug, uuid ve durum.""" | ||
| 126 | + | ||
| 127 | + slug: str | ||
| 128 | + id: uuid_mod.UUID | ||
| 129 | + status: str | ||
| 130 | + | ||
| 131 | + | ||
| 132 | +def database_name(control_db: str, school: uuid_mod.UUID | str) -> str: | ||
| 133 | + """`{kontrol}_school_{uuid tiresiz}` -- backend `tenant.rs:111-112`. | ||
| 134 | + | ||
| 135 | + `uuid.simple()` ile ayni bicim: 32 karakter kucuk hex, tiresiz. Gecersiz | ||
| 136 | + bir metin `ValueError` verir; ad UYDURULMAZ. | ||
| 137 | + """ | ||
| 138 | + uid = school if isinstance(school, uuid_mod.UUID) else uuid_mod.UUID(str(school)) | ||
| 139 | + return f"{control_db}_school_{uid.hex}" | ||
| 140 | + | ||
| 141 | + | ||
| 142 | +class SchoolRegistry: | ||
| 143 | + """slug -> [`SchoolRef`]. Kontrol veritabanindan, TTL'li tek sorgu. | ||
| 144 | + | ||
| 145 | + TTL `0` ise her cagri taze okur (testler bunu kullanir); `30s` varsayilan, | ||
| 146 | + cunku yeni okul acmak seyrek bir olaydir ama bayat bir kutukle bir okulu | ||
| 147 | + hic gormemek daha pahalidir. | ||
| 148 | + """ | ||
| 149 | + | ||
| 150 | + def __init__( | ||
| 151 | + self, | ||
| 152 | + client: Any, | ||
| 153 | + *, | ||
| 154 | + ttl_secs: float = 30.0, | ||
| 155 | + clock_fn: Callable[[], float] = time.monotonic, | ||
| 156 | + ) -> None: | ||
| 157 | + self._client = client | ||
| 158 | + self._ttl = float(ttl_secs) | ||
| 159 | + self._clock = clock_fn | ||
| 160 | + self._by_slug: dict[str, SchoolRef] = {} | ||
| 161 | + self._loaded_at: float | None = None | ||
| 162 | + self._queries = 0 | ||
| 163 | + | ||
| 164 | + @property | ||
| 165 | + def queries(self) -> int: | ||
| 166 | + """Kaca kere kontrol veritabani okundu (onbellek kaniti).""" | ||
| 167 | + return self._queries | ||
| 168 | + | ||
| 169 | + def _stale(self) -> bool: | ||
| 170 | + if self._loaded_at is None or self._ttl <= 0: | ||
| 171 | + return True | ||
| 172 | + return (self._clock() - self._loaded_at) > self._ttl | ||
| 173 | + | ||
| 174 | + async def _load(self) -> None: | ||
| 175 | + try: | ||
| 176 | + rows = await self._client.fetch(CONTROL_SQL) | ||
| 177 | + except Exception as exc: # noqa: BLE001 -- yukariya tek tip hata | ||
| 178 | + raise TenantError( | ||
| 179 | + "kontrol veritabani okunamadi (school tablosu var mi?): %s" % exc | ||
| 180 | + ) from exc | ||
| 181 | + table: dict[str, SchoolRef] = {} | ||
| 182 | + for slug, ident, status in rows: | ||
| 183 | + try: | ||
| 184 | + uid = uuid_mod.UUID(str(ident)) | ||
| 185 | + except ValueError: | ||
| 186 | + # Bozuk bir satir butun kutugu dusurmez; ama sessiz de kalmaz. | ||
| 187 | + log.warning("okul satirinin uuid'si cozulemedi, atlandi: %r", slug) | ||
| 188 | + continue | ||
| 189 | + table[str(slug)] = SchoolRef(str(slug), uid, str(status)) | ||
| 190 | + self._by_slug = table | ||
| 191 | + self._loaded_at = self._clock() | ||
| 192 | + self._queries += 1 | ||
| 193 | + | ||
| 194 | + async def _fresh_table(self) -> dict[str, SchoolRef]: | ||
| 195 | + if self._stale(): | ||
| 196 | + await self._load() | ||
| 197 | + return self._by_slug | ||
| 198 | + | ||
| 199 | + async def all_schools(self) -> dict[str, SchoolRef]: | ||
| 200 | + return dict(await self._fresh_table()) | ||
| 201 | + | ||
| 202 | + async def active_schools(self) -> list[str]: | ||
| 203 | + """Islenmeye hazir okullar: durumu `active`, slug sirali.""" | ||
| 204 | + table = await self._fresh_table() | ||
| 205 | + return sorted(slug for slug, ref in table.items() if ref.status == "active") | ||
| 206 | + | ||
| 207 | + async def resolve(self, slug: str) -> SchoolRef: | ||
| 208 | + """Slug'i okula cevir; yoksa/kapatilmissa reddet.""" | ||
| 209 | + table = await self._fresh_table() | ||
| 210 | + ref = table.get(slug) | ||
| 211 | + if ref is None: | ||
| 212 | + raise UnknownSchool( | ||
| 213 | + "bu dagitimda '%s' okulu yok" % slug, school=slug | ||
| 214 | + ) | ||
| 215 | + if ref.status != "active": | ||
| 216 | + raise SchoolSuspended( | ||
| 217 | + "'%s' okulu kapatilmis (durum: %s)" % (slug, ref.status), school=slug | ||
| 218 | + ) | ||
| 219 | + return ref | ||
| 220 | + | ||
| 221 | + | ||
| 222 | +class OpenedSchool(NamedTuple): | ||
| 223 | + """Bir okul havuzunun acilmis hali: depo + onu kapatan kanca.""" | ||
| 224 | + | ||
| 225 | + store: Any | ||
| 226 | + close: Callable[[], Awaitable[None]] | ||
| 227 | + | ||
| 228 | + | ||
| 229 | +#: Okul -> acilmis havuz. `TenantStores` bunu enjekte edilebilir tutar: | ||
| 230 | +#: birim testleri gercek Postgres olmadan tavan/TTL davranisini kosturur. | ||
| 231 | +Opener = Callable[[SchoolRef], Awaitable[OpenedSchool]] | ||
| 232 | + | ||
| 233 | + | ||
| 234 | +class _Held: | ||
| 235 | + """Onbellekteki tek kayit: depo, kapaticisi ve son kullanim damgasi.""" | ||
| 236 | + | ||
| 237 | + __slots__ = ("store", "close", "last_used") | ||
| 238 | + | ||
| 239 | + def __init__(self, store: Any, close: Callable[[], Awaitable[None]], at: float) -> None: | ||
| 240 | + self.store = store | ||
| 241 | + self.close = close | ||
| 242 | + self.last_used = at | ||
| 243 | + | ||
| 244 | + | ||
| 245 | +class Directory(Protocol): | ||
| 246 | + """Servisin okul dizini: hangi okullar var, her birinin deposu hangisi.""" | ||
| 247 | + | ||
| 248 | + async def active_schools(self) -> list[str]: ... | ||
| 249 | + | ||
| 250 | + async def store_for(self, slug: str) -> Any: ... | ||
| 251 | + | ||
| 252 | + async def close(self) -> None: ... | ||
| 253 | + | ||
| 254 | + def describe(self) -> str: ... | ||
| 255 | + | ||
| 256 | + | ||
| 257 | +class TenantStores: | ||
| 258 | + """Sinirli, TTL'li okul havuzu onbellegi. | ||
| 259 | + | ||
| 260 | + `store_for` TEK yol: her okul istegi buradan kendi veritabanini alir. Geri | ||
| 261 | + dusme yoktur -- kontrol veritabaninin kendisi ya da baska bir okul asla | ||
| 262 | + cevap vermez (`unknown_school` doner). | ||
| 263 | + """ | ||
| 264 | + | ||
| 265 | + def __init__( | ||
| 266 | + self, | ||
| 267 | + registry: SchoolRegistry, | ||
| 268 | + opener: Opener, | ||
| 269 | + *, | ||
| 270 | + max_pools: int = 8, | ||
| 271 | + ttl_secs: float = 900.0, | ||
| 272 | + clock_fn: Callable[[], float] = time.monotonic, | ||
| 273 | + teardown: Sequence[Callable[[], Awaitable[None]]] = (), | ||
| 274 | + ) -> None: | ||
| 275 | + self._registry = registry | ||
| 276 | + self._opener = opener | ||
| 277 | + self._max_pools = max(1, int(max_pools)) | ||
| 278 | + self._ttl = float(ttl_secs) | ||
| 279 | + self._clock = clock_fn | ||
| 280 | + self._teardown = list(teardown) | ||
| 281 | + self._entries: dict[str, _Held] = {} | ||
| 282 | + self._lock = asyncio.Lock() | ||
| 283 | + self._opened = 0 | ||
| 284 | + self._evicted = 0 | ||
| 285 | + self._refused = 0 | ||
| 286 | + | ||
| 287 | + def describe(self) -> str: | ||
| 288 | + return ( | ||
| 289 | + "okul dizini: kontrol veritabani (ZEKA_PG_DSN), adlar " | ||
| 290 | + "{kontrol}_school_{uuid}; havuz tavani=%d, havuz TTL=%.0fs, " | ||
| 291 | + "kayit TTL=%.0fs" % (self._max_pools, self._ttl, self._registry._ttl) | ||
| 292 | + ) | ||
| 293 | + | ||
| 294 | + def stats(self) -> dict[str, int]: | ||
| 295 | + """Sayaclar. `atilan`, tavani ve TTL'i asan havuzlarin sayisidir.""" | ||
| 296 | + return { | ||
| 297 | + "acik": len(self._entries), | ||
| 298 | + "tavan": self._max_pools, | ||
| 299 | + "acilan": self._opened, | ||
| 300 | + "atilan": self._evicted, | ||
| 301 | + "reddedilen": self._refused, | ||
| 302 | + } | ||
| 303 | + | ||
| 304 | + async def active_schools(self) -> list[str]: | ||
| 305 | + return await self._registry.active_schools() | ||
| 306 | + | ||
| 307 | + def _expired(self, held: _Held) -> bool: | ||
| 308 | + return self._ttl > 0 and (self._clock() - held.last_used) > self._ttl | ||
| 309 | + | ||
| 310 | + async def _drop(self, slug: str, reason: str) -> None: | ||
| 311 | + held = self._entries.pop(slug, None) | ||
| 312 | + if held is None: | ||
| 313 | + return | ||
| 314 | + self._evicted += 1 | ||
| 315 | + log.info("okul havuzu kapatildi (okul=%s, sebep=%s)", slug, reason) | ||
| 316 | + try: | ||
| 317 | + await held.close() | ||
| 318 | + except Exception as exc: # noqa: BLE001 -- kapatma hatasi turu durdurmaz | ||
| 319 | + log.warning("okul havuzu kapatilamadi (okul=%s): %s", slug, exc) | ||
| 320 | + | ||
| 321 | + async def _make_room(self) -> None: | ||
| 322 | + while len(self._entries) >= self._max_pools: | ||
| 323 | + oldest = min(self._entries.items(), key=lambda item: item[1].last_used) | ||
| 324 | + await self._drop(oldest[0], "tavan") | ||
| 325 | + | ||
| 326 | + async def _open(self, ref: SchoolRef) -> _Held: | ||
| 327 | + try: | ||
| 328 | + opened = await self._opener(ref) | ||
| 329 | + except TenantError: | ||
| 330 | + self._refused += 1 | ||
| 331 | + raise | ||
| 332 | + except Exception as exc: # noqa: BLE001 -- surucu hatasi tek tipe baglanir | ||
| 333 | + self._refused += 1 | ||
| 334 | + raise SchoolDatabaseGone( | ||
| 335 | + "'%s' okulunun veritabani acilamadi: %s" % (ref.slug, exc), | ||
| 336 | + school=ref.slug, | ||
| 337 | + ) from exc | ||
| 338 | + self._opened += 1 | ||
| 339 | + log.info("okul havuzu acildi (okul=%s)", ref.slug) | ||
| 340 | + return _Held(opened.store, opened.close, self._clock()) | ||
| 341 | + | ||
| 342 | + async def store_for(self, slug: str) -> Any: | ||
| 343 | + """Okulun deposu. Kapanmis/taze degilse yeniden acilir. | ||
| 344 | + | ||
| 345 | + Bilinmeyen ya da kapatilmis okul burada reddedilir; acilista degil, | ||
| 346 | + cunku acilisin okul satirina ihtiyaci YOKTUR (kutuk bos olabilir). | ||
| 347 | + """ | ||
| 348 | + held = self._entries.get(slug) | ||
| 349 | + if held is not None: | ||
| 350 | + if not self._expired(held): | ||
| 351 | + held.last_used = self._clock() | ||
| 352 | + return held.store | ||
| 353 | + await self._drop(slug, "ttl") | ||
| 354 | + | ||
| 355 | + try: | ||
| 356 | + ref = await self._registry.resolve(slug) | ||
| 357 | + except TenantError: | ||
| 358 | + # Bilinmeyen/kapatilmis okul da bir reddir; sayaci burada artir. | ||
| 359 | + self._refused += 1 | ||
| 360 | + raise | ||
| 361 | + | ||
| 362 | + async with self._lock: | ||
| 363 | + # Kilidi beklerken baska bir gorev ayni okulu acmis olabilir. | ||
| 364 | + held = self._entries.get(slug) | ||
| 365 | + if held is not None: | ||
| 366 | + held.last_used = self._clock() | ||
| 367 | + return held.store | ||
| 368 | + await self._make_room() | ||
| 369 | + self._entries[slug] = await self._open(ref) | ||
| 370 | + return self._entries[slug].store | ||
| 371 | + | ||
| 372 | + async def close(self) -> None: | ||
| 373 | + """Butun havuzlari ve bu nesnenin sahibi oldugu kaynaklari kapatir.""" | ||
| 374 | + for slug in list(self._entries): | ||
| 375 | + await self._drop(slug, "kapanis") | ||
| 376 | + for closer in self._teardown: | ||
| 377 | + try: | ||
| 378 | + await closer() | ||
| 379 | + except Exception as exc: # noqa: BLE001 | ||
| 380 | + log.warning("dizin kaynagi kapatilamadi: %s", exc) | ||
| 381 | + | ||
| 382 | + | ||
| 383 | +class OneDatabase: | ||
| 384 | + """Eski tek veritabani modu (SurrealDB): butun okullar ayni depoyu paylasir. | ||
| 385 | + | ||
| 386 | + Cozumleme yine kapali kumedir: listede olmayan slug reddedilir -- eski | ||
| 387 | + modda da "bilinmeyen okul" diye bir sey vardir, yalnizca kaynagi kontrol | ||
| 388 | + veritabani degil, yapilandirmadir (`ZEKA_SCHOOLS`). | ||
| 389 | + """ | ||
| 390 | + | ||
| 391 | + def __init__( | ||
| 392 | + self, | ||
| 393 | + store: Any, | ||
| 394 | + schools: Sequence[str], | ||
| 395 | + *, | ||
| 396 | + teardown: Sequence[Callable[[], Awaitable[None]]] = (), | ||
| 397 | + ) -> None: | ||
| 398 | + self._store = store | ||
| 399 | + self._schools = sorted({str(s) for s in schools if str(s).strip()}) | ||
| 400 | + self._teardown = list(teardown) | ||
| 401 | + | ||
| 402 | + def describe(self) -> str: | ||
| 403 | + return ( | ||
| 404 | + "okul dizini: tek veritabani (eski SurrealDB modu), okullar " | ||
| 405 | + "ZEKA_SCHOOLS'ten (%d)" % len(self._schools) | ||
| 406 | + ) | ||
| 407 | + | ||
| 408 | + async def active_schools(self) -> list[str]: | ||
| 409 | + return list(self._schools) | ||
| 410 | + | ||
| 411 | + async def store_for(self, slug: str) -> Any: | ||
| 412 | + if slug not in self._schools: | ||
| 413 | + raise UnknownSchool( | ||
| 414 | + "bu servis '%s' okulunu islemiyor (ZEKA_SCHOOLS)" % slug, school=slug | ||
| 415 | + ) | ||
| 416 | + return self._store | ||
| 417 | + | ||
| 418 | + async def close(self) -> None: | ||
| 419 | + for closer in self._teardown: | ||
| 420 | + try: | ||
| 421 | + await closer() | ||
| 422 | + except Exception as exc: # noqa: BLE001 | ||
| 423 | + log.warning("dizin kaynagi kapatilamadi: %s", exc) | ||
| 424 | + | ||
| 425 | + | ||
| 426 | +# --- Postgres tarafi ------------------------------------------------------- | ||
| 427 | + | ||
| 428 | + | ||
| 429 | +def school_dsn(control_dsn: str, database: str) -> str: | ||
| 430 | + """Kontrol DSN'inin AYNI sunucusunda, veritabani adi degistirilmis DSN. | ||
| 431 | + | ||
| 432 | + Backend de boyle yapar (`database.rs:130` `school_pool`): kontrol ile okul | ||
| 433 | + veritabanlari ayni Postgres sunucusundadir, degisen tek sey `dbname`dir. | ||
| 434 | + Kullanici/parola kontrol DSN'inden gelir; okul basina sir TUTULMAZ. | ||
| 435 | + """ | ||
| 436 | + import psycopg.conninfo | ||
| 437 | + | ||
| 438 | + parts = psycopg.conninfo.conninfo_to_dict(control_dsn) | ||
| 439 | + parts["dbname"] = database | ||
| 440 | + return psycopg.conninfo.make_conninfo(**parts) | ||
| 441 | + | ||
| 442 | + | ||
| 443 | +async def control_database(client: Any) -> str: | ||
| 444 | + """Kontrol veritabaninin GERCEK adi. | ||
| 445 | + | ||
| 446 | + DSN'i elle ayristirmak yerine sunucuya sorulur: URL bicimi de anahtar=deger | ||
| 447 | + bicimi de ayni cevabi verir, `dbname` yazilmamissa da dogru kalir. | ||
| 448 | + """ | ||
| 449 | + rows = await client.fetch("SELECT current_database()") | ||
| 450 | + if not rows: | ||
| 451 | + raise TenantError("kontrol veritabaninin adi ogrenilemedi") | ||
| 452 | + return str(rows[0][0]) | ||
| 453 | + | ||
| 454 | + | ||
| 455 | +async def verify_school_schema(client: Any, ref: SchoolRef) -> None: | ||
| 456 | + """Okul veritabani `zeka_*` tablolarini tasiyor mu? | ||
| 457 | + | ||
| 458 | + Ayri bir hata tipiyle reddedilir (`school_not_migrated`): veritabani | ||
| 459 | + vardir, baglanti kurulmustur, eksik olan YALNIZCA semadir. Eksikler | ||
| 460 | + adiyla soylenir; hangi DDL'in uygulanacagi da mesajdadir. | ||
| 461 | + """ | ||
| 462 | + rows = await client.fetch(SCHOOL_TABLES_SQL, [list(REQUIRED_TABLES)]) | ||
| 463 | + found = {str(row[0]) for row in rows} | ||
| 464 | + missing = [name for name in REQUIRED_TABLES if name not in found] | ||
| 465 | + if missing: | ||
| 466 | + raise SchoolNotMigrated( | ||
| 467 | + "'%s' okulunun veritabani zeka tablolarini tasimiyor: %d/%d eksik " | ||
| 468 | + "(%s). Veritabanina " | ||
| 469 | + "service/schema/postgres/school/20260916000001_zeka.sql " | ||
| 470 | + "uygulanmalidir." % (ref.slug, len(missing), len(REQUIRED_TABLES), ", ".join(missing)), | ||
| 471 | + school=ref.slug, | ||
| 472 | + ) | ||
| 473 | + | ||
| 474 | + | ||
| 475 | +def postgres_opener( | ||
| 476 | + control_dsn: str, | ||
| 477 | + control_db: str, | ||
| 478 | + *, | ||
| 479 | + connect_timeout_secs: float = 10.0, | ||
| 480 | +) -> Opener: | ||
| 481 | + """Okul havuzlarini acan kanca: DSN turetir, semayi dogrular.""" | ||
| 482 | + | ||
| 483 | + async def open_school(ref: SchoolRef) -> OpenedSchool: | ||
| 484 | + from .pg_client import PsycopgClient | ||
| 485 | + from .store_pg import PgStore | ||
| 486 | + | ||
| 487 | + dsn = school_dsn(control_dsn, database_name(control_db, ref.id)) | ||
| 488 | + client = await PsycopgClient.connect(dsn, connect_timeout=connect_timeout_secs) | ||
| 489 | + try: | ||
| 490 | + await verify_school_schema(client, ref) | ||
| 491 | + except Exception: | ||
| 492 | + await client.close() | ||
| 493 | + raise | ||
| 494 | + log.info( | ||
| 495 | + "okul veritabanina baglanildi (okul=%s, veritabani=%s)", | ||
| 496 | + ref.slug, | ||
| 497 | + database_name(control_db, ref.id), | ||
| 498 | + ) | ||
| 499 | + return OpenedSchool(PgStore(client), client.close) | ||
| 500 | + | ||
| 501 | + return open_school | ||
| 502 | + | ||
| 503 | + | ||
| 504 | +async def open_postgres( | ||
| 505 | + dsn: str, | ||
| 506 | + *, | ||
| 507 | + max_pools: int = 8, | ||
| 508 | + pool_ttl_secs: float = 900.0, | ||
| 509 | + registry_ttl_secs: float = 30.0, | ||
| 510 | + connect_timeout_secs: float = 10.0, | ||
| 511 | + clock_fn: Callable[[], float] = time.monotonic, | ||
| 512 | +) -> TenantStores: | ||
| 513 | + """Kontrol veritabanina baglan ve sinirli okul dizinini kur. | ||
| 514 | + | ||
| 515 | + Acilista kutuk OKUNMAZ: kontrol baglantisi kurulur, veritabaninin kendi | ||
| 516 | + adi ogrenilir ve biter. Okul satiri olmayan bir kurulum bu yuzden SORUNSUZ | ||
| 517 | + acilir; eksik okul veritabani da acilisi degil, o okulun istegini dusurur. | ||
| 518 | + """ | ||
| 519 | + from .pg_client import PsycopgClient | ||
| 520 | + | ||
| 521 | + client = await PsycopgClient.connect(dsn, connect_timeout=connect_timeout_secs) | ||
| 522 | + try: | ||
| 523 | + control_db = await control_database(client) | ||
| 524 | + except Exception: | ||
| 525 | + await client.close() | ||
| 526 | + raise | ||
| 527 | + registry = SchoolRegistry(client, ttl_secs=registry_ttl_secs, clock_fn=clock_fn) | ||
| 528 | + return TenantStores( | ||
| 529 | + registry, | ||
| 530 | + postgres_opener(dsn, control_db, connect_timeout_secs=connect_timeout_secs), | ||
| 531 | + max_pools=max_pools, | ||
| 532 | + ttl_secs=pool_ttl_secs, | ||
| 533 | + clock_fn=clock_fn, | ||
| 534 | + teardown=[client.close], | ||
| 535 | + ) | ||
| 536 | + | ||
| 537 | + | ||
| 538 | +async def open_directory(settings: Any) -> Directory: | ||
| 539 | + """Acilista servisin okul dizinini kurar. | ||
| 540 | + | ||
| 541 | + `ZEKA_PG_DSN` doluysa kontrol tabanli sinirli havuzlar; bos ise eski tek | ||
| 542 | + veritabani modu (okul listesi `ZEKA_SCHOOLS`). | ||
| 543 | + """ | ||
| 544 | + from . import store_factory | ||
| 545 | + | ||
| 546 | + if store_factory.is_postgres(): | ||
| 547 | + import os | ||
| 548 | + | ||
| 549 | + return await open_postgres( | ||
| 550 | + os.environ.get("ZEKA_PG_DSN", "").strip(), | ||
| 551 | + max_pools=settings.max_school_pools, | ||
| 552 | + pool_ttl_secs=settings.school_pool_ttl_secs, | ||
| 553 | + registry_ttl_secs=settings.school_registry_ttl_secs, | ||
| 554 | + connect_timeout_secs=settings.school_connect_timeout_secs, | ||
| 555 | + ) | ||
| 556 | + store, client = await store_factory.open_store() | ||
| 557 | + return OneDatabase(store, settings.schools, teardown=[client.close]) | ||
service/tests/test_config.pymodified+21 -0
| @@ -25,6 +25,10 @@ _CLEARED = { | |||
| 25 | "ZEKA_STUDENT_FILE", | 25 | "ZEKA_STUDENT_FILE", |
| 26 | "ZEKA_SOURCE", | 26 | "ZEKA_SOURCE", |
| 27 | "ZEKA_DB_PASSWORD", | 27 | "ZEKA_DB_PASSWORD", |
| 28 | + "ZEKA_MAX_SCHOOL_POOLS", | ||
| 29 | + "ZEKA_SCHOOL_POOL_TTL_SECS", | ||
| 30 | + "ZEKA_SCHOOL_REGISTRY_TTL_SECS", | ||
| 31 | + "ZEKA_SCHOOL_CONNECT_TIMEOUT_SECS", | ||
| 28 | ) | 32 | ) |
| 29 | } | 33 | } |
| 30 | 34 | ||
| @@ -95,6 +99,23 @@ class ParsingTests(unittest.TestCase): | |||
| 95 | with self.assertRaises(config.ConfigError): | 99 | with self.assertRaises(config.ConfigError): |
| 96 | config.Config() | 100 | config.Config() |
| 97 | 101 | ||
| 102 | + def test_no_school_list_means_every_school(self): | ||
| 103 | + # Okul listesi artik kontrol veritabanindan gelir; buradaki degisken | ||
| 104 | + # yalnizca bir FILTREdir. Sabit bir varsayilan okul olmamali. | ||
| 105 | + with _env(AI_SHARED_TOKEN="t", ZEKA_SCHOOLS=""): | ||
| 106 | + self.assertEqual(config.Config().schools, ()) | ||
| 107 | + | ||
| 108 | + def test_school_pool_knobs_are_parsed_and_bounded(self): | ||
| 109 | + with _env(AI_SHARED_TOKEN="t", ZEKA_MAX_SCHOOL_POOLS="3", ZEKA_SCHOOL_POOL_TTL_SECS="60"): | ||
| 110 | + settings = config.Config() | ||
| 111 | + self.assertEqual(settings.max_school_pools, 3) | ||
| 112 | + self.assertEqual(settings.school_pool_ttl_secs, 60.0) | ||
| 113 | + self.assertEqual(settings.school_registry_ttl_secs, 30.0) | ||
| 114 | + self.assertEqual(settings.school_connect_timeout_secs, 10.0) | ||
| 115 | + with _env(ZEKA_MAX_SCHOOL_POOLS="0"): | ||
| 116 | + with self.assertRaises(config.ConfigError): | ||
| 117 | + config.Config(require_token=False) | ||
| 118 | + | ||
| 98 | def test_defaults_are_the_documented_ones(self): | 119 | def test_defaults_are_the_documented_ones(self): |
| 99 | with _env(AI_SHARED_TOKEN="t"): | 120 | with _env(AI_SHARED_TOKEN="t"): |
| 100 | settings = config.Config() | 121 | settings = config.Config() |
service/tests/test_scheduler.pymodified+101 -8
| @@ -24,6 +24,7 @@ from src.compute import clock | |||
| 24 | from src.scheduler import WINDOW_END_HOUR, WINDOW_START_HOUR, Scheduler, in_window | 24 | from src.scheduler import WINDOW_END_HOUR, WINDOW_START_HOUR, Scheduler, in_window |
| 25 | from src.source import FileSource | 25 | from src.source import FileSource |
| 26 | from src.store import CollectingClient, Store | 26 | from src.store import CollectingClient, Store |
| 27 | +from src.tenants import OneDatabase, SchoolDatabaseGone, TenantError | ||
| 27 | 28 | ||
| 28 | from .fakes import FakeSource | 29 | from .fakes import FakeSource |
| 29 | from .zeka_db import ( | 30 | from .zeka_db import ( |
| @@ -69,8 +70,7 @@ def make_scheduler(data_by_school: dict[str, dict], **kw) -> tuple[Scheduler, St | |||
| 69 | 70 | ||
| 70 | scheduler = Scheduler( | 71 | scheduler = Scheduler( |
| 71 | factory, | 72 | factory, |
| 72 | - store, | 73 | + OneDatabase(store, list(data_by_school)), |
| 73 | - list(data_by_school), | ||
| 74 | term_start_ms=TERM_START, | 74 | term_start_ms=TERM_START, |
| 75 | clock_fn=lambda: NOW, | 75 | clock_fn=lambda: NOW, |
| 76 | **kw, | 76 | **kw, |
| @@ -227,8 +227,7 @@ class TestServeTestMode(unittest.IsolatedAsyncioTestCase): | |||
| 227 | store = Store(CollectingClient()) | 227 | store = Store(CollectingClient()) |
| 228 | scheduler = Scheduler( | 228 | scheduler = Scheduler( |
| 229 | lambda school: FakeSource(data[school]), | 229 | lambda school: FakeSource(data[school]), |
| 230 | - store, | 230 | + OneDatabase(store, list(data)), |
| 231 | - list(data), | ||
| 232 | clock_fn=lambda: noon, | 231 | clock_fn=lambda: noon, |
| 233 | ) | 232 | ) |
| 234 | await scheduler.serve(tick_seconds=0.001, max_ticks=2) | 233 | await scheduler.serve(tick_seconds=0.001, max_ticks=2) |
| @@ -271,8 +270,7 @@ class TestFullCycleAgainstSurreal(unittest.IsolatedAsyncioTestCase): | |||
| 271 | def _scheduler(self, **kw) -> Scheduler: | 270 | def _scheduler(self, **kw) -> Scheduler: |
| 272 | return Scheduler( | 271 | return Scheduler( |
| 273 | lambda school: FileSource(self.root), | 272 | lambda school: FileSource(self.root), |
| 274 | - self.store, | 273 | + OneDatabase(self.store, self.schools), |
| 275 | - self.schools, | ||
| 276 | term_start_ms=TERM_START, | 274 | term_start_ms=TERM_START, |
| 277 | clock_fn=lambda: NOW, | 275 | clock_fn=lambda: NOW, |
| 278 | **kw, | 276 | **kw, |
| @@ -357,8 +355,7 @@ class TestFullCycleAgainstSurreal(unittest.IsolatedAsyncioTestCase): | |||
| 357 | 355 | ||
| 358 | scheduler = Scheduler( | 356 | scheduler = Scheduler( |
| 359 | factory, | 357 | factory, |
| 360 | - self.store, | 358 | + OneDatabase(self.store, self.schools), |
| 361 | - self.schools, | ||
| 362 | term_start_ms=TERM_START, | 359 | term_start_ms=TERM_START, |
| 363 | clock_fn=lambda: NOW, | 360 | clock_fn=lambda: NOW, |
| 364 | ) | 361 | ) |
| @@ -408,5 +405,101 @@ class TestFullCycleAgainstSurreal(unittest.IsolatedAsyncioTestCase): | |||
| 408 | self.assertEqual(count_rows(self.client, "student_summary"), before) | 405 | self.assertEqual(count_rows(self.client, "student_summary"), before) |
| 409 | 406 | ||
| 410 | 407 | ||
| 408 | +class DirectoryDrivenTests(unittest.IsolatedAsyncioTestCase): | ||
| 409 | + """Okul listesi YAPILANDIRMADAN degil, dizinden gelir. | ||
| 410 | + | ||
| 411 | + Eskiden okullar kurucuya liste olarak veriliyordu ve tek bir `store` | ||
| 412 | + paylasiliyordu; cok okullu sekilde okulun kimligi cerceveden/dizinden | ||
| 413 | + gelir, depo da okul basina cozulur. Bu sinif o donusu pinler. | ||
| 414 | + """ | ||
| 415 | + | ||
| 416 | + def _store(self): | ||
| 417 | + return Store(CollectingClient()) | ||
| 418 | + | ||
| 419 | + async def test_the_tick_runs_exactly_what_the_directory_reports(self): | ||
| 420 | + store = self._store() | ||
| 421 | + data = {"a-okul": dataset(2), "b-okul": dataset(2)} | ||
| 422 | + | ||
| 423 | + class Directory: | ||
| 424 | + def __init__(self, schools): | ||
| 425 | + self.schools = list(schools) | ||
| 426 | + | ||
| 427 | + async def active_schools(self): | ||
| 428 | + return list(self.schools) | ||
| 429 | + | ||
| 430 | + async def store_for(self, slug): | ||
| 431 | + if slug not in self.schools: | ||
| 432 | + raise TenantError("yok", school=slug) | ||
| 433 | + return store | ||
| 434 | + | ||
| 435 | + async def close(self): | ||
| 436 | + return None | ||
| 437 | + | ||
| 438 | + def describe(self): | ||
| 439 | + return "test dizini" | ||
| 440 | + | ||
| 441 | + directory = Directory(["a-okul"]) | ||
| 442 | + scheduler = Scheduler( | ||
| 443 | + lambda school: FakeSource(data[school]), | ||
| 444 | + directory, | ||
| 445 | + term_start_ms=TERM_START, | ||
| 446 | + clock_fn=lambda: NOW, | ||
| 447 | + ) | ||
| 448 | + self.assertEqual([r.school for r in await scheduler.run_once(NOW)], ["a-okul"]) | ||
| 449 | + | ||
| 450 | + # Dizin okul eklerse surec YENIDEN BASLATILMADAN onu da gorur. | ||
| 451 | + directory.schools.append("b-okul") | ||
| 452 | + self.assertEqual([r.school for r in await scheduler.run_once(NOW)], ["b-okul"]) | ||
| 453 | + | ||
| 454 | + async def test_an_unreadable_directory_leaves_the_tick_empty_not_failed(self): | ||
| 455 | + class Broken: | ||
| 456 | + async def active_schools(self): | ||
| 457 | + raise TenantError('relation "school" does not exist') | ||
| 458 | + | ||
| 459 | + async def store_for(self, slug): | ||
| 460 | + raise AssertionError("okul listesi yokken depo cozulmemeli") | ||
| 461 | + | ||
| 462 | + async def close(self): | ||
| 463 | + return None | ||
| 464 | + | ||
| 465 | + def describe(self): | ||
| 466 | + return "test dizini" | ||
| 467 | + | ||
| 468 | + scheduler = Scheduler( | ||
| 469 | + lambda school: FakeSource({}), Broken(), clock_fn=lambda: NOW | ||
| 470 | + ) | ||
| 471 | + self.assertEqual(await scheduler.run_once(NOW), []) | ||
| 472 | + self.assertEqual(scheduler._failures, []) | ||
| 473 | + | ||
| 474 | + async def test_a_school_whose_store_cannot_open_fails_alone(self): | ||
| 475 | + store = self._store() | ||
| 476 | + data = {"b-okul": dataset(2)} | ||
| 477 | + | ||
| 478 | + class Directory: | ||
| 479 | + async def active_schools(self): | ||
| 480 | + return ["a-okul", "b-okul"] | ||
| 481 | + | ||
| 482 | + async def store_for(self, slug): | ||
| 483 | + if slug == "a-okul": | ||
| 484 | + raise SchoolDatabaseGone("veritabani yok", school=slug) | ||
| 485 | + return store | ||
| 486 | + | ||
| 487 | + async def close(self): | ||
| 488 | + return None | ||
| 489 | + | ||
| 490 | + def describe(self): | ||
| 491 | + return "test dizini" | ||
| 492 | + | ||
| 493 | + scheduler = Scheduler( | ||
| 494 | + lambda school: FakeSource(data[school]), | ||
| 495 | + Directory(), | ||
| 496 | + term_start_ms=TERM_START, | ||
| 497 | + clock_fn=lambda: NOW, | ||
| 498 | + ) | ||
| 499 | + results = await scheduler.run_once(NOW) | ||
| 500 | + self.assertEqual([r.school for r in results], ["b-okul"]) | ||
| 501 | + self.assertEqual(scheduler._failures, ["a-okul"]) | ||
| 502 | + | ||
| 503 | + | ||
| 411 | if __name__ == "__main__": | 504 | if __name__ == "__main__": |
| 412 | unittest.main() | 505 | unittest.main() |
service/tests/test_segment_config.pyadded+104 -0
| @@ -0,0 +1,104 @@ | |||
| 1 | +"""Segment hattinin LLM yapilandirma adlari (`src/segment/config.py`). | ||
| 2 | + | ||
| 3 | +TEK AD KURALI (2026-09-17 temiz kesim): `LLM_API_KEY`, `LLM_BASE_URL`, | ||
| 4 | +`LLM_MODEL_FLASH/PRO/REASONER`, `LLM_MODEL_ROLE`. Eski adlar (DEEPSEEK_API_KEY, | ||
| 5 | +SEGMENT_API_KEY, SEGMENT_BASE_URL, SEGMENT_MODEL_*) DESTEKLENMEZ ve dolu | ||
| 6 | +bulunurlarsa yapilandirma REDDEDILIR -- "yarim kalan bir adi sessizce yok | ||
| 7 | +saymak", operatorun kendi dosyasinin artik okunmadigini fark etmemesi olurdu. | ||
| 8 | +""" | ||
| 9 | + | ||
| 10 | +from __future__ import annotations | ||
| 11 | + | ||
| 12 | +import os | ||
| 13 | +import unittest | ||
| 14 | +from unittest import mock | ||
| 15 | + | ||
| 16 | +from src.segment.config import ESKI_LLM_ADLARI, SegmentConfig, SegmentConfigError | ||
| 17 | +from src.segment.provider import build_provider | ||
| 18 | + | ||
| 19 | +#: LLM ile ilgili butun adlar: testleri makinenin ortamindan yalitir. | ||
| 20 | +_CLEARED = { | ||
| 21 | + name: "" | ||
| 22 | + for name in ( | ||
| 23 | + "LLM_API_KEY", | ||
| 24 | + "LLM_BASE_URL", | ||
| 25 | + "LLM_MODEL_FLASH", | ||
| 26 | + "LLM_MODEL_PRO", | ||
| 27 | + "LLM_MODEL_REASONER", | ||
| 28 | + "LLM_MODEL_ROLE", | ||
| 29 | + ) | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +def _env(**overrides): | ||
| 34 | + values = dict(_CLEARED) | ||
| 35 | + values.update(overrides) | ||
| 36 | + return mock.patch.dict(os.environ, values, clear=False) | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +class CleanBreakTests(unittest.TestCase): | ||
| 40 | + def test_the_new_names_work(self): | ||
| 41 | + with _env(LLM_API_KEY="anahtar", LLM_BASE_URL="https://gecit.ornek/v1"): | ||
| 42 | + cfg = SegmentConfig.from_env() | ||
| 43 | + self.assertEqual(cfg.api_key, "anahtar") | ||
| 44 | + self.assertEqual(cfg.base_url, "https://gecit.ornek/v1") | ||
| 45 | + | ||
| 46 | + def test_every_removed_name_is_refused(self): | ||
| 47 | + for eski in ESKI_LLM_ADLARI: | ||
| 48 | + with self.subTest(eski=eski): | ||
| 49 | + with _env(**{eski: "deger"}): | ||
| 50 | + with self.assertRaises(SegmentConfigError) as caught: | ||
| 51 | + SegmentConfig.from_env() | ||
| 52 | + self.assertIn(eski, str(caught.exception)) | ||
| 53 | + self.assertIn("LLM_API_KEY", str(caught.exception)) | ||
| 54 | + | ||
| 55 | + def test_the_old_key_does_not_silently_work(self): | ||
| 56 | + # Kanit: eski ad tek basina ne anahtari doldurur ne de sessiz gecer. | ||
| 57 | + with _env(DEEPSEEK_API_KEY="eski-anahtar"): | ||
| 58 | + with self.assertRaises(SegmentConfigError): | ||
| 59 | + SegmentConfig.from_env() | ||
| 60 | + | ||
| 61 | + def test_a_mixed_environment_is_refused_too(self): | ||
| 62 | + # Yeni ad verilmis olsa bile eski ad duruyorsa ortam TEMIZ DEGILDIR. | ||
| 63 | + with _env(LLM_API_KEY="anahtar", DEEPSEEK_API_KEY="eski"): | ||
| 64 | + with self.assertRaises(SegmentConfigError): | ||
| 65 | + SegmentConfig.from_env() | ||
| 66 | + | ||
| 67 | + def test_no_key_at_all_means_no_key(self): | ||
| 68 | + with _env(): | ||
| 69 | + self.assertFalse(SegmentConfig.from_env().api_key) | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +class ModelKnobTests(unittest.TestCase): | ||
| 73 | + def test_per_role_model_overrides(self): | ||
| 74 | + with _env(LLM_MODEL_FLASH="gpt-x-mini", LLM_MODEL_PRO="gpt-x"): | ||
| 75 | + cfg = SegmentConfig.from_env() | ||
| 76 | + self.assertEqual(cfg.model_ids["flash"], "gpt-x-mini") | ||
| 77 | + self.assertEqual(cfg.model_ids["pro"], "gpt-x") | ||
| 78 | + | ||
| 79 | + def test_role_selection_is_validated(self): | ||
| 80 | + with _env(LLM_MODEL_ROLE="yok-boyle-rol"): | ||
| 81 | + with self.assertRaises(SegmentConfigError): | ||
| 82 | + SegmentConfig.from_env() | ||
| 83 | + with _env(LLM_MODEL_ROLE="pro"): | ||
| 84 | + self.assertEqual(SegmentConfig.from_env().model_role, "pro") | ||
| 85 | + | ||
| 86 | + | ||
| 87 | +class GatewayTests(unittest.TestCase): | ||
| 88 | + def test_the_default_gateway_can_be_replaced(self): | ||
| 89 | + with _env(): | ||
| 90 | + self.assertEqual(SegmentConfig.from_env().base_url, "https://api.deepseek.com") | ||
| 91 | + | ||
| 92 | + def test_a_base_url_without_a_key_never_selects_a_real_gateway(self): | ||
| 93 | + with _env(LLM_BASE_URL="https://gecit.ornek/v1", LLM_API_KEY=""): | ||
| 94 | + cfg = SegmentConfig.from_env() | ||
| 95 | + self.assertFalse(cfg.api_key) | ||
| 96 | + self.assertEqual(build_provider(cfg, mock=False).name, "mock") | ||
| 97 | + | ||
| 98 | + def test_a_key_selects_the_real_gateway(self): | ||
| 99 | + with _env(LLM_API_KEY="anahtar", LLM_BASE_URL="https://gecit.ornek/v1"): | ||
| 100 | + self.assertNotEqual(build_provider(SegmentConfig.from_env(), mock=False).name, "mock") | ||
| 101 | + | ||
| 102 | + | ||
| 103 | +if __name__ == "__main__": | ||
| 104 | + unittest.main() | ||
service/tests/test_segment_provider.pymodified+1 -1
| @@ -452,7 +452,7 @@ class TestDeepSeekProvider(unittest.TestCase): | |||
| 452 | p = DeepSeekProvider(c, budget=BudgetGuard(10.0), sleep=lambda _s: None) | 452 | p = DeepSeekProvider(c, budget=BudgetGuard(10.0), sleep=lambda _s: None) |
| 453 | with self.assertRaises(ProviderError) as ctx: | 453 | with self.assertRaises(ProviderError) as ctx: |
| 454 | p.chat("x") | 454 | p.chat("x") |
| 455 | - self.assertIn("DEEPSEEK_API_KEY", str(ctx.exception)) | 455 | + self.assertIn("LLM_API_KEY", str(ctx.exception)) |
| 456 | 456 | ||
| 457 | def test_anahtar_yoksa_build_provider_mocka_duser(self): | 457 | def test_anahtar_yoksa_build_provider_mocka_duser(self): |
| 458 | p = build_provider(cfg(api_key=None), mock=False) | 458 | p = build_provider(cfg(api_key=None), mock=False) |
service/tests/test_tenants.pyadded+612 -0
| @@ -0,0 +1,612 @@ | |||
| 1 | +"""Okul cozumlemesi (`tenants.py`) testleri. | ||
| 2 | + | ||
| 3 | +Iki katman vardir ve ikisi AYRI isler: | ||
| 4 | + | ||
| 5 | +1. **Birim** (bu dosyanin cogu, bagimliliksiz): ad kurali, kayit onbellegi, | ||
| 6 | + havuz tavani/TTL'i, bilinmeyen okulun reddi. Sahte kontrol istemcisi ve | ||
| 7 | + sahte `opener` ile kosar -- gercek veritabani gerekmez, CI'da da kosar. | ||
| 8 | +2. **Entegrasyon** (`ZEKA_TEST_PG_DSN` verilirse): gercek Postgres'te iki | ||
| 9 | + okul veritabani acar, satirlarin birbirine SIZMADIGINI, eksik veritabani | ||
| 10 | + ve migrate edilmemis veritabani hatalarinin AYRI oldugunu olcer. Degisken | ||
| 11 | + yoksa atlanir; birim testleri etkilenmez. | ||
| 12 | + | ||
| 13 | +`ZEKA_TEST_PG_DSN` BILEREK ayri bir degiskendir: `ZEKA_PG_DSN` uretim | ||
| 14 | +kontrol veritabanini gosterebilir ve bu testler veritabani ACAR/SILER. | ||
| 15 | +""" | ||
| 16 | + | ||
| 17 | +from __future__ import annotations | ||
| 18 | + | ||
| 19 | +import asyncio | ||
| 20 | +import os | ||
| 21 | +import sys | ||
| 22 | +import unittest | ||
| 23 | +import uuid | ||
| 24 | +from pathlib import Path | ||
| 25 | + | ||
| 26 | +from src import capabilities, tenants | ||
| 27 | +from src.tenants import ( | ||
| 28 | + OneDatabase, | ||
| 29 | + OpenedSchool, | ||
| 30 | + SchoolNotMigrated, | ||
| 31 | + SchoolRegistry, | ||
| 32 | + SchoolSuspended, | ||
| 33 | + TenantError, | ||
| 34 | + TenantStores, | ||
| 35 | + UnknownSchool, | ||
| 36 | + database_name, | ||
| 37 | +) | ||
| 38 | + | ||
| 39 | +REPO = Path(__file__).resolve().parents[2] | ||
| 40 | +DDL = REPO / "service" / "schema" / "postgres" / "school" / "20260916000001_zeka.sql" | ||
| 41 | + | ||
| 42 | +#: Sabit uuid'ler: hangi okulun hangi veritabani oldugu hata ciktisinda belli | ||
| 43 | +#: olsun (`backend tenant.rs:111-112` deseninin bekledigi bicim). | ||
| 44 | +SCHOOL_A = "01930000-0000-7000-8000-0000000000a1" | ||
| 45 | +SCHOOL_B = "01930000-0000-7000-8000-0000000000b2" | ||
| 46 | +SCHOOL_C = "01930000-0000-7000-8000-0000000000c3" | ||
| 47 | +STUDENT_A = "01930000-0000-7000-8000-0000000000d1" | ||
| 48 | +STUDENT_B = "01930000-0000-7000-8000-0000000000d2" | ||
| 49 | +CONTROL = "hezarfen_control" | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +class _Clock: | ||
| 53 | + """Deterministik saat: TTL sinirlari duvar saatine bagli kalmasin.""" | ||
| 54 | + | ||
| 55 | + def __init__(self, value: float = 1000.0) -> None: | ||
| 56 | + self.value = value | ||
| 57 | + | ||
| 58 | + def __call__(self) -> float: | ||
| 59 | + return self.value | ||
| 60 | + | ||
| 61 | + def advance(self, seconds: float) -> None: | ||
| 62 | + self.value += seconds | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +class _FakeControl: | ||
| 66 | + """`school` tablosunun tek sorgusunu (CONTROL_SQL) taklit eder.""" | ||
| 67 | + | ||
| 68 | + def __init__(self, rows: list[tuple[str, str, str]] | None = None) -> None: | ||
| 69 | + self.rows = list(rows or []) | ||
| 70 | + self.queries = 0 | ||
| 71 | + | ||
| 72 | + async def fetch(self, sql: str, params: tuple = ()) -> list[tuple]: | ||
| 73 | + if sql != tenants.CONTROL_SQL: | ||
| 74 | + raise AssertionError("beklenmeyen sorgu: %s" % sql) | ||
| 75 | + self.queries += 1 | ||
| 76 | + return list(self.rows) | ||
| 77 | + | ||
| 78 | + | ||
| 79 | +class _FakeStore: | ||
| 80 | + def __init__(self, name: str) -> None: | ||
| 81 | + self.name = name | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +class NamingTests(unittest.TestCase): | ||
| 85 | + def test_database_name_follows_the_backend_convention(self) -> None: | ||
| 86 | + # `tenant.rs:111-112` ile ayni: {kontrol}_school_{uuid tiresiz}. | ||
| 87 | + self.assertEqual( | ||
| 88 | + database_name(CONTROL, SCHOOL_A), | ||
| 89 | + "hezarfen_control_school_019300000000700080000000000000a1", | ||
| 90 | + ) | ||
| 91 | + self.assertEqual( | ||
| 92 | + database_name(CONTROL, uuid.UUID(SCHOOL_A)), | ||
| 93 | + "hezarfen_control_school_019300000000700080000000000000a1", | ||
| 94 | + ) | ||
| 95 | + | ||
| 96 | + def test_the_name_never_carries_dashes_or_uppercase(self) -> None: | ||
| 97 | + name = database_name(CONTROL, uuid.UUID(SCHOOL_B.upper())) | ||
| 98 | + self.assertNotIn("-", name) | ||
| 99 | + self.assertEqual(name, name.lower()) | ||
| 100 | + | ||
| 101 | + def test_garbage_is_refused_not_mangled(self) -> None: | ||
| 102 | + with self.assertRaises(ValueError): | ||
| 103 | + database_name(CONTROL, "kadikoy-lisesi") | ||
| 104 | + | ||
| 105 | + | ||
| 106 | +class RegistryTests(unittest.IsolatedAsyncioTestCase): | ||
| 107 | + def setUp(self) -> None: | ||
| 108 | + self.clock = _Clock() | ||
| 109 | + | ||
| 110 | + def _registry(self, rows, ttl: float = 60.0) -> SchoolRegistry: | ||
| 111 | + return SchoolRegistry(_FakeControl(rows), ttl_secs=ttl, clock_fn=self.clock) | ||
| 112 | + | ||
| 113 | + async def test_the_control_query_is_shared_until_the_ttl_expires(self) -> None: | ||
| 114 | + registry = self._registry( | ||
| 115 | + [("a-okul", SCHOOL_A, "active"), ("b-okul", SCHOOL_B, "active")] | ||
| 116 | + ) | ||
| 117 | + client = registry._client | ||
| 118 | + for _ in range(3): | ||
| 119 | + await registry.resolve("a-okul") | ||
| 120 | + await registry.active_schools() | ||
| 121 | + self.assertEqual(client.queries, 1, "kutuk her cagride yeniden okunmamali") | ||
| 122 | + | ||
| 123 | + self.clock.advance(61) | ||
| 124 | + await registry.resolve("a-okul") | ||
| 125 | + self.assertEqual(client.queries, 2) | ||
| 126 | + | ||
| 127 | + async def test_only_active_schools_are_listed_and_the_order_is_stable(self) -> None: | ||
| 128 | + registry = self._registry( | ||
| 129 | + [ | ||
| 130 | + ("kadikoy-lisesi", SCHOOL_A, "active"), | ||
| 131 | + ("kapatilan-lise", SCHOOL_B, "suspended"), | ||
| 132 | + ("ataturk-lisesi", SCHOOL_A, "active"), | ||
| 133 | + ] | ||
| 134 | + ) | ||
| 135 | + self.assertEqual( | ||
| 136 | + await registry.active_schools(), ["ataturk-lisesi", "kadikoy-lisesi"] | ||
| 137 | + ) | ||
| 138 | + | ||
| 139 | + async def test_unknown_and_suspended_are_distinguishable(self) -> None: | ||
| 140 | + registry = self._registry([("kapali-lise", SCHOOL_A, "suspended")]) | ||
| 141 | + with self.assertRaises(UnknownSchool) as unknown: | ||
| 142 | + await registry.resolve("yok-boyle-okul") | ||
| 143 | + self.assertEqual(unknown.exception.code, "unknown_school") | ||
| 144 | + | ||
| 145 | + with self.assertRaises(SchoolSuspended) as suspended: | ||
| 146 | + await registry.resolve("kapali-lise") | ||
| 147 | + self.assertEqual(suspended.exception.code, "school_suspended") | ||
| 148 | + | ||
| 149 | + async def test_a_broken_control_row_does_not_sink_the_catalogue(self) -> None: | ||
| 150 | + registry = self._registry( | ||
| 151 | + [("bozuk", "uuid-degil", "active"), ("saglam", SCHOOL_A, "active")] | ||
| 152 | + ) | ||
| 153 | + self.assertEqual(await registry.active_schools(), ["saglam"]) | ||
| 154 | + | ||
| 155 | + async def test_an_unreadable_control_database_is_a_typed_error(self) -> None: | ||
| 156 | + class Broken: | ||
| 157 | + async def fetch(self, sql, params=()): | ||
| 158 | + raise RuntimeError('relation "school" does not exist') | ||
| 159 | + | ||
| 160 | + registry = SchoolRegistry(Broken(), ttl_secs=0) | ||
| 161 | + with self.assertRaises(TenantError) as caught: | ||
| 162 | + await registry.active_schools() | ||
| 163 | + self.assertEqual(caught.exception.code, "unavailable") | ||
| 164 | + self.assertIn("school", str(caught.exception)) | ||
| 165 | + | ||
| 166 | + | ||
| 167 | +class PoolTests(unittest.IsolatedAsyncioTestCase): | ||
| 168 | + """Sinirli havuz onbellegi: tavani ve TTL'i sahte opener ile olculur.""" | ||
| 169 | + | ||
| 170 | + def setUp(self) -> None: | ||
| 171 | + self.clock = _Clock() | ||
| 172 | + self.rows = [ | ||
| 173 | + ("a-okul", SCHOOL_A, "active"), | ||
| 174 | + ("b-okul", SCHOOL_B, "active"), | ||
| 175 | + ("c-okul", SCHOOL_C, "active"), | ||
| 176 | + ] | ||
| 177 | + self.control = _FakeControl(self.rows) | ||
| 178 | + self.opened: list[str] = [] | ||
| 179 | + self.closed: list[str] = [] | ||
| 180 | + | ||
| 181 | + def _stores(self, *, max_pools: int = 8, ttl: float = 900.0) -> TenantStores: | ||
| 182 | + self.registry = SchoolRegistry(self.control, ttl_secs=60.0, clock_fn=self.clock) | ||
| 183 | + | ||
| 184 | + async def opener(ref): | ||
| 185 | + self.opened.append(ref.slug) | ||
| 186 | + | ||
| 187 | + async def close() -> None: | ||
| 188 | + self.closed.append(ref.slug) | ||
| 189 | + | ||
| 190 | + return OpenedSchool(_FakeStore(ref.slug), close) | ||
| 191 | + | ||
| 192 | + return TenantStores( | ||
| 193 | + self.registry, | ||
| 194 | + opener, | ||
| 195 | + max_pools=max_pools, | ||
| 196 | + ttl_secs=ttl, | ||
| 197 | + clock_fn=self.clock, | ||
| 198 | + ) | ||
| 199 | + | ||
| 200 | + async def test_each_school_gets_its_own_store(self) -> None: | ||
| 201 | + stores = self._stores() | ||
| 202 | + a = await stores.store_for("a-okul") | ||
| 203 | + b = await stores.store_for("b-okul") | ||
| 204 | + self.assertEqual((a.name, b.name), ("a-okul", "b-okul")) | ||
| 205 | + self.assertIsNot(a, b) | ||
| 206 | + # Ikinci cagri onbellegi kullanir: yeniden ACILMAZ. | ||
| 207 | + self.assertIs(await stores.store_for("a-okul"), a) | ||
| 208 | + self.assertEqual(self.opened, ["a-okul", "b-okul"]) | ||
| 209 | + | ||
| 210 | + async def test_an_unknown_school_is_refused_and_nothing_falls_back(self) -> None: | ||
| 211 | + stores = self._stores() | ||
| 212 | + with self.assertRaises(UnknownSchool) as caught: | ||
| 213 | + await stores.store_for("yok-boyle-okul") | ||
| 214 | + self.assertEqual(caught.exception.code, "unknown_school") | ||
| 215 | + self.assertEqual(self.opened, [], "bilinmeyen okul icin havuz ACILMAMALI") | ||
| 216 | + self.assertEqual(stores.stats()["reddedilen"], 1) | ||
| 217 | + | ||
| 218 | + async def test_the_ceiling_evicts_the_least_recently_used_pool(self) -> None: | ||
| 219 | + stores = self._stores(max_pools=2) | ||
| 220 | + await stores.store_for("a-okul") | ||
| 221 | + self.clock.advance(1) | ||
| 222 | + b_store = await stores.store_for("b-okul") | ||
| 223 | + self.clock.advance(1) | ||
| 224 | + await stores.store_for("a-okul") # a artik en yeni kullanilan | ||
| 225 | + self.clock.advance(1) | ||
| 226 | + await stores.store_for("b-okul") # b de oyle; simdi bir yer lazim | ||
| 227 | + | ||
| 228 | + # Ucuncu okul icin yer acilmali: en eski kullanilan kapanir. | ||
| 229 | + self.clock.advance(1) | ||
| 230 | + await stores.store_for("c-okul") | ||
| 231 | + | ||
| 232 | + self.assertEqual(stores.stats()["acik"], 2) | ||
| 233 | + self.assertEqual(stores.stats()["atilan"], 1) | ||
| 234 | + self.assertEqual(self.closed, ["a-okul"]) | ||
| 235 | + # Kapatilan okul yeniden istendiginde yeniden ACILIR (bayat depo yok). | ||
| 236 | + self.clock.advance(1) | ||
| 237 | + again = await stores.store_for("a-okul") | ||
| 238 | + self.assertEqual(again.name, "a-okul") | ||
| 239 | + self.assertEqual(self.opened.count("a-okul"), 2) | ||
| 240 | + self.assertEqual(b_store.name, "b-okul") | ||
| 241 | + | ||
| 242 | + async def test_a_pool_expires_after_its_ttl(self) -> None: | ||
| 243 | + stores = self._stores(ttl=10.0) | ||
| 244 | + first = await stores.store_for("a-okul") | ||
| 245 | + self.clock.advance(11) | ||
| 246 | + second = await stores.store_for("a-okul") | ||
| 247 | + self.assertIsNot(first, second) | ||
| 248 | + self.assertEqual(self.closed, ["a-okul"]) | ||
| 249 | + self.assertEqual(stores.stats()["atilan"], 1) | ||
| 250 | + | ||
| 251 | + async def test_zero_schools_boot_cleanly_and_serve_nothing(self) -> None: | ||
| 252 | + self.control.rows.clear() | ||
| 253 | + stores = self._stores() | ||
| 254 | + self.assertEqual(await stores.active_schools(), []) | ||
| 255 | + with self.assertRaises(UnknownSchool): | ||
| 256 | + await stores.store_for("a-okul") | ||
| 257 | + self.assertEqual(stores.stats()["acik"], 0) | ||
| 258 | + await stores.close() | ||
| 259 | + | ||
| 260 | + async def test_close_releases_every_pool(self) -> None: | ||
| 261 | + stores = self._stores() | ||
| 262 | + await stores.store_for("a-okul") | ||
| 263 | + await stores.store_for("b-okul") | ||
| 264 | + await stores.close() | ||
| 265 | + self.assertEqual(sorted(self.closed), ["a-okul", "b-okul"]) | ||
| 266 | + self.assertEqual(stores.stats()["acik"], 0) | ||
| 267 | + | ||
| 268 | + async def test_a_failing_opener_is_reported_as_an_unavailable_school(self) -> None: | ||
| 269 | + registry = SchoolRegistry(self.control, ttl_secs=60.0, clock_fn=self.clock) | ||
| 270 | + | ||
| 271 | + async def opener(ref): | ||
| 272 | + raise RuntimeError('connection failed: FATAL: database "yok" does not exist') | ||
| 273 | + | ||
| 274 | + stores = TenantStores(registry, opener, clock_fn=self.clock) | ||
| 275 | + with self.assertRaises(TenantError) as caught: | ||
| 276 | + await stores.store_for("a-okul") | ||
| 277 | + self.assertEqual(caught.exception.code, "unavailable") | ||
| 278 | + | ||
| 279 | + | ||
| 280 | +class DispatchTests(unittest.IsolatedAsyncioTestCase): | ||
| 281 | + """Cercevenin `school` alani -> o okulun deposu: istek yolunun dikişi.""" | ||
| 282 | + | ||
| 283 | + def setUp(self) -> None: | ||
| 284 | + self.clock = _Clock() | ||
| 285 | + self.control = _FakeControl( | ||
| 286 | + [("a-okul", SCHOOL_A, "active"), ("b-okul", SCHOOL_B, "active")] | ||
| 287 | + ) | ||
| 288 | + self.seen: dict[str, list[str]] = {} | ||
| 289 | + | ||
| 290 | + def tearDown(self) -> None: | ||
| 291 | + capabilities._handlers.clear() | ||
| 292 | + capabilities.bind_directory(None) | ||
| 293 | + | ||
| 294 | + def _stores(self) -> TenantStores: | ||
| 295 | + registry = SchoolRegistry(self.control, ttl_secs=60.0, clock_fn=self.clock) | ||
| 296 | + | ||
| 297 | + async def opener(ref): | ||
| 298 | + store = _FakeStore(ref.slug) | ||
| 299 | + store.written = [] | ||
| 300 | + self.seen[ref.slug] = store.written | ||
| 301 | + | ||
| 302 | + async def close() -> None: | ||
| 303 | + return None | ||
| 304 | + | ||
| 305 | + return OpenedSchool(store, close) | ||
| 306 | + | ||
| 307 | + return TenantStores(registry, opener, clock_fn=self.clock) | ||
| 308 | + | ||
| 309 | + async def test_the_handler_resolves_the_frame_s_school_and_never_another(self) -> None: | ||
| 310 | + capabilities.bind_directory(self._stores()) | ||
| 311 | + | ||
| 312 | + async def handler(school, payload): | ||
| 313 | + store = await capabilities.directory().store_for(school) | ||
| 314 | + store.written.append(payload["mark"]) | ||
| 315 | + return {"seen": list(store.written), "store": store.name} | ||
| 316 | + | ||
| 317 | + capabilities.register(capabilities.INSIGHT_REFRESH, handler) | ||
| 318 | + | ||
| 319 | + a = await capabilities.dispatch(capabilities.INSIGHT_REFRESH, "a-okul", {"mark": "run-a"}) | ||
| 320 | + b = await capabilities.dispatch(capabilities.INSIGHT_REFRESH, "b-okul", {"mark": "run-b"}) | ||
| 321 | + | ||
| 322 | + self.assertEqual(a, {"seen": ["run-a"], "store": "a-okul"}) | ||
| 323 | + self.assertEqual(b, {"seen": ["run-b"], "store": "b-okul"}) | ||
| 324 | + self.assertEqual(self.seen["a-okul"], ["run-a"]) | ||
| 325 | + self.assertEqual(self.seen["b-okul"], ["run-b"]) | ||
| 326 | + | ||
| 327 | + async def test_an_unknown_school_refuses_with_its_own_code(self) -> None: | ||
| 328 | + capabilities.bind_directory(self._stores()) | ||
| 329 | + | ||
| 330 | + async def handler(school, payload): | ||
| 331 | + store = await capabilities.directory().store_for(school) | ||
| 332 | + return {"store": store.name} | ||
| 333 | + | ||
| 334 | + capabilities.register(capabilities.INSIGHT_STUDENT, handler) | ||
| 335 | + with self.assertRaises(UnknownSchool) as caught: | ||
| 336 | + await capabilities.dispatch(capabilities.INSIGHT_STUDENT, "yok", {}) | ||
| 337 | + # Kod kabloya AYNEN gider (bridge.py: CapabilityError/TenantError). | ||
| 338 | + self.assertEqual(caught.exception.code, "unknown_school") | ||
| 339 | + | ||
| 340 | + async def test_without_a_bound_directory_the_request_is_refused(self) -> None: | ||
| 341 | + with self.assertRaises(capabilities.CapabilityError) as caught: | ||
| 342 | + capabilities.directory() | ||
| 343 | + self.assertEqual(caught.exception.code, "unavailable") | ||
| 344 | + | ||
| 345 | + | ||
| 346 | +class LegacyDirectoryTests(unittest.IsolatedAsyncioTestCase): | ||
| 347 | + """Eski tek veritabani modu da kapali kume olmali.""" | ||
| 348 | + | ||
| 349 | + async def test_the_configured_schools_are_the_only_ones_served(self) -> None: | ||
| 350 | + store = _FakeStore("tek") | ||
| 351 | + directory = OneDatabase(store, ["a-okul", "b-okul"]) | ||
| 352 | + self.assertEqual(await directory.active_schools(), ["a-okul", "b-okul"]) | ||
| 353 | + self.assertIs(await directory.store_for("a-okul"), store) | ||
| 354 | + with self.assertRaises(UnknownSchool): | ||
| 355 | + await directory.store_for("yok") | ||
| 356 | + | ||
| 357 | + | ||
| 358 | +class MigrationListTests(unittest.TestCase): | ||
| 359 | + """`REQUIRED_TABLES` ile okul DDL'i birbirinden kopmasin.""" | ||
| 360 | + | ||
| 361 | + def test_required_tables_match_the_school_migration(self) -> None: | ||
| 362 | + import re | ||
| 363 | + | ||
| 364 | + sql = DDL.read_text(encoding="utf-8") | ||
| 365 | + created = set(re.findall(r"^CREATE TABLE\s+(\w+)", sql, flags=re.MULTILINE)) | ||
| 366 | + self.assertEqual( | ||
| 367 | + created, | ||
| 368 | + set(tenants.REQUIRED_TABLES), | ||
| 369 | + "zeka okul semasi degistiyse REQUIRED_TABLES'i da guncelleyin " | ||
| 370 | + "(`tenants.py`)", | ||
| 371 | + ) | ||
| 372 | + | ||
| 373 | + | ||
| 374 | +# =========================================================================== | ||
| 375 | +# ENTEGRASYON -- gercek Postgres, iki okul | ||
| 376 | +# =========================================================================== | ||
| 377 | + | ||
| 378 | +ADMIN_DSN = os.environ.get("ZEKA_TEST_PG_DSN", "").strip() | ||
| 379 | + | ||
| 380 | +STUB_DDL = """ | ||
| 381 | +CREATE TABLE app_user (id uuid PRIMARY KEY); | ||
| 382 | +CREATE TABLE course (id uuid PRIMARY KEY); | ||
| 383 | +CREATE TABLE subject (id uuid PRIMARY KEY); | ||
| 384 | +CREATE TABLE exam_question (exam uuid NOT NULL, id uuid NOT NULL, PRIMARY KEY (exam, id)); | ||
| 385 | +""" | ||
| 386 | +"""ZEKA tablolarinin disari bakan FK'leri icin asgari hedefler (bkz. | ||
| 387 | +`service/schema/postgres/school/20260916000001_zeka.sql` satirlari 50, 82, | ||
| 388 | +250, 300). Gercek okul veritabaninda bunlar backend'in semasidir.""" | ||
| 389 | + | ||
| 390 | + | ||
| 391 | +def _pg_available() -> bool: | ||
| 392 | + if not ADMIN_DSN: | ||
| 393 | + return False | ||
| 394 | + try: | ||
| 395 | + import psycopg | ||
| 396 | + | ||
| 397 | + with psycopg.connect(ADMIN_DSN, connect_timeout=3) as conn: | ||
| 398 | + conn.execute("SELECT 1") | ||
| 399 | + return True | ||
| 400 | + except Exception: # noqa: BLE001 | ||
| 401 | + return False | ||
| 402 | + | ||
| 403 | + | ||
| 404 | +PG_AVAILABLE = _pg_available() | ||
| 405 | + | ||
| 406 | +CONTROL_DDL = """ | ||
| 407 | +CREATE TABLE school ( | ||
| 408 | + id uuid PRIMARY KEY, | ||
| 409 | + slug TEXT NOT NULL, | ||
| 410 | + name TEXT NOT NULL, | ||
| 411 | + status TEXT NOT NULL CONSTRAINT school_status CHECK (status IN ('active', 'suspended')), | ||
| 412 | + created_at BIGINT NOT NULL, | ||
| 413 | + CONSTRAINT school_slug UNIQUE (slug) | ||
| 414 | +) | ||
| 415 | +""" | ||
| 416 | +"""Kontrol semasinin YALNIZCA kayit cozumlemesinin okudugu kadari. | ||
| 417 | + | ||
| 418 | +Backend'in tam kontrol semasi (`migrations/control/20260912000001_control.sql`) | ||
| 419 | +bir suru tablo daha kurar; zeka yalnizca `school(slug, id, status)` okur, bu | ||
| 420 | +yuzden fikstur o kadardir -- testi backend deposuna baglamak, testi baska bir | ||
| 421 | +deponun surumune baglamak olurdu. | ||
| 422 | +""" | ||
| 423 | + | ||
| 424 | + | ||
| 425 | +@unittest.skipUnless( | ||
| 426 | + PG_AVAILABLE, "ZEKA_TEST_PG_DSN yok/erisilemiyor; Postgres entegrasyonu atlandi" | ||
| 427 | +) | ||
| 428 | +class PgMultiSchoolTests(unittest.IsolatedAsyncioTestCase): | ||
| 429 | + """Iki okul, iki veritabani: sizinti yok, redler ayrilabiliyor.""" | ||
| 430 | + | ||
| 431 | + if sys.platform == "win32": | ||
| 432 | + loop_factory = asyncio.SelectorEventLoop | ||
| 433 | + | ||
| 434 | + async def asyncSetUp(self) -> None: | ||
| 435 | + import psycopg | ||
| 436 | + | ||
| 437 | + from src.pg_client import PsycopgClient | ||
| 438 | + from src.store_pg import PgStore | ||
| 439 | + | ||
| 440 | + self.PsycopgClient = PsycopgClient | ||
| 441 | + self.PgStore = PgStore | ||
| 442 | + self.admin = await psycopg.AsyncConnection.connect(ADMIN_DSN, autocommit=True) | ||
| 443 | + self.tag = uuid.uuid4().hex[:10] | ||
| 444 | + self.control = "zeka_ms_%s" % self.tag | ||
| 445 | + self.a_db = database_name(self.control, SCHOOL_A) | ||
| 446 | + self.b_db = database_name(self.control, SCHOOL_B) | ||
| 447 | + self.made: list[str] = [] | ||
| 448 | + | ||
| 449 | + await self._createdb(self.control) | ||
| 450 | + self.control_conn = await psycopg.AsyncConnection.connect( | ||
| 451 | + tenants.school_dsn(ADMIN_DSN, self.control), autocommit=True | ||
| 452 | + ) | ||
| 453 | + await self.control_conn.execute(CONTROL_DDL) | ||
| 454 | + await self.control_conn.execute( | ||
| 455 | + "INSERT INTO school (id, slug, name, status, created_at) VALUES " | ||
| 456 | + "(%s, 'a-okul', 'A', 'active', 1), (%s, 'b-okul', 'B', 'active', 2), " | ||
| 457 | + "(%s, 'kapali-okul', 'K', 'suspended', 3)", | ||
| 458 | + (SCHOOL_A, SCHOOL_B, SCHOOL_C), | ||
| 459 | + ) | ||
| 460 | + self.dsn = tenants.school_dsn(ADMIN_DSN, self.control) | ||
| 461 | + | ||
| 462 | + async def asyncTearDown(self) -> None: | ||
| 463 | + control_conn = getattr(self, "control_conn", None) | ||
| 464 | + if control_conn is not None: | ||
| 465 | + await control_conn.close() | ||
| 466 | + for name in reversed(self.made): | ||
| 467 | + await self.admin.execute('DROP DATABASE IF EXISTS "%s" WITH (FORCE)' % name) | ||
| 468 | + await self.admin.close() | ||
| 469 | + | ||
| 470 | + async def _createdb(self, name: str) -> None: | ||
| 471 | + await self.admin.execute('CREATE DATABASE "%s"' % name) | ||
| 472 | + self.made.append(name) | ||
| 473 | + | ||
| 474 | + async def _apply_zeka_ddl(self, name: str) -> None: | ||
| 475 | + import psycopg | ||
| 476 | + | ||
| 477 | + conn = await psycopg.AsyncConnection.connect( | ||
| 478 | + tenants.school_dsn(ADMIN_DSN, name), autocommit=True | ||
| 479 | + ) | ||
| 480 | + try: | ||
| 481 | + # ZEKA'nin tablolari DISARI bakan FK'ler tasir (app_user, course, | ||
| 482 | + # subject, exam_question). Okul veritabaninda o tablolar backend'in | ||
| 483 | + # kendi semasindan gelir; fikstur FK'lerin istedigi ASGARI sutunu | ||
| 484 | + # kurar, boylece test backend deposuna baglanmaz. | ||
| 485 | + await conn.execute(STUB_DDL) | ||
| 486 | + # Ogrenci satirlari da gerekli: `zeka_run_pending.student` ile | ||
| 487 | + # `zeka_student_summary.student` app_user'a FK verir. | ||
| 488 | + await conn.execute( | ||
| 489 | + "INSERT INTO app_user (id) VALUES (%s), (%s)", (STUDENT_A, STUDENT_B) | ||
| 490 | + ) | ||
| 491 | + await conn.execute(DDL.read_text(encoding="utf-8")) | ||
| 492 | + finally: | ||
| 493 | + await conn.close() | ||
| 494 | + | ||
| 495 | + async def _open(self, **kw) -> TenantStores: | ||
| 496 | + return await tenants.open_postgres(self.dsn, **kw) | ||
| 497 | + | ||
| 498 | + async def test_boot_succeeds_with_zero_schools(self) -> None: | ||
| 499 | + # Kutugu bosalt: acilis okul satiri istememeli. | ||
| 500 | + await self.control_conn.execute("DELETE FROM school") | ||
| 501 | + stores = await self._open() | ||
| 502 | + self.assertEqual(await stores.active_schools(), []) | ||
| 503 | + with self.assertRaises(UnknownSchool) as caught: | ||
| 504 | + await stores.store_for("a-okul") | ||
| 505 | + self.assertEqual(caught.exception.code, "unknown_school") | ||
| 506 | + await stores.close() | ||
| 507 | + | ||
| 508 | + async def test_two_schools_never_see_each_other_s_rows(self) -> None: | ||
| 509 | + for name in (self.a_db, self.b_db): | ||
| 510 | + await self._createdb(name) | ||
| 511 | + await self._apply_zeka_ddl(name) | ||
| 512 | + | ||
| 513 | + stores = await self._open() | ||
| 514 | + a = await stores.store_for("a-okul") | ||
| 515 | + b = await stores.store_for("b-okul") | ||
| 516 | + | ||
| 517 | + # Hangi veritabanina baglandigimiz ADIYLA dogrulanir: turetme yanlissa | ||
| 518 | + # butun test yanlis yeri olcerdi. | ||
| 519 | + self.assertEqual( | ||
| 520 | + str((await a._client.fetch("SELECT current_database()"))[0][0]), self.a_db | ||
| 521 | + ) | ||
| 522 | + self.assertEqual( | ||
| 523 | + str((await b._client.fetch("SELECT current_database()"))[0][0]), self.b_db | ||
| 524 | + ) | ||
| 525 | + | ||
| 526 | + # `zeka_run_pending.student` bir uuid'dir (app_user'a FK): ogrenci | ||
| 527 | + # kimlikleri de o turden olmali. | ||
| 528 | + self.assertTrue( | ||
| 529 | + await a.write_run( | ||
| 530 | + {"started_at": 1, "status": "running", "pending_students": [STUDENT_A]}, | ||
| 531 | + "2026-09-17", | ||
| 532 | + ) | ||
| 533 | + ) | ||
| 534 | + self.assertTrue( | ||
| 535 | + await b.write_run( | ||
| 536 | + {"started_at": 2, "status": "running", "pending_students": [STUDENT_B]}, | ||
| 537 | + "2026-09-17", | ||
| 538 | + ) | ||
| 539 | + ) | ||
| 540 | + | ||
| 541 | + self.assertEqual(await a.last_pending("a-okul"), [STUDENT_A]) | ||
| 542 | + self.assertEqual(await b.last_pending("b-okul"), [STUDENT_B]) | ||
| 543 | + self.assertEqual( | ||
| 544 | + int((await a._client.fetch("SELECT count(*) FROM zeka_run"))[0][0]), 1 | ||
| 545 | + ) | ||
| 546 | + self.assertEqual( | ||
| 547 | + int((await b._client.fetch("SELECT count(*) FROM zeka_run"))[0][0]), 1 | ||
| 548 | + ) | ||
| 549 | + await stores.close() | ||
| 550 | + | ||
| 551 | + async def test_a_school_with_no_database_is_a_per_request_error(self) -> None: | ||
| 552 | + # Ne a ne b veritabani var: acilis yine de basarili olmali. | ||
| 553 | + stores = await self._open() | ||
| 554 | + self.assertEqual(await stores.active_schools(), ["a-okul", "b-okul"]) | ||
| 555 | + with self.assertRaises(TenantError) as caught: | ||
| 556 | + await stores.store_for("a-okul") | ||
| 557 | + self.assertEqual(caught.exception.code, "unavailable") | ||
| 558 | + self.assertNotIsInstance(caught.exception, UnknownSchool) | ||
| 559 | + await stores.close() | ||
| 560 | + | ||
| 561 | + async def test_an_unmigrated_school_database_is_distinguishable(self) -> None: | ||
| 562 | + await self._createdb(self.a_db) # var ama zeka tablolari yok | ||
| 563 | + | ||
| 564 | + stores = await self._open() | ||
| 565 | + with self.assertRaises(SchoolNotMigrated) as caught: | ||
| 566 | + await stores.store_for("a-okul") | ||
| 567 | + message = str(caught.exception) | ||
| 568 | + self.assertIn("zeka_run", message) | ||
| 569 | + self.assertIn("20260916000001_zeka.sql", message) | ||
| 570 | + self.assertEqual(caught.exception.code, "school_not_migrated") | ||
| 571 | + # Diger okulun veritabani da yok; o BASKA bir hata vermeli. | ||
| 572 | + with self.assertRaises(TenantError) as other: | ||
| 573 | + await stores.store_for("b-okul") | ||
| 574 | + self.assertEqual(other.exception.code, "unavailable") | ||
| 575 | + await stores.close() | ||
| 576 | + | ||
| 577 | + async def test_a_suspended_school_is_refused_by_the_control_row(self) -> None: | ||
| 578 | + stores = await self._open() | ||
| 579 | + with self.assertRaises(SchoolSuspended) as caught: | ||
| 580 | + await stores.store_for("kapali-okul") | ||
| 581 | + self.assertEqual(caught.exception.code, "school_suspended") | ||
| 582 | + await stores.close() | ||
| 583 | + | ||
| 584 | + async def test_the_pool_cache_is_bounded_and_releases_backends(self) -> None: | ||
| 585 | + for name in (self.a_db, self.b_db): | ||
| 586 | + await self._createdb(name) | ||
| 587 | + await self._apply_zeka_ddl(name) | ||
| 588 | + | ||
| 589 | + stores = await self._open(max_pools=1) | ||
| 590 | + await stores.store_for("a-okul") | ||
| 591 | + await stores.store_for("b-okul") | ||
| 592 | + | ||
| 593 | + stats = stores.stats() | ||
| 594 | + self.assertEqual(stats["tavan"], 1) | ||
| 595 | + self.assertEqual(stats["acik"], 1) | ||
| 596 | + self.assertGreaterEqual(stats["atilan"], 1) | ||
| 597 | + | ||
| 598 | + # Kapatilan havuzun sunucu tarafinda baglantisi KALMAMALI; acik olan | ||
| 599 | + # havuzunki durmali. Sayim kontrol baglantisindan yapilir. | ||
| 600 | + sessions = await self.control_conn.execute( | ||
| 601 | + "SELECT datname, count(*) FROM pg_stat_activity " | ||
| 602 | + "WHERE datname IN (%s, %s) GROUP BY datname", | ||
| 603 | + (self.a_db, self.b_db), | ||
| 604 | + ) | ||
| 605 | + counts = {str(row[0]): int(row[1]) for row in await sessions.fetchall()} | ||
| 606 | + self.assertEqual(counts.get(self.a_db, 0), 0, "atilan havuz kapatilmali") | ||
| 607 | + self.assertEqual(counts.get(self.b_db, 0), 1, "acik havuz yasamali") | ||
| 608 | + await stores.close() | ||
| 609 | + | ||
| 610 | + | ||
| 611 | +if __name__ == "__main__": | ||
| 612 | + unittest.main() | ||