d74d2fcd8af3a725bf69a77ea89dfce7ed54f0f0Parent: 89bc04b60 changed files +10910 -1
- .containerignore +22 -0
- .env.example +191 -0
- .github/workflows/mutation.yml +45 -0
- .github/workflows/test.yml +99 -0
- .gitignore +12 -0
- CLAUDE.md +104 -0
- Containerfile +76 -0
- README.md +1114 -1
- compose.yaml +75 -0
- deploy/OKU.md +552 -0
- deploy/rollback.ps1 +104 -0
- deploy/run-stack.ps1 +201 -0
- deploy/setup-models.ps1 +121 -0
- deploy/setup-pipeline.ps1 +94 -0
- requirements.txt +1 -0
- setup.cfg +3 -0
- src/__init__.py +0 -0
- src/bridge.py +327 -0
- src/capabilities.py +153 -0
- src/config.py +140 -0
- src/jobs.py +644 -0
- src/main.py +996 -0
- src/pipeline.py +338 -0
- src/protocol.py +209 -0
- tests/__init__.py +0 -0
- tests/fuzz/__init__.py +0 -0
- tests/fuzz/test_fuzz_protocol.py +207 -0
- tests/integration/__init__.py +0 -0
- tests/integration/test_lifecycle.py +257 -0
- tests/model/__init__.py +0 -0
- tests/model/test_model_jobstore.py +330 -0
- tests/regress/__init__.py +10 -0
- tests/regress/regress_absolute_path.py +110 -0
- tests/regress/regress_api_read.py +91 -0
- tests/regress/regress_cancel_race.py +135 -0
- tests/regress/regress_daemon_shutdown.py +133 -0
- tests/regress/regress_format_vocabulary.py +130 -0
- tests/regress/regress_identifier_path.py +128 -0
- tests/regress/regress_mutation_survivors.py +142 -0
- tests/regress/regress_path_traversal.py +105 -0
- tests/regress/regress_queued_failed.py +92 -0
- tests/regress/regress_retention.py +158 -0
- tests/regress/regress_schema_validation.py +144 -0
- tests/regress/regress_script_alignment.py +103 -0
- tests/regress/regress_secret_leak.py +184 -0
- tests/regress/regress_tmp_residue.py +154 -0
- tests/regress/regress_tool_arguments.py +75 -0
- tests/regress/regress_unanswered_stream.py +206 -0
- tests/regress/regress_unreachable_guard.py +138 -0
- tests/unit/__init__.py +0 -0
- tests/unit/test_capabilities.py +207 -0
- tests/unit/test_config.py +227 -0
- tests/unit/test_jobs.py +389 -0
- tests/unit/test_pipeline.py +273 -0
- tests/unit/test_protocol.py +192 -0
- tools/api_probe.py +64 -0
- tools/dependency_scanner.py +118 -0
- tools/fuzz_test.py +453 -0
- tools/mutation_test.py +221 -0
- tools/smoke_test.py +113 -0
.containerignoreadded+22 -0
| @@ -0,0 +1,22 @@ | |||
| 1 | +.git | ||
| 2 | +.gitignore | ||
| 3 | +.venv | ||
| 4 | +.vscode | ||
| 5 | +__pycache__ | ||
| 6 | +*.py[cod] | ||
| 7 | +*.log | ||
| 8 | +.pytest_cache | ||
| 9 | +.mypy_cache | ||
| 10 | +.coverage | ||
| 11 | +htmlcov | ||
| 12 | +ReadMe.md | ||
| 13 | +CLAUDE.md | ||
| 14 | +compose.yaml | ||
| 15 | +.env | ||
| 16 | +.env.* | ||
| 17 | +out | ||
| 18 | +samples | ||
| 19 | +deploy | ||
| 20 | +vendor/pipeline/**/__pycache__ | ||
| 21 | +vendor/pipeline/.venv | ||
| 22 | +vendor/pipeline/tools/bin/*.exe | ||
.env.exampleadded+191 -0
| @@ -0,0 +1,191 @@ | |||
| 1 | +# hezarfen_podcast_service ortam degiskenleri — ORNEK DOSYA | ||
| 2 | +# | ||
| 3 | +# Kullanim: cp .env.example .env ve degerleri doldur. | ||
| 4 | +# `.env` .gitignore'dadir; BU dosya (.env.example) kasten izlenir. | ||
| 5 | +# BURAYA GERCEK SIR YAZMA. Hepsi yer tutucudur. | ||
| 6 | +# | ||
| 7 | +# Genel kural (backend ile ayni): YANLIS yapilandirma boot'u cokertir (exit 2), | ||
| 8 | +# EKSIK yapilandirma yalnizca ilgili ozelligi sessizce kapatir. | ||
| 9 | + | ||
| 10 | +# --- Kopru / QUIC ------------------------------------------------------------ | ||
| 11 | + | ||
| 12 | +# Backend'in QUIC dinleyicisinin adresi. Servis PORT ACMAZ; buraya dial-out eder. | ||
| 13 | +# Compose agindaki servis adi kullanilir ki NAT/host farki sorun olmasin. | ||
| 14 | +AI_BRIDGE_HOST=hezarfen-backend | ||
| 15 | +AI_BRIDGE_PORT=8090 | ||
| 16 | + | ||
| 17 | +# Sertifikayi cekmek icin backend'in HTTP koku. Backend self-signed sertifikayi | ||
| 18 | +# her acilista uretebildigi icin PEM her yeniden baglanmada tekrar cekilir. | ||
| 19 | +AI_BACKEND_URL=http://hezarfen-backend:8080 | ||
| 20 | + | ||
| 21 | +# Backend ile paylasilan sir. ZORUNLU: yoksa kopru acilista exit 2 verir — | ||
| 22 | +# cunku kaydin kimlik dogrulamasi budur ve sirsiz kayit sessizce reddedilir, | ||
| 23 | +# yani "eksik" degil "yanlis" yapilandirmadir. | ||
| 24 | +# ASLA gercek degerini bu dosyaya yazma; `.env` icine koy. | ||
| 25 | +AI_SHARED_TOKEN=change-me | ||
| 26 | + | ||
| 27 | +# Sertifikanin SAN'i. Backend'in urettigi sertifika `localhost` icin gecerli. | ||
| 28 | +AI_TLS_SERVER_NAME=localhost | ||
| 29 | + | ||
| 30 | +# Hello cercevesinde bildirilecek servis adi. Backend yetenekleri bu ada baglar. | ||
| 31 | +AI_SERVICE_NAME=podcast | ||
| 32 | + | ||
| 33 | +# Ayni anda islenen hab/1 istek sayisi; asilirsa istege `busy` donulur. | ||
| 34 | +# Bu ISTEK esiktir, IS esigi degil — istekler milisaniyeliktir (bkz. PODCAST_MAX_JOBS). | ||
| 35 | +AI_MAX_CONCURRENT=2 | ||
| 36 | + | ||
| 37 | +# Baglanti koptugunda yeniden deneme araligi (saniye). | ||
| 38 | +AI_RECONNECT_SECS=3 | ||
| 39 | + | ||
| 40 | +# debug / info / warn / error. Gecersiz deger boot'u cokertir. | ||
| 41 | +LOG_LEVEL=info | ||
| 42 | + | ||
| 43 | +# --- Podcast is kuyrugu ------------------------------------------------------ | ||
| 44 | + | ||
| 45 | +# Is durumunun tutuldugu dizin: is basina bir JSON dosyasi, atomik yazilir | ||
| 46 | +# (gecici dosya + os.replace). Servis yeniden baslarsa durum kaybolmasin diye | ||
| 47 | +# DISKTE tutulur ve compose'ta adlandirilmis bir hacme baglanir. | ||
| 48 | +PODCAST_JOB_ROOT=/data/podcast/jobs | ||
| 49 | + | ||
| 50 | +# Ayni anda kosan UZUN is sayisi. Uzun isler kendi daemon isci thread'lerinde | ||
| 51 | +# kosar (kuyruk + sentinel ile kapanir); hizli yetenek cagrilari | ||
| 52 | +# (submit/status/result/cancel) o havuza HIC girmez — yoksa 45 dakikalik bir is, | ||
| 53 | +# backend'in 60 saniyelik istek deadline'ini yerdi. | ||
| 54 | +# Thread'ler DAEMON'dur: SIGTERM geldiginde surec, kosan is bitmeden cikabilsin | ||
| 55 | +# diye. ThreadPoolExecutor bunu yapamiyordu (olculdu: 8 sn'lik iste 8 sn takilma). | ||
| 56 | +PODCAST_WORKERS=1 | ||
| 57 | + | ||
| 58 | +# Kuyruk + kosan islerin toplam tavani. Asilirsa `podcast.submit` -> `busy`. | ||
| 59 | +PODCAST_MAX_JOBS=8 | ||
| 60 | + | ||
| 61 | +# SAHTE hattaki her asama arasinda beklenen sure (saniye). Gercek hat henuz | ||
| 62 | +# bagli degil; ocr -> plan -> script -> tts -> mux asamalari taklit ediliyor. | ||
| 63 | +# Kucuk tutulmasinin sebebi: yasam dongusu 45 dakika beklemeden kanitlanabilsin. | ||
| 64 | +# Gercek hat baglaninca bu degisken anlamini yitirecek. | ||
| 65 | +PODCAST_STAGE_SECS=0.2 | ||
| 66 | + | ||
| 67 | +# Bir isin tahmini toplam suresi (saniye); backend'e `eta_secs` olarak bildirilir. | ||
| 68 | +# 0 = OTOMATIK: asama sayisi * PODCAST_STAGE_SECS (en az 1 sn) kullanilir. | ||
| 69 | +# Gerekce: otomatik hesap SAHTE hattin suresidir. Gercek hat baglaninca burasi | ||
| 70 | +# ayarlanmazsa backend'e 45 dakikalik bir is icin "1 saniye" denir. Gercek hat | ||
| 71 | +# icin 2700 gibi bir deger yaz. Aralik 0..86400; disina cikan deger boot'u cokertir. | ||
| 72 | +# `real` modda ve burasi verilmemisse OTOMATIK deger 2700 (45 dk) kullanilir - | ||
| 73 | +# olculen gercek suredir. `simulate` modda otomatik deger eskisi gibi asama | ||
| 74 | +# sayisi * PODCAST_STAGE_SECS'tir. | ||
| 75 | +PODCAST_ETA_SECS=0 | ||
| 76 | + | ||
| 77 | +# `source_id`'nin dosya yoluna cozulecegi paylasilan kok dizin. Backend'in | ||
| 78 | +# FILES_PATH degeriyle AYNI olmali. source_id yalnizca [A-Za-z0-9._-] ve en fazla | ||
| 79 | +# 128 karakter olabilir; cozulen yolun bu kokun ALTINDA kaldigi ayrica dogrulanir | ||
| 80 | +# (symlink kacisi icin). Adim 4'te compose'a baglandi: backend'in `hezarfen-data` | ||
| 81 | +# hacmi buraya SALT-OKUNUR (:ro) monte edilir. Servis PDF'e yalnizca okur. | ||
| 82 | +PODCAST_MEDIA_ROOT=/data/files | ||
| 83 | + | ||
| 84 | +# --- Gercek hat (adim 3) ----------------------------------------------------- | ||
| 85 | + | ||
| 86 | +# SAHTE mi GERCEK mi. `simulate` | `real`. Gecersiz deger boot'u cokertir. | ||
| 87 | +# simulate : `jobs.py::_simulate_pipeline` kosar. Acilista TEK SATIR uyari | ||
| 88 | +# basilir: "SAHTE hat kosuyor, uretilen ses GERCEK DEGIL". | ||
| 89 | +# Uretilen kimlikler `sim_` onekli olur. | ||
| 90 | +# real : `src/pipeline.py` gercek `router.hat.Hat`i kosar. | ||
| 91 | +# PODCAST_PIPELINE_PATH tanimsizsa VEYA `router.hat` import | ||
| 92 | +# edilemiyorsa acilis exit 2 ile coker. SESSIZ SAHTE URETIM YOK. | ||
| 93 | +# compose VARSAYILANI `real`'dir (imajda hat var). Elle `python -m src.bridge` | ||
| 94 | +# kosarken varsayilan hala `simulate`tir - hat yolu tanimsizken boot cokmesin diye. | ||
| 95 | +PODCAST_MODE=real | ||
| 96 | + | ||
| 97 | +# Hat kaynagi kokunun mutlak yolu (icinde `router/hat.py` bulunan dizin). | ||
| 98 | +# `real` modda ZORUNLU; `simulate` modda hic okunmaz. | ||
| 99 | +# CONTAINER'DA: /app/pipeline. Kaynak `deploy/setup-pipeline.ps1` ile | ||
| 100 | +# `vendor/pipeline/`e KOPYALANIR, Containerfile onu imaja alir. Bind-mount YOK: | ||
| 101 | +# bind-mount'lu bir imaj tasinabilir degildir ve hangi kaynakla kostugu | ||
| 102 | +# calisma anina kadar belirsiz kalirdi. | ||
| 103 | +# YERELDE (tools/smoke_test.py): C:\PROJECTS\podcast | ||
| 104 | +PODCAST_PIPELINE_PATH=/app/pipeline | ||
| 105 | + | ||
| 106 | +# `Hat(cikti_koku=...)` - uretilen mp3/script/quiz dosyalarinin kok dizini. | ||
| 107 | +# Container'da uid 10001 sahipliginde olusturulur; kalici hacme baglanmali, | ||
| 108 | +# yoksa uretilen ses container ile birlikte silinir. | ||
| 109 | +PODCAST_OUTPUT_ROOT=/data/podcast/out | ||
| 110 | + | ||
| 111 | +# `Hat(bolum_limiti=...)`. 1 = yalnizca ilk bolum (en hizli, varsayilan). | ||
| 112 | +# 0 veya -1 = HEPSI. Birden fazla bolum uretilirse `podcast.result` cevabinda | ||
| 113 | +# `audio_id`/`script_id` ILK bolumu gosterir, `audio_ids`/`script_ids` HEPSINI. | ||
| 114 | +PODCAST_CHAPTER_LIMIT=1 | ||
| 115 | + | ||
| 116 | +# `Hat(motor_adi=...)` - TTS motoru. Lokal ONNX motoru; ag gerektirmez. | ||
| 117 | +PODCAST_TTS_ENGINE=supertonic-3 | ||
| 118 | + | ||
| 119 | +# `router.kayit.Kayit` defteri (SQLite): adim onbellegi, resume kayitlari ve LLM | ||
| 120 | +# butce sayaci burada durur. ONBELLEK BU HATTIN TASARIM ILKESIDIR - defter kalici | ||
| 121 | +# degilse her kosu her adimi bastan yapar (olculen script adimi tek basina ~34 dk). | ||
| 122 | +# Bu yuzden compose'ta AYRI bir hacme (`podcast-kayit`) baglanir. | ||
| 123 | +PODCAST_LEDGER_DB=/data/podcast/kayit/router.sqlite | ||
| 124 | + | ||
| 125 | +# --- Model agirliklari (adim 4) ---------------------------------------------- | ||
| 126 | + | ||
| 127 | +# HuggingFace ve torch onbellek kokleri. `podcast-models` hacmi buraya SALT-OKUNUR | ||
| 128 | +# baglanir; agirliklar IMAJA GIRMEZ (~3,9 GB olculdu). Hacmi doldurmak: | ||
| 129 | +# pwsh -File deploy/setup-models.ps1 | ||
| 130 | +HF_HOME=/models/hf | ||
| 131 | +TORCH_HOME=/models/torch | ||
| 132 | + | ||
| 133 | +# 1 = HF hub'a AG CAGRISI YAPILMAZ. Agirlik hacimde yoksa hat ACIK hata verir; | ||
| 134 | +# sessizce 2,2 GB indirmeye baslamaz (uretimde istenmeyen davranis). Ilk kez | ||
| 135 | +# doldururken gecici olarak 0 yapilabilir. | ||
| 136 | +HF_HUB_OFFLINE=1 | ||
| 137 | + | ||
| 138 | +# NOT: hattin TTS ve ASR agirliklari HF onbelleginde DEGIL, `ses/ayar.py` icinde | ||
| 139 | +# SABIT KODLU `<hat_koku>/data/ses_modelleri` altindadir. Containerfile o yolu | ||
| 140 | +# /models/ses_modelleri'ne sembolik bagla baglar; ayri bir degisken YOKTUR | ||
| 141 | +# (kaynak dogrulandi: ses/ayar.py:26 MODEL_KOKU, :186 ASR_KOK). | ||
| 142 | + | ||
| 143 | +# --- Imaj build secenekleri (compose `build.args`) ---------------------------- | ||
| 144 | + | ||
| 145 | +# 1 = AGIR bagimliliklar kurulur: torch (CPU tekerlegi) + transformers + easyocr. | ||
| 146 | +# Imaj ~2 GB buyur ve build dakikalarca uzar. UCUNU BIRDEN gate eder cunku | ||
| 147 | +# ucu de ayni torch'a baglidir: | ||
| 148 | +# easyocr -> OCR. Kullanicinin gercek icerigi METIN KATMANI OLMAYAN | ||
| 149 | +# goruntu slaytlaridir; OCR olmadan `ingest` bos metin uretir. | ||
| 150 | +# transformers -> bilgi/erisim.py (e5-large gomme) + ses/motor.py VITS yedek motoru. | ||
| 151 | +# DIKKAT: hattin HICBIR requirements*.txt'inde yazili degil; | ||
| 152 | +# requirements-ses.txt onu "zaten kurulu" varsayiyor. | ||
| 153 | +# torch -> ikisinin de tabani. CPU tekerlegi kullanilir (CUDA CEKILMEZ); | ||
| 154 | +# ASR (faster-whisper) CUDA yoksa cpu/int8'e DUSER - bu | ||
| 155 | +# dogrulandi (ses/dogrula.py:352), hata degil. | ||
| 156 | +# 0 yapilirsa taranmis PDF'ler ACIK uyari ile bos gecer ve gomme/VITS yollari kapanir. | ||
| 157 | +KUR_AGIR=1 | ||
| 158 | + | ||
| 159 | +# --- Backend'in compose kaynaklari (external) -------------------------------- | ||
| 160 | + | ||
| 161 | +# Podcast compose'u backend'in AGINA baglanir ve backend'in DOSYA HACMINI :ro | ||
| 162 | +# monte eder. Ikisinin de adi backend'in COMPOSE PROJE ADINDAN turer | ||
| 163 | +# (`<proje>_default`, `<proje>_hezarfen-data`) ve proje adi varsayilan olarak | ||
| 164 | +# DIZIN ADIDIR. Bu makinede backend dizini `hezarfen_backend-main`, ama | ||
| 165 | +# frontend ve chatbot compose'lari agi `hezarfen_backend_default` diye SABIT | ||
| 166 | +# yaziyor; bu yuzden `deploy/run-stack.ps1` backend'i BILEREK | ||
| 167 | +# `-p hezarfen_backend` ile kaldirir ve asagidaki varsayilanlar tutar. | ||
| 168 | +# Betik ayrica gercek adlari `podman inspect hezarfen-backend`ten OKUR ve | ||
| 169 | +# bu degiskenleri kendisi ayarlar. Elle `podman compose up` yapiyorsan | ||
| 170 | +# ONCE DOGRULA: podman volume ls | podman network ls | ||
| 171 | +HEZARFEN_NET=hezarfen_backend_default | ||
| 172 | +HEZARFEN_DATA_VOLUME=hezarfen_backend_hezarfen-data | ||
| 173 | + | ||
| 174 | +# --- LLM (istege bagli) ------------------------------------------------------ | ||
| 175 | + | ||
| 176 | +# DeepSeek anahtari. TANIMSIZ BIRAKILABILIR — yoklugu boot'u COKERTMEZ, | ||
| 177 | +# yalnizca LLM isteyen formatlari kapatir: | ||
| 178 | +# duz_okuma -> anahtarsiz da sonuna kadar kosar (varsayilan format) | ||
| 179 | +# tek_ogretici -> anahtar ister; anahtarsiz submit -> err `llm_unavailable` | ||
| 180 | +# ogrenci_hoca -> anahtar ister; anahtarsiz submit -> err `llm_unavailable` | ||
| 181 | +# Acilista tek satir log hangi formatlarin acik oldugunu yazar. | ||
| 182 | +# Anahtarin KENDISI hicbir yerde loglanmaz, hata mesajina girmez, diske yazilmaz; | ||
| 183 | +# yalnizca "tanimli / TANIMSIZ" bilgisi gorunur. | ||
| 184 | +# DEEPSEEK_API_KEY=sk-buraya-gercek-anahtar-YAZMA | ||
| 185 | + | ||
| 186 | +# Bitmis (done/failed/cancelled) isleri ve URETTIKLERI ses/script dosyalarini | ||
| 187 | +# kac gun sonra sil. 0 = asla silme (kod varsayilani; veri silmek opt-in). | ||
| 188 | +# Acilista bir kez calisir. Kuyruktaki ve KOSAN isler yasina bakilmadan | ||
| 189 | +# korunur. Silinecek yollar cikti kokunun ALTINDA olmak zorundadir; disari | ||
| 190 | +# isaret eden bir kimlik uyari loglanip ATLANIR. | ||
| 191 | +PODCAST_RETENTION_DAYS=30 | ||
.github/workflows/mutation.ymladded+45 -0
| @@ -0,0 +1,45 @@ | |||
| 1 | +name: mutation | ||
| 2 | + | ||
| 3 | +on: | ||
| 4 | + schedule: | ||
| 5 | + - cron: "0 3 * * 1" | ||
| 6 | + workflow_dispatch: | ||
| 7 | + inputs: | ||
| 8 | + target: | ||
| 9 | + description: "Mutasyon uygulanacak modul" | ||
| 10 | + required: false | ||
| 11 | + default: "src/protocol.py" | ||
| 12 | + | ||
| 13 | +jobs: | ||
| 14 | + mutation: | ||
| 15 | + runs-on: ubuntu-latest | ||
| 16 | + timeout-minutes: 180 | ||
| 17 | + steps: | ||
| 18 | + - name: Servis deposunu al | ||
| 19 | + uses: actions/checkout@v4 | ||
| 20 | + | ||
| 21 | + - name: Python 3.10 | ||
| 22 | + uses: actions/setup-python@v5 | ||
| 23 | + with: | ||
| 24 | + python-version: "3.10" | ||
| 25 | + | ||
| 26 | + - name: Hat deposunu vendor/pipeline icine al | ||
| 27 | + if: vars.PIPELINE_REPO != '' | ||
| 28 | + uses: actions/checkout@v4 | ||
| 29 | + with: | ||
| 30 | + repository: ${{ vars.PIPELINE_REPO }} | ||
| 31 | + ref: ${{ vars.PIPELINE_REF || 'main' }} | ||
| 32 | + token: ${{ secrets.PIPELINE_TOKEN || github.token }} | ||
| 33 | + path: vendor/pipeline | ||
| 34 | + | ||
| 35 | + - name: Mutasyon testi | ||
| 36 | + run: | | ||
| 37 | + hedef="${{ github.event.inputs.target || 'src/protocol.py' }}" | ||
| 38 | + python tools/mutation_test.py "$hedef" | tee mutasyon.log | ||
| 39 | + | ||
| 40 | + - name: Raporu sakla | ||
| 41 | + if: always() | ||
| 42 | + uses: actions/upload-artifact@v4 | ||
| 43 | + with: | ||
| 44 | + name: mutasyon-raporu | ||
| 45 | + path: mutasyon.log | ||
.github/workflows/test.ymladded+99 -0
| @@ -0,0 +1,99 @@ | |||
| 1 | +name: test | ||
| 2 | + | ||
| 3 | +on: | ||
| 4 | + push: | ||
| 5 | + pull_request: | ||
| 6 | + | ||
| 7 | +jobs: | ||
| 8 | + unittest: | ||
| 9 | + runs-on: ubuntu-latest | ||
| 10 | + steps: | ||
| 11 | + - name: Servis deposunu al | ||
| 12 | + uses: actions/checkout@v4 | ||
| 13 | + | ||
| 14 | + - name: Python 3.10 | ||
| 15 | + uses: actions/setup-python@v5 | ||
| 16 | + with: | ||
| 17 | + python-version: "3.10" | ||
| 18 | + | ||
| 19 | + - name: Hat deposunu vendor/pipeline icine al | ||
| 20 | + if: vars.PIPELINE_REPO != '' | ||
| 21 | + uses: actions/checkout@v4 | ||
| 22 | + with: | ||
| 23 | + repository: ${{ vars.PIPELINE_REPO }} | ||
| 24 | + ref: ${{ vars.PIPELINE_REF || 'main' }} | ||
| 25 | + token: ${{ secrets.PIPELINE_TOKEN || github.token }} | ||
| 26 | + path: vendor/pipeline | ||
| 27 | + | ||
| 28 | + - name: Hat kaynagi var mi | ||
| 29 | + run: | | ||
| 30 | + if [ -f vendor/pipeline/script/plan.py ]; then | ||
| 31 | + echo "hat kaynagi VAR - format sozlesmesi testleri kosacak" | ||
| 32 | + else | ||
| 33 | + echo "::warning::vendor/pipeline YOK. regress_format_vocabulary.py'nin" | ||
| 34 | + echo "::warning::3 testi DUSECEK - bu testler format sozlugunu hattin" | ||
| 35 | + echo "::warning::script/plan.py ve router/cli.py dosyalariyla karsilastirir." | ||
| 36 | + echo "::warning::Cozum: depo degiskeni PIPELINE_REPO'yu ayarlayin" | ||
| 37 | + echo "::warning::(ozel depo ise PIPELINE_TOKEN sirri da gerekir)." | ||
| 38 | + fi | ||
| 39 | + | ||
| 40 | + - name: Butunluk kontrolu | ||
| 41 | + run: python -m src.main --validate | ||
| 42 | + | ||
| 43 | + - name: Test paketi | ||
| 44 | + run: python -m unittest discover -s tests -t . --verbose | ||
| 45 | + | ||
| 46 | + - name: Fuzzing kampanyasi (sabit tohumlar, kapi) | ||
| 47 | + run: | | ||
| 48 | + set -e | ||
| 49 | + for seed in 1 2 3; do | ||
| 50 | + echo "--- tohum $seed ---" | ||
| 51 | + python tools/fuzz_test.py --cases 20000 --seed "$seed" --quiet --fail-on-finding | ||
| 52 | + done | ||
| 53 | + | ||
| 54 | + - name: Fuzzing kampanyasi (degisken tohum, bilgilendirme) | ||
| 55 | + continue-on-error: true | ||
| 56 | + run: | | ||
| 57 | + seed="${GITHUB_RUN_NUMBER:-0}" | ||
| 58 | + echo "kosuya ozgu tohum: $seed" | ||
| 59 | + if ! python tools/fuzz_test.py --cases 20000 --seed "$seed" --quiet --fail-on-finding; then | ||
| 60 | + echo "::warning::Degisken tohum yeni bir girdi buldu." | ||
| 61 | + echo "::warning::Bulguyu tools/fuzz_test.py --seed $seed ile yeniden uret," | ||
| 62 | + echo "::warning::tests/fuzz/ icine regresyon testi ekle." | ||
| 63 | + fi | ||
| 64 | + | ||
| 65 | + - name: Yorum ve ASCII disi karakter denetimi | ||
| 66 | + run: | | ||
| 67 | + set -e | ||
| 68 | + if grep -rlP --include='*.py' '[^\x00-\x7F]' src tests tools ; then | ||
| 69 | + echo "::error::src/tests/tools icinde ASCII disi karakter var"; exit 1 | ||
| 70 | + fi | ||
| 71 | + python - <<'PY' | ||
| 72 | + import ast, io, pathlib, sys, tokenize | ||
| 73 | + hata = [] | ||
| 74 | + for p in list(pathlib.Path("src").glob("**/*.py")) + \ | ||
| 75 | + list(pathlib.Path("tests").glob("**/*.py")) + \ | ||
| 76 | + list(pathlib.Path("tools").glob("**/*.py")): | ||
| 77 | + with tokenize.open(p) as f: | ||
| 78 | + for tok in tokenize.generate_tokens(f.readline): | ||
| 79 | + if tok.type == tokenize.COMMENT: | ||
| 80 | + hata.append(f"{p}:{tok.start[0]} yorum") | ||
| 81 | + t = ast.parse(io.open(p, encoding="utf-8").read()) | ||
| 82 | + for n in ast.walk(t): | ||
| 83 | + if isinstance(n, (ast.Module, ast.ClassDef, ast.FunctionDef, | ||
| 84 | + ast.AsyncFunctionDef)) and ast.get_docstring(n): | ||
| 85 | + hata.append(f"{p}:{getattr(n,'lineno',0)} docstring") | ||
| 86 | + if hata: | ||
| 87 | + print("::error::Python kodunda yorum/docstring bulundu (depo kurali: sifir)") | ||
| 88 | + for h in hata[:20]: | ||
| 89 | + print(" ", h) | ||
| 90 | + sys.exit(1) | ||
| 91 | + print("yorum/docstring: sifir") | ||
| 92 | + PY | ||
| 93 | + | ||
| 94 | + - name: Sir taramasi | ||
| 95 | + run: | | ||
| 96 | + if grep -rInE 'sk-[A-Za-z0-9]{10,}' --exclude-dir=vendor --exclude-dir=.git . ; then | ||
| 97 | + echo "::error::Depoda API anahtari deseni bulundu"; exit 1 | ||
| 98 | + fi | ||
| 99 | + echo "sir taramasi temiz" | ||
.gitignoreadded+12 -0
| @@ -0,0 +1,12 @@ | |||
| 1 | +.venv | ||
| 2 | +__pycache__/ | ||
| 3 | +*.py[cod] | ||
| 4 | +*.log | ||
| 5 | +.pytest_cache/ | ||
| 6 | +.coverage | ||
| 7 | +.agents | ||
| 8 | +.env | ||
| 9 | +out/ | ||
| 10 | +vendor/ | ||
| 11 | +.coverage.* | ||
| 12 | +htmlcov/ | ||
CLAUDE.mdadded+104 -0
| @@ -0,0 +1,104 @@ | |||
| 1 | +# CLAUDE.md — hezarfen_podcast_service | ||
| 2 | + | ||
| 3 | +## Ne bu proje | ||
| 4 | +Hezarfen'in dördüncü servisi: podcast üretimi. Kablo + **gerçek iş yaşam döngüsü** | ||
| 5 | +(kuyruk, diskte kalıcı durum, işbirlikçi iptal, açılış süpürmesi) hazır. Gerçek | ||
| 6 | +hat `src/pipeline.py` ile bagli ve konteyner icinde gercek PDF -> MP3 uretimiyle | ||
| 7 | +dogrulandi (her iki formatta, cok bolumlu ornek dahil). `tools/smoke_test.py` | ||
| 8 | +bunu tekrarlar; `tools/mutation_test.py` slayt operatorleriyle mutasyon skoru olcer. | ||
| 9 | + | ||
| 10 | +## Değişmez kurallar (gerekçesiyle) | ||
| 11 | +- **Podman, Docker değil.** Dosya adı `Containerfile`; `podman compose` kullanılır. | ||
| 12 | +- **Kodda yorum yok** — ne `#` ne docstring. Açıklama `ReadMe.md`'ye yazılır. | ||
| 13 | + Kullanıcının açık talimatı. | ||
| 14 | +- **Port açma, HTTP sunucusu açma.** Servis backend'in QUIC'ine *dial-out* eder; | ||
| 15 | + NAT ardında yaşayabilsin ve backend tek otorite kalsın diye. | ||
| 16 | +- **Sertifikayı her reconnect'te yeniden çek.** Backend self-signed sertifikayı her | ||
| 17 | + açılışta üretir; sadece redial etmek eski PEM'e güvenmek olur. | ||
| 18 | +- **Kontrol akışı ömür boyu açık kalır** (`end_stream=False`). Kapanması backend | ||
| 19 | + için kayıttan düşme sinyalidir; heartbeat yok, QUIC PING (10 sn) var. | ||
| 20 | +- **Token loglanmaz, koda/belgeye yazılmaz.** Parmak izinin ilk 12 karakteri | ||
| 21 | + loglanabilir; `compose.yaml` interpolasyon kullanır, literal sır yazmaz. | ||
| 22 | +- **Log mesajları Türkçe ama ASCII**, `[bridge] ` önekli, `print(..., flush=True)`. | ||
| 23 | + Windows konsolu ASCII dışını bozuyor; `logging` modülü kullanılmaz. | ||
| 24 | +- **Tanımlayıcılar İngilizce**, Python 3.10+ uyumlu. | ||
| 25 | +- **Yanlış yapılandırma boot'u çökertir** (exit 2), eksik yapılandırma özelliği | ||
| 26 | + sessizce kapatır. Backend'in kendi kuralı; iki repo aynı davranmalı. | ||
| 27 | + `DEEPSEEK_API_KEY` bunun örneğidir: yoksa yalnızca `duz_okuma` açılır, boot çökmez. | ||
| 28 | +- **Yetenek işleyicileri anında döner.** Backend'in istek deadline tavanı 60 sn | ||
| 29 | + (`constant.rs::AI_MAX_REQUEST_TIMEOUT_SECS`), gerçek iş ~45 dk. Uzun iş `jobs.py` | ||
| 30 | + içindeki **ayrı, daemon** işçi thread'lerinde koşar (kuyruk + `None` sentinel); | ||
| 31 | + asyncio'nun varsayılan executor'ı uzun iş için ASLA kullanılmaz. | ||
| 32 | +- **`ThreadPoolExecutor` kullanılmaz.** Thread'leri daemon değildir; `shutdown` | ||
| 33 | + anında dönse bile yorumlayıcı çıkışta onları join eder ve 45 dakikalık iş | ||
| 34 | + SIGTERM'i SIGKILL'e çevirir. İşçi thread'leri `daemon=True` olmak zorunda. | ||
| 35 | +- **Uzun iş `JobContext` üzerinden konuşur.** `runner` imzası | ||
| 36 | + `Callable[[JobContext], None]`; iptal `ctx.check()`, ilerleme `ctx.progress()`, | ||
| 37 | + bitiş `ctx.finish()`. `begin()`'i işçi çağırır, runner değil. | ||
| 38 | +- **İş durumu diske atomik yazılır** (geçici dosya + `os.replace`) ve açılışta | ||
| 39 | + `running` işler `failed`/`interrupted` olur — backend'in boot süpürmesinin kopyası. | ||
| 40 | +- **API anahtarı asla loglanmaz/yazılmaz**; `Config` yalnızca `has_llm_key` tutar. | ||
| 41 | +- **Sessiz sahte üretim yasak.** `PODCAST_MODE=simulate` açılışta tek satır | ||
| 42 | + "SAHTE hat kosuyor, uretilen ses GERCEK DEGIL" uyarısı basar; | ||
| 43 | + `PODCAST_MODE=real` ise `PODCAST_PIPELINE_PATH` yok/bozuksa ya da | ||
| 44 | + `router.hat` import edilemiyorsa **exit 2**. | ||
| 45 | +- **Gerçek hat TEMBEL import edilir.** `pipeline.py` modül seviyesinde | ||
| 46 | + `router.hat`'ı import etmez; `--validate` ve `simulate` modu onu hiç yüklemez. | ||
| 47 | +- **Kancadan `KasitliKesme` fırlatılır**, kendi istisnamız değil: `Hat.kos()` | ||
| 48 | + onu ayrıca yakalayıp koşuyu "kesildi" diye kapatır; kendi istisnamız koşuyu | ||
| 49 | + "hata" yapar ve resume semantiğini bozardı. | ||
| 50 | +- **İptal adım sınırındadır.** `gunluk` çoğunlukla `_adim_ekle`'den çağrılır (hepsi değil); | ||
| 51 | + 34 dakikalık bir adımın ortasında iptal görülemez. Bu bir sınırdır, gizlenmez. | ||
| 52 | +- **Hat imaja VENDOR edilir, bind-mount edilmez.** `deploy/setup-pipeline.ps1` | ||
| 53 | + kaynağı `vendor/pipeline`'a kopyalar (tek yönlü; `vendor/` gitignore'da), | ||
| 54 | + Containerfile onu `/app/pipeline`'a alır. Ağırlıklar (~3,9 GB ölçüldü) imaja | ||
| 55 | + GİRMEZ, `podcast-models` hacminden `:ro` gelir. `ses/ayar.py` ffmpeg ve model | ||
| 56 | + yollarını SABIT kodlar; ikisi de kaynağa dokunmadan sembolik bağla çözülür. | ||
| 57 | +- **Sağlık compose'da, Containerfile'da DEĞİL.** Podman OCI biçiminde imajdaki | ||
| 58 | + HEALTHCHECK'i yok sayar. `python -m src.main --health` ağ çağrısı yapmaz. | ||
| 59 | +- **Her build etiketlenir** (`:<zaman damgası>` + `:current`); compose | ||
| 60 | + `:current` kullanır. `:local` gibi tek etiket geri dönüşü imkânsız kılardı. | ||
| 61 | +- **Kablo sözleşmesi kırılmaz.** Çok bölümlü koşu için `audio_id`/`script_id` | ||
| 62 | + tekil kaldı; `audio_ids`/`script_ids` **eklendi**. Alan eklemek geriye dönük | ||
| 63 | + uyumludur, yeniden adlandırmak değildir. | ||
| 64 | + | ||
| 65 | +- **Fuzz yükleri kaçış dizisiyle yazılır.** Depo kuralı `src/tests/tools` altında | ||
| 66 | + ASCII dışı karakter yasaklar (CI kapısı), ama fuzzing UTF-8 yollarını sınamak için | ||
| 67 | + ASCII dışı **değerlere** ihtiyaç duyar. Çözüm: dosyada `"ç"`, değerde `ç`. | ||
| 68 | + Ham karakter yazmak CI'ı kırar. | ||
| 69 | +- **Fuzzer'ın izleyicisi önceki izleyiciyi geri koyar.** `sys.settrace(None)` demek | ||
| 70 | + `coverage`'ın izleyicisini de kapatmak demektir; ölçüm sessizce durur. | ||
| 71 | + `sys.gettrace()` ile saklanır, `finally` içinde geri konur. | ||
| 72 | +- **Model tabanlı testte W kümesi elle seçilmez**, bölüntü inceltme + geriye eleme | ||
| 73 | + ile hesaplanır. Elle yazılan bir W kümesi değişim-dedektörüdür; hesaplanan küme | ||
| 74 | + modelin özelliğidir. `JobStore` modeli 7 durumludur (`cancel_requested` bayrağı | ||
| 75 | + `running` ve `failed` durumlarını ikiye böler), 5 değil. | ||
| 76 | + | ||
| 77 | +## Dosyalar ve komutlar | ||
| 78 | +`config.py` ortam+log · `protocol.py` çerçeveleme+mesajlar · `jobs.py` iş deposu+ | ||
| 79 | +durum makinesi+sahte hat · `pipeline.py` gerçek `router.hat.Hat` runner'ı (tembel | ||
| 80 | +import) · `capabilities.py` yetenek defteri · `bridge.py` QUIC istemcisi · | ||
| 81 | +`main.py` `--validate` + `--health` · `tools/smoke_test.py` elle koşulan duman testi · | ||
| 82 | +`tools/mutation_test.py` slayt operatörleriyle mutasyon skoru · `tools/fuzz_test.py` | ||
| 83 | +altı slayt kategorisi + şablon/gramer/kapsam-geri-besleme fuzzing · | ||
| 84 | +`deploy/` dağıtım katmanı (`OKU.md` rehber, `setup-pipeline.ps1` hat kaynağını | ||
| 85 | +`vendor/pipeline`'a kopyalar, `setup-models.ps1` ağırlıkları `podcast-models` | ||
| 86 | +hacmine koyar, `run-stack.ps1` dört repoyu sırayla kaldırır, `rollback.ps1` | ||
| 87 | +`:current` etiketini önceki imaja taşır). | ||
| 88 | +- `python -m src.main --validate` — ağ ve `aioquic` GEREKTİRMEZ; import'ları tembel | ||
| 89 | + tut ki imajın varsayılan `CMD`'si her yerde çalışsın. | ||
| 90 | +- `python -m src.bridge` — köprü (aioquic + `AI_SHARED_TOKEN` şart). | ||
| 91 | +- `python -m unittest discover -s tests -t .` — tüm test paketi (saf `unittest`, | ||
| 92 | + **pytest YOK**). `tests/unit/` birim, `tests/integration/` uçtan uca (sahte `Hat`, | ||
| 93 | + gerçek `JobStore`), `tests/regress/` ölçülerek bulunmuş her kusur için bir dosya, | ||
| 94 | + `tests/fuzz/` ayrıştırıcı sözleşmesi, `tests/model/` W yöntemi uygunluk kümesi. | ||
| 95 | + `regress_*.py` dosyalarını `tests/regress/__init__.py` içindeki `load_tests` katar. | ||
| 96 | + **Test kodunda da yorum ve docstring yok**; açıklama test metot adında ve assert | ||
| 97 | + mesajında durur. Testler ağ kullanmaz, `aioquic` gerektirmez, gerçek hattı import | ||
| 98 | + etmez, `PODCAST_JOB_ROOT`'a yazmaz (`tempfile`). `--validate` bunun yerine geçmez: | ||
| 99 | + o çalışma-zamanı bütünlük kontrolüdür ve küçültülmez. | ||
| 100 | + | ||
| 101 | +## Referanslar | ||
| 102 | +Kablo sözleşmesi: `hezarfen_backend/src/ai/protocol.rs`; referans istemci | ||
| 103 | +`hezarfen_backend/tests/ai_protocol.rs` (`raw`) ve chatbot'un `src/bridge.py`'si. | ||
| 104 | +Sözleşme değişirse önce oradan doğrula. | ||
Containerfileadded+76 -0
| @@ -0,0 +1,76 @@ | |||
| 1 | +# Digest'e PINLI: `:3.10-slim` etiketi upstream'de yeniden yayimlanabilir ve | ||
| 2 | +# ayni Containerfile farkli bir taban imajla derlenebilir. Digest icerigi | ||
| 3 | +# sabitler. Yenilerken: podman pull docker.io/library/python:3.10-slim && | ||
| 4 | +# podman images --digests docker.io/library/python | ||
| 5 | +FROM docker.io/library/python:3.10-slim@sha256:4101e4a31b9d2c927c9052ae2fa58b76a89265997ec9209c02933d9974214b80 | ||
| 6 | + | ||
| 7 | +ARG KUR_AGIR=1 | ||
| 8 | +ARG TORCH_INDEX=https://download.pytorch.org/whl/cpu | ||
| 9 | + | ||
| 10 | +ENV PYTHONDONTWRITEBYTECODE=1 \ | ||
| 11 | + PYTHONUNBUFFERED=1 \ | ||
| 12 | + PIP_DISABLE_PIP_VERSION_CHECK=1 \ | ||
| 13 | + HF_HOME=/models/hf \ | ||
| 14 | + TORCH_HOME=/models/torch \ | ||
| 15 | + PYTHONPATH=/app/pipeline | ||
| 16 | + | ||
| 17 | +WORKDIR /app | ||
| 18 | + | ||
| 19 | +RUN apt-get update \ | ||
| 20 | + && apt-get install --no-install-recommends --yes \ | ||
| 21 | + ffmpeg \ | ||
| 22 | + ca-certificates \ | ||
| 23 | + libgl1 \ | ||
| 24 | + libglib2.0-0 \ | ||
| 25 | + && rm -rf /var/lib/apt/lists/* | ||
| 26 | + | ||
| 27 | +COPY requirements.txt ./ | ||
| 28 | +RUN pip install --no-cache-dir --requirement requirements.txt | ||
| 29 | + | ||
| 30 | +COPY vendor/pipeline/requirements.txt ./hat-req/requirements.txt | ||
| 31 | +COPY vendor/pipeline/requirements-ses.txt ./hat-req/requirements-ses.txt | ||
| 32 | +COPY vendor/pipeline/requirements-ocr.txt ./hat-req/requirements-ocr.txt | ||
| 33 | + | ||
| 34 | +RUN pip install --no-cache-dir \ | ||
| 35 | + --requirement hat-req/requirements.txt \ | ||
| 36 | + --requirement hat-req/requirements-ses.txt \ | ||
| 37 | + && pip install --no-cache-dir \ | ||
| 38 | + onnxruntime==1.23.2 \ | ||
| 39 | + numpy==2.2.6 \ | ||
| 40 | + huggingface_hub==1.27.0 | ||
| 41 | + | ||
| 42 | +RUN if [ "$KUR_AGIR" = "1" ]; then \ | ||
| 43 | + pip install --no-cache-dir \ | ||
| 44 | + --index-url "$TORCH_INDEX" \ | ||
| 45 | + --extra-index-url https://pypi.org/simple \ | ||
| 46 | + torch torchvision \ | ||
| 47 | + && pip install --no-cache-dir transformers==5.15.0 \ | ||
| 48 | + && pip install --no-cache-dir --requirement hat-req/requirements-ocr.txt ; \ | ||
| 49 | + else \ | ||
| 50 | + echo "KUR_AGIR=0 -> torch / transformers / easyocr ATLANDI" ; \ | ||
| 51 | + fi | ||
| 52 | + | ||
| 53 | +COPY vendor/pipeline /app/pipeline | ||
| 54 | +COPY src ./src | ||
| 55 | +COPY tools ./tools | ||
| 56 | + | ||
| 57 | +RUN python tools/dependency_scanner.py /app/pipeline | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +RUN useradd --create-home --uid 10001 podcast \ | ||
| 61 | + && mkdir -p /models/hf /models/torch \ | ||
| 62 | + /data/podcast/jobs /data/podcast/out /data/podcast/kayit \ | ||
| 63 | + /data/podcast/out/_hat /home/podcast/.EasyOCR \ | ||
| 64 | + /app/pipeline/data /app/pipeline/tools/bin \ | ||
| 65 | + && rm -f /app/pipeline/tools/bin/ffmpeg.exe /app/pipeline/tools/bin/ffprobe.exe \ | ||
| 66 | + && ln -sf /usr/bin/ffmpeg /app/pipeline/tools/bin/ffmpeg.exe \ | ||
| 67 | + && ln -sf /usr/bin/ffprobe /app/pipeline/tools/bin/ffprobe.exe \ | ||
| 68 | + && rm -rf /app/pipeline/data/ses_modelleri \ | ||
| 69 | + && ln -sf /models/ses_modelleri /app/pipeline/data/ses_modelleri \ | ||
| 70 | + && rm -rf /app/pipeline/out \ | ||
| 71 | + && ln -sf /data/podcast/out/_hat /app/pipeline/out \ | ||
| 72 | + && chown -R podcast:podcast /app /data/podcast /models /home/podcast | ||
| 73 | + | ||
| 74 | +USER podcast | ||
| 75 | + | ||
| 76 | +CMD ["python", "-m", "src.main", "--validate"] | ||
README.mdmodified+1114 -1
| @@ -1 +1,1114 @@ | |||
| 1 | -test | 1 | +# hezarfen_podcast_service |
| 2 | + | ||
| 3 | +Hezarfen okul sisteminin dördüncü servisi: ders içeriğinden podcast üreten AI | ||
| 4 | +servisi. Kablo çalışır, **iş yaşam döngüsü gerçektir** (kuyruk, diskte kalıcı | ||
| 5 | +durum, işbirlikçi iptal, açılış süpürmesi), **gerçek hat bağlıdır** | ||
| 6 | +(`PODCAST_MODE=real`) ve **dağıtım katmanı yazılmıştır** (`deploy/`). | ||
| 7 | + | ||
| 8 | +Hâlâ eksik olan tek şey **kanıt**: gerçek hat bu repodan bir kez bile | ||
| 9 | +koşturulmadı ve imaj bir kez bile build edilmedi (bkz. "BİLİNEN EKSİKLER"). | ||
| 10 | + | ||
| 11 | +## Nasıl konumlanır | ||
| 12 | + | ||
| 13 | +Servis **HTTP sunucusu açmaz, port dinlemez**. Rust backend (`hezarfen_backend`) | ||
| 14 | +QUIC *sunucusudur*; bu servis ona **dışarıdan bağlanır** (dial-out), yeteneklerini | ||
| 15 | +kaydeder ve backend'in açtığı akışlardan iş alır. Rule-based chatbot ile birebir | ||
| 16 | +aynı konumlanma. | ||
| 17 | + | ||
| 18 | +## Protokol (`hab/1`) | ||
| 19 | + | ||
| 20 | +Çerçeveleme: 4 bayt big-endian uzunluk + o kadar bayt JSON. Tavan 8 MiB. | ||
| 21 | + | ||
| 22 | +1. `GET {AI_BACKEND_URL}/ai/certificate` → dönen PEM QUIC güven deposuna | ||
| 23 | + **pinlenir**. Backend self-signed sertifikayı her açılışta yenileyebildiği için | ||
| 24 | + sertifika **her yeniden bağlanmada tekrar çekilir**; salt redial yanlıştır. | ||
| 25 | +2. QUIC bağlantısı, ALPN `hab/1`, idle timeout 30 sn. | ||
| 26 | +3. İlk client-initiated çift yönlü akış = **kontrol akışı**: tek `Hello` yazılır, | ||
| 27 | + tek `Greeting` okunur, akış ömür boyu açık tutulur (kapanması = kayıttan | ||
| 28 | + düşme). Heartbeat çerçevesi yok; 10 sn'de bir QUIC PING ile canlı tutulur. | ||
| 29 | +4. Her istek backend'in açtığı server-initiated akıştır (`stream_id % 4 == 1`): | ||
| 30 | + tek `Request` okunur, tek `Response` yazılır, akış biter. | ||
| 31 | + | ||
| 32 | +Cevaplar: `{"status":"ok","id":...,"payload":{...}}` veya | ||
| 33 | +`{"status":"err","id":...,"code":...,"message":...}`. Kullanılan kararlı kodlar: | ||
| 34 | +`unsupported_capability`, `bad_request`, `not_found`, `not_ready`, | ||
| 35 | +`llm_unavailable`, `frame_too_large`, `timed_out`, `busy`, `internal`. | ||
| 36 | + | ||
| 37 | +## Neden yetenek işleyicileri anında döner | ||
| 38 | + | ||
| 39 | +Backend'in her `hab/1` isteği için bir deadline'ı var ve **tavanı 60 saniyedir** | ||
| 40 | +(`hezarfen_backend/src/constant.rs`, `AI_MAX_REQUEST_TIMEOUT_SECS`). Gerçek | ||
| 41 | +podcast üretimi ise **~45 dakika** sürer. Bu iki sayı aynı çağrının içine sığmaz. | ||
| 42 | + | ||
| 43 | +Bu yüzden mimari ikiye bölünmüştür: | ||
| 44 | + | ||
| 45 | +- `podcast.submit` / `status` / `result` / `cancel` **yalnızca iş deposuna | ||
| 46 | + dokunur ve anında döner.** Hiçbiri uzun işi beklemez. | ||
| 47 | +- Uzun iş **ayrı, `daemon=True` işaretli işçi thread'lerinde** koşar; işler | ||
| 48 | + `queue.Queue` üzerinden dağıtılır. asyncio'nun varsayılan executor'ı bilerek | ||
| 49 | + kullanılmaz: dakikalarca süren bir iş o havuzu tıkar ve milisaniyelik `status` | ||
| 50 | + çağrıları da kuyruğa girerdi. | ||
| 51 | + | ||
| 52 | +`ThreadPoolExecutor` **bilinçli olarak kullanılmaz.** `shutdown(wait=False, | ||
| 53 | +cancel_futures=True)` anında döner ama executor'ın thread'leri daemon değildir; | ||
| 54 | +yorumlayıcı çıkışta onları yine de `join` eder. Ölçüldü: 8 saniyelik bir iş | ||
| 55 | +koşarken `shutdown` 0 ms'de döndü, **süreç 8079 ms yaşadı**. 45 dakikalık gerçek | ||
| 56 | +iş ile bu, SIGTERM → takılma → compose süre aşımı → SIGKILL demektir. Daemon | ||
| 57 | +thread'lerde aynı ölçüm 1465 ms'dir (`shutdown(timeout=1.0)` kadar), işçi | ||
| 58 | +`JobContext.check()` çağırıyorsa 403 ms. | ||
| 59 | + | ||
| 60 | +`JobStore.shutdown(timeout=10.0)` sırasıyla: `stopping` bayrağını kaldırır, | ||
| 61 | +koşan tüm işlere iptal bayrağı koyar, her thread için kuyruğa bir `None` sentinel | ||
| 62 | +bırakır, thread'leri **toplam** `timeout` bütçesi içinde `join` eder, hâlâ | ||
| 63 | +yaşayan varsa tek satır uyarı basıp döner. Daemon oldukları için süreç çıkabilir. | ||
| 64 | +Henüz başlamamış `queued` işlere **dokunulmaz** — `begin()` kapanma sırasında | ||
| 65 | +işi başlatmadan `False` döner, iş `queued` kalır ve bir sonraki açılışta yeniden | ||
| 66 | +kuyruğa alınır. | ||
| 67 | + | ||
| 68 | +İki eşiği karıştırmayın: `AI_MAX_CONCURRENT` aynı anda işlenen **istek** | ||
| 69 | +sayısıdır (aşılırsa `busy`), `PODCAST_MAX_JOBS` ise kuyruktaki + koşan **iş** | ||
| 70 | +sayısıdır (aşılırsa yine `busy`, ama `podcast.submit` içinden). | ||
| 71 | + | ||
| 72 | +## Yetenekler | ||
| 73 | + | ||
| 74 | +| Yetenek | İstek payload'u | Başarılı cevap | Hatalar | | ||
| 75 | +| --- | --- | --- | --- | | ||
| 76 | +| `podcast.submit` | `source_id` (zorunlu metin), `format` (ops.) | `{"job_id":...,"state":"queued","eta_secs":<int>}` | `bad_request`, `busy`, `llm_unavailable` | | ||
| 77 | +| `podcast.status` | `job_id` (zorunlu metin) | `{"job_id":...,"state":...,"stage":<metin>,"progress":<0.0-1.0>,"error_code":<metin\|null>}` | `bad_request`, `not_found` | | ||
| 78 | +| `podcast.result` | `job_id` (zorunlu metin) | `{"job_id":...,"audio_id":...,"duration_secs":<float>,"script_id":...,"format":...}` | `bad_request`, `not_found`, `not_ready` | | ||
| 79 | +| `podcast.cancel` | `job_id` (zorunlu metin) | `{"job_id":...,"cancelled":<bool>}` | `bad_request`, `not_found` | | ||
| 80 | + | ||
| 81 | +Payload tipleri katı doğrulanır; uymayan istek `bad_request` alır. | ||
| 82 | + | ||
| 83 | +`podcast.result` işi bitmemişse `not_ready` döner — `not_found` **değil**; | ||
| 84 | +"böyle bir iş yok" ile "iş var ama henüz hazır değil" çağıran için farklı | ||
| 85 | +şeylerdir ve ikincisi tekrar denemeye değer. | ||
| 86 | + | ||
| 87 | +`podcast.cancel`'ın `cancelled` alanı **"bu çağrı bir şeyi iptal etti mi"** | ||
| 88 | +sorusunun cevabıdır: kuyruktaki ya da koşan bir iş için `true`, zaten | ||
| 89 | +`done`/`failed`/`cancelled` olmuş bir iş için `false`. Var olmayan iş `not_found` | ||
| 90 | +alır, `false` almaz. | ||
| 91 | + | ||
| 92 | +**Kablo anahtarları İngilizce.** Backend (Rust) ve frontend (TypeScript) bu | ||
| 93 | +alanları tüketiyor ve o iki tarafın tüm alan adları İngilizce (`status`, | ||
| 94 | +`error_code`, `created_at`). Türkçe olan tek şey log ve hata metinleri. | ||
| 95 | + | ||
| 96 | +**`source_id` bir dosya yolu DEĞİLDİR.** Backend'in kayıt kimliğidir; PDF | ||
| 97 | +baytı köprüden geçmez (`AI_API_ALLOWLIST` bayt sunan rotaları bilerek | ||
| 98 | +dışarıda bırakıyor, `constant.rs:612-615`). Kimliğin paylaşılan hacimdeki | ||
| 99 | +dosyaya nasıl çözüleceği sonraki adımın konusudur. | ||
| 100 | + | ||
| 101 | +## Durum makinesi | ||
| 102 | + | ||
| 103 | +``` | ||
| 104 | +queued ──▶ running ──▶ done | ||
| 105 | + │ │ ├─────▶ failed | ||
| 106 | + │ │ └─────▶ cancelled | ||
| 107 | + │ └─────────────▶ failed | ||
| 108 | + └───────────────▶ cancelled | ||
| 109 | +``` | ||
| 110 | + | ||
| 111 | +`queued → failed` **yasaldır**: iş `begin()`'den önce de patlayabilir (gerçek | ||
| 112 | +hatta örneğin `source_id` dosyaya çözülemez → `HatHatasi`). Bu geçiş yasak | ||
| 113 | +olsaydı `fail()` `InvalidTransition` yer, iş `queued` kalır, her açılışta | ||
| 114 | +yeniden kuyruğa alınır, yine patlar ve `PODCAST_MAX_JOBS` kotasından bir slotu | ||
| 115 | +kalıcı olarak yerdi. | ||
| 116 | + | ||
| 117 | +`done`, `failed`, `cancelled` **terminaldir**; çıkış geçişleri yoktur. Geçersiz | ||
| 118 | +bir geçiş denemesi `InvalidTransition` fırlatır — **sessizce yutulmaz**. Bunun | ||
| 119 | +sebebi savunuculuk değil teşhis: sessizce yutulan bir geçiş, ilerideki gerçek | ||
| 120 | +hatta "iş neden hâlâ `running` görünüyor" sorusunu cevaplanamaz hale getirir. | ||
| 121 | + | ||
| 122 | +## İş deposu ve kalıcılık | ||
| 123 | + | ||
| 124 | +İş durumu **iş başına bir JSON dosyası** olarak `PODCAST_JOB_ROOT` altında | ||
| 125 | +tutulur (`{job_id}.json`). Her yazma **atomiktir**: geçici dosyaya yaz → `flush` | ||
| 126 | +→ `fsync` → `os.replace`. Yarım yazılmış bir JSON dosyası hiçbir zaman görünmez; | ||
| 127 | +`os.replace` aynı dosya sisteminde atomik bir isim değiştirmedir. | ||
| 128 | + | ||
| 129 | +Durum diskte tutulur çünkü **servis yeniden başladığında iş durumu | ||
| 130 | +kaybolmamalıdır**. Container'da bu dizin adlandırılmış bir hacme (`podcast-jobs`) | ||
| 131 | +bağlanır; imaj içinde uid 10001'e ait olarak önceden yaratılır, yoksa hacim root | ||
| 132 | +sahipliğiyle oluşur ve servis ilk yazmada `EACCES` alır. | ||
| 133 | + | ||
| 134 | +Yazma sırası **önce disk, sonra bellek**tir ve bu iki yerde birden geçerlidir: | ||
| 135 | + | ||
| 136 | +- `submit()` kaydı **önce diske yazar**, ancak yazma başarılıysa belleğe koyar. | ||
| 137 | + Ters sırada bir `OSError`, hiç koşmayacak ve hiç temizlenmeyecek bir `queued` | ||
| 138 | + kaydı bırakır ve `PODCAST_MAX_JOBS` kotasından bir slotu kalıcı yerdi. | ||
| 139 | +- `transition()` / `update_progress()` / `cancel()` / açılış süpürmesi kaydın bir | ||
| 140 | + **kopyası** üzerinde çalışır, kopyayı yazar, ancak yazma başarılıysa | ||
| 141 | + `record.clear()` + `record.update()` ile commit eder (kaydın kimliği korunur). | ||
| 142 | + Tersi durumda bellek `done`, disk `running` derdi ve iş bir sonraki açılışta | ||
| 143 | + `interrupted` işaretlenirdi. | ||
| 144 | + | ||
| 145 | +Geçici dosya adı iş-id başına sabit değildir; `{job_id}.json.tmp{pid}-{rastgele}` | ||
| 146 | +biçimindedir, böylece iki süreç birbirinin geçici dosyasını ezmez. Açılışta | ||
| 147 | +`*.json.tmp*` artıkları silinir (silinemezse uyarı basılır, açılış çökmez). | ||
| 148 | +`os.replace` sonrası **dizin de fsync'lenir** ki yeniden adlandırma metadata'sı | ||
| 149 | +diske insin; Windows dizin fsync'i desteklemez, oradaki `OSError` sessizce | ||
| 150 | +geçilir (platform farkı, hata değil). | ||
| 151 | + | ||
| 152 | +Açılışta kayıtlar **şema doğrulamasından** geçer: zorunlu alanlardan (`job_id`, | ||
| 153 | +`source_id`, `format`, `state`, `stage`, `progress`, `error_code`, | ||
| 154 | +`cancel_requested`, `audio_id`, `duration_secs`, `script_id`, `created_at`, | ||
| 155 | +`updated_at`) biri eksikse kayıt uyarı ile atlanır. Aksi halde geçerli JSON ama | ||
| 156 | +eksik alanlı bir dosya yüklenir, `podcast.status` `KeyError` atar ve köprü o iş | ||
| 157 | +için sonsuza kadar `internal` döner. | ||
| 158 | + | ||
| 159 | +Dosya adı ile içerideki `job_id` uyuşmayan kayıtlar açılışta atlanır; `job_id` | ||
| 160 | +hiçbir zaman kullanıcı girdisinden dosya yoluna çevrilmez (arama bellekteki | ||
| 161 | +sözlük üzerinden yapılır), bu yüzden yol kaçışı mümkün değildir. | ||
| 162 | + | ||
| 163 | +### Açılış süpürmesi | ||
| 164 | + | ||
| 165 | +Açılışta `running` durumundaki işler `failed` + `error_code: "interrupted"` | ||
| 166 | +olarak işaretlenir. Gerekçe: o işi koşan iş parçacığı artık yoktur, dolayısıyla o | ||
| 167 | +işi bitirecek kimse kalmamıştır — `running` bırakmak sonsuza kadar cevap | ||
| 168 | +bekleyen bir kayıt üretirdi. Bu, backend'in kendi desenini birebir kopyalar | ||
| 169 | +(`hezarfen_backend/src/migration_sql.rs`, `chatbot_message` boot süpürmesi; | ||
| 170 | +orada da kod `interrupted`'dır). | ||
| 171 | + | ||
| 172 | +`queued` işler **süpürülmez** — henüz kimse onlara dokunmadı, bilgi | ||
| 173 | +kaybolmadı — açılışta yeniden kuyruğa alınır. | ||
| 174 | + | ||
| 175 | +### İptal işbirlikçidir | ||
| 176 | + | ||
| 177 | +`podcast.cancel` bir **bayrak** koyar. İşçi `JobContext.check()` çağırdığı her | ||
| 178 | +noktada bayrağı okur; gördüğü anda `JobCancelled` fırlar ve iş `cancelled` | ||
| 179 | +durumuna geçer. Thread zorla öldürülmez: Python'da bir thread'i dışarıdan | ||
| 180 | +öldürmenin güvenli yolu yoktur ve gerçek hat yarıda kesilirse yarım dosyalar | ||
| 181 | +bırakır. | ||
| 182 | + | ||
| 183 | +**İptal kaybolmaz.** İptal, koşan aşamanın bitmesini bekler; ya bir aşama | ||
| 184 | +sınırında (`check()`) ya da **işin bitişinde** yakalanır. `finish()` `done`'a | ||
| 185 | +geçmeden **aynı kilidin altında** `cancel_requested` bayrağını okur; bayrak | ||
| 186 | +konmuşsa iş `done` yerine `cancelled` olur ve `audio_id` yazılmaz. Bu, `cancel` | ||
| 187 | +çağrısına `cancelled=true` deyip işi yine de `done` bitirme yarışını kapatır — | ||
| 188 | +sahte hatta o pencere mikrosaniyeydi, gerçek hatta **45 dakika** genişliğinde | ||
| 189 | +olurdu. | ||
| 190 | + | ||
| 191 | +Kuyruktaki bir iş için iptal anında etki eder; işçi işi almadan önce | ||
| 192 | +`cancelled` görüp hiç başlamaz. | ||
| 193 | + | ||
| 194 | +### `JobContext` — gerçek hattın iptal ve ilerleme kanalı | ||
| 195 | + | ||
| 196 | +`runner` imzası `Callable[[JobContext], None]`'dır. `begin()` çağrısını **işçi | ||
| 197 | +yapar**, runner değil; `begin()` `False` dönerse (iş kuyrukta değil, ya da | ||
| 198 | +başlamadan iptal edildi) runner hiç çağrılmaz. | ||
| 199 | + | ||
| 200 | +| Üye | Anlamı | | ||
| 201 | +| --- | --- | | ||
| 202 | +| `ctx.job_id` / `ctx.source_id` / `ctx.format` | kaydın kimliği, kaynak kimliği, formatı | | ||
| 203 | +| `ctx.stages` | `JobStore.stages` (aşama adları) | | ||
| 204 | +| `ctx.cancelled()` | iptal bayrağı **veya** servis kapanıyor mu | | ||
| 205 | +| `ctx.check()` | iptal varsa `JobCancelled` fırlatır, yoksa `None` | | ||
| 206 | +| `ctx.progress(stage, value)` | `stage` + `0.0-1.0` ilerleme yazar | | ||
| 207 | +| `ctx.finish(audio_id, duration_secs, script_id, audio_ids=None, script_ids=None)` | işi bitirir (iptal varsa `cancelled` döner). Son iki argüman **isteğe bağlıdır** ve verilmezse tekil kimliklerden türetilir — çok bölümlü koşu için eklendi, eski çağrılar aynen çalışır | | ||
| 208 | + | ||
| 209 | +İşçi `JobCancelled`'ı yakalar ve `abort()` çağırır; başka her `Exception` | ||
| 210 | +`failed` + `error_code: "internal"` olur. | ||
| 211 | + | ||
| 212 | +## Mod kapısı: `PODCAST_MODE` | ||
| 213 | + | ||
| 214 | +Servis **iki modda** koşar ve hangisinde olduğunu açılışta **tek satırla söyler**. | ||
| 215 | +Sessiz sahte üretim yasaktır: sahte modda uyarı basılmadan iş kabul edilmez. | ||
| 216 | + | ||
| 217 | +| `PODCAST_MODE` | koşan | açılış satırı | | ||
| 218 | +| --- | --- | --- | | ||
| 219 | +| `simulate` (varsayılan) | `jobs.py::_simulate_pipeline` | `uyari: SAHTE hat kosuyor, uretilen ses GERCEK DEGIL` | | ||
| 220 | +| `real` | `pipeline.py::build_runner(...)` → `router.hat.Hat` | `GERCEK hat bagli: kaynak=... cikti=... tts=...` | | ||
| 221 | + | ||
| 222 | +`real` modda **yanlış yapılandırma boot'u çökertir** (exit 2), iki ayrı kapıdan: | ||
| 223 | + | ||
| 224 | +- `PODCAST_PIPELINE_PATH` tanımsız, dizin değil, ya da altında `router/hat.py` yok | ||
| 225 | +- yol doğru ama `import router.hat` patlıyor (eksik bağımlılık, sözdizimi hatası…) | ||
| 226 | + | ||
| 227 | +Geçersiz bir `PODCAST_MODE` değeri `ConfigError` → exit 2 verir; `config.py`'nin | ||
| 228 | +diğer parser'larıyla aynı davranış. | ||
| 229 | + | ||
| 230 | +`import router.hat` **tembeldir**: `pipeline.py` modül seviyesinde hattı import | ||
| 231 | +etmez, yalnızca `load_pipeline()` içinde eder. Bu yüzden `simulate` modda | ||
| 232 | +(ve `--validate` içinde) gerçek hat **hiç yüklenmez** — `--validate` bunu | ||
| 233 | +`sys.modules`'e bakarak doğrular. | ||
| 234 | + | ||
| 235 | +## Gerçek hat (`src/pipeline.py`) | ||
| 236 | + | ||
| 237 | +Runner `Hat`ı tek parça olarak kurar ve koşturur: | ||
| 238 | + | ||
| 239 | +```python | ||
| 240 | +Hat(pdf=..., format=ctx.format, gunluk=<kanca>, cikti_koku=PODCAST_OUTPUT_ROOT, | ||
| 241 | + bolum_limiti=PODCAST_CHAPTER_LIMIT, motor_adi=PODCAST_TTS_ENGINE, | ||
| 242 | + ses_uret=True).kos() | ||
| 243 | +``` | ||
| 244 | + | ||
| 245 | +### Tek dikiş yeri `gunluk` geri çağırımıdır | ||
| 246 | + | ||
| 247 | +`Hat`'ın dışarıdan sürülebilir tek noktası `gunluk` geri çağırımıdır. On bir | ||
| 248 | +çağrı yerinin çoğu `hat.py::_adim_ekle`'dendir (yani **her adım | ||
| 249 | +BİTTİĞİNDE**), ama hepsi değil: `kos()` açılış afişi (`:725-733`), OCR | ||
| 250 | +bildirimi (`:258`) ve TTS motor yükleme satırları (`:639`, `:643`) de kancayı | ||
| 251 | +tetikler. Sonuç iyi huylu — `update_progress` idempotent olduğu için aynı oran | ||
| 252 | +tekrar yazılır — ve iptal gecikmesini bir miktar **azaltır**. Kanca: | ||
| 253 | + | ||
| 254 | +1. `ctx.cancelled()` ise `KasitliKesme` fırlatır, | ||
| 255 | +2. değilse `hat.sonuc.adimlar` **canlı listesinin uzunluğundan** ilerleme | ||
| 256 | + hesaplar ve `ctx.progress(<aşama>, <oran>)` yazar, | ||
| 257 | +3. mesajı `config.log("debug", ...)` ile geçirir. | ||
| 258 | + | ||
| 259 | +Log satırı **ayrıştırılmaz** — biçimi hattın iç meselesidir, kırılgan olurdu. | ||
| 260 | +Tamamlanan adım sayısı doğrudan `sonuc.adimlar` listesinden okunur. | ||
| 261 | + | ||
| 262 | +**SINIR — iptal yalnızca adım sınırında yakalanır.** `script` adımı ölçülen | ||
| 263 | +koşuda tek başına ~34 dakika sürebilir; o adımın *ortasında* iptal görülemez, | ||
| 264 | +çünkü hattın içinde başka bir kanca yoktur. `podcast.cancel` bu yüzden | ||
| 265 | +*hemen* değil, **koşan adım bittiğinde** etki eder. İş yine de doğru biter | ||
| 266 | +(`cancelled`), sadece gecikir. Bunu kapatmanın tek yolu hattın kendisine ara | ||
| 267 | +kontrol noktası eklemektir; bu adım 3'ün kapsamında bilinçli olarak yapılmadı. | ||
| 268 | + | ||
| 269 | +**SATIR SIRASI BAĞIMLILIĞI — sahibi olmadığımız bir dosyada.** Kanca | ||
| 270 | +`KasitliKesme` fırlattığında `hat.py:750`'deki `except KasitliKesme` bloğu | ||
| 271 | +çalışır; o blok `kosu_kapat("kesildi")`'i **751'de**, `_adim_ekle`'yi | ||
| 272 | +**753'te** çağırır. `_adim_ekle` kancayı yeniden tetikler ve kanca ikinci kez | ||
| 273 | +fırlatır — ama koşu kaydı o an **zaten kapanmıştır**. 751 ile 753 yer | ||
| 274 | +değiştirirse resume kaydı açık kalır ve `kosu_kapat` hiç çağrılmaz. Bu | ||
| 275 | +sıralama ampirik olarak doğrulandı; `hat.py` değişirse yeniden sınanmalıdır. | ||
| 276 | + | ||
| 277 | +### Neden `KasitliKesme`, neden kendi istisnamız değil | ||
| 278 | + | ||
| 279 | +`KasitliKesme` (`hat.py:59`) hattın **kendi bilinçli-kesme** istisnasıdır ve | ||
| 280 | +`kos()` onu ayrıca yakalayıp koşuyu `kayit.kosu_kapat("kesildi")` ile kapatır — | ||
| 281 | +`"hata"` ile **değil**. Kancadan kendi istisnamızı fırlatsaydık `kos()` onu | ||
| 282 | +`BaseException` dalında yakalar, koşuyu `"hata"` diye kapatır ve **resume | ||
| 283 | +semantiği bozulurdu**: yeniden başlatılan iş bitmiş adımları atlayamazdı. | ||
| 284 | +Bu yüzden kanca `KasitliKesme` fırlatır; runner onu yakalar ve | ||
| 285 | +`ctx.cancelled()` doğruysa `jobs.JobCancelled`'a çevirir (işçi bunu `cancelled` | ||
| 286 | +olarak kapatır). `ctx.cancelled()` yanlışsa kesme **hattın kendisinden** | ||
| 287 | +gelmiştir (`--kes <adim>` resume sınaması) ve yeniden fırlatılır → `failed`. | ||
| 288 | + | ||
| 289 | +### Çıktı eşlemesi | ||
| 290 | + | ||
| 291 | +`HatSonucu` → `podcast.result`: | ||
| 292 | + | ||
| 293 | +| cevap alanı | kaynak | | ||
| 294 | +| --- | --- | | ||
| 295 | +| `audio_id` | `mp3_yollari[0]`'ın `PODCAST_OUTPUT_ROOT`'a göre **relatif yolu** (posix) | | ||
| 296 | +| `script_id` | `script_yollari[0]`'ın relatif yolu | | ||
| 297 | +| `duration_secs` | `ses_toplam_sn` | | ||
| 298 | +| `audio_ids` | tüm `mp3_yollari`'nın relatif yolları | | ||
| 299 | +| `script_ids` | `audio_ids`'in bölümlerine **hizalanmış** script yolları | | ||
| 300 | + | ||
| 301 | +**Kimlik neden dosya adı DEĞİL — ölçülen çarpışma.** Hat çıktıyı düz durmaz, | ||
| 302 | +`<pdf_stem>/ses/<format>/<pdf_stem>-b01.mp3` şeklinde yazar | ||
| 303 | +(`router/hat.py:187` + `:605`). Sadece dosya adı alınırsa üç dizin seviyesi | ||
| 304 | +kaybolur **ve** aynı PDF'in `duz_okuma` ile `tek_ogretici` koşusu | ||
| 305 | +**AYNI** kimliği döner — `bolum_id` formattan bağımsızdır | ||
| 306 | +(`script/kapsam.py:251`). Backend o kimlikle dosyayı bulamaz, üstelik iki iş | ||
| 307 | +birbirini gölgeler. Bu yüzden kimlik çıktı köküne göre relatif yoldur; kök | ||
| 308 | +dışında kalan bir yol dosya adına düşer. Konteyner içi mutlak yol yine | ||
| 309 | +sızdırılmaz. | ||
| 310 | + | ||
| 311 | +**`script_ids` neden hizalanıyor.** `bolum_limiti` yalnızca **sese** | ||
| 312 | +uygulanıyor (`router/hat.py:596`); `script_yollari` her zaman TÜM bölümleri | ||
| 313 | +taşır. Varsayılan `PODCAST_CHAPTER_LIMIT=1` + 3 bölümlü bir PDF'te listeler | ||
| 314 | +1'e 3 çıkardı ve tüketici 1:1 eşleme varsayarsa yanlış script'i yanlış sese | ||
| 315 | +bağlardı. Servis script'leri üretilen ses bölümlerine filtreler; eşleşme hiç | ||
| 316 | +tutmazsa filtrelemeden döner ve **uyarı loglar**. | ||
| 317 | + | ||
| 318 | +`PODCAST_CHAPTER_LIMIT` 1'den büyükse (ya da `0`/`-1` = hepsi) birden fazla MP3 | ||
| 319 | +üretilir. Kablo sözleşmesi **kırılmadı**: `audio_id`/`script_id` tekil kaldı ve | ||
| 320 | +ilk bölümü gösteriyor; çoğul listeler **eklendi**. Alan eklemek geriye dönük | ||
| 321 | +uyumludur, yeniden adlandırmak değildir. | ||
| 322 | + | ||
| 323 | +**`duration_secs` ve önbellek.** `router/hat.py:622`'deki önbellek yolu | ||
| 324 | +MP3'ü `mp3_yollari`'na ekliyor ama `ses_toplam_sn`'i artırmıyordu; taze yol | ||
| 325 | +(`:661-662`) ikisini de yapıyordu. Sonuç: aynı PDF+format ikinci kez | ||
| 326 | +istendiğinde `duration_secs` **0.0** dönüyordu. Önbellek bu hattın tasarım | ||
| 327 | +ilkesi olduğu için bu kenar durum değil, ikinci koşudan itibaren varsayılan | ||
| 328 | +davranıştı. **Hattın kaynağında düzeltildi** (süre `ses.dogrula.sure_olc` ile | ||
| 329 | +ffprobe'dan ölçülüyor). Servis ayrıca `audio_ids` dolu ama `duration_secs` | ||
| 330 | +sıfırsa uyarı loglar. | ||
| 331 | + | ||
| 332 | +### Hata kodları | ||
| 333 | + | ||
| 334 | +| `error_code` | ne zaman | | ||
| 335 | +| --- | --- | | ||
| 336 | +| `source_not_found` | `resolve_source` reddetti, dosya yok, ya da `Hat` kurulurken `HatHatasi` | | ||
| 337 | +| `no_audio` | hat koştu ama `mp3_yollari` **boş** — sessizce boş cevap dönmek yerine iş `failed` olur | | ||
| 338 | +| `internal` | başka her istisna (işçinin genel dalı) | | ||
| 339 | +| `interrupted` | açılış süpürmesi (süreç koşan işin ortasında öldü) | | ||
| 340 | + | ||
| 341 | +`no_audio` bilinçli bir kapıdır: `--ses-yok` benzeri bir yapılandırma ya da TTS | ||
| 342 | +çöküşü sessizce "başarılı ama sessiz" bir iş üretmesin diye. | ||
| 343 | + | ||
| 344 | +## Sahte hat | ||
| 345 | + | ||
| 346 | +`PODCAST_MODE=simulate` iken `src/jobs.py` içindeki | ||
| 347 | +`_simulate_pipeline` fonksiyonu aşamaları taklit eder: | ||
| 348 | + | ||
| 349 | +``` | ||
| 350 | +ocr → plan → script → tts → mux | ||
| 351 | +``` | ||
| 352 | + | ||
| 353 | +Her aşama arasında `PODCAST_STAGE_SECS` kadar beklenir ve `progress` güncellenir. | ||
| 354 | +İş bittiğinde `audio_id`, `duration_secs`, `script_id` üretilir — üretilen | ||
| 355 | +kimlikler `sim_` önekiyle başlar, böylece sahte çıktı gerçek çıktıyla asla | ||
| 356 | +karıştırılamaz. | ||
| 357 | + | ||
| 358 | +Bu bilinçli bir karardır: **yaşam döngüsü 45 dakika beklemeden | ||
| 359 | +kanıtlanabilsin diye.** `PODCAST_STAGE_SECS=0.0` ile tüm döngü milisaniyeler | ||
| 360 | +içinde koşar, ki `--validate` tam olarak bunu yapar. | ||
| 361 | + | ||
| 362 | +`bridge.main()` moda göre `build_store(settings, runner=..., stages=..., | ||
| 363 | +job_secs=...)` çağırır; kuyruk, kalıcılık, iptal ve süpürme her iki modda da | ||
| 364 | +aynıdır. Aşama adları: | ||
| 365 | + | ||
| 366 | +| mod | `stages` | otomatik `job_secs` | | ||
| 367 | +| --- | --- | --- | | ||
| 368 | +| `simulate` | `ocr → plan → script → tts → mux` | aşama sayısı × `PODCAST_STAGE_SECS` (en az 1 sn) | | ||
| 369 | +| `real` | `ingest → scriptler → quiz → ses` | **2700 sn (45 dk)** — ölçülen gerçek süre, `pipeline.REAL_ETA_SECS` | | ||
| 370 | + | ||
| 371 | +`PODCAST_ETA_SECS` verilmişse her iki modda da o kazanır. | ||
| 372 | + | ||
| 373 | +`resolve_source` `PODCAST_MEDIA_ROOT` altındaki dosya yolunu üretir: | ||
| 374 | +`^[A-Za-z0-9._-]{1,128}$` desenine uymayan `source_id` `ValueError` alır ve | ||
| 375 | +`Path.resolve()` sonrası sonucun medya kökünün **altında** kaldığı ayrıca | ||
| 376 | +doğrulanır (symlink kaçışı için; `..` deseni geçse bile burada takılır). | ||
| 377 | +Dosyanın **var olup olmadığına bakmaz**; varlık denetimini | ||
| 378 | +`pipeline.resolve_pdf()` yapar ve dosya yoksa iş `failed` + | ||
| 379 | +`error_code: "source_not_found"` olur. | ||
| 380 | + | ||
| 381 | +## Anahtarsız çalışma | ||
| 382 | + | ||
| 383 | +Podcast hattı LLM için `DEEPSEEK_API_KEY` ortam değişkenini kullanır. Ev kuralı | ||
| 384 | +gereği bu **eksik** yapılandırmadır, **yanlış** değil — dolayısıyla boot'u | ||
| 385 | +çökertmez, yalnızca ilgili özelliği kapatır: | ||
| 386 | + | ||
| 387 | +| değer | anlam | anahtarsız | | ||
| 388 | +| --- | --- | --- | | ||
| 389 | +| `duz_okuma` | varsayılan | **çalışır** | | ||
| 390 | +| `tek_ogretici` | tek anlatıcı | `llm_unavailable` | | ||
| 391 | +| `ogrenci_hoca` | iki sesli | `llm_unavailable` | | ||
| 392 | + | ||
| 393 | +Gerekçe: podcast projesinde `duz_okuma` hattı anahtarsız **sonuna kadar koşar**; | ||
| 394 | +diğer iki format 12 LLM ajanına bağımlıdır. Kaynak: `C:\PROJECTS\podcast\router\hat.py` | ||
| 395 | +dosyasının baş yorumu — "LLM isteyen bir adım anahtarsız çağrıldığında ATLANIR ve | ||
| 396 | +rapora ATLANDI diye YAZILIR; uydurma üretilmez. `duz_okuma` hattı anahtarsız | ||
| 397 | +SONUNA KADAR koşar." | ||
| 398 | + | ||
| 399 | +`llm_unavailable` mesajı hangi formatların kullanılabilir olduğunu **söyler**; | ||
| 400 | +çağıran tarafın tahmin etmesi gerekmez. Açılışta da tek satır log basılır: | ||
| 401 | + | ||
| 402 | +``` | ||
| 403 | +[bridge] acik formatlar: duz_okuma (DEEPSEEK_API_KEY tanimsiz; tek_ogretici, ogrenci_hoca kapali) | ||
| 404 | +[bridge] acik formatlar: tek_ogretici, ogrenci_hoca, duz_okuma (DEEPSEEK_API_KEY tanimli) | ||
| 405 | +``` | ||
| 406 | + | ||
| 407 | +**Anahtarın kendisi hiçbir yerde loglanmaz, hata mesajına girmez, diske | ||
| 408 | +yazılmaz.** `Config` yalnızca `has_llm_key` booleanını tutar; anahtar değeri | ||
| 409 | +process'te hiç saklanmaz. Yapılandırma özetinde görünen tek şey | ||
| 410 | +`llm_anahtari=tanimli` ya da `llm_anahtari=TANIMSIZ`'dır. | ||
| 411 | + | ||
| 412 | +**`format` yalnızca şu üç değeri alır** ve bu küme podcast projesinin kilitli | ||
| 413 | +sözleşmesidir; gerçeğin kaynağı `script/plan.py` içindeki `Format` enum'u ve | ||
| 414 | +`router/cli.py`'nin `choices` listesidir. Buradaki liste onun kopyasıdır ve | ||
| 415 | +`--validate` kopyanın bozulmadığını denetler. Enum değişirse **ikisi birden** | ||
| 416 | +değişmelidir. | ||
| 417 | + | ||
| 418 | +## Ortam değişkenleri | ||
| 419 | + | ||
| 420 | +| Değişken | Varsayılan | Anlamı | | ||
| 421 | +| --- | --- | --- | | ||
| 422 | +| `AI_BRIDGE_HOST` | `hezarfen-backend` | QUIC ile bağlanılacak host | | ||
| 423 | +| `AI_BRIDGE_PORT` | `8090` | QUIC portu (UDP) | | ||
| 424 | +| `AI_BACKEND_URL` | `http://hezarfen-backend:8080` | Sertifika için HTTP kökü | | ||
| 425 | +| `AI_SHARED_TOKEN` | **yok** | Backend ile aynı paylaşılan sır. Tanımsızsa köprü açılışta çıkar (exit 2) | | ||
| 426 | +| `AI_TLS_SERVER_NAME` | `localhost` | Sertifikanın SAN'ı | | ||
| 427 | +| `AI_SERVICE_NAME` | `podcast` | Hello'daki servis adı | | ||
| 428 | +| `AI_MAX_CONCURRENT` | `2` | Aynı anda kabul edilen **istek**; aşılırsa `busy` | | ||
| 429 | +| `AI_RECONNECT_SECS` | `3` | Kopunca yeniden deneme aralığı | | ||
| 430 | +| `LOG_LEVEL` | `info` | `debug`/`info`/`warn`/`error` | | ||
| 431 | +| `PODCAST_JOB_ROOT` | `/data/podcast/jobs` | İş durumu dizini (kalıcı hacim) | | ||
| 432 | +| `PODCAST_WORKERS` | `1` | Eş zamanlı **uzun iş** sayısı (ayrı havuz) | | ||
| 433 | +| `PODCAST_MAX_JOBS` | `8` | Kuyruk + koşan iş tavanı; aşılırsa `busy` | | ||
| 434 | +| `PODCAST_STAGE_SECS` | `0.2` | Sahte aşama süresi (gerçek hat bağlanınca anlamsızlaşır) | | ||
| 435 | +| `PODCAST_ETA_SECS` | `0` | Bir işin tahmini süresi (sn). `0` = otomatik (aşama sayısı × `PODCAST_STAGE_SECS`, en az 1). Gerçek hat için `2700` gibi bir değer verilir; aralık `0..86400` | | ||
| 436 | +| `PODCAST_MEDIA_ROOT` | `/data/files` | `source_id`'nin çözüleceği paylaşılan dosya kökü; backend'in `FILES_PATH` değeriyle **aynı** olmalı | | ||
| 437 | +| `PODCAST_MODE` | `simulate` | `simulate` \| `real`. Başka değer → exit 2 | | ||
| 438 | +| `PODCAST_PIPELINE_PATH` | **boş** | Hat kaynağının kökü (içinde `router/hat.py`). `real` modda **zorunlu**; yoksa/bozuksa exit 2 | | ||
| 439 | +| `PODCAST_OUTPUT_ROOT` | `/data/podcast/out` | `Hat(cikti_koku=...)` — üretilen mp3/script/quiz kökü (kalıcı hacim) | | ||
| 440 | +| `PODCAST_CHAPTER_LIMIT` | `1` | `Hat(bolum_limiti=...)`. `0` veya `-1` = **hepsi**; aralık `-1..4096` | | ||
| 441 | +| `PODCAST_TTS_ENGINE` | `supertonic-3` | `Hat(motor_adi=...)` — lokal ONNX motoru | | ||
| 442 | +| `PODCAST_LEDGER_DB` | `/data/podcast/router.sqlite` | `router.kayit.Kayit` defteri: adım önbelleği, resume, LLM bütçe sayacı. compose'ta `/data/podcast/kayit/router.sqlite` (ayrı kalıcı hacim) | | ||
| 443 | +| `HF_HOME` | *(imajda)* `/models/hf` | HuggingFace önbellek kökü; `podcast-models` hacmi buraya `:ro` bağlanır | | ||
| 444 | +| `TORCH_HOME` | *(imajda)* `/models/torch` | torch önbellek kökü | | ||
| 445 | +| `HF_HUB_OFFLINE` | `1` (compose) | HF hub'a **ağ çağrısı yok**. Ağırlık hacimde yoksa açık hata; sessizce 2,2 GB indirilmez | | ||
| 446 | +| `DEEPSEEK_API_KEY` | **yok** | Yoksa yalnızca `duz_okuma`; boot çökmez | | ||
| 447 | + | ||
| 448 | +Yapılandırma kuralı (backend'in kendi kuralı): **yanlış** yapılandırma boot'u | ||
| 449 | +çökertir (geçersiz port, geçersiz `LOG_LEVEL`, `PODCAST_WORKERS=abc`, | ||
| 450 | +`PODCAST_MAX_JOBS=0`, eksik token → exit 2); **eksik** yapılandırma yalnızca | ||
| 451 | +ilgili özelliği sessizce kapatır (`DEEPSEEK_API_KEY`). | ||
| 452 | + | ||
| 453 | +Yorumlu şablon: **`.env.example`**. Kopyala, doldur, `.env` olarak kaydet. | ||
| 454 | +`.env` `.gitignore`'dadır; `.env.example` kasten izlenir ve `.containerignore` | ||
| 455 | +sayesinde imaja girmez. | ||
| 456 | + | ||
| 457 | +Token asla loglanmaz. Sertifika parmak izinin yalnızca ilk 12 karakteri loglanır. | ||
| 458 | + | ||
| 459 | +## Çalıştırma | ||
| 460 | + | ||
| 461 | +```sh | ||
| 462 | +python -m src.main --validate # bütünlük kontrolü, ağ ve aioquic gerekmez | ||
| 463 | +pip install -r requirements.txt | ||
| 464 | +python -m src.bridge # köprüyü çalıştır (AI_SHARED_TOKEN şart) | ||
| 465 | +``` | ||
| 466 | + | ||
| 467 | +```sh | ||
| 468 | +python -m src.main --health # canlilik: kokler yazilabilir mi, hat import edilir mi, kayit var mi | ||
| 469 | +``` | ||
| 470 | + | ||
| 471 | +Container (Podman) — **tam yol `deploy/OKU.md`'dedir**: | ||
| 472 | + | ||
| 473 | +```powershell | ||
| 474 | +pwsh -File deploy/setup-pipeline.ps1 # hat kaynagi -> vendor/pipeline | ||
| 475 | +pwsh -File deploy/setup-models.ps1 # agirliklar -> podcast-models hacmi | ||
| 476 | +Copy-Item .env.example .env # sonra icindeki AI_SHARED_TOKEN'i backend ile AYNI yap | ||
| 477 | + # (ortam degiskeni YETMEZ: compose `down`/`ps` de interpolate eder) | ||
| 478 | +pwsh -File deploy/run-stack.ps1 # backend -> frontend -> chatbot -> podcast | ||
| 479 | +podman logs -f hezarfen-podcast-bridge | ||
| 480 | +``` | ||
| 481 | + | ||
| 482 | +### `--health` neyi denetler | ||
| 483 | + | ||
| 484 | +Compose'un `healthcheck`'i budur. **Ağ çağrısı yapmaz**, ölçülen süre | ||
| 485 | +**0,66 sn** (timeout 10 sn). Denetlediği: | ||
| 486 | + | ||
| 487 | +- `PODCAST_JOB_ROOT` ve `PODCAST_OUTPUT_ROOT` gerçekten **yazılabilir mi** | ||
| 488 | + (mkdir + dosya yaz + sil; hacim root sahipliğinde oluştuysa burada patlar) | ||
| 489 | +- `real` modda **hat içeri alınabiliyor mu** (`import router.hat`; ölçüldü 0,12 sn) | ||
| 490 | +- köprü backend'e **kayıtlı mı** | ||
| 491 | + | ||
| 492 | +Kayıt durumu iş kökündeki **`.bridge-status`** dosyasından okunur. Köprü bu dosyayı | ||
| 493 | +`jobs.py`'nin **atomik** deseniyle (geçici dosya + `os.replace`) yazar: kayıt | ||
| 494 | +başarılı olunca `registered=true`, bağlantı koptuğunda `false`. Dosya adı | ||
| 495 | +`*.json` desenine uymadığı için açılıştaki iş taramasına karışmaz; artığı | ||
| 496 | +`_purge_temporaries` süpürür. | ||
| 497 | + | ||
| 498 | +**Bayatlık (staleness) denetimi bilerek YOK.** Köprü yalnızca durum | ||
| 499 | +*değiştiğinde* yazar; sağlıklı ve saatlerce süren bir bağlantı hiçbir şey | ||
| 500 | +yazmaz. Zaman aşımı koymak sağlıklı köprüyü hasta gösterirdi. | ||
| 501 | + | ||
| 502 | +Çıkış kodu: `0` sağlıklı · `1` sağlıksız · `2` yapılandırma hatası. | ||
| 503 | + | ||
| 504 | +### `--validate` neyi denetler | ||
| 505 | + | ||
| 506 | +Ağ kullanmaz, `aioquic` import etmez, **gerçek hattı import etmez**, | ||
| 507 | +`PODCAST_JOB_ROOT`'a **dokunmaz** (geçici dizinde çalışır) ve token yokken de | ||
| 508 | +çalışır (uyarı basar, 0 döner) — imajın güvenli varsayılan `CMD`'si budur. | ||
| 509 | + | ||
| 510 | +`PODCAST_MODE=real` ile çağrılırsa `--validate` de mod kapısını uygular: | ||
| 511 | +`PODCAST_PIPELINE_PATH` yoksa/bozuksa açık bir satır basar ve **2** döner. | ||
| 512 | +Yol geçerli olsa bile `--validate` hattı **import etmez**; yalnızca yolun | ||
| 513 | +varlığını ve `router/hat.py`'nin orada olduğunu denetler. | ||
| 514 | + | ||
| 515 | +Denetlediği kapılar: | ||
| 516 | + | ||
| 517 | +- format kümesi ve varsayılanın kilitli sözleşmeden sapmadığı | ||
| 518 | +- yetenek defteri, çerçeveleme gidiş-dönüşü, greeting ayrıştırma, deadline payı | ||
| 519 | +- iş deposunun geçici bir dizine yazılıp okunabildiği, geçici dosya bırakmadığı | ||
| 520 | + ve deponun yeniden açılışta kaydı bulduğu | ||
| 521 | +- durum makinesinin geçersiz geçişi (`queued → done`, `done → running`, | ||
| 522 | + bilinmeyen hedef) reddettiği | ||
| 523 | +- anahtarsızken `tek_ogretici`/`ogrenci_hoca` submit'inin `llm_unavailable` | ||
| 524 | + döndüğü ve mesajın kullanılabilir formatları söylediği | ||
| 525 | +- anahtarsızken `duz_okuma` submit'inin **kabul edildiği** | ||
| 526 | +- anahtar varken `tek_ogretici`'nin kabul edildiği | ||
| 527 | +- `PODCAST_MAX_JOBS` aşılınca `busy` döndüğü | ||
| 528 | +- açılış süpürmesinin `running` işi `failed`/`interrupted` yaptığı, `queued` işe | ||
| 529 | + dokunmadığı | ||
| 530 | +- uçtan uca yaşam döngüsü: submit → sahte hat → `done` → `result` gerçek | ||
| 531 | + kimlikler döner | ||
| 532 | +- işbirlikçi iptal: koşan bir işin `cancel` sonrası `cancelled`'a geçtiği | ||
| 533 | +- **iptal yarışı**: `finish()` çağrılmadan hemen önce gelen `cancel`'ın işi | ||
| 534 | + `done` değil `cancelled` bitirdiği ve bunun **diske de** yansıdığı | ||
| 535 | +- **`queued → failed`** geçişinin yasal olduğu (başlamadan patlayan iş) | ||
| 536 | +- **`resolve_source` yol kaçışı**: `..`, `../x`, `a/b`, `/etc/passwd`, boş dize, | ||
| 537 | + 129 karakterlik ad, `..\x`, `.` reddedilir; geçerli ad medya kökü altına çözülür | ||
| 538 | +- **`PODCAST_ETA_SECS`** verildiğinde `estimate_eta`'nın sahte aşama süresini | ||
| 539 | + değil onu kullandığı, `stages` parametresinin dinlendiği | ||
| 540 | +- **kayıt şeması**: zorunlu alanı eksik kaydın açılışta atlandığı, sağlam | ||
| 541 | + komşusunun etkilenmediği, `*.json.tmp*` artığının silindiği | ||
| 542 | +- **kapanma**: işçi thread'lerinin `daemon` olduğu ve 8 saniyelik bir iş | ||
| 543 | + koşarken `shutdown(timeout=0.5)`'in takılmadan döndüğü | ||
| 544 | +- **mod kapısı**: geçersiz `PODCAST_MODE` değerinin `ConfigError` verdiği | ||
| 545 | +- **tembel import**: `simulate` modda `router.hat`'ın `sys.modules`'te | ||
| 546 | + **olmadığı** (yani `--validate` gerçek hattı hiç yüklemediği) | ||
| 547 | +- **`real` yolu**: boş / var olmayan / `router/hat.py` içermeyen | ||
| 548 | + `PODCAST_PIPELINE_PATH` değerlerinin açık hata ile reddedildiği | ||
| 549 | +- **bölüm limiti** normalleştirmesi: `0` ve `-1` → "hepsi", pozitif değer korunur | ||
| 550 | +- **çıktı eşlemesi**: sahte bir `HatSonucu` benzeri nesneden `audio_id`, | ||
| 551 | + `script_id`, `duration_secs`, `audio_ids`, `script_ids` alanlarının doğru | ||
| 552 | + türetildiği (tam yol değil dosya adı; ilk bölüm tekil alanlarda) | ||
| 553 | +- **iptal kancası**: `ctx.cancelled()` `True` iken `gunluk` kancasının kesme | ||
| 554 | + istisnası fırlattığı ve ilerleme **yazmadığı**; `False` iken adım sayısından | ||
| 555 | + doğru aşama/oran ürettiği (gerçek `Hat` olmadan, sahte bir ctx ile) | ||
| 556 | +- **gerçek runner uçtan uca** (sahte bir `Hat` sınıfıyla, gerçek `JobStore` ve | ||
| 557 | + gerçek `capabilities` üzerinden): | ||
| 558 | + - iki MP3 üreten koşu → `done`, `audio_ids`/`script_ids` iki elemanlı | ||
| 559 | + - `mp3_yollari` boş → `failed` + `no_audio`, `audio_id` yazılmamış | ||
| 560 | + - kaynak dosya yok → `failed` + `source_not_found` | ||
| 561 | + | ||
| 562 | +Beklenmedik bir istisna da bir bütünlük hatası olarak raporlanır; `--validate` | ||
| 563 | +traceback ile ölmez. | ||
| 564 | + | ||
| 565 | + | ||
| 566 | +## Testler | ||
| 567 | + | ||
| 568 | +Geliştirme sırasında koşulan test paketi `tests/` altındadır. **Saf `unittest`; | ||
| 569 | +`pytest` kullanılmaz** — ne `import pytest`, ne `conftest.py`, ne `pytest.ini`. | ||
| 570 | +Bu, rule-based chatbot deposundaki desenin birebir kopyasıdır ve bilinçlidir: | ||
| 571 | +testler standart kütüphaneden başka bir şey istemez, imajda ek bağımlılık yoktur. | ||
| 572 | + | ||
| 573 | +```sh | ||
| 574 | +python -m unittest discover -s tests -t . # tüm paket (298 test, ~9 sn) | ||
| 575 | +python -m unittest tests.unit.test_jobs # tek dosya | ||
| 576 | +python -m unittest tests.regress.regress_cancel_race -v | ||
| 577 | +``` | ||
| 578 | + | ||
| 579 | +`tests/regress/` dosyaları `regress_*.py` adlandırıldığı için `discover`'ın | ||
| 580 | +varsayılan `test*.py` deseniyle bulunmaz; `tests/regress/__init__.py` içindeki | ||
| 581 | +`load_tests` bunları pakete katar. Tek komut yine de her şeyi koşar. | ||
| 582 | + | ||
| 583 | +### `--validate` ile ilişkisi | ||
| 584 | + | ||
| 585 | +`python -m src.main --validate` **çalışma-zamanı bütünlük kontrolüdür** ve | ||
| 586 | +öyle kalır: container sağlık akışı onu kullanır, ağ ve `aioquic` istemez, tek | ||
| 587 | +süreçte kendi geçici dizinini kurar. Test paketi onun yerine geçmez, **yanında** | ||
| 588 | +durur: `--validate` "bu imaj şu an tutarlı mı" der, `tests/` ise "bu değişiklik | ||
| 589 | +bilinen bir kusuru geri getirdi mi" der. | ||
| 590 | + | ||
| 591 | +### Dizin yapısı | ||
| 592 | + | ||
| 593 | +| Dizin | Ne sınar | | ||
| 594 | +| --- | --- | | ||
| 595 | +| `tests/unit/` | Tek modül davranışı: çerceveleme, ortam çözümleme, yetenek defteri, durum makinesi, çıktı eşlemesi (138 test) | | ||
| 596 | +| `tests/integration/` | `submit -> status -> result` uçtan uca; sahte bir `Hat` sınıfı ile ama **gerçek** `JobStore`, gerçek işçi thread'leri, gerçek `capabilities.dispatch` (8 test) | | ||
| 597 | +| `tests/regress/` | Her dosya **ölçülerek bulunmuş bir kusur**; düzeltme geri alınırsa kırmızıya döner (17 dosya, 130 test) | | ||
| 598 | +| `tests/fuzz/` | Hatalı biçimlendirilmiş girdi altında ayrıştırıcı sözleşmesi: altı slayt kategorisi, şablon/bayt mutasyonu, gramer üretimi (13 test) | | ||
| 599 | +| `tests/model/` | `JobStore`'un Mealy makinesi modeline uygunluğu; W yöntemiyle üretilen `V·W ∪ V·X·W` kümesi (9 test) | | ||
| 600 | + | ||
| 601 | +### Regresyon dosyaları ve kapattıkları kusur | ||
| 602 | + | ||
| 603 | +| Dosya | Kusur | | ||
| 604 | +| --- | --- | | ||
| 605 | +| `regress_format_vocabulary.py` | Format kümesi kilitli sözleşmeden sapmamalı. Gerçeğin kaynağı `script/plan.py` `Format` enum'u ve `router/cli.py` `choices` listesidir; test bu iki dosyayı **okuyup** karşılaştırır. Dosya bulunamazsa test atlanmaz, **açık hata** verir (yol değişmiş demektir). | | ||
| 606 | +| `regress_unanswered_stream.py` | Ayrıştırılamayan istek cevapsız bırakılmamalı; backend cevapsız akışı deadline boyunca bekler ve worker kiralamasını tutar. 8 MiB aşan cevap sessizce yutulmamalı, `frame_too_large` err'ine düşürülmeli. | | ||
| 607 | +| `regress_cancel_race.py` | `finish()` iptal bayrağını **aynı kilit altında** okumalı; bayrak setken `done` değil `cancelled` dönmeli ve `audio_id` yazılmamalı. Bellekte ve **diskte** aynı sonuç. Ölçülen: düzeltmeden önce bellek=`done` disk=`done` `audio_id=a1`. | | ||
| 608 | +| `regress_queued_failed.py` | `queued -> failed` geçişi yasal olmalı. Yoksa `begin()` öncesi patlayan iş sonsuza kadar `queued` kalır, her açılışta yeniden kuyruğa alınır ve `max_jobs` kotasından bir slotu kalıcı yer. | | ||
| 609 | +| `regress_daemon_shutdown.py` | İşçi thread'ler `daemon` olmalı ve `shutdown(timeout=)` sınırlı sürede dönmeli. Ölçülen: `ThreadPoolExecutor` ile süreç 8139 ms yaşıyordu, daemon thread'lerle 57 ms. | | ||
| 610 | +| `regress_identifier_path.py` | `audio_id`/`script_id` çıktı köküne göre **relatif yol** olmalı, dosya adı değil. Gerçek yol `<stem>/ses/<format>/<stem>-bNN.mp3`; sadece dosya adı alınırsa üç dizin seviyesi kaybolur **ve** aynı PDF'in `duz_okuma` ile `tek_ogretici` koşusu aynı kimliği döner (bölüm_id formattan bağımsız). Kök dışı kalan yol dosya adına düşer. | | ||
| 611 | +| `regress_script_alignment.py` | `bolum_limiti` yalnızca **sese** uygulanıyor; `script_yollari` her zaman tüm bölümleri taşır. 1 ses + 3 script → `script_ids` 1 elemana filtrelenmeli. Eşleşme hiç tutmazsa filtrelenmeden dönmeli (ve uyarı loglanmalı). | | ||
| 612 | +| `regress_absolute_path.py` | `job_root`/`output_root`/`media_root`/`ledger_db` **mutlak** olmalı. Ölçülen kusur: göreli çıktı kökü verildiğinde hattın ffmpeg concat listesi yolu ikiye katlıyor ve montaj patlıyor. | | ||
| 613 | +| `regress_path_traversal.py` | `resolve_source` şunları reddetmeli: `..`, `../x`, `a/b`, `/etc/passwd`, `..\x`, `.`, boş ad, 129 karakterlik ad, `\\srv\share`, `C:\Windows`, NUL içeren ad. Geçerli ad kabul edilir ve sonuç `media_root` **altında** kalır. | | ||
| 614 | +| `regress_schema_validation.py` | Eksik alanlı iş kaydı açılışta atlanmalı (`KeyError` değil). `REQUIRED_FIELDS`'a `audio_ids`/`script_ids` **eklenmemeli** — eklenirse alan eklenmeden önce yazılmış eski kayıtlar topluca atılır. | | ||
| 615 | +| `regress_tmp_residue.py` | Geçici dosya adı pid içerir; açılışta `*.json.tmp*` artıkları temizlenir; atomik yazma temp + `os.replace` ile yapılır. Ayrıca temizleme mantığı **kopyaladığı dosyaları silmemeli** (PowerShell `-Include` tuzağının Python karşılığı: filtre gerçekten uygulanıyor mu). | | ||
| 616 | +| `regress_secret_leak.py` | `DEEPSEEK_API_KEY` ve `AI_SHARED_TOKEN` değerleri `Config.summary()` çıktısında, iş JSON kayıtlarında ve istisna metinlerinde geçmemeli. Kanarya değerlerle sınanır. | | ||
| 617 | +| `regress_mutation_survivors.py` | Mutasyon testinin hayatta bıraktığı 10 mutantın kapattığı boşluklar: `len(body) > MAX_FRAME_BYTES` sınırı **tam değerinde** (kabul) ve bir bayt üstünde (ret), istisna metinlerinin kod+mesaj taşıması, `ApiResponse` alanlarının okunması, `GREETING_TIMEOUT_SECS < 10` (backend `AI_HANDSHAKE_TIMEOUT_SECS`) ve `KEEPALIVE_SECS < IDLE_TIMEOUT_SECS` bağıntıları. | | ||
| 618 | +| `regress_unreachable_guard.py` | `JobStore.begin()` içindeki "kuyruktayken iptal bayrağı" koruması **erişilemez**: bayrağı yalnızca `cancel` ve `shutdown` doğruya çeker, ikisi de `queued` durumunu geride bırakmaz. AST ile yazıcı kümesi kilitlenir; yeni bir yazıcı eklenirse test kırmızıya döner ve korumanın canlandığını söyler. | | ||
| 619 | + | ||
| 620 | +### Slayt teorisine göre denetim | ||
| 621 | + | ||
| 622 | +Ders slaytları (`slides/week01-11`) ile paket madde madde karşılaştırıldı. Aşağıdaki | ||
| 623 | +her satır **ölçülmüş** bir sonuçtur, iddia değil. | ||
| 624 | + | ||
| 625 | +#### 1. Kapsam bir taban, hedef değil (week01, RIPR) | ||
| 626 | + | ||
| 627 | +RIPR modeli: bir kusurun **görünmesi** için dörtlü şart gerekir — kusura *erişilmeli* | ||
| 628 | +(Reached), durum *bozulmalı* (Infected), bozukluk *yayılmalı* (Propagated), sonuç | ||
| 629 | +*gözlenmeli* (Revealed). %100 kapsam yalnızca birinci şartı garanti eder. | ||
| 630 | + | ||
| 631 | +Bu depoda kanıtlandı: `protocol.py` satır ve dal kapsamı **%100** iken mutasyon | ||
| 632 | +skoru **%89,4** çıktı. Aynı kod, aynı testler; 10 mutant hayatta kaldı çünkü | ||
| 633 | +erişilen satırlar assert edilmiyordu. | ||
| 634 | + | ||
| 635 | +Ölçülen kapsam (`coverage run --branch --source=src`): | ||
| 636 | + | ||
| 637 | +| Modül | Satır | Not | | ||
| 638 | +| --- | --- | --- | | ||
| 639 | +| `protocol.py` | %100 satır + %100 dal | mutasyonla da doğrulandı | | ||
| 640 | +| `config.py` | %97 | | | ||
| 641 | +| `capabilities.py` | %96 | | | ||
| 642 | +| `jobs.py` | %91 | erişilemez koruma dahil (aşağıya bak) | | ||
| 643 | +| `pipeline.py` | %76 | gerçek `Hat` yolları sahte sınıfla değiştirilir | | ||
| 644 | +| `main.py` | %68 | unittest **çağırmaz**; `--validate` adımı çağırır | | ||
| 645 | +| `bridge.py` | %34 | **gerçek boşluk**: QUIC istemcisi, ağ ve `aioquic` ister | | ||
| 646 | +| TOPLAM | %76 | unittest + `--validate` birleşik | | ||
| 647 | + | ||
| 648 | +`main.py`'yi yalnız unittest ile ölçmek **%0** verir ve bu rakam yanıltıcıdır: dosya | ||
| 649 | +996 satırlık bir çalışma-zamanı doğrulama koşumudur (14 `_check_*` fonksiyonu) ve | ||
| 650 | +CI'da ayrı bir adım olarak koşar. Slaytların "eksik test mi, erişilemez mi" | ||
| 651 | +sınıflandırması gereği: **başka mekanizmayla kapsanıyor**. Geriye kalan tek gerçek | ||
| 652 | +boşluk `bridge.py`'dir. | ||
| 653 | + | ||
| 654 | +#### 2. Mutasyon testi (week06 operatörleri) | ||
| 655 | + | ||
| 656 | +`mutmut` beş ayrı nedenle bu depoda koşmadı (Windows desteği yok; bind-mount izin | ||
| 657 | +üstverisi `copytree`'yi kırıyor; `pytest` zorunlu tutuyor; root olmayan kullanıcı | ||
| 658 | +kök dizine yazamıyor; üretim imajında `tests/` yok — ki olmaması doğru). Bunun | ||
| 659 | +yerine slayt operatörlerini uygulayan `tools/mutation_test.py` yazıldı: **ROR, AOR, | ||
| 660 | +COR, UOI, SDL**. (Slaytlarda geçen ABS uygulanmadı: `protocol.py` mutlak değer | ||
| 661 | +alınabilecek tek bir aritmetik ifade içermiyor.) Skor slayt formülüyle raporlanır: `killed / (toplam - | ||
| 662 | +eşdeğer)`, eşdeğer mutantlar **elle** işaretlenir. | ||
| 663 | + | ||
| 664 | +İlk koşu `protocol.py` üzerinde 123 mutant üretti, 110'u öldü, **10'u hayatta | ||
| 665 | +kaldı**. Slaytların M-1.3b kriteri her hayatta kalan için karar ister; onu da | ||
| 666 | +incelendi ve **hiçbiri eşdeğer çıkmadı** — hepsi gerçek test boşluğuydu: | ||
| 667 | + | ||
| 668 | +| Hayatta kalan | Neden hayatta kaldı | Kapatan test | | ||
| 669 | +| --- | --- | --- | | ||
| 670 | +| ROR satır 32, 65 | `> MAX_FRAME_BYTES` sınırı hiç **tam değerinde** sınanmamış; `>=` yazılsa test fark etmezdi | `test_a_frame_of_exactly_the_limit_must_be_accepted` + üç kardeşi | | ||
| 671 | +| SDL satır 20, 26, 142 | `super().__init__(mesaj)` silinince kimse fark etmiyor — istisna **metni** hiç assert edilmemiş | `ExceptionsCarryTheirMessage` | | ||
| 672 | +| SDL satır 148, 150 | `ApiResponse.request_id` ve `.body` hiç okunmamış | `ApiResponseKeepsEveryField` | | ||
| 673 | +| ROR satır 87, 185 | `!= PROTOCOL` ve `!= "ok"` karşılaştırmalarının ters yönü sınanmamış | `ComparisonsRejectTheWrongSide` | | ||
| 674 | +| SDL satır 12 | `GREETING_TIMEOUT_SECS = 8.0` sabiti hiç doğrulanmamış | `TimeoutConstantsStayInsideTheBackendWindow` | | ||
| 675 | + | ||
| 676 | +15 test eklendi ve mutasyon yeniden koşuldu. Skor **%89,4 → %91,5** çıktı ama | ||
| 677 | +**4 mutant hâlâ hayattaydı** — üçü yine aynı `super().__init__` satırları. Sebebi | ||
| 678 | +kodda değil, **yeni yazılan testlerin kendisindeydi**: | ||
| 679 | + | ||
| 680 | +- `BaseException.__new__` argümanları zaten `args`'a koyar. `super().__init__` | ||
| 681 | + silinse bile `str(hata)` `"('bad_request', 'alan eksik')"` döner ve | ||
| 682 | + `assertIn("alan eksik", ...)` **geçer**. Alt dize kontrolü bu mutantı göremez. | ||
| 683 | +- `_coerce_status`'un `bool` dalı silindiğinde `True` doğrudan dönüyordu; | ||
| 684 | + `assertEqual(status, 1)` yine **geçiyordu**, çünkü Python'da `True == 1`. | ||
| 685 | + | ||
| 686 | +Assertion'lar tam eşitliğe çevrildi (`str(hata) == "alan eksik"`, biçimlenmiş | ||
| 687 | +cümlenin tamamı, `len(args) == 1`) ve `assertIs(type(status), int)` eklendi. Üçüncü | ||
| 688 | +tur sonucu: | ||
| 689 | + | ||
| 690 | +``` | ||
| 691 | +MUTASYON SONUCU: src/protocol.py (129 mutant: SDL 63, ROR 42, AOR 12, UOI 8, COR 4) | ||
| 692 | + oldurulen : 126 | ||
| 693 | + asili kaldi: 3 (sonsuz dongu; paket sonlanmayarak yakaladi) | ||
| 694 | + hayatta : 0 | ||
| 695 | + HAM SKOR : 100.0% | ||
| 696 | +``` | ||
| 697 | + | ||
| 698 | +| Tur | Skor | Hayatta | Ne gösterdi | | ||
| 699 | +| --- | --- | --- | --- | | ||
| 700 | +| 1 | %89,4 | 10 | %100 kapsamlı kodda sınır ve assertion boşlukları | | ||
| 701 | +| 2 | %91,5 | 4 | Boşluğu kapatmak için yazılan **testlerin kendisi** zayıftı | | ||
| 702 | +| 3 | %100,0 | 0 | — | | ||
| 703 | + | ||
| 704 | +Slaytların savı burada iki kez doğrulandı: mutasyon testi önce **kodun** boşluğunu, | ||
| 705 | +sonra o boşluğu kapatmak için yazılan **testlerin** zayıflığını gösterdi. Satır ve | ||
| 706 | +dal kapsamı üç turda da %100'dü ve hiçbir şey söylemedi. | ||
| 707 | + | ||
| 708 | +**Asılı kalan üç mutant hakkında.** Üçü de `FrameStream`'in akış-sonu mantığında | ||
| 709 | +(`feed`'in `None` nöbetçisi, `_read_exact`'in `EOFError`'ı ve `_eof` bayrağı). | ||
| 710 | +Silindiklerinde `_read_exact` boş kuyruğu sonsuza kadar bekler: 7,9 saniyelik paket | ||
| 711 | +90 saniyede bitmiyor. Bunlar **öldürülmüş** sayılır — paket onları sonlanmayarak | ||
| 712 | +tespit eder; `mutmut` ve PIT aynı kuralı kullanır. Üçü de ayrı ayrı elle | ||
| 713 | +doğrulandı, varsayılmadı. | ||
| 714 | + | ||
| 715 | +İlk koşularda dördüncü bir zaman aşımı daha görünüyordu (`build_api_request`'in | ||
| 716 | +sözlük ataması). Tek başına denendiğinde **1,7 saniyede normal yoldan ölüyor**; | ||
| 717 | +o zaman aşımı, aynı anda koşan başka işlerin yarattığı bir yanlış sınıflandırmaydı. | ||
| 718 | +`tools/mutation_test.py` buna göre düzeltildi: mutant süre sınırı artık sabit değil, | ||
| 719 | +**ölçülen temel koşunun 10 katı**; zaman aşımı görülürse iki kat sınırla bir kez daha | ||
| 720 | +denenir. Ölçüm aracının kendisi de ölçülmelidir. | ||
| 721 | + | ||
| 722 | +Mutasyon her pazartesi ve elle tetikle `.github/workflows/mutation.yml` ile koşar; | ||
| 723 | +rapor artefakt olarak saklanır. | ||
| 724 | + | ||
| 725 | +#### 3. Fuzzing (week08) | ||
| 726 | + | ||
| 727 | +Slayt 11 "Fuzzing Nasıl Yapılır?" altı girdi kategorisi sayar; `tools/fuzz_test.py` | ||
| 728 | +altısını da üretir: | ||
| 729 | + | ||
| 730 | +| Kategori | Örnek | | ||
| 731 | +| --- | --- | | ||
| 732 | +| uzunluk | boş, 1, 255, 65535, 70000 karakter; 40000 çok baytlı; 20000 emoji | | ||
| 733 | +| sayı sınırları | 0, -0, ±2^31, ±2^63, 2^70, `1e309`, `NaN`, `Infinity` | | ||
| 734 | +| özel değerler | NUL, gömülü NUL, satır sonu, EOF, BOM, sağdan-sola işareti | | ||
| 735 | +| biçimlendirici | `%s`, `%x`, `%n`, süslü parantezler, JNDI kalıbı | | ||
| 736 | +| noktalama | noktalı virgül, tırnaklar, ters eğik çizgi, `../`, kabuk ikamesi, tüm kontrol karakterleri | | ||
| 737 | +| anahtar kelimeler | `halt`, `return`, `DROP TABLES`, format adları, yetenek adları, `__class__` | | ||
| 738 | + | ||
| 739 | +Ayrıca slaytların diğer üç tekniği: **şablon (mutasyon) tabanlı** fuzzing geçerli | ||
| 740 | +çerçeveleri tohum alıp alan/bayt düzeyinde bozar; **gramer tabanlı** üretim bir | ||
| 741 | +context-free grammar'dan JSON çerçevesi türetir (yineleme derinliği sınırlı, slayt | ||
| 742 | +21'deki annotation önerisi); **kapsam geri beslemesi** yeni satır kapsayan girdiyi | ||
| 743 | +tohum havuzuna geri koyar (slayt 13/25, AFL mantığı). | ||
| 744 | + | ||
| 745 | +Orakl kesin: `bridge.py::_serve_request` yalnızca `EOFError`, `CapabilityError` ve | ||
| 746 | +`ValueError` yakalar. Bunların dışında bir istisna, akışı **hiç cevaplamadan** | ||
| 747 | +bırakır ve backend tam deadline boyunca asılı kalır. Fuzzer bu sözleşmeyi ihlal eden | ||
| 748 | +her girdiyi bulgu sayar. | ||
| 749 | + | ||
| 750 | +**İlk koşu iki gerçek kusur buldu**, ikisi de aynı satırda — `parse_api_response` | ||
| 751 | +içindeki `int(frame.get("status", 0))`: | ||
| 752 | + | ||
| 753 | +``` | ||
| 754 | +status = [] -> TypeError: int() argument must be ... not 'list' | ||
| 755 | +status = float('inf') -> OverflowError: cannot convert float infinity to integer | ||
| 756 | +``` | ||
| 757 | + | ||
| 758 | +`call_api` bu çağrıyı hiçbir korumaya sarmıyordu. `_coerce_status` eklendi: artık | ||
| 759 | +kullanılamaz her `status` biçimi ilan edilmiş `ApiRefused("malformed", ...)` ile | ||
| 760 | +reddedilir, kullanılabilir olanlar (`200`, `"404"`, `301.0`) geçer. Düzeltmeden önce | ||
| 761 | +17 test kırmızıydı, sonra hepsi yeşil. | ||
| 762 | + | ||
| 763 | +Düzeltme sonrası üç tohumla 50 000'den fazla girdi koşuldu: **sıfır bulgu**. CI'da | ||
| 764 | +sabit tohumlar (1, 2, 3) kapı olarak, koşuya özgü değişken tohum ise bilgilendirme | ||
| 765 | +olarak koşar — fuzzing bir kampanyadır, sabit bir küme değil. | ||
| 766 | + | ||
| 767 | +Lab notunun tek katı kuralı — *"The fuzzer must never crash"* — testle korunur: | ||
| 768 | +`TheFuzzerItselfNeverCrashes`. | ||
| 769 | + | ||
| 770 | +Fuzzer'ın kendi izleyicisi bir yan etki üretiyordu: `sys.settrace(None)` çağrısı | ||
| 771 | +`coverage`'ın izleyicisini de kapatıyor, dolayısıyla fuzz testleri koştuktan sonra | ||
| 772 | +kapsam ölçümü sessizce duruyordu. Önceki izleyici `sys.gettrace()` ile saklanıp geri | ||
| 773 | +konur; testle doğrulandı. | ||
| 774 | + | ||
| 775 | +#### 4. Model tabanlı test (week10, W yöntemi) | ||
| 776 | + | ||
| 777 | +`JobStore` biçimsel bir **Mealy makinesi** olarak modellendi. Modelleme sırasında | ||
| 778 | +durum etiketlerinin yetmediği ortaya çıktı: `cancel_requested` bayrağı davranışı | ||
| 779 | +değiştirdiği için `running` ikiye (`R`, `RC`), `failed` ikiye (`F`, `FC`) ayrılıyor. | ||
| 780 | +Sonuç **7 durumlu** bir makine — beş değil. | ||
| 781 | + | ||
| 782 | +- **X** (7 girdi): `begin`, `finish`, `fail`, `cancel`, `progress`, `status`, | ||
| 783 | + `cancel_requested` | ||
| 784 | +- **V** (durum örtüsü): BFS ile üretilir, boş dizi dahil 7 dizi | ||
| 785 | +- **W** (karakterize edici küme): bölüntü inceltme + geriye eleme ile **hesaplanır**, | ||
| 786 | + elle seçilmez. Sonuç `{[status], [cancel_requested]}` — 2 dizi, slaytın `n-1` | ||
| 787 | + sınırının çok altında | ||
| 788 | +- **Test kümesi**: `V·W ∪ V·X·W` = **100 dizi**, her dizinin öncesinde sıfırlama | ||
| 789 | + (taze iş kaydı) | ||
| 790 | + | ||
| 791 | +Slayt 12 geçiş turunun **yeterli olmadığını** söyler. Bunu kendi kodumuzda ölçtük. | ||
| 792 | +`fail()` iptal bayrağını silecek şekilde bozuldu — yani `FC` durumu tamamen yok | ||
| 793 | +edildi: | ||
| 794 | + | ||
| 795 | +``` | ||
| 796 | +eski paket (unit + integration + regress, 272 test) -> HEPSI YESIL | ||
| 797 | +model paketi (100 dizi) -> 9 KIRMIZI | ||
| 798 | +``` | ||
| 799 | + | ||
| 800 | +272 testin tamamı bu durum geçiş hatasını kaçırdı; yalnızca biçimsel modelin | ||
| 801 | +adlandırdığı `FC` durumu onu görünür kıldı. Slaytların *"durum geçiş hataları ... | ||
| 802 | +fark etmesi daha zor"* uyarısının bu depodaki doğrudan kanıtı budur. | ||
| 803 | + | ||
| 804 | +Model ayrıca **erişilemez kod** buldu: `JobStore.begin()` içindeki | ||
| 805 | +`if record["cancel_requested"]` koruması hiçbir genel API dizisiyle çalıştırılamıyor, | ||
| 806 | +çünkü bayrağı doğruya çeken iki fonksiyon (`cancel`, `shutdown`) da işi `queued` | ||
| 807 | +durumunda bırakmıyor. Kapsam ölçümü bunu bağımsız olarak doğruladı | ||
| 808 | +(`jobs.py:578-580` kapsanmamış). Slaytların sınıflandırması gereği: **erişilemez, | ||
| 809 | +eksik test değil**. Kod silinmedi — savunma amaçlı; bunun yerine | ||
| 810 | +`regress_unreachable_guard.py` bayrağı yazan fonksiyon kümesini AST ile kilitledi: | ||
| 811 | +biri eklenirse test kırmızıya döner ve korumanın canlandığını söyler. | ||
| 812 | + | ||
| 813 | +#### 5. Açık kalanlar | ||
| 814 | + | ||
| 815 | +- `bridge.py` %34 — QUIC istemcisi için sahte bir `aioquic` sunucusu gerekir; kanıt | ||
| 816 | + bugün elle koşumdan geliyor. Paketin bilinen en büyük boşluğu. | ||
| 817 | +- Mutasyon yalnızca `protocol.py` için tamamlandı; `jobs.py`, `capabilities.py`, | ||
| 818 | + `config.py`, `pipeline.py` sırada. Haftalık iş akışı bunları zamanla kapsayacak. | ||
| 819 | +- PDF ayrıştırıcı fuzzing'i (slayt 7 PDF'i açıkça sayar) bu depoda **değil**: PDF'i | ||
| 820 | + hat deposu ayrıştırır, servis yalnızca kimlik ve yol doğrular. Fuzzing oraya ait ve | ||
| 821 | + orada açık bir maddedir. | ||
| 822 | + | ||
| 823 | +### Test yazma kuralları (bu depo) | ||
| 824 | + | ||
| 825 | +- **Test kodunda yorum ve docstring yok** — `src/` ile aynı kural. Açıklama test | ||
| 826 | + **metot adında** ve `assertX` **mesajında** durur. | ||
| 827 | +- Her dosyanın sonunda `if __name__ == "__main__": unittest.main()`. | ||
| 828 | +- Çok vakalı kontroller `subTest` ile; `@unittest.skip` kullanılmaz. | ||
| 829 | +- Testler **ağ kullanmaz**, `aioquic` gerektirmez (`bridge.py` sınanırken | ||
| 830 | + `sys.modules`'a kukla bir `aioquic` konur), gerçek hattı import etmez ve | ||
| 831 | + `PODCAST_JOB_ROOT`'a yazmaz — hepsi `tempfile` altında çalışır. | ||
| 832 | +- Testler birbirinden bağımsızdır: ortam değişkeni veya `config._active_level` | ||
| 833 | + değiştiren test `setUp`/`tearDown` ile geri alır. | ||
| 834 | +- Tüm paket 30 saniyenin altında koşar; uzun `sleep` yoktur. | ||
| 835 | + | ||
| 836 | +### Neyi KAPSAMAZ | ||
| 837 | + | ||
| 838 | +Bunlar bilerek dışarıda bırakılmıştır; kanıtları başka yerden gelir: | ||
| 839 | + | ||
| 840 | +- **Container montajı** — imaj build'i, `podman compose`, hacim bağlama, sağlık | ||
| 841 | + kontrolü akışı. Bunlar `deploy/OKU.md` ve elle koşum ile doğrulanır. | ||
| 842 | +- **Gerçek hat** — `router.hat.Hat`, gerçek OCR/TTS/ffmpeg. Testler `Hat`'ın | ||
| 843 | + yerine sahte bir sınıf koyar; ağırlıklar ve ffmpeg gerekmez. Gerçek hat kanıtı | ||
| 844 | + `tools/smoke_test.py` ile üretilir. | ||
| 845 | +- **LLM yolu** — `tek_ogretici`/`ogrenci_hoca` üretimi, DeepSeek çağrıları, | ||
| 846 | + bütçe muhasebesi. Testler yalnızca **kapının** (anahtar yokken | ||
| 847 | + `llm_unavailable`) doğru çalıştığını sınar, üretimin kalitesini değil. | ||
| 848 | +- **Çok bölümlü PDF** — çok bölümlü gerçek bir koşunun bölümleme, süre ve montaj | ||
| 849 | + davranışı. Kimlik/hizalama mantığı sahte yollarla sınanır, gerçek PDF ile değil. | ||
| 850 | +- **QUIC kablosu** — sertifika çekme, TLS pinleme, gerçek bağlantı, yeniden | ||
| 851 | + bağlanma döngüsü. `bridge.py`'nin yalnızca çerçeve/cevap mantığı sınanır. | ||
| 852 | + | ||
| 853 | + | ||
| 854 | +## Dağıtım (adım 4) | ||
| 855 | + | ||
| 856 | +İnsan rehberi **`deploy/OKU.md`**'dir; burada yalnızca **kararlar ve | ||
| 857 | +gerekçeleri** yazılıdır. | ||
| 858 | + | ||
| 859 | +> `deploy/*.ps1` betiklerinde **yorum satırı yoktur.** Koşturarak ölçülmüş beş | ||
| 860 | +> PowerShell/podman tuzağı ve `Invoke-Quiet` yardımcısının gerekçesi | ||
| 861 | +> `deploy/OKU.md` → **"Betiklerdeki tuzaklar (ölçüldü)"** bölümündedir. Bir | ||
| 862 | +> betiği düzenlemeden önce orayı okuyun. | ||
| 863 | + | ||
| 864 | +### Hat imaja VENDOR edilir, bind-mount edilmez | ||
| 865 | + | ||
| 866 | +Hat ayrı bir repodadır (`C:\PROJECTS\podcast`). İki gereksinim çatışıyordu: | ||
| 867 | +imaj **self-contained** olmalı (bind-mount'lu bir imaj taşınabilir değildir ve | ||
| 868 | +hangi kaynakla koştuğu çalışma anına kadar belirsiz kalır), ama hattın **gerçek | ||
| 869 | +kaynağı tek** kalmalı. Çözüm tek yönlü bir kopyalayıcıdır: | ||
| 870 | + | ||
| 871 | +``` | ||
| 872 | +deploy/setup-pipeline.ps1 -> vendor/pipeline/ (kaynak: C:\PROJECTS\podcast) | ||
| 873 | +.gitignore -> vendor/ izlenmez | ||
| 874 | +Containerfile -> COPY vendor/pipeline /app/pipeline | ||
| 875 | +compose.yaml -> PODCAST_PIPELINE_PATH=/app/pipeline | ||
| 876 | +``` | ||
| 877 | + | ||
| 878 | +Kopyalanan: `router/ script/ ses/ ingest/ bilgi/ config/` + üç | ||
| 879 | +`requirements*.txt` — **ölçüldü: ~1,5 MB**. Vendor içinde yapılan düzenleme bir | ||
| 880 | +sonraki koşuda silinir; gerçek düzenleme hat reposunda yapılır. | ||
| 881 | + | ||
| 882 | +**`tools/bin/` bilerek KOPYALANMAZ.** İçindekiler `ffmpeg.exe` + `ffprobe.exe`, | ||
| 883 | +yani **Windows ikilileri**, ve **ölçüldü: 219,8 MB**. Linux container'da | ||
| 884 | +çalışmazlar. `ses/ayar.py:22-23` bu yolu **sabit kodlar** ve ortam değişkeni | ||
| 885 | +kabul etmez, bu yüzden Containerfile ffmpeg'i `apt`'tan kurar ve | ||
| 886 | +`tools/bin/ffmpeg.exe → /usr/bin/ffmpeg` sembolik bağını atar — uzantı | ||
| 887 | +Linux'ta anlamsızdır, yani kaynağa dokunmadan çözülür. | ||
| 888 | + | ||
| 889 | +### Ağırlıklar hacimde, imajda DEĞİL | ||
| 890 | + | ||
| 891 | +Ağırlık **veridir, kod değildir**. İmaja koymak her `--build`'i 4 GB'lık bir | ||
| 892 | +katman kopyasına çevirir ve `rollback.ps1`in tuttuğu **her** etiketi 4 GB yapardı. | ||
| 893 | + | ||
| 894 | +| Ağırlık | Ölçülen | Container yolu | Ne için | | ||
| 895 | +|---|---|---|---| | ||
| 896 | +| `intfloat/multilingual-e5-large` | 2156,99 MB | `/models/hf/hub/` | gömme (`bilgi/erisim.py`) | | ||
| 897 | +| `faster-whisper medium` | 1459,67 MB | `/models/ses_modelleri/faster_whisper/` | round-trip CER kalite kapısı | | ||
| 898 | +| `supertonic-3` | 382,72 MB | `/models/ses_modelleri/supertonic-3/` | TTS | | ||
| 899 | +| **toplam** | **~3,9 GB** | `podcast-models` hacmi, `:ro` | | | ||
| 900 | + | ||
| 901 | +`deploy/setup-models.ps1` **yerelden kopyalar** (üçü de bu makinede var); | ||
| 902 | +bulamadığını **indirmez, indirme komutunu basar** — 4 GB'lık bir çekmeye | ||
| 903 | +operatör karar verir. Hacme yazma tekniği chatbot'un | ||
| 904 | +`setup-podman-wsl.ps1:39-42` deseni (`podman cp`), **ağ gerektirmez**. | ||
| 905 | + | ||
| 906 | +**İki farklı arama yolu var, karıştırılmamalı:** | ||
| 907 | + | ||
| 908 | +- `e5-large` HF hub önbelleğinden gelir → `HF_HOME=/models/hf` işe yarar. | ||
| 909 | +- **TTS ve ASR ağırlıkları HF önbelleğinde DEĞİL.** `ses/ayar.py:26` | ||
| 910 | + `MODEL_KOKU = <hat_koku>/data/ses_modelleri` diye **sabit kodlar** | ||
| 911 | + (`:186` `ASR_KOK` da ondan türer) ve **ortam değişkeni yoktur**. Bu yüzden | ||
| 912 | + Containerfile `/app/pipeline/data/ses_modelleri → /models/ses_modelleri` | ||
| 913 | + sembolik bağını atar. Kaynağa dokunmadan çözülen ikinci nokta budur. | ||
| 914 | + | ||
| 915 | +`HF_HUB_OFFLINE=1`: ağırlık hacimde yoksa hat **açık hata** verir, sessizce | ||
| 916 | +2,2 GB indirmeye başlamaz. | ||
| 917 | + | ||
| 918 | +### Medya ve çıktı hacimleri | ||
| 919 | + | ||
| 920 | +| Hacim | Bağlantı | Mod | Ne tutar | | ||
| 921 | +|---|---|---|---| | ||
| 922 | +| `hezarfen-data` (**external**) | `/data/files` | **:ro** | Backend'in PDF blob deposu (`FILES_PATH`). `PODCAST_MEDIA_ROOT` ile aynı yol. | | ||
| 923 | +| `podcast-out` | `/data/podcast/out` | rw | Üretilen mp3 / script / quiz (`PODCAST_OUTPUT_ROOT`) | | ||
| 924 | +| `podcast-jobs` | `/data/podcast/jobs` | rw | İş durumu + `.bridge-status` | | ||
| 925 | +| `podcast-kayit` | `/data/podcast/kayit` | rw | `router.sqlite` — adım önbelleği, resume, LLM bütçesi | | ||
| 926 | +| `podcast-models` | `/models` | **:ro** | ~3,9 GB ağırlık | | ||
| 927 | +| `podcast-easyocr` | `/home/podcast/.EasyOCR` | rw | easyocr'ın kendi indirdiği tanıma modelleri | | ||
| 928 | + | ||
| 929 | +PDF **okunur**, ses **yazılır**: medya hacmi `:ro` bağlanır. `podcast-kayit` | ||
| 930 | +ayrı bir hacimdir çünkü **önbellek bu hattın tasarım ilkesidir**; defter kalıcı | ||
| 931 | +değilse her koşu her adımı baştan yapar (ölçülen `script` adımı tek başına | ||
| 932 | +~34 dk). | ||
| 933 | + | ||
| 934 | +> **OPERATÖR DOĞRULAMALI — `external` adlar.** Bu makinede **podman kurulu | ||
| 935 | +> değil**; `hezarfen-data` hacminin ve backend ağının gerçek adı çalışan bir | ||
| 936 | +> sistemde **doğrulanamadı**. Adlar compose **proje adından** türer ve proje | ||
| 937 | +> adı varsayılan olarak **dizin adıdır**; backend dizini | ||
| 938 | +> `hezarfen_backend-main`'dir, yani ham `podman compose up` ile adlar | ||
| 939 | +> `hezarfen_backend-main_default` / `hezarfen_backend-main_hezarfen-data` | ||
| 940 | +> olurdu. Ama `frontend` ve `chatbot` compose'ları ağı | ||
| 941 | +> **`hezarfen_backend_default` diye sabit yazıyor** — o adla kalkmazlardı. | ||
| 942 | +> Bu yüzden `deploy/run-stack.ps1` backend'i **bilerek `-p hezarfen_backend`** | ||
| 943 | +> ile kaldırır; compose varsayılanları (`hezarfen_backend_default`, | ||
| 944 | +> `hezarfen_backend_hezarfen-data`) buna dayanır. Betik ayrıca gerçek adları | ||
| 945 | +> `podman inspect hezarfen-backend`ten **okur** ve `HEZARFEN_NET` / | ||
| 946 | +> `HEZARFEN_DATA_VOLUME` olarak geçirir. Elle `podman compose up` yapan | ||
| 947 | +> operatör **önce `podman volume ls` / `podman network ls` ile doğrulamalıdır.** | ||
| 948 | + | ||
| 949 | +### Sağlık compose'da, Containerfile'da DEĞİL | ||
| 950 | + | ||
| 951 | +Podman'ın OCI biçimi imajdaki `HEALTHCHECK`'i **yok sayar**. Bu yüzden sağlık | ||
| 952 | +`compose.yaml`dadır: `python -m src.main --health`, `interval 30s`, | ||
| 953 | +`timeout 10s`, `retries 3`, `start_period 90s`. `--health`'in ne yaptığı | ||
| 954 | +yukarıda ("Çalıştırma") anlatıldı. | ||
| 955 | + | ||
| 956 | +`start_period: 90s` **ölçülmedi**; model yükleme süresine göre seçilmiş bir | ||
| 957 | +tahmindir ve ilk gerçek koşudan sonra ayarlanmalıdır. | ||
| 958 | + | ||
| 959 | +### İmaj sürümleme ve geri alma | ||
| 960 | + | ||
| 961 | +Ev şablonu (chatbot) `:local` kullanıyor ve her build aynı etiketi eziyor — | ||
| 962 | +**dönülecek bir imaj kalmıyor**. Burada `run-stack.ps1` her build'i | ||
| 963 | +`localhost/hezarfen-podcast:<yyyyMMdd-HHmmss>` olarak etiketler **ve** | ||
| 964 | +`:current` işaretini oraya taşır; `compose.yaml` `:current` kullanır. | ||
| 965 | + | ||
| 966 | +```powershell | ||
| 967 | +podman images localhost/hezarfen-podcast --format "{{.Tag}} {{.ID}} {{.CreatedSince}}" | ||
| 968 | +pwsh -File deploy/rollback.ps1 -List | ||
| 969 | +pwsh -File deploy/rollback.ps1 # bir onceki etikete don | ||
| 970 | +pwsh -File deploy/rollback.ps1 -Tag 20260831-181530 | ||
| 971 | +``` | ||
| 972 | + | ||
| 973 | +Geri alma **yeniden build etmez**: `podman tag` + `compose up -d | ||
| 974 | +--force-recreate`. `--force-recreate` şarttır — etiket **adı** değişmediği için | ||
| 975 | +compose "değişiklik yok" deyip container'ı bırakabilir. | ||
| 976 | + | ||
| 977 | +### Kaynak sınırları — ÖLÇÜLMEDİ | ||
| 978 | + | ||
| 979 | +`mem_limit: 8g`, `cpus: 4.0`. Adım 1'deki `2g` sahte hat içindi; artık ~4 GB'lık | ||
| 980 | +ağırlık yükleniyor. **Bu iki sayı ölçüm değildir.** Ölçülen tek şey ağırlıkların | ||
| 981 | +**disk** boyutudur (e5-large 2156,99 MB + faster-whisper 1459,67 MB + | ||
| 982 | +supertonic 382,72 MB); RSS ölçülmedi ve üçünün **aynı anda** yüklü olup | ||
| 983 | +olmadığı da bilinmiyor. **İlk gerçek konteyner koşusundan sonra ayarlanmalıdır.** | ||
| 984 | + | ||
| 985 | +## BİLİNEN EKSİKLER / SONRAKİ ADIM | ||
| 986 | + | ||
| 987 | +- **Üretilen MP3 backend'e ULAŞMIYOR — teslim yolu tanımsız.** `podcast-out` | ||
| 988 | + özel bir hacimdir; backend onu bağlamıyor (yalnızca `hezarfen-data`). | ||
| 989 | + `podcast.result`'ın döndürdüğü `audio_id`, `PODCAST_OUTPUT_ROOT`'a göre | ||
| 990 | + relatif bir yoldur ve backend'in çözebileceği bir kökü yoktur. Ürünün ana | ||
| 991 | + çıktısının teslim mekanizması **henüz kararlaştırılmadı**; iki seçenek var: | ||
| 992 | + (a) MP3'ü `hezarfen-data`'nın `files/` altına ULID adıyla yazmak ve backend'in | ||
| 993 | + mevcut blob rotasını kullanmak — bu `hezarfen-data`'yı `:ro` yerine `rw` | ||
| 994 | + bağlamayı gerektirir, (b) backend'e `podcast-out`'u `:ro` bağlayıp yeni bir | ||
| 995 | + servis rotası eklemek. Karar backend tarafıyla birlikte verilmeli. | ||
| 996 | + | ||
| 997 | +- ~~Cok bolumlu hizalama sinanmadi~~ - **KAPANDI (2026-09-07).** Eldeki | ||
| 998 | + orneklerin hicbiri birden fazla bolum uretmiyordu; bunun icin hat deposuna | ||
| 999 | + `tools/make_cok_bolumlu_pdf.py` yazildi (dort ust duzey bolum, her biri | ||
| 1000 | + kendi sayfasinda). Olculdu: hat **3 script** uretti, `bolum_limiti=1` ile | ||
| 1001 | + **1 ses** cikti ve `script_ids` 3'ten **1'e suzuldu**. Hizalama olmasaydi | ||
| 1002 | + tuketici 1 sese 3 script gorurdu. | ||
| 1003 | + | ||
| 1004 | +- ~~LLM'li formatlar sinanmadi~~ - **KAPANDI (2026-09-07).** `tek_ogretici` | ||
| 1005 | + gercek anahtarla konteyner icinde kostu: script adimi 637,8 sn, 19 replika, | ||
| 1006 | + 312,5 sn ses, **quiz 4 madde** (`duz_okuma`'da 0). `audio_id` yolu | ||
| 1007 | + `.../ses/tek_ogretici/...` - `duz_okuma` kosusuyla ayni `bolum_id`, farkli | ||
| 1008 | + yol; format carpismasi gercek ciktiyla da kapandi. | ||
| 1009 | + kez bile build edilmedi, hiçbir betik koşturulmadı. Doğrulanmamış varsayımlar: | ||
| 1010 | + `pip install` çözümlemesinin Linux/py3.10'da geçtiği, `torch` CPU tekerleğinin | ||
| 1011 | + bulunduğu, ağ ve hacim adları, imaj boyutu, build süresi, `start_period: 90s`, | ||
| 1012 | + `mem_limit: 8g`. Betikler yalnızca **sözdizimi** olarak denetlendi | ||
| 1013 | + (`[Parser]::ParseFile`). | ||
| 1014 | +- **`transformers` hattın hiçbir `requirements*.txt`inde yazılı değil.** | ||
| 1015 | + `requirements-ses.txt` onu (ve `onnxruntime`, `numpy`, `huggingface_hub`'ı) | ||
| 1016 | + "zaten kurulu" varsayıyor. Containerfile bu boşluğu yereldeki **ölçülen** | ||
| 1017 | + sürümlere pinleyerek kapatır (`transformers==5.15.0`, `onnxruntime==1.23.2`, | ||
| 1018 | + `numpy==2.2.6`, `huggingface_hub==1.27.0`). `torch` **pinlenmedi** — CPU | ||
| 1019 | + tekerlek indeksinde py3.10 için hangi sürümün durduğu doğrulanamadı. | ||
| 1020 | +- **easyocr ağırlıkları imajda yok.** İlk taranmış PDF'te easyocr onları kendi | ||
| 1021 | + indirir (`podcast-easyocr` hacmine; kalıcı ama **ağ gerekir**). `HF_HUB_OFFLINE` | ||
| 1022 | + easyocr'ı etkilemez — kendi indiricisi vardır. | ||
| 1023 | +- **`--health` bayatlık denetlemez.** Köprü durumu yalnızca *değiştiğinde* yazar; | ||
| 1024 | + asılı kalmış (hung) ama `registered=true` bırakmış bir süreç sağlıklı görünür. | ||
| 1025 | +- **İptal adım sınırında.** 34 dakikalık `script` adımının ortasında iptal | ||
| 1026 | + görülemez (yukarıda "SINIR" başlığı). Hattın kendisine ara kontrol noktası | ||
| 1027 | + eklenmedi. | ||
| 1028 | +- **`PODCAST_OUTPUT_ROOT` temizlenmiyor.** Üretilen mp3'ler süresiz birikir; | ||
| 1029 | + `PODCAST_JOB_ROOT` ile aynı retention sorunu. | ||
| 1030 | +- **`PODCAST_OUTPUT_ROOT` altındaki `_hat` dizini.** `ses/ayar.py`'nin | ||
| 1031 | + `ARA_KOKU` varsayılanı (`<hat_koku>/out/ses/_ara`) imajda | ||
| 1032 | + `/data/podcast/out/_hat`'e sembolik bağlanır. Ölçülen çağrı yollarında | ||
| 1033 | + `Hat` ara dizini **her zaman kendisi verir** (`self.cikti/_ara/<bolum>`), | ||
| 1034 | + yani bu bağ pratikte kullanılmıyor — sigorta olarak duruyor. | ||
| 1035 | + | ||
| 1036 | +### Duman testi (`tools/smoke_test.py`) | ||
| 1037 | + | ||
| 1038 | +`--validate`'in **parçası değildir** ve otomatik koşmaz: tek bir gerçek işi | ||
| 1039 | +uçtan uca koşturur, dakikalar sürer (LLM gerekmez ama TTS uzundur). | ||
| 1040 | +`samples/kisa_slayt.pdf` en küçük uygun örnektir ve varsayılan kaynaktır. | ||
| 1041 | + | ||
| 1042 | +```sh | ||
| 1043 | +cd C:\PROJECTS\podcast\hezarfen_podcast_service | ||
| 1044 | +python tools/smoke_test.py | ||
| 1045 | +``` | ||
| 1046 | + | ||
| 1047 | +Varsayılanlar: `PODCAST_MODE=real`, | ||
| 1048 | +`PODCAST_PIPELINE_PATH=C:\PROJECTS\podcast`, | ||
| 1049 | +`PODCAST_MEDIA_ROOT=C:\PROJECTS\podcast\samples`, | ||
| 1050 | +`--source kisa_slayt.pdf`, `--format duz_okuma`. İş ve çıktı kökleri | ||
| 1051 | +`./out/duman/` altına yazılır; `PODCAST_JOB_ROOT`'a dokunmaz. | ||
| 1052 | + | ||
| 1053 | +Faydalı bayraklar: | ||
| 1054 | + | ||
| 1055 | +```sh | ||
| 1056 | +python tools/smoke_test.py --source ornek_ders.pdf --format duz_okuma | ||
| 1057 | +python tools/smoke_test.py --timeout 3600 # bkz. --help | ||
| 1058 | +python tools/smoke_test.py --cancel-after 90 # 90 sn sonra iptal ister | ||
| 1059 | +``` | ||
| 1060 | + | ||
| 1061 | +`--cancel-after` iptalin **adım sınırında** yakalandığını gözlemlemek içindir: | ||
| 1062 | +iptal isteği anında değil, koşan adım bitince etki eder. | ||
| 1063 | + | ||
| 1064 | +Çıkış kodu: `0` = `done`, `1` = `failed`/`cancelled`/zaman aşımı, | ||
| 1065 | +`2` = hat yüklenemedi. | ||
| 1066 | + | ||
| 1067 | +### Adım 3: `Hat` nasıl bağlanacak (tarihçe) | ||
| 1068 | + | ||
| 1069 | +Gerçek hat tek parçadır — `Hat(pdf, format=...).kos()`, **~45 dakika**. Bağlantı | ||
| 1070 | +noktası `bridge.build_store(settings, runner=..., stages=...)`'tır: | ||
| 1071 | + | ||
| 1072 | +```python | ||
| 1073 | +def hat_runner(ctx): | ||
| 1074 | + ctx.check() | ||
| 1075 | + pdf = jobs.resolve_source(settings.media_root, ctx.source_id) | ||
| 1076 | + | ||
| 1077 | + def gunluk(asama, oran=0.0): | ||
| 1078 | + ctx.check() | ||
| 1079 | + ctx.progress(asama, oran) | ||
| 1080 | + | ||
| 1081 | + cikti = Hat(pdf, format=ctx.format, gunluk=gunluk).kos() | ||
| 1082 | + ctx.finish(cikti.audio_id, cikti.duration_secs, cikti.script_id) | ||
| 1083 | + | ||
| 1084 | +store = build_store(settings, runner=hat_runner, stages=HAT_ASAMALARI) | ||
| 1085 | +``` | ||
| 1086 | + | ||
| 1087 | +Dikkat edilecekler: | ||
| 1088 | + | ||
| 1089 | +- **İptal, `Hat(gunluk=...)` geri çağırımının içinden görülür.** `Hat` tek parça | ||
| 1090 | + olduğu için ara kontrol yalnızca oradan yapılabilir; `gunluk` her çağrıldığında | ||
| 1091 | + `ctx.check()` işletilir ve iptal varsa `JobCancelled` hattın **içinden** fırlar. | ||
| 1092 | + `Hat` bu istisnayı yutmamalı. Geri çağırım hiç çağrılmazsa iptal ancak işin | ||
| 1093 | + bitişinde (`ctx.finish()`) yakalanır — kaybolmaz, sadece gecikir. | ||
| 1094 | +- `PODCAST_ETA_SECS` gerçek süreye ayarlanmalı (ör. `2700`), yoksa backend'e | ||
| 1095 | + `eta_secs=1` bildirilir. | ||
| 1096 | +- `PODCAST_MEDIA_ROOT` backend'in `FILES_PATH`'i ile aynı olmalı. Adım 4'te | ||
| 1097 | + bağlandı: backend'in `hezarfen-data` hacmi `/data/files`'a **`:ro`** monte | ||
| 1098 | + edilir (bkz. "Dağıtım"). | ||
| 1099 | +- `HatHatasi` gibi hat istisnaları `failed` + `internal` olur; hattın kendi hata | ||
| 1100 | + kodlarını `error_code`'a taşımak istenirse `runner` içinde `store.fail()` | ||
| 1101 | + açıkça çağrılmalıdır. | ||
| 1102 | +- ~~Bitmis isler temizlenmiyor~~ - **KAPANDI.** `PODCAST_RETENTION_DAYS` | ||
| 1103 | + (kod varsayilani `0` = asla silme; `compose.yaml` `30` veriyor). Acilista | ||
| 1104 | + bir kez kosar, **yalnizca terminal durumdaki** (done/failed/cancelled) | ||
| 1105 | + isleri ve urettikleri ses/script dosyalarini siler. Kuyruktaki ve **kosan** | ||
| 1106 | + isler yasina bakilmadan korunur. Silinecek her yol cikti kokunun ALTINDA | ||
| 1107 | + olmak zorundadir - is JSON'lari diskten gelir ve kurcalanmis olabilir; | ||
| 1108 | + disari isaret eden kimlik uyari loglanip **atlanir** (`regress_retention.py` | ||
| 1109 | + bunu `../disarida/dokunulmaz.txt` ile sinar). | ||
| 1110 | +- ~~Taban imaj digest pin'i yok~~ - **KAPANDI.** `python:3.10-slim@sha256:4101e4a3...` | ||
| 1111 | + ile pinli; yenileme komutu `Containerfile` basindaki yorumda. | ||
| 1112 | +- ~~Test paketi yok~~ - **KAPANDI.** `tests/` altinda saf `unittest`, 255 test. | ||
| 1113 | +- **API-read yok.** Protokol servis→backend `ApiRequest` akışını destekliyor; | ||
| 1114 | + bu adımda kullanılmıyor. | ||
compose.yamladded+75 -0
| @@ -0,0 +1,75 @@ | |||
| 1 | +services: | ||
| 2 | + bridge: | ||
| 3 | + build: | ||
| 4 | + context: . | ||
| 5 | + dockerfile: Containerfile | ||
| 6 | + args: | ||
| 7 | + KUR_AGIR: ${KUR_AGIR:-1} | ||
| 8 | + image: localhost/hezarfen-podcast:current | ||
| 9 | + container_name: hezarfen-podcast-bridge | ||
| 10 | + init: true | ||
| 11 | + command: ["python", "-m", "src.bridge"] | ||
| 12 | + environment: | ||
| 13 | + AI_BRIDGE_HOST: hezarfen-backend | ||
| 14 | + AI_BRIDGE_PORT: "8090" | ||
| 15 | + AI_BACKEND_URL: http://hezarfen-backend:8080 | ||
| 16 | + AI_SHARED_TOKEN: ${AI_SHARED_TOKEN:?AI_SHARED_TOKEN gerekli} | ||
| 17 | + AI_TLS_SERVER_NAME: localhost | ||
| 18 | + AI_SERVICE_NAME: podcast | ||
| 19 | + AI_MAX_CONCURRENT: "2" | ||
| 20 | + AI_RECONNECT_SECS: "3" | ||
| 21 | + LOG_LEVEL: ${LOG_LEVEL:-info} | ||
| 22 | + PODCAST_JOB_ROOT: /data/podcast/jobs | ||
| 23 | + PODCAST_WORKERS: "1" | ||
| 24 | + PODCAST_MAX_JOBS: "8" | ||
| 25 | + # Bitmis isleri ve ciktilarini kac gun sonra sil. 0 = ASLA silme. | ||
| 26 | + # Kodda varsayilan 0 (veri silmek opt-in olmali); dagitimda acik deger | ||
| 27 | + # verilir, yoksa podcast-out ve podcast-jobs suresiz buyur. | ||
| 28 | + PODCAST_RETENTION_DAYS: "30" | ||
| 29 | + PODCAST_STAGE_SECS: "0.2" | ||
| 30 | + PODCAST_ETA_SECS: "0" | ||
| 31 | + PODCAST_MEDIA_ROOT: /data/files | ||
| 32 | + PODCAST_MODE: ${PODCAST_MODE:-real} | ||
| 33 | + PODCAST_PIPELINE_PATH: ${PODCAST_PIPELINE_PATH:-/app/pipeline} | ||
| 34 | + PODCAST_OUTPUT_ROOT: /data/podcast/out | ||
| 35 | + PODCAST_LEDGER_DB: /data/podcast/kayit/router.sqlite | ||
| 36 | + PODCAST_CHAPTER_LIMIT: "1" | ||
| 37 | + PODCAST_TTS_ENGINE: supertonic-3 | ||
| 38 | + HF_HOME: /models/hf | ||
| 39 | + TORCH_HOME: /models/torch | ||
| 40 | + HF_HUB_OFFLINE: ${HF_HUB_OFFLINE:-1} | ||
| 41 | + TRANSFORMERS_OFFLINE: ${HF_HUB_OFFLINE:-1} | ||
| 42 | + DEEPSEEK_API_KEY: ${DEEPSEEK_API_KEY:-} | ||
| 43 | + volumes: | ||
| 44 | + - hezarfen-data:/data:ro | ||
| 45 | + - podcast-jobs:/data/podcast/jobs | ||
| 46 | + - podcast-out:/data/podcast/out | ||
| 47 | + - podcast-kayit:/data/podcast/kayit | ||
| 48 | + - podcast-models:/models:ro | ||
| 49 | + - podcast-easyocr:/home/podcast/.EasyOCR | ||
| 50 | + restart: unless-stopped | ||
| 51 | + healthcheck: | ||
| 52 | + test: ["CMD", "python", "-m", "src.main", "--health"] | ||
| 53 | + interval: 30s | ||
| 54 | + timeout: 10s | ||
| 55 | + retries: 3 | ||
| 56 | + start_period: 90s | ||
| 57 | + mem_limit: 8g | ||
| 58 | + cpus: 4.0 | ||
| 59 | + networks: | ||
| 60 | + - backend_net | ||
| 61 | + | ||
| 62 | +volumes: | ||
| 63 | + podcast-jobs: | ||
| 64 | + podcast-out: | ||
| 65 | + podcast-kayit: | ||
| 66 | + podcast-models: | ||
| 67 | + podcast-easyocr: | ||
| 68 | + hezarfen-data: | ||
| 69 | + external: true | ||
| 70 | + name: ${HEZARFEN_DATA_VOLUME:-hezarfen_backend_hezarfen-data} | ||
| 71 | + | ||
| 72 | +networks: | ||
| 73 | + backend_net: | ||
| 74 | + external: true | ||
| 75 | + name: ${HEZARFEN_NET:-hezarfen_backend_default} | ||
deploy/OKU.mdadded+552 -0
| @@ -0,0 +1,552 @@ | |||
| 1 | +# Podcast servisi — dağıtım rehberi (Podman / Windows-WSL2) | ||
| 2 | + | ||
| 3 | +Bu dizin `hezarfen_podcast_service`'i **gerçek hattıyla birlikte** container'da | ||
| 4 | +ayağa kaldırır. Ev şablonu chatbot'un `deploy/` dizinidir; farklar ve | ||
| 5 | +**gerekçeleri** aşağıda tek tek yazılıdır. | ||
| 6 | + | ||
| 7 | +> **Kernel/machine kurulumu bu repoda TEKRARLANMADI.** Podman'ın WSL2'de | ||
| 8 | +> çalışması için gereken özel kernel + rootless machine adımları **bir kez** | ||
| 9 | +> yapılır ve chatbot reposundadır: | ||
| 10 | +> `hezarfen_rule_based_chatbot-main\...\deploy\PODMAN-WSL-SETUP.md` | ||
| 11 | +> (`setup-podman-wsl.ps1`). İki kopya iki doğruluk kaynağı olurdu. | ||
| 12 | + | ||
| 13 | +--- | ||
| 14 | + | ||
| 15 | +## Ön koşullar | ||
| 16 | + | ||
| 17 | +| # | Koşul | Doğrulama | | ||
| 18 | +|---|---|---| | ||
| 19 | +| 1 | Podman Desktop + çalışan bir machine, **rootless** | `podman machine list` | | ||
| 20 | +| 2 | WSL2 özel kernel'i kurulmuş (nft_fib/bridge/veth/tun) | `podman run --rm docker.io/surrealdb/surrealdb:v3 version` netavark hatası vermemeli | | ||
| 21 | +| 3 | Hat kaynağı diskte | `C:\PROJECTS\podcast\router\hat.py` var mı | | ||
| 22 | +| 4 | Model ağırlıkları diskte (ya da indirilecek) | aşağıdaki tablo | | ||
| 23 | +| 5 | `AI_SHARED_TOKEN` — backend'inkiyle **aynı** | **`.env` dosyası** (ortam değişkeni değil — aşağıya bkz.) | | ||
| 24 | +| 6 | Boş disk: imaj ~4-5 GB + hacimler ~4 GB | | | ||
| 25 | + | ||
| 26 | +--- | ||
| 27 | + | ||
| 28 | +## Hızlı başlangıç (dört komut) | ||
| 29 | + | ||
| 30 | +```powershell | ||
| 31 | +cd C:\PROJECTS\podcast\hezarfen_podcast_service | ||
| 32 | + | ||
| 33 | +pwsh -File deploy/setup-pipeline.ps1 # 1) hat kaynagi -> vendor/pipeline (~1,5 MB, saniyeler) | ||
| 34 | +pwsh -File deploy/setup-models.ps1 # 2) agirliklar -> podcast-models hacmi (~3,9 GB, DAKIKALAR) | ||
| 35 | +Copy-Item .env.example .env # 3) sonra .env icindeki | ||
| 36 | + # AI_SHARED_TOKEN degerini | ||
| 37 | + # backend ile AYNI yap | ||
| 38 | +pwsh -File deploy/run-stack.ps1 # 4) dort repoyu sirayla kaldirir + dogrular | ||
| 39 | +``` | ||
| 40 | + | ||
| 41 | +Bittiğinde: frontend **http://localhost:5173** (`admin` / `admin123`), | ||
| 42 | +backend **http://localhost:8080**, podcast köprüsü port açmaz — | ||
| 43 | +kanıtı `podman logs hezarfen-podcast-bridge` içindeki `kayit basarili` satırıdır. | ||
| 44 | + | ||
| 45 | +--- | ||
| 46 | + | ||
| 47 | +## Adım adım | ||
| 48 | + | ||
| 49 | +### 1. `setup-pipeline.ps1` — hattı vendor'a kopyalar | ||
| 50 | + | ||
| 51 | +Hat **ayrı bir repodadır** (`C:\PROJECTS\podcast`). İmaj self-contained olmalı | ||
| 52 | +ama hattın gerçek kaynağı **tek** kalmalı. Karar: tek yönlü kopyalayıcı. | ||
| 53 | + | ||
| 54 | +* Kaynak önce **doğrulanır** (`router/hat.py`, `config/router.toml`, | ||
| 55 | + `router/yonlendirici.py`, `script/plan.py`, `ses/montaj.py`, | ||
| 56 | + `ingest/__init__.py`, üç `requirements*.txt`). Yanlış yol sessizce boş bir | ||
| 57 | + vendor üretemez. | ||
| 58 | +* Kopyalanan: `router/ script/ ses/ ingest/ bilgi/ config/` + | ||
| 59 | + `requirements.txt requirements-ocr.txt requirements-ses.txt` — **ölçüldü: ~1,5 MB**. | ||
| 60 | +* Kopyalanmayan: `.venv/ out/ data/ models/ samples/ vastai_* backend/ frontend/ | ||
| 61 | + hezarfen_*/ .git/ __pycache__/ *.pyc`. | ||
| 62 | +* **`tools/bin/` de kopyalanmaz.** İçindekiler `ffmpeg.exe` + `ffprobe.exe`, | ||
| 63 | + yani **Windows ikilileri** ve **ölçüldü: 219,8 MB**. Linux container'da | ||
| 64 | + çalışmazlar. Containerfile ffmpeg'i `apt`'tan kurar ve | ||
| 65 | + `tools/bin/ffmpeg.exe → /usr/bin/ffmpeg` sembolik bağını atar | ||
| 66 | + (`ses/ayar.py:22` yolu **sabit kodlar**; uzantı Linux'ta anlamsızdır). | ||
| 67 | + `-WindowsBinaries` ile yine de kopyalanabilir. | ||
| 68 | + | ||
| 69 | +`vendor/` **`.gitignore`'dadır**: kaynağı orada değil, hat reposundadır. | ||
| 70 | +Vendor içinde yapılan düzenleme bir sonraki koşuda **silinir**. | ||
| 71 | + | ||
| 72 | +### 2. `setup-models.ps1` — ağırlıkları `podcast-models` hacmine koyar | ||
| 73 | + | ||
| 74 | +Ağırlık **veridir, kod değildir**; imaja koymak her build'i 4 GB'lık bir katman | ||
| 75 | +kopyasına çevirir ve `rollback.ps1`in tuttuğu her etiketi 4 GB yapardı. | ||
| 76 | + | ||
| 77 | +| Ağırlık | Ölçülen boyut | Nereye | Ne için | | ||
| 78 | +|---|---|---|---| | ||
| 79 | +| `intfloat/multilingual-e5-large` | **2156,99 MB** | `/models/hf/hub/` | gömme (`bilgi/erisim.py`) | | ||
| 80 | +| `faster-whisper medium` | **1459,67 MB** | `/models/ses_modelleri/faster_whisper/` | round-trip CER kalite kapısı | | ||
| 81 | +| `supertonic-3` | **382,72 MB** | `/models/ses_modelleri/supertonic-3/` | TTS | | ||
| 82 | +| **toplam** | **~3,9 GB** | | | | ||
| 83 | + | ||
| 84 | +* **Yerel-önce.** Üç ağırlık da bu makinede zaten var; betik onları kopyalar. | ||
| 85 | + Bulunmayan için **indirme komutunu basar ama indirmez** — 4 GB'lık bir çekmeye | ||
| 86 | + operatör karar verir. | ||
| 87 | +* Hacme yazma tekniği: yardımcı bir container + `podman cp` (chatbot'un | ||
| 88 | + `setup-podman-wsl.ps1:39-42` deseni). **Ağ gerektirmez.** Tek fark: chatbot | ||
| 89 | + `podman create` kullanır, biz `podman run -d ... sleep` kullanırız — | ||
| 90 | + `podman cp` **duran** bir container'ın hacim bağlı yoluna yazdığında podman | ||
| 91 | + sürümüne göre hacme değil rootfs'e yazabilir ve yazma **sessizce kaybolur**. | ||
| 92 | +* Sonda `chmod -R a+rX /models` çalışır: hacim root sahipliğinde oluşur, | ||
| 93 | + container **uid 10001** ile ve `/models` `:ro` bağlanarak koşar. | ||
| 94 | + | ||
| 95 | +Denetleme: `pwsh -File deploy/setup-models.ps1 -Check` | ||
| 96 | + | ||
| 97 | +### 3. `run-stack.ps1` — dört repoyu sırayla kaldırır | ||
| 98 | + | ||
| 99 | +Sıra: **backend** (ağı ve `hezarfen-data` hacmini yaratır) → **frontend** → | ||
| 100 | +**chatbot** → **podcast**. | ||
| 101 | + | ||
| 102 | +**Repolar ada göre aranmaz.** Ev şablonu sabit adlarla arıyor | ||
| 103 | +(`hezarfen_backend` / `hezarfen_frontend` / `Hezarfen-Rule-Based-Chatbot`) ve bu | ||
| 104 | +makinede **hiçbiri tutmuyor**. Bu betik her repoyu `compose.yaml`ın | ||
| 105 | +**varlığına ve içeriğine** göre bulur (`container_name: hezarfen-backend` vb.), | ||
| 106 | +bulamazsa **açık hata** verir; birden çok aday bulursa da hata verir. | ||
| 107 | + | ||
| 108 | +**Proje adı kapısı (kritik).** `frontend` ve `chatbot` compose'ları ağı | ||
| 109 | +`hezarfen_backend_default` diye **sabit yazıyor**. compose proje adını dizin | ||
| 110 | +adından türetir; backend dizini `hezarfen_backend-main` olduğu için ağ | ||
| 111 | +`hezarfen_backend-main_default` olurdu ve **frontend/chatbot ayağa kalkmazdı.** | ||
| 112 | +Bu yüzden backend **bilerek** `-p hezarfen_backend` ile kaldırılır. | ||
| 113 | + | ||
| 114 | +Sonra betik gerçek adları **tahmin etmez, okur**: | ||
| 115 | + | ||
| 116 | +```powershell | ||
| 117 | +podman inspect hezarfen-backend --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' | ||
| 118 | +podman inspect hezarfen-backend --format '{{range .Mounts}}{{if eq .Destination "/data"}}{{.Name}}{{end}}{{end}}' | ||
| 119 | +``` | ||
| 120 | + | ||
| 121 | +ve bunları `HEZARFEN_NET` / `HEZARFEN_DATA_VOLUME` olarak podcast compose'una | ||
| 122 | +geçirir. | ||
| 123 | + | ||
| 124 | +**Doğrulama** (sonda): `podman ps` + `localhost:8080` + `localhost:5173` HTTP + | ||
| 125 | +podcast loglarında **`kayit basarili`** satırı (30 sn boyunca aranır). Kayıt | ||
| 126 | +görülmezse betik son 40 log satırını basar ve **exit 1** verir. | ||
| 127 | + | ||
| 128 | +Yararlı bayraklar: | ||
| 129 | + | ||
| 130 | +```powershell | ||
| 131 | +pwsh -File deploy/run-stack.ps1 -PodcastOnly # backend/frontend/chatbot zaten ayakta | ||
| 132 | +pwsh -File deploy/run-stack.ps1 -Rebuild # podcast imajini --no-cache build et | ||
| 133 | +pwsh -File deploy/run-stack.ps1 -Root D:\baska # arama kokunu degistir | ||
| 134 | +``` | ||
| 135 | + | ||
| 136 | +### 4. `rollback.ps1` — önceki imaja dön | ||
| 137 | + | ||
| 138 | +Ev şablonu `:local` kullanıyor, her build aynı etiketi eziyor, **geri dönüş yok.** | ||
| 139 | +Biz her build'i `localhost/hezarfen-podcast:<yyyyMMdd-HHmmss>` olarak etiketler | ||
| 140 | +**ve** `:current` işaretini oraya taşırız; compose `:current` kullanır. | ||
| 141 | + | ||
| 142 | +```powershell | ||
| 143 | +pwsh -File deploy/rollback.ps1 -List # etiketler + hangisi :current | ||
| 144 | +pwsh -File deploy/rollback.ps1 # bir onceki etikete don | ||
| 145 | +pwsh -File deploy/rollback.ps1 -Tag 20260831-181530 | ||
| 146 | +``` | ||
| 147 | + | ||
| 148 | +Etiketleri listeleyen **tek satırlık yol** (betik gerekmez): | ||
| 149 | + | ||
| 150 | +```powershell | ||
| 151 | +podman images localhost/hezarfen-podcast --format "{{.Tag}} {{.ID}} {{.CreatedSince}}" | ||
| 152 | +``` | ||
| 153 | + | ||
| 154 | +Geri alma **yeniden build etmez**: `podman tag` + `compose up -d --force-recreate` | ||
| 155 | +(saniyeler). `--force-recreate` şart — etiket adı aynı kaldığı için compose | ||
| 156 | +"değişiklik yok" deyip container'ı bırakabilir. | ||
| 157 | + | ||
| 158 | +--- | ||
| 159 | + | ||
| 160 | +## Betiklerdeki tuzaklar (ölçüldü) | ||
| 161 | + | ||
| 162 | +Bu bölüm `deploy/*.ps1` içinde **koşturarak** bulunmuş, PowerShell 5.1 + | ||
| 163 | +podman 5.8.6 üzerinde ölçülmüş tuzakların **tek kayıtlı yeridir**. Betiklerde | ||
| 164 | +yorum satırı **yoktur**; bilgi burada durur. Bir betiği düzenleyen önce burayı | ||
| 165 | +okumalı — beş maddenin her biri sessiz ya da **ikinci koşuda** ortaya çıkan bir | ||
| 166 | +bozulmadır. | ||
| 167 | + | ||
| 168 | +### 1. `Get-ChildItem -LiteralPath -Recurse -Include` → `-Include` YOK SAYILIR | ||
| 169 | + | ||
| 170 | +**Betik:** `setup-pipeline.ps1`, vendor kopyasından `*.pyc / *.pyo / *.yedek` | ||
| 171 | +artıklarını temizleyen ikinci geçiş. | ||
| 172 | + | ||
| 173 | +**Bozuk satır yapısı:** | ||
| 174 | + | ||
| 175 | +```powershell | ||
| 176 | +Get-ChildItem -LiteralPath $target -Recurse -Force -Include *.pyc,*.pyo,*.yedek | | ||
| 177 | + ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force } | ||
| 178 | +``` | ||
| 179 | + | ||
| 180 | +**Ne oluyordu (ölçüldü 2026-08-31):** `-LiteralPath` ile `-Recurse` birlikte | ||
| 181 | +kullanıldığında `-Include` **uygulanmaz** ve filtre yokmuş gibi **her dosya** | ||
| 182 | +eşleşir. Bu satır, `vendor/pipeline`a saniyeler önce kopyalanan dosyaların | ||
| 183 | +**tamamını** siliyordu; geriye yalnızca boş dizinler kalıyordu. Hata sessizdi: | ||
| 184 | +betik "TAMAM" yazıp çıkıyor, bozukluk ancak build'de ya da container içinde | ||
| 185 | +`PODCAST_MODE=real` exit 2 verdiğinde görülüyordu. | ||
| 186 | + | ||
| 187 | +**Doğrusu:** uzantı süzmesi `-Include` ile değil, `Where-Object` ile yapılır: | ||
| 188 | + | ||
| 189 | +```powershell | ||
| 190 | +Get-ChildItem -LiteralPath $target -Recurse -Force -File | | ||
| 191 | + Where-Object { $_.Extension -in @(".pyc", ".pyo", ".yedek") } | | ||
| 192 | + ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force } | ||
| 193 | +``` | ||
| 194 | + | ||
| 195 | +### 2. `podman machine start` zaten çalışıyorsa stderr'e yazar → betiği ÖLDÜRÜR | ||
| 196 | + | ||
| 197 | +**Betikler:** `setup-models.ps1` ve `run-stack.ps1` — podman machine'i garantiye | ||
| 198 | +alan satır. | ||
| 199 | + | ||
| 200 | +**Bozuk satır yapısı:** | ||
| 201 | + | ||
| 202 | +```powershell | ||
| 203 | +$ErrorActionPreference = "Stop" | ||
| 204 | +... | ||
| 205 | +& $PODMAN machine start *> $null # 'zararsiz' sanilan satir | ||
| 206 | +``` | ||
| 207 | + | ||
| 208 | +**Ne oluyordu (ölçüldü 2026-09-01):** PowerShell 5.1'de bir **native** komutun | ||
| 209 | +stderr'i yönlendirildiğinde **her satır** bir `NativeCommandError` kaydına | ||
| 210 | +sarılır; `$ErrorActionPreference = 'Stop'` altında bu kayıt terminating sayılır | ||
| 211 | +ve betiği düşürür — komutun **çıkış kodu 0 olsa bile**. `podman machine start` | ||
| 212 | +makine **zaten çalışıyorsa** mesajını stderr'e yazar. Yani satır ilk koşuda | ||
| 213 | +geçiyor, **ikinci koşuda** betiği öldürüyordu. | ||
| 214 | + | ||
| 215 | +**Yönlendirme biçimi fark etmez:** `*> $null 2>&1`, `*> $null` ve `2>$null` | ||
| 216 | +üçü de ölçüldü, **üçü de** düşürdü. Aynı kusur ev şablonundaki (chatbot) | ||
| 217 | +betikte de vardır. | ||
| 218 | + | ||
| 219 | +**Doğrusu:** çağrının etrafında `$ErrorActionPreference` geçici olarak | ||
| 220 | +`'Continue'`ya alınır, sonra geri konur: | ||
| 221 | + | ||
| 222 | +```powershell | ||
| 223 | +$previousEAP = $ErrorActionPreference | ||
| 224 | +$ErrorActionPreference = 'Continue' | ||
| 225 | +& $PODMAN machine start *> $null | ||
| 226 | +$ErrorActionPreference = $previousEAP | ||
| 227 | +``` | ||
| 228 | + | ||
| 229 | +### 3. `podman volume create` zaten varsa aynı şekilde öldürüyordu | ||
| 230 | + | ||
| 231 | +**Betik:** `setup-models.ps1`, `podcast-models` hacmini garantiye alan satır. | ||
| 232 | + | ||
| 233 | +Mekanizma **2 ile birebir aynıdır**: `podman volume create <var-olan-hacim>` | ||
| 234 | +"already exists" mesajını **stderr'e** yazar, çıkış kodu 0 olsa da | ||
| 235 | +`NativeCommandError` üretir ve `Stop` altında betiği düşürür. Yine **ilk koşuda | ||
| 236 | +sorun yok, ikinci koşuda betik ölüyordu** — hacim zaten yaratılmış olduğu için. | ||
| 237 | + | ||
| 238 | +Aynı sınıf `podman rm -f <olmayan-container>` ve | ||
| 239 | +`podman exec ... test -e <olmayan-yol>` çağrılarında da geçerlidir; ikisi de | ||
| 240 | +**bilerek** başarısız olabilen ve stderr'e yazan çağrılardır. | ||
| 241 | + | ||
| 242 | +### `Invoke-Quiet` yardımcısı NEDEN var | ||
| 243 | + | ||
| 244 | +2 ve 3 numaralı tuzakların ortak çözümü. `setup-models.ps1`, `run-stack.ps1` ve | ||
| 245 | +`rollback.ps1` içinde **aynen tekrarlanır**: | ||
| 246 | + | ||
| 247 | +```powershell | ||
| 248 | +function Invoke-Quiet { | ||
| 249 | + param([Parameter(Mandatory)][string]$Command, [string[]]$Arg = @()) | ||
| 250 | + $previousEAP = $ErrorActionPreference | ||
| 251 | + $ErrorActionPreference = 'Continue' | ||
| 252 | + try { & $Command @Arg *> $null } finally { $ErrorActionPreference = $previousEAP } | ||
| 253 | + return $LASTEXITCODE | ||
| 254 | +} | ||
| 255 | +``` | ||
| 256 | + | ||
| 257 | +Görevi tek cümleyle: **çıktısı bastırılacak her native çağrıyı, | ||
| 258 | +`$ErrorActionPreference='Stop'`u geçici olarak devre dışı bırakarak koşturmak; | ||
| 259 | +hata fırlatmak yerine ÇIKIŞ KODUNU döndürmek.** Başarı/başarısızlık kararı | ||
| 260 | +çağıran tarafta `$LASTEXITCODE` ile verilir. `finally` şart: çağrı fırlatsa | ||
| 261 | +bile eski `$ErrorActionPreference` geri konur. Bastırılması gereken **her** | ||
| 262 | +podman çağrısı bundan geçmelidir; doğrudan yazılan bir | ||
| 263 | +`& $PODMAN ... *> $null` satırı 2/3 numaralı tuzağa geri döner. | ||
| 264 | + | ||
| 265 | +### 4. `Sort-Object -Unique` tek eleman kaldığında SKALER döner → yol tek karaktere iner | ||
| 266 | + | ||
| 267 | +**Betik:** `run-stack.ps1`, `Find-Repo` fonksiyonu (repoları `compose.yaml` | ||
| 268 | +**içeriğinden** bulan tarama). | ||
| 269 | + | ||
| 270 | +**Bozuk satır yapısı:** | ||
| 271 | + | ||
| 272 | +```powershell | ||
| 273 | +$found = $found | Sort-Object -Unique # @() ile sarilmamis | ||
| 274 | +... | ||
| 275 | +Push-Location $found[0] | ||
| 276 | +``` | ||
| 277 | + | ||
| 278 | +**Ne oluyordu (ölçüldü 2026-09-01):** PowerShell tek elemanlı bir sonucu | ||
| 279 | +**diziden çıkarır**; `Sort-Object -Unique` geriye dizi değil **skaler string** | ||
| 280 | +döndürür. Tam da beklenen durumda — her repo için **bir** aday bulunduğunda — | ||
| 281 | +`$found[0]` artık ilk elemanı değil, string'in **ilk karakterini** verir: | ||
| 282 | +`"C:\PROJECTS\podcast\backend\hezarfen_backend-main"` → `"C"`. Ardından | ||
| 283 | +`Push-Location "C"` patlıyordu ve hata mesajı asıl sebebi hiç göstermiyordu. | ||
| 284 | +Aynı sebeple `$found.Count` de 1 yerine **string uzunluğunu** verir. | ||
| 285 | + | ||
| 286 | +**Doğrusu:** sonuç `@()` ile diziye zorlanır: | ||
| 287 | + | ||
| 288 | +```powershell | ||
| 289 | +$found = @($found | Sort-Object -Unique) | ||
| 290 | +``` | ||
| 291 | + | ||
| 292 | +Aynı korunma `run-stack.ps1`'deki base-imaj pre-pull listesinde de gerekir: | ||
| 293 | +`$bases | Sort-Object -Unique` bir `foreach` içinde tüketildiği için orada | ||
| 294 | +zararsızdır, ama indekslenirse aynı tuzağa düşer. | ||
| 295 | + | ||
| 296 | +### 5. Go şablonundaki gömülü çift tırnak PowerShell 5.1'de bozulur | ||
| 297 | + | ||
| 298 | +**Betikler:** `run-stack.ps1` ve `rollback.ps1` — backend'in `/data` hacminin | ||
| 299 | +**gerçek adını** okuyan satır. | ||
| 300 | + | ||
| 301 | +**Bozuk satır yapısı:** | ||
| 302 | + | ||
| 303 | +```powershell | ||
| 304 | +podman inspect hezarfen-backend --format '{{range .Mounts}}{{if eq .Destination "/data"}}{{.Name}}{{end}}{{end}}' | ||
| 305 | +``` | ||
| 306 | + | ||
| 307 | +**Ne oluyordu (ölçüldü 2026-09-01):** PowerShell 5.1, native bir komuta | ||
| 308 | +geçirilen argümanın **içindeki** çift tırnakları bozar. Go şablonundaki | ||
| 309 | +`eq .Destination "/data"` podman'a bozulmuş halde ulaşır ve podman şunu verir: | ||
| 310 | + | ||
| 311 | +``` | ||
| 312 | +Error: template: unexpected "/" in operand | ||
| 313 | +``` | ||
| 314 | + | ||
| 315 | +Hacim adı okunamaz, `$env:HEZARFEN_DATA_VOLUME` boş kalır, compose varsayılana | ||
| 316 | +düşer ve yanlış hacim adıyla `volume ... not found` alınır — sebebi hiç | ||
| 317 | +görünmeden. | ||
| 318 | + | ||
| 319 | +**Doğrusu:** şablonda **dize sabiti kullanma**. JSON alınır, ayrıştırma | ||
| 320 | +PowerShell tarafında yapılır: | ||
| 321 | + | ||
| 322 | +```powershell | ||
| 323 | +$raw = & $PODMAN inspect hezarfen-backend --format json 2>$null | ||
| 324 | +$mounts = @() | ||
| 325 | +if ($raw) { try { $mounts = ($raw | ConvertFrom-Json)[0].Mounts } catch { $mounts = @() } } | ||
| 326 | +$volume = ($mounts | Where-Object { $_.Destination -eq '/data' } | | ||
| 327 | + Select-Object -First 1 -ExpandProperty Name -ErrorAction SilentlyContinue) | ||
| 328 | +``` | ||
| 329 | + | ||
| 330 | +Ağ adını okuyan şablon | ||
| 331 | +(`{{range $k, $v := .NetworkSettings.Networks}}{{$k}} {{end}}`) **dize sabiti | ||
| 332 | +içermediği için** güvenlidir ve olduğu gibi kullanılabilir. | ||
| 333 | + | ||
| 334 | +--- | ||
| 335 | + | ||
| 336 | +### Betiklerde ayrıca ölçülmüş, kaybolmaması gereken kararlar | ||
| 337 | + | ||
| 338 | +* **`Copy-Item -Recurse -Exclude` birlikte ÇALIŞMAZ** (`setup-pipeline.ps1`). | ||
| 339 | + İkisi bir arada verildiğinde PowerShell dizin **ağacını kurar ama dosyaları | ||
| 340 | + kopyalamaz**; `vendor/pipeline` boş dizinlerle dolu kalır ve build sessizce | ||
| 341 | + bozuk imaj üretir. Bu yüzden kopyalama **süzmesiz** yapılır, süzme ikinci | ||
| 342 | + geçişe bırakılır (bkz. tuzak 1). | ||
| 343 | +* **`Copy-Item -Exclude` yalnızca EN ÜST seviyede süzer.** Alt ağaçlardaki | ||
| 344 | + `__pycache__` / `*.pyc` kalır; ikinci geçiş bunları temizler | ||
| 345 | + (**ölçüldü: ~40 dizin**). | ||
| 346 | +* **Bağımlılık kapısı** (`setup-pipeline.ps1` sonunda | ||
| 347 | + `tools/dependency_scanner.py` çağrısı — **ölçüldü 2026-08-31**): hattın | ||
| 348 | + `requirements*.txt` dosyaları `rapidfuzz`i **hiç listelemiyordu**; | ||
| 349 | + container'da `ingest` geçti ve `script` adımında | ||
| 350 | + `No module named 'rapidfuzz'` ile düştü. Aynı sınıf daha önce `transformers` | ||
| 351 | + için de yaşandı. Tarayıcı, kodun import ettiği ama **beyan edilmeyen** | ||
| 352 | + paketleri vendor **anında** yakalar — 20 dakikalık build'den sonra değil. | ||
| 353 | + Çıkış kodu 0 değilse betik `throw` eder. | ||
| 354 | +* **Hacim VARLIĞI değil İÇERİĞİ denetlenir** (`run-stack.ps1`, denetimde | ||
| 355 | + bulundu). `podman volume exists podcast-models` yalnızca hacmin **var | ||
| 356 | + olduğunu** sorar; `setup-models.ps1` ise hacmi kopyalamadan **önce** yaratır. | ||
| 357 | + Ağırlıklar eksik kalırsa geriye **var ama boş** bir hacim kalır ve bu kapı | ||
| 358 | + sessizce geçerdi — hata 20 dakikalık build'den sonra TTS'te patlardı. Bu | ||
| 359 | + yüzden imza dosyası denetlenir: | ||
| 360 | + `/models/ses_modelleri/supertonic-3/onnx/vocoder.onnx`. | ||
| 361 | +* **Sürüm etiketi yalnızca imaj GERÇEKTEN değiştiyse açılır** | ||
| 362 | + (`run-stack.ps1`). Build önce `:current` olarak yapılır, sonra imaj kimliği | ||
| 363 | + build öncesiyle karşılaştırılır. Gerekçe: build zaten katman önbelleklidir, | ||
| 364 | + ama her koşuda koşulsuz yeni bir zaman damgası üretmek etiket listesini | ||
| 365 | + şişirir ve `rollback.ps1`i aynı içeriğe işaret eden anlamsız "sürümlerle" | ||
| 366 | + doldurur — geri alacak bir şey yokken varmış gibi görünürdü. | ||
| 367 | +* **`--force-recreate` ve `--no-build` şart** (`rollback.ps1`). | ||
| 368 | + `--force-recreate` olmazsa: imaj ID değişti ama **etiket adı aynı kaldığı** | ||
| 369 | + için compose "değişiklik yok" deyip container'ı bırakabilir. `--no-build` | ||
| 370 | + olmazsa: `compose.yaml`da `build:` bloğu vardır ve yeniden build eden bir | ||
| 371 | + podman-compose sürümü `:current`i **yeni** imajla ezip geri almayı **iptal** | ||
| 372 | + ederdi. | ||
| 373 | +* **`podman cp` için `run -d ... sleep`, `create` DEĞİL** (`setup-models.ps1`). | ||
| 374 | + `podman cp` **duran** bir container'ın hacim bağlı yollarına yazdığında | ||
| 375 | + podman sürümüne göre ya hacme ya da rootfs'e yazar; ikincisi **sessizce | ||
| 376 | + kaybolur**. Koşan container'da bağlama noktası gerçektir, yazma kesin hacme | ||
| 377 | + gider. Yardımcı imaj build sırasında zaten çekildiği için **ağ gerektirmez**. | ||
| 378 | +* **Base imaj pre-pull** (`run-stack.ps1`): docker.io anonim-pull dalgalanması | ||
| 379 | + build **ortasında** `unauthorized` verir; önce çekmek o hatayı build'den | ||
| 380 | + **önce** ve tek başına görünür kılar. | ||
| 381 | +* **`restart: unless-stopped` tek başına YETMEZ.** Makine yeniden başladıktan | ||
| 382 | + sonra konteynerleri geri getiren `podman-restart.service` birimidir ve o | ||
| 383 | + **varsayılan olarak devre dışıdır**; ayrıntı ve tek seferlik kurulum için | ||
| 384 | + aşağıdaki *SUNUCU YENİDEN BAŞLADIĞINDA* bölümüne bakın. | ||
| 385 | + | ||
| 386 | +--- | ||
| 387 | + | ||
| 388 | +## Hacimler | ||
| 389 | + | ||
| 390 | +| Hacim | Bağlantı | Mod | Ne tutar | | ||
| 391 | +|---|---|---|---| | ||
| 392 | +| `hezarfen-data` (**external**) | `/data/files` | **:ro** | Backend'in PDF blob deposu. `PODCAST_MEDIA_ROOT`. Servis **yalnızca okur**. | | ||
| 393 | +| `podcast-out` | `/data/podcast/out` | rw | Üretilen mp3 / script / quiz. `PODCAST_OUTPUT_ROOT`. | | ||
| 394 | +| `podcast-jobs` | `/data/podcast/jobs` | rw | İş durumu (JSON/iş) + köprü durum dosyası. | | ||
| 395 | +| `podcast-kayit` | `/data/podcast/kayit` | rw | `router.sqlite` — adım önbelleği, resume, LLM bütçesi. | | ||
| 396 | +| `podcast-models` | `/models` | **:ro** | ~3,9 GB ağırlık. | | ||
| 397 | +| `podcast-easyocr` | `/home/podcast/.EasyOCR` | rw | easyocr'ın kendi indirdiği tanıma modelleri. | | ||
| 398 | + | ||
| 399 | +`hezarfen-data` **external**'dır: backend yaratır, biz sadece bağlanırız. | ||
| 400 | +Adı yanlışsa compose **ayağa kalkmaz**. | ||
| 401 | + | ||
| 402 | +> **OPERATÖR DOĞRULAMALI.** Bu makinede podman **kurulu değil**, dolayısıyla | ||
| 403 | +> hacmin gerçek adı **çalışan bir sistemde doğrulanamadı**. Varsayılan | ||
| 404 | +> `hezarfen_backend_hezarfen-data`, `run-stack.ps1`in backend'i | ||
| 405 | +> `-p hezarfen_backend` ile kaldırdığı varsayımına dayanır. Elle | ||
| 406 | +> `podman compose up` yapıyorsan **önce doğrula**: | ||
| 407 | +> ```powershell | ||
| 408 | +> podman volume ls ; podman network ls | ||
| 409 | +> $env:HEZARFEN_DATA_VOLUME = "<gercek-ad>" | ||
| 410 | +> $env:HEZARFEN_NET = "<gercek-ag>" | ||
| 411 | +> ``` | ||
| 412 | + | ||
| 413 | +--- | ||
| 414 | + | ||
| 415 | +## Sağlık kontrolü | ||
| 416 | + | ||
| 417 | +Podman'ın OCI biçimi **imajdaki `HEALTHCHECK`'i yok sayar**; bu yüzden sağlık | ||
| 418 | +`compose.yaml`dadır, `Containerfile`da değil. | ||
| 419 | + | ||
| 420 | +```yaml | ||
| 421 | +healthcheck: | ||
| 422 | + test: ["CMD", "python", "-m", "src.main", "--health"] | ||
| 423 | + interval: 30s | ||
| 424 | + timeout: 10s | ||
| 425 | + retries: 3 | ||
| 426 | + start_period: 90s | ||
| 427 | +``` | ||
| 428 | + | ||
| 429 | +`--health` **ağ çağrısı yapmaz**. Denetlediği: iş kökü ve çıktı kökü | ||
| 430 | +yazılabilir mi · `real` modda hat **içeri alınabiliyor mu** (`import router.hat` | ||
| 431 | +— ölçüldü: **0,12 sn**) · köprü backend'e **kayıtlı mı**. Toplam ölçüm: | ||
| 432 | +**0,66 sn** (10 sn'lik timeout'un çok altında). | ||
| 433 | + | ||
| 434 | +Kayıt durumu iş kökündeki `.bridge-status` dosyasından okunur; köprü onu `jobs.py` | ||
| 435 | +ile aynı **atomik** desenle (geçici dosya + `os.replace`) yazar: kayıt başarılı | ||
| 436 | +olunca `registered=true`, bağlantı koptuğunda `false`. Dosya `*.json` desenine | ||
| 437 | +uymadığı için iş taramasına karışmaz. | ||
| 438 | + | ||
| 439 | +**Bayatlık denetimi bilerek YOK**: sağlıklı ve uzun süren bir bağlantı saatlerce | ||
| 440 | +hiçbir şey yazmaz; zaman aşımı koymak sağlıklı köprüyü hasta gösterirdi. | ||
| 441 | + | ||
| 442 | +`start_period: 90s` **ölçülmedi**, model yükleme süresine göre seçilmiş bir | ||
| 443 | +tahmindir; ilk gerçek koşudan sonra ayarlanmalıdır. | ||
| 444 | + | ||
| 445 | +Elle: `podman exec hezarfen-podcast-bridge python -m src.main --health` | ||
| 446 | +(çıkış `0` sağlıklı, `1` sağlıksız). `--health` **asla 2 dönmez** — 2 yalnızca `--validate`'e aittir. | ||
| 447 | + | ||
| 448 | +--- | ||
| 449 | + | ||
| 450 | +## Sorun giderme | ||
| 451 | + | ||
| 452 | +| Belirti | Neden / Çözüm | | ||
| 453 | +|---|---| | ||
| 454 | +| `network hezarfen_backend_default not found` | Backend `-p hezarfen_backend` ile kaldırılmadı ya da hiç ayakta değil. `podman network ls` ile gerçek adı bul, `$env:HEZARFEN_NET`'e yaz. | | ||
| 455 | +| `volume ... hezarfen-data not found` | Aynı sebep, hacim tarafı. `podman volume ls`. | | ||
| 456 | +| build: `COPY vendor/pipeline: no such file` | `deploy/setup-pipeline.ps1` çalıştırılmadı. | | ||
| 457 | +| Boot'ta `exit 2` + `PODCAST_MODE=real ama gercek hat yuklenemedi` | vendor eksik kopyalandı ya da hattın bir bağımlılığı imajda yok. `podman run --rm localhost/hezarfen-podcast:current python -c "import router.hat"` ile tek başına dene. | | ||
| 458 | +| `ffmpeg/ffprobe bulunamadi: /app/pipeline/tools/bin/ffmpeg.exe` | Sembolik bağ yok. `podman exec ... ls -l /app/pipeline/tools/bin/`. Vendor `tools/bin` ile kopyalandıysa gerçek `.exe`ler bağın üstüne yazılmıştır → `setup-pipeline.ps1`i `-WindowsBinaries` **olmadan** koştur. | | ||
| 459 | +| TTS: `model dizini yok` / `vocoder.onnx` | `podcast-models` hacmi boş ya da izinler kapalı. `pwsh -File deploy/setup-models.ps1 -Check` | | ||
| 460 | +| `OSError: ... multilingual-e5-large ... offline` | Ağırlık hacimde yok. `HF_HUB_OFFLINE=1` **bilerek** indirmeyi engelliyor. `setup-models.ps1` koştur; ya da geçici olarak `HF_HUB_OFFLINE=0`. | | ||
| 461 | +| ASR `cuda` hatası | Yok — `ses/dogrula.py:352` CUDA yoksa **`cpu/int8`e düşer** ve bunu raporlar. Container'da beklenen davranış budur, hata değil. | | ||
| 462 | +| Konteyner `unhealthy` ama loglar temiz | `podman logs` içinde `kayit basarili` yoksa köprü backend'e bağlanamıyor: token uyuşmuyor ya da backend ayakta değil. | | ||
| 463 | +| `EACCES` — `/data/podcast/...` | Hacim root sahipliğinde oluşmuş. `podman volume rm podcast-jobs` (durum kaybolur) veya `podman unshare chown -R 10001:10001 ...`. | | ||
| 464 | +| İmaj build'i 20 dk sürüyor | Normal: torch + easyocr. `KUR_AGIR=0` ile ~2 GB ve dakikalar kısalır (OCR, e5 gömme ve VITS yedek motoru kapanır). | | ||
| 465 | +| `unable to retrieve auth token ... unauthorized` | docker.io anonim-pull dalgalanması. `run-stack.ps1` pre-pull yapar; tekrar koştur. | | ||
| 466 | + | ||
| 467 | +--- | ||
| 468 | + | ||
| 469 | +## Durdurma / temizlik | ||
| 470 | + | ||
| 471 | +```powershell | ||
| 472 | +cd C:\PROJECTS\podcast\hezarfen_podcast_service ; podman compose down | ||
| 473 | +podman compose down -v # podcast-jobs / out / kayit / models de SILINIR | ||
| 474 | +``` | ||
| 475 | + | ||
| 476 | +Diğer repolar kendi dizinlerinde (`podman compose down`); backend | ||
| 477 | +`-p hezarfen_backend` ile kaldırıldıysa `podman compose -p hezarfen_backend down`. | ||
| 478 | + | ||
| 479 | +--- | ||
| 480 | + | ||
| 481 | +### Token neden `.env` dosyasında olmalı, ortam değişkeninde değil | ||
| 482 | + | ||
| 483 | +`compose.yaml` `${AI_SHARED_TOKEN:?}` kullanıyor ve compose dosyayı **her | ||
| 484 | +komutta** interpolate eder — `up` kadar `down`, `ps`, `logs` da. Token yalnızca | ||
| 485 | +kabuk değişkenindeyse, kabuğu kapatıp yeni bir terminal açan operatör yığıtı | ||
| 486 | +**indiremez**: | ||
| 487 | + | ||
| 488 | +``` | ||
| 489 | +error while interpolating services.bridge.environment.AI_SHARED_TOKEN: | ||
| 490 | +required variable AI_SHARED_TOKEN is missing a value | ||
| 491 | +``` | ||
| 492 | + | ||
| 493 | +Bu ölçüldü (2026-09-01, Podman 5.8.6). `.env` dosyası compose tarafından | ||
| 494 | +kendiliğinden okunur ve sorunu tamamen kapatır; `.env` `.gitignore`'dadır. | ||
| 495 | +`deploy/rollback.ps1` ayrıca kendi kapısını koşar ve eksikse açık hata verir. | ||
| 496 | + | ||
| 497 | +## SUNUCU YENİDEN BAŞLADIĞINDA — tek seferlik zorunlu ayar | ||
| 498 | + | ||
| 499 | +**Ölçüldü (2026-09-04):** makine yeniden başladıktan sonra beş konteynerin | ||
| 500 | +**hiçbiri geri gelmedi**, `restart: unless-stopped` yazılı olmasına rağmen. | ||
| 501 | + | ||
| 502 | +Sebep: Podman **daemonsuz**. Restart politikası yalnızca podman süreci/makinesi | ||
| 503 | +ayaktayken geçerlidir; açılışta konteyner geri getirmek `podman-restart.service` | ||
| 504 | +biriminin işi ve o **varsayılan olarak devre dışı**. | ||
| 505 | + | ||
| 506 | +```bash | ||
| 507 | +podman machine ssh | ||
| 508 | +sudo chown -R $(id -u):$(id -g) ~/.config/systemd # dizin root sahipliginde gelir | ||
| 509 | +export XDG_RUNTIME_DIR=/run/user/$(id -u) | ||
| 510 | +systemctl --user enable podman-restart.service | ||
| 511 | +loginctl show-user $(whoami) --property=Linger # Linger=yes olmali | ||
| 512 | +``` | ||
| 513 | + | ||
| 514 | +`chown` satırı şart: makine imajında `~/.config/systemd/user` **root** | ||
| 515 | +sahipliğinde geliyor ve `systemctl --user enable` `Access denied` veriyor. | ||
| 516 | + | ||
| 517 | +Doğrulama: `podman machine stop && podman machine start`, 30 saniye sonra beş | ||
| 518 | +konteyner de `Up` olmalı. Ölçülen kurtarma süresi **~30 sn**. | ||
| 519 | + | ||
| 520 | +Not: birim `--filter should-start-on-boot=true` kullanıyor ve bu filtre | ||
| 521 | +`unless-stopped`'ı **kapsıyor** (ölçüldü); açıklama satırındaki "Restart Policy | ||
| 522 | +Set To Always" ifadesi yanıltıcıdır. | ||
| 523 | + | ||
| 524 | +### Yeniden başlatma sertifikayı DEĞİŞTİRİR | ||
| 525 | + | ||
| 526 | +Backend her açılışta yeni self-signed sertifika üretir — ölçüldü: | ||
| 527 | +`f1555574d670` → `9120c487eeef`. Köprü sertifikayı **her yeniden bağlanmada | ||
| 528 | +yeniden çeker** (`bridge.py`, `run_once` içinde); önbelleğe alınsaydı servis | ||
| 529 | +backend restart'ından sonra bir daha bağlanamaz, sessizce ölürdü. | ||
| 530 | + | ||
| 531 | +## Bu katmanda BİLEREK yapılmayanlar | ||
| 532 | + | ||
| 533 | +* **Betiklerden yalnızca `setup-pipeline.ps1` çalıştırıldı** (yerel, podman | ||
| 534 | + gerektirmez): 76 dosya / 1,49 MB, ve vendor kopyasından `router.hat`'in | ||
| 535 | + import edildiği doğrulandı. Podman bu makinede kurulu olmadığı için ağ adı, | ||
| 536 | + hacim adı, imaj boyutu ve build süresi **ölçülmedi**. | ||
| 537 | +* **`mem_limit: 8g` / `cpus: 4.0` ölçülmedi.** Ölçülen tek şey ağırlıkların | ||
| 538 | + disk boyutudur (~3,9 GB); RSS değil. İlk gerçek koşudan sonra ayarlanmalı. | ||
| 539 | +* ~~Taban imaj digest'e pinlenmedi~~ - **kapandi**, `@sha256:4101e4a3...`. | ||
| 540 | +* ~~`podcast-out`/`podcast-jobs` temizlenmiyor~~ - **kapandi**, | ||
| 541 | + `PODCAST_RETENTION_DAYS` (compose'ta `30`, kod varsayilani `0`). | ||
| 542 | +* **easyocr ağırlıkları imajda yok**; ilk taranmış PDF'te kendi indirir | ||
| 543 | + (`podcast-easyocr` hacmine, kalıcı). Ağ gerekir. | ||
| 544 | +* **`torch` / `transformers` / `easyocr` tek bir ARG'a bağlıdır: `KUR_AGIR` | ||
| 545 | + (varsayılan `1`).** `transformers` hattın **hiçbir `requirements*.txt`inde | ||
| 546 | + yazılı değil** — `requirements-ses.txt` onu (ve `onnxruntime`, `numpy`, | ||
| 547 | + `huggingface_hub`'ı) "zaten kurulu" varsayıyor; bu boşluk Containerfile'da | ||
| 548 | + açık pin'lerle kapatıldı (`transformers==5.15.0`, `onnxruntime==1.23.2`, | ||
| 549 | + `numpy==2.2.6`, `huggingface_hub==1.27.0` — yereldeki ölçülen sürümler). | ||
| 550 | + `torch` **sürüm pinlenmedi**: CPU tekerlek indeksinde py3.10 için hangi | ||
| 551 | + sürümün duracağı doğrulanamadı, bu yüzden çözücüye bırakıldı. | ||
| 552 | + `KUR_AGIR=0` ile OCR, e5 gömme ve VITS yedek motoru kapanır. | ||
deploy/rollback.ps1added+104 -0
| @@ -0,0 +1,104 @@ | |||
| 1 | +[CmdletBinding()] | ||
| 2 | +param( | ||
| 3 | + [string]$Image = "localhost/hezarfen-podcast", | ||
| 4 | + [string]$Tag, | ||
| 5 | + [switch]$List | ||
| 6 | +) | ||
| 7 | +$ErrorActionPreference = "Stop" | ||
| 8 | + | ||
| 9 | +function Invoke-Quiet { | ||
| 10 | + param([Parameter(Mandatory)][string]$Command, [string[]]$Arg = @()) | ||
| 11 | + $previousEAP = $ErrorActionPreference | ||
| 12 | + $ErrorActionPreference = 'Continue' | ||
| 13 | + try { & $Command @Arg *> $null } finally { $ErrorActionPreference = $previousEAP } | ||
| 14 | + return $LASTEXITCODE | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +function Find-Podman { | ||
| 19 | + $c = (Get-Command podman -ErrorAction SilentlyContinue).Source | ||
| 20 | + if ($c) { return $c } | ||
| 21 | + foreach ($p in @("$env:LOCALAPPDATA\Programs\Podman\podman.exe", | ||
| 22 | + "$env:ProgramFiles\RedHat\Podman\podman.exe")) { | ||
| 23 | + if (Test-Path $p) { return $p } | ||
| 24 | + } | ||
| 25 | + throw "podman.exe bulunamadi." | ||
| 26 | +} | ||
| 27 | +$PODMAN = Find-Podman | ||
| 28 | +$podcast = Split-Path -Parent $PSScriptRoot | ||
| 29 | + | ||
| 30 | +$lines = & $PODMAN images $Image --format "{{.Tag}}`t{{.ID}}`t{{.CreatedSince}}" 2>$null | ||
| 31 | +if (-not $lines) { throw "Hic '$Image' imaji yok. Once: pwsh -File deploy/run-stack.ps1" } | ||
| 32 | + | ||
| 33 | +$records = @() | ||
| 34 | +foreach ($s in $lines) { | ||
| 35 | + $p = $s -split "`t" | ||
| 36 | + if ($p.Count -ge 2) { | ||
| 37 | + $records += [pscustomobject]@{ Tag = $p[0]; Id = $p[1]; Age = $p[2] } | ||
| 38 | + } | ||
| 39 | +} | ||
| 40 | +$currentId = ($records | Where-Object { $_.Tag -eq "current" } | Select-Object -First 1).Id | ||
| 41 | +$versions = $records | Where-Object { $_.Tag -match '^\d{8}-\d{6}$' } | | ||
| 42 | + Sort-Object Tag -Descending | ||
| 43 | + | ||
| 44 | +if ($List -or -not $versions) { | ||
| 45 | + Write-Host "`n$Image etiketleri (yeni -> eski):" | ||
| 46 | + foreach ($k in $versions) { | ||
| 47 | + $marker = if ($k.Id -eq $currentId) { " <- :current" } else { "" } | ||
| 48 | + Write-Host (" {0} {1} {2}{3}" -f $k.Tag, $k.Id, $k.Age, $marker) | ||
| 49 | + } | ||
| 50 | + if (-not $versions) { Write-Host " (zaman damgali etiket yok - run-stack.ps1 ile build edilmemis)" } | ||
| 51 | + if ($List) { return } | ||
| 52 | + throw "Donulecek etiket yok." | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +if ($Tag) { | ||
| 56 | + $target = $versions | Where-Object { $_.Tag -eq $Tag } | Select-Object -First 1 | ||
| 57 | + if (-not $target) { throw "Boyle bir etiket yok: $Tag (-List ile bak)" } | ||
| 58 | +} else { | ||
| 59 | + $index = 0 | ||
| 60 | + for ($i = 0; $i -lt $versions.Count; $i++) { | ||
| 61 | + if ($versions[$i].Id -eq $currentId) { $index = $i; break } | ||
| 62 | + } | ||
| 63 | + if ($index + 1 -ge $versions.Count) { | ||
| 64 | + throw "Bir onceki surum yok (yalnizca $($versions.Count) etiket var). -List ile bak." | ||
| 65 | + } | ||
| 66 | + $target = $versions[$index + 1] | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +Write-Host "[rollback] :current $currentId -> $($target.Tag) ($($target.Id), $($target.Age))" | ||
| 70 | +& $PODMAN tag "$($Image):$($target.Tag)" "$($Image):current" | ||
| 71 | +if ($LASTEXITCODE -ne 0) { throw "podman tag basarisiz." } | ||
| 72 | + | ||
| 73 | +if (-not $env:AI_SHARED_TOKEN) { | ||
| 74 | + $envFile = Join-Path $podcast ".env" | ||
| 75 | + if (-not (Test-Path -LiteralPath $envFile) -or | ||
| 76 | + -not ((Get-Content -LiteralPath $envFile -Raw) -match '(?m)^\s*AI_SHARED_TOKEN\s*=\s*\S')) { | ||
| 77 | + throw "AI_SHARED_TOKEN yok. `$env:AI_SHARED_TOKEN='...' ver ya da .env doldur (backend ile AYNI deger)." | ||
| 78 | + } | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +$null = Invoke-Quiet $PODMAN @('inspect','hezarfen-backend','--format','{{range $k, $v := .NetworkSettings.Networks}}{{$k}}{{end}}') | ||
| 82 | +if ($LASTEXITCODE -eq 0) { | ||
| 83 | + $network = (& $PODMAN inspect hezarfen-backend --format '{{range $k, $v := .NetworkSettings.Networks}}{{$k}}{{end}}' 2>$null | Select-Object -First 1) | ||
| 84 | + if ($network) { $env:HEZARFEN_NET = $network.Trim() } | ||
| 85 | + $_raw = & $PODMAN inspect hezarfen-backend --format json 2>$null | ||
| 86 | + $_mounts = @() | ||
| 87 | + if ($_raw) { try { $_mounts = ($_raw | ConvertFrom-Json)[0].Mounts } catch { $_mounts = @() } } | ||
| 88 | + $volume = ($_mounts | Where-Object { $_.Destination -eq '/data' } | | ||
| 89 | + Select-Object -First 1 -ExpandProperty Name -ErrorAction SilentlyContinue) | ||
| 90 | + if ($volume) { $env:HEZARFEN_DATA_VOLUME = $volume.Trim() } | ||
| 91 | + Write-Host "[rollback] ag=$env:HEZARFEN_NET hacim=$env:HEZARFEN_DATA_VOLUME" | ||
| 92 | +} else { | ||
| 93 | + Write-Host "[rollback] UYARI: hezarfen-backend calismiyor; compose varsayilan adlari kullanilacak." | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +Push-Location $podcast | ||
| 97 | +try { | ||
| 98 | + & $PODMAN compose up -d --force-recreate --no-build | ||
| 99 | + if ($LASTEXITCODE -ne 0) { throw "compose up basarisiz." } | ||
| 100 | +} finally { Pop-Location } | ||
| 101 | + | ||
| 102 | +Start-Sleep -Seconds 5 | ||
| 103 | +& $PODMAN ps --format "{{.Names}}`t{{.Status}}`t{{.Image}}" | Where-Object { $_ -match "podcast" } | ||
| 104 | +Write-Host "`n[rollback] TAMAM. Ileri almak icin: pwsh -File deploy/rollback.ps1 -Tag <yeni-etiket>" | ||
deploy/run-stack.ps1added+201 -0
| @@ -0,0 +1,201 @@ | |||
| 1 | +[CmdletBinding()] | ||
| 2 | +param( | ||
| 3 | + [string]$Root = "C:\PROJECTS\podcast", | ||
| 4 | + [string]$BackendProject = "hezarfen_backend", | ||
| 5 | + [switch]$Rebuild, | ||
| 6 | + [switch]$PodcastOnly | ||
| 7 | +) | ||
| 8 | +$ErrorActionPreference = "Stop" | ||
| 9 | + | ||
| 10 | +function Invoke-Quiet { | ||
| 11 | + param([Parameter(Mandatory)][string]$Command, [string[]]$Arg = @()) | ||
| 12 | + $previousEAP = $ErrorActionPreference | ||
| 13 | + $ErrorActionPreference = 'Continue' | ||
| 14 | + try { & $Command @Arg *> $null } finally { $ErrorActionPreference = $previousEAP } | ||
| 15 | + return $LASTEXITCODE | ||
| 16 | +} | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +function Find-Podman { | ||
| 20 | + $c = (Get-Command podman -ErrorAction SilentlyContinue).Source | ||
| 21 | + if ($c) { return $c } | ||
| 22 | + foreach ($p in @("$env:LOCALAPPDATA\Programs\Podman\podman.exe", | ||
| 23 | + "$env:ProgramFiles\RedHat\Podman\podman.exe")) { | ||
| 24 | + if (Test-Path $p) { return $p } | ||
| 25 | + } | ||
| 26 | + throw "podman.exe bulunamadi. winget install RedHat.Podman" | ||
| 27 | +} | ||
| 28 | +$PODMAN = Find-Podman | ||
| 29 | +$podcast = Split-Path -Parent $PSScriptRoot | ||
| 30 | +Write-Host "[stack] podman : $PODMAN" | ||
| 31 | +Write-Host "[stack] podcast : $podcast" | ||
| 32 | + | ||
| 33 | +if (-not (Test-Path -LiteralPath $Root)) { throw "Arama koku yok: $Root" } | ||
| 34 | +Write-Host "[stack] repolar araniyor: $Root" | ||
| 35 | +$candidates = Get-ChildItem -LiteralPath $Root -Recurse -Depth 3 -File -Filter "compose.yaml" ` | ||
| 36 | + -ErrorAction SilentlyContinue | | ||
| 37 | + Where-Object { $_.FullName -notmatch '\\(\.venv|node_modules|vendor|out|target)\\' } | ||
| 38 | + | ||
| 39 | +function Find-Repo([string]$signature, [string]$label) { | ||
| 40 | + $found = @() | ||
| 41 | + foreach ($c in $candidates) { | ||
| 42 | + if ($c.DirectoryName -eq $podcast) { continue } | ||
| 43 | + if ((Get-Content -LiteralPath $c.FullName -Raw) -match $signature) { $found += $c.DirectoryName } | ||
| 44 | + } | ||
| 45 | + $found = @($found | Sort-Object -Unique) | ||
| 46 | + if ($found.Count -eq 0) { | ||
| 47 | + throw "$label reposu bulunamadi ($Root altinda '$signature' iceren compose.yaml yok). -Root ile arama kokunu ver." | ||
| 48 | + } | ||
| 49 | + if ($found.Count -gt 1) { | ||
| 50 | + throw "$label icin BIRDEN COK aday bulundu; hangisi oldugu belirsiz:`n " + ($found -join "`n ") | ||
| 51 | + } | ||
| 52 | + Write-Host ("[stack] {0,-9}: {1}" -f $label, $found[0]) | ||
| 53 | + return $found[0] | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +if (-not $PodcastOnly) { | ||
| 57 | + $backend = Find-Repo 'container_name:\s*hezarfen-backend' "backend" | ||
| 58 | + $frontend = Find-Repo 'container_name:\s*hezarfen-frontend' "frontend" | ||
| 59 | + $chatbot = Find-Repo 'container_name:\s*hezarfen-chatbot-bridge' "chatbot" | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +$vendor = Join-Path $podcast "vendor\pipeline\router\hat.py" | ||
| 63 | +if (-not (Test-Path -LiteralPath $vendor)) { | ||
| 64 | + throw "vendor/pipeline yok. Once calistir: pwsh -File deploy/setup-pipeline.ps1" | ||
| 65 | +} | ||
| 66 | +if (-not $env:AI_SHARED_TOKEN) { | ||
| 67 | + $envFile = Join-Path $podcast ".env" | ||
| 68 | + if (-not (Test-Path -LiteralPath $envFile) -or | ||
| 69 | + -not ((Get-Content -LiteralPath $envFile -Raw) -match '(?m)^\s*AI_SHARED_TOKEN\s*=\s*\S')) { | ||
| 70 | + throw "AI_SHARED_TOKEN yok. `$env:AI_SHARED_TOKEN='...' ver ya da .env doldur (backend ile AYNI deger)." | ||
| 71 | + } | ||
| 72 | +} | ||
| 73 | +$probeFile = "/models/ses_modelleri/supertonic-3/onnx/vocoder.onnx" | ||
| 74 | +$null = Invoke-Quiet $PODMAN @('volume','exists','podcast-models') | ||
| 75 | +if ($LASTEXITCODE -ne 0) { | ||
| 76 | + Write-Host "[stack] UYARI: 'podcast-models' hacmi YOK. TTS ve CER kapisi CALISMAZ." | ||
| 77 | + Write-Host " pwsh -File deploy/setup-models.ps1" | ||
| 78 | +} else { | ||
| 79 | + & $PODMAN run --rm -v podcast-models:/models:ro docker.io/library/python:3.10-slim ` | ||
| 80 | + test -e $probeFile | ||
| 81 | + if ($LASTEXITCODE -ne 0) { | ||
| 82 | + Write-Host "[stack] UYARI: 'podcast-models' hacmi var ama BOS/EKSIK gorunuyor." | ||
| 83 | + Write-Host " beklenen: $probeFile" | ||
| 84 | + Write-Host " pwsh -File deploy/setup-models.ps1 -Refresh" | ||
| 85 | + } | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +$previousEAP = $ErrorActionPreference | ||
| 89 | +$ErrorActionPreference = 'Continue' | ||
| 90 | +& $PODMAN machine start *> $null | ||
| 91 | +$ErrorActionPreference = $previousEAP | ||
| 92 | + | ||
| 93 | +if (-not $PodcastOnly) { | ||
| 94 | + Write-Host "`n[stack] 1/5 base imajlar pre-pull..." | ||
| 95 | + $bases = @("docker.io/surrealdb/surrealdb:v3") | ||
| 96 | + foreach ($d in @($backend, $frontend, $chatbot, $podcast)) { | ||
| 97 | + $cf = Join-Path $d "Containerfile" | ||
| 98 | + if (Test-Path -LiteralPath $cf) { | ||
| 99 | + Select-String -LiteralPath $cf -Pattern '^\s*FROM\s+(\S+)' | ForEach-Object { | ||
| 100 | + $bases += $_.Matches[0].Groups[1].Value | ||
| 101 | + } | ||
| 102 | + } | ||
| 103 | + } | ||
| 104 | + foreach ($img in ($bases | Where-Object { $_ -notmatch '^\$' } | Sort-Object -Unique)) { | ||
| 105 | + Write-Host " pull $img"; Invoke-Quiet $PODMAN @('pull',$img) | Out-Null | ||
| 106 | + } | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +function Compose-Up([string]$dir, [string[]]$preArgs) { | ||
| 110 | + Push-Location $dir | ||
| 111 | + try { | ||
| 112 | + & $PODMAN compose @preArgs up -d --build | ||
| 113 | + if ($LASTEXITCODE -ne 0) { throw "compose up basarisiz: $dir" } | ||
| 114 | + } finally { Pop-Location } | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +if (-not $PodcastOnly) { | ||
| 118 | + Write-Host "`n[stack] 2/5 backend (-p $BackendProject ; Rust ilk seferde uzun surer)..." | ||
| 119 | + Compose-Up $backend @("-p", $BackendProject) | ||
| 120 | + Write-Host "`n[stack] 3/5 frontend..." | ||
| 121 | + Compose-Up $frontend @() | ||
| 122 | + Write-Host "`n[stack] 4/5 chatbot..." | ||
| 123 | + Compose-Up $chatbot @() | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +$net = (& $PODMAN inspect hezarfen-backend --format '{{range $k, $v := .NetworkSettings.Networks}}{{$k}} {{end}}' 2>$null) | ||
| 127 | +$net = ($net -split '\s+' | Where-Object { $_ }) | Select-Object -First 1 | ||
| 128 | +$_raw = & $PODMAN inspect hezarfen-backend --format json 2>$null | ||
| 129 | +$_mounts = @() | ||
| 130 | +if ($_raw) { try { $_mounts = ($_raw | ConvertFrom-Json)[0].Mounts } catch { $_mounts = @() } } | ||
| 131 | +$vol = ($_mounts | Where-Object { $_.Destination -eq '/data' } | | ||
| 132 | + Select-Object -First 1 -ExpandProperty Name -ErrorAction SilentlyContinue) | ||
| 133 | +$vol = ($vol | Out-String).Trim() | ||
| 134 | + | ||
| 135 | +if ($net) { $env:HEZARFEN_NET = $net } | ||
| 136 | +else { Write-Host "[stack] UYARI: backend agi okunamadi; compose varsayilani kullanilacak." } | ||
| 137 | +if ($vol) { $env:HEZARFEN_DATA_VOLUME = $vol } | ||
| 138 | +else { Write-Host "[stack] UYARI: backend /data hacmi okunamadi; compose varsayilani kullanilacak." } | ||
| 139 | +Write-Host "`n[stack] backend agi : $($env:HEZARFEN_NET)" | ||
| 140 | +Write-Host "[stack] backend hacmi : $($env:HEZARFEN_DATA_VOLUME) (PDF'ler burada, :ro baglanir)" | ||
| 141 | + | ||
| 142 | +$image = "localhost/hezarfen-podcast" | ||
| 143 | + | ||
| 144 | +$previousId = (& $PODMAN images "${image}:current" --format "{{.ID}}" 2>$null | | ||
| 145 | + Select-Object -First 1) | ||
| 146 | + | ||
| 147 | +Write-Host "`n[stack] 5/5 podcast imaji build ediliyor (${image}:current)" | ||
| 148 | +Push-Location $podcast | ||
| 149 | +try { | ||
| 150 | + $buildArgs = @("build", "-t", "${image}:current", "-f", "Containerfile", ".") | ||
| 151 | + if ($Rebuild) { $buildArgs = @("build", "--no-cache") + $buildArgs[1..($buildArgs.Count - 1)] } | ||
| 152 | + & $PODMAN @buildArgs | ||
| 153 | + if ($LASTEXITCODE -ne 0) { throw "podcast imaji build edilemedi." } | ||
| 154 | + | ||
| 155 | + $currentId = (& $PODMAN images "${image}:current" --format "{{.ID}}" 2>$null | | ||
| 156 | + Select-Object -First 1) | ||
| 157 | + if ($currentId -and $currentId -ne $previousId) { | ||
| 158 | + $tag = Get-Date -Format "yyyyMMdd-HHmmss" | ||
| 159 | + & $PODMAN tag "${image}:current" "${image}:$tag" | ||
| 160 | + if ($LASTEXITCODE -ne 0) { throw "surum etiketi konulamadi." } | ||
| 161 | + Write-Host "[stack] imaj DEGISTI -> yeni surum etiketi: $tag ($currentId)" | ||
| 162 | + } else { | ||
| 163 | + Write-Host "[stack] imaj degismedi ($currentId) - yeni surum etiketi ACILMADI" | ||
| 164 | + } | ||
| 165 | + | ||
| 166 | + & $PODMAN compose up -d | ||
| 167 | + if ($LASTEXITCODE -ne 0) { throw "podcast compose up basarisiz." } | ||
| 168 | +} finally { Pop-Location } | ||
| 169 | + | ||
| 170 | +Write-Host "`n[stack] dogrulama..." | ||
| 171 | +Start-Sleep -Seconds 8 | ||
| 172 | +& $PODMAN ps --format "{{.Names}}`t{{.Status}}`t{{.Image}}" | ||
| 173 | + | ||
| 174 | +foreach ($p in 8080, 5173) { | ||
| 175 | + try { | ||
| 176 | + $code = (Invoke-WebRequest -UseBasicParsing -Uri "http://localhost:$p/" -TimeoutSec 8).StatusCode | ||
| 177 | + Write-Host " localhost:$p -> HTTP $code" | ||
| 178 | + } catch { | ||
| 179 | + Write-Host " localhost:$p -> ERISILEMEDI ($($_.Exception.Message))" | ||
| 180 | + } | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +Write-Host " podcast kaydi bekleniyor (en fazla 30 sn)..." | ||
| 184 | +$registered = $false | ||
| 185 | +for ($i = 0; $i -lt 15; $i++) { | ||
| 186 | + $log = (& $PODMAN logs --tail 200 hezarfen-podcast-bridge 2>&1 | Out-String) | ||
| 187 | + if ($log -match "kayit basarili") { $registered = $true; break } | ||
| 188 | + Start-Sleep -Seconds 2 | ||
| 189 | +} | ||
| 190 | +if ($registered) { | ||
| 191 | + ((& $PODMAN logs --tail 200 hezarfen-podcast-bridge 2>&1 | Out-String) -split "`n" | | ||
| 192 | + Where-Object { $_ -match "kayit basarili|GERCEK hat bagli|acik formatlar|SAHTE hat" }) | | ||
| 193 | + ForEach-Object { Write-Host " $($_.Trim())" } | ||
| 194 | + Write-Host "`n[stack] HAZIR. Frontend: http://localhost:5173 (admin / admin123)" | ||
| 195 | + Write-Host "[stack] geri alma : pwsh -File deploy/rollback.ps1 -List" | ||
| 196 | +} else { | ||
| 197 | + Write-Host "`n[stack] !!! Podcast koprusu KAYIT OLMADI. Son loglar:" | ||
| 198 | + & $PODMAN logs --tail 40 hezarfen-podcast-bridge | ||
| 199 | + Write-Host "`n[stack] sorun giderme: deploy/OKU.md" | ||
| 200 | + exit 1 | ||
| 201 | +} | ||
deploy/setup-models.ps1added+121 -0
| @@ -0,0 +1,121 @@ | |||
| 1 | +[CmdletBinding()] | ||
| 2 | +param( | ||
| 3 | + [string]$Volume = "podcast-models", | ||
| 4 | + [string]$VoiceModels = "C:\PROJECTS\podcast\data\ses_modelleri", | ||
| 5 | + [string]$HfCache = "$env:USERPROFILE\.cache\huggingface\hub", | ||
| 6 | + [string]$HelperImage = "docker.io/library/python:3.10-slim", | ||
| 7 | + [switch]$Check, | ||
| 8 | + [switch]$Refresh | ||
| 9 | +) | ||
| 10 | +$ErrorActionPreference = "Stop" | ||
| 11 | + | ||
| 12 | +function Invoke-Quiet { | ||
| 13 | + param([Parameter(Mandatory)][string]$Command, [string[]]$Arg = @()) | ||
| 14 | + $previousEAP = $ErrorActionPreference | ||
| 15 | + $ErrorActionPreference = 'Continue' | ||
| 16 | + try { & $Command @Arg *> $null } finally { $ErrorActionPreference = $previousEAP } | ||
| 17 | + return $LASTEXITCODE | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +function Find-Podman { | ||
| 22 | + $c = (Get-Command podman -ErrorAction SilentlyContinue).Source | ||
| 23 | + if ($c) { return $c } | ||
| 24 | + foreach ($p in @("$env:LOCALAPPDATA\Programs\Podman\podman.exe", | ||
| 25 | + "$env:ProgramFiles\RedHat\Podman\podman.exe")) { | ||
| 26 | + if (Test-Path $p) { return $p } | ||
| 27 | + } | ||
| 28 | + throw "podman.exe bulunamadi. winget install RedHat.Podman" | ||
| 29 | +} | ||
| 30 | +$PODMAN = Find-Podman | ||
| 31 | +Write-Host "[model] podman: $PODMAN" | ||
| 32 | +$previousEAP = $ErrorActionPreference | ||
| 33 | +$ErrorActionPreference = 'Continue' | ||
| 34 | +& $PODMAN machine start *> $null | ||
| 35 | +$ErrorActionPreference = $previousEAP | ||
| 36 | + | ||
| 37 | +$writer = "podcast-model-yazici" | ||
| 38 | + | ||
| 39 | +function Start-Writer { | ||
| 40 | + Invoke-Quiet $PODMAN @('rm','-f',$writer) | Out-Null | ||
| 41 | + & $PODMAN run -d --name $writer -v "${Volume}:/models" $HelperImage sleep 7200 | Out-Null | ||
| 42 | + if ($LASTEXITCODE -ne 0) { throw "Yazici container baslatilamadi ($HelperImage cekilmemis olabilir: podman pull $HelperImage)" } | ||
| 43 | + & $PODMAN exec $writer mkdir -p /models/ses_modelleri /models/hf/hub /models/torch | Out-Null | ||
| 44 | +} | ||
| 45 | +function Stop-Writer { | ||
| 46 | + Invoke-Quiet $PODMAN @('rm','-f',$writer) | Out-Null | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +Invoke-Quiet $PODMAN @('volume','create',$Volume) | Out-Null | ||
| 50 | + | ||
| 51 | +if ($Check) { | ||
| 52 | + Start-Writer | ||
| 53 | + try { | ||
| 54 | + Write-Host "`n[model] '$Volume' hacminin icerigi:" | ||
| 55 | + & $PODMAN exec $writer sh -c "du -sh /models/* /models/ses_modelleri/* /models/hf/hub/* 2>/dev/null | sort -k2" | ||
| 56 | + } finally { Stop-Writer } | ||
| 57 | + return | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +$jobs = @( | ||
| 61 | + @{ name = "supertonic-3"; | ||
| 62 | + source = (Join-Path $VoiceModels "supertonic-3"); | ||
| 63 | + target = "/models/ses_modelleri"; | ||
| 64 | + probe = "/models/ses_modelleri/supertonic-3/onnx/vocoder.onnx"; | ||
| 65 | + download = "python -c ""from huggingface_hub import snapshot_download; snapshot_download('Supertone/supertonic-3', local_dir='data/ses_modelleri/supertonic-3')""" }, | ||
| 66 | + @{ name = "faster_whisper (medium)"; | ||
| 67 | + source = (Join-Path $VoiceModels "faster_whisper"); | ||
| 68 | + target = "/models/ses_modelleri"; | ||
| 69 | + probe = "/models/ses_modelleri/faster_whisper/models--Systran--faster-whisper-medium"; | ||
| 70 | + download = "python -c ""from faster_whisper import WhisperModel; WhisperModel('medium', device='cpu', compute_type='int8', download_root='data/ses_modelleri/faster_whisper')""" }, | ||
| 71 | + @{ name = "multilingual-e5-large"; | ||
| 72 | + source = (Join-Path $HfCache "models--intfloat--multilingual-e5-large"); | ||
| 73 | + target = "/models/hf/hub"; | ||
| 74 | + probe = "/models/hf/hub/models--intfloat--multilingual-e5-large"; | ||
| 75 | + download = "python -c ""from huggingface_hub import snapshot_download; snapshot_download('intfloat/multilingual-e5-large')""" } | ||
| 76 | +) | ||
| 77 | + | ||
| 78 | +Start-Writer | ||
| 79 | +$missing = @() | ||
| 80 | +try { | ||
| 81 | + foreach ($job in $jobs) { | ||
| 82 | + $name = $job.name | ||
| 83 | + $null = Invoke-Quiet $PODMAN @('exec',$writer,'test','-e',$job.probe) | ||
| 84 | + $exists = ($LASTEXITCODE -eq 0) | ||
| 85 | + if ($exists -and -not $Refresh) { | ||
| 86 | + Write-Host "[model] $name -> hacimde ZATEN VAR, atlandi (-Refresh ile ez)" | ||
| 87 | + continue | ||
| 88 | + } | ||
| 89 | + if (-not (Test-Path -LiteralPath $job.source)) { | ||
| 90 | + Write-Host "[model] $name -> YEREL KOPYA YOK: $($job.source)" | ||
| 91 | + $missing += $job | ||
| 92 | + continue | ||
| 93 | + } | ||
| 94 | + $mb = ((Get-ChildItem -LiteralPath $job.source -Recurse -Force -File | | ||
| 95 | + Measure-Object -Property Length -Sum).Sum) / 1MB | ||
| 96 | + Write-Host ("[model] $name -> kopyalaniyor ({0:N0} MB, WSL uzerinden dakikalar surebilir)..." -f $mb) | ||
| 97 | + & $PODMAN cp $job.source "${writer}:$($job.target)" | ||
| 98 | + if ($LASTEXITCODE -ne 0) { throw "podman cp basarisiz: $name" } | ||
| 99 | + } | ||
| 100 | + | ||
| 101 | + Write-Host "[model] izinler aciliyor (a+rX)..." | ||
| 102 | + & $PODMAN exec $writer sh -c "chmod -R a+rX /models" | Out-Null | ||
| 103 | + | ||
| 104 | + Write-Host "`n[model] hacim icerigi:" | ||
| 105 | + & $PODMAN exec $writer sh -c "du -sh /models/ses_modelleri/* /models/hf/hub/* 2>/dev/null" | ||
| 106 | +} finally { | ||
| 107 | + Stop-Writer | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +if ($missing.Count -gt 0) { | ||
| 111 | + Write-Host "`n[model] !!! EKSIK AGIRLIKLAR - betik BILEREK indirmedi (4 GB'a operator karar verir):" | ||
| 112 | + foreach ($job in $missing) { | ||
| 113 | + Write-Host "`n * $($job.name)" | ||
| 114 | + Write-Host " beklenen yerel yol : $($job.source)" | ||
| 115 | + Write-Host " indirme komutu : cd C:\PROJECTS\podcast ; $($job.download)" | ||
| 116 | + } | ||
| 117 | + Write-Host "`n Indirdikten sonra bu betigi TEKRAR calistir." | ||
| 118 | + exit 1 | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +Write-Host "`n[model] TAMAM. Siradaki: pwsh -File deploy/run-stack.ps1" | ||
deploy/setup-pipeline.ps1added+94 -0
| @@ -0,0 +1,94 @@ | |||
| 1 | +[CmdletBinding()] | ||
| 2 | +param( | ||
| 3 | + [string]$Source = "C:\PROJECTS\podcast", | ||
| 4 | + [switch]$WindowsBinaries, | ||
| 5 | + [switch]$Clean | ||
| 6 | +) | ||
| 7 | +$ErrorActionPreference = "Stop" | ||
| 8 | + | ||
| 9 | +$repo = Split-Path -Parent $PSScriptRoot | ||
| 10 | +$target = Join-Path $repo "vendor\pipeline" | ||
| 11 | + | ||
| 12 | +if (-not (Test-Path -LiteralPath $Source)) { | ||
| 13 | + throw "Hat kaynagi bulunamadi: $Source (-Source <yol> ile ver)" | ||
| 14 | +} | ||
| 15 | +$Source = (Resolve-Path -LiteralPath $Source).Path | ||
| 16 | +foreach ($signature in @("router\hat.py", "config\router.toml", "router\yonlendirici.py", | ||
| 17 | + "script\plan.py", "ses\montaj.py", "ingest\__init__.py", | ||
| 18 | + "requirements.txt", "requirements-ses.txt", "requirements-ocr.txt")) { | ||
| 19 | + $p = Join-Path $Source $signature | ||
| 20 | + if (-not (Test-Path -LiteralPath $p)) { | ||
| 21 | + throw "Kaynak hat gibi gorunmuyor: $signature yok ($Source)" | ||
| 22 | + } | ||
| 23 | +} | ||
| 24 | +Write-Host "[pipeline] kaynak dogrulandi: $Source" | ||
| 25 | + | ||
| 26 | +if ($Clean) { | ||
| 27 | + if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Recurse -Force } | ||
| 28 | + Write-Host "[pipeline] vendor/pipeline silindi. Cikiliyor." | ||
| 29 | + return | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +$directories = @("router", "script", "ses", "ingest", "bilgi", "config") | ||
| 33 | +$files = @("requirements.txt", "requirements-ocr.txt", "requirements-ses.txt") | ||
| 34 | + | ||
| 35 | +if ($WindowsBinaries) { $directories += "tools\bin" } | ||
| 36 | + | ||
| 37 | +$excluded = @("__pycache__", ".venv", ".git", "out", "*.pyc", "*.pyo", "*.yedek") | ||
| 38 | + | ||
| 39 | +if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Recurse -Force } | ||
| 40 | +New-Item -ItemType Directory -Force -Path $target | Out-Null | ||
| 41 | + | ||
| 42 | +Write-Host "[pipeline] kopyalaniyor -> $target" | ||
| 43 | +foreach ($d in $directories) { | ||
| 44 | + $src = Join-Path $Source $d | ||
| 45 | + if (-not (Test-Path -LiteralPath $src)) { Write-Host " ATLANDI (yok): $d"; continue } | ||
| 46 | + $dst = Join-Path $target $d | ||
| 47 | + New-Item -ItemType Directory -Force -Path (Split-Path -Parent $dst) | Out-Null | ||
| 48 | + Copy-Item -LiteralPath $src -Destination $dst -Recurse -Force | ||
| 49 | + Write-Host " $d" | ||
| 50 | +} | ||
| 51 | +foreach ($f in $files) { | ||
| 52 | + Copy-Item -LiteralPath (Join-Path $Source $f) -Destination (Join-Path $target $f) -Force | ||
| 53 | + Write-Host " $f" | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +Get-ChildItem -LiteralPath $target -Recurse -Force -Directory -Filter "__pycache__" | | ||
| 57 | + Sort-Object { $_.FullName.Length } -Descending | | ||
| 58 | + ForEach-Object { Remove-Item -LiteralPath $_.FullName -Recurse -Force } | ||
| 59 | +Get-ChildItem -LiteralPath $target -Recurse -Force -File | | ||
| 60 | + Where-Object { $_.Extension -in @(".pyc", ".pyo", ".yedek") } | | ||
| 61 | + ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force } | ||
| 62 | + | ||
| 63 | +foreach ($signature in @("router\hat.py", "config\router.toml", "requirements-ses.txt")) { | ||
| 64 | + if (-not (Test-Path -LiteralPath (Join-Path $target $signature))) { | ||
| 65 | + throw "Kopyalama eksik: $signature vendor/pipeline altinda yok." | ||
| 66 | + } | ||
| 67 | +} | ||
| 68 | +$fileCount = (Get-ChildItem -LiteralPath $target -Recurse -Force -File).Count | ||
| 69 | +$size = (Get-ChildItem -LiteralPath $target -Recurse -Force -File | | ||
| 70 | + Measure-Object -Property Length -Sum).Sum | ||
| 71 | +Write-Host "" | ||
| 72 | +Write-Host ("[pipeline] TAMAM: {0} dosya, {1:N2} MB" -f $fileCount, ($size / 1MB)) | ||
| 73 | +Write-Host "[pipeline] hedef: $target" | ||
| 74 | +if (-not $WindowsBinaries) { | ||
| 75 | + Write-Host "[pipeline] tools/bin/*.exe ATLANDI (Windows ikilileri, ~220 MB). Container ffmpeg'i apt'tan kurar." | ||
| 76 | +} | ||
| 77 | +$py = $null | ||
| 78 | + foreach ($candidate in @((Join-Path (Join-Path (Join-Path $Source ".venv") "Scripts") "python.exe"), "python")) { | ||
| 79 | + if ($candidate -eq "python") { if (Get-Command python -ErrorAction SilentlyContinue) { $py = "python" } } | ||
| 80 | + elseif (Test-Path -LiteralPath $candidate) { $py = $candidate } | ||
| 81 | + if ($py) { break } | ||
| 82 | +} | ||
| 83 | +if ($py) { | ||
| 84 | + Write-Host "" | ||
| 85 | + & $py (Join-Path (Join-Path (Split-Path -Parent $PSScriptRoot) "tools") "dependency_scanner.py") $target | ||
| 86 | + if ($LASTEXITCODE -ne 0) { | ||
| 87 | + throw "Beyan edilmemis bagimlilik var (yukari bkz). Imaj derlenmeden ONCE requirements*.txt duzeltilmeli." | ||
| 88 | + } | ||
| 89 | +} else { | ||
| 90 | + Write-Host "[pipeline] UYARI: python bulunamadi, bagimlilik taramasi ATLANDI." | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +Write-Host "" | ||
| 94 | +Write-Host "[pipeline] siradaki: pwsh -File deploy/setup-models.ps1" | ||
requirements.txtadded+1 -0
| @@ -0,0 +1 @@ | |||
| 1 | +aioquic==1.3.0 | ||
setup.cfgadded+3 -0
| @@ -0,0 +1,3 @@ | |||
| 1 | +[mutmut] | ||
| 2 | +paths_to_mutate=src/protocol.py,src/capabilities.py | ||
| 3 | +tests_dir=tests/ | ||
src/__init__.pyadded+0 -0
src/bridge.pyadded+327 -0
| @@ -0,0 +1,327 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import asyncio | ||
| 4 | +import json | ||
| 5 | +import ssl | ||
| 6 | +import sys | ||
| 7 | +import urllib.error | ||
| 8 | +import urllib.request | ||
| 9 | +from functools import partial | ||
| 10 | +from typing import Any, Callable | ||
| 11 | + | ||
| 12 | +from aioquic.asyncio import connect | ||
| 13 | +from aioquic.asyncio.protocol import QuicConnectionProtocol | ||
| 14 | +from aioquic.quic.configuration import QuicConfiguration | ||
| 15 | +from aioquic.quic.events import ConnectionTerminated, QuicEvent, StreamDataReceived | ||
| 16 | + | ||
| 17 | +from . import capabilities, config, jobs, pipeline, protocol | ||
| 18 | +from .protocol import CapabilityError | ||
| 19 | + | ||
| 20 | +CERT_FETCH_TIMEOUT_SECS = 10 | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class BridgeProtocol(QuicConnectionProtocol): | ||
| 24 | + def __init__(self, *args: Any, settings: config.Config, **kwargs: Any) -> None: | ||
| 25 | + super().__init__(*args, **kwargs) | ||
| 26 | + self._settings = settings | ||
| 27 | + self._streams: dict[int, protocol.FrameStream] = {} | ||
| 28 | + self._control_sid: int | None = None | ||
| 29 | + self._ping_uid = 0 | ||
| 30 | + self._inflight = 0 | ||
| 31 | + self._tasks: set[asyncio.Future] = set() | ||
| 32 | + | ||
| 33 | + def quic_event_received(self, event: QuicEvent) -> None: | ||
| 34 | + if isinstance(event, StreamDataReceived): | ||
| 35 | + sid = event.stream_id | ||
| 36 | + stream = self._streams.get(sid) | ||
| 37 | + if stream is None: | ||
| 38 | + if sid % 4 not in (0, 1): | ||
| 39 | + return | ||
| 40 | + stream = protocol.FrameStream() | ||
| 41 | + self._streams[sid] = stream | ||
| 42 | + if sid % 4 == 1: | ||
| 43 | + task = asyncio.ensure_future(self._serve_request(sid, stream)) | ||
| 44 | + self._tasks.add(task) | ||
| 45 | + task.add_done_callback(self._tasks.discard) | ||
| 46 | + stream.feed(event.data, event.end_stream) | ||
| 47 | + elif isinstance(event, ConnectionTerminated): | ||
| 48 | + for stream in self._streams.values(): | ||
| 49 | + stream.feed(b"", end=True) | ||
| 50 | + | ||
| 51 | + async def register(self) -> None: | ||
| 52 | + sid = self._quic.get_next_available_stream_id() | ||
| 53 | + self._control_sid = sid | ||
| 54 | + stream = protocol.FrameStream() | ||
| 55 | + self._streams[sid] = stream | ||
| 56 | + hello = protocol.build_hello( | ||
| 57 | + self._settings.service, | ||
| 58 | + capabilities.names(), | ||
| 59 | + self._settings.token, | ||
| 60 | + self._settings.max_concurrent, | ||
| 61 | + ) | ||
| 62 | + self._send_frame(sid, hello, end=False) | ||
| 63 | + greeting = await asyncio.wait_for( | ||
| 64 | + stream.read_frame(), timeout=protocol.GREETING_TIMEOUT_SECS | ||
| 65 | + ) | ||
| 66 | + worker_id = protocol.parse_greeting(greeting) | ||
| 67 | + jobs.write_status(self._settings.job_root, True, worker_id) | ||
| 68 | + config.log( | ||
| 69 | + "info", | ||
| 70 | + f"kayit basarili: worker_id={worker_id} yetenekler={','.join(capabilities.names())}", | ||
| 71 | + ) | ||
| 72 | + | ||
| 73 | + async def api_get( | ||
| 74 | + self, | ||
| 75 | + path: str, | ||
| 76 | + query: str | None = None, | ||
| 77 | + on_behalf_of: str | None = None, | ||
| 78 | + timeout: float = protocol.API_TIMEOUT_SECS, | ||
| 79 | + ) -> protocol.ApiResponse: | ||
| 80 | + sid = self._quic.get_next_available_stream_id() | ||
| 81 | + stream = protocol.FrameStream() | ||
| 82 | + self._streams[sid] = stream | ||
| 83 | + request = protocol.build_api_request( | ||
| 84 | + jobs.new_job_id(), path, query, on_behalf_of | ||
| 85 | + ) | ||
| 86 | + try: | ||
| 87 | + self._send_frame(sid, request, end=True) | ||
| 88 | + frame = await asyncio.wait_for(stream.read_frame(), timeout=timeout) | ||
| 89 | + finally: | ||
| 90 | + self._streams.pop(sid, None) | ||
| 91 | + response = protocol.parse_api_response(frame) | ||
| 92 | + config.log( | ||
| 93 | + "debug", | ||
| 94 | + f"api {path} -> status={response.status} " | ||
| 95 | + f"kim={on_behalf_of or 'servis(ai rolu)'}", | ||
| 96 | + ) | ||
| 97 | + return response | ||
| 98 | + | ||
| 99 | + def _send_frame(self, sid: int, obj: Any, end: bool) -> None: | ||
| 100 | + self._quic.send_stream_data(sid, protocol.encode_frame(obj), end_stream=end) | ||
| 101 | + self.transmit() | ||
| 102 | + | ||
| 103 | + async def _serve_request(self, sid: int, stream: protocol.FrameStream) -> None: | ||
| 104 | + request_id = "" | ||
| 105 | + try: | ||
| 106 | + frame = await stream.read_frame() | ||
| 107 | + if isinstance(frame, dict) and isinstance(frame.get("id"), str): | ||
| 108 | + request_id = frame["id"] | ||
| 109 | + request_id, capability, payload, timeout = protocol.parse_request(frame) | ||
| 110 | + except EOFError as exc: | ||
| 111 | + config.log("warn", f"istek {sid} okunamadi: {exc}") | ||
| 112 | + self._streams.pop(sid, None) | ||
| 113 | + return | ||
| 114 | + except (CapabilityError, ValueError) as exc: | ||
| 115 | + code = getattr(exc, "code", "bad_request") | ||
| 116 | + config.log("warn", f"istek {sid} ayristirilamadi: {exc}") | ||
| 117 | + self._finish(sid, request_id, protocol.err_response(request_id, code, str(exc))) | ||
| 118 | + return | ||
| 119 | + | ||
| 120 | + if self._inflight >= self._settings.max_concurrent: | ||
| 121 | + response = protocol.err_response( | ||
| 122 | + request_id, "busy", "worker es zamanli istek sinirinda" | ||
| 123 | + ) | ||
| 124 | + self._finish(sid, request_id, response) | ||
| 125 | + return | ||
| 126 | + | ||
| 127 | + self._inflight += 1 | ||
| 128 | + try: | ||
| 129 | + config.log("debug", f"istek {request_id} yetenek={capability}") | ||
| 130 | + result = await asyncio.wait_for(self._handle(capability, payload), timeout=timeout) | ||
| 131 | + response = protocol.ok_response(request_id, result) | ||
| 132 | + except CapabilityError as exc: | ||
| 133 | + response = protocol.err_response(request_id, exc.code, str(exc)) | ||
| 134 | + except asyncio.TimeoutError: | ||
| 135 | + response = protocol.err_response( | ||
| 136 | + request_id, "timed_out", "istek sure icinde tamamlanamadi" | ||
| 137 | + ) | ||
| 138 | + except Exception as exc: | ||
| 139 | + config.log("error", f"istek {request_id} islenemedi: {exc}") | ||
| 140 | + response = protocol.err_response(request_id, "internal", "beklenmeyen hata") | ||
| 141 | + finally: | ||
| 142 | + self._inflight -= 1 | ||
| 143 | + | ||
| 144 | + self._finish(sid, request_id, response) | ||
| 145 | + | ||
| 146 | + def _finish(self, sid: int, request_id: str, response: dict[str, Any]) -> None: | ||
| 147 | + try: | ||
| 148 | + self._send_frame(sid, response, end=True) | ||
| 149 | + except CapabilityError as exc: | ||
| 150 | + config.log("warn", f"cevap {request_id} cerceve sinirini asti: {exc}") | ||
| 151 | + try: | ||
| 152 | + self._send_frame( | ||
| 153 | + sid, | ||
| 154 | + protocol.err_response(request_id, "frame_too_large", str(exc)), | ||
| 155 | + end=True, | ||
| 156 | + ) | ||
| 157 | + except Exception as inner: | ||
| 158 | + config.log("error", f"cevap {request_id} yazilamadi: {inner}") | ||
| 159 | + except Exception as exc: | ||
| 160 | + config.log("error", f"cevap {request_id} yazilamadi: {exc}") | ||
| 161 | + finally: | ||
| 162 | + self._streams.pop(sid, None) | ||
| 163 | + | ||
| 164 | + async def _handle(self, capability: str, payload: Any) -> dict[str, Any]: | ||
| 165 | + loop = asyncio.get_running_loop() | ||
| 166 | + return await loop.run_in_executor(None, capabilities.dispatch, capability, payload) | ||
| 167 | + | ||
| 168 | + async def keepalive(self) -> None: | ||
| 169 | + while True: | ||
| 170 | + await asyncio.sleep(protocol.KEEPALIVE_SECS) | ||
| 171 | + self._ping_uid += 1 | ||
| 172 | + try: | ||
| 173 | + self._quic.send_ping(self._ping_uid) | ||
| 174 | + self.transmit() | ||
| 175 | + except Exception: | ||
| 176 | + return | ||
| 177 | + | ||
| 178 | + | ||
| 179 | +def fetch_certificate(backend_url: str) -> str: | ||
| 180 | + url = f"{backend_url}{protocol.CERTIFICATE_PATH}" | ||
| 181 | + with urllib.request.urlopen(url, timeout=CERT_FETCH_TIMEOUT_SECS) as resp: | ||
| 182 | + data = json.loads(resp.read()) | ||
| 183 | + pem = data.get("certificate_pem") | ||
| 184 | + if not pem: | ||
| 185 | + raise RuntimeError(f"{url} beklenen certificate_pem alanini dondurmedi") | ||
| 186 | + fingerprint = str(data.get("fingerprint_sha256", "?"))[:12] | ||
| 187 | + config.log("info", f"sertifika alindi (fingerprint {fingerprint})") | ||
| 188 | + return pem | ||
| 189 | + | ||
| 190 | + | ||
| 191 | +def build_quic_configuration(settings: config.Config, cert_pem: str) -> QuicConfiguration: | ||
| 192 | + quic_config = QuicConfiguration(is_client=True, alpn_protocols=[protocol.PROTOCOL]) | ||
| 193 | + quic_config.server_name = settings.server_name | ||
| 194 | + quic_config.verify_mode = ssl.CERT_REQUIRED | ||
| 195 | + quic_config.load_verify_locations(cadata=cert_pem.encode("utf-8")) | ||
| 196 | + quic_config.idle_timeout = protocol.IDLE_TIMEOUT_SECS | ||
| 197 | + return quic_config | ||
| 198 | + | ||
| 199 | + | ||
| 200 | +async def run_once(settings: config.Config) -> None: | ||
| 201 | + cert_pem = fetch_certificate(settings.backend_url) | ||
| 202 | + quic_config = build_quic_configuration(settings, cert_pem) | ||
| 203 | + config.log( | ||
| 204 | + "info", | ||
| 205 | + f"{settings.host}:{settings.port} adresine baglaniliyor (ALPN {protocol.PROTOCOL})", | ||
| 206 | + ) | ||
| 207 | + create = partial(BridgeProtocol, settings=settings) | ||
| 208 | + async with connect( | ||
| 209 | + settings.host, | ||
| 210 | + settings.port, | ||
| 211 | + configuration=quic_config, | ||
| 212 | + create_protocol=create, | ||
| 213 | + ) as connection: | ||
| 214 | + assert isinstance(connection, BridgeProtocol) | ||
| 215 | + await connection.wait_connected() | ||
| 216 | + await connection.register() | ||
| 217 | + keepalive_task = asyncio.ensure_future(connection.keepalive()) | ||
| 218 | + try: | ||
| 219 | + await connection.wait_closed() | ||
| 220 | + finally: | ||
| 221 | + keepalive_task.cancel() | ||
| 222 | + config.log("info", "baglanti kapandi") | ||
| 223 | + | ||
| 224 | + | ||
| 225 | +async def run_forever(settings: config.Config) -> int: | ||
| 226 | + config.log("info", f"podcast koprusu basliyor: {settings.summary()}") | ||
| 227 | + jobs.write_status(settings.job_root, False) | ||
| 228 | + while True: | ||
| 229 | + try: | ||
| 230 | + await run_once(settings) | ||
| 231 | + except (urllib.error.URLError, ConnectionError, OSError) as exc: | ||
| 232 | + config.log("warn", f"backend'e ulasilamadi: {exc}") | ||
| 233 | + except protocol.HandshakeRejected as exc: | ||
| 234 | + config.log("error", str(exc)) | ||
| 235 | + if exc.code in ("unauthorized", "unsupported_protocol"): | ||
| 236 | + jobs.write_status(settings.job_root, False) | ||
| 237 | + config.log("error", "yapilandirma degismeden yeniden denenmeyecek") | ||
| 238 | + return 2 | ||
| 239 | + except Exception as exc: | ||
| 240 | + config.log("error", f"baglanti hatasi: {exc}") | ||
| 241 | + jobs.write_status(settings.job_root, False) | ||
| 242 | + config.log("info", f"{settings.reconnect_secs}s sonra yeniden denenecek") | ||
| 243 | + await asyncio.sleep(settings.reconnect_secs) | ||
| 244 | + | ||
| 245 | + | ||
| 246 | +def build_store( | ||
| 247 | + settings: config.Config, | ||
| 248 | + runner: Callable[[jobs.JobContext], None] | None = None, | ||
| 249 | + stages: tuple[str, ...] | None = None, | ||
| 250 | + job_secs: float | None = None, | ||
| 251 | +) -> jobs.JobStore: | ||
| 252 | + try: | ||
| 253 | + store = jobs.JobStore( | ||
| 254 | + root=settings.job_root, | ||
| 255 | + workers=settings.workers, | ||
| 256 | + max_jobs=settings.max_jobs, | ||
| 257 | + stage_secs=settings.stage_secs, | ||
| 258 | + runner=runner, | ||
| 259 | + stages=stages, | ||
| 260 | + job_secs=job_secs, | ||
| 261 | + retention_days=settings.retention_days, | ||
| 262 | + output_root=settings.output_root, | ||
| 263 | + ) | ||
| 264 | + except OSError as exc: | ||
| 265 | + config.log("error", f"PODCAST_JOB_ROOT kullanilamiyor ({settings.job_root}): {exc}") | ||
| 266 | + sys.exit(2) | ||
| 267 | + if store.swept: | ||
| 268 | + config.log( | ||
| 269 | + "warn", | ||
| 270 | + f"acilis supurmesi: {store.swept} kosan is " | ||
| 271 | + f"'{jobs.INTERRUPTED_CODE}' olarak isaretlendi", | ||
| 272 | + ) | ||
| 273 | + requeued = store.start() | ||
| 274 | + if requeued: | ||
| 275 | + config.log("info", f"acilista {requeued} kuyruktaki is yeniden alindi") | ||
| 276 | + return store | ||
| 277 | + | ||
| 278 | + | ||
| 279 | +def select_runner( | ||
| 280 | + settings: config.Config, | ||
| 281 | +) -> tuple[Callable[[jobs.JobContext], None] | None, bool]: | ||
| 282 | + if settings.mode != pipeline.MODE_REAL: | ||
| 283 | + config.log("warn", pipeline.FAKE_WARNING) | ||
| 284 | + return None, settings.has_llm_key | ||
| 285 | + try: | ||
| 286 | + runner, probe = pipeline.build_runner(settings) | ||
| 287 | + except pipeline.PipelineUnavailable as exc: | ||
| 288 | + config.log("error", f"PODCAST_MODE=real ama gercek hat yuklenemedi: {exc}") | ||
| 289 | + sys.exit(2) | ||
| 290 | + config.log( | ||
| 291 | + "info", | ||
| 292 | + f"GERCEK hat bagli: kaynak={settings.pipeline_path} " | ||
| 293 | + f"cikti={settings.output_root} tts={settings.tts_engine}", | ||
| 294 | + ) | ||
| 295 | + llm_ready = bool(probe["llm_ready"]) | ||
| 296 | + if llm_ready != settings.has_llm_key: | ||
| 297 | + config.log( | ||
| 298 | + "warn", | ||
| 299 | + "LLM hazirligi ortam degiskeninden FARKLI: hat '%s' diyor " | ||
| 300 | + "(gerekce: %s). Hattin karari esas alinir." | ||
| 301 | + % ("HAZIR" if llm_ready else "YOK", probe["llm_reason"][:120]), | ||
| 302 | + ) | ||
| 303 | + return runner, llm_ready | ||
| 304 | + | ||
| 305 | + | ||
| 306 | +def main() -> int: | ||
| 307 | + settings = config.load(require_token=True) | ||
| 308 | + runner, llm_ready = select_runner(settings) | ||
| 309 | + store = build_store( | ||
| 310 | + settings, | ||
| 311 | + runner=runner, | ||
| 312 | + stages=pipeline.stages_for(settings), | ||
| 313 | + job_secs=pipeline.job_secs_for(settings), | ||
| 314 | + ) | ||
| 315 | + capabilities.configure(store, llm_ready) | ||
| 316 | + config.log("info", capabilities.format_summary(llm_ready)) | ||
| 317 | + try: | ||
| 318 | + return asyncio.run(run_forever(settings)) | ||
| 319 | + except KeyboardInterrupt: | ||
| 320 | + config.log("info", "durduruldu") | ||
| 321 | + return 0 | ||
| 322 | + finally: | ||
| 323 | + store.shutdown() | ||
| 324 | + | ||
| 325 | + | ||
| 326 | +if __name__ == "__main__": | ||
| 327 | + sys.exit(main()) | ||
src/capabilities.pyadded+153 -0
| @@ -0,0 +1,153 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +from typing import Any, Callable | ||
| 4 | + | ||
| 5 | +from . import jobs | ||
| 6 | +from .protocol import CapabilityError | ||
| 7 | + | ||
| 8 | +Handler = Callable[[dict], dict] | ||
| 9 | + | ||
| 10 | +FORMATS = ("tek_ogretici", "ogrenci_hoca", "duz_okuma") | ||
| 11 | +DEFAULT_FORMAT = "duz_okuma" | ||
| 12 | +LLM_FORMATS = ("tek_ogretici", "ogrenci_hoca") | ||
| 13 | +KEYLESS_FORMATS = tuple(name for name in FORMATS if name not in LLM_FORMATS) | ||
| 14 | +LLM_KEY_NAME = "DEEPSEEK_API_KEY" | ||
| 15 | + | ||
| 16 | +_store: jobs.JobStore | None = None | ||
| 17 | +_llm_ready = False | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def configure(store: jobs.JobStore | None, llm_ready: bool) -> None: | ||
| 21 | + global _store, _llm_ready | ||
| 22 | + _store = store | ||
| 23 | + _llm_ready = bool(llm_ready) | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def allowed_formats(llm_ready: bool) -> tuple[str, ...]: | ||
| 27 | + return FORMATS if llm_ready else KEYLESS_FORMATS | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def format_summary(llm_ready: bool) -> str: | ||
| 31 | + enabled = ", ".join(allowed_formats(llm_ready)) | ||
| 32 | + if llm_ready: | ||
| 33 | + return f"acik formatlar: {enabled} ({LLM_KEY_NAME} tanimli)" | ||
| 34 | + disabled = ", ".join(LLM_FORMATS) | ||
| 35 | + return f"acik formatlar: {enabled} ({LLM_KEY_NAME} tanimsiz; {disabled} kapali)" | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +def _active_store() -> jobs.JobStore: | ||
| 39 | + if _store is None: | ||
| 40 | + raise CapabilityError("internal", "is deposu hazir degil") | ||
| 41 | + return _store | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +def _require_text(payload: dict, key: str) -> str: | ||
| 45 | + value = payload.get(key) | ||
| 46 | + if not isinstance(value, str) or not value.strip(): | ||
| 47 | + raise CapabilityError("bad_request", f"'{key}' bos olmayan bir metin olmali") | ||
| 48 | + return value.strip() | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +def _optional_choice(payload: dict, key: str, choices: tuple, default: str) -> str: | ||
| 52 | + value = payload.get(key) | ||
| 53 | + if value is None: | ||
| 54 | + return default | ||
| 55 | + if not isinstance(value, str): | ||
| 56 | + raise CapabilityError("bad_request", f"'{key}' bir metin olmali") | ||
| 57 | + normalized = value.strip().lower() | ||
| 58 | + if normalized not in choices: | ||
| 59 | + raise CapabilityError( | ||
| 60 | + "bad_request", f"'{key}' su degerlerden biri olmali: {', '.join(choices)}" | ||
| 61 | + ) | ||
| 62 | + return normalized | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +def _lookup(store: jobs.JobStore, job_id: str) -> dict: | ||
| 66 | + try: | ||
| 67 | + return store.get(job_id) | ||
| 68 | + except jobs.JobNotFound as exc: | ||
| 69 | + raise CapabilityError("not_found", str(exc)) from exc | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +def submit(payload: dict) -> dict: | ||
| 73 | + source_id = _require_text(payload, "source_id") | ||
| 74 | + job_format = _optional_choice(payload, "format", FORMATS, DEFAULT_FORMAT) | ||
| 75 | + if job_format in LLM_FORMATS and not _llm_ready: | ||
| 76 | + raise CapabilityError( | ||
| 77 | + "llm_unavailable", | ||
| 78 | + f"'{job_format}' formati LLM anahtari gerektiriyor ama {LLM_KEY_NAME} " | ||
| 79 | + f"tanimsiz; su an kullanilabilir formatlar: {', '.join(KEYLESS_FORMATS)}", | ||
| 80 | + ) | ||
| 81 | + store = _active_store() | ||
| 82 | + try: | ||
| 83 | + record, eta = store.submit(source_id, job_format) | ||
| 84 | + except jobs.JobStoreFull as exc: | ||
| 85 | + raise CapabilityError("busy", str(exc)) from exc | ||
| 86 | + except OSError as exc: | ||
| 87 | + raise CapabilityError("internal", f"is durumu diske yazilamadi: {exc}") from exc | ||
| 88 | + return {"job_id": record["job_id"], "state": record["state"], "eta_secs": eta} | ||
| 89 | + | ||
| 90 | + | ||
| 91 | +def status(payload: dict) -> dict: | ||
| 92 | + job_id = _require_text(payload, "job_id") | ||
| 93 | + record = _lookup(_active_store(), job_id) | ||
| 94 | + return { | ||
| 95 | + "job_id": record["job_id"], | ||
| 96 | + "state": record["state"], | ||
| 97 | + "stage": record["stage"], | ||
| 98 | + "progress": record["progress"], | ||
| 99 | + "error_code": record["error_code"], | ||
| 100 | + } | ||
| 101 | + | ||
| 102 | + | ||
| 103 | +def result(payload: dict) -> dict: | ||
| 104 | + job_id = _require_text(payload, "job_id") | ||
| 105 | + record = _lookup(_active_store(), job_id) | ||
| 106 | + if record["state"] != jobs.STATE_DONE: | ||
| 107 | + raise CapabilityError( | ||
| 108 | + "not_ready", f"is henuz hazir degil: {job_id} durum={record['state']}" | ||
| 109 | + ) | ||
| 110 | + return { | ||
| 111 | + "job_id": record["job_id"], | ||
| 112 | + "audio_id": record["audio_id"], | ||
| 113 | + "duration_secs": record["duration_secs"], | ||
| 114 | + "script_id": record["script_id"], | ||
| 115 | + "audio_ids": list(record.get("audio_ids") or []), | ||
| 116 | + "script_ids": list(record.get("script_ids") or []), | ||
| 117 | + "format": record["format"], | ||
| 118 | + } | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +def cancel(payload: dict) -> dict: | ||
| 122 | + job_id = _require_text(payload, "job_id") | ||
| 123 | + store = _active_store() | ||
| 124 | + try: | ||
| 125 | + cancelled = store.cancel(job_id) | ||
| 126 | + except jobs.JobNotFound as exc: | ||
| 127 | + raise CapabilityError("not_found", str(exc)) from exc | ||
| 128 | + except jobs.InvalidTransition as exc: | ||
| 129 | + raise CapabilityError("internal", str(exc)) from exc | ||
| 130 | + return {"job_id": job_id, "cancelled": cancelled} | ||
| 131 | + | ||
| 132 | + | ||
| 133 | +REGISTRY: dict[str, Handler] = { | ||
| 134 | + "podcast.submit": submit, | ||
| 135 | + "podcast.status": status, | ||
| 136 | + "podcast.result": result, | ||
| 137 | + "podcast.cancel": cancel, | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | + | ||
| 141 | +def names() -> list[str]: | ||
| 142 | + return sorted(REGISTRY) | ||
| 143 | + | ||
| 144 | + | ||
| 145 | +def dispatch(capability: str, payload: Any) -> dict: | ||
| 146 | + handler = REGISTRY.get(capability) | ||
| 147 | + if handler is None: | ||
| 148 | + raise CapabilityError("unsupported_capability", f"bilinmeyen yetenek: {capability}") | ||
| 149 | + if payload is None: | ||
| 150 | + payload = {} | ||
| 151 | + if not isinstance(payload, dict): | ||
| 152 | + raise CapabilityError("bad_request", "'payload' bir nesne olmali") | ||
| 153 | + return handler(payload) | ||
src/config.pyadded+140 -0
| @@ -0,0 +1,140 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import os | ||
| 4 | +from pathlib import Path | ||
| 5 | +import sys | ||
| 6 | + | ||
| 7 | +LOG_LEVELS = {"debug": 10, "info": 20, "warn": 30, "warning": 30, "error": 40} | ||
| 8 | +DEFAULT_LOG_LEVEL = "info" | ||
| 9 | + | ||
| 10 | +PIPELINE_MODES = ("simulate", "real") | ||
| 11 | +PIPELINE_MODE_DEFAULT = "simulate" | ||
| 12 | + | ||
| 13 | +_active_level = LOG_LEVELS[DEFAULT_LOG_LEVEL] | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +class ConfigError(Exception): | ||
| 17 | + pass | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def set_log_level(name: str) -> None: | ||
| 21 | + global _active_level | ||
| 22 | + level = LOG_LEVELS.get(name.strip().lower()) | ||
| 23 | + if level is None: | ||
| 24 | + raise ConfigError( | ||
| 25 | + f"LOG_LEVEL gecersiz: '{name}' (beklenen: {', '.join(sorted(LOG_LEVELS))})" | ||
| 26 | + ) | ||
| 27 | + _active_level = level | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def log(level: str, message: str) -> None: | ||
| 31 | + if LOG_LEVELS.get(level, LOG_LEVELS[DEFAULT_LOG_LEVEL]) >= _active_level: | ||
| 32 | + print(f"[bridge] {message}", flush=True) | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +def env_str(name: str, default: str) -> str: | ||
| 36 | + value = os.environ.get(name) | ||
| 37 | + return value if value is not None and value.strip() else default | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +def env_int(name: str, default: int, minimum: int, maximum: int) -> int: | ||
| 41 | + raw = os.environ.get(name) | ||
| 42 | + if raw is None or not raw.strip(): | ||
| 43 | + return default | ||
| 44 | + try: | ||
| 45 | + value = int(raw.strip()) | ||
| 46 | + except ValueError as exc: | ||
| 47 | + raise ConfigError(f"{name} bir tamsayi olmali, alinan: '{raw}'") from exc | ||
| 48 | + if value < minimum or value > maximum: | ||
| 49 | + raise ConfigError(f"{name} {minimum}..{maximum} araliginda olmali, alinan: {value}") | ||
| 50 | + return value | ||
| 51 | + | ||
| 52 | + | ||
| 53 | +def env_choice(name: str, default: str, choices: tuple[str, ...]) -> str: | ||
| 54 | + raw = os.environ.get(name) | ||
| 55 | + if raw is None or not raw.strip(): | ||
| 56 | + return default | ||
| 57 | + value = raw.strip().lower() | ||
| 58 | + if value not in choices: | ||
| 59 | + raise ConfigError( | ||
| 60 | + f"{name} su degerlerden biri olmali: {', '.join(choices)}; alinan: '{raw}'" | ||
| 61 | + ) | ||
| 62 | + return value | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +def env_float(name: str, default: float, minimum: float, maximum: float) -> float: | ||
| 66 | + raw = os.environ.get(name) | ||
| 67 | + if raw is None or not raw.strip(): | ||
| 68 | + return default | ||
| 69 | + try: | ||
| 70 | + value = float(raw.strip()) | ||
| 71 | + except ValueError as exc: | ||
| 72 | + raise ConfigError(f"{name} bir sayi olmali, alinan: '{raw}'") from exc | ||
| 73 | + if value < minimum or value > maximum: | ||
| 74 | + raise ConfigError(f"{name} {minimum}..{maximum} araliginda olmali, alinan: {value}") | ||
| 75 | + return value | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def _absolute(path: str) -> str: | ||
| 79 | + if not path: | ||
| 80 | + return path | ||
| 81 | + return str(Path(path).expanduser().resolve()) | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +class Config: | ||
| 85 | + def __init__(self, require_token: bool = True) -> None: | ||
| 86 | + self.log_level = env_str("LOG_LEVEL", DEFAULT_LOG_LEVEL) | ||
| 87 | + set_log_level(self.log_level) | ||
| 88 | + self.host = env_str("AI_BRIDGE_HOST", "hezarfen-backend") | ||
| 89 | + self.port = env_int("AI_BRIDGE_PORT", 8090, 1, 65535) | ||
| 90 | + self.backend_url = env_str("AI_BACKEND_URL", "http://hezarfen-backend:8080").rstrip("/") | ||
| 91 | + self.server_name = env_str("AI_TLS_SERVER_NAME", "localhost") | ||
| 92 | + self.service = env_str("AI_SERVICE_NAME", "podcast") | ||
| 93 | + self.max_concurrent = env_int("AI_MAX_CONCURRENT", 2, 1, 64) | ||
| 94 | + self.reconnect_secs = env_float("AI_RECONNECT_SECS", 3.0, 0.1, 300.0) | ||
| 95 | + self.token = env_str("AI_SHARED_TOKEN", "") | ||
| 96 | + self.has_token = bool(self.token) | ||
| 97 | + self.job_root = _absolute(env_str("PODCAST_JOB_ROOT", "/data/podcast/jobs")) | ||
| 98 | + self.workers = env_int("PODCAST_WORKERS", 1, 1, 32) | ||
| 99 | + self.max_jobs = env_int("PODCAST_MAX_JOBS", 8, 1, 4096) | ||
| 100 | + self.retention_days = env_float("PODCAST_RETENTION_DAYS", 0.0, 0.0, 3650.0) | ||
| 101 | + self.stage_secs = env_float("PODCAST_STAGE_SECS", 0.2, 0.0, 3600.0) | ||
| 102 | + self.eta_secs = env_float("PODCAST_ETA_SECS", 0.0, 0.0, 86400.0) | ||
| 103 | + self.media_root = _absolute(env_str("PODCAST_MEDIA_ROOT", "/data/files")) | ||
| 104 | + self.mode = env_choice("PODCAST_MODE", PIPELINE_MODE_DEFAULT, PIPELINE_MODES) | ||
| 105 | + self.pipeline_path = env_str("PODCAST_PIPELINE_PATH", "") | ||
| 106 | + self.output_root = _absolute(env_str("PODCAST_OUTPUT_ROOT", "/data/podcast/out")) | ||
| 107 | + self.ledger_db = _absolute(env_str("PODCAST_LEDGER_DB", "/data/podcast/router.sqlite")) | ||
| 108 | + self.chapter_limit = env_int("PODCAST_CHAPTER_LIMIT", 1, -1, 4096) | ||
| 109 | + self.tts_engine = env_str("PODCAST_TTS_ENGINE", "supertonic-3") | ||
| 110 | + self.has_llm_key = bool(os.environ.get("DEEPSEEK_API_KEY", "").strip()) | ||
| 111 | + if require_token and not self.has_token: | ||
| 112 | + raise ConfigError( | ||
| 113 | + "AI_SHARED_TOKEN tanimli degil; backend ile ayni sir olmadan kayit yapilamaz" | ||
| 114 | + ) | ||
| 115 | + | ||
| 116 | + def summary(self) -> str: | ||
| 117 | + return ( | ||
| 118 | + f"servis='{self.service}' hedef={self.host}:{self.port} " | ||
| 119 | + f"backend={self.backend_url} tls_ad={self.server_name} " | ||
| 120 | + f"max_es_zamanli={self.max_concurrent} yeniden_baglanma={self.reconnect_secs}s " | ||
| 121 | + f"log={self.log_level} token={'tanimli' if self.has_token else 'TANIMSIZ'} " | ||
| 122 | + f"is_kok={self.job_root} isciler={self.workers} max_is={self.max_jobs} " | ||
| 123 | + f"asama={self.stage_secs}s " | ||
| 124 | + f"eta={'otomatik' if self.eta_secs <= 0 else str(self.eta_secs) + 's'} " | ||
| 125 | + f"medya_kok={self.media_root} mod={self.mode} " | ||
| 126 | + f"hat_yolu={self.pipeline_path if self.pipeline_path else 'TANIMSIZ'} " | ||
| 127 | + f"cikti_kok={self.output_root} defter={self.ledger_db} " | ||
| 128 | + f"retention={self.retention_days:g}g " | ||
| 129 | + f"bolum_limiti={'hepsi' if self.chapter_limit <= 0 else self.chapter_limit} " | ||
| 130 | + f"tts={self.tts_engine} " | ||
| 131 | + f"llm_anahtari={'tanimli' if self.has_llm_key else 'TANIMSIZ'}" | ||
| 132 | + ) | ||
| 133 | + | ||
| 134 | + | ||
| 135 | +def load(require_token: bool = True) -> Config: | ||
| 136 | + try: | ||
| 137 | + return Config(require_token=require_token) | ||
| 138 | + except ConfigError as exc: | ||
| 139 | + print(f"[bridge] yapilandirma hatasi: {exc}", flush=True) | ||
| 140 | + sys.exit(2) | ||
src/jobs.pyadded+644 -0
| @@ -0,0 +1,644 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import json | ||
| 4 | +import math | ||
| 5 | +import os | ||
| 6 | +import queue | ||
| 7 | +import re | ||
| 8 | +import secrets | ||
| 9 | +import threading | ||
| 10 | +import time | ||
| 11 | +import zlib | ||
| 12 | +from pathlib import Path | ||
| 13 | +from typing import Any, Callable | ||
| 14 | + | ||
| 15 | +from . import config | ||
| 16 | + | ||
| 17 | +STATE_QUEUED = "queued" | ||
| 18 | +STATE_RUNNING = "running" | ||
| 19 | +STATE_DONE = "done" | ||
| 20 | +STATE_FAILED = "failed" | ||
| 21 | +STATE_CANCELLED = "cancelled" | ||
| 22 | + | ||
| 23 | +STATES = (STATE_QUEUED, STATE_RUNNING, STATE_DONE, STATE_FAILED, STATE_CANCELLED) | ||
| 24 | +TERMINAL_STATES = (STATE_DONE, STATE_FAILED, STATE_CANCELLED) | ||
| 25 | +DAY_MS = 86_400_000 | ||
| 26 | + | ||
| 27 | +TRANSITIONS: dict[str, tuple[str, ...]] = { | ||
| 28 | + STATE_QUEUED: (STATE_RUNNING, STATE_CANCELLED, STATE_FAILED), | ||
| 29 | + STATE_RUNNING: (STATE_DONE, STATE_FAILED, STATE_CANCELLED), | ||
| 30 | + STATE_DONE: (), | ||
| 31 | + STATE_FAILED: (), | ||
| 32 | + STATE_CANCELLED: (), | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +SIMULATED_STAGES = ("ocr", "plan", "script", "tts", "mux") | ||
| 36 | +INTERRUPTED_CODE = "interrupted" | ||
| 37 | + | ||
| 38 | +REQUIRED_FIELDS = ( | ||
| 39 | + "job_id", | ||
| 40 | + "source_id", | ||
| 41 | + "format", | ||
| 42 | + "state", | ||
| 43 | + "stage", | ||
| 44 | + "progress", | ||
| 45 | + "error_code", | ||
| 46 | + "cancel_requested", | ||
| 47 | + "audio_id", | ||
| 48 | + "duration_secs", | ||
| 49 | + "script_id", | ||
| 50 | + "created_at", | ||
| 51 | + "updated_at", | ||
| 52 | +) | ||
| 53 | + | ||
| 54 | +SAFE_SOURCE_ID = re.compile(r"^[A-Za-z0-9._-]{1,128}$") | ||
| 55 | + | ||
| 56 | +SHUTDOWN_TIMEOUT_SECS = 10.0 | ||
| 57 | + | ||
| 58 | +STATUS_FILE = ".bridge-status" | ||
| 59 | + | ||
| 60 | +_CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" | ||
| 61 | +JOB_ID_LENGTH = 26 | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +class JobError(Exception): | ||
| 65 | + pass | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +class JobNotFound(JobError): | ||
| 69 | + def __init__(self, job_id: str) -> None: | ||
| 70 | + super().__init__(f"is bulunamadi: {job_id}") | ||
| 71 | + self.job_id = job_id | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +class JobStoreFull(JobError): | ||
| 75 | + def __init__(self, active: int, limit: int) -> None: | ||
| 76 | + super().__init__(f"is kuyrugu dolu: {active}/{limit} is beklemede veya kosuyor") | ||
| 77 | + self.active = active | ||
| 78 | + self.limit = limit | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +class InvalidTransition(JobError): | ||
| 82 | + def __init__(self, current: str, target: str) -> None: | ||
| 83 | + super().__init__(f"gecersiz durum gecisi: {current} -> {target}") | ||
| 84 | + self.current = current | ||
| 85 | + self.target = target | ||
| 86 | + | ||
| 87 | + | ||
| 88 | +class JobCancelled(JobError): | ||
| 89 | + def __init__(self, job_id: str) -> None: | ||
| 90 | + super().__init__(f"is iptal edildi: {job_id}") | ||
| 91 | + self.job_id = job_id | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +def new_job_id() -> str: | ||
| 95 | + value = (int(time.time() * 1000) << 80) | secrets.randbits(80) | ||
| 96 | + chars = [] | ||
| 97 | + for _ in range(JOB_ID_LENGTH): | ||
| 98 | + chars.append(_CROCKFORD[value & 31]) | ||
| 99 | + value >>= 5 | ||
| 100 | + return "".join(reversed(chars)) | ||
| 101 | + | ||
| 102 | + | ||
| 103 | +def _now_ms() -> int: | ||
| 104 | + return int(time.time() * 1000) | ||
| 105 | + | ||
| 106 | + | ||
| 107 | +def _id_list(values: list[str] | None, fallback: str) -> list[str]: | ||
| 108 | + if values: | ||
| 109 | + return [str(value) for value in values] | ||
| 110 | + return [str(fallback)] if fallback else [] | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +def can_transition(current: str, target: str) -> bool: | ||
| 114 | + return target in TRANSITIONS.get(current, ()) | ||
| 115 | + | ||
| 116 | + | ||
| 117 | +def resolve_source(media_root: str | os.PathLike, source_id: str) -> Path: | ||
| 118 | + if not isinstance(source_id, str) or SAFE_SOURCE_ID.match(source_id) is None: | ||
| 119 | + raise ValueError(f"gecersiz source_id: {source_id!r}") | ||
| 120 | + root = Path(media_root).resolve() | ||
| 121 | + candidate = (root / source_id).resolve() | ||
| 122 | + if candidate == root or root not in candidate.parents: | ||
| 123 | + raise ValueError(f"source_id medya kokunun disina cikiyor: {source_id!r}") | ||
| 124 | + return candidate | ||
| 125 | + | ||
| 126 | + | ||
| 127 | +def status_path(root: str | os.PathLike) -> Path: | ||
| 128 | + return Path(root) / STATUS_FILE | ||
| 129 | + | ||
| 130 | + | ||
| 131 | +def write_status(root: str | os.PathLike, registered: bool, worker_id: str = "") -> None: | ||
| 132 | + path = status_path(root) | ||
| 133 | + record = { | ||
| 134 | + "registered": bool(registered), | ||
| 135 | + "worker_id": str(worker_id), | ||
| 136 | + "pid": os.getpid(), | ||
| 137 | + "updated_at": _now_ms(), | ||
| 138 | + } | ||
| 139 | + tmp = path.parent / f"{path.name}.tmp{os.getpid()}-{secrets.token_hex(4)}" | ||
| 140 | + try: | ||
| 141 | + with open(tmp, "w", encoding="utf-8") as handle: | ||
| 142 | + json.dump(record, handle, ensure_ascii=False) | ||
| 143 | + handle.flush() | ||
| 144 | + os.fsync(handle.fileno()) | ||
| 145 | + os.replace(tmp, path) | ||
| 146 | + except OSError as exc: | ||
| 147 | + config.log("warn", f"kopru durum dosyasi yazilamadi: {exc}") | ||
| 148 | + try: | ||
| 149 | + tmp.unlink() | ||
| 150 | + except OSError: | ||
| 151 | + pass | ||
| 152 | + | ||
| 153 | + | ||
| 154 | +def read_status(root: str | os.PathLike) -> dict[str, Any] | None: | ||
| 155 | + try: | ||
| 156 | + with open(status_path(root), "r", encoding="utf-8") as handle: | ||
| 157 | + record = json.load(handle) | ||
| 158 | + except (OSError, ValueError): | ||
| 159 | + return None | ||
| 160 | + return record if isinstance(record, dict) else None | ||
| 161 | + | ||
| 162 | + | ||
| 163 | +class JobContext: | ||
| 164 | + def __init__(self, store: "JobStore", job_id: str) -> None: | ||
| 165 | + record = store.get(job_id) | ||
| 166 | + self.store = store | ||
| 167 | + self.job_id = job_id | ||
| 168 | + self.source_id = record["source_id"] | ||
| 169 | + self.format = record["format"] | ||
| 170 | + self.stages = store.stages | ||
| 171 | + | ||
| 172 | + def cancelled(self) -> bool: | ||
| 173 | + if self.store.stopping: | ||
| 174 | + return True | ||
| 175 | + return self.store.cancel_requested(self.job_id) | ||
| 176 | + | ||
| 177 | + def check(self) -> None: | ||
| 178 | + if self.cancelled(): | ||
| 179 | + raise JobCancelled(self.job_id) | ||
| 180 | + | ||
| 181 | + def progress(self, stage: str, value: float) -> dict[str, Any] | None: | ||
| 182 | + return self.store.update_progress(self.job_id, stage, value) | ||
| 183 | + | ||
| 184 | + def finish( | ||
| 185 | + self, | ||
| 186 | + audio_id: str, | ||
| 187 | + duration_secs: float, | ||
| 188 | + script_id: str, | ||
| 189 | + audio_ids: list[str] | None = None, | ||
| 190 | + script_ids: list[str] | None = None, | ||
| 191 | + ) -> dict[str, Any]: | ||
| 192 | + return self.store.finish( | ||
| 193 | + self.job_id, | ||
| 194 | + audio_id=audio_id, | ||
| 195 | + duration_secs=duration_secs, | ||
| 196 | + script_id=script_id, | ||
| 197 | + audio_ids=audio_ids, | ||
| 198 | + script_ids=script_ids, | ||
| 199 | + ) | ||
| 200 | + | ||
| 201 | + | ||
| 202 | +def _simulate_pipeline(ctx: JobContext) -> None: | ||
| 203 | + stages = ctx.stages | ||
| 204 | + total = len(stages) | ||
| 205 | + for index, stage in enumerate(stages): | ||
| 206 | + ctx.check() | ||
| 207 | + ctx.progress(stage, index / total) | ||
| 208 | + if ctx.store.stage_secs > 0: | ||
| 209 | + time.sleep(ctx.store.stage_secs) | ||
| 210 | + ctx.check() | ||
| 211 | + suffix = ctx.job_id[-10:].lower() | ||
| 212 | + checksum = zlib.crc32(ctx.job_id.encode("ascii")) | ||
| 213 | + record = ctx.finish( | ||
| 214 | + audio_id=f"sim_audio_{suffix}", | ||
| 215 | + duration_secs=round(240.0 + (checksum % 12000) / 100.0, 2), | ||
| 216 | + script_id=f"sim_script_{suffix}", | ||
| 217 | + ) | ||
| 218 | + if record["state"] == STATE_DONE: | ||
| 219 | + config.log("info", f"is {ctx.job_id} tamamlandi (sahte hat)") | ||
| 220 | + else: | ||
| 221 | + config.log("info", f"is {ctx.job_id} bitis aninda iptal edildi") | ||
| 222 | + | ||
| 223 | + | ||
| 224 | +class JobStore: | ||
| 225 | + def __init__( | ||
| 226 | + self, | ||
| 227 | + root: str | os.PathLike, | ||
| 228 | + workers: int = 1, | ||
| 229 | + max_jobs: int = 8, | ||
| 230 | + stage_secs: float = 0.2, | ||
| 231 | + runner: Callable[[JobContext], None] | None = None, | ||
| 232 | + stages: tuple[str, ...] | None = None, | ||
| 233 | + job_secs: float | None = None, | ||
| 234 | + retention_days: float = 0.0, | ||
| 235 | + output_root: str | os.PathLike | None = None, | ||
| 236 | + ) -> None: | ||
| 237 | + self.root = Path(root) | ||
| 238 | + self.workers = max(1, int(workers)) | ||
| 239 | + self.max_jobs = max(1, int(max_jobs)) | ||
| 240 | + self.stage_secs = float(stage_secs) | ||
| 241 | + self.stages = tuple(stages) if stages else SIMULATED_STAGES | ||
| 242 | + self.job_secs = ( | ||
| 243 | + float(job_secs) if job_secs else max(len(self.stages) * self.stage_secs, 1.0) | ||
| 244 | + ) | ||
| 245 | + self.retention_days = max(0.0, float(retention_days)) | ||
| 246 | + self.output_root = Path(output_root) if output_root else None | ||
| 247 | + self._runner = runner or _simulate_pipeline | ||
| 248 | + self._lock = threading.RLock() | ||
| 249 | + self._jobs: dict[str, dict[str, Any]] = {} | ||
| 250 | + self._queue: queue.Queue = queue.Queue() | ||
| 251 | + self._threads: list[threading.Thread] = [] | ||
| 252 | + self._stopping = threading.Event() | ||
| 253 | + self.root.mkdir(parents=True, exist_ok=True) | ||
| 254 | + self.swept = self._load() | ||
| 255 | + | ||
| 256 | + @property | ||
| 257 | + def stopping(self) -> bool: | ||
| 258 | + return self._stopping.is_set() | ||
| 259 | + | ||
| 260 | + def _path(self, job_id: str) -> Path: | ||
| 261 | + return self.root / f"{job_id}.json" | ||
| 262 | + | ||
| 263 | + def _fsync_dir(self) -> None: | ||
| 264 | + try: | ||
| 265 | + handle = os.open(self.root, os.O_RDONLY) | ||
| 266 | + except OSError: | ||
| 267 | + return | ||
| 268 | + try: | ||
| 269 | + os.fsync(handle) | ||
| 270 | + except OSError: | ||
| 271 | + pass | ||
| 272 | + finally: | ||
| 273 | + os.close(handle) | ||
| 274 | + | ||
| 275 | + def _write(self, record: dict[str, Any]) -> None: | ||
| 276 | + path = self._path(record["job_id"]) | ||
| 277 | + tmp = path.parent / f"{path.name}.tmp{os.getpid()}-{secrets.token_hex(4)}" | ||
| 278 | + with open(tmp, "w", encoding="utf-8") as handle: | ||
| 279 | + json.dump(record, handle, ensure_ascii=False) | ||
| 280 | + handle.flush() | ||
| 281 | + os.fsync(handle.fileno()) | ||
| 282 | + os.replace(tmp, path) | ||
| 283 | + self._fsync_dir() | ||
| 284 | + | ||
| 285 | + def _commit(self, record: dict[str, Any], candidate: dict[str, Any]) -> None: | ||
| 286 | + self._write(candidate) | ||
| 287 | + record.clear() | ||
| 288 | + record.update(candidate) | ||
| 289 | + | ||
| 290 | + def _purge_temporaries(self) -> None: | ||
| 291 | + residues = sorted(self.root.glob("*.json.tmp*")) + sorted( | ||
| 292 | + self.root.glob(f"{STATUS_FILE}.tmp*") | ||
| 293 | + ) | ||
| 294 | + for path in residues: | ||
| 295 | + try: | ||
| 296 | + path.unlink() | ||
| 297 | + except OSError as exc: | ||
| 298 | + config.log("warn", f"gecici is dosyasi silinemedi: {path.name} ({exc})") | ||
| 299 | + | ||
| 300 | + def _safe_output_path(self, identifier: Any) -> Path | None: | ||
| 301 | + if self.output_root is None: | ||
| 302 | + return None | ||
| 303 | + if not isinstance(identifier, str) or not identifier.strip(): | ||
| 304 | + return None | ||
| 305 | + if identifier.startswith(("/", "\\")) or ":" in identifier: | ||
| 306 | + return None | ||
| 307 | + try: | ||
| 308 | + root = self.output_root.resolve() | ||
| 309 | + target = (root / identifier).resolve() | ||
| 310 | + except OSError: | ||
| 311 | + return None | ||
| 312 | + if target == root or root not in target.parents: | ||
| 313 | + return None | ||
| 314 | + return target | ||
| 315 | + | ||
| 316 | + def _purge_expired(self) -> int: | ||
| 317 | + if self.retention_days <= 0: | ||
| 318 | + return 0 | ||
| 319 | + cutoff = _now_ms() - int(self.retention_days * DAY_MS) | ||
| 320 | + removed = 0 | ||
| 321 | + for job_id, record in list(self._jobs.items()): | ||
| 322 | + if record.get("state") not in TERMINAL_STATES: | ||
| 323 | + continue | ||
| 324 | + try: | ||
| 325 | + updated = int(record.get("updated_at") or 0) | ||
| 326 | + except (TypeError, ValueError): | ||
| 327 | + continue | ||
| 328 | + if updated >= cutoff: | ||
| 329 | + continue | ||
| 330 | + for field in ("audio_ids", "script_ids"): | ||
| 331 | + for identifier in (record.get(field) or []): | ||
| 332 | + path = self._safe_output_path(identifier) | ||
| 333 | + if path is None: | ||
| 334 | + config.log( | ||
| 335 | + "warn", | ||
| 336 | + f"is {job_id}: cikti kimligi cikti kokunun disinda, " | ||
| 337 | + f"SILINMEDI: {identifier!r}", | ||
| 338 | + ) | ||
| 339 | + continue | ||
| 340 | + try: | ||
| 341 | + path.unlink(missing_ok=True) | ||
| 342 | + except OSError as exc: | ||
| 343 | + config.log("warn", f"cikti silinemedi {path.name}: {exc}") | ||
| 344 | + try: | ||
| 345 | + self._path(job_id).unlink(missing_ok=True) | ||
| 346 | + except OSError as exc: | ||
| 347 | + config.log("warn", f"is dosyasi silinemedi {job_id}: {exc}") | ||
| 348 | + continue | ||
| 349 | + self._jobs.pop(job_id, None) | ||
| 350 | + removed += 1 | ||
| 351 | + if removed: | ||
| 352 | + config.log( | ||
| 353 | + "info", | ||
| 354 | + f"retention: {self.retention_days:g} gunden eski {removed} bitmis is " | ||
| 355 | + f"ve ciktilari silindi", | ||
| 356 | + ) | ||
| 357 | + return removed | ||
| 358 | + | ||
| 359 | + def _load(self) -> int: | ||
| 360 | + self._purge_temporaries() | ||
| 361 | + swept = 0 | ||
| 362 | + for path in sorted(self.root.glob("*.json")): | ||
| 363 | + try: | ||
| 364 | + with open(path, "r", encoding="utf-8") as handle: | ||
| 365 | + record = json.load(handle) | ||
| 366 | + except (OSError, ValueError) as exc: | ||
| 367 | + config.log("warn", f"is dosyasi okunamadi, atlandi: {path.name} ({exc})") | ||
| 368 | + continue | ||
| 369 | + if not isinstance(record, dict): | ||
| 370 | + continue | ||
| 371 | + job_id = record.get("job_id") | ||
| 372 | + if not isinstance(job_id, str) or job_id != path.stem: | ||
| 373 | + config.log("warn", f"is dosyasi kimligi adiyla uyusmuyor, atlandi: {path.name}") | ||
| 374 | + continue | ||
| 375 | + missing = [name for name in REQUIRED_FIELDS if name not in record] | ||
| 376 | + if missing: | ||
| 377 | + config.log( | ||
| 378 | + "warn", | ||
| 379 | + f"is dosyasinda zorunlu alan eksik, atlandi: {path.name} " | ||
| 380 | + f"({', '.join(missing)})", | ||
| 381 | + ) | ||
| 382 | + continue | ||
| 383 | + if record["state"] not in STATES: | ||
| 384 | + config.log("warn", f"is dosyasi gecersiz durumda, atlandi: {path.name}") | ||
| 385 | + continue | ||
| 386 | + if record["state"] == STATE_RUNNING: | ||
| 387 | + candidate = dict(record) | ||
| 388 | + candidate["state"] = STATE_FAILED | ||
| 389 | + candidate["error_code"] = INTERRUPTED_CODE | ||
| 390 | + candidate["updated_at"] = _now_ms() | ||
| 391 | + try: | ||
| 392 | + self._commit(record, candidate) | ||
| 393 | + except OSError as exc: | ||
| 394 | + config.log("error", f"supurme yazilamadi {job_id}: {exc}") | ||
| 395 | + else: | ||
| 396 | + swept += 1 | ||
| 397 | + self._jobs[job_id] = record | ||
| 398 | + self.purged = self._purge_expired() | ||
| 399 | + return swept | ||
| 400 | + | ||
| 401 | + def start(self) -> int: | ||
| 402 | + with self._lock: | ||
| 403 | + if not self._threads: | ||
| 404 | + self._stopping.clear() | ||
| 405 | + for index in range(self.workers): | ||
| 406 | + thread = threading.Thread( | ||
| 407 | + target=self._worker_loop, | ||
| 408 | + name=f"podcast-job-{index}", | ||
| 409 | + daemon=True, | ||
| 410 | + ) | ||
| 411 | + self._threads.append(thread) | ||
| 412 | + thread.start() | ||
| 413 | + pending = [ | ||
| 414 | + record["job_id"] | ||
| 415 | + for record in self._jobs.values() | ||
| 416 | + if record["state"] == STATE_QUEUED | ||
| 417 | + ] | ||
| 418 | + for job_id in pending: | ||
| 419 | + self._dispatch(job_id) | ||
| 420 | + return len(pending) | ||
| 421 | + | ||
| 422 | + def shutdown(self, timeout: float = SHUTDOWN_TIMEOUT_SECS) -> None: | ||
| 423 | + self._stopping.set() | ||
| 424 | + with self._lock: | ||
| 425 | + threads = list(self._threads) | ||
| 426 | + self._threads.clear() | ||
| 427 | + running = [ | ||
| 428 | + record | ||
| 429 | + for record in self._jobs.values() | ||
| 430 | + if record["state"] == STATE_RUNNING and not record["cancel_requested"] | ||
| 431 | + ] | ||
| 432 | + for record in running: | ||
| 433 | + candidate = dict(record) | ||
| 434 | + candidate["cancel_requested"] = True | ||
| 435 | + candidate["updated_at"] = _now_ms() | ||
| 436 | + try: | ||
| 437 | + self._commit(record, candidate) | ||
| 438 | + except OSError as exc: | ||
| 439 | + config.log( | ||
| 440 | + "warn", | ||
| 441 | + f"kapanista iptal bayragi yazilamadi {record['job_id']}: {exc}", | ||
| 442 | + ) | ||
| 443 | + for _ in threads: | ||
| 444 | + self._queue.put(None) | ||
| 445 | + deadline = time.monotonic() + max(0.0, float(timeout)) | ||
| 446 | + stuck = 0 | ||
| 447 | + for thread in threads: | ||
| 448 | + thread.join(timeout=max(0.0, deadline - time.monotonic())) | ||
| 449 | + if thread.is_alive(): | ||
| 450 | + stuck += 1 | ||
| 451 | + if stuck: | ||
| 452 | + config.log( | ||
| 453 | + "warn", | ||
| 454 | + f"kapanista {stuck} isci thread {timeout}s icinde bitmedi; " | ||
| 455 | + f"daemon olduklari icin surec yine de cikabiliyor", | ||
| 456 | + ) | ||
| 457 | + | ||
| 458 | + def _dispatch(self, job_id: str) -> None: | ||
| 459 | + self._queue.put(job_id) | ||
| 460 | + | ||
| 461 | + def _worker_loop(self) -> None: | ||
| 462 | + while True: | ||
| 463 | + job_id = self._queue.get() | ||
| 464 | + if job_id is None: | ||
| 465 | + return | ||
| 466 | + try: | ||
| 467 | + self._work(job_id) | ||
| 468 | + except Exception as exc: | ||
| 469 | + config.log("error", f"isci dongusu {job_id} isini isleyemedi: {exc}") | ||
| 470 | + | ||
| 471 | + def _work(self, job_id: str) -> None: | ||
| 472 | + try: | ||
| 473 | + if not self.begin(job_id): | ||
| 474 | + return | ||
| 475 | + self._runner(JobContext(self, job_id)) | ||
| 476 | + except JobCancelled: | ||
| 477 | + try: | ||
| 478 | + self.abort(job_id) | ||
| 479 | + config.log("info", f"is {job_id} iptal edildi") | ||
| 480 | + except JobError: | ||
| 481 | + pass | ||
| 482 | + except Exception as exc: | ||
| 483 | + config.log("error", f"is {job_id} beklenmedik sekilde bitti: {exc}") | ||
| 484 | + try: | ||
| 485 | + self.fail(job_id, "internal") | ||
| 486 | + except JobError as inner: | ||
| 487 | + config.log("warn", f"is {job_id} hata durumuna alinamadi: {inner}") | ||
| 488 | + | ||
| 489 | + def _active_count(self) -> int: | ||
| 490 | + return sum( | ||
| 491 | + 1 | ||
| 492 | + for record in self._jobs.values() | ||
| 493 | + if record["state"] in (STATE_QUEUED, STATE_RUNNING) | ||
| 494 | + ) | ||
| 495 | + | ||
| 496 | + def estimate_eta(self, pending: int) -> int: | ||
| 497 | + waves = max(1, math.ceil(max(pending, 1) / self.workers)) | ||
| 498 | + return int(math.ceil(self.job_secs * waves)) | ||
| 499 | + | ||
| 500 | + def submit(self, source_id: str, job_format: str) -> tuple[dict[str, Any], int]: | ||
| 501 | + now = _now_ms() | ||
| 502 | + with self._lock: | ||
| 503 | + active = self._active_count() | ||
| 504 | + if active >= self.max_jobs: | ||
| 505 | + raise JobStoreFull(active, self.max_jobs) | ||
| 506 | + job_id = new_job_id() | ||
| 507 | + record = { | ||
| 508 | + "job_id": job_id, | ||
| 509 | + "source_id": source_id, | ||
| 510 | + "format": job_format, | ||
| 511 | + "state": STATE_QUEUED, | ||
| 512 | + "stage": "", | ||
| 513 | + "progress": 0.0, | ||
| 514 | + "error_code": None, | ||
| 515 | + "cancel_requested": False, | ||
| 516 | + "audio_id": None, | ||
| 517 | + "duration_secs": None, | ||
| 518 | + "script_id": None, | ||
| 519 | + "audio_ids": [], | ||
| 520 | + "script_ids": [], | ||
| 521 | + "created_at": now, | ||
| 522 | + "updated_at": now, | ||
| 523 | + } | ||
| 524 | + self._write(record) | ||
| 525 | + self._jobs[job_id] = record | ||
| 526 | + eta = self.estimate_eta(active + 1) | ||
| 527 | + snapshot = dict(record) | ||
| 528 | + config.log("info", f"is {job_id} kuyruga alindi (format={job_format} eta={eta}s)") | ||
| 529 | + self._dispatch(job_id) | ||
| 530 | + return snapshot, eta | ||
| 531 | + | ||
| 532 | + def get(self, job_id: str) -> dict[str, Any]: | ||
| 533 | + with self._lock: | ||
| 534 | + record = self._jobs.get(job_id) | ||
| 535 | + if record is None: | ||
| 536 | + raise JobNotFound(job_id) | ||
| 537 | + return dict(record) | ||
| 538 | + | ||
| 539 | + def transition(self, job_id: str, target: str, **fields: Any) -> dict[str, Any]: | ||
| 540 | + with self._lock: | ||
| 541 | + record = self._jobs.get(job_id) | ||
| 542 | + if record is None: | ||
| 543 | + raise JobNotFound(job_id) | ||
| 544 | + current = record["state"] | ||
| 545 | + if not can_transition(current, target): | ||
| 546 | + raise InvalidTransition(current, target) | ||
| 547 | + candidate = dict(record) | ||
| 548 | + candidate["state"] = target | ||
| 549 | + candidate.update(fields) | ||
| 550 | + candidate["updated_at"] = _now_ms() | ||
| 551 | + self._commit(record, candidate) | ||
| 552 | + return dict(record) | ||
| 553 | + | ||
| 554 | + def update_progress( | ||
| 555 | + self, job_id: str, stage: str, progress: float | ||
| 556 | + ) -> dict[str, Any] | None: | ||
| 557 | + with self._lock: | ||
| 558 | + record = self._jobs.get(job_id) | ||
| 559 | + if record is None: | ||
| 560 | + raise JobNotFound(job_id) | ||
| 561 | + if record["state"] != STATE_RUNNING: | ||
| 562 | + return None | ||
| 563 | + candidate = dict(record) | ||
| 564 | + candidate["stage"] = stage | ||
| 565 | + candidate["progress"] = round(min(max(float(progress), 0.0), 1.0), 4) | ||
| 566 | + candidate["updated_at"] = _now_ms() | ||
| 567 | + self._commit(record, candidate) | ||
| 568 | + return dict(record) | ||
| 569 | + | ||
| 570 | + def begin(self, job_id: str) -> bool: | ||
| 571 | + with self._lock: | ||
| 572 | + record = self._jobs.get(job_id) | ||
| 573 | + if record is None or record["state"] != STATE_QUEUED: | ||
| 574 | + return False | ||
| 575 | + if self.stopping: | ||
| 576 | + return False | ||
| 577 | + if record["cancel_requested"]: | ||
| 578 | + self.transition(job_id, STATE_CANCELLED) | ||
| 579 | + config.log("info", f"is {job_id} baslamadan iptal edildi") | ||
| 580 | + return False | ||
| 581 | + self.transition(job_id, STATE_RUNNING, stage=self.stages[0], progress=0.0) | ||
| 582 | + return True | ||
| 583 | + | ||
| 584 | + def cancel_requested(self, job_id: str) -> bool: | ||
| 585 | + with self._lock: | ||
| 586 | + record = self._jobs.get(job_id) | ||
| 587 | + if record is None: | ||
| 588 | + raise JobNotFound(job_id) | ||
| 589 | + return bool(record["cancel_requested"]) | ||
| 590 | + | ||
| 591 | + def cancel(self, job_id: str) -> bool: | ||
| 592 | + with self._lock: | ||
| 593 | + record = self._jobs.get(job_id) | ||
| 594 | + if record is None: | ||
| 595 | + raise JobNotFound(job_id) | ||
| 596 | + state = record["state"] | ||
| 597 | + if state == STATE_QUEUED: | ||
| 598 | + self.transition(job_id, STATE_CANCELLED, cancel_requested=True, stage="") | ||
| 599 | + config.log("info", f"is {job_id} kuyruktan iptal edildi") | ||
| 600 | + return True | ||
| 601 | + if state == STATE_RUNNING: | ||
| 602 | + if not record["cancel_requested"]: | ||
| 603 | + candidate = dict(record) | ||
| 604 | + candidate["cancel_requested"] = True | ||
| 605 | + candidate["updated_at"] = _now_ms() | ||
| 606 | + self._commit(record, candidate) | ||
| 607 | + config.log("info", f"is {job_id} icin iptal bayragi kondu") | ||
| 608 | + return True | ||
| 609 | + return False | ||
| 610 | + | ||
| 611 | + def abort(self, job_id: str) -> dict[str, Any]: | ||
| 612 | + return self.transition(job_id, STATE_CANCELLED) | ||
| 613 | + | ||
| 614 | + def fail(self, job_id: str, error_code: str) -> dict[str, Any]: | ||
| 615 | + return self.transition(job_id, STATE_FAILED, error_code=error_code) | ||
| 616 | + | ||
| 617 | + def finish( | ||
| 618 | + self, | ||
| 619 | + job_id: str, | ||
| 620 | + audio_id: str, | ||
| 621 | + duration_secs: float, | ||
| 622 | + script_id: str, | ||
| 623 | + audio_ids: list[str] | None = None, | ||
| 624 | + script_ids: list[str] | None = None, | ||
| 625 | + ) -> dict[str, Any]: | ||
| 626 | + with self._lock: | ||
| 627 | + record = self._jobs.get(job_id) | ||
| 628 | + if record is None: | ||
| 629 | + raise JobNotFound(job_id) | ||
| 630 | + if record["cancel_requested"]: | ||
| 631 | + config.log("info", f"is {job_id} bitiste iptal bayragini gordu") | ||
| 632 | + return self.transition(job_id, STATE_CANCELLED) | ||
| 633 | + return self.transition( | ||
| 634 | + job_id, | ||
| 635 | + STATE_DONE, | ||
| 636 | + stage="done", | ||
| 637 | + progress=1.0, | ||
| 638 | + error_code=None, | ||
| 639 | + audio_id=audio_id, | ||
| 640 | + duration_secs=float(duration_secs), | ||
| 641 | + script_id=script_id, | ||
| 642 | + audio_ids=_id_list(audio_ids, audio_id), | ||
| 643 | + script_ids=_id_list(script_ids, script_id), | ||
| 644 | + ) | ||
src/main.pyadded+996 -0
| @@ -0,0 +1,996 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import argparse | ||
| 4 | +import asyncio | ||
| 5 | +import json | ||
| 6 | +import os | ||
| 7 | +import sys | ||
| 8 | +import tempfile | ||
| 9 | +import threading | ||
| 10 | +import time | ||
| 11 | +from pathlib import Path | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def _expect_error(problems: list[str], label: str, code: str, call, *args) -> None: | ||
| 15 | + from .protocol import CapabilityError | ||
| 16 | + | ||
| 17 | + try: | ||
| 18 | + call(*args) | ||
| 19 | + except CapabilityError as exc: | ||
| 20 | + if exc.code != code: | ||
| 21 | + problems.append(f"{label}: '{code}' yerine '{exc.code}' dondu") | ||
| 22 | + return | ||
| 23 | + problems.append(f"{label}: '{code}' hatasi beklenirken cevap dondu") | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def _guard(label: str, call, *args) -> list[str]: | ||
| 27 | + try: | ||
| 28 | + return call(*args) | ||
| 29 | + except Exception as exc: | ||
| 30 | + from . import capabilities | ||
| 31 | + | ||
| 32 | + capabilities.configure(None, llm_ready=False) | ||
| 33 | + return [f"{label} kontrolu beklenmedik sekilde patladi: {type(exc).__name__}: {exc}"] | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def _await_state(store, job_id: str, wanted: tuple[str, ...], deadline_secs: float): | ||
| 37 | + limit = time.monotonic() + deadline_secs | ||
| 38 | + while time.monotonic() < limit: | ||
| 39 | + record = store.get(job_id) | ||
| 40 | + if record["state"] in wanted: | ||
| 41 | + return record | ||
| 42 | + time.sleep(0.005) | ||
| 43 | + return store.get(job_id) | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def _check_registry(root: str) -> list[str]: | ||
| 47 | + from . import capabilities, jobs | ||
| 48 | + | ||
| 49 | + problems: list[str] = [] | ||
| 50 | + locked = ("tek_ogretici", "ogrenci_hoca", "duz_okuma") | ||
| 51 | + if tuple(capabilities.FORMATS) != locked: | ||
| 52 | + problems.append( | ||
| 53 | + f"format kumesi projenin kilitli sozlesmesinden sapmis: {capabilities.FORMATS}" | ||
| 54 | + ) | ||
| 55 | + if capabilities.DEFAULT_FORMAT != "duz_okuma": | ||
| 56 | + problems.append( | ||
| 57 | + f"varsayilan format hattinkiyle uyusmuyor: {capabilities.DEFAULT_FORMAT}" | ||
| 58 | + ) | ||
| 59 | + if capabilities.KEYLESS_FORMATS != ("duz_okuma",): | ||
| 60 | + problems.append( | ||
| 61 | + f"anahtarsiz format kumesi beklenenden farkli: {capabilities.KEYLESS_FORMATS}" | ||
| 62 | + ) | ||
| 63 | + | ||
| 64 | + if problems: | ||
| 65 | + return problems | ||
| 66 | + | ||
| 67 | + expected = {"podcast.submit", "podcast.status", "podcast.result", "podcast.cancel"} | ||
| 68 | + found = set(capabilities.names()) | ||
| 69 | + if found != expected: | ||
| 70 | + problems.append(f"yetenek kumesi beklenenden farkli: {sorted(found)}") | ||
| 71 | + for name, handler in capabilities.REGISTRY.items(): | ||
| 72 | + if not callable(handler): | ||
| 73 | + problems.append(f"{name} icin isleyici cagrilabilir degil") | ||
| 74 | + | ||
| 75 | + store = jobs.JobStore(root=os.path.join(root, "registry"), workers=1, max_jobs=8, stage_secs=0.0) | ||
| 76 | + capabilities.configure(store, llm_ready=False) | ||
| 77 | + | ||
| 78 | + submitted = capabilities.dispatch("podcast.submit", {"source_id": "ornek"}) | ||
| 79 | + job_id = str(submitted.get("job_id", "")) | ||
| 80 | + if submitted.get("state") != "queued" or len(job_id) != 26: | ||
| 81 | + problems.append(f"anahtarsiz duz_okuma submit'i kabul edilmedi: {submitted}") | ||
| 82 | + if not isinstance(submitted.get("eta_secs"), int) or submitted["eta_secs"] < 1: | ||
| 83 | + problems.append(f"eta_secs bir pozitif tamsayi degil: {submitted.get('eta_secs')}") | ||
| 84 | + | ||
| 85 | + reported = capabilities.dispatch("podcast.status", {"job_id": job_id}) | ||
| 86 | + if reported.get("state") != "queued" or reported.get("progress") != 0.0: | ||
| 87 | + problems.append(f"podcast.status kuyruktaki isi dogru bildirmedi: {reported}") | ||
| 88 | + if "error_code" not in reported or reported["error_code"] is not None: | ||
| 89 | + problems.append("podcast.status error_code alanini null olarak dondurmedi") | ||
| 90 | + | ||
| 91 | + _expect_error( | ||
| 92 | + problems, | ||
| 93 | + "bitmemis is icin podcast.result", | ||
| 94 | + "not_ready", | ||
| 95 | + capabilities.dispatch, | ||
| 96 | + "podcast.result", | ||
| 97 | + {"job_id": job_id}, | ||
| 98 | + ) | ||
| 99 | + | ||
| 100 | + if capabilities.dispatch("podcast.cancel", {"job_id": job_id}).get("cancelled") is not True: | ||
| 101 | + problems.append("kuyruktaki is iptal edilemedi") | ||
| 102 | + if capabilities.dispatch("podcast.status", {"job_id": job_id}).get("state") != "cancelled": | ||
| 103 | + problems.append("iptal sonrasi durum 'cancelled' olmadi") | ||
| 104 | + if capabilities.dispatch("podcast.cancel", {"job_id": job_id}).get("cancelled") is not False: | ||
| 105 | + problems.append("bitmis is icin ikinci iptal True dondu") | ||
| 106 | + | ||
| 107 | + _expect_error( | ||
| 108 | + problems, | ||
| 109 | + "anahtarsiz tek_ogretici submit'i", | ||
| 110 | + "llm_unavailable", | ||
| 111 | + capabilities.dispatch, | ||
| 112 | + "podcast.submit", | ||
| 113 | + {"source_id": "ornek", "format": "tek_ogretici"}, | ||
| 114 | + ) | ||
| 115 | + _expect_error( | ||
| 116 | + problems, | ||
| 117 | + "anahtarsiz ogrenci_hoca submit'i", | ||
| 118 | + "llm_unavailable", | ||
| 119 | + capabilities.dispatch, | ||
| 120 | + "podcast.submit", | ||
| 121 | + {"source_id": "ornek", "format": "ogrenci_hoca"}, | ||
| 122 | + ) | ||
| 123 | + | ||
| 124 | + from .protocol import CapabilityError | ||
| 125 | + | ||
| 126 | + try: | ||
| 127 | + capabilities.dispatch("podcast.submit", {"source_id": "ornek", "format": "tek_ogretici"}) | ||
| 128 | + except CapabilityError as exc: | ||
| 129 | + if "duz_okuma" not in str(exc): | ||
| 130 | + problems.append("llm_unavailable mesaji kullanilabilir formatlari soylemiyor") | ||
| 131 | + | ||
| 132 | + for capability in ("podcast.status", "podcast.result", "podcast.cancel"): | ||
| 133 | + _expect_error( | ||
| 134 | + problems, | ||
| 135 | + f"{capability} bilinmeyen is icin", | ||
| 136 | + "not_found", | ||
| 137 | + capabilities.dispatch, | ||
| 138 | + capability, | ||
| 139 | + {"job_id": "YOKBOYLEBIRIS"}, | ||
| 140 | + ) | ||
| 141 | + | ||
| 142 | + for capability, payload in ( | ||
| 143 | + ("podcast.submit", {}), | ||
| 144 | + ("podcast.submit", {"source_id": "ornek", "format": "opera"}), | ||
| 145 | + ("podcast.status", {"job_id": 7}), | ||
| 146 | + ("podcast.cancel", {}), | ||
| 147 | + ): | ||
| 148 | + _expect_error( | ||
| 149 | + problems, | ||
| 150 | + f"{capability} gecersiz payload {payload}", | ||
| 151 | + "bad_request", | ||
| 152 | + capabilities.dispatch, | ||
| 153 | + capability, | ||
| 154 | + payload, | ||
| 155 | + ) | ||
| 156 | + | ||
| 157 | + _expect_error( | ||
| 158 | + problems, | ||
| 159 | + "bilinmeyen yetenek", | ||
| 160 | + "unsupported_capability", | ||
| 161 | + capabilities.dispatch, | ||
| 162 | + "podcast.bilinmeyen", | ||
| 163 | + {}, | ||
| 164 | + ) | ||
| 165 | + | ||
| 166 | + capabilities.configure(store, llm_ready=True) | ||
| 167 | + with_key = capabilities.dispatch( | ||
| 168 | + "podcast.submit", {"source_id": "ornek", "format": "tek_ogretici"} | ||
| 169 | + ) | ||
| 170 | + if with_key.get("state") != "queued": | ||
| 171 | + problems.append(f"anahtar varken tek_ogretici submit'i kabul edilmedi: {with_key}") | ||
| 172 | + | ||
| 173 | + small = jobs.JobStore(root=os.path.join(root, "busy"), workers=1, max_jobs=1, stage_secs=0.0) | ||
| 174 | + capabilities.configure(small, llm_ready=False) | ||
| 175 | + capabilities.dispatch("podcast.submit", {"source_id": "ilk"}) | ||
| 176 | + _expect_error( | ||
| 177 | + problems, | ||
| 178 | + "kuyruk tavani asildiginda submit", | ||
| 179 | + "busy", | ||
| 180 | + capabilities.dispatch, | ||
| 181 | + "podcast.submit", | ||
| 182 | + {"source_id": "ikinci"}, | ||
| 183 | + ) | ||
| 184 | + | ||
| 185 | + capabilities.configure(None, llm_ready=False) | ||
| 186 | + return problems | ||
| 187 | + | ||
| 188 | + | ||
| 189 | +def _check_job_store(root: str) -> list[str]: | ||
| 190 | + from . import jobs | ||
| 191 | + | ||
| 192 | + problems: list[str] = [] | ||
| 193 | + | ||
| 194 | + for state, allowed in jobs.TRANSITIONS.items(): | ||
| 195 | + for target in allowed: | ||
| 196 | + if target not in jobs.STATES: | ||
| 197 | + problems.append(f"durum makinesinde bilinmeyen hedef: {state} -> {target}") | ||
| 198 | + for terminal in (jobs.STATE_DONE, jobs.STATE_FAILED, jobs.STATE_CANCELLED): | ||
| 199 | + if jobs.TRANSITIONS[terminal]: | ||
| 200 | + problems.append(f"terminal durum '{terminal}' cikis gecisi tanimliyor") | ||
| 201 | + | ||
| 202 | + persist_root = os.path.join(root, "persist") | ||
| 203 | + store = jobs.JobStore(root=persist_root, workers=1, max_jobs=8, stage_secs=0.0) | ||
| 204 | + record, _ = store.submit("kaynak-1", "duz_okuma") | ||
| 205 | + job_id = record["job_id"] | ||
| 206 | + | ||
| 207 | + path = os.path.join(persist_root, f"{job_id}.json") | ||
| 208 | + if not os.path.exists(path): | ||
| 209 | + problems.append("is durumu diske yazilmadi") | ||
| 210 | + else: | ||
| 211 | + with open(path, "r", encoding="utf-8") as handle: | ||
| 212 | + on_disk = json.load(handle) | ||
| 213 | + if on_disk.get("job_id") != job_id or on_disk.get("state") != "queued": | ||
| 214 | + problems.append(f"diskteki is kaydi beklenenden farkli: {on_disk}") | ||
| 215 | + leftovers = [name for name in os.listdir(persist_root) if ".json.tmp" in name] | ||
| 216 | + if leftovers: | ||
| 217 | + problems.append(f"atomik yazmadan gecici dosya kaldi: {leftovers}") | ||
| 218 | + | ||
| 219 | + reopened = jobs.JobStore(root=persist_root, workers=1, max_jobs=8, stage_secs=0.0) | ||
| 220 | + try: | ||
| 221 | + again = reopened.get(job_id) | ||
| 222 | + except jobs.JobNotFound: | ||
| 223 | + problems.append("yeniden acilan depo kuyruktaki isi bulamadi") | ||
| 224 | + again = {} | ||
| 225 | + if again.get("state") != "queued": | ||
| 226 | + problems.append(f"kuyruktaki is yeniden acilista bozuldu: {again.get('state')}") | ||
| 227 | + if reopened.swept != 0: | ||
| 228 | + problems.append(f"kuyruktaki is supuruldu, supurulmemeliydi: {reopened.swept}") | ||
| 229 | + | ||
| 230 | + try: | ||
| 231 | + store.transition(job_id, jobs.STATE_DONE) | ||
| 232 | + problems.append("queued -> done gecisi reddedilmedi") | ||
| 233 | + except jobs.InvalidTransition: | ||
| 234 | + pass | ||
| 235 | + try: | ||
| 236 | + store.transition(job_id, "bilinmeyen") | ||
| 237 | + problems.append("bilinmeyen hedef durum reddedilmedi") | ||
| 238 | + except jobs.InvalidTransition: | ||
| 239 | + pass | ||
| 240 | + store.transition(job_id, jobs.STATE_RUNNING) | ||
| 241 | + store.finish(job_id, audio_id="a", duration_secs=1.0, script_id="s") | ||
| 242 | + try: | ||
| 243 | + store.transition(job_id, jobs.STATE_RUNNING) | ||
| 244 | + problems.append("done -> running gecisi reddedilmedi") | ||
| 245 | + except jobs.InvalidTransition: | ||
| 246 | + pass | ||
| 247 | + try: | ||
| 248 | + store.transition("YOKBOYLEBIRIS", jobs.STATE_RUNNING) | ||
| 249 | + problems.append("bilinmeyen is icin gecis reddedilmedi") | ||
| 250 | + except jobs.JobNotFound: | ||
| 251 | + pass | ||
| 252 | + | ||
| 253 | + sweep_root = os.path.join(root, "sweep") | ||
| 254 | + seed = jobs.JobStore(root=sweep_root, workers=1, max_jobs=8, stage_secs=0.0) | ||
| 255 | + running_record, _ = seed.submit("kaynak-2", "duz_okuma") | ||
| 256 | + running_id = running_record["job_id"] | ||
| 257 | + seed.transition(running_id, jobs.STATE_RUNNING) | ||
| 258 | + queued_record, _ = seed.submit("kaynak-3", "duz_okuma") | ||
| 259 | + queued_id = queued_record["job_id"] | ||
| 260 | + | ||
| 261 | + swept_store = jobs.JobStore(root=sweep_root, workers=1, max_jobs=8, stage_secs=0.0) | ||
| 262 | + if swept_store.swept != 1: | ||
| 263 | + problems.append(f"acilis supurmesi tam olarak 1 is beklerken {swept_store.swept} buldu") | ||
| 264 | + revived = swept_store.get(running_id) | ||
| 265 | + if revived["state"] != jobs.STATE_FAILED: | ||
| 266 | + problems.append(f"kosan is supurmede 'failed' olmadi: {revived['state']}") | ||
| 267 | + if revived["error_code"] != jobs.INTERRUPTED_CODE: | ||
| 268 | + problems.append(f"supurulen isin error_code'u yanlis: {revived['error_code']}") | ||
| 269 | + if swept_store.get(queued_id)["state"] != jobs.STATE_QUEUED: | ||
| 270 | + problems.append("kuyruktaki is supurmede bozuldu") | ||
| 271 | + | ||
| 272 | + return problems | ||
| 273 | + | ||
| 274 | + | ||
| 275 | +def _check_lifecycle(root: str) -> list[str]: | ||
| 276 | + from . import capabilities, jobs | ||
| 277 | + | ||
| 278 | + problems: list[str] = [] | ||
| 279 | + | ||
| 280 | + done_store = jobs.JobStore( | ||
| 281 | + root=os.path.join(root, "lifecycle"), workers=1, max_jobs=8, stage_secs=0.0 | ||
| 282 | + ) | ||
| 283 | + done_store.start() | ||
| 284 | + capabilities.configure(done_store, llm_ready=False) | ||
| 285 | + try: | ||
| 286 | + submitted = capabilities.dispatch("podcast.submit", {"source_id": "kaynak", "format": "duz_okuma"}) | ||
| 287 | + job_id = submitted["job_id"] | ||
| 288 | + final = _await_state(done_store, job_id, (jobs.STATE_DONE, jobs.STATE_FAILED), 10.0) | ||
| 289 | + if final["state"] != jobs.STATE_DONE: | ||
| 290 | + problems.append(f"sahte hat 'done' ile bitmedi: {final['state']} {final['error_code']}") | ||
| 291 | + else: | ||
| 292 | + reported = capabilities.dispatch("podcast.status", {"job_id": job_id}) | ||
| 293 | + if reported.get("progress") != 1.0: | ||
| 294 | + problems.append(f"biten isin ilerlemesi 1.0 degil: {reported.get('progress')}") | ||
| 295 | + payload = capabilities.dispatch("podcast.result", {"job_id": job_id}) | ||
| 296 | + if not payload.get("audio_id") or not payload.get("script_id"): | ||
| 297 | + problems.append(f"podcast.result kimlikleri uretmedi: {payload}") | ||
| 298 | + if not isinstance(payload.get("duration_secs"), float): | ||
| 299 | + problems.append(f"duration_secs bir ondalik degil: {payload.get('duration_secs')}") | ||
| 300 | + if payload.get("format") != "duz_okuma": | ||
| 301 | + problems.append(f"podcast.result format alanini kaybetti: {payload}") | ||
| 302 | + finally: | ||
| 303 | + done_store.shutdown() | ||
| 304 | + | ||
| 305 | + cancel_store = jobs.JobStore( | ||
| 306 | + root=os.path.join(root, "cancel"), workers=1, max_jobs=8, stage_secs=0.1 | ||
| 307 | + ) | ||
| 308 | + cancel_store.start() | ||
| 309 | + capabilities.configure(cancel_store, llm_ready=False) | ||
| 310 | + try: | ||
| 311 | + submitted = capabilities.dispatch("podcast.submit", {"source_id": "kaynak"}) | ||
| 312 | + job_id = submitted["job_id"] | ||
| 313 | + started = _await_state(cancel_store, job_id, (jobs.STATE_RUNNING,), 10.0) | ||
| 314 | + if started["state"] != jobs.STATE_RUNNING: | ||
| 315 | + problems.append(f"is kosmaya baslamadi: {started['state']}") | ||
| 316 | + else: | ||
| 317 | + capabilities.dispatch("podcast.cancel", {"job_id": job_id}) | ||
| 318 | + stopped = _await_state( | ||
| 319 | + cancel_store, | ||
| 320 | + job_id, | ||
| 321 | + (jobs.STATE_CANCELLED, jobs.STATE_DONE, jobs.STATE_FAILED), | ||
| 322 | + 10.0, | ||
| 323 | + ) | ||
| 324 | + if stopped["state"] != jobs.STATE_CANCELLED: | ||
| 325 | + problems.append(f"kosan is isbirlikci iptali gormedi: {stopped['state']}") | ||
| 326 | + finally: | ||
| 327 | + cancel_store.shutdown() | ||
| 328 | + | ||
| 329 | + capabilities.configure(None, llm_ready=False) | ||
| 330 | + return problems | ||
| 331 | + | ||
| 332 | + | ||
| 333 | +def _check_cancel_race(root: str) -> list[str]: | ||
| 334 | + from . import jobs | ||
| 335 | + | ||
| 336 | + problems: list[str] = [] | ||
| 337 | + race_root = os.path.join(root, "race") | ||
| 338 | + store = jobs.JobStore(root=race_root, workers=1, max_jobs=8, stage_secs=0.0) | ||
| 339 | + | ||
| 340 | + record, _ = store.submit("kaynak-yaris", "duz_okuma") | ||
| 341 | + job_id = record["job_id"] | ||
| 342 | + store.transition(job_id, jobs.STATE_RUNNING) | ||
| 343 | + if store.cancel(job_id) is not True: | ||
| 344 | + problems.append("kosan is icin cancel True donmedi") | ||
| 345 | + finished = store.finish(job_id, audio_id="a", duration_secs=1.0, script_id="s") | ||
| 346 | + if finished["state"] != jobs.STATE_CANCELLED: | ||
| 347 | + problems.append( | ||
| 348 | + f"iptal bayragi setken finish() 'done' verdi: {finished['state']}" | ||
| 349 | + ) | ||
| 350 | + if finished["audio_id"] is not None: | ||
| 351 | + problems.append("iptal edilen is yine de audio_id yazdi") | ||
| 352 | + with open(os.path.join(race_root, f"{job_id}.json"), "r", encoding="utf-8") as handle: | ||
| 353 | + on_disk = json.load(handle) | ||
| 354 | + if on_disk.get("state") != jobs.STATE_CANCELLED: | ||
| 355 | + problems.append(f"finish() iptali diske yansitmadi: {on_disk.get('state')}") | ||
| 356 | + return problems | ||
| 357 | + | ||
| 358 | + | ||
| 359 | +def _check_early_failure(root: str) -> list[str]: | ||
| 360 | + from . import jobs | ||
| 361 | + | ||
| 362 | + problems: list[str] = [] | ||
| 363 | + if jobs.STATE_FAILED not in jobs.TRANSITIONS[jobs.STATE_QUEUED]: | ||
| 364 | + problems.append("queued -> failed gecisi durum makinesinde tanimli degil") | ||
| 365 | + store = jobs.JobStore( | ||
| 366 | + root=os.path.join(root, "erken"), workers=1, max_jobs=8, stage_secs=0.0 | ||
| 367 | + ) | ||
| 368 | + record, _ = store.submit("kaynak-erken", "duz_okuma") | ||
| 369 | + job_id = record["job_id"] | ||
| 370 | + try: | ||
| 371 | + failed = store.fail(job_id, "kaynak_yok") | ||
| 372 | + if failed["state"] != jobs.STATE_FAILED: | ||
| 373 | + problems.append(f"baslamadan patlayan is 'failed' olmadi: {failed['state']}") | ||
| 374 | + if failed["error_code"] != "kaynak_yok": | ||
| 375 | + problems.append(f"hata kodu kaybedildi: {failed['error_code']}") | ||
| 376 | + except jobs.InvalidTransition as exc: | ||
| 377 | + problems.append(f"queued -> failed reddedildi, is kotayi kalici yer: {exc}") | ||
| 378 | + return problems | ||
| 379 | + | ||
| 380 | + | ||
| 381 | +def _check_source_paths(root: str) -> list[str]: | ||
| 382 | + from pathlib import Path | ||
| 383 | + | ||
| 384 | + from . import jobs | ||
| 385 | + | ||
| 386 | + problems: list[str] = [] | ||
| 387 | + media_root = os.path.join(root, "media") | ||
| 388 | + os.makedirs(media_root, exist_ok=True) | ||
| 389 | + for bad in ("..", "../x", "a/b", "/etc/passwd", "", "x" * 129, "..\\x", ".", "a b"): | ||
| 390 | + try: | ||
| 391 | + resolved = jobs.resolve_source(media_root, bad) | ||
| 392 | + problems.append(f"resolve_source kotu source_id'yi kabul etti: {bad!r} -> {resolved}") | ||
| 393 | + except ValueError: | ||
| 394 | + pass | ||
| 395 | + good = jobs.resolve_source(media_root, "ders-01.pdf") | ||
| 396 | + if good != Path(media_root).resolve() / "ders-01.pdf": | ||
| 397 | + problems.append(f"resolve_source gecerli source_id'yi yanlis cozdu: {good}") | ||
| 398 | + if good.exists(): | ||
| 399 | + problems.append("test kurulumu bozuk: cozulen dosya gercekten var") | ||
| 400 | + return problems | ||
| 401 | + | ||
| 402 | + | ||
| 403 | +def _check_eta_source(root: str) -> list[str]: | ||
| 404 | + from . import config, jobs | ||
| 405 | + | ||
| 406 | + problems: list[str] = [] | ||
| 407 | + fixed = jobs.JobStore( | ||
| 408 | + root=os.path.join(root, "eta"), | ||
| 409 | + workers=2, | ||
| 410 | + max_jobs=8, | ||
| 411 | + stage_secs=0.0, | ||
| 412 | + job_secs=2700.0, | ||
| 413 | + ) | ||
| 414 | + if fixed.estimate_eta(1) != 2700: | ||
| 415 | + problems.append(f"estimate_eta job_secs'i kullanmiyor: {fixed.estimate_eta(1)}") | ||
| 416 | + if fixed.estimate_eta(4) != 5400: | ||
| 417 | + problems.append(f"estimate_eta dalga sayisini kaybetti: {fixed.estimate_eta(4)}") | ||
| 418 | + | ||
| 419 | + auto = jobs.JobStore( | ||
| 420 | + root=os.path.join(root, "eta-auto"), workers=1, max_jobs=8, stage_secs=0.0 | ||
| 421 | + ) | ||
| 422 | + if auto.job_secs != 1.0: | ||
| 423 | + problems.append(f"job_secs otomatik tabani 1.0 degil: {auto.job_secs}") | ||
| 424 | + custom = jobs.JobStore( | ||
| 425 | + root=os.path.join(root, "eta-stages"), | ||
| 426 | + workers=1, | ||
| 427 | + max_jobs=8, | ||
| 428 | + stage_secs=0.0, | ||
| 429 | + stages=("ocr", "tts"), | ||
| 430 | + ) | ||
| 431 | + if custom.stages != ("ocr", "tts"): | ||
| 432 | + problems.append(f"stages parametresi yok sayildi: {custom.stages}") | ||
| 433 | + | ||
| 434 | + previous = os.environ.get("PODCAST_ETA_SECS") | ||
| 435 | + os.environ["PODCAST_ETA_SECS"] = "900" | ||
| 436 | + try: | ||
| 437 | + settings = config.Config(require_token=False) | ||
| 438 | + finally: | ||
| 439 | + if previous is None: | ||
| 440 | + del os.environ["PODCAST_ETA_SECS"] | ||
| 441 | + else: | ||
| 442 | + os.environ["PODCAST_ETA_SECS"] = previous | ||
| 443 | + if settings.eta_secs != 900.0: | ||
| 444 | + problems.append(f"PODCAST_ETA_SECS okunmadi: {settings.eta_secs}") | ||
| 445 | + return problems | ||
| 446 | + | ||
| 447 | + | ||
| 448 | +def _check_record_schema(root: str) -> list[str]: | ||
| 449 | + from . import jobs | ||
| 450 | + | ||
| 451 | + problems: list[str] = [] | ||
| 452 | + schema_root = os.path.join(root, "sema") | ||
| 453 | + seed = jobs.JobStore(root=schema_root, workers=1, max_jobs=8, stage_secs=0.0) | ||
| 454 | + healthy_id = seed.submit("saglam", "duz_okuma")[0]["job_id"] | ||
| 455 | + broken_id = seed.submit("bozuk", "duz_okuma")[0]["job_id"] | ||
| 456 | + | ||
| 457 | + broken_path = os.path.join(schema_root, f"{broken_id}.json") | ||
| 458 | + with open(broken_path, "r", encoding="utf-8") as handle: | ||
| 459 | + payload = json.load(handle) | ||
| 460 | + payload.pop("stage") | ||
| 461 | + with open(broken_path, "w", encoding="utf-8") as handle: | ||
| 462 | + json.dump(payload, handle) | ||
| 463 | + | ||
| 464 | + leftover = os.path.join(schema_root, f"{broken_id}.json.tmp999-dead") | ||
| 465 | + with open(leftover, "w", encoding="utf-8") as handle: | ||
| 466 | + handle.write("{}") | ||
| 467 | + | ||
| 468 | + reopened = jobs.JobStore(root=schema_root, workers=1, max_jobs=8, stage_secs=0.0) | ||
| 469 | + try: | ||
| 470 | + reopened.get(broken_id) | ||
| 471 | + problems.append("eksik alanli kayit acilista atlanmadi") | ||
| 472 | + except jobs.JobNotFound: | ||
| 473 | + pass | ||
| 474 | + try: | ||
| 475 | + if reopened.get(healthy_id)["state"] != jobs.STATE_QUEUED: | ||
| 476 | + problems.append("saglam kayit eksik alanli komsusu yuzunden bozuldu") | ||
| 477 | + except jobs.JobNotFound: | ||
| 478 | + problems.append("saglam kayit eksik alanli komsusu yuzunden kayboldu") | ||
| 479 | + if os.path.exists(leftover): | ||
| 480 | + problems.append("acilista gecici dosya artigi temizlenmedi") | ||
| 481 | + return problems | ||
| 482 | + | ||
| 483 | + | ||
| 484 | +def _check_shutdown(root: str) -> list[str]: | ||
| 485 | + from . import jobs | ||
| 486 | + | ||
| 487 | + problems: list[str] = [] | ||
| 488 | + gate = threading.Event() | ||
| 489 | + | ||
| 490 | + def blocking_runner(ctx) -> None: | ||
| 491 | + gate.wait(20.0) | ||
| 492 | + | ||
| 493 | + store = jobs.JobStore( | ||
| 494 | + root=os.path.join(root, "kapanis"), | ||
| 495 | + workers=1, | ||
| 496 | + max_jobs=8, | ||
| 497 | + stage_secs=0.0, | ||
| 498 | + runner=blocking_runner, | ||
| 499 | + ) | ||
| 500 | + store.start() | ||
| 501 | + try: | ||
| 502 | + job_id = store.submit("uzun-is", "duz_okuma")[0]["job_id"] | ||
| 503 | + started = _await_state(store, job_id, (jobs.STATE_RUNNING,), 10.0) | ||
| 504 | + if started["state"] != jobs.STATE_RUNNING: | ||
| 505 | + problems.append(f"uzun is kosmaya baslamadi: {started['state']}") | ||
| 506 | + return problems | ||
| 507 | + workers = [ | ||
| 508 | + thread | ||
| 509 | + for thread in threading.enumerate() | ||
| 510 | + if thread.name.startswith("podcast-job") | ||
| 511 | + ] | ||
| 512 | + if not workers: | ||
| 513 | + problems.append("isci thread bulunamadi") | ||
| 514 | + if any(not thread.daemon for thread in workers): | ||
| 515 | + problems.append( | ||
| 516 | + "isci thread daemon degil; yorumlayici cikista onu join eder" | ||
| 517 | + ) | ||
| 518 | + began = time.monotonic() | ||
| 519 | + store.shutdown(timeout=0.5) | ||
| 520 | + elapsed = time.monotonic() - began | ||
| 521 | + if elapsed > 3.0: | ||
| 522 | + problems.append(f"shutdown(timeout=0.5) {elapsed:.1f}s takildi") | ||
| 523 | + if not store.stopping: | ||
| 524 | + problems.append("shutdown sonrasi store.stopping False") | ||
| 525 | + if store.get(job_id)["cancel_requested"] is not True: | ||
| 526 | + problems.append("kapanista kosan ise iptal bayragi konmadi") | ||
| 527 | + finally: | ||
| 528 | + gate.set() | ||
| 529 | + return problems | ||
| 530 | + | ||
| 531 | + | ||
| 532 | +def _check_framing() -> list[str]: | ||
| 533 | + from . import capabilities, protocol | ||
| 534 | + | ||
| 535 | + problems: list[str] = [] | ||
| 536 | + message = protocol.build_hello("podcast", capabilities.names(), "gizli", 2) | ||
| 537 | + | ||
| 538 | + async def round_trip() -> object: | ||
| 539 | + stream = protocol.FrameStream() | ||
| 540 | + encoded = protocol.encode_frame(message) | ||
| 541 | + stream.feed(encoded[:3], end=False) | ||
| 542 | + stream.feed(encoded[3:], end=True) | ||
| 543 | + return await stream.read_frame() | ||
| 544 | + | ||
| 545 | + decoded = asyncio.run(round_trip()) | ||
| 546 | + if decoded != message: | ||
| 547 | + problems.append("cerceve gidis-donusu bozuldu") | ||
| 548 | + if protocol.encode_frame({})[:4] != b"\x00\x00\x00\x02": | ||
| 549 | + problems.append("uzunluk oneki big-endian degil") | ||
| 550 | + if protocol.PROTOCOL != "hab/1": | ||
| 551 | + problems.append(f"protokol kimligi beklenenden farkli: {protocol.PROTOCOL}") | ||
| 552 | + | ||
| 553 | + try: | ||
| 554 | + protocol.parse_greeting({"code": "unauthorized", "message": "bad token"}) | ||
| 555 | + problems.append("reddedilen greeting hata uretmedi") | ||
| 556 | + except protocol.HandshakeRejected: | ||
| 557 | + pass | ||
| 558 | + welcome = {"type": "welcome", "worker_id": "w1", "protocol": protocol.PROTOCOL} | ||
| 559 | + if protocol.parse_greeting(welcome) != "w1": | ||
| 560 | + problems.append("welcome greeting cozumlenemedi") | ||
| 561 | + try: | ||
| 562 | + protocol.parse_greeting({"type": "welcome", "worker_id": "w1"}) | ||
| 563 | + problems.append("protokol alani eksik welcome kabul edildi") | ||
| 564 | + except protocol.HandshakeRejected: | ||
| 565 | + pass | ||
| 566 | + | ||
| 567 | + deadline = protocol.parse_request( | ||
| 568 | + {"id": "r1", "capability": "podcast.status", "payload": {}, "deadline_ms": 60000} | ||
| 569 | + )[3] | ||
| 570 | + if deadline is None or deadline >= 60.0: | ||
| 571 | + problems.append(f"deadline payi birakilmadi: {deadline}") | ||
| 572 | + return problems | ||
| 573 | + | ||
| 574 | + | ||
| 575 | +class _FakeResult: | ||
| 576 | + def __init__(self, mp3: list, scripts: list, duration: float) -> None: | ||
| 577 | + self.mp3_yollari = mp3 | ||
| 578 | + self.script_yollari = scripts | ||
| 579 | + self.ses_toplam_sn = duration | ||
| 580 | + self.adimlar: list = [] | ||
| 581 | + | ||
| 582 | + | ||
| 583 | +class _FakePipelineError(RuntimeError): | ||
| 584 | + pass | ||
| 585 | + | ||
| 586 | + | ||
| 587 | +class _FakeInterrupt(RuntimeError): | ||
| 588 | + pass | ||
| 589 | + | ||
| 590 | + | ||
| 591 | +class _FakeCtx: | ||
| 592 | + def __init__(self, cancelled: bool, stages: tuple) -> None: | ||
| 593 | + self._cancelled = cancelled | ||
| 594 | + self.stages = stages | ||
| 595 | + self.seen: list = [] | ||
| 596 | + | ||
| 597 | + def cancelled(self) -> bool: | ||
| 598 | + return self._cancelled | ||
| 599 | + | ||
| 600 | + def progress(self, stage: str, value: float) -> None: | ||
| 601 | + self.seen.append((stage, value)) | ||
| 602 | + | ||
| 603 | + | ||
| 604 | +def _fake_pipeline(mp3: list, scripts: list, duration: float): | ||
| 605 | + class FakePipeline: | ||
| 606 | + def __init__(self, pdf, format, gunluk, cikti_koku, bolum_limiti, | ||
| 607 | + motor_adi, ses_uret, kayit=None): | ||
| 608 | + self.pdf = pdf | ||
| 609 | + self.format = format | ||
| 610 | + self.gunluk = gunluk | ||
| 611 | + self.cikti_koku = cikti_koku | ||
| 612 | + self.bolum_limiti = bolum_limiti | ||
| 613 | + self.motor_adi = motor_adi | ||
| 614 | + self.ses_uret = ses_uret | ||
| 615 | + self.kayit = kayit | ||
| 616 | + self.sonuc = _FakeResult(list(mp3), list(scripts), duration) | ||
| 617 | + | ||
| 618 | + def kos(self): | ||
| 619 | + for name in ("ingest", "scriptler"): | ||
| 620 | + self.sonuc.adimlar.append(name) | ||
| 621 | + self.gunluk(f"[KOSTU ] {name}") | ||
| 622 | + return self.sonuc | ||
| 623 | + | ||
| 624 | + return FakePipeline | ||
| 625 | + | ||
| 626 | + | ||
| 627 | +def _pipeline_store(root: str, name: str, media_root: str, mp3: list, scripts: list): | ||
| 628 | + from . import jobs, pipeline | ||
| 629 | + | ||
| 630 | + runner = pipeline.make_runner( | ||
| 631 | + media_root, | ||
| 632 | + os.path.join(root, name + "-cikti"), | ||
| 633 | + 1, | ||
| 634 | + "supertonic-3", | ||
| 635 | + _fake_pipeline(mp3, scripts, 123.5), | ||
| 636 | + _FakePipelineError, | ||
| 637 | + _FakeInterrupt, | ||
| 638 | + ) | ||
| 639 | + return jobs.JobStore( | ||
| 640 | + root=os.path.join(root, name), | ||
| 641 | + workers=1, | ||
| 642 | + max_jobs=8, | ||
| 643 | + stage_secs=0.0, | ||
| 644 | + runner=runner, | ||
| 645 | + stages=pipeline.REAL_STAGES, | ||
| 646 | + ) | ||
| 647 | + | ||
| 648 | + | ||
| 649 | +def _check_pipeline(root: str) -> list[str]: | ||
| 650 | + from . import capabilities, config, jobs, pipeline | ||
| 651 | + | ||
| 652 | + problems: list[str] = [] | ||
| 653 | + | ||
| 654 | + if pipeline.MODES != ("simulate", "real"): | ||
| 655 | + problems.append(f"mod kumesi beklenenden farkli: {pipeline.MODES}") | ||
| 656 | + if pipeline.REAL_ETA_SECS != 2700.0: | ||
| 657 | + problems.append(f"gercek hat eta sabiti degismis: {pipeline.REAL_ETA_SECS}") | ||
| 658 | + | ||
| 659 | + previous = os.environ.get("PODCAST_MODE") | ||
| 660 | + os.environ["PODCAST_MODE"] = "gecersiz-mod" | ||
| 661 | + try: | ||
| 662 | + config.Config(require_token=False) | ||
| 663 | + problems.append("gecersiz PODCAST_MODE degeri kabul edildi") | ||
| 664 | + except config.ConfigError: | ||
| 665 | + pass | ||
| 666 | + finally: | ||
| 667 | + if previous is None: | ||
| 668 | + os.environ.pop("PODCAST_MODE", None) | ||
| 669 | + else: | ||
| 670 | + os.environ["PODCAST_MODE"] = previous | ||
| 671 | + | ||
| 672 | + simulate = config.Config(require_token=False) | ||
| 673 | + if simulate.mode == "simulate": | ||
| 674 | + if pipeline.PIPELINE_MODULE in sys.modules: | ||
| 675 | + problems.append( | ||
| 676 | + "simulate modda gercek hat import edildi: " | ||
| 677 | + f"{pipeline.PIPELINE_MODULE} sys.modules icinde" | ||
| 678 | + ) | ||
| 679 | + if pipeline.stages_for(simulate) is not None: | ||
| 680 | + problems.append("simulate modda gercek asama adlari zorlaniyor") | ||
| 681 | + if pipeline.job_secs_for(simulate) is not None: | ||
| 682 | + problems.append("simulate modda gercek hat etasi zorlaniyor") | ||
| 683 | + | ||
| 684 | + for bad in ("", " "): | ||
| 685 | + try: | ||
| 686 | + pipeline.check_pipeline_path(bad) | ||
| 687 | + problems.append(f"bos PODCAST_PIPELINE_PATH kabul edildi: {bad!r}") | ||
| 688 | + except pipeline.PipelineUnavailable: | ||
| 689 | + pass | ||
| 690 | + try: | ||
| 691 | + pipeline.check_pipeline_path(os.path.join(root, "olmayan-hat")) | ||
| 692 | + problems.append("var olmayan PODCAST_PIPELINE_PATH kabul edildi") | ||
| 693 | + except pipeline.PipelineUnavailable: | ||
| 694 | + pass | ||
| 695 | + empty_root = os.path.join(root, "hatsiz") | ||
| 696 | + os.makedirs(empty_root, exist_ok=True) | ||
| 697 | + try: | ||
| 698 | + pipeline.check_pipeline_path(empty_root) | ||
| 699 | + problems.append("router/hat.py icermeyen kok kabul edildi") | ||
| 700 | + except pipeline.PipelineUnavailable: | ||
| 701 | + pass | ||
| 702 | + | ||
| 703 | + if pipeline.normalize_limit(0) is not None or pipeline.normalize_limit(-1) is not None: | ||
| 704 | + problems.append("bolum limiti 0/negatif icin 'hepsi' anlamina gelmiyor") | ||
| 705 | + if pipeline.normalize_limit(3) != 3: | ||
| 706 | + problems.append("pozitif bolum limiti bozuldu") | ||
| 707 | + | ||
| 708 | + output_root = os.path.join(root, "hat-cikti") | ||
| 709 | + def _out_path(*parts: str) -> str: | ||
| 710 | + return os.path.join(output_root, *parts) | ||
| 711 | + | ||
| 712 | + mapped = pipeline.derive_outputs( | ||
| 713 | + _FakeResult( | ||
| 714 | + [_out_path("ders", "ses", "duz_okuma", "ders-b01.mp3"), | ||
| 715 | + _out_path("ders", "ses", "duz_okuma", "ders-b02.mp3")], | ||
| 716 | + [_out_path("ders", "script", "duz_okuma", "ders-b01.script.json"), | ||
| 717 | + _out_path("ders", "script", "duz_okuma", "ders-b02.script.json")], | ||
| 718 | + 321.25, | ||
| 719 | + ), | ||
| 720 | + output_root, | ||
| 721 | + ) | ||
| 722 | + if mapped["audio_id"] != "ders/ses/duz_okuma/ders-b01.mp3": | ||
| 723 | + problems.append(f"audio_id cikti kokune gore relatif degil: {mapped['audio_id']}") | ||
| 724 | + if mapped["script_id"] != "ders/script/duz_okuma/ders-b01.script.json": | ||
| 725 | + problems.append(f"script_id cikti kokune gore relatif degil: {mapped['script_id']}") | ||
| 726 | + if mapped["duration_secs"] != 321.25: | ||
| 727 | + problems.append(f"duration_secs ses_toplam_sn'den gelmedi: {mapped['duration_secs']}") | ||
| 728 | + if len(mapped["audio_ids"]) != 2 or len(mapped["script_ids"]) != 2: | ||
| 729 | + problems.append(f"kimlik listeleri eksik: {mapped}") | ||
| 730 | + | ||
| 731 | + other = pipeline.derive_outputs( | ||
| 732 | + _FakeResult( | ||
| 733 | + [_out_path("ders", "ses", "tek_ogretici", "ders-b01.mp3")], | ||
| 734 | + [_out_path("ders", "script", "tek_ogretici", "ders-b01.script.json")], | ||
| 735 | + 10.0, | ||
| 736 | + ), | ||
| 737 | + output_root, | ||
| 738 | + ) | ||
| 739 | + if other["audio_id"] == mapped["audio_id"]: | ||
| 740 | + problems.append( | ||
| 741 | + f"ayni PDF'in iki formati AYNI audio_id dondu: {other['audio_id']}" | ||
| 742 | + ) | ||
| 743 | + | ||
| 744 | + trimmed = pipeline.derive_outputs( | ||
| 745 | + _FakeResult( | ||
| 746 | + [_out_path("ders", "ses", "duz_okuma", "ders-b01.mp3")], | ||
| 747 | + [_out_path("ders", "script", "duz_okuma", "ders-b01.script.json"), | ||
| 748 | + _out_path("ders", "script", "duz_okuma", "ders-b02.script.json"), | ||
| 749 | + _out_path("ders", "script", "duz_okuma", "ders-b03.script.json")], | ||
| 750 | + 10.0, | ||
| 751 | + ), | ||
| 752 | + output_root, | ||
| 753 | + ) | ||
| 754 | + if len(trimmed["script_ids"]) != 1: | ||
| 755 | + problems.append( | ||
| 756 | + f"script_ids ses bolumlerine hizalanmadi: {trimmed['script_ids']}" | ||
| 757 | + ) | ||
| 758 | + | ||
| 759 | + outside = pipeline.derive_outputs( | ||
| 760 | + _FakeResult(["/baska/yer/x.mp3"], ["/baska/yer/x.script.json"], 1.0), | ||
| 761 | + output_root, | ||
| 762 | + ) | ||
| 763 | + if outside["audio_id"] != "x.mp3": | ||
| 764 | + problems.append(f"kok disi yol dosya adina dusmedi: {outside['audio_id']}") | ||
| 765 | + | ||
| 766 | + if pipeline.derive_outputs(_FakeResult([], [], 0.0), output_root)["audio_ids"]: | ||
| 767 | + problems.append("bos mp3 listesinden audio_ids uretildi") | ||
| 768 | + | ||
| 769 | + for missing in ("router/yonlendirici.py", "config/router.toml", "script/plan.py"): | ||
| 770 | + fake_root = os.path.join(root, "sahte-hat") | ||
| 771 | + os.makedirs(os.path.join(fake_root, "router"), exist_ok=True) | ||
| 772 | + with open(os.path.join(fake_root, "router", "hat.py"), "w") as h: | ||
| 773 | + h.write("") | ||
| 774 | + try: | ||
| 775 | + pipeline.check_pipeline_path(fake_root) | ||
| 776 | + problems.append(f"eksik {missing} olan kok mod kapisini gecti") | ||
| 777 | + except pipeline.PipelineUnavailable: | ||
| 778 | + pass | ||
| 779 | + break | ||
| 780 | + | ||
| 781 | + cancelled_ctx = _FakeCtx(True, pipeline.REAL_STAGES) | ||
| 782 | + hook = pipeline.build_log_hook(cancelled_ctx, lambda: 1, pipeline.REAL_STAGES, _FakeInterrupt) | ||
| 783 | + try: | ||
| 784 | + hook("[KOSTU ] ingest") | ||
| 785 | + problems.append("iptal istenmisken gunluk kancasi kesme firlatmadi") | ||
| 786 | + except _FakeInterrupt: | ||
| 787 | + pass | ||
| 788 | + if cancelled_ctx.seen: | ||
| 789 | + problems.append("iptal edilen iste kanca yine de ilerleme yazdi") | ||
| 790 | + | ||
| 791 | + live_ctx = _FakeCtx(False, pipeline.REAL_STAGES) | ||
| 792 | + live_hook = pipeline.build_log_hook(live_ctx, lambda: 2, pipeline.REAL_STAGES, _FakeInterrupt) | ||
| 793 | + live_hook("[KOSTU ] scriptler") | ||
| 794 | + if live_ctx.seen != [("quiz", 0.5)]: | ||
| 795 | + problems.append(f"kanca ilerlemeyi adim sayisindan turetmedi: {live_ctx.seen}") | ||
| 796 | + | ||
| 797 | + media_root = os.path.join(root, "hat-medya") | ||
| 798 | + os.makedirs(media_root, exist_ok=True) | ||
| 799 | + with open(os.path.join(media_root, "ders.pdf"), "wb") as handle: | ||
| 800 | + handle.write(b"%PDF-1.4\n") | ||
| 801 | + | ||
| 802 | + ok_store = _pipeline_store( | ||
| 803 | + root, | ||
| 804 | + "hat-ok", | ||
| 805 | + media_root, | ||
| 806 | + ["/out/ders/bolum-1.mp3", "/out/ders/bolum-2.mp3"], | ||
| 807 | + ["/out/ders/bolum-1.txt", "/out/ders/bolum-2.txt"], | ||
| 808 | + ) | ||
| 809 | + ok_store.start() | ||
| 810 | + capabilities.configure(ok_store, llm_ready=False) | ||
| 811 | + try: | ||
| 812 | + job_id = capabilities.dispatch("podcast.submit", {"source_id": "ders.pdf"})["job_id"] | ||
| 813 | + final = _await_state(ok_store, job_id, (jobs.STATE_DONE, jobs.STATE_FAILED), 10.0) | ||
| 814 | + if final["state"] != jobs.STATE_DONE: | ||
| 815 | + problems.append( | ||
| 816 | + "sahte Hat ile kosan gercek runner 'done' vermedi: " | ||
| 817 | + f"{final['state']} {final['error_code']}" | ||
| 818 | + ) | ||
| 819 | + else: | ||
| 820 | + payload = capabilities.dispatch("podcast.result", {"job_id": job_id}) | ||
| 821 | + if payload.get("audio_id") != "bolum-1.mp3": | ||
| 822 | + problems.append(f"result audio_id yanlis: {payload.get('audio_id')}") | ||
| 823 | + if payload.get("script_id") != "bolum-1.txt": | ||
| 824 | + problems.append(f"result script_id yanlis: {payload.get('script_id')}") | ||
| 825 | + if payload.get("duration_secs") != 123.5: | ||
| 826 | + problems.append(f"result duration_secs yanlis: {payload.get('duration_secs')}") | ||
| 827 | + if payload.get("audio_ids") != ["bolum-1.mp3", "bolum-2.mp3"]: | ||
| 828 | + problems.append(f"result audio_ids yanlis: {payload.get('audio_ids')}") | ||
| 829 | + if payload.get("script_ids") != ["bolum-1.txt", "bolum-2.txt"]: | ||
| 830 | + problems.append(f"result script_ids yanlis: {payload.get('script_ids')}") | ||
| 831 | + finally: | ||
| 832 | + ok_store.shutdown() | ||
| 833 | + | ||
| 834 | + quiet_store = _pipeline_store(root, "hat-sessiz", media_root, [], ["/out/ders/bolum-1.txt"]) | ||
| 835 | + quiet_store.start() | ||
| 836 | + capabilities.configure(quiet_store, llm_ready=False) | ||
| 837 | + try: | ||
| 838 | + job_id = capabilities.dispatch("podcast.submit", {"source_id": "ders.pdf"})["job_id"] | ||
| 839 | + final = _await_state(quiet_store, job_id, (jobs.STATE_DONE, jobs.STATE_FAILED), 10.0) | ||
| 840 | + if final["state"] != jobs.STATE_FAILED: | ||
| 841 | + problems.append(f"mp3 uretilmeyen is 'failed' olmadi: {final['state']}") | ||
| 842 | + if final["error_code"] != pipeline.NO_AUDIO: | ||
| 843 | + problems.append(f"sessiz kosunun hata kodu yanlis: {final['error_code']}") | ||
| 844 | + if final["audio_id"] is not None: | ||
| 845 | + problems.append("ses uretmeyen is yine de audio_id yazdi") | ||
| 846 | + finally: | ||
| 847 | + quiet_store.shutdown() | ||
| 848 | + | ||
| 849 | + missing_store = _pipeline_store(root, "hat-kayip", media_root, ["/out/x.mp3"], ["/out/x.txt"]) | ||
| 850 | + missing_store.start() | ||
| 851 | + capabilities.configure(missing_store, llm_ready=False) | ||
| 852 | + try: | ||
| 853 | + job_id = capabilities.dispatch("podcast.submit", {"source_id": "yok.pdf"})["job_id"] | ||
| 854 | + final = _await_state(missing_store, job_id, (jobs.STATE_DONE, jobs.STATE_FAILED), 10.0) | ||
| 855 | + if final["state"] != jobs.STATE_FAILED: | ||
| 856 | + problems.append(f"kaynagi olmayan is 'failed' olmadi: {final['state']}") | ||
| 857 | + if final["error_code"] != pipeline.SOURCE_NOT_FOUND: | ||
| 858 | + problems.append(f"kayip kaynagin hata kodu yanlis: {final['error_code']}") | ||
| 859 | + finally: | ||
| 860 | + missing_store.shutdown() | ||
| 861 | + | ||
| 862 | + capabilities.configure(None, llm_ready=False) | ||
| 863 | + return problems | ||
| 864 | + | ||
| 865 | + | ||
| 866 | +def validate() -> int: | ||
| 867 | + from . import capabilities, config | ||
| 868 | + | ||
| 869 | + settings = config.load(require_token=False) | ||
| 870 | + print(f"[bridge] yapilandirma: {settings.summary()}", flush=True) | ||
| 871 | + if not settings.has_token: | ||
| 872 | + print( | ||
| 873 | + "[bridge] uyari: AI_SHARED_TOKEN tanimsiz; kopru bu haliyle acilista cikar", | ||
| 874 | + flush=True, | ||
| 875 | + ) | ||
| 876 | + print(f"[bridge] {capabilities.format_summary(settings.has_llm_key)}", flush=True) | ||
| 877 | + | ||
| 878 | + from . import pipeline | ||
| 879 | + | ||
| 880 | + if settings.mode == pipeline.MODE_REAL: | ||
| 881 | + try: | ||
| 882 | + source_root = pipeline.check_pipeline_path(settings.pipeline_path) | ||
| 883 | + except pipeline.PipelineUnavailable as exc: | ||
| 884 | + print(f"[bridge] PODCAST_MODE=real ama hat kaynagi yok: {exc}", flush=True) | ||
| 885 | + return 2 | ||
| 886 | + print(f"[bridge] gercek hat kaynagi: {source_root}", flush=True) | ||
| 887 | + else: | ||
| 888 | + print(f"[bridge] uyari: {pipeline.FAKE_WARNING}", flush=True) | ||
| 889 | + | ||
| 890 | + problems = _guard("cerceveleme", _check_framing) | ||
| 891 | + with tempfile.TemporaryDirectory(prefix="podcast-validate-") as root: | ||
| 892 | + problems += _guard("is deposu", _check_job_store, root) | ||
| 893 | + problems += _guard("yetenek defteri", _check_registry, root) | ||
| 894 | + problems += _guard("yasam dongusu", _check_lifecycle, root) | ||
| 895 | + problems += _guard("iptal yarisi", _check_cancel_race, root) | ||
| 896 | + problems += _guard("erken hata", _check_early_failure, root) | ||
| 897 | + problems += _guard("kaynak yolu", _check_source_paths, root) | ||
| 898 | + problems += _guard("eta kaynagi", _check_eta_source, root) | ||
| 899 | + problems += _guard("kayit semasi", _check_record_schema, root) | ||
| 900 | + problems += _guard("kapanma", _check_shutdown, root) | ||
| 901 | + problems += _guard("gercek hat kablosu", _check_pipeline, root) | ||
| 902 | + | ||
| 903 | + if problems: | ||
| 904 | + for problem in problems: | ||
| 905 | + print(f"[bridge] butunluk hatasi: {problem}", flush=True) | ||
| 906 | + return 1 | ||
| 907 | + | ||
| 908 | + print(f"[bridge] yetenekler: {', '.join(capabilities.names())}", flush=True) | ||
| 909 | + print("[bridge] butunluk kontrolu tamam (ag kullanilmadi)", flush=True) | ||
| 910 | + return 0 | ||
| 911 | + | ||
| 912 | + | ||
| 913 | +def _check_writable(root: str, label: str, problems: list[str], notes: list[str]) -> None: | ||
| 914 | + target = Path(root) | ||
| 915 | + probe = target / f".health-{os.getpid()}" | ||
| 916 | + try: | ||
| 917 | + target.mkdir(parents=True, exist_ok=True) | ||
| 918 | + with open(probe, "w", encoding="ascii") as handle: | ||
| 919 | + handle.write("ok") | ||
| 920 | + probe.unlink() | ||
| 921 | + except OSError as exc: | ||
| 922 | + problems.append(f"{label} yazilamiyor ({target}): {exc}") | ||
| 923 | + return | ||
| 924 | + notes.append(f"{label} yazilabilir: {target}") | ||
| 925 | + | ||
| 926 | + | ||
| 927 | +def health() -> int: | ||
| 928 | + from . import config, jobs, pipeline | ||
| 929 | + | ||
| 930 | + settings = config.load(require_token=False) | ||
| 931 | + problems: list[str] = [] | ||
| 932 | + notes: list[str] = [f"mod={settings.mode}"] | ||
| 933 | + | ||
| 934 | + _check_writable(settings.job_root, "is koku", problems, notes) | ||
| 935 | + _check_writable(settings.output_root, "cikti koku", problems, notes) | ||
| 936 | + | ||
| 937 | + if settings.mode == pipeline.MODE_REAL: | ||
| 938 | + try: | ||
| 939 | + source_root = pipeline.check_pipeline_path(settings.pipeline_path) | ||
| 940 | + pipeline.load_pipeline(settings.pipeline_path) | ||
| 941 | + notes.append(f"hat iceri alindi: {source_root}") | ||
| 942 | + except pipeline.PipelineUnavailable as exc: | ||
| 943 | + problems.append(f"hat yuklenemedi: {exc}") | ||
| 944 | + else: | ||
| 945 | + notes.append("simulate modda hat denetlenmez") | ||
| 946 | + | ||
| 947 | + status = jobs.read_status(settings.job_root) | ||
| 948 | + if status is None: | ||
| 949 | + problems.append( | ||
| 950 | + f"kopru durum dosyasi yok ({jobs.status_path(settings.job_root)}); " | ||
| 951 | + "kayit henuz yapilmadi" | ||
| 952 | + ) | ||
| 953 | + elif not status.get("registered"): | ||
| 954 | + problems.append("kopru backend'e kayitli degil (durum dosyasi registered=false)") | ||
| 955 | + else: | ||
| 956 | + notes.append(f"kayitli: worker_id={status.get('worker_id', '?')}") | ||
| 957 | + | ||
| 958 | + for note in notes: | ||
| 959 | + print(f"[bridge] saglik: {note}", flush=True) | ||
| 960 | + if problems: | ||
| 961 | + for problem in problems: | ||
| 962 | + print(f"[bridge] saglik HATASI: {problem}", flush=True) | ||
| 963 | + return 1 | ||
| 964 | + print("[bridge] saglik: TAMAM", flush=True) | ||
| 965 | + return 0 | ||
| 966 | + | ||
| 967 | + | ||
| 968 | +def build_parser() -> argparse.ArgumentParser: | ||
| 969 | + parser = argparse.ArgumentParser(description="Hezarfen podcast servisi") | ||
| 970 | + parser.add_argument( | ||
| 971 | + "--validate", | ||
| 972 | + action="store_true", | ||
| 973 | + help="Yapilandirma, yetenek defteri, is deposu ve cerceveleme butunlugunu ag olmadan dogrular.", | ||
| 974 | + ) | ||
| 975 | + parser.add_argument( | ||
| 976 | + "--health", | ||
| 977 | + action="store_true", | ||
| 978 | + help="Canlilik denetimi: is/cikti koku yazilabilir mi, real modda hat iceri alinabilir mi, kopru kayitli mi.", | ||
| 979 | + ) | ||
| 980 | + return parser | ||
| 981 | + | ||
| 982 | + | ||
| 983 | +def main() -> int: | ||
| 984 | + args = build_parser().parse_args() | ||
| 985 | + if args.health: | ||
| 986 | + return health() | ||
| 987 | + if args.validate: | ||
| 988 | + return validate() | ||
| 989 | + | ||
| 990 | + from .bridge import main as bridge_main | ||
| 991 | + | ||
| 992 | + return bridge_main() | ||
| 993 | + | ||
| 994 | + | ||
| 995 | +if __name__ == "__main__": | ||
| 996 | + sys.exit(main()) | ||
src/pipeline.pyadded+338 -0
| @@ -0,0 +1,338 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import sys | ||
| 4 | +from pathlib import Path | ||
| 5 | +from typing import Any, Callable | ||
| 6 | + | ||
| 7 | +from . import config, jobs | ||
| 8 | + | ||
| 9 | +MODE_SIMULATE = "simulate" | ||
| 10 | +MODE_REAL = "real" | ||
| 11 | +MODES = (MODE_SIMULATE, MODE_REAL) | ||
| 12 | + | ||
| 13 | +REAL_STAGES = ("ingest", "scriptler", "quiz", "ses") | ||
| 14 | +REQUIRED_PIPELINE_FILES = ( | ||
| 15 | + "router/hat.py", | ||
| 16 | + "router/yonlendirici.py", | ||
| 17 | + "config/router.toml", | ||
| 18 | + "ingest/__init__.py", | ||
| 19 | + "script/plan.py", | ||
| 20 | + "ses/montaj.py", | ||
| 21 | +) | ||
| 22 | +PIPELINE_MISCONFIGURED = "pipeline_misconfigured" | ||
| 23 | +REAL_ETA_SECS = 2700.0 | ||
| 24 | + | ||
| 25 | +PIPELINE_MODULE = "router.hat" | ||
| 26 | + | ||
| 27 | +SOURCE_NOT_FOUND = "source_not_found" | ||
| 28 | +NO_AUDIO = "no_audio" | ||
| 29 | + | ||
| 30 | +FAKE_WARNING = "SAHTE hat kosuyor, uretilen ses GERCEK DEGIL" | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +class PipelineUnavailable(Exception): | ||
| 34 | + pass | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +def check_pipeline_path(pipeline_path: str) -> Path: | ||
| 38 | + if not isinstance(pipeline_path, str) or not pipeline_path.strip(): | ||
| 39 | + raise PipelineUnavailable( | ||
| 40 | + "PODCAST_PIPELINE_PATH tanimsiz; PODCAST_MODE=real hat kaynaginin " | ||
| 41 | + "kokunu ister (ornek: /opt/podcast)" | ||
| 42 | + ) | ||
| 43 | + root = Path(pipeline_path.strip()).expanduser() | ||
| 44 | + try: | ||
| 45 | + root = root.resolve() | ||
| 46 | + except OSError as exc: | ||
| 47 | + raise PipelineUnavailable( | ||
| 48 | + f"PODCAST_PIPELINE_PATH cozulemedi ({pipeline_path}): {exc}" | ||
| 49 | + ) from exc | ||
| 50 | + if not root.is_dir(): | ||
| 51 | + raise PipelineUnavailable(f"PODCAST_PIPELINE_PATH bir dizin degil: {root}") | ||
| 52 | + for part in REQUIRED_PIPELINE_FILES: | ||
| 53 | + if not (root / part).is_file(): | ||
| 54 | + raise PipelineUnavailable( | ||
| 55 | + f"PODCAST_PIPELINE_PATH altinda {part} yok: {root}" | ||
| 56 | + ) | ||
| 57 | + return root | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +def prepare_path(pipeline_path: str) -> Path: | ||
| 61 | + root = check_pipeline_path(pipeline_path) | ||
| 62 | + text = str(root) | ||
| 63 | + if text not in sys.path: | ||
| 64 | + sys.path.append(text) | ||
| 65 | + return root | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +def load_pipeline(pipeline_path: str) -> tuple[Any, Any, Any, Any]: | ||
| 69 | + root = prepare_path(pipeline_path) | ||
| 70 | + try: | ||
| 71 | + from router.hat import Hat, HatHatasi, KasitliKesme | ||
| 72 | + from router.kayit import Kayit | ||
| 73 | + except Exception as exc: | ||
| 74 | + raise PipelineUnavailable( | ||
| 75 | + f"{PIPELINE_MODULE} iceri alinamadi ({root}): {type(exc).__name__}: {exc}" | ||
| 76 | + ) from exc | ||
| 77 | + return Hat, HatHatasi, KasitliKesme, Kayit | ||
| 78 | + | ||
| 79 | + | ||
| 80 | +def probe_pipeline(pipeline_path: str) -> dict[str, Any]: | ||
| 81 | + prepare_path(pipeline_path) | ||
| 82 | + try: | ||
| 83 | + from router.yonlendirici import Katman, Yonlendirici | ||
| 84 | + except Exception as exc: | ||
| 85 | + raise PipelineUnavailable( | ||
| 86 | + f"router.yonlendirici iceri alinamadi: {type(exc).__name__}: {exc}" | ||
| 87 | + ) from exc | ||
| 88 | + try: | ||
| 89 | + router = Yonlendirici() | ||
| 90 | + resolution = router.katman_cozumu(Katman.GUCLU) | ||
| 91 | + general = router.ayarlar.genel | ||
| 92 | + except Exception as exc: | ||
| 93 | + raise PipelineUnavailable( | ||
| 94 | + f"hat yapilandirmasi okunamadi: {type(exc).__name__}: {exc}" | ||
| 95 | + ) from exc | ||
| 96 | + return { | ||
| 97 | + "llm_ready": bool(resolution.hazir), | ||
| 98 | + "llm_reason": str(resolution.gerekce), | ||
| 99 | + "maks_usd": float(general.maks_usd), | ||
| 100 | + "maks_cagri_usd": float(general.maks_cagri_usd), | ||
| 101 | + "onbellek": bool(general.onbellek), | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + | ||
| 105 | +def resolve_pdf(media_root: str, source_id: str) -> Path: | ||
| 106 | + path = jobs.resolve_source(media_root, source_id) | ||
| 107 | + if not path.is_file(): | ||
| 108 | + raise FileNotFoundError(f"kaynak dosya yok: {path}") | ||
| 109 | + return path | ||
| 110 | + | ||
| 111 | + | ||
| 112 | +def normalize_limit(chapter_limit: int) -> int | None: | ||
| 113 | + return None if int(chapter_limit) <= 0 else int(chapter_limit) | ||
| 114 | + | ||
| 115 | + | ||
| 116 | +def _relative_id(value: Any, output_root: Path | None) -> str: | ||
| 117 | + path = Path(str(value)) | ||
| 118 | + if output_root is not None: | ||
| 119 | + try: | ||
| 120 | + return path.resolve().relative_to(output_root.resolve()).as_posix() | ||
| 121 | + except (ValueError, OSError): | ||
| 122 | + pass | ||
| 123 | + return path.name | ||
| 124 | + | ||
| 125 | + | ||
| 126 | +def _names(values: Any, output_root: Path | None = None) -> list[str]: | ||
| 127 | + if not values: | ||
| 128 | + return [] | ||
| 129 | + return [_relative_id(value, output_root) for value in values] | ||
| 130 | + | ||
| 131 | + | ||
| 132 | +def _chapter_key(identifier: str) -> str: | ||
| 133 | + base = identifier.rsplit("/", 1)[-1] | ||
| 134 | + for suffix in (".script.json", ".mp3", ".json"): | ||
| 135 | + if base.endswith(suffix): | ||
| 136 | + return base[: -len(suffix)] | ||
| 137 | + return base | ||
| 138 | + | ||
| 139 | + | ||
| 140 | +def _align_scripts(audio_ids: list[str], script_ids: list[str]) -> list[str]: | ||
| 141 | + if not audio_ids or not script_ids: | ||
| 142 | + return script_ids | ||
| 143 | + chapters = {_chapter_key(a) for a in audio_ids} | ||
| 144 | + matched = [s for s in script_ids if _chapter_key(s) in chapters] | ||
| 145 | + if not matched: | ||
| 146 | + config.log( | ||
| 147 | + "warn", | ||
| 148 | + "script kimlikleri ses bolumleriyle eslesmedi; filtrelenmeden " | ||
| 149 | + "donuluyor (audio=%d script=%d)" % (len(audio_ids), len(script_ids)), | ||
| 150 | + ) | ||
| 151 | + return script_ids | ||
| 152 | + return matched | ||
| 153 | + | ||
| 154 | + | ||
| 155 | +def derive_outputs(result: Any, output_root: Any = None) -> dict[str, Any]: | ||
| 156 | + root = Path(output_root) if output_root else None | ||
| 157 | + audio_ids = _names(getattr(result, "mp3_yollari", None), root) | ||
| 158 | + script_ids = _align_scripts( | ||
| 159 | + audio_ids, _names(getattr(result, "script_yollari", None), root) | ||
| 160 | + ) | ||
| 161 | + try: | ||
| 162 | + duration = float(getattr(result, "ses_toplam_sn", 0.0) or 0.0) | ||
| 163 | + except (TypeError, ValueError): | ||
| 164 | + duration = 0.0 | ||
| 165 | + return { | ||
| 166 | + "audio_id": audio_ids[0] if audio_ids else "", | ||
| 167 | + "script_id": script_ids[0] if script_ids else "", | ||
| 168 | + "duration_secs": duration, | ||
| 169 | + "audio_ids": audio_ids, | ||
| 170 | + "script_ids": script_ids, | ||
| 171 | + } | ||
| 172 | + | ||
| 173 | + | ||
| 174 | +def build_log_hook( | ||
| 175 | + ctx: Any, | ||
| 176 | + steps: Callable[[], int], | ||
| 177 | + stages: tuple[str, ...], | ||
| 178 | + interrupt: Any, | ||
| 179 | +) -> Callable[[str], None]: | ||
| 180 | + names = tuple(stages) if stages else REAL_STAGES | ||
| 181 | + total = max(1, len(names)) | ||
| 182 | + | ||
| 183 | + def hook(message: str) -> None: | ||
| 184 | + if ctx.cancelled(): | ||
| 185 | + raise interrupt("iptal istendi") | ||
| 186 | + try: | ||
| 187 | + done = int(steps()) | ||
| 188 | + except Exception: | ||
| 189 | + done = 0 | ||
| 190 | + if done < 0: | ||
| 191 | + done = 0 | ||
| 192 | + ctx.progress(names[min(done, total - 1)], min(float(done) / float(total), 1.0)) | ||
| 193 | + config.log("debug", f"hat: {str(message).strip()}") | ||
| 194 | + | ||
| 195 | + return hook | ||
| 196 | + | ||
| 197 | + | ||
| 198 | +def make_runner( | ||
| 199 | + media_root: str, | ||
| 200 | + output_root: str, | ||
| 201 | + chapter_limit: int, | ||
| 202 | + tts_engine: str, | ||
| 203 | + pipeline_factory: Any, | ||
| 204 | + pipeline_error: Any, | ||
| 205 | + interrupt: Any, | ||
| 206 | + ledger_factory: Any = None, | ||
| 207 | + ledger_path: str = "", | ||
| 208 | + budget: dict[str, Any] | None = None, | ||
| 209 | +) -> Callable[[jobs.JobContext], None]: | ||
| 210 | + limit = normalize_limit(chapter_limit) | ||
| 211 | + output_dir = Path(output_root) | ||
| 212 | + budget = budget or {} | ||
| 213 | + | ||
| 214 | + def runner(ctx: jobs.JobContext) -> None: | ||
| 215 | + stages = tuple(ctx.stages) if ctx.stages else REAL_STAGES | ||
| 216 | + try: | ||
| 217 | + pdf = resolve_pdf(media_root, ctx.source_id) | ||
| 218 | + except (ValueError, FileNotFoundError, OSError) as exc: | ||
| 219 | + config.log("error", f"is {ctx.job_id} kaynagi cozulemedi: {exc}") | ||
| 220 | + ctx.store.fail(ctx.job_id, SOURCE_NOT_FOUND) | ||
| 221 | + return | ||
| 222 | + | ||
| 223 | + ctx.check() | ||
| 224 | + ctx.progress(stages[0], 0.0) | ||
| 225 | + | ||
| 226 | + holder: list[Any] = [] | ||
| 227 | + | ||
| 228 | + def steps() -> int: | ||
| 229 | + if not holder: | ||
| 230 | + return 0 | ||
| 231 | + return len(getattr(getattr(holder[0], "sonuc", None), "adimlar", ()) or ()) | ||
| 232 | + | ||
| 233 | + hook = build_log_hook(ctx, steps, stages, interrupt) | ||
| 234 | + | ||
| 235 | + try: | ||
| 236 | + ledger = None | ||
| 237 | + if ledger_factory is not None and ledger_path: | ||
| 238 | + ledger = ledger_factory( | ||
| 239 | + ledger_path, | ||
| 240 | + maks_usd=float(budget.get("maks_usd", 5.0)), | ||
| 241 | + maks_cagri_usd=float(budget.get("maks_cagri_usd", 0.50)), | ||
| 242 | + onbellek_acik=bool(budget.get("onbellek", True)), | ||
| 243 | + ) | ||
| 244 | + pipeline = pipeline_factory( | ||
| 245 | + pdf=str(pdf), | ||
| 246 | + format=ctx.format, | ||
| 247 | + gunluk=hook, | ||
| 248 | + cikti_koku=output_dir, | ||
| 249 | + bolum_limiti=limit, | ||
| 250 | + motor_adi=tts_engine, | ||
| 251 | + ses_uret=True, | ||
| 252 | + kayit=ledger, | ||
| 253 | + ) | ||
| 254 | + except pipeline_error as exc: | ||
| 255 | + config.log("error", f"is {ctx.job_id} hat kurulamadi: {exc}") | ||
| 256 | + ctx.store.fail(ctx.job_id, PIPELINE_MISCONFIGURED) | ||
| 257 | + return | ||
| 258 | + except Exception as exc: | ||
| 259 | + config.log( | ||
| 260 | + "error", | ||
| 261 | + f"is {ctx.job_id} hat kurulamadi ({type(exc).__name__}): {exc}", | ||
| 262 | + ) | ||
| 263 | + ctx.store.fail(ctx.job_id, PIPELINE_MISCONFIGURED) | ||
| 264 | + return | ||
| 265 | + holder.append(pipeline) | ||
| 266 | + | ||
| 267 | + config.log("info", f"is {ctx.job_id} gercek hatta veriliyor: {pdf.name}") | ||
| 268 | + try: | ||
| 269 | + result = pipeline.kos() | ||
| 270 | + except interrupt as exc: | ||
| 271 | + if ctx.cancelled(): | ||
| 272 | + raise jobs.JobCancelled(ctx.job_id) from exc | ||
| 273 | + config.log("error", f"is {ctx.job_id} hat tarafindan bilerek kesildi: {exc}") | ||
| 274 | + raise | ||
| 275 | + | ||
| 276 | + outputs = derive_outputs(result, output_dir) | ||
| 277 | + if outputs["audio_ids"] and outputs["duration_secs"] <= 0.0: | ||
| 278 | + config.log( | ||
| 279 | + "warn", | ||
| 280 | + f"is {ctx.job_id} mp3 uretti ama sure 0.0 olctu; " | ||
| 281 | + f"duration_secs guvenilmez", | ||
| 282 | + ) | ||
| 283 | + if not outputs["audio_ids"]: | ||
| 284 | + config.log( | ||
| 285 | + "error", | ||
| 286 | + f"is {ctx.job_id} hicbir mp3 uretmedi; bos cevap donulmuyor", | ||
| 287 | + ) | ||
| 288 | + ctx.store.fail(ctx.job_id, NO_AUDIO) | ||
| 289 | + return | ||
| 290 | + | ||
| 291 | + record = ctx.finish( | ||
| 292 | + audio_id=outputs["audio_id"], | ||
| 293 | + duration_secs=outputs["duration_secs"], | ||
| 294 | + script_id=outputs["script_id"], | ||
| 295 | + audio_ids=outputs["audio_ids"], | ||
| 296 | + script_ids=outputs["script_ids"], | ||
| 297 | + ) | ||
| 298 | + if record["state"] == jobs.STATE_DONE: | ||
| 299 | + config.log( | ||
| 300 | + "info", | ||
| 301 | + f"is {ctx.job_id} tamamlandi (gercek hat): " | ||
| 302 | + f"{len(outputs['audio_ids'])} mp3, " | ||
| 303 | + f"{outputs['duration_secs']:.1f}s ses", | ||
| 304 | + ) | ||
| 305 | + else: | ||
| 306 | + config.log("info", f"is {ctx.job_id} bitis aninda iptal edildi") | ||
| 307 | + | ||
| 308 | + return runner | ||
| 309 | + | ||
| 310 | + | ||
| 311 | +def build_runner(settings: Any) -> tuple[Callable[[jobs.JobContext], None], dict[str, Any]]: | ||
| 312 | + pipeline_factory, pipeline_error, interrupt, ledger_factory = load_pipeline(settings.pipeline_path) | ||
| 313 | + probe = probe_pipeline(settings.pipeline_path) | ||
| 314 | + runner = make_runner( | ||
| 315 | + settings.media_root, | ||
| 316 | + settings.output_root, | ||
| 317 | + settings.chapter_limit, | ||
| 318 | + settings.tts_engine, | ||
| 319 | + pipeline_factory, | ||
| 320 | + pipeline_error, | ||
| 321 | + interrupt, | ||
| 322 | + ledger_factory=ledger_factory, | ||
| 323 | + ledger_path=settings.ledger_db, | ||
| 324 | + budget=probe, | ||
| 325 | + ) | ||
| 326 | + return runner, probe | ||
| 327 | + | ||
| 328 | + | ||
| 329 | +def job_secs_for(settings: Any) -> float | None: | ||
| 330 | + if settings.eta_secs > 0: | ||
| 331 | + return float(settings.eta_secs) | ||
| 332 | + if settings.mode == MODE_REAL: | ||
| 333 | + return REAL_ETA_SECS | ||
| 334 | + return None | ||
| 335 | + | ||
| 336 | + | ||
| 337 | +def stages_for(settings: Any) -> tuple[str, ...] | None: | ||
| 338 | + return REAL_STAGES if settings.mode == MODE_REAL else None | ||
src/protocol.pyadded+209 -0
| @@ -0,0 +1,209 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import asyncio | ||
| 4 | +import json | ||
| 5 | +import math | ||
| 6 | +import struct | ||
| 7 | +from typing import Any | ||
| 8 | + | ||
| 9 | +PROTOCOL = "hab/1" | ||
| 10 | +MAX_FRAME_BYTES = 8 * 1024 * 1024 | ||
| 11 | +KEEPALIVE_SECS = 10 | ||
| 12 | +IDLE_TIMEOUT_SECS = 30.0 | ||
| 13 | +GREETING_TIMEOUT_SECS = 8.0 | ||
| 14 | +CERTIFICATE_PATH = "/ai/certificate" | ||
| 15 | +DEADLINE_MARGIN_SECS = 0.25 | ||
| 16 | +API_TIMEOUT_SECS = 15.0 | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +class CapabilityError(Exception): | ||
| 20 | + def __init__(self, code: str, message: str) -> None: | ||
| 21 | + super().__init__(message) | ||
| 22 | + self.code = code | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +class HandshakeRejected(RuntimeError): | ||
| 26 | + def __init__(self, code: str, message: str) -> None: | ||
| 27 | + super().__init__(f"backend kaydi reddetti ({code}): {message}") | ||
| 28 | + self.code = code | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def encode_frame(obj: Any) -> bytes: | ||
| 32 | + body = json.dumps(obj, ensure_ascii=False).encode("utf-8") | ||
| 33 | + if len(body) > MAX_FRAME_BYTES: | ||
| 34 | + raise CapabilityError("frame_too_large", f"{len(body)} bayt cerceve sinirini asiyor") | ||
| 35 | + return struct.pack(">I", len(body)) + body | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +class FrameStream: | ||
| 39 | + def __init__(self) -> None: | ||
| 40 | + self._buf = bytearray() | ||
| 41 | + self._queue: "asyncio.Queue[bytes | None]" = asyncio.Queue() | ||
| 42 | + self._eof = False | ||
| 43 | + | ||
| 44 | + def feed(self, data: bytes, end: bool) -> None: | ||
| 45 | + if data: | ||
| 46 | + self._queue.put_nowait(data) | ||
| 47 | + if end: | ||
| 48 | + self._queue.put_nowait(None) | ||
| 49 | + | ||
| 50 | + async def _read_exact(self, n: int) -> bytes: | ||
| 51 | + while len(self._buf) < n: | ||
| 52 | + if self._eof: | ||
| 53 | + raise EOFError("cerceve tamamlanmadan akis bitti") | ||
| 54 | + chunk = await self._queue.get() | ||
| 55 | + if chunk is None: | ||
| 56 | + self._eof = True | ||
| 57 | + continue | ||
| 58 | + self._buf.extend(chunk) | ||
| 59 | + out = bytes(self._buf[:n]) | ||
| 60 | + del self._buf[:n] | ||
| 61 | + return out | ||
| 62 | + | ||
| 63 | + async def read_frame(self) -> Any: | ||
| 64 | + header = await self._read_exact(4) | ||
| 65 | + (length,) = struct.unpack(">I", header) | ||
| 66 | + if length > MAX_FRAME_BYTES: | ||
| 67 | + raise CapabilityError("frame_too_large", f"{length} bayt cerceve sinirini asiyor") | ||
| 68 | + body = await self._read_exact(length) | ||
| 69 | + return json.loads(body) | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +def build_hello( | ||
| 73 | + service: str, capabilities: list[str], token: str, max_concurrent: int | ||
| 74 | +) -> dict[str, Any]: | ||
| 75 | + return { | ||
| 76 | + "protocol": PROTOCOL, | ||
| 77 | + "service": service, | ||
| 78 | + "capabilities": list(capabilities), | ||
| 79 | + "token": token, | ||
| 80 | + "max_concurrent": max_concurrent, | ||
| 81 | + } | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def parse_greeting(greeting: Any) -> str: | ||
| 85 | + if not isinstance(greeting, dict): | ||
| 86 | + raise HandshakeRejected("malformed", "greeting bir nesne degil") | ||
| 87 | + if greeting.get("type") == "welcome": | ||
| 88 | + if greeting.get("protocol") != PROTOCOL: | ||
| 89 | + raise HandshakeRejected( | ||
| 90 | + "unsupported_protocol", f"beklenmeyen protokol: {greeting.get('protocol')}" | ||
| 91 | + ) | ||
| 92 | + return str(greeting.get("worker_id", "?")) | ||
| 93 | + raise HandshakeRejected( | ||
| 94 | + str(greeting.get("code", "?")), str(greeting.get("message", "")) | ||
| 95 | + ) | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +def ok_response(request_id: str, payload: dict[str, Any]) -> dict[str, Any]: | ||
| 99 | + return {"status": "ok", "id": request_id, "payload": payload} | ||
| 100 | + | ||
| 101 | + | ||
| 102 | +def err_response(request_id: str, code: str, message: str) -> dict[str, Any]: | ||
| 103 | + return {"status": "err", "id": request_id, "code": code, "message": message} | ||
| 104 | + | ||
| 105 | + | ||
| 106 | +def parse_request(frame: Any) -> tuple[str, str, Any, float | None]: | ||
| 107 | + if not isinstance(frame, dict): | ||
| 108 | + raise CapabilityError("bad_request", "istek cercevesi bir nesne degil") | ||
| 109 | + request_id = frame.get("id") | ||
| 110 | + capability = frame.get("capability") | ||
| 111 | + if not isinstance(request_id, str) or not isinstance(capability, str): | ||
| 112 | + raise CapabilityError("bad_request", "'id' ve 'capability' metin olmali") | ||
| 113 | + deadline_ms = frame.get("deadline_ms") | ||
| 114 | + timeout = None | ||
| 115 | + if isinstance(deadline_ms, (int, float)) and not isinstance(deadline_ms, bool): | ||
| 116 | + if deadline_ms > 0: | ||
| 117 | + budget_secs = deadline_ms / 1000.0 | ||
| 118 | + timeout = max(budget_secs - DEADLINE_MARGIN_SECS, budget_secs * 0.5) | ||
| 119 | + return request_id, capability, frame.get("payload"), timeout | ||
| 120 | + | ||
| 121 | +API_ALLOWLIST = ( | ||
| 122 | + "/auth/me", | ||
| 123 | + "/users/me/profile", | ||
| 124 | + "/users/{id}/profile", | ||
| 125 | + "/notes", | ||
| 126 | + "/notes/{id}", | ||
| 127 | + "/homework", | ||
| 128 | + "/homework/{id}", | ||
| 129 | + "/homework/{id}/result", | ||
| 130 | + "/homework/{id}/submission", | ||
| 131 | + "/homework/report/{user}", | ||
| 132 | + "/marks/me", | ||
| 133 | + "/marks/{user}", | ||
| 134 | + "/attendance/me", | ||
| 135 | + "/attendance/{user}", | ||
| 136 | + "/pomodoro/me", | ||
| 137 | + "/pomodoro/{user}", | ||
| 138 | +) | ||
| 139 | + | ||
| 140 | + | ||
| 141 | +class ApiRefused(Exception): | ||
| 142 | + def __init__(self, code: str, message: str) -> None: | ||
| 143 | + super().__init__(f"kopru istegi reddetti ({code}): {message}") | ||
| 144 | + self.code = code | ||
| 145 | + | ||
| 146 | + | ||
| 147 | +class ApiResponse: | ||
| 148 | + def __init__(self, request_id: str, status: int, body: Any) -> None: | ||
| 149 | + self.request_id = request_id | ||
| 150 | + self.status = status | ||
| 151 | + self.body = body | ||
| 152 | + | ||
| 153 | + @property | ||
| 154 | + def ok(self) -> bool: | ||
| 155 | + return 200 <= self.status < 300 | ||
| 156 | + | ||
| 157 | + | ||
| 158 | +def build_api_request( | ||
| 159 | + request_id: str, | ||
| 160 | + path: str, | ||
| 161 | + query: str | None = None, | ||
| 162 | + on_behalf_of: str | None = None, | ||
| 163 | + method: str = "GET", | ||
| 164 | +) -> dict[str, Any]: | ||
| 165 | + if not isinstance(path, str) or not path.startswith("/") or "?" in path: | ||
| 166 | + raise ApiRefused( | ||
| 167 | + "bad_path", | ||
| 168 | + f"yol / ile baslamali ve ? icermemeli (query ayri alanda gider): {path!r}", | ||
| 169 | + ) | ||
| 170 | + request: dict[str, Any] = {"id": request_id, "path": path, "method": method} | ||
| 171 | + if query: | ||
| 172 | + request["query"] = query.lstrip("?") | ||
| 173 | + if on_behalf_of: | ||
| 174 | + request["on_behalf_of"] = on_behalf_of | ||
| 175 | + return request | ||
| 176 | + | ||
| 177 | + | ||
| 178 | +def _coerce_status(value: Any) -> int: | ||
| 179 | + if isinstance(value, bool): | ||
| 180 | + return int(value) | ||
| 181 | + if isinstance(value, int): | ||
| 182 | + return value | ||
| 183 | + if isinstance(value, float): | ||
| 184 | + if math.isnan(value) or math.isinf(value): | ||
| 185 | + raise ApiRefused("malformed", f"status sayisal degil: {value!r}") | ||
| 186 | + return int(value) | ||
| 187 | + if isinstance(value, str): | ||
| 188 | + try: | ||
| 189 | + return int(value) | ||
| 190 | + except ValueError as exc: | ||
| 191 | + raise ApiRefused("malformed", f"status sayisal degil: {value!r}") from exc | ||
| 192 | + raise ApiRefused("malformed", f"status sayisal degil: {value!r}") | ||
| 193 | + | ||
| 194 | + | ||
| 195 | +def parse_api_response(frame: Any) -> ApiResponse: | ||
| 196 | + if not isinstance(frame, dict): | ||
| 197 | + raise ApiRefused("malformed", "api cevabi bir nesne degil") | ||
| 198 | + outcome = frame.get("outcome") | ||
| 199 | + if outcome == "err": | ||
| 200 | + raise ApiRefused( | ||
| 201 | + str(frame.get("code", "?")), str(frame.get("message", "")) | ||
| 202 | + ) | ||
| 203 | + if outcome != "ok": | ||
| 204 | + raise ApiRefused("malformed", f"bilinmeyen outcome: {outcome!r}") | ||
| 205 | + return ApiResponse( | ||
| 206 | + str(frame.get("id", "")), | ||
| 207 | + _coerce_status(frame.get("status", 0)), | ||
| 208 | + frame.get("body"), | ||
| 209 | + ) | ||
tests/__init__.pyadded+0 -0
tests/fuzz/__init__.pyadded+0 -0
tests/fuzz/test_fuzz_protocol.pyadded+207 -0
| @@ -0,0 +1,207 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import asyncio | ||
| 4 | +import random | ||
| 5 | +import struct | ||
| 6 | +import sys | ||
| 7 | +import unittest | ||
| 8 | +from pathlib import Path | ||
| 9 | + | ||
| 10 | +sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) | ||
| 11 | + | ||
| 12 | +from src import capabilities, protocol | ||
| 13 | +from tools import fuzz_test | ||
| 14 | + | ||
| 15 | +ALLOWED_REQUEST = (protocol.CapabilityError, ValueError, EOFError) | ||
| 16 | +ALLOWED_GREETING = (protocol.HandshakeRejected, ValueError, EOFError) | ||
| 17 | +ALLOWED_API = (protocol.ApiRefused, ValueError, EOFError) | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def read_frame_bytes(blob: bytes): | ||
| 21 | + async def run(): | ||
| 22 | + stream = protocol.FrameStream() | ||
| 23 | + stream.feed(blob, end=True) | ||
| 24 | + return await stream.read_frame() | ||
| 25 | + | ||
| 26 | + return asyncio.run(run()) | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +class KnownCrashersStayFixed(unittest.TestCase): | ||
| 30 | + def test_a_non_numeric_status_is_refused_not_crashed(self) -> None: | ||
| 31 | + with self.assertRaises(protocol.ApiRefused) as caught: | ||
| 32 | + protocol.parse_api_response( | ||
| 33 | + {"outcome": "ok", "id": "r1", "status": [], "body": {}} | ||
| 34 | + ) | ||
| 35 | + self.assertEqual(caught.exception.code, "malformed") | ||
| 36 | + | ||
| 37 | + def test_an_infinite_status_is_refused_not_crashed(self) -> None: | ||
| 38 | + with self.assertRaises(protocol.ApiRefused) as caught: | ||
| 39 | + protocol.parse_api_response( | ||
| 40 | + {"outcome": "ok", "id": "r1", "status": float("inf"), "body": {}} | ||
| 41 | + ) | ||
| 42 | + self.assertEqual(caught.exception.code, "malformed") | ||
| 43 | + | ||
| 44 | + def test_every_unusable_status_shape_is_refused(self) -> None: | ||
| 45 | + for status in ([], {}, None, "abc", float("nan"), float("-inf"), | ||
| 46 | + "1e309", object()): | ||
| 47 | + with self.subTest(status=status): | ||
| 48 | + with self.assertRaises(protocol.ApiRefused): | ||
| 49 | + protocol.parse_api_response( | ||
| 50 | + {"outcome": "ok", "id": "r", "status": status} | ||
| 51 | + ) | ||
| 52 | + | ||
| 53 | + def test_a_usable_status_still_passes_through(self) -> None: | ||
| 54 | + for status, expected in ((200, 200), ("404", 404), (301.0, 301), (True, 1)): | ||
| 55 | + with self.subTest(status=status): | ||
| 56 | + answer = protocol.parse_api_response( | ||
| 57 | + {"outcome": "ok", "id": "r", "status": status} | ||
| 58 | + ) | ||
| 59 | + self.assertEqual(answer.status, expected) | ||
| 60 | + self.assertIs( | ||
| 61 | + type(answer.status), int, | ||
| 62 | + "status tam sayiya normallestirilmeli; bool dondurulurse " | ||
| 63 | + "assertEqual yakalayamaz cunku True == 1", | ||
| 64 | + ) | ||
| 65 | + | ||
| 66 | + | ||
| 67 | +class EveryCategoryStaysInsideTheDeclaredContract(unittest.TestCase): | ||
| 68 | + def _values(self): | ||
| 69 | + for name, values in fuzz_test.CATEGORY_STRINGS.items(): | ||
| 70 | + for value in values: | ||
| 71 | + yield name, value | ||
| 72 | + for value in fuzz_test.CATEGORY_SCALARS.get(name, []): | ||
| 73 | + yield name, value | ||
| 74 | + | ||
| 75 | + def _check(self, name, value, call, allowed) -> None: | ||
| 76 | + try: | ||
| 77 | + call() | ||
| 78 | + except allowed: | ||
| 79 | + return | ||
| 80 | + except RecursionError: | ||
| 81 | + return | ||
| 82 | + except BaseException as exc: | ||
| 83 | + self.fail( | ||
| 84 | + "kategori %s: beyan edilmemis %s -> %s (girdi %.80r)" | ||
| 85 | + % (name, type(exc).__name__, exc, value) | ||
| 86 | + ) | ||
| 87 | + | ||
| 88 | + def test_parse_request_never_raises_an_undeclared_exception(self) -> None: | ||
| 89 | + for name, value in self._values(): | ||
| 90 | + for field in ("id", "capability", "payload", "deadline_ms"): | ||
| 91 | + frame = dict(fuzz_test.SEED_FRAMES[0]) | ||
| 92 | + frame[field] = value | ||
| 93 | + with self.subTest(category=name, field=field): | ||
| 94 | + self._check(name, value, | ||
| 95 | + lambda f=frame: protocol.parse_request(f), | ||
| 96 | + ALLOWED_REQUEST) | ||
| 97 | + | ||
| 98 | + def test_parse_greeting_never_raises_an_undeclared_exception(self) -> None: | ||
| 99 | + for name, value in self._values(): | ||
| 100 | + for field in ("type", "protocol", "worker_id", "code"): | ||
| 101 | + greeting = dict(fuzz_test.SEED_GREETINGS[0]) | ||
| 102 | + greeting[field] = value | ||
| 103 | + with self.subTest(category=name, field=field): | ||
| 104 | + self._check(name, value, | ||
| 105 | + lambda g=greeting: protocol.parse_greeting(g), | ||
| 106 | + ALLOWED_GREETING) | ||
| 107 | + | ||
| 108 | + def test_parse_api_response_never_raises_an_undeclared_exception(self) -> None: | ||
| 109 | + for name, value in self._values(): | ||
| 110 | + for field in ("outcome", "id", "status", "body", "code"): | ||
| 111 | + answer = dict(fuzz_test.SEED_API[0]) | ||
| 112 | + answer[field] = value | ||
| 113 | + with self.subTest(category=name, field=field): | ||
| 114 | + self._check(name, value, | ||
| 115 | + lambda a=answer: protocol.parse_api_response(a), | ||
| 116 | + ALLOWED_API) | ||
| 117 | + | ||
| 118 | + def test_dispatch_never_raises_an_undeclared_exception(self) -> None: | ||
| 119 | + capabilities.configure(None, False) | ||
| 120 | + for name, value in self._values(): | ||
| 121 | + body = {"job_id": value, "file_id": value, "format": value} | ||
| 122 | + for capability in capabilities.names(): | ||
| 123 | + with self.subTest(category=name, capability=capability): | ||
| 124 | + self._check(name, value, | ||
| 125 | + lambda c=capability, b=body: | ||
| 126 | + capabilities.dispatch(c, b), | ||
| 127 | + (protocol.CapabilityError,)) | ||
| 128 | + | ||
| 129 | + | ||
| 130 | +class MutatedAndGeneratedFramesStayInsideTheContract(unittest.TestCase): | ||
| 131 | + SEEDS = (1, 7, 99) | ||
| 132 | + CASES = 400 | ||
| 133 | + | ||
| 134 | + def test_template_mutation_of_request_frames_is_survivable(self) -> None: | ||
| 135 | + pool = [] | ||
| 136 | + for name, values in fuzz_test.CATEGORY_STRINGS.items(): | ||
| 137 | + pool.extend(values) | ||
| 138 | + pool.extend(fuzz_test.CATEGORY_SCALARS.get(name, [])) | ||
| 139 | + for seed in self.SEEDS: | ||
| 140 | + rng = random.Random(seed) | ||
| 141 | + for _ in range(self.CASES): | ||
| 142 | + candidate = fuzz_test.mutate_frame( | ||
| 143 | + rng, rng.choice(fuzz_test.SEED_FRAMES), pool | ||
| 144 | + ) | ||
| 145 | + try: | ||
| 146 | + protocol.parse_request(candidate) | ||
| 147 | + except ALLOWED_REQUEST: | ||
| 148 | + pass | ||
| 149 | + except RecursionError: | ||
| 150 | + pass | ||
| 151 | + except BaseException as exc: | ||
| 152 | + self.fail("tohum %d: beyan edilmemis %s -> %s" | ||
| 153 | + % (seed, type(exc).__name__, exc)) | ||
| 154 | + | ||
| 155 | + def test_byte_level_mutation_of_frames_is_survivable(self) -> None: | ||
| 156 | + base = [protocol.encode_frame(f) for f in fuzz_test.SEED_FRAMES] | ||
| 157 | + for seed in self.SEEDS: | ||
| 158 | + rng = random.Random(seed) | ||
| 159 | + for _ in range(self.CASES): | ||
| 160 | + blob = fuzz_test.mutate_bytes(rng, rng.choice(base)) | ||
| 161 | + try: | ||
| 162 | + read_frame_bytes(blob) | ||
| 163 | + except ALLOWED_REQUEST + (struct.error,): | ||
| 164 | + pass | ||
| 165 | + except BaseException as exc: | ||
| 166 | + self.fail("tohum %d: beyan edilmemis %s -> %s" | ||
| 167 | + % (seed, type(exc).__name__, exc)) | ||
| 168 | + | ||
| 169 | + def test_grammar_generated_frames_are_survivable(self) -> None: | ||
| 170 | + for seed in self.SEEDS: | ||
| 171 | + rng = random.Random(seed) | ||
| 172 | + for _ in range(self.CASES): | ||
| 173 | + encoded = fuzz_test.derive(rng).encode("utf-8") | ||
| 174 | + blob = struct.pack(">I", len(encoded)) + encoded | ||
| 175 | + try: | ||
| 176 | + read_frame_bytes(blob) | ||
| 177 | + except ALLOWED_REQUEST + (struct.error,): | ||
| 178 | + pass | ||
| 179 | + except BaseException as exc: | ||
| 180 | + self.fail("tohum %d: beyan edilmemis %s -> %s" | ||
| 181 | + % (seed, type(exc).__name__, exc)) | ||
| 182 | + | ||
| 183 | + | ||
| 184 | +class TheFuzzerItselfNeverCrashes(unittest.TestCase): | ||
| 185 | + def test_a_short_run_completes_and_reports(self) -> None: | ||
| 186 | + capabilities.configure(None, False) | ||
| 187 | + report = fuzz_test.fuzz(cases=120, seed=4242, verbose=False) | ||
| 188 | + self.assertGreater(report.runs, 120) | ||
| 189 | + self.assertGreater(report.coverage, 0) | ||
| 190 | + self.assertEqual( | ||
| 191 | + report.findings, | ||
| 192 | + [], | ||
| 193 | + "fuzzer yeni bir beyan edilmemis istisna buldu; " | ||
| 194 | + "tools/fuzz_test.py ciktisina bak", | ||
| 195 | + ) | ||
| 196 | + | ||
| 197 | + def test_all_six_slide_categories_are_exercised(self) -> None: | ||
| 198 | + capabilities.configure(None, False) | ||
| 199 | + report = fuzz_test.fuzz(cases=40, seed=5, verbose=False) | ||
| 200 | + for name in ("uzunluk", "sayi_sinirlari", "ozel_degerler", | ||
| 201 | + "bicimlendirici", "noktalama", "anahtar_kelimeler"): | ||
| 202 | + self.assertIn(name, report.by_category) | ||
| 203 | + self.assertGreater(report.by_category[name], 0) | ||
| 204 | + | ||
| 205 | + | ||
| 206 | +if __name__ == "__main__": | ||
| 207 | + unittest.main() | ||
tests/integration/__init__.pyadded+0 -0
tests/integration/test_lifecycle.pyadded+257 -0
| @@ -0,0 +1,257 @@ | |||
| 1 | +import json | ||
| 2 | +import tempfile | ||
| 3 | +import threading | ||
| 4 | +import time | ||
| 5 | +import unittest | ||
| 6 | +from pathlib import Path | ||
| 7 | + | ||
| 8 | +from src import capabilities, config, jobs, pipeline | ||
| 9 | +from src.protocol import CapabilityError | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +class FakeResult: | ||
| 13 | + def __init__(self, mp3: list, scripts: list, duration: float) -> None: | ||
| 14 | + self.mp3_yollari = mp3 | ||
| 15 | + self.script_yollari = scripts | ||
| 16 | + self.ses_toplam_sn = duration | ||
| 17 | + self.adimlar: list = [] | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +class FakePipelineError(RuntimeError): | ||
| 21 | + pass | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +class FakeInterrupt(RuntimeError): | ||
| 25 | + pass | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +def fake_pipeline_class(mp3: list, scripts: list, duration: float, gate=None): | ||
| 29 | + class FakePipeline: | ||
| 30 | + def __init__(self, pdf, format, gunluk, cikti_koku, bolum_limiti, | ||
| 31 | + motor_adi, ses_uret, kayit=None): | ||
| 32 | + self.pdf = pdf | ||
| 33 | + self.format = format | ||
| 34 | + self.gunluk = gunluk | ||
| 35 | + self.cikti_koku = cikti_koku | ||
| 36 | + self.bolum_limiti = bolum_limiti | ||
| 37 | + self.motor_adi = motor_adi | ||
| 38 | + self.ses_uret = ses_uret | ||
| 39 | + self.kayit = kayit | ||
| 40 | + self.sonuc = FakeResult(list(mp3), list(scripts), duration) | ||
| 41 | + | ||
| 42 | + def kos(self): | ||
| 43 | + for name in pipeline.REAL_STAGES: | ||
| 44 | + if gate is not None: | ||
| 45 | + gate.wait(5.0) | ||
| 46 | + self.sonuc.adimlar.append(name) | ||
| 47 | + self.gunluk(f"[KOSTU ] {name}") | ||
| 48 | + return self.sonuc | ||
| 49 | + | ||
| 50 | + return FakePipeline | ||
| 51 | + | ||
| 52 | + | ||
| 53 | +def wait_for(store: jobs.JobStore, job_id: str, wanted: tuple, deadline_secs: float) -> dict: | ||
| 54 | + limit = time.monotonic() + deadline_secs | ||
| 55 | + while time.monotonic() < limit: | ||
| 56 | + record = store.get(job_id) | ||
| 57 | + if record["state"] in wanted: | ||
| 58 | + return record | ||
| 59 | + time.sleep(0.005) | ||
| 60 | + return store.get(job_id) | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +class LifecycleTestCase(unittest.TestCase): | ||
| 64 | + def setUp(self) -> None: | ||
| 65 | + self._log_level = config._active_level | ||
| 66 | + config.set_log_level("error") | ||
| 67 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-dongu-") | ||
| 68 | + self.root = Path(self._tmp.name) | ||
| 69 | + self.media_root = self.root / "medya" | ||
| 70 | + self.media_root.mkdir(parents=True, exist_ok=True) | ||
| 71 | + (self.media_root / "ders.pdf").write_bytes(b"%PDF-1.4\n") | ||
| 72 | + self.output_root = self.root / "cikti" | ||
| 73 | + self._stores: list = [] | ||
| 74 | + | ||
| 75 | + def tearDown(self) -> None: | ||
| 76 | + capabilities.configure(None, llm_ready=False) | ||
| 77 | + for store in self._stores: | ||
| 78 | + store.shutdown(timeout=1.0) | ||
| 79 | + self._tmp.cleanup() | ||
| 80 | + config._active_level = self._log_level | ||
| 81 | + | ||
| 82 | + def pipeline_store(self, name: str, mp3: list, scripts: list, duration: float = 123.5, | ||
| 83 | + gate=None, chapter_limit: int = 1) -> jobs.JobStore: | ||
| 84 | + runner = pipeline.make_runner( | ||
| 85 | + str(self.media_root), | ||
| 86 | + str(self.output_root), | ||
| 87 | + chapter_limit, | ||
| 88 | + "supertonic-3", | ||
| 89 | + fake_pipeline_class(mp3, scripts, duration, gate), | ||
| 90 | + FakePipelineError, | ||
| 91 | + FakeInterrupt, | ||
| 92 | + ) | ||
| 93 | + store = jobs.JobStore( | ||
| 94 | + root=self.root / name, | ||
| 95 | + workers=1, | ||
| 96 | + max_jobs=8, | ||
| 97 | + stage_secs=0.0, | ||
| 98 | + runner=runner, | ||
| 99 | + stages=pipeline.REAL_STAGES, | ||
| 100 | + ) | ||
| 101 | + self._stores.append(store) | ||
| 102 | + store.start() | ||
| 103 | + capabilities.configure(store, llm_ready=False) | ||
| 104 | + return store | ||
| 105 | + | ||
| 106 | + def output_path(self, *parts: str) -> str: | ||
| 107 | + return str(self.output_root.joinpath(*parts)) | ||
| 108 | + | ||
| 109 | + | ||
| 110 | +class SubmitStatusResultTests(LifecycleTestCase): | ||
| 111 | + def test_submit_status_result_walks_a_job_from_queue_to_audio(self) -> None: | ||
| 112 | + store = self.pipeline_store( | ||
| 113 | + "mutlu", | ||
| 114 | + [self.output_path("ders", "ses", "duz_okuma", "ders-b01.mp3")], | ||
| 115 | + [self.output_path("ders", "script", "duz_okuma", "ders-b01.script.json")], | ||
| 116 | + ) | ||
| 117 | + submitted = capabilities.dispatch( | ||
| 118 | + "podcast.submit", {"source_id": "ders.pdf", "format": "duz_okuma"} | ||
| 119 | + ) | ||
| 120 | + job_id = submitted["job_id"] | ||
| 121 | + self.assertEqual(submitted["state"], "queued") | ||
| 122 | + | ||
| 123 | + final = wait_for(store, job_id, (jobs.STATE_DONE, jobs.STATE_FAILED), 10.0) | ||
| 124 | + self.assertEqual(final["state"], jobs.STATE_DONE, final["error_code"]) | ||
| 125 | + | ||
| 126 | + state = capabilities.dispatch("podcast.status", {"job_id": job_id}) | ||
| 127 | + self.assertEqual(state["state"], "done") | ||
| 128 | + self.assertEqual(state["progress"], 1.0) | ||
| 129 | + self.assertIsNone(state["error_code"]) | ||
| 130 | + | ||
| 131 | + result = capabilities.dispatch("podcast.result", {"job_id": job_id}) | ||
| 132 | + self.assertEqual(result["audio_id"], "ders/ses/duz_okuma/ders-b01.mp3") | ||
| 133 | + self.assertEqual(result["script_id"], "ders/script/duz_okuma/ders-b01.script.json") | ||
| 134 | + self.assertEqual(result["duration_secs"], 123.5) | ||
| 135 | + self.assertEqual(result["format"], "duz_okuma") | ||
| 136 | + self.assertEqual(result["audio_ids"], [result["audio_id"]]) | ||
| 137 | + | ||
| 138 | + def test_the_finished_state_is_readable_from_a_freshly_opened_store(self) -> None: | ||
| 139 | + store = self.pipeline_store( | ||
| 140 | + "kalici", | ||
| 141 | + [self.output_path("ders", "ses", "duz_okuma", "ders-b01.mp3")], | ||
| 142 | + [self.output_path("ders", "script", "duz_okuma", "ders-b01.script.json")], | ||
| 143 | + ) | ||
| 144 | + job_id = capabilities.dispatch("podcast.submit", {"source_id": "ders.pdf"})["job_id"] | ||
| 145 | + wait_for(store, job_id, (jobs.STATE_DONE, jobs.STATE_FAILED), 10.0) | ||
| 146 | + store.shutdown(timeout=1.0) | ||
| 147 | + | ||
| 148 | + reopened = jobs.JobStore(root=self.root / "kalici", workers=1, max_jobs=8, stage_secs=0.0) | ||
| 149 | + self._stores.append(reopened) | ||
| 150 | + self.assertEqual(reopened.swept, 0, "biten is yeniden acilista supurulmemeli") | ||
| 151 | + capabilities.configure(reopened, llm_ready=False) | ||
| 152 | + result = capabilities.dispatch("podcast.result", {"job_id": job_id}) | ||
| 153 | + self.assertEqual(result["audio_id"], "ders/ses/duz_okuma/ders-b01.mp3") | ||
| 154 | + | ||
| 155 | + def test_progress_is_reported_while_the_job_is_still_running(self) -> None: | ||
| 156 | + gate = threading.Event() | ||
| 157 | + store = self.pipeline_store( | ||
| 158 | + "ilerleme", | ||
| 159 | + [self.output_path("ders", "ses", "duz_okuma", "ders-b01.mp3")], | ||
| 160 | + [self.output_path("ders", "script", "duz_okuma", "ders-b01.script.json")], | ||
| 161 | + gate=gate, | ||
| 162 | + ) | ||
| 163 | + job_id = capabilities.dispatch("podcast.submit", {"source_id": "ders.pdf"})["job_id"] | ||
| 164 | + running = wait_for(store, job_id, (jobs.STATE_RUNNING,), 5.0) | ||
| 165 | + self.assertEqual(running["state"], jobs.STATE_RUNNING) | ||
| 166 | + state = capabilities.dispatch("podcast.status", {"job_id": job_id}) | ||
| 167 | + self.assertIn(state["stage"], pipeline.REAL_STAGES) | ||
| 168 | + self.assertGreaterEqual(state["progress"], 0.0) | ||
| 169 | + self.assertLessEqual(state["progress"], 1.0) | ||
| 170 | + gate.set() | ||
| 171 | + wait_for(store, job_id, (jobs.STATE_DONE, jobs.STATE_FAILED), 10.0) | ||
| 172 | + | ||
| 173 | + | ||
| 174 | +class FailurePathTests(LifecycleTestCase): | ||
| 175 | + def test_a_missing_source_fails_with_source_not_found_and_no_audio_id(self) -> None: | ||
| 176 | + store = self.pipeline_store("kayip", ["/o/x.mp3"], ["/o/x.json"]) | ||
| 177 | + job_id = capabilities.dispatch("podcast.submit", {"source_id": "yok.pdf"})["job_id"] | ||
| 178 | + final = wait_for(store, job_id, (jobs.STATE_DONE, jobs.STATE_FAILED), 10.0) | ||
| 179 | + self.assertEqual(final["state"], jobs.STATE_FAILED) | ||
| 180 | + self.assertEqual(final["error_code"], pipeline.SOURCE_NOT_FOUND) | ||
| 181 | + self.assertIsNone(final["audio_id"]) | ||
| 182 | + with self.assertRaises(CapabilityError) as raised: | ||
| 183 | + capabilities.dispatch("podcast.result", {"job_id": job_id}) | ||
| 184 | + self.assertEqual(raised.exception.code, "not_ready") | ||
| 185 | + | ||
| 186 | + def test_a_run_that_produced_no_mp3_fails_instead_of_returning_an_empty_result(self) -> None: | ||
| 187 | + store = self.pipeline_store( | ||
| 188 | + "sessiz", [], [self.output_path("ders", "script", "duz_okuma", "ders-b01.script.json")] | ||
| 189 | + ) | ||
| 190 | + job_id = capabilities.dispatch("podcast.submit", {"source_id": "ders.pdf"})["job_id"] | ||
| 191 | + final = wait_for(store, job_id, (jobs.STATE_DONE, jobs.STATE_FAILED), 10.0) | ||
| 192 | + self.assertEqual(final["state"], jobs.STATE_FAILED) | ||
| 193 | + self.assertEqual(final["error_code"], pipeline.NO_AUDIO) | ||
| 194 | + self.assertIsNone(final["audio_id"], "ses uretmeyen is audio_id yazmamali") | ||
| 195 | + | ||
| 196 | + | ||
| 197 | +class CancellationTests(LifecycleTestCase): | ||
| 198 | + def test_a_running_job_stops_at_the_next_step_boundary_after_cancel(self) -> None: | ||
| 199 | + gate = threading.Event() | ||
| 200 | + store = self.pipeline_store( | ||
| 201 | + "iptal", | ||
| 202 | + [self.output_path("ders", "ses", "duz_okuma", "ders-b01.mp3")], | ||
| 203 | + [self.output_path("ders", "script", "duz_okuma", "ders-b01.script.json")], | ||
| 204 | + gate=gate, | ||
| 205 | + ) | ||
| 206 | + job_id = capabilities.dispatch("podcast.submit", {"source_id": "ders.pdf"})["job_id"] | ||
| 207 | + wait_for(store, job_id, (jobs.STATE_RUNNING,), 5.0) | ||
| 208 | + self.assertTrue(capabilities.dispatch("podcast.cancel", {"job_id": job_id})["cancelled"]) | ||
| 209 | + gate.set() | ||
| 210 | + final = wait_for( | ||
| 211 | + store, job_id, (jobs.STATE_CANCELLED, jobs.STATE_DONE, jobs.STATE_FAILED), 10.0 | ||
| 212 | + ) | ||
| 213 | + self.assertEqual(final["state"], jobs.STATE_CANCELLED) | ||
| 214 | + self.assertIsNone(final["audio_id"], "iptal edilen is audio_id yazmamali") | ||
| 215 | + | ||
| 216 | + def test_a_cancelled_job_is_cancelled_on_disk_too(self) -> None: | ||
| 217 | + store = self.pipeline_store("iptal-disk", ["/o/x.mp3"], ["/o/x.json"]) | ||
| 218 | + job_id = capabilities.dispatch("podcast.submit", {"source_id": "ders.pdf"})["job_id"] | ||
| 219 | + wait_for(store, job_id, (jobs.STATE_DONE, jobs.STATE_FAILED, jobs.STATE_CANCELLED), 10.0) | ||
| 220 | + store.shutdown(timeout=1.0) | ||
| 221 | + with open(self.root / "iptal-disk" / f"{job_id}.json", "r", encoding="utf-8") as handle: | ||
| 222 | + on_disk = json.load(handle) | ||
| 223 | + self.assertEqual(on_disk["job_id"], job_id) | ||
| 224 | + self.assertIn(on_disk["state"], jobs.STATES) | ||
| 225 | + | ||
| 226 | + | ||
| 227 | +class QuotaTests(LifecycleTestCase): | ||
| 228 | + def test_the_queue_quota_answers_busy_and_recovers_after_jobs_finish(self) -> None: | ||
| 229 | + runner = pipeline.make_runner( | ||
| 230 | + str(self.media_root), | ||
| 231 | + str(self.output_root), | ||
| 232 | + 1, | ||
| 233 | + "supertonic-3", | ||
| 234 | + fake_pipeline_class([self.output_path("d", "ses", "duz_okuma", "d-b01.mp3")], [], 1.0), | ||
| 235 | + FakePipelineError, | ||
| 236 | + FakeInterrupt, | ||
| 237 | + ) | ||
| 238 | + store = jobs.JobStore( | ||
| 239 | + root=self.root / "kota", | ||
| 240 | + workers=1, | ||
| 241 | + max_jobs=1, | ||
| 242 | + stage_secs=0.0, | ||
| 243 | + runner=runner, | ||
| 244 | + stages=pipeline.REAL_STAGES, | ||
| 245 | + ) | ||
| 246 | + self._stores.append(store) | ||
| 247 | + capabilities.configure(store, llm_ready=False) | ||
| 248 | + first = capabilities.dispatch("podcast.submit", {"source_id": "ders.pdf"})["job_id"] | ||
| 249 | + with self.assertRaises(CapabilityError) as raised: | ||
| 250 | + capabilities.dispatch("podcast.submit", {"source_id": "ders.pdf"}) | ||
| 251 | + self.assertEqual(raised.exception.code, "busy") | ||
| 252 | + capabilities.dispatch("podcast.cancel", {"job_id": first}) | ||
| 253 | + capabilities.dispatch("podcast.submit", {"source_id": "ders.pdf"}) | ||
| 254 | + | ||
| 255 | + | ||
| 256 | +if __name__ == "__main__": | ||
| 257 | + unittest.main() | ||
tests/model/__init__.pyadded+0 -0
tests/model/test_model_jobstore.pyadded+330 -0
| @@ -0,0 +1,330 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import sys | ||
| 4 | +import tempfile | ||
| 5 | +import unittest | ||
| 6 | +from collections import deque | ||
| 7 | +from pathlib import Path | ||
| 8 | + | ||
| 9 | +sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) | ||
| 10 | + | ||
| 11 | +from src import config, jobs | ||
| 12 | + | ||
| 13 | +INITIAL = "Q" | ||
| 14 | + | ||
| 15 | +INPUTS = ( | ||
| 16 | + "begin", | ||
| 17 | + "finish", | ||
| 18 | + "fail", | ||
| 19 | + "cancel", | ||
| 20 | + "progress", | ||
| 21 | + "status", | ||
| 22 | + "cancel_requested", | ||
| 23 | +) | ||
| 24 | + | ||
| 25 | +MODEL = { | ||
| 26 | + "Q": { | ||
| 27 | + "begin": ("True", "R"), | ||
| 28 | + "finish": ("InvalidTransition", "Q"), | ||
| 29 | + "fail": ("failed", "F"), | ||
| 30 | + "cancel": ("True", "C"), | ||
| 31 | + "progress": ("None", "Q"), | ||
| 32 | + "status": ("queued", "Q"), | ||
| 33 | + "cancel_requested": ("False", "Q"), | ||
| 34 | + }, | ||
| 35 | + "R": { | ||
| 36 | + "begin": ("False", "R"), | ||
| 37 | + "finish": ("done", "D"), | ||
| 38 | + "fail": ("failed", "F"), | ||
| 39 | + "cancel": ("True", "RC"), | ||
| 40 | + "progress": ("running", "R"), | ||
| 41 | + "status": ("running", "R"), | ||
| 42 | + "cancel_requested": ("False", "R"), | ||
| 43 | + }, | ||
| 44 | + "RC": { | ||
| 45 | + "begin": ("False", "RC"), | ||
| 46 | + "finish": ("cancelled", "C"), | ||
| 47 | + "fail": ("failed", "FC"), | ||
| 48 | + "cancel": ("True", "RC"), | ||
| 49 | + "progress": ("running", "RC"), | ||
| 50 | + "status": ("running", "RC"), | ||
| 51 | + "cancel_requested": ("True", "RC"), | ||
| 52 | + }, | ||
| 53 | + "D": { | ||
| 54 | + "begin": ("False", "D"), | ||
| 55 | + "finish": ("InvalidTransition", "D"), | ||
| 56 | + "fail": ("InvalidTransition", "D"), | ||
| 57 | + "cancel": ("False", "D"), | ||
| 58 | + "progress": ("None", "D"), | ||
| 59 | + "status": ("done", "D"), | ||
| 60 | + "cancel_requested": ("False", "D"), | ||
| 61 | + }, | ||
| 62 | + "F": { | ||
| 63 | + "begin": ("False", "F"), | ||
| 64 | + "finish": ("InvalidTransition", "F"), | ||
| 65 | + "fail": ("InvalidTransition", "F"), | ||
| 66 | + "cancel": ("False", "F"), | ||
| 67 | + "progress": ("None", "F"), | ||
| 68 | + "status": ("failed", "F"), | ||
| 69 | + "cancel_requested": ("False", "F"), | ||
| 70 | + }, | ||
| 71 | + "FC": { | ||
| 72 | + "begin": ("False", "FC"), | ||
| 73 | + "finish": ("InvalidTransition", "FC"), | ||
| 74 | + "fail": ("InvalidTransition", "FC"), | ||
| 75 | + "cancel": ("False", "FC"), | ||
| 76 | + "progress": ("None", "FC"), | ||
| 77 | + "status": ("failed", "FC"), | ||
| 78 | + "cancel_requested": ("True", "FC"), | ||
| 79 | + }, | ||
| 80 | + "C": { | ||
| 81 | + "begin": ("False", "C"), | ||
| 82 | + "finish": ("InvalidTransition", "C"), | ||
| 83 | + "fail": ("InvalidTransition", "C"), | ||
| 84 | + "cancel": ("False", "C"), | ||
| 85 | + "progress": ("None", "C"), | ||
| 86 | + "status": ("cancelled", "C"), | ||
| 87 | + "cancel_requested": ("True", "C"), | ||
| 88 | + }, | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | + | ||
| 92 | +def trace(state: str, sequence: tuple[str, ...]) -> tuple[str, tuple[str, ...]]: | ||
| 93 | + outputs = [] | ||
| 94 | + for symbol in sequence: | ||
| 95 | + output, state = MODEL[state][symbol] | ||
| 96 | + outputs.append(output) | ||
| 97 | + return state, tuple(outputs) | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +def state_cover() -> dict[str, tuple[str, ...]]: | ||
| 101 | + cover = {INITIAL: ()} | ||
| 102 | + frontier = deque([INITIAL]) | ||
| 103 | + while frontier: | ||
| 104 | + state = frontier.popleft() | ||
| 105 | + for symbol in INPUTS: | ||
| 106 | + _, target = MODEL[state][symbol] | ||
| 107 | + if target not in cover: | ||
| 108 | + cover[target] = cover[state] + (symbol,) | ||
| 109 | + frontier.append(target) | ||
| 110 | + return cover | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +def characterizing_set() -> list[tuple[str, ...]]: | ||
| 114 | + blocks = {state: "0" for state in MODEL} | ||
| 115 | + witnesses: list[tuple[str, ...]] = [] | ||
| 116 | + while True: | ||
| 117 | + split_found = False | ||
| 118 | + for symbol in INPUTS: | ||
| 119 | + refined = { | ||
| 120 | + state: blocks[state] + "|" + MODEL[state][symbol][0] + "->" | ||
| 121 | + + blocks[MODEL[state][symbol][1]] | ||
| 122 | + for state in MODEL | ||
| 123 | + } | ||
| 124 | + if len(set(refined.values())) > len(set(blocks.values())): | ||
| 125 | + blocks = { | ||
| 126 | + state: str(sorted(set(refined.values())).index(refined[state])) | ||
| 127 | + for state in MODEL | ||
| 128 | + } | ||
| 129 | + witnesses.append((symbol,)) | ||
| 130 | + split_found = True | ||
| 131 | + if not split_found: | ||
| 132 | + break | ||
| 133 | + return _minimize(witnesses) | ||
| 134 | + | ||
| 135 | + | ||
| 136 | +def _pairs() -> list[tuple[str, str]]: | ||
| 137 | + ordered = sorted(MODEL) | ||
| 138 | + return [ | ||
| 139 | + (a, b) | ||
| 140 | + for index, a in enumerate(ordered) | ||
| 141 | + for b in ordered[index + 1:] | ||
| 142 | + ] | ||
| 143 | + | ||
| 144 | + | ||
| 145 | +def _separates_all(candidates: list[tuple[str, ...]]) -> bool: | ||
| 146 | + return all( | ||
| 147 | + any(trace(a, seq)[1] != trace(b, seq)[1] for seq in candidates) | ||
| 148 | + for a, b in _pairs() | ||
| 149 | + ) | ||
| 150 | + | ||
| 151 | + | ||
| 152 | +def _minimize(witnesses: list[tuple[str, ...]]) -> list[tuple[str, ...]]: | ||
| 153 | + kept: list[tuple[str, ...]] = [] | ||
| 154 | + for candidate in witnesses: | ||
| 155 | + unresolved = [ | ||
| 156 | + pair for pair in _pairs() | ||
| 157 | + if all(trace(pair[0], seq)[1] == trace(pair[1], seq)[1] for seq in kept) | ||
| 158 | + ] | ||
| 159 | + if any( | ||
| 160 | + trace(a, candidate)[1] != trace(b, candidate)[1] for a, b in unresolved | ||
| 161 | + ): | ||
| 162 | + kept.append(candidate) | ||
| 163 | + for candidate in list(kept): | ||
| 164 | + trimmed = [seq for seq in kept if seq != candidate] | ||
| 165 | + if trimmed and _separates_all(trimmed): | ||
| 166 | + kept = trimmed | ||
| 167 | + return kept | ||
| 168 | + | ||
| 169 | + | ||
| 170 | +class Adapter: | ||
| 171 | + def __init__(self, store: jobs.JobStore) -> None: | ||
| 172 | + self.store = store | ||
| 173 | + self.job_id = "" | ||
| 174 | + | ||
| 175 | + def reset(self) -> None: | ||
| 176 | + record, _ = self.store.submit("01SOURCE", "duz_okuma") | ||
| 177 | + self.job_id = record["job_id"] | ||
| 178 | + | ||
| 179 | + def send(self, symbol: str) -> str: | ||
| 180 | + try: | ||
| 181 | + if symbol == "begin": | ||
| 182 | + return str(self.store.begin(self.job_id)) | ||
| 183 | + if symbol == "finish": | ||
| 184 | + return self.store.finish(self.job_id, "a.mp3", 1.0, "s.txt")["state"] | ||
| 185 | + if symbol == "fail": | ||
| 186 | + return self.store.fail(self.job_id, "test")["state"] | ||
| 187 | + if symbol == "cancel": | ||
| 188 | + return str(self.store.cancel(self.job_id)) | ||
| 189 | + if symbol == "progress": | ||
| 190 | + answer = self.store.update_progress(self.job_id, "ingest", 0.5) | ||
| 191 | + return "None" if answer is None else answer["state"] | ||
| 192 | + if symbol == "status": | ||
| 193 | + return self.store.get(self.job_id)["state"] | ||
| 194 | + if symbol == "cancel_requested": | ||
| 195 | + return str(self.store.cancel_requested(self.job_id)) | ||
| 196 | + except jobs.InvalidTransition: | ||
| 197 | + return "InvalidTransition" | ||
| 198 | + raise AssertionError("bilinmeyen girdi: %s" % symbol) | ||
| 199 | + | ||
| 200 | + | ||
| 201 | +class ModelStructureTests(unittest.TestCase): | ||
| 202 | + def test_the_model_is_complete_over_the_input_alphabet(self) -> None: | ||
| 203 | + for state, rows in MODEL.items(): | ||
| 204 | + self.assertEqual( | ||
| 205 | + tuple(sorted(rows)), tuple(sorted(INPUTS)), | ||
| 206 | + "durum %s girdi alfabesini tam kapsamiyor" % state, | ||
| 207 | + ) | ||
| 208 | + for symbol, (_, target) in rows.items(): | ||
| 209 | + self.assertIn(target, MODEL, | ||
| 210 | + "%s/%s tanimsiz duruma gidiyor" % (state, symbol)) | ||
| 211 | + | ||
| 212 | + def test_every_state_is_reachable_from_the_initial_state(self) -> None: | ||
| 213 | + cover = state_cover() | ||
| 214 | + self.assertEqual(sorted(cover), sorted(MODEL), | ||
| 215 | + "erisilemeyen durum var; model minimal degil") | ||
| 216 | + | ||
| 217 | + def test_the_model_is_minimal_under_the_computed_w_set(self) -> None: | ||
| 218 | + w_set = characterizing_set() | ||
| 219 | + self.assertTrue(w_set, "W kumesi bos cikti") | ||
| 220 | + signatures = { | ||
| 221 | + state: tuple(trace(state, seq)[1] for seq in w_set) for state in MODEL | ||
| 222 | + } | ||
| 223 | + self.assertEqual( | ||
| 224 | + len(set(signatures.values())), len(MODEL), | ||
| 225 | + "W kumesi tum durum ciftlerini ayirmiyor: %r" % (signatures,), | ||
| 226 | + ) | ||
| 227 | + | ||
| 228 | + def test_the_w_set_respects_the_size_bound_from_the_lecture(self) -> None: | ||
| 229 | + w_set = characterizing_set() | ||
| 230 | + self.assertLessEqual( | ||
| 231 | + len(w_set), len(MODEL) - 1, | ||
| 232 | + "n durumlu minimal FSM icin W en fazla n-1 dizi icermeli", | ||
| 233 | + ) | ||
| 234 | + for seq in w_set: | ||
| 235 | + self.assertLessEqual( | ||
| 236 | + len(seq), len(MODEL) - 1, | ||
| 237 | + "W icindeki her dizi en fazla n-1 uzunlukta olmali", | ||
| 238 | + ) | ||
| 239 | + | ||
| 240 | + def test_the_w_set_is_irredundant(self) -> None: | ||
| 241 | + w_set = characterizing_set() | ||
| 242 | + for candidate in w_set: | ||
| 243 | + trimmed = [seq for seq in w_set if seq != candidate] | ||
| 244 | + self.assertFalse( | ||
| 245 | + _separates_all(trimmed), | ||
| 246 | + "W kumesinde gereksiz dizi var: %r" % (candidate,), | ||
| 247 | + ) | ||
| 248 | + | ||
| 249 | + def test_the_state_cover_reaches_each_state_exactly_once(self) -> None: | ||
| 250 | + cover = state_cover() | ||
| 251 | + self.assertIn((), cover.values(), "durum ortusu bos diziyi icermeli") | ||
| 252 | + for state, sequence in cover.items(): | ||
| 253 | + self.assertEqual( | ||
| 254 | + trace(INITIAL, sequence)[0], state, | ||
| 255 | + "V dizisi %r hedeflenen %s durumuna gitmiyor" % (sequence, state), | ||
| 256 | + ) | ||
| 257 | + | ||
| 258 | + | ||
| 259 | +class WMethodConformanceTests(unittest.TestCase): | ||
| 260 | + def setUp(self) -> None: | ||
| 261 | + self._log_level = config._active_level | ||
| 262 | + config.set_log_level("error") | ||
| 263 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-model-") | ||
| 264 | + self.store = jobs.JobStore( | ||
| 265 | + root=Path(self._tmp.name) / "isler", | ||
| 266 | + workers=1, | ||
| 267 | + max_jobs=100000, | ||
| 268 | + stage_secs=0.0, | ||
| 269 | + ) | ||
| 270 | + self.adapter = Adapter(self.store) | ||
| 271 | + | ||
| 272 | + def tearDown(self) -> None: | ||
| 273 | + self.store.shutdown(timeout=1.0) | ||
| 274 | + self._tmp.cleanup() | ||
| 275 | + config._active_level = self._log_level | ||
| 276 | + | ||
| 277 | + def _suite(self) -> list[tuple[str, ...]]: | ||
| 278 | + cover = state_cover() | ||
| 279 | + w_set = characterizing_set() | ||
| 280 | + prefixes = sorted(set(cover.values())) | ||
| 281 | + middles = [()] + [(symbol,) for symbol in INPUTS] | ||
| 282 | + return sorted({ | ||
| 283 | + prefix + middle + suffix | ||
| 284 | + for prefix in prefixes | ||
| 285 | + for middle in middles | ||
| 286 | + for suffix in w_set | ||
| 287 | + }) | ||
| 288 | + | ||
| 289 | + def _run(self, sequence: tuple[str, ...]) -> tuple[str, ...]: | ||
| 290 | + self.adapter.reset() | ||
| 291 | + return tuple(self.adapter.send(symbol) for symbol in sequence) | ||
| 292 | + | ||
| 293 | + def test_the_implementation_conforms_to_the_model(self) -> None: | ||
| 294 | + suite = self._suite() | ||
| 295 | + self.assertGreaterEqual(len(suite), 100, | ||
| 296 | + "V.W union V.X.W beklenenden kucuk") | ||
| 297 | + for sequence in suite: | ||
| 298 | + expected = trace(INITIAL, sequence)[1] | ||
| 299 | + with self.subTest(sequence="/".join(sequence)): | ||
| 300 | + self.assertEqual( | ||
| 301 | + self._run(sequence), expected, | ||
| 302 | + "model ile gercek JobStore ayrisiyor: %s" % ("/".join(sequence),), | ||
| 303 | + ) | ||
| 304 | + | ||
| 305 | + def test_the_suite_visits_every_modelled_state(self) -> None: | ||
| 306 | + visited = set() | ||
| 307 | + for sequence in self._suite(): | ||
| 308 | + state = INITIAL | ||
| 309 | + visited.add(state) | ||
| 310 | + for symbol in sequence: | ||
| 311 | + state = MODEL[state][symbol][1] | ||
| 312 | + visited.add(state) | ||
| 313 | + self.assertEqual(sorted(visited), sorted(MODEL)) | ||
| 314 | + | ||
| 315 | + def test_the_suite_exercises_every_modelled_transition(self) -> None: | ||
| 316 | + covered = set() | ||
| 317 | + for sequence in self._suite(): | ||
| 318 | + state = INITIAL | ||
| 319 | + for symbol in sequence: | ||
| 320 | + covered.add((state, symbol)) | ||
| 321 | + state = MODEL[state][symbol][1] | ||
| 322 | + expected = {(state, symbol) for state in MODEL for symbol in INPUTS} | ||
| 323 | + self.assertEqual( | ||
| 324 | + covered, expected, | ||
| 325 | + "kapsanmayan gecis: %r" % (sorted(expected - covered),), | ||
| 326 | + ) | ||
| 327 | + | ||
| 328 | + | ||
| 329 | +if __name__ == "__main__": | ||
| 330 | + unittest.main() | ||
tests/regress/__init__.pyadded+10 -0
| @@ -0,0 +1,10 @@ | |||
| 1 | +import os | ||
| 2 | + | ||
| 3 | + | ||
| 4 | +def load_tests(loader, standard_tests, pattern): | ||
| 5 | + here = os.path.dirname(os.path.abspath(__file__)) | ||
| 6 | + repo_root = os.path.dirname(os.path.dirname(here)) | ||
| 7 | + standard_tests.addTests( | ||
| 8 | + loader.discover(here, pattern="regress_*.py", top_level_dir=repo_root) | ||
| 9 | + ) | ||
| 10 | + return standard_tests | ||
tests/regress/regress_absolute_path.pyadded+110 -0
| @@ -0,0 +1,110 @@ | |||
| 1 | +import os | ||
| 2 | +import tempfile | ||
| 3 | +import unittest | ||
| 4 | +from pathlib import Path | ||
| 5 | + | ||
| 6 | +from src import config | ||
| 7 | + | ||
| 8 | +ABSOLUTE_FIELDS = ("job_root", "output_root", "media_root", "ledger_db") | ||
| 9 | + | ||
| 10 | +ENV_NAMES = ( | ||
| 11 | + "LOG_LEVEL", | ||
| 12 | + "AI_SHARED_TOKEN", | ||
| 13 | + "PODCAST_JOB_ROOT", | ||
| 14 | + "PODCAST_OUTPUT_ROOT", | ||
| 15 | + "PODCAST_MEDIA_ROOT", | ||
| 16 | + "PODCAST_LEDGER_DB", | ||
| 17 | + "PODCAST_MODE", | ||
| 18 | + "PODCAST_PIPELINE_PATH", | ||
| 19 | + "DEEPSEEK_API_KEY", | ||
| 20 | +) | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class AbsolutePathRegression(unittest.TestCase): | ||
| 24 | + def setUp(self) -> None: | ||
| 25 | + self._log_level = config._active_level | ||
| 26 | + self._previous = {name: os.environ.get(name) for name in ENV_NAMES} | ||
| 27 | + for name in ENV_NAMES: | ||
| 28 | + os.environ.pop(name, None) | ||
| 29 | + self._previous_cwd = os.getcwd() | ||
| 30 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-mutlak-") | ||
| 31 | + os.chdir(self._tmp.name) | ||
| 32 | + | ||
| 33 | + def tearDown(self) -> None: | ||
| 34 | + os.chdir(self._previous_cwd) | ||
| 35 | + self._tmp.cleanup() | ||
| 36 | + for name, value in self._previous.items(): | ||
| 37 | + if value is None: | ||
| 38 | + os.environ.pop(name, None) | ||
| 39 | + else: | ||
| 40 | + os.environ[name] = value | ||
| 41 | + config._active_level = self._log_level | ||
| 42 | + | ||
| 43 | + def test_every_relative_root_that_is_given_must_be_made_absolute(self) -> None: | ||
| 44 | + os.environ["PODCAST_JOB_ROOT"] = "isler" | ||
| 45 | + os.environ["PODCAST_OUTPUT_ROOT"] = "out" | ||
| 46 | + os.environ["PODCAST_MEDIA_ROOT"] = "medya" | ||
| 47 | + os.environ["PODCAST_LEDGER_DB"] = "defter.sqlite" | ||
| 48 | + settings = config.Config(require_token=False) | ||
| 49 | + for field in ABSOLUTE_FIELDS: | ||
| 50 | + value = getattr(settings, field) | ||
| 51 | + with self.subTest(field=field): | ||
| 52 | + self.assertTrue( | ||
| 53 | + Path(value).is_absolute(), | ||
| 54 | + f"{field} goreli kaldi ({value}); hat ffmpeg concat listesi yolunu " | ||
| 55 | + f"IKIYE KATLAR ve montaj patlar", | ||
| 56 | + ) | ||
| 57 | + | ||
| 58 | + def test_a_relative_root_starting_with_a_dot_must_also_become_absolute(self) -> None: | ||
| 59 | + os.environ["PODCAST_OUTPUT_ROOT"] = os.path.join(".", "out") | ||
| 60 | + settings = config.Config(require_token=False) | ||
| 61 | + self.assertTrue(Path(settings.output_root).is_absolute()) | ||
| 62 | + self.assertNotIn( | ||
| 63 | + f"{os.sep}.{os.sep}", settings.output_root, "nokta parcasi cozulmedi" | ||
| 64 | + ) | ||
| 65 | + | ||
| 66 | + def test_parent_directory_parts_must_be_resolved(self) -> None: | ||
| 67 | + os.environ["PODCAST_OUTPUT_ROOT"] = os.path.join("a", "..", "out") | ||
| 68 | + settings = config.Config(require_token=False) | ||
| 69 | + self.assertTrue(Path(settings.output_root).is_absolute()) | ||
| 70 | + self.assertNotIn("..", settings.output_root, "ust dizin parcasi cozulmedi") | ||
| 71 | + | ||
| 72 | + def test_the_default_roots_must_be_absolute_too(self) -> None: | ||
| 73 | + settings = config.Config(require_token=False) | ||
| 74 | + for field in ABSOLUTE_FIELDS: | ||
| 75 | + with self.subTest(field=field): | ||
| 76 | + self.assertTrue( | ||
| 77 | + Path(getattr(settings, field)).is_absolute(), | ||
| 78 | + f"varsayilan {field} mutlak degil", | ||
| 79 | + ) | ||
| 80 | + | ||
| 81 | + def test_a_root_that_is_given_as_absolute_must_not_be_changed(self) -> None: | ||
| 82 | + target = Path(self._tmp.name).resolve() / "sabit" | ||
| 83 | + os.environ["PODCAST_OUTPUT_ROOT"] = str(target) | ||
| 84 | + settings = config.Config(require_token=False) | ||
| 85 | + self.assertEqual(Path(settings.output_root), target) | ||
| 86 | + | ||
| 87 | + def test_the_output_root_must_be_independent_of_the_working_directory(self) -> None: | ||
| 88 | + os.environ["PODCAST_OUTPUT_ROOT"] = "out" | ||
| 89 | + first = config.Config(require_token=False).output_root | ||
| 90 | + child = Path(self._tmp.name) / "alt" | ||
| 91 | + child.mkdir(parents=True, exist_ok=True) | ||
| 92 | + os.chdir(child) | ||
| 93 | + second = config.Config(require_token=False).output_root | ||
| 94 | + self.assertNotEqual( | ||
| 95 | + first, | ||
| 96 | + second, | ||
| 97 | + "goreli kok cozulmemis; ayni ayar iki dizinde ayni yolu gosteriyor", | ||
| 98 | + ) | ||
| 99 | + for value in (first, second): | ||
| 100 | + with self.subTest(value=value): | ||
| 101 | + self.assertTrue(Path(value).is_absolute()) | ||
| 102 | + | ||
| 103 | + def test_absolute_paths_must_appear_in_the_summary_output_too(self) -> None: | ||
| 104 | + os.environ["PODCAST_OUTPUT_ROOT"] = "out" | ||
| 105 | + settings = config.Config(require_token=False) | ||
| 106 | + self.assertIn(settings.output_root, settings.summary()) | ||
| 107 | + | ||
| 108 | + | ||
| 109 | +if __name__ == "__main__": | ||
| 110 | + unittest.main() | ||
tests/regress/regress_api_read.pyadded+91 -0
| @@ -0,0 +1,91 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import unittest | ||
| 4 | + | ||
| 5 | +from src import protocol | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +class ApiRequestFormat(unittest.TestCase): | ||
| 9 | + def test_query_goes_in_a_separate_field_question_mark_inside_path_is_rejected(self): | ||
| 10 | + with self.assertRaises(protocol.ApiRefused) as raised: | ||
| 11 | + protocol.build_api_request("r1", "/notes?limit=10") | ||
| 12 | + self.assertEqual(raised.exception.code, "bad_path") | ||
| 13 | + | ||
| 14 | + def test_path_must_start_with_slash(self): | ||
| 15 | + with self.assertRaises(protocol.ApiRefused): | ||
| 16 | + protocol.build_api_request("r1", "notes") | ||
| 17 | + | ||
| 18 | + def test_request_fields_are_identical_to_the_backend_protocol(self): | ||
| 19 | + request = protocol.build_api_request( | ||
| 20 | + "r1", "/notes", query="limit=10&offset=0", on_behalf_of="user:01J" | ||
| 21 | + ) | ||
| 22 | + self.assertEqual(request["id"], "r1") | ||
| 23 | + self.assertEqual(request["path"], "/notes") | ||
| 24 | + self.assertEqual(request["query"], "limit=10&offset=0") | ||
| 25 | + self.assertEqual(request["on_behalf_of"], "user:01J") | ||
| 26 | + self.assertEqual(request["method"], "GET") | ||
| 27 | + | ||
| 28 | + def test_leading_question_mark_of_the_query_is_trimmed(self): | ||
| 29 | + request = protocol.build_api_request("r1", "/notes", query="?limit=10") | ||
| 30 | + self.assertEqual(request["query"], "limit=10") | ||
| 31 | + | ||
| 32 | + def test_on_behalf_of_field_is_not_sent_at_all_when_not_given(self): | ||
| 33 | + request = protocol.build_api_request("r1", "/auth/me") | ||
| 34 | + self.assertNotIn("on_behalf_of", request) | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +class ApiResponseInterpretation(unittest.TestCase): | ||
| 38 | + def test_outcome_ok_status_404_IS_NOT_AN_ERROR_the_api_did_respond(self): | ||
| 39 | + response = protocol.parse_api_response( | ||
| 40 | + {"outcome": "ok", "id": "r1", "status": 404, "body": None} | ||
| 41 | + ) | ||
| 42 | + self.assertEqual(response.status, 404) | ||
| 43 | + self.assertFalse(response.ok) | ||
| 44 | + | ||
| 45 | + def test_outcome_ok_status_403_IS_NOT_AN_ERROR_it_means_insufficient_permission(self): | ||
| 46 | + response = protocol.parse_api_response( | ||
| 47 | + {"outcome": "ok", "id": "r1", "status": 403, "body": {"error": "requires teacher role or higher"}} | ||
| 48 | + ) | ||
| 49 | + self.assertEqual(response.status, 403) | ||
| 50 | + self.assertFalse(response.ok) | ||
| 51 | + | ||
| 52 | + def test_outcome_err_is_a_bridge_refusal_and_raises_an_exception(self): | ||
| 53 | + with self.assertRaises(protocol.ApiRefused) as raised: | ||
| 54 | + protocol.parse_api_response( | ||
| 55 | + {"outcome": "err", "id": "r1", "code": "path_not_allowed", "message": "..."} | ||
| 56 | + ) | ||
| 57 | + self.assertEqual(raised.exception.code, "path_not_allowed") | ||
| 58 | + | ||
| 59 | + def test_ok_is_true_only_for_2xx(self): | ||
| 60 | + for status, expected in ((200, True), (201, True), (299, True), (300, False), (404, False), (500, False)): | ||
| 61 | + with self.subTest(status=status): | ||
| 62 | + response = protocol.parse_api_response( | ||
| 63 | + {"outcome": "ok", "id": "r", "status": status, "body": None} | ||
| 64 | + ) | ||
| 65 | + self.assertEqual(response.ok, expected) | ||
| 66 | + | ||
| 67 | + def test_unknown_outcome_is_rejected(self): | ||
| 68 | + with self.assertRaises(protocol.ApiRefused): | ||
| 69 | + protocol.parse_api_response({"outcome": "belki", "id": "r"}) | ||
| 70 | + | ||
| 71 | + def test_non_object_frame_is_rejected(self): | ||
| 72 | + with self.assertRaises(protocol.ApiRefused): | ||
| 73 | + protocol.parse_api_response(["ok"]) | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +class AllowlistRecord(unittest.TestCase): | ||
| 77 | + def test_allowlist_is_the_same_set_as_the_backend_constant(self): | ||
| 78 | + self.assertEqual(len(protocol.API_ALLOWLIST), 16) | ||
| 79 | + for path in protocol.API_ALLOWLIST: | ||
| 80 | + with self.subTest(path=path): | ||
| 81 | + self.assertTrue(path.startswith("/")) | ||
| 82 | + self.assertNotIn("?", path) | ||
| 83 | + | ||
| 84 | + def test_byte_serving_routes_are_NOT_in_the_allowlist(self): | ||
| 85 | + for forbidden in ("/notes/{id}/files", "/notes/{id}/files/{file_id}", "/users/{id}/avatar"): | ||
| 86 | + with self.subTest(path=forbidden): | ||
| 87 | + self.assertNotIn(forbidden, protocol.API_ALLOWLIST) | ||
| 88 | + | ||
| 89 | + | ||
| 90 | +if __name__ == "__main__": | ||
| 91 | + unittest.main() | ||
tests/regress/regress_cancel_race.pyadded+135 -0
| @@ -0,0 +1,135 @@ | |||
| 1 | +import json | ||
| 2 | +import tempfile | ||
| 3 | +import threading | ||
| 4 | +import unittest | ||
| 5 | +from pathlib import Path | ||
| 6 | + | ||
| 7 | +from src import config, jobs | ||
| 8 | + | ||
| 9 | + | ||
| 10 | +class CancelRaceRegression(unittest.TestCase): | ||
| 11 | + def setUp(self) -> None: | ||
| 12 | + self._log_level = config._active_level | ||
| 13 | + config.set_log_level("error") | ||
| 14 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-yaris-") | ||
| 15 | + self.root = Path(self._tmp.name) | ||
| 16 | + self.store = jobs.JobStore( | ||
| 17 | + root=self.root / "isler", workers=1, max_jobs=8, stage_secs=0.0 | ||
| 18 | + ) | ||
| 19 | + | ||
| 20 | + def tearDown(self) -> None: | ||
| 21 | + self.store.shutdown(timeout=1.0) | ||
| 22 | + self._tmp.cleanup() | ||
| 23 | + config._active_level = self._log_level | ||
| 24 | + | ||
| 25 | + def running_job(self) -> str: | ||
| 26 | + job_id = self.store.submit("kaynak-yaris", "duz_okuma")[0]["job_id"] | ||
| 27 | + self.store.transition(job_id, jobs.STATE_RUNNING) | ||
| 28 | + return job_id | ||
| 29 | + | ||
| 30 | + def read_from_disk(self, job_id: str) -> dict: | ||
| 31 | + with open(self.root / "isler" / f"{job_id}.json", "r", encoding="utf-8") as handle: | ||
| 32 | + return json.load(handle) | ||
| 33 | + | ||
| 34 | + def test_finish_returns_cancelled_not_done_when_cancel_flag_set(self) -> None: | ||
| 35 | + job_id = self.running_job() | ||
| 36 | + self.assertTrue(self.store.cancel(job_id)) | ||
| 37 | + finished = self.store.finish( | ||
| 38 | + job_id, audio_id="a1", duration_secs=12.0, script_id="s1" | ||
| 39 | + ) | ||
| 40 | + self.assertEqual( | ||
| 41 | + finished["state"], | ||
| 42 | + jobs.STATE_CANCELLED, | ||
| 43 | + "iptal bayragi setken finish() 'done' verdi; iptal yarisi kaybedildi", | ||
| 44 | + ) | ||
| 45 | + | ||
| 46 | + def test_finish_must_not_write_audio_id_when_cancel_flag_set(self) -> None: | ||
| 47 | + job_id = self.running_job() | ||
| 48 | + self.store.cancel(job_id) | ||
| 49 | + finished = self.store.finish( | ||
| 50 | + job_id, audio_id="a1", duration_secs=12.0, script_id="s1" | ||
| 51 | + ) | ||
| 52 | + self.assertIsNone( | ||
| 53 | + finished["audio_id"], "iptal edilen is yine de audio_id yazdi" | ||
| 54 | + ) | ||
| 55 | + self.assertIsNone(finished["script_id"], "iptal edilen is yine de script_id yazdi") | ||
| 56 | + self.assertIsNone(finished["duration_secs"]) | ||
| 57 | + self.assertEqual(finished["audio_ids"], []) | ||
| 58 | + self.assertEqual(finished["script_ids"], []) | ||
| 59 | + | ||
| 60 | + def test_in_memory_and_on_disk_result_must_be_identical(self) -> None: | ||
| 61 | + job_id = self.running_job() | ||
| 62 | + self.store.cancel(job_id) | ||
| 63 | + self.store.finish(job_id, audio_id="a1", duration_secs=12.0, script_id="s1") | ||
| 64 | + memory = self.store.get(job_id) | ||
| 65 | + disk = self.read_from_disk(job_id) | ||
| 66 | + self.assertEqual( | ||
| 67 | + memory["state"], | ||
| 68 | + disk["state"], | ||
| 69 | + f"bellek={memory['state']} disk={disk['state']}; iptal diske yansimadi", | ||
| 70 | + ) | ||
| 71 | + self.assertEqual(memory["state"], jobs.STATE_CANCELLED) | ||
| 72 | + self.assertIsNone(disk["audio_id"], "iptal edilen isin audio_id'si diske yazildi") | ||
| 73 | + | ||
| 74 | + def test_job_that_was_not_cancelled_must_become_done_normally(self) -> None: | ||
| 75 | + job_id = self.running_job() | ||
| 76 | + finished = self.store.finish( | ||
| 77 | + job_id, audio_id="a1", duration_secs=12.0, script_id="s1" | ||
| 78 | + ) | ||
| 79 | + self.assertEqual(finished["state"], jobs.STATE_DONE) | ||
| 80 | + self.assertEqual(finished["audio_id"], "a1") | ||
| 81 | + self.assertEqual(self.read_from_disk(job_id)["audio_id"], "a1") | ||
| 82 | + | ||
| 83 | + def test_result_must_stay_consistent_when_cancel_and_finish_run_concurrently(self) -> None: | ||
| 84 | + for round_index in range(20): | ||
| 85 | + with self.subTest(round_index=round_index): | ||
| 86 | + job_id = self.running_job() | ||
| 87 | + barrier = threading.Barrier(2) | ||
| 88 | + output: dict = {} | ||
| 89 | + | ||
| 90 | + def do_cancel() -> None: | ||
| 91 | + barrier.wait() | ||
| 92 | + self.store.cancel(job_id) | ||
| 93 | + | ||
| 94 | + def do_finish() -> None: | ||
| 95 | + barrier.wait() | ||
| 96 | + output["record"] = self.store.finish( | ||
| 97 | + job_id, audio_id="a1", duration_secs=1.0, script_id="s1" | ||
| 98 | + ) | ||
| 99 | + | ||
| 100 | + thread_a = threading.Thread(target=do_cancel) | ||
| 101 | + thread_b = threading.Thread(target=do_finish) | ||
| 102 | + thread_a.start() | ||
| 103 | + thread_b.start() | ||
| 104 | + thread_a.join(5.0) | ||
| 105 | + thread_b.join(5.0) | ||
| 106 | + | ||
| 107 | + record = output["record"] | ||
| 108 | + disk = self.read_from_disk(job_id) | ||
| 109 | + self.assertEqual( | ||
| 110 | + record["state"], | ||
| 111 | + disk["state"], | ||
| 112 | + "yaris sonunda bellek ve disk ayrildi", | ||
| 113 | + ) | ||
| 114 | + if record["state"] == jobs.STATE_CANCELLED: | ||
| 115 | + self.assertIsNone( | ||
| 116 | + disk["audio_id"], | ||
| 117 | + "cancelled biten kosu diske audio_id yazdi", | ||
| 118 | + ) | ||
| 119 | + else: | ||
| 120 | + self.assertEqual(record["state"], jobs.STATE_DONE) | ||
| 121 | + self.assertEqual(disk["audio_id"], "a1") | ||
| 122 | + | ||
| 123 | + def test_finish_must_hold_the_same_lock_while_a_running_job_is_cancelled(self) -> None: | ||
| 124 | + job_id = self.running_job() | ||
| 125 | + self.store.cancel(job_id) | ||
| 126 | + self.assertTrue( | ||
| 127 | + self.store.cancel_requested(job_id), | ||
| 128 | + "iptal bayragi finish() ile ayni kilit altinda okunmali", | ||
| 129 | + ) | ||
| 130 | + self.store.finish(job_id, audio_id="a1", duration_secs=1.0, script_id="s1") | ||
| 131 | + self.assertEqual(self.store.get(job_id)["state"], jobs.STATE_CANCELLED) | ||
| 132 | + | ||
| 133 | + | ||
| 134 | +if __name__ == "__main__": | ||
| 135 | + unittest.main() | ||
tests/regress/regress_daemon_shutdown.pyadded+133 -0
| @@ -0,0 +1,133 @@ | |||
| 1 | +import tempfile | ||
| 2 | +import threading | ||
| 3 | +import time | ||
| 4 | +import unittest | ||
| 5 | +from pathlib import Path | ||
| 6 | + | ||
| 7 | +from src import config, jobs | ||
| 8 | + | ||
| 9 | +SHUTDOWN_CEILING_SECS = 3.0 | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +def wait_for(store: jobs.JobStore, job_id: str, wanted: tuple, deadline_secs: float) -> dict: | ||
| 13 | + limit = time.monotonic() + deadline_secs | ||
| 14 | + while time.monotonic() < limit: | ||
| 15 | + record = store.get(job_id) | ||
| 16 | + if record["state"] in wanted: | ||
| 17 | + return record | ||
| 18 | + time.sleep(0.005) | ||
| 19 | + return store.get(job_id) | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +class DaemonShutdownRegression(unittest.TestCase): | ||
| 23 | + def setUp(self) -> None: | ||
| 24 | + self._log_level = config._active_level | ||
| 25 | + config.set_log_level("error") | ||
| 26 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-kapanis-") | ||
| 27 | + self.root = Path(self._tmp.name) | ||
| 28 | + self.gate = threading.Event() | ||
| 29 | + self.store = jobs.JobStore( | ||
| 30 | + root=self.root / "isler", | ||
| 31 | + workers=2, | ||
| 32 | + max_jobs=8, | ||
| 33 | + stage_secs=0.0, | ||
| 34 | + runner=self.blocking_runner, | ||
| 35 | + ) | ||
| 36 | + | ||
| 37 | + def tearDown(self) -> None: | ||
| 38 | + self.gate.set() | ||
| 39 | + self.store.shutdown(timeout=1.0) | ||
| 40 | + self._tmp.cleanup() | ||
| 41 | + config._active_level = self._log_level | ||
| 42 | + | ||
| 43 | + def blocking_runner(self, ctx) -> None: | ||
| 44 | + self.gate.wait(10.0) | ||
| 45 | + | ||
| 46 | + def worker_threads(self) -> list: | ||
| 47 | + return [ | ||
| 48 | + thread | ||
| 49 | + for thread in threading.enumerate() | ||
| 50 | + if thread.name.startswith("podcast-job") | ||
| 51 | + ] | ||
| 52 | + | ||
| 53 | + def test_worker_threads_must_be_daemon_or_interpreter_joins_them_on_exit(self) -> None: | ||
| 54 | + self.store.start() | ||
| 55 | + job_id = self.store.submit("uzun-is", "duz_okuma")[0]["job_id"] | ||
| 56 | + wait_for(self.store, job_id, (jobs.STATE_RUNNING,), 5.0) | ||
| 57 | + threads = self.worker_threads() | ||
| 58 | + self.assertTrue(threads, "isci thread bulunamadi") | ||
| 59 | + for thread in threads: | ||
| 60 | + with self.subTest(thread=thread.name): | ||
| 61 | + self.assertTrue( | ||
| 62 | + thread.daemon, | ||
| 63 | + "isci thread daemon degil; 45 dakikalik is SIGTERM'i SIGKILL'e cevirir", | ||
| 64 | + ) | ||
| 65 | + | ||
| 66 | + def test_shutdown_does_not_hang_longer_than_the_given_timeout(self) -> None: | ||
| 67 | + self.store.start() | ||
| 68 | + job_id = self.store.submit("uzun-is", "duz_okuma")[0]["job_id"] | ||
| 69 | + running = wait_for(self.store, job_id, (jobs.STATE_RUNNING,), 5.0) | ||
| 70 | + self.assertEqual(running["state"], jobs.STATE_RUNNING, "uzun is kosmaya baslamadi") | ||
| 71 | + started = time.monotonic() | ||
| 72 | + self.store.shutdown(timeout=0.3) | ||
| 73 | + elapsed = time.monotonic() - started | ||
| 74 | + self.assertLess( | ||
| 75 | + elapsed, | ||
| 76 | + SHUTDOWN_CEILING_SECS, | ||
| 77 | + f"shutdown(timeout=0.3) {elapsed:.1f}s takildi; tikanan is kapanmayi kilitliyor", | ||
| 78 | + ) | ||
| 79 | + | ||
| 80 | + def test_shutdown_must_raise_the_stopping_flag(self) -> None: | ||
| 81 | + self.store.start() | ||
| 82 | + self.assertFalse(self.store.stopping) | ||
| 83 | + self.store.shutdown(timeout=0.3) | ||
| 84 | + self.assertTrue(self.store.stopping, "shutdown sonrasi stopping False kaldi") | ||
| 85 | + | ||
| 86 | + def test_shutdown_must_set_the_cancel_flag_on_running_jobs(self) -> None: | ||
| 87 | + self.store.start() | ||
| 88 | + job_id = self.store.submit("uzun-is", "duz_okuma")[0]["job_id"] | ||
| 89 | + wait_for(self.store, job_id, (jobs.STATE_RUNNING,), 5.0) | ||
| 90 | + self.store.shutdown(timeout=0.3) | ||
| 91 | + self.assertTrue( | ||
| 92 | + self.store.get(job_id)["cancel_requested"], | ||
| 93 | + "kapanista kosan ise iptal bayragi konmadi; is kendini durduramaz", | ||
| 94 | + ) | ||
| 95 | + | ||
| 96 | + def test_cancel_flag_set_at_shutdown_must_also_be_written_to_disk(self) -> None: | ||
| 97 | + self.store.start() | ||
| 98 | + job_id = self.store.submit("uzun-is", "duz_okuma")[0]["job_id"] | ||
| 99 | + wait_for(self.store, job_id, (jobs.STATE_RUNNING,), 5.0) | ||
| 100 | + self.store.shutdown(timeout=0.3) | ||
| 101 | + reopened = jobs.JobStore( | ||
| 102 | + root=self.root / "isler", workers=1, max_jobs=8, stage_secs=0.0 | ||
| 103 | + ) | ||
| 104 | + try: | ||
| 105 | + self.assertEqual( | ||
| 106 | + reopened.get(job_id)["state"], | ||
| 107 | + jobs.STATE_FAILED, | ||
| 108 | + "kesilen kosan is yeniden acilista supurulmeli", | ||
| 109 | + ) | ||
| 110 | + self.assertEqual(reopened.get(job_id)["error_code"], jobs.INTERRUPTED_CODE) | ||
| 111 | + finally: | ||
| 112 | + reopened.shutdown(timeout=1.0) | ||
| 113 | + | ||
| 114 | + def test_shutdown_on_an_empty_store_must_return_immediately(self) -> None: | ||
| 115 | + self.store.start() | ||
| 116 | + started = time.monotonic() | ||
| 117 | + self.store.shutdown(timeout=5.0) | ||
| 118 | + elapsed = time.monotonic() - started | ||
| 119 | + self.assertLess( | ||
| 120 | + elapsed, 1.0, f"issiz depoda shutdown {elapsed:.1f}s bekledi; sentinel gonderilmiyor" | ||
| 121 | + ) | ||
| 122 | + | ||
| 123 | + def test_threads_must_stay_daemon_when_the_thread_pool_is_restarted(self) -> None: | ||
| 124 | + self.store.start() | ||
| 125 | + self.store.shutdown(timeout=0.3) | ||
| 126 | + self.store.start() | ||
| 127 | + for thread in self.worker_threads(): | ||
| 128 | + with self.subTest(thread=thread.name): | ||
| 129 | + self.assertTrue(thread.daemon) | ||
| 130 | + | ||
| 131 | + | ||
| 132 | +if __name__ == "__main__": | ||
| 133 | + unittest.main() | ||
tests/regress/regress_format_vocabulary.pyadded+130 -0
| @@ -0,0 +1,130 @@ | |||
| 1 | +import os | ||
| 2 | +import re | ||
| 3 | +import unittest | ||
| 4 | +from pathlib import Path | ||
| 5 | + | ||
| 6 | +from src import capabilities | ||
| 7 | + | ||
| 8 | +LOCKED_FORMATS = ("tek_ogretici", "ogrenci_hoca", "duz_okuma") | ||
| 9 | +LOCKED_DEFAULT = "duz_okuma" | ||
| 10 | + | ||
| 11 | +REPO_ROOT = Path(__file__).resolve().parents[2] | ||
| 12 | + | ||
| 13 | +ENUM_PATTERN = re.compile(r"^\s{4}[A-Z_]+\s*=\s*\"([a-z_]+)\"\s*$", re.MULTILINE) | ||
| 14 | +CHOICES_PATTERN = re.compile(r"choices=\[([^\]]*)\]") | ||
| 15 | +CLI_DEFAULT_PATTERN = re.compile(r"\"--format\",\s*default=\"([a-z_]+)\"") | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +def pipeline_roots() -> list: | ||
| 19 | + candidates = [] | ||
| 20 | + env_path = os.environ.get("PODCAST_PIPELINE_PATH", "").strip() | ||
| 21 | + if env_path: | ||
| 22 | + candidates.append(Path(env_path)) | ||
| 23 | + candidates.append(REPO_ROOT / "vendor" / "pipeline") | ||
| 24 | + candidates.append(REPO_ROOT.parent) | ||
| 25 | + return candidates | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +def pipeline_file(relative: str) -> tuple: | ||
| 29 | + tried = [] | ||
| 30 | + for root in pipeline_roots(): | ||
| 31 | + candidate = root / relative | ||
| 32 | + tried.append(str(candidate)) | ||
| 33 | + if candidate.is_file(): | ||
| 34 | + return candidate, tried | ||
| 35 | + return None, tried | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +class FormatContractRegression(unittest.TestCase): | ||
| 39 | + def test_service_format_set_must_not_drift_from_the_locked_contract(self) -> None: | ||
| 40 | + self.assertEqual( | ||
| 41 | + tuple(capabilities.FORMATS), | ||
| 42 | + LOCKED_FORMATS, | ||
| 43 | + "format kumesi projenin kilitli sozlesmesinden sapti", | ||
| 44 | + ) | ||
| 45 | + | ||
| 46 | + def test_default_format_must_stay_duz_okuma(self) -> None: | ||
| 47 | + self.assertEqual( | ||
| 48 | + capabilities.DEFAULT_FORMAT, | ||
| 49 | + LOCKED_DEFAULT, | ||
| 50 | + "varsayilan format hattin varsayilaniyla ayni kalmali", | ||
| 51 | + ) | ||
| 52 | + | ||
| 53 | + def test_keyless_format_set_must_be_only_duz_okuma(self) -> None: | ||
| 54 | + self.assertEqual( | ||
| 55 | + capabilities.KEYLESS_FORMATS, | ||
| 56 | + (LOCKED_DEFAULT,), | ||
| 57 | + "LLM anahtari yokken yalnizca duz_okuma acik kalmali", | ||
| 58 | + ) | ||
| 59 | + | ||
| 60 | + def test_pipeline_plan_py_format_enum_must_define_the_same_set_as_the_service(self) -> None: | ||
| 61 | + path, tried = pipeline_file(os.path.join("script", "plan.py")) | ||
| 62 | + if path is None: | ||
| 63 | + self.fail( | ||
| 64 | + "gercegin kaynagi script/plan.py bulunamadi; hat yolu degismis olabilir. " | ||
| 65 | + f"denenen yollar: {tried}" | ||
| 66 | + ) | ||
| 67 | + text = path.read_text(encoding="utf-8", errors="replace") | ||
| 68 | + body = text.split("class Format(str, Enum):", 1) | ||
| 69 | + self.assertEqual( | ||
| 70 | + len(body), 2, f"{path} icinde 'class Format(str, Enum):' bulunamadi" | ||
| 71 | + ) | ||
| 72 | + section = body[1].split("\nclass ", 1)[0] | ||
| 73 | + values = ENUM_PATTERN.findall(section) | ||
| 74 | + self.assertEqual( | ||
| 75 | + set(values), | ||
| 76 | + set(LOCKED_FORMATS), | ||
| 77 | + f"hattin Format enum'u servisin format kumesinden farkli ({path})", | ||
| 78 | + ) | ||
| 79 | + self.assertEqual( | ||
| 80 | + set(values), | ||
| 81 | + set(capabilities.FORMATS), | ||
| 82 | + f"capabilities.FORMATS hattin Format enum'uyla ayni kumeyi tasimali ({path})", | ||
| 83 | + ) | ||
| 84 | + | ||
| 85 | + def test_pipeline_cli_format_choices_must_define_the_same_set_as_the_service(self) -> None: | ||
| 86 | + path, tried = pipeline_file(os.path.join("router", "cli.py")) | ||
| 87 | + if path is None: | ||
| 88 | + self.fail( | ||
| 89 | + "gercegin kaynagi router/cli.py bulunamadi; hat yolu degismis olabilir. " | ||
| 90 | + f"denenen yollar: {tried}" | ||
| 91 | + ) | ||
| 92 | + text = path.read_text(encoding="utf-8", errors="replace") | ||
| 93 | + format_lists = [] | ||
| 94 | + for raw in CHOICES_PATTERN.findall(text): | ||
| 95 | + choices = {part.strip().strip("\"'") for part in raw.split(",") if part.strip()} | ||
| 96 | + if LOCKED_DEFAULT in choices: | ||
| 97 | + format_lists.append(choices) | ||
| 98 | + self.assertTrue( | ||
| 99 | + format_lists, | ||
| 100 | + f"{path} icinde format choices listesi bulunamadi; cli sozlesmesi degismis olabilir", | ||
| 101 | + ) | ||
| 102 | + for choices in format_lists: | ||
| 103 | + with self.subTest(choices=sorted(choices)): | ||
| 104 | + self.assertEqual( | ||
| 105 | + choices, | ||
| 106 | + set(capabilities.FORMATS), | ||
| 107 | + f"cli format secenekleri servisin format kumesinden farkli ({path})", | ||
| 108 | + ) | ||
| 109 | + | ||
| 110 | + def test_pipeline_cli_default_format_must_match_the_service_default(self) -> None: | ||
| 111 | + path, tried = pipeline_file(os.path.join("router", "cli.py")) | ||
| 112 | + if path is None: | ||
| 113 | + self.fail( | ||
| 114 | + "gercegin kaynagi router/cli.py bulunamadi; hat yolu degismis olabilir. " | ||
| 115 | + f"denenen yollar: {tried}" | ||
| 116 | + ) | ||
| 117 | + text = path.read_text(encoding="utf-8", errors="replace") | ||
| 118 | + defaults = set(CLI_DEFAULT_PATTERN.findall(text)) | ||
| 119 | + self.assertTrue( | ||
| 120 | + defaults, f"{path} icinde --format varsayilani bulunamadi" | ||
| 121 | + ) | ||
| 122 | + self.assertEqual( | ||
| 123 | + defaults, | ||
| 124 | + {capabilities.DEFAULT_FORMAT}, | ||
| 125 | + f"cli varsayilan formati servisin varsayilanindan farkli ({path})", | ||
| 126 | + ) | ||
| 127 | + | ||
| 128 | + | ||
| 129 | +if __name__ == "__main__": | ||
| 130 | + unittest.main() | ||
tests/regress/regress_identifier_path.pyadded+128 -0
| @@ -0,0 +1,128 @@ | |||
| 1 | +import tempfile | ||
| 2 | +import unittest | ||
| 3 | +from pathlib import Path | ||
| 4 | + | ||
| 5 | +from src import config, pipeline | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +class FakeResult: | ||
| 9 | + def __init__(self, mp3: list, scripts: list, duration: float) -> None: | ||
| 10 | + self.mp3_yollari = mp3 | ||
| 11 | + self.script_yollari = scripts | ||
| 12 | + self.ses_toplam_sn = duration | ||
| 13 | + self.adimlar: list = [] | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +class IdentifierPathRegression(unittest.TestCase): | ||
| 17 | + def setUp(self) -> None: | ||
| 18 | + self._log_level = config._active_level | ||
| 19 | + config.set_log_level("error") | ||
| 20 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-kimlik-") | ||
| 21 | + self.root = Path(self._tmp.name) / "cikti" | ||
| 22 | + | ||
| 23 | + def tearDown(self) -> None: | ||
| 24 | + self._tmp.cleanup() | ||
| 25 | + config._active_level = self._log_level | ||
| 26 | + | ||
| 27 | + def path(self, stem: str, format_name: str, file: str) -> str: | ||
| 28 | + return str(self.root / stem / "ses" / format_name / file) | ||
| 29 | + | ||
| 30 | + def script_path(self, stem: str, format_name: str, file: str) -> str: | ||
| 31 | + return str(self.root / stem / "script" / format_name / file) | ||
| 32 | + | ||
| 33 | + def output(self, mp3: list, scripts: list, duration: float = 10.0) -> dict: | ||
| 34 | + return pipeline.derive_outputs(FakeResult(mp3, scripts, duration), str(self.root)) | ||
| 35 | + | ||
| 36 | + def test_audio_id_must_be_a_path_relative_to_the_output_root_not_the_file_name(self) -> None: | ||
| 37 | + output = self.output( | ||
| 38 | + [self.path("ders", "duz_okuma", "ders-b01.mp3")], | ||
| 39 | + [self.script_path("ders", "duz_okuma", "ders-b01.script.json")], | ||
| 40 | + ) | ||
| 41 | + self.assertEqual( | ||
| 42 | + output["audio_id"], | ||
| 43 | + "ders/ses/duz_okuma/ders-b01.mp3", | ||
| 44 | + "audio_id dosya adina indirgendi; uc dizin seviyesi kayboldu", | ||
| 45 | + ) | ||
| 46 | + self.assertEqual( | ||
| 47 | + output["audio_id"].count("/"), | ||
| 48 | + 3, | ||
| 49 | + "audio_id <stem>/ses/<format>/<dosya> yapisini korumali", | ||
| 50 | + ) | ||
| 51 | + | ||
| 52 | + def test_script_id_must_also_be_a_path_relative_to_the_output_root(self) -> None: | ||
| 53 | + output = self.output( | ||
| 54 | + [self.path("ders", "duz_okuma", "ders-b01.mp3")], | ||
| 55 | + [self.script_path("ders", "duz_okuma", "ders-b01.script.json")], | ||
| 56 | + ) | ||
| 57 | + self.assertEqual( | ||
| 58 | + output["script_id"], | ||
| 59 | + "ders/script/duz_okuma/ders-b01.script.json", | ||
| 60 | + "script_id dosya adina indirgendi", | ||
| 61 | + ) | ||
| 62 | + | ||
| 63 | + def test_same_pdf_in_a_different_format_must_return_a_different_identifier(self) -> None: | ||
| 64 | + plain = self.output( | ||
| 65 | + [self.path("ders", "duz_okuma", "ders-b01.mp3")], | ||
| 66 | + [self.script_path("ders", "duz_okuma", "ders-b01.script.json")], | ||
| 67 | + ) | ||
| 68 | + single = self.output( | ||
| 69 | + [self.path("ders", "tek_ogretici", "ders-b01.mp3")], | ||
| 70 | + [self.script_path("ders", "tek_ogretici", "ders-b01.script.json")], | ||
| 71 | + ) | ||
| 72 | + self.assertNotEqual( | ||
| 73 | + plain["audio_id"], | ||
| 74 | + single["audio_id"], | ||
| 75 | + "ayni PDF'in duz_okuma ve tek_ogretici kosusu AYNI audio_id dondu; " | ||
| 76 | + "bolum_id formattan bagimsiz oldugu icin kimlikler carpisiyor", | ||
| 77 | + ) | ||
| 78 | + self.assertNotEqual( | ||
| 79 | + plain["script_id"], single["script_id"], "iki formatin script kimlikleri carpisti" | ||
| 80 | + ) | ||
| 81 | + | ||
| 82 | + def test_different_chapters_of_the_same_pdf_must_not_collide_either(self) -> None: | ||
| 83 | + output = self.output( | ||
| 84 | + [ | ||
| 85 | + self.path("ders", "duz_okuma", "ders-b01.mp3"), | ||
| 86 | + self.path("ders", "duz_okuma", "ders-b02.mp3"), | ||
| 87 | + self.path("ders", "duz_okuma", "ders-b03.mp3"), | ||
| 88 | + ], | ||
| 89 | + [], | ||
| 90 | + ) | ||
| 91 | + self.assertEqual( | ||
| 92 | + len(set(output["audio_ids"])), 3, "bolum kimlikleri birbirine carpisti" | ||
| 93 | + ) | ||
| 94 | + | ||
| 95 | + def test_different_pdfs_must_not_collide_even_with_the_same_chapter_name(self) -> None: | ||
| 96 | + first = self.output([self.path("ders-a", "duz_okuma", "ders-b01.mp3")], []) | ||
| 97 | + second = self.output([self.path("ders-b", "duz_okuma", "ders-b01.mp3")], []) | ||
| 98 | + self.assertNotEqual( | ||
| 99 | + first["audio_id"], | ||
| 100 | + second["audio_id"], | ||
| 101 | + "iki farkli PDF ayni audio_id dondu", | ||
| 102 | + ) | ||
| 103 | + | ||
| 104 | + def test_path_falling_outside_the_root_must_drop_to_the_file_name(self) -> None: | ||
| 105 | + output = self.output(["/baska/yer/x.mp3"], ["/baska/yer/x.script.json"]) | ||
| 106 | + self.assertEqual( | ||
| 107 | + output["audio_id"], | ||
| 108 | + "x.mp3", | ||
| 109 | + "cikti kokunun disindaki yol dosya adina dusmeli, mutlak yol sizmamali", | ||
| 110 | + ) | ||
| 111 | + self.assertEqual(output["script_id"], "x.script.json") | ||
| 112 | + | ||
| 113 | + def test_identifier_must_always_use_the_posix_separator(self) -> None: | ||
| 114 | + output = self.output([self.path("ders", "duz_okuma", "ders-b01.mp3")], []) | ||
| 115 | + self.assertNotIn( | ||
| 116 | + "\\", output["audio_id"], "kimlik Windows ayraci tasiyor; kablo sozlesmesi posix" | ||
| 117 | + ) | ||
| 118 | + | ||
| 119 | + def test_identifier_must_not_be_an_absolute_path(self) -> None: | ||
| 120 | + output = self.output([self.path("ders", "duz_okuma", "ders-b01.mp3")], []) | ||
| 121 | + self.assertFalse( | ||
| 122 | + Path(output["audio_id"]).is_absolute(), | ||
| 123 | + "kimlik mutlak yol sizdiriyor; container ici yol backend'e gitmemeli", | ||
| 124 | + ) | ||
| 125 | + | ||
| 126 | + | ||
| 127 | +if __name__ == "__main__": | ||
| 128 | + unittest.main() | ||
tests/regress/regress_mutation_survivors.pyadded+142 -0
| @@ -0,0 +1,142 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import asyncio | ||
| 4 | +import json | ||
| 5 | +import struct | ||
| 6 | +import unittest | ||
| 7 | + | ||
| 8 | +from src import protocol | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +class FrameSizeBoundaryIsExact(unittest.TestCase): | ||
| 12 | + def _payload_of_exact_size(self, size: int) -> dict: | ||
| 13 | + filler = "a" * size | ||
| 14 | + while True: | ||
| 15 | + body = json.dumps({"v": filler}, ensure_ascii=False).encode("utf-8") | ||
| 16 | + if len(body) == size: | ||
| 17 | + return {"v": filler} | ||
| 18 | + filler = filler[: len(filler) - (len(body) - size)] | ||
| 19 | + | ||
| 20 | + def test_a_frame_of_exactly_the_limit_must_be_accepted(self) -> None: | ||
| 21 | + payload = self._payload_of_exact_size(protocol.MAX_FRAME_BYTES) | ||
| 22 | + encoded = protocol.encode_frame(payload) | ||
| 23 | + self.assertEqual( | ||
| 24 | + len(encoded) - 4, | ||
| 25 | + protocol.MAX_FRAME_BYTES, | ||
| 26 | + "tam sinirdaki cerceve reddedildi; sinir '>' degil '>=' yazilmis olabilir", | ||
| 27 | + ) | ||
| 28 | + | ||
| 29 | + def test_a_frame_one_byte_over_the_limit_must_be_refused(self) -> None: | ||
| 30 | + payload = self._payload_of_exact_size(protocol.MAX_FRAME_BYTES + 1) | ||
| 31 | + with self.assertRaises(protocol.CapabilityError) as caught: | ||
| 32 | + protocol.encode_frame(payload) | ||
| 33 | + self.assertEqual(caught.exception.code, "frame_too_large") | ||
| 34 | + | ||
| 35 | + def test_reader_accepts_a_declared_length_exactly_at_the_limit(self) -> None: | ||
| 36 | + async def read_it() -> None: | ||
| 37 | + stream = protocol.FrameStream() | ||
| 38 | + payload = self._payload_of_exact_size(protocol.MAX_FRAME_BYTES) | ||
| 39 | + encoded = protocol.encode_frame(payload) | ||
| 40 | + stream.feed(encoded, end=True) | ||
| 41 | + decoded = await stream.read_frame() | ||
| 42 | + self.assertEqual(decoded, payload) | ||
| 43 | + | ||
| 44 | + asyncio.run(read_it()) | ||
| 45 | + | ||
| 46 | + def test_reader_refuses_a_declared_length_one_byte_over_the_limit(self) -> None: | ||
| 47 | + async def read_it() -> None: | ||
| 48 | + stream = protocol.FrameStream() | ||
| 49 | + stream.feed(struct.pack(">I", protocol.MAX_FRAME_BYTES + 1), end=True) | ||
| 50 | + with self.assertRaises(protocol.CapabilityError) as caught: | ||
| 51 | + await stream.read_frame() | ||
| 52 | + self.assertEqual(caught.exception.code, "frame_too_large") | ||
| 53 | + | ||
| 54 | + asyncio.run(read_it()) | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +class ExceptionsCarryTheirMessage(unittest.TestCase): | ||
| 58 | + def test_capability_error_text_is_exactly_the_message(self) -> None: | ||
| 59 | + error = protocol.CapabilityError("bad_request", "alan eksik") | ||
| 60 | + self.assertEqual( | ||
| 61 | + str(error), "alan eksik", | ||
| 62 | + "metin tam esit olmali; alt dize kontrolu super().__init__ " | ||
| 63 | + "silinse bile gecer cunku BaseException.__new__ args'i saklar", | ||
| 64 | + ) | ||
| 65 | + self.assertEqual(error.args, ("alan eksik",)) | ||
| 66 | + self.assertEqual(error.code, "bad_request") | ||
| 67 | + | ||
| 68 | + def test_handshake_rejection_text_is_the_formatted_sentence(self) -> None: | ||
| 69 | + error = protocol.HandshakeRejected("unauthorized", "token yanlis") | ||
| 70 | + self.assertEqual( | ||
| 71 | + str(error), "backend kaydi reddetti (unauthorized): token yanlis" | ||
| 72 | + ) | ||
| 73 | + self.assertEqual(len(error.args), 1) | ||
| 74 | + | ||
| 75 | + def test_api_refusal_text_is_the_formatted_sentence(self) -> None: | ||
| 76 | + error = protocol.ApiRefused("path_not_allowed", "/courses yasak") | ||
| 77 | + self.assertEqual( | ||
| 78 | + str(error), "kopru istegi reddetti (path_not_allowed): /courses yasak" | ||
| 79 | + ) | ||
| 80 | + self.assertEqual(len(error.args), 1) | ||
| 81 | + | ||
| 82 | + | ||
| 83 | +class ApiResponseKeepsEveryField(unittest.TestCase): | ||
| 84 | + def test_request_id_is_carried_through(self) -> None: | ||
| 85 | + answer = protocol.parse_api_response( | ||
| 86 | + {"outcome": "ok", "id": "01ABC", "status": 200, "body": {"x": 1}} | ||
| 87 | + ) | ||
| 88 | + self.assertEqual(answer.request_id, "01ABC") | ||
| 89 | + | ||
| 90 | + def test_body_is_carried_through(self) -> None: | ||
| 91 | + answer = protocol.parse_api_response( | ||
| 92 | + {"outcome": "ok", "id": "r", "status": 200, "body": {"role": "ai"}} | ||
| 93 | + ) | ||
| 94 | + self.assertEqual(answer.body, {"role": "ai"}) | ||
| 95 | + | ||
| 96 | + def test_status_is_carried_through(self) -> None: | ||
| 97 | + answer = protocol.parse_api_response( | ||
| 98 | + {"outcome": "ok", "id": "r", "status": 404, "body": None} | ||
| 99 | + ) | ||
| 100 | + self.assertEqual(answer.status, 404) | ||
| 101 | + | ||
| 102 | + | ||
| 103 | +class ComparisonsRejectTheWrongSide(unittest.TestCase): | ||
| 104 | + def test_a_welcome_with_a_different_protocol_is_rejected(self) -> None: | ||
| 105 | + with self.assertRaises(protocol.HandshakeRejected): | ||
| 106 | + protocol.parse_greeting( | ||
| 107 | + {"type": "welcome", "worker_id": "w", "protocol": "hab/2"} | ||
| 108 | + ) | ||
| 109 | + | ||
| 110 | + def test_a_welcome_with_the_right_protocol_is_accepted(self) -> None: | ||
| 111 | + worker = protocol.parse_greeting( | ||
| 112 | + {"type": "welcome", "worker_id": "w9", "protocol": protocol.PROTOCOL} | ||
| 113 | + ) | ||
| 114 | + self.assertEqual(worker, "w9") | ||
| 115 | + | ||
| 116 | + def test_an_outcome_other_than_ok_or_err_is_rejected(self) -> None: | ||
| 117 | + for outcome in ("okk", "OK", "ok ", "", "success"): | ||
| 118 | + with self.subTest(outcome=outcome): | ||
| 119 | + with self.assertRaises(protocol.ApiRefused): | ||
| 120 | + protocol.parse_api_response({"outcome": outcome, "id": "r"}) | ||
| 121 | + | ||
| 122 | + | ||
| 123 | +class TimeoutConstantsStayInsideTheBackendWindow(unittest.TestCase): | ||
| 124 | + def test_greeting_timeout_is_below_the_backend_handshake_window(self) -> None: | ||
| 125 | + self.assertLess( | ||
| 126 | + protocol.GREETING_TIMEOUT_SECS, | ||
| 127 | + 10.0, | ||
| 128 | + "backend AI_HANDSHAKE_TIMEOUT_SECS=10; esit veya buyuk olursa bizim " | ||
| 129 | + "zaman asimimiz hic atesnemez, jenerik EOFError aliriz", | ||
| 130 | + ) | ||
| 131 | + self.assertGreater(protocol.GREETING_TIMEOUT_SECS, 0.0) | ||
| 132 | + | ||
| 133 | + def test_keepalive_stays_below_the_backend_idle_timeout(self) -> None: | ||
| 134 | + self.assertLess( | ||
| 135 | + protocol.KEEPALIVE_SECS, | ||
| 136 | + protocol.IDLE_TIMEOUT_SECS, | ||
| 137 | + "keepalive idle timeout'un altinda kalmali, yoksa baglanti duser", | ||
| 138 | + ) | ||
| 139 | + | ||
| 140 | + | ||
| 141 | +if __name__ == "__main__": | ||
| 142 | + unittest.main() | ||
tests/regress/regress_path_traversal.pyadded+105 -0
| @@ -0,0 +1,105 @@ | |||
| 1 | +import tempfile | ||
| 2 | +import unittest | ||
| 3 | +from pathlib import Path | ||
| 4 | + | ||
| 5 | +from src import config, jobs | ||
| 6 | + | ||
| 7 | +REJECTED_NAMES = ( | ||
| 8 | + "..", | ||
| 9 | + "../x", | ||
| 10 | + "a/b", | ||
| 11 | + "/etc/passwd", | ||
| 12 | + "..\\x", | ||
| 13 | + ".", | ||
| 14 | + "", | ||
| 15 | + "x" * 129, | ||
| 16 | + "\\\\srv\\share", | ||
| 17 | + "C:\\Windows", | ||
| 18 | + "ders\x00.pdf", | ||
| 19 | +) | ||
| 20 | + | ||
| 21 | +ACCEPTED_NAMES = ( | ||
| 22 | + "ders-01.pdf", | ||
| 23 | + "ders_01.pdf", | ||
| 24 | + "ders.01.pdf", | ||
| 25 | + "DERS01", | ||
| 26 | + "a", | ||
| 27 | + "x" * 128, | ||
| 28 | +) | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +class PathTraversalRegression(unittest.TestCase): | ||
| 32 | + def setUp(self) -> None: | ||
| 33 | + self._log_level = config._active_level | ||
| 34 | + config.set_log_level("error") | ||
| 35 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-kacis-") | ||
| 36 | + self.media_root = Path(self._tmp.name) / "medya" | ||
| 37 | + self.media_root.mkdir(parents=True, exist_ok=True) | ||
| 38 | + | ||
| 39 | + def tearDown(self) -> None: | ||
| 40 | + self._tmp.cleanup() | ||
| 41 | + config._active_level = self._log_level | ||
| 42 | + | ||
| 43 | + def test_traversal_attempts_must_be_rejected(self) -> None: | ||
| 44 | + for source_id in REJECTED_NAMES: | ||
| 45 | + with self.subTest(source_id=source_id): | ||
| 46 | + with self.assertRaises(ValueError, msg=f"kabul edildi: {source_id!r}"): | ||
| 47 | + jobs.resolve_source(self.media_root, source_id) | ||
| 48 | + | ||
| 49 | + def test_a_non_text_source_id_must_be_rejected(self) -> None: | ||
| 50 | + for source_id in (None, 7, b"ders.pdf", ["ders.pdf"], Path("ders.pdf")): | ||
| 51 | + with self.subTest(source_id=source_id): | ||
| 52 | + with self.assertRaises(ValueError): | ||
| 53 | + jobs.resolve_source(self.media_root, source_id) | ||
| 54 | + | ||
| 55 | + def test_valid_names_must_be_accepted(self) -> None: | ||
| 56 | + for source_id in ACCEPTED_NAMES: | ||
| 57 | + with self.subTest(source_id=source_id): | ||
| 58 | + resolved = jobs.resolve_source(self.media_root, source_id) | ||
| 59 | + self.assertEqual(resolved.name, source_id) | ||
| 60 | + | ||
| 61 | + def test_the_resolved_path_must_stay_under_the_media_root(self) -> None: | ||
| 62 | + root = self.media_root.resolve() | ||
| 63 | + for source_id in ACCEPTED_NAMES: | ||
| 64 | + with self.subTest(source_id=source_id): | ||
| 65 | + resolved = jobs.resolve_source(self.media_root, source_id) | ||
| 66 | + self.assertIn( | ||
| 67 | + root, | ||
| 68 | + resolved.parents, | ||
| 69 | + f"cozulen yol medya kokunun disina cikti: {resolved}", | ||
| 70 | + ) | ||
| 71 | + self.assertNotEqual(resolved, root, "cozulen yol medya kokunun kendisi olamaz") | ||
| 72 | + | ||
| 73 | + def test_shell_and_redirection_characters_must_be_rejected(self) -> None: | ||
| 74 | + for source_id in ( | ||
| 75 | + "ders 01.pdf", | ||
| 76 | + "ders;rm -rf /", | ||
| 77 | + "ders|kat", | ||
| 78 | + "ders$(whoami)", | ||
| 79 | + "ders\npdf", | ||
| 80 | + "ders\tpdf", | ||
| 81 | + "ders*.pdf", | ||
| 82 | + "ders?.pdf", | ||
| 83 | + "ders<>.pdf", | ||
| 84 | + "ders:akis", | ||
| 85 | + ): | ||
| 86 | + with self.subTest(source_id=source_id): | ||
| 87 | + with self.assertRaises(ValueError): | ||
| 88 | + jobs.resolve_source(self.media_root, source_id) | ||
| 89 | + | ||
| 90 | + def test_the_length_limit_must_cut_off_at_exactly_128_characters(self) -> None: | ||
| 91 | + jobs.resolve_source(self.media_root, "x" * 128) | ||
| 92 | + with self.assertRaises(ValueError, msg="129 karakterlik ad kabul edildi"): | ||
| 93 | + jobs.resolve_source(self.media_root, "x" * 129) | ||
| 94 | + | ||
| 95 | + def test_the_pipeline_layer_must_use_the_same_gate(self) -> None: | ||
| 96 | + from src import pipeline | ||
| 97 | + | ||
| 98 | + for source_id in REJECTED_NAMES: | ||
| 99 | + with self.subTest(source_id=source_id): | ||
| 100 | + with self.assertRaises(ValueError): | ||
| 101 | + pipeline.resolve_pdf(str(self.media_root), source_id) | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +if __name__ == "__main__": | ||
| 105 | + unittest.main() | ||
tests/regress/regress_queued_failed.pyadded+92 -0
| @@ -0,0 +1,92 @@ | |||
| 1 | +import tempfile | ||
| 2 | +import unittest | ||
| 3 | +from pathlib import Path | ||
| 4 | + | ||
| 5 | +from src import config, jobs | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +class QueuedFailedRegression(unittest.TestCase): | ||
| 9 | + def setUp(self) -> None: | ||
| 10 | + self._log_level = config._active_level | ||
| 11 | + config.set_log_level("error") | ||
| 12 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-erken-") | ||
| 13 | + self.root = Path(self._tmp.name) | ||
| 14 | + self._stores: list = [] | ||
| 15 | + | ||
| 16 | + def tearDown(self) -> None: | ||
| 17 | + for store in self._stores: | ||
| 18 | + store.shutdown(timeout=1.0) | ||
| 19 | + self._tmp.cleanup() | ||
| 20 | + config._active_level = self._log_level | ||
| 21 | + | ||
| 22 | + def make_store(self, name: str, max_jobs: int = 8) -> jobs.JobStore: | ||
| 23 | + store = jobs.JobStore( | ||
| 24 | + root=self.root / name, workers=1, max_jobs=max_jobs, stage_secs=0.0 | ||
| 25 | + ) | ||
| 26 | + self._stores.append(store) | ||
| 27 | + return store | ||
| 28 | + | ||
| 29 | + def test_the_queued_to_failed_transition_must_be_legal_in_the_state_machine(self) -> None: | ||
| 30 | + self.assertIn( | ||
| 31 | + jobs.STATE_FAILED, | ||
| 32 | + jobs.TRANSITIONS[jobs.STATE_QUEUED], | ||
| 33 | + "queued -> failed yasal degil; begin() oncesi patlayan is sonsuza kadar " | ||
| 34 | + "queued kalir", | ||
| 35 | + ) | ||
| 36 | + self.assertTrue(jobs.can_transition(jobs.STATE_QUEUED, jobs.STATE_FAILED)) | ||
| 37 | + | ||
| 38 | + def test_a_job_that_fails_before_starting_must_be_able_to_become_failed(self) -> None: | ||
| 39 | + store = self.make_store("erken") | ||
| 40 | + job_id = store.submit("kaynak-erken", "duz_okuma")[0]["job_id"] | ||
| 41 | + try: | ||
| 42 | + record = store.fail(job_id, "source_not_found") | ||
| 43 | + except jobs.InvalidTransition as exc: | ||
| 44 | + self.fail(f"queued -> failed reddedildi, is kotayi kalici yer: {exc}") | ||
| 45 | + self.assertEqual(record["state"], jobs.STATE_FAILED) | ||
| 46 | + self.assertEqual(record["error_code"], "source_not_found", "hata kodu kaybedildi") | ||
| 47 | + | ||
| 48 | + def test_a_failed_job_must_not_occupy_a_slot_in_the_max_jobs_quota(self) -> None: | ||
| 49 | + store = self.make_store("kota", max_jobs=1) | ||
| 50 | + job_id = store.submit("ilk", "duz_okuma")[0]["job_id"] | ||
| 51 | + with self.assertRaises(jobs.JobStoreFull): | ||
| 52 | + store.submit("ikinci", "duz_okuma") | ||
| 53 | + store.fail(job_id, "source_not_found") | ||
| 54 | + store.submit("ikinci", "duz_okuma") | ||
| 55 | + | ||
| 56 | + def test_a_failed_job_must_not_be_requeued_on_every_startup(self) -> None: | ||
| 57 | + seed = self.make_store("acilis") | ||
| 58 | + job_id = seed.submit("kaynak-erken", "duz_okuma")[0]["job_id"] | ||
| 59 | + seed.fail(job_id, "source_not_found") | ||
| 60 | + | ||
| 61 | + reopened = self.make_store("acilis") | ||
| 62 | + self.assertEqual( | ||
| 63 | + reopened.get(job_id)["state"], | ||
| 64 | + jobs.STATE_FAILED, | ||
| 65 | + "failed is yeniden acilista queued'a donmemeli", | ||
| 66 | + ) | ||
| 67 | + self.assertEqual( | ||
| 68 | + reopened.start(), | ||
| 69 | + 0, | ||
| 70 | + "failed is her acilista yeniden kuyruga aliniyor; kotadan slot yiyor", | ||
| 71 | + ) | ||
| 72 | + | ||
| 73 | + def test_no_job_must_stay_queued_forever(self) -> None: | ||
| 74 | + store = self.make_store("terminal") | ||
| 75 | + for target in (jobs.STATE_RUNNING, jobs.STATE_CANCELLED, jobs.STATE_FAILED): | ||
| 76 | + with self.subTest(target=target): | ||
| 77 | + job_id = store.submit("kaynak", "duz_okuma")[0]["job_id"] | ||
| 78 | + store.transition(job_id, target) | ||
| 79 | + self.assertEqual(store.get(job_id)["state"], target) | ||
| 80 | + | ||
| 81 | + def test_failed_must_stay_terminal_and_must_not_go_back(self) -> None: | ||
| 82 | + store = self.make_store("geri") | ||
| 83 | + job_id = store.submit("kaynak", "duz_okuma")[0]["job_id"] | ||
| 84 | + store.fail(job_id, "source_not_found") | ||
| 85 | + for target in (jobs.STATE_QUEUED, jobs.STATE_RUNNING, jobs.STATE_DONE): | ||
| 86 | + with self.subTest(target=target): | ||
| 87 | + with self.assertRaises(jobs.InvalidTransition): | ||
| 88 | + store.transition(job_id, target) | ||
| 89 | + | ||
| 90 | + | ||
| 91 | +if __name__ == "__main__": | ||
| 92 | + unittest.main() | ||
tests/regress/regress_retention.pyadded+158 -0
| @@ -0,0 +1,158 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import json | ||
| 4 | +import os | ||
| 5 | +import tempfile | ||
| 6 | +import unittest | ||
| 7 | +from pathlib import Path | ||
| 8 | + | ||
| 9 | +from src import jobs | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +def _record(job_id, state, updated_at, audio=None, script=None): | ||
| 13 | + return { | ||
| 14 | + "job_id": job_id, | ||
| 15 | + "source_id": "kaynak.pdf", | ||
| 16 | + "format": "duz_okuma", | ||
| 17 | + "state": state, | ||
| 18 | + "stage": "done", | ||
| 19 | + "progress": 1.0, | ||
| 20 | + "error_code": None, | ||
| 21 | + "cancel_requested": False, | ||
| 22 | + "audio_id": (audio or [""])[0] if audio else None, | ||
| 23 | + "duration_secs": 1.0, | ||
| 24 | + "script_id": (script or [""])[0] if script else None, | ||
| 25 | + "created_at": updated_at, | ||
| 26 | + "updated_at": updated_at, | ||
| 27 | + "audio_ids": audio or [], | ||
| 28 | + "script_ids": script or [], | ||
| 29 | + } | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +class RetentionDeletesExpiredJobs(unittest.TestCase): | ||
| 33 | + def setUp(self): | ||
| 34 | + self._tmp = tempfile.TemporaryDirectory() | ||
| 35 | + self.root = Path(self._tmp.name) | ||
| 36 | + self.job_root = self.root / "jobs" | ||
| 37 | + self.output = self.root / "out" | ||
| 38 | + self.job_root.mkdir() | ||
| 39 | + self.output.mkdir() | ||
| 40 | + | ||
| 41 | + def tearDown(self): | ||
| 42 | + self._tmp.cleanup() | ||
| 43 | + | ||
| 44 | + def _write(self, record, outputs=()): | ||
| 45 | + (self.job_root / f"{record['job_id']}.json").write_text( | ||
| 46 | + json.dumps(record), encoding="utf-8" | ||
| 47 | + ) | ||
| 48 | + for rel in outputs: | ||
| 49 | + path = self.output / rel | ||
| 50 | + path.parent.mkdir(parents=True, exist_ok=True) | ||
| 51 | + path.write_bytes(b"x" * 16) | ||
| 52 | + | ||
| 53 | + def _store(self, days): | ||
| 54 | + return jobs.JobStore( | ||
| 55 | + root=self.job_root, retention_days=days, output_root=self.output | ||
| 56 | + ) | ||
| 57 | + | ||
| 58 | + def test_nothing_is_deleted_while_retention_is_off(self): | ||
| 59 | + old = jobs._now_ms() - 400 * jobs.DAY_MS | ||
| 60 | + self._write(_record("ESKI", jobs.STATE_DONE, old, ["a/x.mp3"]), ["a/x.mp3"]) | ||
| 61 | + store = self._store(0.0) | ||
| 62 | + self.assertEqual(store.purged, 0, "retention kapaliyken is silindi") | ||
| 63 | + self.assertTrue((self.output / "a/x.mp3").exists()) | ||
| 64 | + | ||
| 65 | + def test_expired_finished_job_and_its_outputs_are_deleted(self): | ||
| 66 | + old = jobs._now_ms() - 40 * jobs.DAY_MS | ||
| 67 | + self._write( | ||
| 68 | + _record("ESKI", jobs.STATE_DONE, old, ["a/x.mp3"], ["a/x.script.json"]), | ||
| 69 | + ["a/x.mp3", "a/x.script.json"], | ||
| 70 | + ) | ||
| 71 | + store = self._store(30.0) | ||
| 72 | + self.assertEqual(store.purged, 1) | ||
| 73 | + self.assertFalse((self.job_root / "ESKI.json").exists(), "is dosyasi kaldi") | ||
| 74 | + self.assertFalse((self.output / "a/x.mp3").exists(), "ses dosyasi kaldi") | ||
| 75 | + self.assertFalse((self.output / "a/x.script.json").exists(), "script kaldi") | ||
| 76 | + | ||
| 77 | + def test_a_fresh_finished_job_is_PRESERVED(self): | ||
| 78 | + fresh = jobs._now_ms() - 2 * jobs.DAY_MS | ||
| 79 | + self._write(_record("TAZE", jobs.STATE_DONE, fresh, ["a/y.mp3"]), ["a/y.mp3"]) | ||
| 80 | + store = self._store(30.0) | ||
| 81 | + self.assertEqual(store.purged, 0) | ||
| 82 | + self.assertTrue((self.output / "a/y.mp3").exists()) | ||
| 83 | + | ||
| 84 | + def test_an_unfinished_job_is_preserved_REGARDLESS_OF_ITS_AGE(self): | ||
| 85 | + old = jobs._now_ms() - 400 * jobs.DAY_MS | ||
| 86 | + for state in (jobs.STATE_QUEUED, jobs.STATE_RUNNING): | ||
| 87 | + with self.subTest(state=state): | ||
| 88 | + root = Path(tempfile.mkdtemp()) | ||
| 89 | + (root / f"IS.json").write_text( | ||
| 90 | + json.dumps(_record("IS", state, old)), encoding="utf-8" | ||
| 91 | + ) | ||
| 92 | + store = jobs.JobStore(root=root, retention_days=1.0, output_root=self.output) | ||
| 93 | + self.assertEqual(store.purged, 0, f"{state} durumundaki is silindi") | ||
| 94 | + self.assertTrue((root / "IS.json").exists()) | ||
| 95 | + | ||
| 96 | + def test_cancelled_and_failed_jobs_are_also_deleted_when_they_expire(self): | ||
| 97 | + old = jobs._now_ms() - 40 * jobs.DAY_MS | ||
| 98 | + self._write(_record("A", jobs.STATE_FAILED, old)) | ||
| 99 | + self._write(_record("B", jobs.STATE_CANCELLED, old)) | ||
| 100 | + store = self._store(30.0) | ||
| 101 | + self.assertEqual(store.purged, 2) | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +class RetentionGuardsAgainstPathTraversal(unittest.TestCase): | ||
| 105 | + def setUp(self): | ||
| 106 | + self._tmp = tempfile.TemporaryDirectory() | ||
| 107 | + self.root = Path(self._tmp.name) | ||
| 108 | + self.job_root = self.root / "jobs" | ||
| 109 | + self.output = self.root / "out" | ||
| 110 | + self.outside = self.root / "disarida" | ||
| 111 | + self.job_root.mkdir() | ||
| 112 | + self.output.mkdir() | ||
| 113 | + self.outside.mkdir() | ||
| 114 | + self.victim = self.outside / "dokunulmaz.txt" | ||
| 115 | + self.victim.write_bytes(b"KORUNMALI") | ||
| 116 | + | ||
| 117 | + def tearDown(self): | ||
| 118 | + self._tmp.cleanup() | ||
| 119 | + | ||
| 120 | + def test_identifier_pointing_outside_the_output_root_is_not_deleted(self): | ||
| 121 | + old = jobs._now_ms() - 40 * jobs.DAY_MS | ||
| 122 | + bad = "../disarida/dokunulmaz.txt" | ||
| 123 | + (self.job_root / "KOTU.json").write_text( | ||
| 124 | + json.dumps(_record("KOTU", jobs.STATE_DONE, old, [bad])), encoding="utf-8" | ||
| 125 | + ) | ||
| 126 | + store = jobs.JobStore(root=self.job_root, retention_days=30.0, output_root=self.output) | ||
| 127 | + self.assertEqual(store.purged, 1, "is kaydi yine de temizlenmeli") | ||
| 128 | + self.assertTrue( | ||
| 129 | + self.victim.exists(), | ||
| 130 | + "cikti kokunun DISINDAKI dosya silindi - yol kacisi korumasi calismadi", | ||
| 131 | + ) | ||
| 132 | + | ||
| 133 | + def test_absolute_paths_and_drive_letters_are_rejected(self): | ||
| 134 | + store = jobs.JobStore(root=self.job_root, retention_days=30.0, output_root=self.output) | ||
| 135 | + for bad in ("/etc/passwd", r"\\sunucu\pay", "C:/Windows/x", "..", ".", ""): | ||
| 136 | + with self.subTest(identifier=bad): | ||
| 137 | + self.assertIsNone( | ||
| 138 | + store._safe_output_path(bad), f"guvensiz kimlik kabul edildi: {bad!r}" | ||
| 139 | + ) | ||
| 140 | + | ||
| 141 | + def test_a_normal_identifier_under_the_root_is_accepted(self): | ||
| 142 | + store = jobs.JobStore(root=self.job_root, retention_days=30.0, output_root=self.output) | ||
| 143 | + path = store._safe_output_path("ders/ses/duz_okuma/ders-b01.mp3") | ||
| 144 | + self.assertIsNotNone(path) | ||
| 145 | + self.assertTrue(str(path).startswith(str(self.output.resolve()))) | ||
| 146 | + | ||
| 147 | + def test_no_file_is_deleted_when_no_output_root_is_given(self): | ||
| 148 | + old = jobs._now_ms() - 40 * jobs.DAY_MS | ||
| 149 | + (self.job_root / "X.json").write_text( | ||
| 150 | + json.dumps(_record("X", jobs.STATE_DONE, old, ["a/x.mp3"])), encoding="utf-8" | ||
| 151 | + ) | ||
| 152 | + store = jobs.JobStore(root=self.job_root, retention_days=30.0, output_root=None) | ||
| 153 | + self.assertIsNone(store._safe_output_path("a/x.mp3")) | ||
| 154 | + self.assertEqual(store.purged, 1) | ||
| 155 | + | ||
| 156 | + | ||
| 157 | +if __name__ == "__main__": | ||
| 158 | + unittest.main() | ||
tests/regress/regress_schema_validation.pyadded+144 -0
| @@ -0,0 +1,144 @@ | |||
| 1 | +import json | ||
| 2 | +import tempfile | ||
| 3 | +import unittest | ||
| 4 | +from pathlib import Path | ||
| 5 | + | ||
| 6 | +from src import config, jobs | ||
| 7 | + | ||
| 8 | +FIELDS_ABSENT_FROM_OLD_RECORDS = ("audio_ids", "script_ids") | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +class SchemaValidationRegression(unittest.TestCase): | ||
| 12 | + def setUp(self) -> None: | ||
| 13 | + self._log_level = config._active_level | ||
| 14 | + config.set_log_level("error") | ||
| 15 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-sema-") | ||
| 16 | + self.root = Path(self._tmp.name) / "isler" | ||
| 17 | + self._stores: list = [] | ||
| 18 | + | ||
| 19 | + def tearDown(self) -> None: | ||
| 20 | + for store in self._stores: | ||
| 21 | + store.shutdown(timeout=1.0) | ||
| 22 | + self._tmp.cleanup() | ||
| 23 | + config._active_level = self._log_level | ||
| 24 | + | ||
| 25 | + def make_store(self) -> jobs.JobStore: | ||
| 26 | + store = jobs.JobStore(root=self.root, workers=1, max_jobs=8, stage_secs=0.0) | ||
| 27 | + self._stores.append(store) | ||
| 28 | + return store | ||
| 29 | + | ||
| 30 | + def write_record(self, job_id: str, record: dict) -> None: | ||
| 31 | + with open(self.root / f"{job_id}.json", "w", encoding="utf-8") as handle: | ||
| 32 | + json.dump(record, handle) | ||
| 33 | + | ||
| 34 | + def read_record(self, job_id: str) -> dict: | ||
| 35 | + with open(self.root / f"{job_id}.json", "r", encoding="utf-8") as handle: | ||
| 36 | + return json.load(handle) | ||
| 37 | + | ||
| 38 | + def test_a_record_with_a_missing_field_must_be_skipped_at_startup_not_raise_keyerror(self) -> None: | ||
| 39 | + for field in jobs.REQUIRED_FIELDS: | ||
| 40 | + if field == "job_id": | ||
| 41 | + continue | ||
| 42 | + with self.subTest(missing=field): | ||
| 43 | + seed = self.make_store() | ||
| 44 | + healthy_id = seed.submit("saglam", "duz_okuma")[0]["job_id"] | ||
| 45 | + corrupt_id = seed.submit("bozuk", "duz_okuma")[0]["job_id"] | ||
| 46 | + corrupt = self.read_record(corrupt_id) | ||
| 47 | + corrupt.pop(field) | ||
| 48 | + self.write_record(corrupt_id, corrupt) | ||
| 49 | + | ||
| 50 | + reopened = self.make_store() | ||
| 51 | + with self.assertRaises( | ||
| 52 | + jobs.JobNotFound, msg=f"'{field}' alani eksik kayit acilista atlanmadi" | ||
| 53 | + ): | ||
| 54 | + reopened.get(corrupt_id) | ||
| 55 | + self.assertEqual( | ||
| 56 | + reopened.get(healthy_id)["state"], | ||
| 57 | + jobs.STATE_QUEUED, | ||
| 58 | + "saglam kayit eksik alanli komsusu yuzunden bozuldu", | ||
| 59 | + ) | ||
| 60 | + for path in sorted(self.root.glob("*.json")): | ||
| 61 | + path.unlink() | ||
| 62 | + | ||
| 63 | + def test_audio_ids_and_script_ids_must_not_be_added_to_required_fields(self) -> None: | ||
| 64 | + for field in FIELDS_ABSENT_FROM_OLD_RECORDS: | ||
| 65 | + with self.subTest(field=field): | ||
| 66 | + self.assertNotIn( | ||
| 67 | + field, | ||
| 68 | + jobs.REQUIRED_FIELDS, | ||
| 69 | + f"REQUIRED_FIELDS'a '{field}' eklenmis; alan eklenmeden once yazilmis " | ||
| 70 | + f"eski kayitlar acilista topluca atilir", | ||
| 71 | + ) | ||
| 72 | + | ||
| 73 | + def test_an_old_record_without_the_plural_identifier_fields_must_still_load(self) -> None: | ||
| 74 | + seed = self.make_store() | ||
| 75 | + job_id = seed.submit("eski", "duz_okuma")[0]["job_id"] | ||
| 76 | + old = self.read_record(job_id) | ||
| 77 | + for field in FIELDS_ABSENT_FROM_OLD_RECORDS: | ||
| 78 | + old.pop(field, None) | ||
| 79 | + self.write_record(job_id, old) | ||
| 80 | + | ||
| 81 | + reopened = self.make_store() | ||
| 82 | + record = reopened.get(job_id) | ||
| 83 | + self.assertEqual( | ||
| 84 | + record["state"], | ||
| 85 | + jobs.STATE_QUEUED, | ||
| 86 | + "cogul kimlik alanlari olmayan eski kayit atildi; alan eklemek geriye donuk " | ||
| 87 | + "uyumlu olmaliydi", | ||
| 88 | + ) | ||
| 89 | + | ||
| 90 | + def test_a_record_in_an_unknown_state_must_be_skipped(self) -> None: | ||
| 91 | + seed = self.make_store() | ||
| 92 | + job_id = seed.submit("gecersiz", "duz_okuma")[0]["job_id"] | ||
| 93 | + record = self.read_record(job_id) | ||
| 94 | + record["state"] = "yariyolda" | ||
| 95 | + self.write_record(job_id, record) | ||
| 96 | + | ||
| 97 | + reopened = self.make_store() | ||
| 98 | + with self.assertRaises(jobs.JobNotFound): | ||
| 99 | + reopened.get(job_id) | ||
| 100 | + | ||
| 101 | + def test_a_record_whose_identifier_does_not_match_the_file_name_must_be_skipped(self) -> None: | ||
| 102 | + seed = self.make_store() | ||
| 103 | + job_id = seed.submit("kimlik", "duz_okuma")[0]["job_id"] | ||
| 104 | + record = self.read_record(job_id) | ||
| 105 | + record["job_id"] = "BASKABIRKIMLIK00000000000" | ||
| 106 | + self.write_record(job_id, record) | ||
| 107 | + | ||
| 108 | + reopened = self.make_store() | ||
| 109 | + with self.assertRaises(jobs.JobNotFound): | ||
| 110 | + reopened.get(job_id) | ||
| 111 | + | ||
| 112 | + def test_a_record_that_is_not_json_must_not_crash_startup(self) -> None: | ||
| 113 | + self.root.mkdir(parents=True, exist_ok=True) | ||
| 114 | + with open(self.root / "01BOZUKKAYITDOSYASI000000.json", "w", encoding="utf-8") as handle: | ||
| 115 | + handle.write("{ bu json degil") | ||
| 116 | + with open(self.root / "01LISTEOLANKAYIT000000000.json", "w", encoding="utf-8") as handle: | ||
| 117 | + handle.write("[1, 2, 3]") | ||
| 118 | + store = self.make_store() | ||
| 119 | + self.assertEqual(store.swept, 0) | ||
| 120 | + | ||
| 121 | + def test_the_required_field_list_must_match_the_wire_contract(self) -> None: | ||
| 122 | + self.assertEqual( | ||
| 123 | + set(jobs.REQUIRED_FIELDS), | ||
| 124 | + { | ||
| 125 | + "job_id", | ||
| 126 | + "source_id", | ||
| 127 | + "format", | ||
| 128 | + "state", | ||
| 129 | + "stage", | ||
| 130 | + "progress", | ||
| 131 | + "error_code", | ||
| 132 | + "cancel_requested", | ||
| 133 | + "audio_id", | ||
| 134 | + "duration_secs", | ||
| 135 | + "script_id", | ||
| 136 | + "created_at", | ||
| 137 | + "updated_at", | ||
| 138 | + }, | ||
| 139 | + "zorunlu alan listesi degisti; eski kayitlarla uyum kontrol edilmeli", | ||
| 140 | + ) | ||
| 141 | + | ||
| 142 | + | ||
| 143 | +if __name__ == "__main__": | ||
| 144 | + unittest.main() | ||
tests/regress/regress_script_alignment.pyadded+103 -0
| @@ -0,0 +1,103 @@ | |||
| 1 | +import tempfile | ||
| 2 | +import unittest | ||
| 3 | +from pathlib import Path | ||
| 4 | + | ||
| 5 | +from src import config, pipeline | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +class FakeResult: | ||
| 9 | + def __init__(self, mp3: list, scripts: list, duration: float) -> None: | ||
| 10 | + self.mp3_yollari = mp3 | ||
| 11 | + self.script_yollari = scripts | ||
| 12 | + self.ses_toplam_sn = duration | ||
| 13 | + self.adimlar: list = [] | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +class ScriptAlignmentRegression(unittest.TestCase): | ||
| 17 | + def setUp(self) -> None: | ||
| 18 | + self._log_level = config._active_level | ||
| 19 | + config.set_log_level("error") | ||
| 20 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-hizalama-") | ||
| 21 | + self.root = Path(self._tmp.name) / "cikti" | ||
| 22 | + | ||
| 23 | + def tearDown(self) -> None: | ||
| 24 | + self._tmp.cleanup() | ||
| 25 | + config._active_level = self._log_level | ||
| 26 | + | ||
| 27 | + def audio(self, chapter: str, format_name: str = "duz_okuma") -> str: | ||
| 28 | + return str(self.root / "ders" / "ses" / format_name / f"ders-{chapter}.mp3") | ||
| 29 | + | ||
| 30 | + def script(self, chapter: str, format_name: str = "duz_okuma") -> str: | ||
| 31 | + return str(self.root / "ders" / "script" / format_name / f"ders-{chapter}.script.json") | ||
| 32 | + | ||
| 33 | + def output(self, mp3: list, scripts: list) -> dict: | ||
| 34 | + return pipeline.derive_outputs(FakeResult(mp3, scripts, 10.0), str(self.root)) | ||
| 35 | + | ||
| 36 | + def test_scripts_must_be_trimmed_when_the_chapter_limit_applies_only_to_audio(self) -> None: | ||
| 37 | + outputs = self.output( | ||
| 38 | + [self.audio("b01")], | ||
| 39 | + [self.script("b01"), self.script("b02"), self.script("b03")], | ||
| 40 | + ) | ||
| 41 | + self.assertEqual( | ||
| 42 | + len(outputs["script_ids"]), | ||
| 43 | + 1, | ||
| 44 | + "bolum_limiti yalnizca sese uygulanirken script_ids TUM bolumleri tasidi; " | ||
| 45 | + "sonuc ses ile script arasinda uyumsuz", | ||
| 46 | + ) | ||
| 47 | + self.assertEqual(outputs["script_ids"], ["ders/script/duz_okuma/ders-b01.script.json"]) | ||
| 48 | + | ||
| 49 | + def test_the_trimmed_script_must_belong_to_the_chapter_that_was_voiced(self) -> None: | ||
| 50 | + outputs = self.output( | ||
| 51 | + [self.audio("b02")], | ||
| 52 | + [self.script("b01"), self.script("b02"), self.script("b03")], | ||
| 53 | + ) | ||
| 54 | + self.assertEqual(outputs["script_ids"], ["ders/script/duz_okuma/ders-b02.script.json"]) | ||
| 55 | + self.assertEqual(outputs["script_id"], "ders/script/duz_okuma/ders-b02.script.json") | ||
| 56 | + | ||
| 57 | + def test_nothing_must_be_trimmed_when_the_audio_and_script_counts_are_equal(self) -> None: | ||
| 58 | + outputs = self.output( | ||
| 59 | + [self.audio("b01"), self.audio("b02")], | ||
| 60 | + [self.script("b01"), self.script("b02")], | ||
| 61 | + ) | ||
| 62 | + self.assertEqual(len(outputs["script_ids"]), 2) | ||
| 63 | + self.assertEqual(len(outputs["audio_ids"]), 2) | ||
| 64 | + | ||
| 65 | + def test_scripts_must_be_returned_unfiltered_when_nothing_matches_at_all(self) -> None: | ||
| 66 | + outputs = self.output( | ||
| 67 | + [self.audio("b01")], | ||
| 68 | + [self.script("x99"), self.script("y98")], | ||
| 69 | + ) | ||
| 70 | + self.assertEqual( | ||
| 71 | + len(outputs["script_ids"]), | ||
| 72 | + 2, | ||
| 73 | + "eslesme hic tutmadiginda scriptler tamamen silinmemeli; " | ||
| 74 | + "bos script listesi donmek veri kaybidir", | ||
| 75 | + ) | ||
| 76 | + | ||
| 77 | + def test_the_audio_identifiers_must_not_be_broken_when_there_is_no_script(self) -> None: | ||
| 78 | + outputs = self.output([self.audio("b01")], []) | ||
| 79 | + self.assertEqual(outputs["audio_ids"], ["ders/ses/duz_okuma/ders-b01.mp3"]) | ||
| 80 | + self.assertEqual(outputs["script_ids"], []) | ||
| 81 | + self.assertEqual(outputs["script_id"], "") | ||
| 82 | + | ||
| 83 | + def test_the_scripts_must_stay_untouched_when_there_is_no_audio(self) -> None: | ||
| 84 | + outputs = self.output([], [self.script("b01"), self.script("b02")]) | ||
| 85 | + self.assertEqual(len(outputs["script_ids"]), 2) | ||
| 86 | + | ||
| 87 | + def test_the_chapter_key_must_be_normalised_regardless_of_the_extension(self) -> None: | ||
| 88 | + for extension in (".script.json", ".json", ""): | ||
| 89 | + with self.subTest(extension=extension): | ||
| 90 | + self.assertEqual(pipeline._chapter_key(f"a/b/ders-b01{extension}"), "ders-b01") | ||
| 91 | + self.assertEqual(pipeline._chapter_key("a/b/ders-b01.mp3"), "ders-b01") | ||
| 92 | + | ||
| 93 | + def test_the_singular_script_id_must_be_the_first_of_the_trimmed_list(self) -> None: | ||
| 94 | + outputs = self.output( | ||
| 95 | + [self.audio("b03")], | ||
| 96 | + [self.script("b01"), self.script("b02"), self.script("b03")], | ||
| 97 | + ) | ||
| 98 | + self.assertEqual(outputs["script_id"], outputs["script_ids"][0]) | ||
| 99 | + self.assertIn("b03", outputs["script_id"]) | ||
| 100 | + | ||
| 101 | + | ||
| 102 | +if __name__ == "__main__": | ||
| 103 | + unittest.main() | ||
tests/regress/regress_secret_leak.pyadded+184 -0
| @@ -0,0 +1,184 @@ | |||
| 1 | +import os | ||
| 2 | +import tempfile | ||
| 3 | +import unittest | ||
| 4 | +from pathlib import Path | ||
| 5 | + | ||
| 6 | +from src import capabilities, config, jobs | ||
| 7 | + | ||
| 8 | +LLM_CANARY = "kanarya-deepseek-anahtari-9f3a2b" | ||
| 9 | +TOKEN_CANARY = "kanarya-paylasilan-sir-7c1e8d" | ||
| 10 | + | ||
| 11 | +SECRET_NAMES = ("DEEPSEEK_API_KEY", "AI_SHARED_TOKEN") | ||
| 12 | + | ||
| 13 | +ENV_NAMES = ( | ||
| 14 | + "LOG_LEVEL", | ||
| 15 | + "AI_SHARED_TOKEN", | ||
| 16 | + "AI_MAX_CONCURRENT", | ||
| 17 | + "AI_RECONNECT_SECS", | ||
| 18 | + "PODCAST_JOB_ROOT", | ||
| 19 | + "PODCAST_OUTPUT_ROOT", | ||
| 20 | + "PODCAST_MEDIA_ROOT", | ||
| 21 | + "PODCAST_LEDGER_DB", | ||
| 22 | + "PODCAST_MODE", | ||
| 23 | + "PODCAST_PIPELINE_PATH", | ||
| 24 | + "PODCAST_WORKERS", | ||
| 25 | + "PODCAST_MAX_JOBS", | ||
| 26 | + "PODCAST_STAGE_SECS", | ||
| 27 | + "PODCAST_ETA_SECS", | ||
| 28 | + "PODCAST_CHAPTER_LIMIT", | ||
| 29 | + "PODCAST_TTS_ENGINE", | ||
| 30 | + "DEEPSEEK_API_KEY", | ||
| 31 | +) | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +class SecretLeakRegression(unittest.TestCase): | ||
| 35 | + def setUp(self) -> None: | ||
| 36 | + self._log_level = config._active_level | ||
| 37 | + self._previous = {name: os.environ.get(name) for name in ENV_NAMES} | ||
| 38 | + for name in ENV_NAMES: | ||
| 39 | + os.environ.pop(name, None) | ||
| 40 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-sir-") | ||
| 41 | + self.root = Path(self._tmp.name) | ||
| 42 | + os.environ["LOG_LEVEL"] = "error" | ||
| 43 | + os.environ["DEEPSEEK_API_KEY"] = LLM_CANARY | ||
| 44 | + os.environ["AI_SHARED_TOKEN"] = TOKEN_CANARY | ||
| 45 | + os.environ["PODCAST_JOB_ROOT"] = str(self.root / "isler") | ||
| 46 | + os.environ["PODCAST_OUTPUT_ROOT"] = str(self.root / "cikti") | ||
| 47 | + os.environ["PODCAST_MEDIA_ROOT"] = str(self.root / "medya") | ||
| 48 | + os.environ["PODCAST_LEDGER_DB"] = str(self.root / "defter.sqlite") | ||
| 49 | + self._stores: list = [] | ||
| 50 | + | ||
| 51 | + def tearDown(self) -> None: | ||
| 52 | + capabilities.configure(None, llm_ready=False) | ||
| 53 | + for store in self._stores: | ||
| 54 | + store.shutdown(timeout=1.0) | ||
| 55 | + self._tmp.cleanup() | ||
| 56 | + for name, value in self._previous.items(): | ||
| 57 | + if value is None: | ||
| 58 | + os.environ.pop(name, None) | ||
| 59 | + else: | ||
| 60 | + os.environ[name] = value | ||
| 61 | + config._active_level = self._log_level | ||
| 62 | + | ||
| 63 | + def find_canaries(self, text: str, where: str) -> None: | ||
| 64 | + for canary in (LLM_CANARY, TOKEN_CANARY): | ||
| 65 | + self.assertNotIn( | ||
| 66 | + canary, text, f"{where} icinde sir degeri gorunuyor: {canary[:12]}..." | ||
| 67 | + ) | ||
| 68 | + | ||
| 69 | + def test_secret_values_must_not_appear_in_the_config_summary_output(self) -> None: | ||
| 70 | + settings = config.Config(require_token=True) | ||
| 71 | + self.find_canaries(settings.summary(), "Config.summary()") | ||
| 72 | + | ||
| 73 | + def test_the_config_summary_must_report_only_the_presence_of_the_secrets(self) -> None: | ||
| 74 | + settings = config.Config(require_token=True) | ||
| 75 | + summary = settings.summary() | ||
| 76 | + self.assertIn("token=tanimli", summary) | ||
| 77 | + self.assertIn("llm_anahtari=tanimli", summary) | ||
| 78 | + self.assertTrue(settings.has_token) | ||
| 79 | + self.assertTrue(settings.has_llm_key) | ||
| 80 | + | ||
| 81 | + def test_the_format_summary_gives_the_key_name_not_its_value(self) -> None: | ||
| 82 | + for llm_ready in (False, True): | ||
| 83 | + with self.subTest(llm_ready=llm_ready): | ||
| 84 | + summary = capabilities.format_summary(llm_ready) | ||
| 85 | + self.assertIn(capabilities.LLM_KEY_NAME, summary) | ||
| 86 | + self.find_canaries(summary, "capabilities.format_summary()") | ||
| 87 | + | ||
| 88 | + def test_secret_values_must_not_appear_in_the_job_json_records(self) -> None: | ||
| 89 | + settings = config.Config(require_token=True) | ||
| 90 | + store = jobs.JobStore( | ||
| 91 | + root=settings.job_root, workers=1, max_jobs=8, stage_secs=0.0 | ||
| 92 | + ) | ||
| 93 | + self._stores.append(store) | ||
| 94 | + capabilities.configure(store, llm_ready=True) | ||
| 95 | + job_id = capabilities.dispatch( | ||
| 96 | + "podcast.submit", {"source_id": "ders.pdf", "format": "tek_ogretici"} | ||
| 97 | + )["job_id"] | ||
| 98 | + store.transition(job_id, jobs.STATE_RUNNING) | ||
| 99 | + store.finish(job_id, audio_id="a/b.mp3", duration_secs=1.0, script_id="a/b.json") | ||
| 100 | + jobs.write_status(settings.job_root, True, "w1") | ||
| 101 | + | ||
| 102 | + for path in sorted(Path(settings.job_root).iterdir()): | ||
| 103 | + if not path.is_file(): | ||
| 104 | + continue | ||
| 105 | + with self.subTest(file=path.name): | ||
| 106 | + self.find_canaries( | ||
| 107 | + path.read_text(encoding="utf-8", errors="replace"), f"is kaydi {path.name}" | ||
| 108 | + ) | ||
| 109 | + | ||
| 110 | + def test_secret_values_must_not_appear_in_exception_texts(self) -> None: | ||
| 111 | + broken_settings = ( | ||
| 112 | + ("PODCAST_WORKERS", "yedi"), | ||
| 113 | + ("PODCAST_WORKERS", "9999"), | ||
| 114 | + ("PODCAST_MAX_JOBS", "sifir"), | ||
| 115 | + ("PODCAST_STAGE_SECS", "yavas"), | ||
| 116 | + ("PODCAST_ETA_SECS", "-5"), | ||
| 117 | + ("AI_MAX_CONCURRENT", "999"), | ||
| 118 | + ("AI_RECONNECT_SECS", "hemen"), | ||
| 119 | + ("PODCAST_MODE", "yari-gercek"), | ||
| 120 | + ("LOG_LEVEL", "gurultu"), | ||
| 121 | + ("PODCAST_CHAPTER_LIMIT", "cok"), | ||
| 122 | + ) | ||
| 123 | + for name, value in broken_settings: | ||
| 124 | + with self.subTest(variable=name, value=value): | ||
| 125 | + previous = os.environ.get(name) | ||
| 126 | + os.environ[name] = value | ||
| 127 | + try: | ||
| 128 | + with self.assertRaises(config.ConfigError) as raised: | ||
| 129 | + config.Config(require_token=True) | ||
| 130 | + self.find_canaries(str(raised.exception), f"{name} istisnasi") | ||
| 131 | + finally: | ||
| 132 | + if previous is None: | ||
| 133 | + os.environ.pop(name, None) | ||
| 134 | + else: | ||
| 135 | + os.environ[name] = previous | ||
| 136 | + | ||
| 137 | + def test_env_str_must_not_put_the_raw_value_into_any_error_message(self) -> None: | ||
| 138 | + os.environ["PODCAST_TTS_ENGINE"] = LLM_CANARY | ||
| 139 | + self.assertEqual(config.env_str("PODCAST_TTS_ENGINE", "supertonic-3"), LLM_CANARY) | ||
| 140 | + os.environ["PODCAST_WORKERS"] = "yedi" | ||
| 141 | + try: | ||
| 142 | + with self.assertRaises(config.ConfigError) as raised: | ||
| 143 | + config.Config(require_token=True) | ||
| 144 | + finally: | ||
| 145 | + os.environ.pop("PODCAST_WORKERS", None) | ||
| 146 | + os.environ.pop("PODCAST_TTS_ENGINE", None) | ||
| 147 | + self.assertNotIn( | ||
| 148 | + LLM_CANARY, | ||
| 149 | + str(raised.exception), | ||
| 150 | + "env_str ile okunan bir degerin ham hali hata mesajina sizdi", | ||
| 151 | + ) | ||
| 152 | + | ||
| 153 | + def test_the_missing_token_error_must_not_carry_a_secret_either(self) -> None: | ||
| 154 | + os.environ.pop("AI_SHARED_TOKEN", None) | ||
| 155 | + with self.assertRaises(config.ConfigError) as raised: | ||
| 156 | + config.Config(require_token=True) | ||
| 157 | + self.find_canaries(str(raised.exception), "eksik token istisnasi") | ||
| 158 | + | ||
| 159 | + def test_the_config_object_must_not_store_the_secrets_as_fields(self) -> None: | ||
| 160 | + settings = config.Config(require_token=True) | ||
| 161 | + for field, value in vars(settings).items(): | ||
| 162 | + if field == "token": | ||
| 163 | + continue | ||
| 164 | + with self.subTest(field=field): | ||
| 165 | + self.assertNotIn( | ||
| 166 | + LLM_CANARY, | ||
| 167 | + str(value), | ||
| 168 | + f"Config.{field} LLM anahtarinin degerini tasiyor", | ||
| 169 | + ) | ||
| 170 | + self.assertFalse( | ||
| 171 | + hasattr(settings, "llm_key"), | ||
| 172 | + "Config LLM anahtarinin degerini saklamamali; yalnizca has_llm_key tutulur", | ||
| 173 | + ) | ||
| 174 | + | ||
| 175 | + def test_the_bridge_status_file_must_not_carry_a_secret(self) -> None: | ||
| 176 | + settings = config.Config(require_token=True) | ||
| 177 | + Path(settings.job_root).mkdir(parents=True, exist_ok=True) | ||
| 178 | + jobs.write_status(settings.job_root, True, "w1") | ||
| 179 | + text = jobs.status_path(settings.job_root).read_text(encoding="utf-8") | ||
| 180 | + self.find_canaries(text, "kopru durum dosyasi") | ||
| 181 | + | ||
| 182 | + | ||
| 183 | +if __name__ == "__main__": | ||
| 184 | + unittest.main() | ||
tests/regress/regress_tmp_residue.pyadded+154 -0
| @@ -0,0 +1,154 @@ | |||
| 1 | +import json | ||
| 2 | +import os | ||
| 3 | +import tempfile | ||
| 4 | +import unittest | ||
| 5 | +from pathlib import Path | ||
| 6 | + | ||
| 7 | +from src import config, jobs | ||
| 8 | + | ||
| 9 | + | ||
| 10 | +class TempFileRecorder: | ||
| 11 | + def __init__(self) -> None: | ||
| 12 | + self.sources: list = [] | ||
| 13 | + self._real = os.replace | ||
| 14 | + | ||
| 15 | + def __enter__(self) -> "TempFileRecorder": | ||
| 16 | + def record_it(src, dst, *args, **kwargs): | ||
| 17 | + self.sources.append(os.path.basename(str(src))) | ||
| 18 | + return self._real(src, dst, *args, **kwargs) | ||
| 19 | + | ||
| 20 | + os.replace = record_it | ||
| 21 | + return self | ||
| 22 | + | ||
| 23 | + def __exit__(self, *exc) -> None: | ||
| 24 | + os.replace = self._real | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +class TmpResidueRegression(unittest.TestCase): | ||
| 28 | + def setUp(self) -> None: | ||
| 29 | + self._log_level = config._active_level | ||
| 30 | + config.set_log_level("error") | ||
| 31 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-artik-") | ||
| 32 | + self.root = Path(self._tmp.name) / "isler" | ||
| 33 | + self._stores: list = [] | ||
| 34 | + | ||
| 35 | + def tearDown(self) -> None: | ||
| 36 | + for store in self._stores: | ||
| 37 | + store.shutdown(timeout=1.0) | ||
| 38 | + self._tmp.cleanup() | ||
| 39 | + config._active_level = self._log_level | ||
| 40 | + | ||
| 41 | + def make_store(self) -> jobs.JobStore: | ||
| 42 | + store = jobs.JobStore(root=self.root, workers=1, max_jobs=8, stage_secs=0.0) | ||
| 43 | + self._stores.append(store) | ||
| 44 | + return store | ||
| 45 | + | ||
| 46 | + def test_the_temp_file_name_must_contain_the_pid(self) -> None: | ||
| 47 | + store = self.make_store() | ||
| 48 | + with TempFileRecorder() as recorder: | ||
| 49 | + store.submit("kaynak", "duz_okuma") | ||
| 50 | + jobs.write_status(self.root, True, "w1") | ||
| 51 | + self.assertTrue(recorder.sources, "atomik yazma os.replace kullanmiyor") | ||
| 52 | + for name in recorder.sources: | ||
| 53 | + with self.subTest(temp=name): | ||
| 54 | + self.assertIn( | ||
| 55 | + f".tmp{os.getpid()}", | ||
| 56 | + name, | ||
| 57 | + "gecici dosya adi pid icermiyor; iki surec ayni gecici dosyayi ezer", | ||
| 58 | + ) | ||
| 59 | + | ||
| 60 | + def test_atomic_writing_must_be_done_with_a_temp_file_plus_replace(self) -> None: | ||
| 61 | + store = self.make_store() | ||
| 62 | + with TempFileRecorder() as recorder: | ||
| 63 | + job_id = store.submit("kaynak", "duz_okuma")[0]["job_id"] | ||
| 64 | + self.assertIn( | ||
| 65 | + f"{job_id}.json.tmp{os.getpid()}", | ||
| 66 | + "".join(recorder.sources), | ||
| 67 | + "is kaydi gecici dosya uzerinden yazilmadi", | ||
| 68 | + ) | ||
| 69 | + with open(self.root / f"{job_id}.json", "r", encoding="utf-8") as handle: | ||
| 70 | + self.assertEqual(json.load(handle)["job_id"], job_id) | ||
| 71 | + | ||
| 72 | + def test_no_residue_must_remain_after_a_normal_write(self) -> None: | ||
| 73 | + store = self.make_store() | ||
| 74 | + store.submit("kaynak", "duz_okuma") | ||
| 75 | + jobs.write_status(self.root, True, "w1") | ||
| 76 | + residues = [name for name in os.listdir(self.root) if ".tmp" in name] | ||
| 77 | + self.assertEqual(residues, [], f"atomik yazmadan gecici dosya kaldi: {residues}") | ||
| 78 | + | ||
| 79 | + def test_temp_file_residues_must_be_cleaned_up_at_startup(self) -> None: | ||
| 80 | + self.root.mkdir(parents=True, exist_ok=True) | ||
| 81 | + residues = [ | ||
| 82 | + self.root / "01ESKIISKAYDI000000000000.json.tmp999-dead", | ||
| 83 | + self.root / "01ESKIISKAYDI000000000000.json.tmp12345-beef", | ||
| 84 | + self.root / f"{jobs.STATUS_FILE}.tmp999-dead", | ||
| 85 | + ] | ||
| 86 | + for path in residues: | ||
| 87 | + path.write_text("{}", encoding="ascii") | ||
| 88 | + self.make_store() | ||
| 89 | + for path in residues: | ||
| 90 | + with self.subTest(residue=path.name): | ||
| 91 | + self.assertFalse( | ||
| 92 | + path.exists(), f"acilista gecici dosya artigi temizlenmedi: {path.name}" | ||
| 93 | + ) | ||
| 94 | + | ||
| 95 | + def test_the_cleanup_must_not_delete_real_job_records(self) -> None: | ||
| 96 | + seed = self.make_store() | ||
| 97 | + job_id = seed.submit("saglam", "duz_okuma")[0]["job_id"] | ||
| 98 | + jobs.write_status(self.root, True, "w1") | ||
| 99 | + (self.root / "01ESKIISKAYDI000000000000.json.tmp999-dead").write_text("{}", encoding="ascii") | ||
| 100 | + | ||
| 101 | + reopened = self.make_store() | ||
| 102 | + self.assertTrue( | ||
| 103 | + (self.root / f"{job_id}.json").is_file(), | ||
| 104 | + "temizleme filtresi gercekten uygulanmiyor; is kaydi silindi", | ||
| 105 | + ) | ||
| 106 | + self.assertEqual(reopened.get(job_id)["state"], jobs.STATE_QUEUED) | ||
| 107 | + self.assertIsNotNone( | ||
| 108 | + jobs.read_status(self.root), "temizleme kopru durum dosyasini sildi" | ||
| 109 | + ) | ||
| 110 | + | ||
| 111 | + def test_the_cleanup_must_not_delete_unrelated_files(self) -> None: | ||
| 112 | + self.root.mkdir(parents=True, exist_ok=True) | ||
| 113 | + preserved = [ | ||
| 114 | + self.root / "notlar.txt", | ||
| 115 | + self.root / "arsiv.json.gz", | ||
| 116 | + self.root / "tmpnot.txt", | ||
| 117 | + self.root / "OKU.md", | ||
| 118 | + ] | ||
| 119 | + for path in preserved: | ||
| 120 | + path.write_text("veri", encoding="ascii") | ||
| 121 | + (self.root / "01ESKIISKAYDI000000000000.json.tmp999-dead").write_text("{}", encoding="ascii") | ||
| 122 | + | ||
| 123 | + self.make_store() | ||
| 124 | + for path in preserved: | ||
| 125 | + with self.subTest(file=path.name): | ||
| 126 | + self.assertTrue( | ||
| 127 | + path.is_file(), | ||
| 128 | + f"temizleme filtre disindaki dosyayi sildi: {path.name}", | ||
| 129 | + ) | ||
| 130 | + | ||
| 131 | + def test_the_cleanup_must_not_touch_child_directories(self) -> None: | ||
| 132 | + self.root.mkdir(parents=True, exist_ok=True) | ||
| 133 | + child = self.root / "arsiv" | ||
| 134 | + child.mkdir(parents=True, exist_ok=True) | ||
| 135 | + (child / "eski.json").write_text("{}", encoding="ascii") | ||
| 136 | + self.make_store() | ||
| 137 | + self.assertTrue((child / "eski.json").is_file(), "temizleme alt dizini bosaltti") | ||
| 138 | + | ||
| 139 | + def test_a_half_written_temp_file_must_not_be_loaded_as_a_record(self) -> None: | ||
| 140 | + seed = self.make_store() | ||
| 141 | + job_id = seed.submit("saglam", "duz_okuma")[0]["job_id"] | ||
| 142 | + (self.root / f"{job_id}.json.tmp999-dead").write_text( | ||
| 143 | + json.dumps({"job_id": job_id, "state": "done"}), encoding="ascii" | ||
| 144 | + ) | ||
| 145 | + reopened = self.make_store() | ||
| 146 | + self.assertEqual( | ||
| 147 | + reopened.get(job_id)["state"], | ||
| 148 | + jobs.STATE_QUEUED, | ||
| 149 | + "yarim yazilmis gecici dosya gercek kaydin uzerine yuklendi", | ||
| 150 | + ) | ||
| 151 | + | ||
| 152 | + | ||
| 153 | +if __name__ == "__main__": | ||
| 154 | + unittest.main() | ||
tests/regress/regress_tool_arguments.pyadded+75 -0
| @@ -0,0 +1,75 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import ast | ||
| 4 | +import io | ||
| 5 | +import pathlib | ||
| 6 | +import unittest | ||
| 7 | + | ||
| 8 | +TOOLS = sorted(pathlib.Path("tools").glob("*.py")) | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +def _declared_dests(tree: ast.AST) -> set[str]: | ||
| 12 | + dests: set[str] = set() | ||
| 13 | + for node in ast.walk(tree): | ||
| 14 | + if not isinstance(node, ast.Call): | ||
| 15 | + continue | ||
| 16 | + func = node.func | ||
| 17 | + if not (isinstance(func, ast.Attribute) and func.attr == "add_argument"): | ||
| 18 | + continue | ||
| 19 | + explicit = None | ||
| 20 | + for keyword in node.keywords: | ||
| 21 | + if keyword.arg == "dest" and isinstance(keyword.value, ast.Constant): | ||
| 22 | + explicit = str(keyword.value.value) | ||
| 23 | + if explicit is not None: | ||
| 24 | + dests.add(explicit) | ||
| 25 | + continue | ||
| 26 | + for arg in node.args: | ||
| 27 | + if not isinstance(arg, ast.Constant) or not isinstance(arg.value, str): | ||
| 28 | + continue | ||
| 29 | + name = arg.value | ||
| 30 | + if name.startswith("--"): | ||
| 31 | + dests.add(name[2:].replace("-", "_")) | ||
| 32 | + elif not name.startswith("-"): | ||
| 33 | + dests.add(name.replace("-", "_")) | ||
| 34 | + return dests | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +def _accessed_names(tree: ast.AST) -> set[str]: | ||
| 38 | + used: set[str] = set() | ||
| 39 | + for node in ast.walk(tree): | ||
| 40 | + if ( | ||
| 41 | + isinstance(node, ast.Attribute) | ||
| 42 | + and isinstance(node.value, ast.Name) | ||
| 43 | + and node.value.id == "args" | ||
| 44 | + ): | ||
| 45 | + used.add(node.attr) | ||
| 46 | + return used | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +class ToolArgumentsMatchTheirParser(unittest.TestCase): | ||
| 50 | + def test_every_args_attribute_has_a_declared_argument(self): | ||
| 51 | + self.assertTrue(TOOLS, "tools/*.py bulunamadi") | ||
| 52 | + for path in TOOLS: | ||
| 53 | + with self.subTest(tool=path.name): | ||
| 54 | + tree = ast.parse(io.open(path, encoding="utf-8").read()) | ||
| 55 | + orphan = sorted(_accessed_names(tree) - _declared_dests(tree)) | ||
| 56 | + self.assertEqual( | ||
| 57 | + orphan, | ||
| 58 | + [], | ||
| 59 | + f"{path.name}: parser'da tanimli OLMAYAN args ozniteligi " | ||
| 60 | + f"{orphan}. Bayrak yeniden adlandirilip atif guncellenmemis " | ||
| 61 | + f"olabilir; bu sinif hicbir testte gorunmez, yalnizca araci " | ||
| 62 | + f"gercekten kosturunca AttributeError verir.", | ||
| 63 | + ) | ||
| 64 | + | ||
| 65 | + def test_declared_arguments_are_ascii_and_lowercase(self): | ||
| 66 | + for path in TOOLS: | ||
| 67 | + tree = ast.parse(io.open(path, encoding="utf-8").read()) | ||
| 68 | + for dest in sorted(_declared_dests(tree)): | ||
| 69 | + with self.subTest(tool=path.name, dest=dest): | ||
| 70 | + self.assertTrue(dest.isascii(), f"ASCII disi arguman: {dest}") | ||
| 71 | + self.assertEqual(dest, dest.lower()) | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +if __name__ == "__main__": | ||
| 75 | + unittest.main() | ||
tests/regress/regress_unanswered_stream.pyadded+206 -0
| @@ -0,0 +1,206 @@ | |||
| 1 | +import asyncio | ||
| 2 | +import json | ||
| 3 | +import struct | ||
| 4 | +import sys | ||
| 5 | +import types | ||
| 6 | +import unittest | ||
| 7 | + | ||
| 8 | +from src import config, protocol | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +def install_fake_aioquic() -> None: | ||
| 12 | + if "aioquic" in sys.modules: | ||
| 13 | + return | ||
| 14 | + try: | ||
| 15 | + import aioquic | ||
| 16 | + return | ||
| 17 | + except ImportError: | ||
| 18 | + pass | ||
| 19 | + | ||
| 20 | + class QuicConnectionProtocol: | ||
| 21 | + def __init__(self, *args, **kwargs) -> None: | ||
| 22 | + pass | ||
| 23 | + | ||
| 24 | + def transmit(self) -> None: | ||
| 25 | + pass | ||
| 26 | + | ||
| 27 | + class QuicConfiguration: | ||
| 28 | + def __init__(self, *args, **kwargs) -> None: | ||
| 29 | + pass | ||
| 30 | + | ||
| 31 | + class QuicEvent: | ||
| 32 | + pass | ||
| 33 | + | ||
| 34 | + class StreamDataReceived(QuicEvent): | ||
| 35 | + pass | ||
| 36 | + | ||
| 37 | + class ConnectionTerminated(QuicEvent): | ||
| 38 | + pass | ||
| 39 | + | ||
| 40 | + def connect(*args, **kwargs): | ||
| 41 | + raise RuntimeError("kukla aioquic ag acmaz") | ||
| 42 | + | ||
| 43 | + root = types.ModuleType("aioquic") | ||
| 44 | + asyncio_module = types.ModuleType("aioquic.asyncio") | ||
| 45 | + protocol_module = types.ModuleType("aioquic.asyncio.protocol") | ||
| 46 | + quic_module = types.ModuleType("aioquic.quic") | ||
| 47 | + configuration_module = types.ModuleType("aioquic.quic.configuration") | ||
| 48 | + events_module = types.ModuleType("aioquic.quic.events") | ||
| 49 | + | ||
| 50 | + asyncio_module.connect = connect | ||
| 51 | + protocol_module.QuicConnectionProtocol = QuicConnectionProtocol | ||
| 52 | + configuration_module.QuicConfiguration = QuicConfiguration | ||
| 53 | + events_module.QuicEvent = QuicEvent | ||
| 54 | + events_module.StreamDataReceived = StreamDataReceived | ||
| 55 | + events_module.ConnectionTerminated = ConnectionTerminated | ||
| 56 | + asyncio_module.protocol = protocol_module | ||
| 57 | + quic_module.configuration = configuration_module | ||
| 58 | + quic_module.events = events_module | ||
| 59 | + root.asyncio = asyncio_module | ||
| 60 | + root.quic = quic_module | ||
| 61 | + | ||
| 62 | + sys.modules["aioquic"] = root | ||
| 63 | + sys.modules["aioquic.asyncio"] = asyncio_module | ||
| 64 | + sys.modules["aioquic.asyncio.protocol"] = protocol_module | ||
| 65 | + sys.modules["aioquic.quic"] = quic_module | ||
| 66 | + sys.modules["aioquic.quic.configuration"] = configuration_module | ||
| 67 | + sys.modules["aioquic.quic.events"] = events_module | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +class FakeQuic: | ||
| 71 | + def __init__(self) -> None: | ||
| 72 | + self.written: list = [] | ||
| 73 | + | ||
| 74 | + def send_stream_data(self, sid: int, data: bytes, end_stream: bool) -> None: | ||
| 75 | + self.written.append((sid, data, end_stream)) | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +class FakeSettings: | ||
| 79 | + max_concurrent = 4 | ||
| 80 | + service = "podcast" | ||
| 81 | + token = "sir" | ||
| 82 | + job_root = "" | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +def decode_frame(data: bytes) -> dict: | ||
| 86 | + (length,) = struct.unpack(">I", data[:4]) | ||
| 87 | + return json.loads(data[4 : 4 + length].decode("utf-8")) | ||
| 88 | + | ||
| 89 | + | ||
| 90 | +class UnansweredStreamRegression(unittest.TestCase): | ||
| 91 | + @classmethod | ||
| 92 | + def setUpClass(cls) -> None: | ||
| 93 | + install_fake_aioquic() | ||
| 94 | + from src import bridge | ||
| 95 | + | ||
| 96 | + cls.bridge = bridge | ||
| 97 | + | ||
| 98 | + def setUp(self) -> None: | ||
| 99 | + self._log_level = config._active_level | ||
| 100 | + config.set_log_level("error") | ||
| 101 | + self.quic = FakeQuic() | ||
| 102 | + self.proto = self.bridge.BridgeProtocol(settings=FakeSettings()) | ||
| 103 | + self.proto._quic = self.quic | ||
| 104 | + | ||
| 105 | + def tearDown(self) -> None: | ||
| 106 | + config._active_level = self._log_level | ||
| 107 | + | ||
| 108 | + def run_request(self, body: object, sid: int = 1) -> None: | ||
| 109 | + stream = protocol.FrameStream() | ||
| 110 | + stream.feed(protocol.encode_frame(body), end=True) | ||
| 111 | + self.proto._streams[sid] = stream | ||
| 112 | + asyncio.run(self.proto._serve_request(sid, stream)) | ||
| 113 | + | ||
| 114 | + def test_unparseable_request_is_answered_with_bad_request_not_left_hanging(self) -> None: | ||
| 115 | + for body in ([1, 2], "istek", {}, {"capability": "podcast.status"}, {"id": 7}): | ||
| 116 | + with self.subTest(body=body): | ||
| 117 | + self.quic.written.clear() | ||
| 118 | + self.proto._streams.clear() | ||
| 119 | + self.run_request(body) | ||
| 120 | + self.assertEqual( | ||
| 121 | + len(self.quic.written), | ||
| 122 | + 1, | ||
| 123 | + "ayristirilamayan istek cevapsiz birakildi; backend deadline boyunca " | ||
| 124 | + "bekler ve worker kiralamasini tutar", | ||
| 125 | + ) | ||
| 126 | + sid, data, end = self.quic.written[0] | ||
| 127 | + response = decode_frame(data) | ||
| 128 | + self.assertEqual(response["status"], "err") | ||
| 129 | + self.assertEqual(response["code"], "bad_request") | ||
| 130 | + self.assertTrue(end, "cevap yazildiktan sonra akis kapatilmali") | ||
| 131 | + | ||
| 132 | + def test_request_identifier_is_preserved_on_an_unparseable_request(self) -> None: | ||
| 133 | + self.run_request({"id": "r-42", "capability": 7}) | ||
| 134 | + response = decode_frame(self.quic.written[0][1]) | ||
| 135 | + self.assertEqual( | ||
| 136 | + response["id"], "r-42", "hata cevabi istegin kimligini kaybetmemeli" | ||
| 137 | + ) | ||
| 138 | + | ||
| 139 | + def test_answered_stream_is_dropped_from_the_registry(self) -> None: | ||
| 140 | + self.run_request({"id": "r-1", "capability": 7}, sid=5) | ||
| 141 | + self.assertNotIn( | ||
| 142 | + 5, self.proto._streams, "cevaplanan akis kaydi sizdirilmamali" | ||
| 143 | + ) | ||
| 144 | + | ||
| 145 | + def test_closed_stream_leaks_no_registry_entry_even_when_left_unanswered(self) -> None: | ||
| 146 | + stream = protocol.FrameStream() | ||
| 147 | + stream.feed(b"", end=True) | ||
| 148 | + self.proto._streams[9] = stream | ||
| 149 | + asyncio.run(self.proto._serve_request(9, stream)) | ||
| 150 | + self.assertEqual( | ||
| 151 | + self.quic.written, [], "karsi taraf akisi kapattiysa cevap yazilamaz" | ||
| 152 | + ) | ||
| 153 | + self.assertNotIn(9, self.proto._streams) | ||
| 154 | + | ||
| 155 | + def test_response_over_eight_mib_returns_frame_too_large_instead_of_being_silently_swallowed(self) -> None: | ||
| 156 | + huge = protocol.ok_response( | ||
| 157 | + "r-9", {"payload": "a" * (protocol.MAX_FRAME_BYTES + 16)} | ||
| 158 | + ) | ||
| 159 | + self.proto._streams[3] = protocol.FrameStream() | ||
| 160 | + self.proto._finish(3, "r-9", huge) | ||
| 161 | + self.assertEqual( | ||
| 162 | + len(self.quic.written), | ||
| 163 | + 1, | ||
| 164 | + "cerceve sinirini asan cevap sessizce yutulmamali; hata cevabi yazilmali", | ||
| 165 | + ) | ||
| 166 | + response = decode_frame(self.quic.written[0][1]) | ||
| 167 | + self.assertEqual(response["status"], "err") | ||
| 168 | + self.assertEqual( | ||
| 169 | + response["code"], | ||
| 170 | + "frame_too_large", | ||
| 171 | + "buyuk cevap 'frame_too_large' err'ine dusurulmeli", | ||
| 172 | + ) | ||
| 173 | + self.assertEqual(response["id"], "r-9") | ||
| 174 | + self.assertTrue(self.quic.written[0][2]) | ||
| 175 | + self.assertNotIn(3, self.proto._streams) | ||
| 176 | + | ||
| 177 | + def test_response_under_the_limit_is_sent_as_is(self) -> None: | ||
| 178 | + response = protocol.ok_response("r-8", {"job_id": "J"}) | ||
| 179 | + self.proto._streams[7] = protocol.FrameStream() | ||
| 180 | + self.proto._finish(7, "r-8", response) | ||
| 181 | + self.assertEqual(decode_frame(self.quic.written[0][1]), response) | ||
| 182 | + | ||
| 183 | + def test_huge_payload_produced_by_a_capability_also_returns_frame_too_large(self) -> None: | ||
| 184 | + from src import capabilities | ||
| 185 | + | ||
| 186 | + def huge_capability(payload: dict) -> dict: | ||
| 187 | + return {"payload": "a" * (protocol.MAX_FRAME_BYTES + 16)} | ||
| 188 | + | ||
| 189 | + capabilities.REGISTRY["podcast.devasa"] = huge_capability | ||
| 190 | + try: | ||
| 191 | + self.run_request({"id": "r-7", "capability": "podcast.devasa", "payload": {}}) | ||
| 192 | + finally: | ||
| 193 | + capabilities.REGISTRY.pop("podcast.devasa", None) | ||
| 194 | + self.assertEqual(len(self.quic.written), 1) | ||
| 195 | + response = decode_frame(self.quic.written[0][1]) | ||
| 196 | + self.assertEqual(response["code"], "frame_too_large") | ||
| 197 | + | ||
| 198 | + def test_busy_is_returned_at_the_concurrent_request_ceiling_without_hanging_the_stream(self) -> None: | ||
| 199 | + self.proto._inflight = FakeSettings.max_concurrent | ||
| 200 | + self.run_request({"id": "r-6", "capability": "podcast.status", "payload": {}}) | ||
| 201 | + response = decode_frame(self.quic.written[0][1]) | ||
| 202 | + self.assertEqual(response["code"], "busy") | ||
| 203 | + | ||
| 204 | + | ||
| 205 | +if __name__ == "__main__": | ||
| 206 | + unittest.main() | ||
tests/regress/regress_unreachable_guard.pyadded+138 -0
| @@ -0,0 +1,138 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import ast | ||
| 4 | +import io | ||
| 5 | +import sys | ||
| 6 | +import tempfile | ||
| 7 | +import unittest | ||
| 8 | +from pathlib import Path | ||
| 9 | + | ||
| 10 | +sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) | ||
| 11 | + | ||
| 12 | +from src import config, jobs | ||
| 13 | + | ||
| 14 | +SOURCE = Path(__file__).resolve().parent.parent.parent / "src" / "jobs.py" | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +def _is_false(node: ast.AST) -> bool: | ||
| 18 | + return isinstance(node, ast.Constant) and node.value is False | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +def _flag_writers() -> set[str]: | ||
| 22 | + tree = ast.parse(io.open(SOURCE, encoding="utf-8").read()) | ||
| 23 | + owners = set() | ||
| 24 | + for node in ast.walk(tree): | ||
| 25 | + if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): | ||
| 26 | + continue | ||
| 27 | + for inner in ast.walk(node): | ||
| 28 | + written = False | ||
| 29 | + if isinstance(inner, ast.Assign) and not _is_false(inner.value): | ||
| 30 | + for target in inner.targets: | ||
| 31 | + if ( | ||
| 32 | + isinstance(target, ast.Subscript) | ||
| 33 | + and isinstance(target.slice, ast.Constant) | ||
| 34 | + and target.slice.value == "cancel_requested" | ||
| 35 | + ): | ||
| 36 | + written = True | ||
| 37 | + if isinstance(inner, ast.Call): | ||
| 38 | + for keyword in inner.keywords: | ||
| 39 | + if keyword.arg == "cancel_requested" and not _is_false( | ||
| 40 | + keyword.value | ||
| 41 | + ): | ||
| 42 | + written = True | ||
| 43 | + if isinstance(inner, ast.Dict): | ||
| 44 | + for key, value in zip(inner.keys, inner.values): | ||
| 45 | + if ( | ||
| 46 | + isinstance(key, ast.Constant) | ||
| 47 | + and key.value == "cancel_requested" | ||
| 48 | + and not _is_false(value) | ||
| 49 | + ): | ||
| 50 | + written = True | ||
| 51 | + if written: | ||
| 52 | + owners.add(node.name) | ||
| 53 | + return owners | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +class CancelFlagOnQueuedIsUnreachable(unittest.TestCase): | ||
| 57 | + def setUp(self) -> None: | ||
| 58 | + self._log_level = config._active_level | ||
| 59 | + config.set_log_level("error") | ||
| 60 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-guard-") | ||
| 61 | + self.store = jobs.JobStore( | ||
| 62 | + root=Path(self._tmp.name) / "isler", workers=1, max_jobs=64, stage_secs=0.0 | ||
| 63 | + ) | ||
| 64 | + | ||
| 65 | + def tearDown(self) -> None: | ||
| 66 | + self.store.shutdown(timeout=1.0) | ||
| 67 | + self._tmp.cleanup() | ||
| 68 | + config._active_level = self._log_level | ||
| 69 | + | ||
| 70 | + def test_only_cancel_and_shutdown_may_raise_the_cancel_flag(self) -> None: | ||
| 71 | + self.assertEqual( | ||
| 72 | + _flag_writers(), | ||
| 73 | + {"cancel", "shutdown"}, | ||
| 74 | + "cancel_requested bayragini yazan yeni bir fonksiyon eklenmis; " | ||
| 75 | + "JobStore.begin icindeki kuyruk korumasi artik olu kod olmayabilir, " | ||
| 76 | + "tests/model/test_model_jobstore.py modelini gozden gecir", | ||
| 77 | + ) | ||
| 78 | + | ||
| 79 | + def test_cancelling_a_queued_job_leaves_it_cancelled_not_queued(self) -> None: | ||
| 80 | + record, _ = self.store.submit("01SOURCE", "duz_okuma") | ||
| 81 | + job_id = record["job_id"] | ||
| 82 | + self.assertTrue(self.store.cancel(job_id)) | ||
| 83 | + after = self.store.get(job_id) | ||
| 84 | + self.assertEqual(after["state"], jobs.STATE_CANCELLED) | ||
| 85 | + self.assertTrue(after["cancel_requested"]) | ||
| 86 | + | ||
| 87 | + def test_shutdown_only_flags_running_jobs(self) -> None: | ||
| 88 | + queued, _ = self.store.submit("01SOURCE", "duz_okuma") | ||
| 89 | + self.store.shutdown(timeout=1.0) | ||
| 90 | + after = self.store.get(queued["job_id"]) | ||
| 91 | + self.assertEqual(after["state"], jobs.STATE_QUEUED) | ||
| 92 | + self.assertFalse( | ||
| 93 | + after["cancel_requested"], | ||
| 94 | + "shutdown kuyruktaki ise iptal bayragi koydu; begin korumasi canlandi", | ||
| 95 | + ) | ||
| 96 | + | ||
| 97 | + STEPS = { | ||
| 98 | + "begin": jobs.STATE_RUNNING, | ||
| 99 | + "cancel": jobs.STATE_CANCELLED, | ||
| 100 | + "fail": jobs.STATE_FAILED, | ||
| 101 | + "shutdown": jobs.STATE_QUEUED, | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + def test_no_public_sequence_produces_a_queued_job_with_the_flag(self) -> None: | ||
| 105 | + for step, expected_state in self.STEPS.items(): | ||
| 106 | + with self.subTest(step=step): | ||
| 107 | + store = jobs.JobStore( | ||
| 108 | + root=Path(self._tmp.name) / step, workers=1, | ||
| 109 | + max_jobs=64, stage_secs=0.0, | ||
| 110 | + ) | ||
| 111 | + try: | ||
| 112 | + record, _ = store.submit("01SOURCE", "duz_okuma") | ||
| 113 | + job_id = record["job_id"] | ||
| 114 | + if step == "begin": | ||
| 115 | + store.begin(job_id) | ||
| 116 | + elif step == "cancel": | ||
| 117 | + store.cancel(job_id) | ||
| 118 | + elif step == "fail": | ||
| 119 | + store.fail(job_id, "test") | ||
| 120 | + else: | ||
| 121 | + store.shutdown(timeout=1.0) | ||
| 122 | + after = store.get(job_id) | ||
| 123 | + self.assertEqual( | ||
| 124 | + after["state"], expected_state, | ||
| 125 | + "%s adimi beklenen duruma goturmedi" % step, | ||
| 126 | + ) | ||
| 127 | + self.assertFalse( | ||
| 128 | + after["state"] == jobs.STATE_QUEUED | ||
| 129 | + and after["cancel_requested"], | ||
| 130 | + "queued + cancel_requested durumu uretildi; " | ||
| 131 | + "begin icindeki koruma artik olu kod degil", | ||
| 132 | + ) | ||
| 133 | + finally: | ||
| 134 | + store.shutdown(timeout=1.0) | ||
| 135 | + | ||
| 136 | + | ||
| 137 | +if __name__ == "__main__": | ||
| 138 | + unittest.main() | ||
tests/unit/__init__.pyadded+0 -0
tests/unit/test_capabilities.pyadded+207 -0
| @@ -0,0 +1,207 @@ | |||
| 1 | +import tempfile | ||
| 2 | +import unittest | ||
| 3 | +from pathlib import Path | ||
| 4 | + | ||
| 5 | +from src import capabilities, config, jobs | ||
| 6 | +from src.protocol import CapabilityError | ||
| 7 | + | ||
| 8 | + | ||
| 9 | +class CapabilityTestCase(unittest.TestCase): | ||
| 10 | + def setUp(self) -> None: | ||
| 11 | + self._log_level = config._active_level | ||
| 12 | + config.set_log_level("error") | ||
| 13 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-yetenek-") | ||
| 14 | + self.root = Path(self._tmp.name) | ||
| 15 | + self.store = jobs.JobStore( | ||
| 16 | + root=self.root / "isler", workers=1, max_jobs=8, stage_secs=0.0 | ||
| 17 | + ) | ||
| 18 | + capabilities.configure(self.store, llm_ready=False) | ||
| 19 | + | ||
| 20 | + def tearDown(self) -> None: | ||
| 21 | + capabilities.configure(None, llm_ready=False) | ||
| 22 | + self.store.shutdown(timeout=1.0) | ||
| 23 | + self._tmp.cleanup() | ||
| 24 | + config._active_level = self._log_level | ||
| 25 | + | ||
| 26 | + def error_code(self, capability: str, payload: dict) -> str: | ||
| 27 | + with self.assertRaises(CapabilityError) as raised: | ||
| 28 | + capabilities.dispatch(capability, payload) | ||
| 29 | + return raised.exception.code | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +class RegistryTests(CapabilityTestCase): | ||
| 33 | + def test_registry_holds_exactly_the_four_wire_capabilities(self) -> None: | ||
| 34 | + self.assertEqual( | ||
| 35 | + capabilities.names(), | ||
| 36 | + ["podcast.cancel", "podcast.result", "podcast.status", "podcast.submit"], | ||
| 37 | + ) | ||
| 38 | + | ||
| 39 | + def test_every_handler_is_callable(self) -> None: | ||
| 40 | + for name, handler in capabilities.REGISTRY.items(): | ||
| 41 | + with self.subTest(capability=name): | ||
| 42 | + self.assertTrue(callable(handler), f"{name} isleyicisi cagrilabilir degil") | ||
| 43 | + | ||
| 44 | + def test_unknown_capability_is_unsupported_capability(self) -> None: | ||
| 45 | + self.assertEqual(self.error_code("podcast.bilinmeyen", {}), "unsupported_capability") | ||
| 46 | + | ||
| 47 | + def test_non_object_payload_is_bad_request(self) -> None: | ||
| 48 | + for payload in ([], "metin", 7, True): | ||
| 49 | + with self.subTest(payload=payload): | ||
| 50 | + self.assertEqual(self.error_code("podcast.submit", payload), "bad_request") | ||
| 51 | + | ||
| 52 | + def test_none_payload_is_treated_as_empty_object(self) -> None: | ||
| 53 | + with self.assertRaises(CapabilityError) as raised: | ||
| 54 | + capabilities.dispatch("podcast.submit", None) | ||
| 55 | + self.assertEqual(raised.exception.code, "bad_request") | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +class FormatDictionaryTests(CapabilityTestCase): | ||
| 59 | + def test_format_set_and_default_match_the_locked_contract(self) -> None: | ||
| 60 | + self.assertEqual( | ||
| 61 | + capabilities.FORMATS, ("tek_ogretici", "ogrenci_hoca", "duz_okuma") | ||
| 62 | + ) | ||
| 63 | + self.assertEqual(capabilities.DEFAULT_FORMAT, "duz_okuma") | ||
| 64 | + self.assertEqual(capabilities.LLM_FORMATS, ("tek_ogretici", "ogrenci_hoca")) | ||
| 65 | + self.assertEqual(capabilities.KEYLESS_FORMATS, ("duz_okuma",)) | ||
| 66 | + | ||
| 67 | + def test_default_format_never_needs_an_llm_key(self) -> None: | ||
| 68 | + self.assertIn( | ||
| 69 | + capabilities.DEFAULT_FORMAT, | ||
| 70 | + capabilities.KEYLESS_FORMATS, | ||
| 71 | + "varsayilan format anahtarsiz kosabilmeli", | ||
| 72 | + ) | ||
| 73 | + | ||
| 74 | + def test_allowed_formats_shrink_to_keyless_set_without_key(self) -> None: | ||
| 75 | + self.assertEqual(capabilities.allowed_formats(False), capabilities.KEYLESS_FORMATS) | ||
| 76 | + self.assertEqual(capabilities.allowed_formats(True), capabilities.FORMATS) | ||
| 77 | + | ||
| 78 | + def test_format_summary_names_the_key_variable_in_both_states(self) -> None: | ||
| 79 | + for llm_ready in (False, True): | ||
| 80 | + with self.subTest(llm_ready=llm_ready): | ||
| 81 | + self.assertIn( | ||
| 82 | + capabilities.LLM_KEY_NAME, capabilities.format_summary(llm_ready) | ||
| 83 | + ) | ||
| 84 | + | ||
| 85 | + def test_keyless_summary_lists_the_disabled_formats(self) -> None: | ||
| 86 | + summary = capabilities.format_summary(False) | ||
| 87 | + for name in capabilities.LLM_FORMATS: | ||
| 88 | + with self.subTest(format=name): | ||
| 89 | + self.assertIn(name, summary, "kapali formatlar ozette adiyla anilmali") | ||
| 90 | + | ||
| 91 | + | ||
| 92 | +class SubmitTests(CapabilityTestCase): | ||
| 93 | + def test_keyless_submit_returns_queued_job_with_positive_eta(self) -> None: | ||
| 94 | + response = capabilities.dispatch("podcast.submit", {"source_id": "ders.pdf"}) | ||
| 95 | + self.assertEqual(response["state"], "queued") | ||
| 96 | + self.assertEqual(len(response["job_id"]), jobs.JOB_ID_LENGTH) | ||
| 97 | + self.assertIsInstance(response["eta_secs"], int) | ||
| 98 | + self.assertGreaterEqual(response["eta_secs"], 1) | ||
| 99 | + | ||
| 100 | + def test_missing_or_blank_source_id_is_bad_request(self) -> None: | ||
| 101 | + for payload in ({}, {"source_id": ""}, {"source_id": " "}, {"source_id": 7}): | ||
| 102 | + with self.subTest(payload=payload): | ||
| 103 | + self.assertEqual(self.error_code("podcast.submit", payload), "bad_request") | ||
| 104 | + | ||
| 105 | + def test_unknown_format_is_bad_request(self) -> None: | ||
| 106 | + self.assertEqual( | ||
| 107 | + self.error_code("podcast.submit", {"source_id": "x", "format": "opera"}), "bad_request" | ||
| 108 | + ) | ||
| 109 | + | ||
| 110 | + def test_non_text_format_is_bad_request(self) -> None: | ||
| 111 | + self.assertEqual( | ||
| 112 | + self.error_code("podcast.submit", {"source_id": "x", "format": 7}), "bad_request" | ||
| 113 | + ) | ||
| 114 | + | ||
| 115 | + def test_llm_formats_are_llm_unavailable_without_the_key(self) -> None: | ||
| 116 | + for name in capabilities.LLM_FORMATS: | ||
| 117 | + with self.subTest(format=name): | ||
| 118 | + self.assertEqual( | ||
| 119 | + self.error_code("podcast.submit", {"source_id": "x", "format": name}), | ||
| 120 | + "llm_unavailable", | ||
| 121 | + ) | ||
| 122 | + | ||
| 123 | + def test_llm_unavailable_message_names_the_usable_formats(self) -> None: | ||
| 124 | + with self.assertRaises(CapabilityError) as raised: | ||
| 125 | + capabilities.dispatch( | ||
| 126 | + "podcast.submit", {"source_id": "x", "format": "tek_ogretici"} | ||
| 127 | + ) | ||
| 128 | + self.assertIn(capabilities.DEFAULT_FORMAT, str(raised.exception)) | ||
| 129 | + | ||
| 130 | + def test_llm_formats_are_accepted_once_the_key_is_ready(self) -> None: | ||
| 131 | + capabilities.configure(self.store, llm_ready=True) | ||
| 132 | + response = capabilities.dispatch( | ||
| 133 | + "podcast.submit", {"source_id": "x", "format": "ogrenci_hoca"} | ||
| 134 | + ) | ||
| 135 | + self.assertEqual(response["state"], "queued") | ||
| 136 | + | ||
| 137 | + def test_full_queue_answers_busy_not_internal(self) -> None: | ||
| 138 | + small = jobs.JobStore(root=self.root / "dar", workers=1, max_jobs=1, stage_secs=0.0) | ||
| 139 | + capabilities.configure(small, llm_ready=False) | ||
| 140 | + try: | ||
| 141 | + capabilities.dispatch("podcast.submit", {"source_id": "ilk"}) | ||
| 142 | + self.assertEqual(self.error_code("podcast.submit", {"source_id": "ikinci"}), "busy") | ||
| 143 | + finally: | ||
| 144 | + small.shutdown(timeout=1.0) | ||
| 145 | + | ||
| 146 | + def test_missing_store_answers_internal(self) -> None: | ||
| 147 | + capabilities.configure(None, llm_ready=False) | ||
| 148 | + self.assertEqual(self.error_code("podcast.submit", {"source_id": "x"}), "internal") | ||
| 149 | + | ||
| 150 | + | ||
| 151 | +class StatusResultCancelTests(CapabilityTestCase): | ||
| 152 | + def test_status_reports_queued_job_without_error_code(self) -> None: | ||
| 153 | + job_id = capabilities.dispatch("podcast.submit", {"source_id": "x"})["job_id"] | ||
| 154 | + response = capabilities.dispatch("podcast.status", {"job_id": job_id}) | ||
| 155 | + self.assertEqual(response["state"], "queued") | ||
| 156 | + self.assertEqual(response["progress"], 0.0) | ||
| 157 | + self.assertIn("error_code", response) | ||
| 158 | + self.assertIsNone(response["error_code"]) | ||
| 159 | + | ||
| 160 | + def test_result_before_completion_is_not_ready(self) -> None: | ||
| 161 | + job_id = capabilities.dispatch("podcast.submit", {"source_id": "x"})["job_id"] | ||
| 162 | + self.assertEqual(self.error_code("podcast.result", {"job_id": job_id}), "not_ready") | ||
| 163 | + | ||
| 164 | + def test_unknown_job_is_not_found_for_every_lookup_capability(self) -> None: | ||
| 165 | + for name in ("podcast.status", "podcast.result", "podcast.cancel"): | ||
| 166 | + with self.subTest(capability=name): | ||
| 167 | + self.assertEqual(self.error_code(name, {"job_id": "YOKBOYLEBIRIS"}), "not_found") | ||
| 168 | + | ||
| 169 | + def test_blank_job_id_is_bad_request_for_every_lookup_capability(self) -> None: | ||
| 170 | + for name in ("podcast.status", "podcast.result", "podcast.cancel"): | ||
| 171 | + for payload in ({}, {"job_id": ""}, {"job_id": 7}): | ||
| 172 | + with self.subTest(capability=name, payload=payload): | ||
| 173 | + self.assertEqual(self.error_code(name, payload), "bad_request") | ||
| 174 | + | ||
| 175 | + def test_cancel_of_queued_job_reports_true_then_false(self) -> None: | ||
| 176 | + job_id = capabilities.dispatch("podcast.submit", {"source_id": "x"})["job_id"] | ||
| 177 | + self.assertTrue(capabilities.dispatch("podcast.cancel", {"job_id": job_id})["cancelled"]) | ||
| 178 | + self.assertEqual( | ||
| 179 | + capabilities.dispatch("podcast.status", {"job_id": job_id})["state"], "cancelled" | ||
| 180 | + ) | ||
| 181 | + self.assertFalse( | ||
| 182 | + capabilities.dispatch("podcast.cancel", {"job_id": job_id})["cancelled"], | ||
| 183 | + "bitmis is icin ikinci iptal False donmeli", | ||
| 184 | + ) | ||
| 185 | + | ||
| 186 | + def test_result_payload_carries_both_singular_and_plural_identifiers(self) -> None: | ||
| 187 | + job_id = capabilities.dispatch("podcast.submit", {"source_id": "x"})["job_id"] | ||
| 188 | + self.store.transition(job_id, jobs.STATE_RUNNING) | ||
| 189 | + self.store.finish( | ||
| 190 | + job_id, | ||
| 191 | + audio_id="a/b.mp3", | ||
| 192 | + duration_secs=12.5, | ||
| 193 | + script_id="a/b.json", | ||
| 194 | + audio_ids=["a/b.mp3", "a/c.mp3"], | ||
| 195 | + script_ids=["a/b.json", "a/c.json"], | ||
| 196 | + ) | ||
| 197 | + response = capabilities.dispatch("podcast.result", {"job_id": job_id}) | ||
| 198 | + self.assertEqual(response["audio_id"], "a/b.mp3") | ||
| 199 | + self.assertEqual(response["script_id"], "a/b.json") | ||
| 200 | + self.assertEqual(response["duration_secs"], 12.5) | ||
| 201 | + self.assertEqual(response["audio_ids"], ["a/b.mp3", "a/c.mp3"]) | ||
| 202 | + self.assertEqual(response["script_ids"], ["a/b.json", "a/c.json"]) | ||
| 203 | + self.assertEqual(response["format"], "duz_okuma") | ||
| 204 | + | ||
| 205 | + | ||
| 206 | +if __name__ == "__main__": | ||
| 207 | + unittest.main() | ||
tests/unit/test_config.pyadded+227 -0
| @@ -0,0 +1,227 @@ | |||
| 1 | +import os | ||
| 2 | +import unittest | ||
| 3 | +from pathlib import Path | ||
| 4 | + | ||
| 5 | +from src import config | ||
| 6 | + | ||
| 7 | +ENV_NAMES = ( | ||
| 8 | + "LOG_LEVEL", | ||
| 9 | + "AI_BRIDGE_HOST", | ||
| 10 | + "AI_BRIDGE_PORT", | ||
| 11 | + "AI_BACKEND_URL", | ||
| 12 | + "AI_TLS_SERVER_NAME", | ||
| 13 | + "AI_SERVICE_NAME", | ||
| 14 | + "AI_MAX_CONCURRENT", | ||
| 15 | + "AI_RECONNECT_SECS", | ||
| 16 | + "AI_SHARED_TOKEN", | ||
| 17 | + "PODCAST_JOB_ROOT", | ||
| 18 | + "PODCAST_WORKERS", | ||
| 19 | + "PODCAST_MAX_JOBS", | ||
| 20 | + "PODCAST_STAGE_SECS", | ||
| 21 | + "PODCAST_ETA_SECS", | ||
| 22 | + "PODCAST_MEDIA_ROOT", | ||
| 23 | + "PODCAST_MODE", | ||
| 24 | + "PODCAST_PIPELINE_PATH", | ||
| 25 | + "PODCAST_OUTPUT_ROOT", | ||
| 26 | + "PODCAST_LEDGER_DB", | ||
| 27 | + "PODCAST_CHAPTER_LIMIT", | ||
| 28 | + "PODCAST_TTS_ENGINE", | ||
| 29 | + "DEEPSEEK_API_KEY", | ||
| 30 | + "PODCAST_TEST_DEGISKENI", | ||
| 31 | +) | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +class EnvIsolatedTestCase(unittest.TestCase): | ||
| 35 | + def setUp(self) -> None: | ||
| 36 | + self._previous = {name: os.environ.get(name) for name in ENV_NAMES} | ||
| 37 | + for name in ENV_NAMES: | ||
| 38 | + os.environ.pop(name, None) | ||
| 39 | + self._log_level = config._active_level | ||
| 40 | + | ||
| 41 | + def tearDown(self) -> None: | ||
| 42 | + for name, value in self._previous.items(): | ||
| 43 | + if value is None: | ||
| 44 | + os.environ.pop(name, None) | ||
| 45 | + else: | ||
| 46 | + os.environ[name] = value | ||
| 47 | + config._active_level = self._log_level | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +class EnvStrTests(EnvIsolatedTestCase): | ||
| 51 | + def test_missing_or_blank_value_falls_back_to_default(self) -> None: | ||
| 52 | + for raw in (None, "", " ", "\t"): | ||
| 53 | + with self.subTest(raw=raw): | ||
| 54 | + if raw is None: | ||
| 55 | + os.environ.pop("PODCAST_TEST_DEGISKENI", None) | ||
| 56 | + else: | ||
| 57 | + os.environ["PODCAST_TEST_DEGISKENI"] = raw | ||
| 58 | + self.assertEqual( | ||
| 59 | + config.env_str("PODCAST_TEST_DEGISKENI", "varsayilan"), | ||
| 60 | + "varsayilan", | ||
| 61 | + "bos ya da tanimsiz deger varsayilana dusmeli", | ||
| 62 | + ) | ||
| 63 | + | ||
| 64 | + def test_value_is_returned_unstripped_when_present(self) -> None: | ||
| 65 | + os.environ["PODCAST_TEST_DEGISKENI"] = " deger " | ||
| 66 | + self.assertEqual(config.env_str("PODCAST_TEST_DEGISKENI", "x"), " deger ") | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +class EnvIntTests(EnvIsolatedTestCase): | ||
| 70 | + def test_valid_values_are_parsed(self) -> None: | ||
| 71 | + for raw, expected in (("7", 7), (" 7 ", 7), ("-3", -3), ("0", 0)): | ||
| 72 | + with self.subTest(raw=raw): | ||
| 73 | + os.environ["PODCAST_TEST_DEGISKENI"] = raw | ||
| 74 | + self.assertEqual( | ||
| 75 | + config.env_int("PODCAST_TEST_DEGISKENI", 1, -10, 10), expected | ||
| 76 | + ) | ||
| 77 | + | ||
| 78 | + def test_non_integer_is_a_config_error(self) -> None: | ||
| 79 | + os.environ["PODCAST_TEST_DEGISKENI"] = "yedi" | ||
| 80 | + with self.assertRaises(config.ConfigError): | ||
| 81 | + config.env_int("PODCAST_TEST_DEGISKENI", 1, 0, 10) | ||
| 82 | + | ||
| 83 | + def test_out_of_range_is_a_config_error_on_both_ends(self) -> None: | ||
| 84 | + for raw in ("-1", "11"): | ||
| 85 | + with self.subTest(raw=raw): | ||
| 86 | + os.environ["PODCAST_TEST_DEGISKENI"] = raw | ||
| 87 | + with self.assertRaises(config.ConfigError): | ||
| 88 | + config.env_int("PODCAST_TEST_DEGISKENI", 1, 0, 10) | ||
| 89 | + | ||
| 90 | + def test_blank_value_uses_default_without_raising(self) -> None: | ||
| 91 | + os.environ["PODCAST_TEST_DEGISKENI"] = " " | ||
| 92 | + self.assertEqual(config.env_int("PODCAST_TEST_DEGISKENI", 4, 0, 10), 4) | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +class EnvFloatTests(EnvIsolatedTestCase): | ||
| 96 | + def test_valid_values_are_parsed(self) -> None: | ||
| 97 | + os.environ["PODCAST_TEST_DEGISKENI"] = " 2.5 " | ||
| 98 | + self.assertEqual(config.env_float("PODCAST_TEST_DEGISKENI", 1.0, 0.0, 10.0), 2.5) | ||
| 99 | + | ||
| 100 | + def test_non_number_is_a_config_error(self) -> None: | ||
| 101 | + os.environ["PODCAST_TEST_DEGISKENI"] = "iki-bucuk" | ||
| 102 | + with self.assertRaises(config.ConfigError): | ||
| 103 | + config.env_float("PODCAST_TEST_DEGISKENI", 1.0, 0.0, 10.0) | ||
| 104 | + | ||
| 105 | + def test_out_of_range_is_a_config_error(self) -> None: | ||
| 106 | + os.environ["PODCAST_TEST_DEGISKENI"] = "10.5" | ||
| 107 | + with self.assertRaises(config.ConfigError): | ||
| 108 | + config.env_float("PODCAST_TEST_DEGISKENI", 1.0, 0.0, 10.0) | ||
| 109 | + | ||
| 110 | + | ||
| 111 | +class EnvChoiceTests(EnvIsolatedTestCase): | ||
| 112 | + def test_choice_is_case_insensitive_and_trimmed(self) -> None: | ||
| 113 | + os.environ["PODCAST_TEST_DEGISKENI"] = " REAL " | ||
| 114 | + self.assertEqual( | ||
| 115 | + config.env_choice("PODCAST_TEST_DEGISKENI", "simulate", config.PIPELINE_MODES), | ||
| 116 | + "real", | ||
| 117 | + ) | ||
| 118 | + | ||
| 119 | + def test_unknown_choice_is_a_config_error(self) -> None: | ||
| 120 | + os.environ["PODCAST_TEST_DEGISKENI"] = "yari-gercek" | ||
| 121 | + with self.assertRaises(config.ConfigError): | ||
| 122 | + config.env_choice("PODCAST_TEST_DEGISKENI", "simulate", config.PIPELINE_MODES) | ||
| 123 | + | ||
| 124 | + def test_blank_choice_uses_default(self) -> None: | ||
| 125 | + os.environ["PODCAST_TEST_DEGISKENI"] = "" | ||
| 126 | + self.assertEqual( | ||
| 127 | + config.env_choice("PODCAST_TEST_DEGISKENI", "simulate", config.PIPELINE_MODES), | ||
| 128 | + "simulate", | ||
| 129 | + ) | ||
| 130 | + | ||
| 131 | + | ||
| 132 | +class LogLevelTests(EnvIsolatedTestCase): | ||
| 133 | + def test_known_levels_are_accepted_and_actually_applied(self) -> None: | ||
| 134 | + for name, expected in ( | ||
| 135 | + ("debug", 10), | ||
| 136 | + ("INFO", 20), | ||
| 137 | + (" warn ", 30), | ||
| 138 | + ("warning", 30), | ||
| 139 | + ("error", 40), | ||
| 140 | + ): | ||
| 141 | + with self.subTest(name=name): | ||
| 142 | + config.set_log_level(name) | ||
| 143 | + self.assertEqual( | ||
| 144 | + config._active_level, | ||
| 145 | + expected, | ||
| 146 | + f"'{name}' kabul edildi ama etkin seviye uygulanmadi", | ||
| 147 | + ) | ||
| 148 | + | ||
| 149 | + def test_unknown_level_is_a_config_error(self) -> None: | ||
| 150 | + with self.assertRaises(config.ConfigError): | ||
| 151 | + config.set_log_level("gurultu") | ||
| 152 | + | ||
| 153 | + def test_lower_priority_messages_are_filtered_out(self) -> None: | ||
| 154 | + config.set_log_level("error") | ||
| 155 | + self.assertEqual(config.LOG_LEVELS["debug"], 10) | ||
| 156 | + self.assertLess( | ||
| 157 | + config.LOG_LEVELS["debug"], | ||
| 158 | + config._active_level, | ||
| 159 | + "error seviyesinde debug mesaji basilmamali", | ||
| 160 | + ) | ||
| 161 | + | ||
| 162 | + | ||
| 163 | +class AbsolutePathTests(EnvIsolatedTestCase): | ||
| 164 | + def test_relative_path_becomes_absolute(self) -> None: | ||
| 165 | + resolved = config._absolute("out") | ||
| 166 | + self.assertTrue(Path(resolved).is_absolute(), f"goreli yol mutlaklastirilmadi: {resolved}") | ||
| 167 | + | ||
| 168 | + def test_empty_path_stays_empty(self) -> None: | ||
| 169 | + self.assertEqual(config._absolute(""), "") | ||
| 170 | + | ||
| 171 | + def test_dot_segments_are_collapsed(self) -> None: | ||
| 172 | + resolved = config._absolute(os.path.join("a", "..", "b")) | ||
| 173 | + self.assertNotIn("..", resolved, "nokta parcalari cozulmeli") | ||
| 174 | + | ||
| 175 | + | ||
| 176 | +class ConfigDefaultsTests(EnvIsolatedTestCase): | ||
| 177 | + def test_defaults_match_the_documented_contract(self) -> None: | ||
| 178 | + settings = config.Config(require_token=False) | ||
| 179 | + self.assertEqual(settings.service, "podcast") | ||
| 180 | + self.assertEqual(settings.port, 8090) | ||
| 181 | + self.assertEqual(settings.mode, config.PIPELINE_MODE_DEFAULT) | ||
| 182 | + self.assertEqual(settings.max_concurrent, 2) | ||
| 183 | + self.assertEqual(settings.workers, 1) | ||
| 184 | + self.assertEqual(settings.max_jobs, 8) | ||
| 185 | + self.assertEqual(settings.chapter_limit, 1) | ||
| 186 | + self.assertEqual(settings.tts_engine, "supertonic-3") | ||
| 187 | + self.assertFalse(settings.has_token) | ||
| 188 | + self.assertFalse(settings.has_llm_key) | ||
| 189 | + | ||
| 190 | + def test_backend_url_trailing_slash_is_trimmed(self) -> None: | ||
| 191 | + os.environ["AI_BACKEND_URL"] = "http://backend:8080/" | ||
| 192 | + self.assertEqual(config.Config(require_token=False).backend_url, "http://backend:8080") | ||
| 193 | + | ||
| 194 | + def test_missing_token_is_fatal_only_when_required(self) -> None: | ||
| 195 | + config.Config(require_token=False) | ||
| 196 | + with self.assertRaises(config.ConfigError): | ||
| 197 | + config.Config(require_token=True) | ||
| 198 | + | ||
| 199 | + def test_llm_key_presence_is_recorded_as_a_boolean_not_the_value(self) -> None: | ||
| 200 | + os.environ["DEEPSEEK_API_KEY"] = "sk-ornek" | ||
| 201 | + settings = config.Config(require_token=False) | ||
| 202 | + self.assertTrue(settings.has_llm_key) | ||
| 203 | + self.assertFalse( | ||
| 204 | + hasattr(settings, "llm_key"), | ||
| 205 | + "Config LLM anahtarinin degerini saklamamali, yalnizca varligini", | ||
| 206 | + ) | ||
| 207 | + | ||
| 208 | + | ||
| 209 | +class ModeGateTests(EnvIsolatedTestCase): | ||
| 210 | + def test_pipeline_modes_are_exactly_simulate_and_real(self) -> None: | ||
| 211 | + self.assertEqual(config.PIPELINE_MODES, ("simulate", "real")) | ||
| 212 | + self.assertEqual(config.PIPELINE_MODE_DEFAULT, "simulate") | ||
| 213 | + | ||
| 214 | + def test_both_modes_are_accepted(self) -> None: | ||
| 215 | + for mode in config.PIPELINE_MODES: | ||
| 216 | + with self.subTest(mode=mode): | ||
| 217 | + os.environ["PODCAST_MODE"] = mode | ||
| 218 | + self.assertEqual(config.Config(require_token=False).mode, mode) | ||
| 219 | + | ||
| 220 | + def test_unknown_mode_crashes_the_boot_instead_of_silently_simulating(self) -> None: | ||
| 221 | + os.environ["PODCAST_MODE"] = "yari-gercek" | ||
| 222 | + with self.assertRaises(config.ConfigError): | ||
| 223 | + config.Config(require_token=False) | ||
| 224 | + | ||
| 225 | + | ||
| 226 | +if __name__ == "__main__": | ||
| 227 | + unittest.main() | ||
tests/unit/test_jobs.pyadded+389 -0
| @@ -0,0 +1,389 @@ | |||
| 1 | +import json | ||
| 2 | +import os | ||
| 3 | +import tempfile | ||
| 4 | +import threading | ||
| 5 | +import time | ||
| 6 | +import unittest | ||
| 7 | +from pathlib import Path | ||
| 8 | + | ||
| 9 | +from src import config, jobs | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +def wait_for(store: jobs.JobStore, job_id: str, wanted: tuple, deadline_secs: float) -> dict: | ||
| 13 | + limit = time.monotonic() + deadline_secs | ||
| 14 | + while time.monotonic() < limit: | ||
| 15 | + record = store.get(job_id) | ||
| 16 | + if record["state"] in wanted: | ||
| 17 | + return record | ||
| 18 | + time.sleep(0.005) | ||
| 19 | + return store.get(job_id) | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +class JobTestCase(unittest.TestCase): | ||
| 23 | + def setUp(self) -> None: | ||
| 24 | + self._log_level = config._active_level | ||
| 25 | + config.set_log_level("error") | ||
| 26 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-isler-") | ||
| 27 | + self.root = Path(self._tmp.name) | ||
| 28 | + self._stores: list = [] | ||
| 29 | + | ||
| 30 | + def tearDown(self) -> None: | ||
| 31 | + for store in self._stores: | ||
| 32 | + store.shutdown(timeout=1.0) | ||
| 33 | + self._tmp.cleanup() | ||
| 34 | + config._active_level = self._log_level | ||
| 35 | + | ||
| 36 | + def make_store(self, name: str, **kwargs) -> jobs.JobStore: | ||
| 37 | + defaults = {"workers": 1, "max_jobs": 8, "stage_secs": 0.0} | ||
| 38 | + defaults.update(kwargs) | ||
| 39 | + store = jobs.JobStore(root=self.root / name, **defaults) | ||
| 40 | + self._stores.append(store) | ||
| 41 | + return store | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +class JobIdTests(JobTestCase): | ||
| 45 | + def test_job_id_is_twenty_six_crockford_characters(self) -> None: | ||
| 46 | + for _ in range(50): | ||
| 47 | + job_id = jobs.new_job_id() | ||
| 48 | + with self.subTest(job_id=job_id): | ||
| 49 | + self.assertEqual(len(job_id), jobs.JOB_ID_LENGTH) | ||
| 50 | + self.assertTrue( | ||
| 51 | + set(job_id) <= set("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), | ||
| 52 | + f"is kimliginde Crockford disi karakter var: {job_id}", | ||
| 53 | + ) | ||
| 54 | + | ||
| 55 | + def test_job_ids_are_unique(self) -> None: | ||
| 56 | + produced = [jobs.new_job_id() for _ in range(500)] | ||
| 57 | + self.assertEqual(len(set(produced)), len(produced), "is kimlikleri carpisti") | ||
| 58 | + | ||
| 59 | + def test_job_id_timestamp_prefix_never_goes_backwards(self) -> None: | ||
| 60 | + prefixes = [jobs.new_job_id()[:10] for _ in range(200)] | ||
| 61 | + self.assertEqual( | ||
| 62 | + sorted(prefixes), prefixes, "is kimliginin zaman oneki geriye gitmemeli" | ||
| 63 | + ) | ||
| 64 | + | ||
| 65 | + | ||
| 66 | +class StateMachineTests(JobTestCase): | ||
| 67 | + def test_state_set_is_the_documented_five(self) -> None: | ||
| 68 | + self.assertEqual( | ||
| 69 | + jobs.STATES, ("queued", "running", "done", "failed", "cancelled") | ||
| 70 | + ) | ||
| 71 | + | ||
| 72 | + def test_every_transition_target_is_a_known_state(self) -> None: | ||
| 73 | + for state, allowed in jobs.TRANSITIONS.items(): | ||
| 74 | + for target in allowed: | ||
| 75 | + with self.subTest(state=state, target=target): | ||
| 76 | + self.assertIn(target, jobs.STATES) | ||
| 77 | + | ||
| 78 | + def test_terminal_states_have_no_outgoing_transition(self) -> None: | ||
| 79 | + for terminal in (jobs.STATE_DONE, jobs.STATE_FAILED, jobs.STATE_CANCELLED): | ||
| 80 | + with self.subTest(state=terminal): | ||
| 81 | + self.assertEqual( | ||
| 82 | + jobs.TRANSITIONS[terminal], (), f"'{terminal}' terminal olmali" | ||
| 83 | + ) | ||
| 84 | + | ||
| 85 | + def test_can_transition_matches_the_table(self) -> None: | ||
| 86 | + legal = ( | ||
| 87 | + ("queued", "running"), | ||
| 88 | + ("queued", "cancelled"), | ||
| 89 | + ("queued", "failed"), | ||
| 90 | + ("running", "done"), | ||
| 91 | + ("running", "failed"), | ||
| 92 | + ("running", "cancelled"), | ||
| 93 | + ) | ||
| 94 | + forbidden = ( | ||
| 95 | + ("queued", "done"), | ||
| 96 | + ("done", "running"), | ||
| 97 | + ("failed", "running"), | ||
| 98 | + ("cancelled", "done"), | ||
| 99 | + ("running", "queued"), | ||
| 100 | + ("queued", "bilinmeyen"), | ||
| 101 | + ) | ||
| 102 | + for current, target in legal: | ||
| 103 | + with self.subTest(transition=(current, target)): | ||
| 104 | + self.assertTrue(jobs.can_transition(current, target)) | ||
| 105 | + for current, target in forbidden: | ||
| 106 | + with self.subTest(transition=(current, target)): | ||
| 107 | + self.assertFalse(jobs.can_transition(current, target)) | ||
| 108 | + | ||
| 109 | + def test_illegal_transition_raises_invalid_transition(self) -> None: | ||
| 110 | + store = self.make_store("gecis") | ||
| 111 | + job_id = store.submit("x", "duz_okuma")[0]["job_id"] | ||
| 112 | + with self.assertRaises(jobs.InvalidTransition): | ||
| 113 | + store.transition(job_id, jobs.STATE_DONE) | ||
| 114 | + | ||
| 115 | + def test_transition_on_unknown_job_raises_job_not_found(self) -> None: | ||
| 116 | + store = self.make_store("bilinmeyen") | ||
| 117 | + with self.assertRaises(jobs.JobNotFound): | ||
| 118 | + store.transition("YOKBOYLEBIRIS", jobs.STATE_RUNNING) | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +class ProgressTests(JobTestCase): | ||
| 122 | + def test_progress_is_ignored_unless_the_job_is_running(self) -> None: | ||
| 123 | + store = self.make_store("ilerleme") | ||
| 124 | + job_id = store.submit("x", "duz_okuma")[0]["job_id"] | ||
| 125 | + self.assertIsNone( | ||
| 126 | + store.update_progress(job_id, "ocr", 0.5), | ||
| 127 | + "kuyruktaki ise ilerleme yazilmamali", | ||
| 128 | + ) | ||
| 129 | + | ||
| 130 | + def test_progress_is_clamped_to_the_unit_interval(self) -> None: | ||
| 131 | + store = self.make_store("kirpma") | ||
| 132 | + job_id = store.submit("x", "duz_okuma")[0]["job_id"] | ||
| 133 | + store.transition(job_id, jobs.STATE_RUNNING) | ||
| 134 | + for given, expected in ((-1.0, 0.0), (0.0, 0.0), (0.5, 0.5), (2.0, 1.0)): | ||
| 135 | + with self.subTest(given=given): | ||
| 136 | + record = store.update_progress(job_id, "ocr", given) | ||
| 137 | + self.assertEqual(record["progress"], expected) | ||
| 138 | + | ||
| 139 | + | ||
| 140 | +class PersistenceTests(JobTestCase): | ||
| 141 | + def test_submitted_job_is_written_to_disk_atomically(self) -> None: | ||
| 142 | + root = self.root / "kalici" | ||
| 143 | + store = self.make_store("kalici") | ||
| 144 | + job_id = store.submit("kaynak-1", "duz_okuma")[0]["job_id"] | ||
| 145 | + path = root / f"{job_id}.json" | ||
| 146 | + self.assertTrue(path.is_file(), "is durumu diske yazilmadi") | ||
| 147 | + with open(path, "r", encoding="utf-8") as handle: | ||
| 148 | + on_disk = json.load(handle) | ||
| 149 | + self.assertEqual(on_disk["job_id"], job_id) | ||
| 150 | + self.assertEqual(on_disk["state"], "queued") | ||
| 151 | + self.assertEqual( | ||
| 152 | + [name for name in os.listdir(root) if ".json.tmp" in name], | ||
| 153 | + [], | ||
| 154 | + "atomik yazmadan gecici dosya artigi kalmamali", | ||
| 155 | + ) | ||
| 156 | + | ||
| 157 | + def test_reopened_store_recovers_queued_jobs_without_sweeping_them(self) -> None: | ||
| 158 | + store = self.make_store("yeniden") | ||
| 159 | + job_id = store.submit("kaynak-1", "duz_okuma")[0]["job_id"] | ||
| 160 | + reopened = self.make_store("yeniden") | ||
| 161 | + self.assertEqual(reopened.get(job_id)["state"], "queued") | ||
| 162 | + self.assertEqual(reopened.swept, 0, "kuyruktaki is supurulmemeli") | ||
| 163 | + | ||
| 164 | + def test_record_id_must_match_the_file_name(self) -> None: | ||
| 165 | + root = self.root / "kimlik" | ||
| 166 | + store = self.make_store("kimlik") | ||
| 167 | + job_id = store.submit("kaynak-1", "duz_okuma")[0]["job_id"] | ||
| 168 | + with open(root / f"{job_id}.json", "r", encoding="utf-8") as handle: | ||
| 169 | + record = json.load(handle) | ||
| 170 | + record["job_id"] = "BASKABIRKIMLIK" | ||
| 171 | + with open(root / f"{job_id}.json", "w", encoding="utf-8") as handle: | ||
| 172 | + json.dump(record, handle) | ||
| 173 | + reopened = self.make_store("kimlik") | ||
| 174 | + with self.assertRaises(jobs.JobNotFound): | ||
| 175 | + reopened.get(job_id) | ||
| 176 | + | ||
| 177 | + def test_unreadable_record_is_skipped_not_fatal(self) -> None: | ||
| 178 | + root = self.root / "bozuk" | ||
| 179 | + root.mkdir(parents=True, exist_ok=True) | ||
| 180 | + with open(root / "01BOZUKKAYIT.json", "w", encoding="utf-8") as handle: | ||
| 181 | + handle.write("{ bu json degil") | ||
| 182 | + store = self.make_store("bozuk") | ||
| 183 | + self.assertEqual(store.swept, 0) | ||
| 184 | + | ||
| 185 | + | ||
| 186 | +class SweepTests(JobTestCase): | ||
| 187 | + def test_running_jobs_become_failed_interrupted_on_boot(self) -> None: | ||
| 188 | + seed = self.make_store("supurme") | ||
| 189 | + running_id = seed.submit("kaynak-2", "duz_okuma")[0]["job_id"] | ||
| 190 | + seed.transition(running_id, jobs.STATE_RUNNING) | ||
| 191 | + queued_id = seed.submit("kaynak-3", "duz_okuma")[0]["job_id"] | ||
| 192 | + | ||
| 193 | + swept = self.make_store("supurme") | ||
| 194 | + self.assertEqual(swept.swept, 1, "acilis supurmesi tam olarak 1 is bulmali") | ||
| 195 | + revived = swept.get(running_id) | ||
| 196 | + self.assertEqual(revived["state"], jobs.STATE_FAILED) | ||
| 197 | + self.assertEqual(revived["error_code"], jobs.INTERRUPTED_CODE) | ||
| 198 | + self.assertEqual( | ||
| 199 | + swept.get(queued_id)["state"], "queued", "kuyruktaki is supurmede bozulmamali" | ||
| 200 | + ) | ||
| 201 | + | ||
| 202 | + def test_sweep_is_persisted_so_a_second_boot_finds_nothing(self) -> None: | ||
| 203 | + seed = self.make_store("iki-acilis") | ||
| 204 | + job_id = seed.submit("kaynak", "duz_okuma")[0]["job_id"] | ||
| 205 | + seed.transition(job_id, jobs.STATE_RUNNING) | ||
| 206 | + self.assertEqual(self.make_store("iki-acilis").swept, 1) | ||
| 207 | + self.assertEqual( | ||
| 208 | + self.make_store("iki-acilis").swept, 0, "supurme diske yazilmadigi icin tekrarlaniyor" | ||
| 209 | + ) | ||
| 210 | + self.assertEqual(self.make_store("iki-acilis").get(job_id)["state"], jobs.STATE_FAILED) | ||
| 211 | + | ||
| 212 | + | ||
| 213 | +class QueueTests(JobTestCase): | ||
| 214 | + def test_queue_quota_counts_only_queued_and_running_jobs(self) -> None: | ||
| 215 | + store = self.make_store("kota", max_jobs=2) | ||
| 216 | + first = store.submit("a", "duz_okuma")[0]["job_id"] | ||
| 217 | + store.submit("b", "duz_okuma") | ||
| 218 | + with self.assertRaises(jobs.JobStoreFull): | ||
| 219 | + store.submit("c", "duz_okuma") | ||
| 220 | + store.cancel(first) | ||
| 221 | + store.submit("c", "duz_okuma") | ||
| 222 | + | ||
| 223 | + def test_queue_full_error_reports_the_limit(self) -> None: | ||
| 224 | + store = self.make_store("kota-mesaj", max_jobs=1) | ||
| 225 | + store.submit("a", "duz_okuma") | ||
| 226 | + with self.assertRaises(jobs.JobStoreFull) as raised: | ||
| 227 | + store.submit("b", "duz_okuma") | ||
| 228 | + self.assertEqual(raised.exception.limit, 1) | ||
| 229 | + self.assertEqual(raised.exception.active, 1) | ||
| 230 | + | ||
| 231 | + def test_estimate_eta_multiplies_by_worker_waves(self) -> None: | ||
| 232 | + store = self.make_store("eta", workers=2, job_secs=2700.0) | ||
| 233 | + self.assertEqual(store.estimate_eta(1), 2700) | ||
| 234 | + self.assertEqual(store.estimate_eta(2), 2700) | ||
| 235 | + self.assertEqual(store.estimate_eta(4), 5400) | ||
| 236 | + self.assertEqual(store.estimate_eta(0), 2700, "bos kuyruk icin eta bir dalga olmali") | ||
| 237 | + | ||
| 238 | + def test_auto_job_secs_never_drops_below_one_second(self) -> None: | ||
| 239 | + self.assertEqual(self.make_store("eta-oto").job_secs, 1.0) | ||
| 240 | + | ||
| 241 | + def test_custom_stages_are_honoured(self) -> None: | ||
| 242 | + self.assertEqual(self.make_store("asamalar", stages=("ocr", "tts")).stages, ("ocr", "tts")) | ||
| 243 | + | ||
| 244 | + def test_default_stages_are_the_simulated_five(self) -> None: | ||
| 245 | + self.assertEqual(self.make_store("varsayilan-asama").stages, jobs.SIMULATED_STAGES) | ||
| 246 | + | ||
| 247 | + | ||
| 248 | +class CancellationTests(JobTestCase): | ||
| 249 | + def test_cancelling_a_queued_job_terminates_it_immediately(self) -> None: | ||
| 250 | + store = self.make_store("iptal-kuyruk") | ||
| 251 | + job_id = store.submit("x", "duz_okuma")[0]["job_id"] | ||
| 252 | + self.assertTrue(store.cancel(job_id)) | ||
| 253 | + self.assertEqual(store.get(job_id)["state"], jobs.STATE_CANCELLED) | ||
| 254 | + | ||
| 255 | + def test_cancelling_a_running_job_only_raises_the_flag(self) -> None: | ||
| 256 | + store = self.make_store("iptal-kosan") | ||
| 257 | + job_id = store.submit("x", "duz_okuma")[0]["job_id"] | ||
| 258 | + store.transition(job_id, jobs.STATE_RUNNING) | ||
| 259 | + self.assertTrue(store.cancel(job_id)) | ||
| 260 | + record = store.get(job_id) | ||
| 261 | + self.assertEqual(record["state"], jobs.STATE_RUNNING) | ||
| 262 | + self.assertTrue(record["cancel_requested"]) | ||
| 263 | + | ||
| 264 | + def test_cancelling_a_terminal_job_returns_false(self) -> None: | ||
| 265 | + store = self.make_store("iptal-bitmis") | ||
| 266 | + job_id = store.submit("x", "duz_okuma")[0]["job_id"] | ||
| 267 | + store.transition(job_id, jobs.STATE_RUNNING) | ||
| 268 | + store.finish(job_id, audio_id="a", duration_secs=1.0, script_id="s") | ||
| 269 | + self.assertFalse(store.cancel(job_id)) | ||
| 270 | + | ||
| 271 | + def test_cancel_of_unknown_job_raises_job_not_found(self) -> None: | ||
| 272 | + with self.assertRaises(jobs.JobNotFound): | ||
| 273 | + self.make_store("iptal-yok").cancel("YOKBOYLEBIRIS") | ||
| 274 | + | ||
| 275 | + def test_begin_refuses_a_job_cancelled_before_it_started(self) -> None: | ||
| 276 | + store = self.make_store("baslamadan") | ||
| 277 | + job_id = store.submit("x", "duz_okuma")[0]["job_id"] | ||
| 278 | + store.cancel(job_id) | ||
| 279 | + self.assertFalse(store.begin(job_id)) | ||
| 280 | + self.assertEqual(store.get(job_id)["state"], jobs.STATE_CANCELLED) | ||
| 281 | + | ||
| 282 | + def test_begin_refuses_while_the_store_is_stopping(self) -> None: | ||
| 283 | + store = self.make_store("kapanirken") | ||
| 284 | + job_id = store.submit("x", "duz_okuma")[0]["job_id"] | ||
| 285 | + store.shutdown(timeout=0.5) | ||
| 286 | + self.assertFalse(store.begin(job_id)) | ||
| 287 | + | ||
| 288 | + def test_job_context_sees_cancellation_through_the_store(self) -> None: | ||
| 289 | + store = self.make_store("baglam") | ||
| 290 | + job_id = store.submit("x", "duz_okuma")[0]["job_id"] | ||
| 291 | + store.transition(job_id, jobs.STATE_RUNNING) | ||
| 292 | + ctx = jobs.JobContext(store, job_id) | ||
| 293 | + self.assertFalse(ctx.cancelled()) | ||
| 294 | + ctx.check() | ||
| 295 | + store.cancel(job_id) | ||
| 296 | + self.assertTrue(ctx.cancelled()) | ||
| 297 | + with self.assertRaises(jobs.JobCancelled): | ||
| 298 | + ctx.check() | ||
| 299 | + | ||
| 300 | + | ||
| 301 | +class WorkerLoopTests(JobTestCase): | ||
| 302 | + def test_simulated_pipeline_carries_a_job_to_done(self) -> None: | ||
| 303 | + store = self.make_store("sahte-hat") | ||
| 304 | + store.start() | ||
| 305 | + job_id = store.submit("x", "duz_okuma")[0]["job_id"] | ||
| 306 | + final = wait_for(store, job_id, (jobs.STATE_DONE, jobs.STATE_FAILED), 10.0) | ||
| 307 | + self.assertEqual(final["state"], jobs.STATE_DONE, final["error_code"]) | ||
| 308 | + self.assertEqual(final["progress"], 1.0) | ||
| 309 | + self.assertTrue(final["audio_id"]) | ||
| 310 | + self.assertTrue(final["script_id"]) | ||
| 311 | + self.assertEqual(final["audio_ids"], [final["audio_id"]]) | ||
| 312 | + | ||
| 313 | + def test_a_runner_that_raises_moves_the_job_to_failed_internal(self) -> None: | ||
| 314 | + def raising(ctx) -> None: | ||
| 315 | + raise RuntimeError("bilerek patladi") | ||
| 316 | + | ||
| 317 | + store = self.make_store("patlayan", runner=raising) | ||
| 318 | + store.start() | ||
| 319 | + job_id = store.submit("x", "duz_okuma")[0]["job_id"] | ||
| 320 | + final = wait_for(store, job_id, (jobs.STATE_FAILED, jobs.STATE_DONE), 10.0) | ||
| 321 | + self.assertEqual(final["state"], jobs.STATE_FAILED) | ||
| 322 | + self.assertEqual(final["error_code"], "internal") | ||
| 323 | + | ||
| 324 | + def test_a_runner_that_honours_cancellation_ends_as_cancelled(self) -> None: | ||
| 325 | + gate = threading.Event() | ||
| 326 | + | ||
| 327 | + def cooperative(ctx) -> None: | ||
| 328 | + gate.wait(5.0) | ||
| 329 | + ctx.check() | ||
| 330 | + | ||
| 331 | + store = self.make_store("isbirlikci", runner=cooperative) | ||
| 332 | + store.start() | ||
| 333 | + job_id = store.submit("x", "duz_okuma")[0]["job_id"] | ||
| 334 | + wait_for(store, job_id, (jobs.STATE_RUNNING,), 5.0) | ||
| 335 | + store.cancel(job_id) | ||
| 336 | + gate.set() | ||
| 337 | + final = wait_for(store, job_id, (jobs.STATE_CANCELLED, jobs.STATE_DONE), 10.0) | ||
| 338 | + self.assertEqual(final["state"], jobs.STATE_CANCELLED) | ||
| 339 | + | ||
| 340 | + def test_start_requeues_jobs_left_queued_from_a_previous_boot(self) -> None: | ||
| 341 | + seed = self.make_store("yeniden-kuyruk") | ||
| 342 | + job_id = seed.submit("x", "duz_okuma")[0]["job_id"] | ||
| 343 | + reopened = self.make_store("yeniden-kuyruk") | ||
| 344 | + self.assertEqual(reopened.start(), 1, "acilista kuyruktaki is yeniden alinmali") | ||
| 345 | + final = wait_for(reopened, job_id, (jobs.STATE_DONE, jobs.STATE_FAILED), 10.0) | ||
| 346 | + self.assertEqual(final["state"], jobs.STATE_DONE) | ||
| 347 | + | ||
| 348 | + | ||
| 349 | +class SourceResolutionTests(JobTestCase): | ||
| 350 | + def test_valid_name_resolves_under_the_media_root(self) -> None: | ||
| 351 | + media = self.root / "medya" | ||
| 352 | + media.mkdir(parents=True, exist_ok=True) | ||
| 353 | + resolved = jobs.resolve_source(media, "ders-01.pdf") | ||
| 354 | + self.assertEqual(resolved, media.resolve() / "ders-01.pdf") | ||
| 355 | + | ||
| 356 | + def test_escaping_names_are_rejected(self) -> None: | ||
| 357 | + media = self.root / "medya2" | ||
| 358 | + media.mkdir(parents=True, exist_ok=True) | ||
| 359 | + for bad in ("..", "../x", "a/b", "/etc/passwd", "", "."): | ||
| 360 | + with self.subTest(source_id=bad): | ||
| 361 | + with self.assertRaises(ValueError): | ||
| 362 | + jobs.resolve_source(media, bad) | ||
| 363 | + | ||
| 364 | + | ||
| 365 | +class StatusFileTests(JobTestCase): | ||
| 366 | + def test_status_file_round_trips_registration_state(self) -> None: | ||
| 367 | + root = self.root / "durum" | ||
| 368 | + root.mkdir(parents=True, exist_ok=True) | ||
| 369 | + jobs.write_status(root, True, "w9") | ||
| 370 | + record = jobs.read_status(root) | ||
| 371 | + self.assertEqual(record["registered"], True) | ||
| 372 | + self.assertEqual(record["worker_id"], "w9") | ||
| 373 | + self.assertEqual(record["pid"], os.getpid()) | ||
| 374 | + | ||
| 375 | + def test_missing_status_file_reads_as_none(self) -> None: | ||
| 376 | + root = self.root / "durumsuz" | ||
| 377 | + root.mkdir(parents=True, exist_ok=True) | ||
| 378 | + self.assertIsNone(jobs.read_status(root)) | ||
| 379 | + | ||
| 380 | + def test_corrupt_status_file_reads_as_none_instead_of_raising(self) -> None: | ||
| 381 | + root = self.root / "durum-bozuk" | ||
| 382 | + root.mkdir(parents=True, exist_ok=True) | ||
| 383 | + with open(jobs.status_path(root), "w", encoding="utf-8") as handle: | ||
| 384 | + handle.write("bu json degil") | ||
| 385 | + self.assertIsNone(jobs.read_status(root)) | ||
| 386 | + | ||
| 387 | + | ||
| 388 | +if __name__ == "__main__": | ||
| 389 | + unittest.main() | ||
tests/unit/test_pipeline.pyadded+273 -0
| @@ -0,0 +1,273 @@ | |||
| 1 | +import sys | ||
| 2 | +import tempfile | ||
| 3 | +import unittest | ||
| 4 | +from pathlib import Path | ||
| 5 | + | ||
| 6 | +from src import config, pipeline | ||
| 7 | + | ||
| 8 | + | ||
| 9 | +class FakeResult: | ||
| 10 | + def __init__(self, mp3: list, scripts: list, duration) -> None: | ||
| 11 | + self.mp3_yollari = mp3 | ||
| 12 | + self.script_yollari = scripts | ||
| 13 | + self.ses_toplam_sn = duration | ||
| 14 | + self.adimlar: list = [] | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +class FakeInterrupt(RuntimeError): | ||
| 18 | + pass | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +class FakeContext: | ||
| 22 | + def __init__(self, cancelled: bool, stages: tuple) -> None: | ||
| 23 | + self._cancelled = cancelled | ||
| 24 | + self.stages = stages | ||
| 25 | + self.seen: list = [] | ||
| 26 | + | ||
| 27 | + def cancelled(self) -> bool: | ||
| 28 | + return self._cancelled | ||
| 29 | + | ||
| 30 | + def progress(self, stage: str, value: float) -> None: | ||
| 31 | + self.seen.append((stage, value)) | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +class PipelineTestCase(unittest.TestCase): | ||
| 35 | + def setUp(self) -> None: | ||
| 36 | + self._log_level = config._active_level | ||
| 37 | + config.set_log_level("error") | ||
| 38 | + self._tmp = tempfile.TemporaryDirectory(prefix="podcast-hat-") | ||
| 39 | + self.root = Path(self._tmp.name) | ||
| 40 | + | ||
| 41 | + def tearDown(self) -> None: | ||
| 42 | + self._tmp.cleanup() | ||
| 43 | + config._active_level = self._log_level | ||
| 44 | + | ||
| 45 | + def output_path(self, *parts: str) -> str: | ||
| 46 | + return str(self.root / "cikti" / Path(*parts)) | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +class ModeGateTests(PipelineTestCase): | ||
| 50 | + def test_mode_set_matches_the_config_module(self) -> None: | ||
| 51 | + self.assertEqual(pipeline.MODES, ("simulate", "real")) | ||
| 52 | + self.assertEqual(pipeline.MODES, config.PIPELINE_MODES) | ||
| 53 | + | ||
| 54 | + def test_real_pipeline_module_is_never_imported_at_module_level(self) -> None: | ||
| 55 | + self.assertNotIn( | ||
| 56 | + pipeline.PIPELINE_MODULE, | ||
| 57 | + sys.modules, | ||
| 58 | + "gercek hat tembel import edilmeli; modul seviyesinde yuklenmemeli", | ||
| 59 | + ) | ||
| 60 | + | ||
| 61 | + def test_blank_pipeline_path_is_rejected(self) -> None: | ||
| 62 | + for bad in ("", " ", None, 7): | ||
| 63 | + with self.subTest(pipeline_path=bad): | ||
| 64 | + with self.assertRaises(pipeline.PipelineUnavailable): | ||
| 65 | + pipeline.check_pipeline_path(bad) | ||
| 66 | + | ||
| 67 | + def test_missing_directory_is_rejected(self) -> None: | ||
| 68 | + with self.assertRaises(pipeline.PipelineUnavailable): | ||
| 69 | + pipeline.check_pipeline_path(str(self.root / "olmayan")) | ||
| 70 | + | ||
| 71 | + def test_directory_missing_any_required_file_is_rejected(self) -> None: | ||
| 72 | + for missing in pipeline.REQUIRED_PIPELINE_FILES: | ||
| 73 | + with self.subTest(missing=missing): | ||
| 74 | + fake_dir = self.root / ("hat-" + missing.replace("/", "-")) | ||
| 75 | + for part in pipeline.REQUIRED_PIPELINE_FILES: | ||
| 76 | + if part == missing: | ||
| 77 | + continue | ||
| 78 | + target = fake_dir / part | ||
| 79 | + target.parent.mkdir(parents=True, exist_ok=True) | ||
| 80 | + target.write_text("", encoding="ascii") | ||
| 81 | + with self.assertRaises(pipeline.PipelineUnavailable): | ||
| 82 | + pipeline.check_pipeline_path(str(fake_dir)) | ||
| 83 | + | ||
| 84 | + def test_directory_with_every_required_file_is_accepted(self) -> None: | ||
| 85 | + fake_dir = self.root / "hat-tam" | ||
| 86 | + for part in pipeline.REQUIRED_PIPELINE_FILES: | ||
| 87 | + target = fake_dir / part | ||
| 88 | + target.parent.mkdir(parents=True, exist_ok=True) | ||
| 89 | + target.write_text("", encoding="ascii") | ||
| 90 | + self.assertEqual(pipeline.check_pipeline_path(str(fake_dir)), fake_dir.resolve()) | ||
| 91 | + | ||
| 92 | + def test_simulate_mode_forces_neither_real_stages_nor_real_eta(self) -> None: | ||
| 93 | + class FakeSettings: | ||
| 94 | + mode = "simulate" | ||
| 95 | + eta_secs = 0.0 | ||
| 96 | + | ||
| 97 | + self.assertIsNone(pipeline.stages_for(FakeSettings)) | ||
| 98 | + self.assertIsNone(pipeline.job_secs_for(FakeSettings)) | ||
| 99 | + | ||
| 100 | + def test_real_mode_uses_the_real_stage_names_and_eta(self) -> None: | ||
| 101 | + class FakeSettings: | ||
| 102 | + mode = "real" | ||
| 103 | + eta_secs = 0.0 | ||
| 104 | + | ||
| 105 | + self.assertEqual(pipeline.stages_for(FakeSettings), pipeline.REAL_STAGES) | ||
| 106 | + self.assertEqual(pipeline.job_secs_for(FakeSettings), pipeline.REAL_ETA_SECS) | ||
| 107 | + | ||
| 108 | + def test_explicit_eta_overrides_the_mode_default(self) -> None: | ||
| 109 | + class FakeSettings: | ||
| 110 | + mode = "real" | ||
| 111 | + eta_secs = 900.0 | ||
| 112 | + | ||
| 113 | + self.assertEqual(pipeline.job_secs_for(FakeSettings), 900.0) | ||
| 114 | + | ||
| 115 | + | ||
| 116 | +class LimitTests(PipelineTestCase): | ||
| 117 | + def test_zero_and_negative_limits_mean_all_chapters(self) -> None: | ||
| 118 | + for value in (0, -1, -4096): | ||
| 119 | + with self.subTest(chapter_limit=value): | ||
| 120 | + self.assertIsNone(pipeline.normalize_limit(value)) | ||
| 121 | + | ||
| 122 | + def test_positive_limit_is_preserved(self) -> None: | ||
| 123 | + self.assertEqual(pipeline.normalize_limit(3), 3) | ||
| 124 | + | ||
| 125 | + | ||
| 126 | +class ResolvePdfTests(PipelineTestCase): | ||
| 127 | + def test_existing_file_under_media_root_resolves(self) -> None: | ||
| 128 | + media = self.root / "medya" | ||
| 129 | + media.mkdir(parents=True, exist_ok=True) | ||
| 130 | + (media / "ders.pdf").write_bytes(b"%PDF-1.4\n") | ||
| 131 | + self.assertEqual( | ||
| 132 | + pipeline.resolve_pdf(str(media), "ders.pdf"), (media / "ders.pdf").resolve() | ||
| 133 | + ) | ||
| 134 | + | ||
| 135 | + def test_missing_file_raises_file_not_found(self) -> None: | ||
| 136 | + media = self.root / "medya-bos" | ||
| 137 | + media.mkdir(parents=True, exist_ok=True) | ||
| 138 | + with self.assertRaises(FileNotFoundError): | ||
| 139 | + pipeline.resolve_pdf(str(media), "yok.pdf") | ||
| 140 | + | ||
| 141 | + def test_a_directory_is_not_accepted_as_a_source_file(self) -> None: | ||
| 142 | + media = self.root / "medya-dizin" | ||
| 143 | + (media / "ders.pdf").mkdir(parents=True, exist_ok=True) | ||
| 144 | + with self.assertRaises(FileNotFoundError): | ||
| 145 | + pipeline.resolve_pdf(str(media), "ders.pdf") | ||
| 146 | + | ||
| 147 | + def test_escaping_source_id_raises_value_error_before_touching_disk(self) -> None: | ||
| 148 | + media = self.root / "medya-kacis" | ||
| 149 | + media.mkdir(parents=True, exist_ok=True) | ||
| 150 | + for bad in ("..", "../x", "a/b", ""): | ||
| 151 | + with self.subTest(source_id=bad): | ||
| 152 | + with self.assertRaises(ValueError): | ||
| 153 | + pipeline.resolve_pdf(str(media), bad) | ||
| 154 | + | ||
| 155 | + | ||
| 156 | +class DeriveOutputsTests(PipelineTestCase): | ||
| 157 | + def test_identifiers_are_relative_to_the_output_root(self) -> None: | ||
| 158 | + root = str(self.root / "cikti") | ||
| 159 | + outputs = pipeline.derive_outputs( | ||
| 160 | + FakeResult( | ||
| 161 | + [self.output_path("ders", "ses", "duz_okuma", "ders-b01.mp3")], | ||
| 162 | + [self.output_path("ders", "script", "duz_okuma", "ders-b01.script.json")], | ||
| 163 | + 321.25, | ||
| 164 | + ), | ||
| 165 | + root, | ||
| 166 | + ) | ||
| 167 | + self.assertEqual(outputs["audio_id"], "ders/ses/duz_okuma/ders-b01.mp3") | ||
| 168 | + self.assertEqual(outputs["script_id"], "ders/script/duz_okuma/ders-b01.script.json") | ||
| 169 | + self.assertEqual(outputs["duration_secs"], 321.25) | ||
| 170 | + | ||
| 171 | + def test_first_identifier_leads_the_plural_lists(self) -> None: | ||
| 172 | + root = str(self.root / "cikti") | ||
| 173 | + outputs = pipeline.derive_outputs( | ||
| 174 | + FakeResult( | ||
| 175 | + [self.output_path("d", "ses", "duz_okuma", "d-b01.mp3"), | ||
| 176 | + self.output_path("d", "ses", "duz_okuma", "d-b02.mp3")], | ||
| 177 | + [self.output_path("d", "script", "duz_okuma", "d-b01.script.json"), | ||
| 178 | + self.output_path("d", "script", "duz_okuma", "d-b02.script.json")], | ||
| 179 | + 10.0, | ||
| 180 | + ), | ||
| 181 | + root, | ||
| 182 | + ) | ||
| 183 | + self.assertEqual(len(outputs["audio_ids"]), 2) | ||
| 184 | + self.assertEqual(outputs["audio_id"], outputs["audio_ids"][0]) | ||
| 185 | + self.assertEqual(outputs["script_id"], outputs["script_ids"][0]) | ||
| 186 | + | ||
| 187 | + def test_paths_outside_the_root_fall_back_to_the_file_name(self) -> None: | ||
| 188 | + outputs = pipeline.derive_outputs( | ||
| 189 | + FakeResult(["/baska/yer/x.mp3"], ["/baska/yer/x.script.json"], 1.0), | ||
| 190 | + str(self.root / "cikti"), | ||
| 191 | + ) | ||
| 192 | + self.assertEqual(outputs["audio_id"], "x.mp3") | ||
| 193 | + self.assertEqual(outputs["script_id"], "x.script.json") | ||
| 194 | + | ||
| 195 | + def test_empty_result_produces_empty_identifiers_not_none(self) -> None: | ||
| 196 | + outputs = pipeline.derive_outputs(FakeResult([], [], 0.0), str(self.root / "cikti")) | ||
| 197 | + self.assertEqual(outputs["audio_id"], "") | ||
| 198 | + self.assertEqual(outputs["script_id"], "") | ||
| 199 | + self.assertEqual(outputs["audio_ids"], []) | ||
| 200 | + self.assertEqual(outputs["script_ids"], []) | ||
| 201 | + | ||
| 202 | + def test_unparseable_duration_degrades_to_zero(self) -> None: | ||
| 203 | + for duration in (None, "uzun", object()): | ||
| 204 | + with self.subTest(duration=duration): | ||
| 205 | + outputs = pipeline.derive_outputs( | ||
| 206 | + FakeResult(["/o/x.mp3"], ["/o/x.json"], duration), str(self.root / "cikti") | ||
| 207 | + ) | ||
| 208 | + self.assertEqual(outputs["duration_secs"], 0.0) | ||
| 209 | + | ||
| 210 | + def test_without_an_output_root_identifiers_degrade_to_file_names(self) -> None: | ||
| 211 | + outputs = pipeline.derive_outputs( | ||
| 212 | + FakeResult([self.output_path("d", "ses", "duz_okuma", "d-b01.mp3")], [], 1.0) | ||
| 213 | + ) | ||
| 214 | + self.assertEqual(outputs["audio_id"], "d-b01.mp3") | ||
| 215 | + | ||
| 216 | + | ||
| 217 | +class LogHookTests(PipelineTestCase): | ||
| 218 | + def test_hook_raises_the_pipelines_own_interrupt_when_cancelled(self) -> None: | ||
| 219 | + ctx = FakeContext(True, pipeline.REAL_STAGES) | ||
| 220 | + hook = pipeline.build_log_hook(ctx, lambda: 1, pipeline.REAL_STAGES, FakeInterrupt) | ||
| 221 | + with self.assertRaises(FakeInterrupt): | ||
| 222 | + hook("[KOSTU ] ingest") | ||
| 223 | + self.assertEqual( | ||
| 224 | + ctx.seen, [], "iptal edilen iste kanca ilerleme yazmamali" | ||
| 225 | + ) | ||
| 226 | + | ||
| 227 | + def test_hook_derives_progress_from_the_completed_step_count(self) -> None: | ||
| 228 | + for step, expected in ((0, ("ingest", 0.0)), (2, ("quiz", 0.5)), (3, ("ses", 0.75))): | ||
| 229 | + with self.subTest(step=step): | ||
| 230 | + ctx = FakeContext(False, pipeline.REAL_STAGES) | ||
| 231 | + hook = pipeline.build_log_hook( | ||
| 232 | + ctx, lambda step=step: step, pipeline.REAL_STAGES, FakeInterrupt | ||
| 233 | + ) | ||
| 234 | + hook("[KOSTU ] bir sey") | ||
| 235 | + self.assertEqual(ctx.seen, [expected]) | ||
| 236 | + | ||
| 237 | + def test_step_count_beyond_the_stage_list_is_clamped_to_the_last_stage(self) -> None: | ||
| 238 | + ctx = FakeContext(False, pipeline.REAL_STAGES) | ||
| 239 | + hook = pipeline.build_log_hook(ctx, lambda: 99, pipeline.REAL_STAGES, FakeInterrupt) | ||
| 240 | + hook("[KOSTU ] tasma") | ||
| 241 | + self.assertEqual(ctx.seen, [(pipeline.REAL_STAGES[-1], 1.0)]) | ||
| 242 | + | ||
| 243 | + def test_a_broken_step_counter_does_not_kill_the_run(self) -> None: | ||
| 244 | + def broken() -> int: | ||
| 245 | + raise RuntimeError("sayac patladi") | ||
| 246 | + | ||
| 247 | + ctx = FakeContext(False, pipeline.REAL_STAGES) | ||
| 248 | + hook = pipeline.build_log_hook(ctx, broken, pipeline.REAL_STAGES, FakeInterrupt) | ||
| 249 | + hook("[KOSTU ] ingest") | ||
| 250 | + self.assertEqual(ctx.seen, [(pipeline.REAL_STAGES[0], 0.0)]) | ||
| 251 | + | ||
| 252 | + def test_negative_step_count_is_floored_at_zero(self) -> None: | ||
| 253 | + ctx = FakeContext(False, pipeline.REAL_STAGES) | ||
| 254 | + hook = pipeline.build_log_hook(ctx, lambda: -5, pipeline.REAL_STAGES, FakeInterrupt) | ||
| 255 | + hook("[KOSTU ] ingest") | ||
| 256 | + self.assertEqual(ctx.seen, [(pipeline.REAL_STAGES[0], 0.0)]) | ||
| 257 | + | ||
| 258 | + | ||
| 259 | +class ErrorCodeTests(PipelineTestCase): | ||
| 260 | + def test_pipeline_error_codes_are_stable(self) -> None: | ||
| 261 | + self.assertEqual(pipeline.SOURCE_NOT_FOUND, "source_not_found") | ||
| 262 | + self.assertEqual(pipeline.NO_AUDIO, "no_audio") | ||
| 263 | + self.assertEqual(pipeline.PIPELINE_MISCONFIGURED, "pipeline_misconfigured") | ||
| 264 | + | ||
| 265 | + def test_real_stage_names_match_the_documented_four(self) -> None: | ||
| 266 | + self.assertEqual(pipeline.REAL_STAGES, ("ingest", "scriptler", "quiz", "ses")) | ||
| 267 | + | ||
| 268 | + def test_simulate_warning_never_hides_that_the_audio_is_fake(self) -> None: | ||
| 269 | + self.assertIn("GERCEK DEGIL", pipeline.FAKE_WARNING) | ||
| 270 | + | ||
| 271 | + | ||
| 272 | +if __name__ == "__main__": | ||
| 273 | + unittest.main() | ||
tests/unit/test_protocol.pyadded+192 -0
| @@ -0,0 +1,192 @@ | |||
| 1 | +import asyncio | ||
| 2 | +import json | ||
| 3 | +import struct | ||
| 4 | +import unittest | ||
| 5 | + | ||
| 6 | +from src import protocol | ||
| 7 | + | ||
| 8 | + | ||
| 9 | +class FramingTests(unittest.TestCase): | ||
| 10 | + def test_length_prefix_is_four_byte_big_endian(self) -> None: | ||
| 11 | + self.assertEqual( | ||
| 12 | + protocol.encode_frame({})[:4], | ||
| 13 | + b"\x00\x00\x00\x02", | ||
| 14 | + "uzunluk oneki 4 bayt big-endian olmali", | ||
| 15 | + ) | ||
| 16 | + | ||
| 17 | + def test_body_is_utf8_json_without_ascii_escaping(self) -> None: | ||
| 18 | + frame = protocol.encode_frame({"k": "cok"}) | ||
| 19 | + self.assertEqual(json.loads(frame[4:].decode("utf-8")), {"k": "cok"}) | ||
| 20 | + | ||
| 21 | + def test_encode_frame_raises_frame_too_large_above_eight_mib(self) -> None: | ||
| 22 | + large = {"payload": "a" * (protocol.MAX_FRAME_BYTES + 16)} | ||
| 23 | + with self.assertRaises(protocol.CapabilityError) as raised: | ||
| 24 | + protocol.encode_frame(large) | ||
| 25 | + self.assertEqual( | ||
| 26 | + raised.exception.code, | ||
| 27 | + "frame_too_large", | ||
| 28 | + "8 MiB ustu cerceve 'frame_too_large' kodu ile reddedilmeli", | ||
| 29 | + ) | ||
| 30 | + | ||
| 31 | + def test_round_trip_survives_split_across_chunk_boundary(self) -> None: | ||
| 32 | + message = protocol.build_hello("podcast", ["podcast.submit"], "gizli", 2) | ||
| 33 | + | ||
| 34 | + async def round_trip() -> object: | ||
| 35 | + stream = protocol.FrameStream() | ||
| 36 | + encoded = protocol.encode_frame(message) | ||
| 37 | + stream.feed(encoded[:3], end=False) | ||
| 38 | + stream.feed(encoded[3:7], end=False) | ||
| 39 | + stream.feed(encoded[7:], end=True) | ||
| 40 | + return await stream.read_frame() | ||
| 41 | + | ||
| 42 | + self.assertEqual( | ||
| 43 | + asyncio.run(round_trip()), | ||
| 44 | + message, | ||
| 45 | + "cerceve parcali beslendiginde gidis-donus bozulmamali", | ||
| 46 | + ) | ||
| 47 | + | ||
| 48 | + def test_declared_length_above_limit_is_rejected_before_body_read(self) -> None: | ||
| 49 | + async def run() -> None: | ||
| 50 | + stream = protocol.FrameStream() | ||
| 51 | + stream.feed(struct.pack(">I", protocol.MAX_FRAME_BYTES + 1), end=True) | ||
| 52 | + await stream.read_frame() | ||
| 53 | + | ||
| 54 | + with self.assertRaises(protocol.CapabilityError) as raised: | ||
| 55 | + asyncio.run(run()) | ||
| 56 | + self.assertEqual(raised.exception.code, "frame_too_large") | ||
| 57 | + | ||
| 58 | + def test_truncated_frame_raises_eof_not_silent_none(self) -> None: | ||
| 59 | + async def run() -> None: | ||
| 60 | + stream = protocol.FrameStream() | ||
| 61 | + stream.feed(struct.pack(">I", 32) + b"{", end=True) | ||
| 62 | + await stream.read_frame() | ||
| 63 | + | ||
| 64 | + with self.assertRaises(EOFError): | ||
| 65 | + asyncio.run(run()) | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +class HelloAndGreetingTests(unittest.TestCase): | ||
| 69 | + def test_hello_carries_protocol_service_capabilities_token_and_concurrency(self) -> None: | ||
| 70 | + hello = protocol.build_hello("podcast", ["a", "b"], "sir", 3) | ||
| 71 | + self.assertEqual( | ||
| 72 | + hello, | ||
| 73 | + { | ||
| 74 | + "protocol": protocol.PROTOCOL, | ||
| 75 | + "service": "podcast", | ||
| 76 | + "capabilities": ["a", "b"], | ||
| 77 | + "token": "sir", | ||
| 78 | + "max_concurrent": 3, | ||
| 79 | + }, | ||
| 80 | + ) | ||
| 81 | + | ||
| 82 | + def test_protocol_identifier_is_hab_one(self) -> None: | ||
| 83 | + self.assertEqual(protocol.PROTOCOL, "hab/1", "kablo sozlesmesi kimligi degismemeli") | ||
| 84 | + | ||
| 85 | + def test_welcome_greeting_returns_worker_id(self) -> None: | ||
| 86 | + greeting = {"type": "welcome", "worker_id": "w7", "protocol": protocol.PROTOCOL} | ||
| 87 | + self.assertEqual(protocol.parse_greeting(greeting), "w7") | ||
| 88 | + | ||
| 89 | + def test_welcome_with_wrong_protocol_is_rejected_as_unsupported_protocol(self) -> None: | ||
| 90 | + with self.assertRaises(protocol.HandshakeRejected) as raised: | ||
| 91 | + protocol.parse_greeting({"type": "welcome", "protocol": "hab/9"}) | ||
| 92 | + self.assertEqual(raised.exception.code, "unsupported_protocol") | ||
| 93 | + | ||
| 94 | + def test_non_welcome_greeting_propagates_backend_error_code(self) -> None: | ||
| 95 | + with self.assertRaises(protocol.HandshakeRejected) as raised: | ||
| 96 | + protocol.parse_greeting({"code": "unauthorized", "message": "kotu token"}) | ||
| 97 | + self.assertEqual(raised.exception.code, "unauthorized") | ||
| 98 | + | ||
| 99 | + def test_non_object_greeting_is_rejected_as_malformed(self) -> None: | ||
| 100 | + for greeting in ([], "welcome", 3, None): | ||
| 101 | + with self.subTest(greeting=greeting): | ||
| 102 | + with self.assertRaises(protocol.HandshakeRejected) as raised: | ||
| 103 | + protocol.parse_greeting(greeting) | ||
| 104 | + self.assertEqual(raised.exception.code, "malformed") | ||
| 105 | + | ||
| 106 | + | ||
| 107 | +class ResponseShapeTests(unittest.TestCase): | ||
| 108 | + def test_ok_response_shape(self) -> None: | ||
| 109 | + self.assertEqual( | ||
| 110 | + protocol.ok_response("r1", {"job_id": "J"}), | ||
| 111 | + {"status": "ok", "id": "r1", "payload": {"job_id": "J"}}, | ||
| 112 | + ) | ||
| 113 | + | ||
| 114 | + def test_err_response_shape(self) -> None: | ||
| 115 | + self.assertEqual( | ||
| 116 | + protocol.err_response("r1", "busy", "dolu"), | ||
| 117 | + {"status": "err", "id": "r1", "code": "busy", "message": "dolu"}, | ||
| 118 | + ) | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +class RequestParsingTests(unittest.TestCase): | ||
| 122 | + def test_valid_request_is_unpacked(self) -> None: | ||
| 123 | + parsed = protocol.parse_request( | ||
| 124 | + {"id": "r1", "capability": "podcast.status", "payload": {"job_id": "J"}} | ||
| 125 | + ) | ||
| 126 | + self.assertEqual(parsed[0], "r1") | ||
| 127 | + self.assertEqual(parsed[1], "podcast.status") | ||
| 128 | + self.assertEqual(parsed[2], {"job_id": "J"}) | ||
| 129 | + self.assertIsNone(parsed[3], "deadline_ms yoksa zaman asimi None olmali") | ||
| 130 | + | ||
| 131 | + def test_unparseable_frames_raise_bad_request(self) -> None: | ||
| 132 | + for frame in ( | ||
| 133 | + [], | ||
| 134 | + "istek", | ||
| 135 | + None, | ||
| 136 | + {}, | ||
| 137 | + {"id": 7, "capability": "podcast.status"}, | ||
| 138 | + {"id": "r1", "capability": 7}, | ||
| 139 | + {"capability": "podcast.status"}, | ||
| 140 | + {"id": "r1"}, | ||
| 141 | + ): | ||
| 142 | + with self.subTest(frame=frame): | ||
| 143 | + with self.assertRaises(protocol.CapabilityError) as raised: | ||
| 144 | + protocol.parse_request(frame) | ||
| 145 | + self.assertEqual( | ||
| 146 | + raised.exception.code, | ||
| 147 | + "bad_request", | ||
| 148 | + "ayristirilamayan istek 'bad_request' ile reddedilmeli", | ||
| 149 | + ) | ||
| 150 | + | ||
| 151 | + def test_deadline_margin_is_subtracted_so_answer_beats_backend_timeout(self) -> None: | ||
| 152 | + timeout = protocol.parse_request( | ||
| 153 | + {"id": "r1", "capability": "podcast.status", "deadline_ms": 60000} | ||
| 154 | + )[3] | ||
| 155 | + self.assertIsNotNone(timeout) | ||
| 156 | + self.assertLess( | ||
| 157 | + timeout, 60.0, "deadline payi birakilmali; cevap backend'in tavanindan once gitmeli" | ||
| 158 | + ) | ||
| 159 | + self.assertAlmostEqual(timeout, 60.0 - protocol.DEADLINE_MARGIN_SECS, places=6) | ||
| 160 | + | ||
| 161 | + def test_short_deadline_keeps_at_least_half_the_budget(self) -> None: | ||
| 162 | + timeout = protocol.parse_request( | ||
| 163 | + {"id": "r1", "capability": "podcast.status", "deadline_ms": 100} | ||
| 164 | + )[3] | ||
| 165 | + self.assertAlmostEqual(timeout, 0.05, places=6) | ||
| 166 | + self.assertGreater(timeout, 0.0, "kisa deadline negatif zaman asimi uretmemeli") | ||
| 167 | + | ||
| 168 | + def test_non_positive_or_boolean_deadline_yields_no_timeout(self) -> None: | ||
| 169 | + for value in (0, -1, True, False, "60000", None, [60000]): | ||
| 170 | + with self.subTest(deadline_ms=value): | ||
| 171 | + self.assertIsNone( | ||
| 172 | + protocol.parse_request( | ||
| 173 | + {"id": "r1", "capability": "podcast.status", "deadline_ms": value} | ||
| 174 | + )[3] | ||
| 175 | + ) | ||
| 176 | + | ||
| 177 | + | ||
| 178 | +class ConstantTests(unittest.TestCase): | ||
| 179 | + def test_wire_constants_match_the_documented_contract(self) -> None: | ||
| 180 | + self.assertEqual(protocol.MAX_FRAME_BYTES, 8 * 1024 * 1024) | ||
| 181 | + self.assertEqual(protocol.CERTIFICATE_PATH, "/ai/certificate") | ||
| 182 | + self.assertEqual(protocol.KEEPALIVE_SECS, 10) | ||
| 183 | + self.assertEqual(protocol.IDLE_TIMEOUT_SECS, 30.0) | ||
| 184 | + self.assertLess( | ||
| 185 | + protocol.KEEPALIVE_SECS, | ||
| 186 | + protocol.IDLE_TIMEOUT_SECS, | ||
| 187 | + "keepalive araligi idle timeout'tan kisa olmali", | ||
| 188 | + ) | ||
| 189 | + | ||
| 190 | + | ||
| 191 | +if __name__ == "__main__": | ||
| 192 | + unittest.main() | ||
tools/api_probe.pyadded+64 -0
| @@ -0,0 +1,64 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import argparse | ||
| 4 | +import asyncio | ||
| 5 | +import os | ||
| 6 | +import sys | ||
| 7 | + | ||
| 8 | +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +def build_parser() -> argparse.ArgumentParser: | ||
| 12 | + parser = argparse.ArgumentParser( | ||
| 13 | + description="Gercek backend'e ApiRequest atar (tani araci, uretim yolu DEGIL)" | ||
| 14 | + ) | ||
| 15 | + parser.add_argument("--path", default="/auth/me") | ||
| 16 | + parser.add_argument("--query", default="") | ||
| 17 | + parser.add_argument("--on-behalf-of", default="") | ||
| 18 | + return parser | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +async def run_probe(args) -> int: | ||
| 22 | + from functools import partial | ||
| 23 | + | ||
| 24 | + from aioquic.asyncio.client import connect | ||
| 25 | + | ||
| 26 | + from src import bridge, capabilities, config, jobs, protocol | ||
| 27 | + | ||
| 28 | + settings = config.load(require_token=True) | ||
| 29 | + store = jobs.JobStore(root=settings.job_root, workers=1, max_jobs=2) | ||
| 30 | + capabilities.configure(store, settings.has_llm_key) | ||
| 31 | + | ||
| 32 | + cert = bridge.fetch_certificate(settings.backend_url) | ||
| 33 | + quic_config = bridge.build_quic_configuration(settings, cert) | ||
| 34 | + create = partial(bridge.BridgeProtocol, settings=settings) | ||
| 35 | + async with connect( | ||
| 36 | + settings.host, settings.port, configuration=quic_config, create_protocol=create | ||
| 37 | + ) as connection: | ||
| 38 | + await connection.wait_connected() | ||
| 39 | + await connection.register() | ||
| 40 | + try: | ||
| 41 | + response = await connection.api_get( | ||
| 42 | + args.path, args.query or None, args.on_behalf_of or None | ||
| 43 | + ) | ||
| 44 | + except protocol.ApiRefused as exc: | ||
| 45 | + print(f"[api] KOPRU REDDETTI code={exc.code} :: {exc}", flush=True) | ||
| 46 | + return 1 | ||
| 47 | + print(f"[api] yol = {args.path}", flush=True) | ||
| 48 | + print(f"[api] status = {response.status}", flush=True) | ||
| 49 | + print(f"[api] basarili = {response.ok}", flush=True) | ||
| 50 | + print(f"[api] body = {str(response.body)[:300]}", flush=True) | ||
| 51 | + store.shutdown() | ||
| 52 | + return 0 | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +def main() -> int: | ||
| 56 | + args = build_parser().parse_args() | ||
| 57 | + try: | ||
| 58 | + return asyncio.run(run_probe(args)) | ||
| 59 | + except KeyboardInterrupt: | ||
| 60 | + return 0 | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +if __name__ == "__main__": | ||
| 64 | + sys.exit(main()) | ||
tools/dependency_scanner.pyadded+118 -0
| @@ -0,0 +1,118 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import argparse | ||
| 4 | +import ast | ||
| 5 | +import importlib.util | ||
| 6 | +import os | ||
| 7 | +import re | ||
| 8 | +import sys | ||
| 9 | + | ||
| 10 | +LOCAL = {"router", "script", "ses", "ingest", "bilgi", "config", "tools", "src", "tests"} | ||
| 11 | + | ||
| 12 | +ALIASES = { | ||
| 13 | + "PIL": "pillow", | ||
| 14 | + "pdfminer": "pdfminer.six", | ||
| 15 | + "lingua": "lingua_language_detector", | ||
| 16 | + "faster_whisper": "faster_whisper", | ||
| 17 | + "yaml": "pyyaml", | ||
| 18 | + "sklearn": "scikit_learn", | ||
| 19 | + "cv2": "opencv_python_headless", | ||
| 20 | +} | ||
| 21 | + | ||
| 22 | +DELIBERATELY_ABSENT = { | ||
| 23 | + "fitz": "PyMuPDF AGPL-3.0 - ingest/backends/mupdf.py, try icinde", | ||
| 24 | + "espeakng_loader": "GPL-3.0 - ses/motor.py, try icinde", | ||
| 25 | + "rapidocr_onnxruntime": "opsiyonel OCR backend B - ingest/ocr.py, try icinde", | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def top_module(name: str) -> str: | ||
| 30 | + return name.split(".")[0] | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +def collect_imports(root: str) -> set[str]: | ||
| 34 | + found: set[str] = set() | ||
| 35 | + for directory, _, filenames in os.walk(root): | ||
| 36 | + if "__pycache__" in directory: | ||
| 37 | + continue | ||
| 38 | + for filename in filenames: | ||
| 39 | + if not filename.endswith(".py"): | ||
| 40 | + continue | ||
| 41 | + path = os.path.join(directory, filename) | ||
| 42 | + try: | ||
| 43 | + tree = ast.parse(open(path, encoding="utf-8").read()) | ||
| 44 | + except (OSError, SyntaxError, UnicodeDecodeError): | ||
| 45 | + continue | ||
| 46 | + for node in ast.walk(tree): | ||
| 47 | + if isinstance(node, ast.Import): | ||
| 48 | + for name in node.names: | ||
| 49 | + found.add(top_module(name.name)) | ||
| 50 | + elif isinstance(node, ast.ImportFrom): | ||
| 51 | + if node.level == 0 and node.module: | ||
| 52 | + found.add(top_module(node.module)) | ||
| 53 | + return found | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +def declared_packages(root: str) -> set[str]: | ||
| 57 | + names: set[str] = set() | ||
| 58 | + for filename in os.listdir(root): | ||
| 59 | + if not (filename.startswith("requirements") and filename.endswith(".txt")): | ||
| 60 | + continue | ||
| 61 | + for line in open(os.path.join(root, filename), encoding="utf-8"): | ||
| 62 | + line = line.split("#")[0].strip() | ||
| 63 | + if not line or line.startswith("-"): | ||
| 64 | + continue | ||
| 65 | + name = re.split(r"[=<>!\[;]", line)[0].strip() | ||
| 66 | + if name: | ||
| 67 | + names.add(name.lower().replace("-", "_").replace(".", "_")) | ||
| 68 | + return names | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def main() -> int: | ||
| 72 | + parser = argparse.ArgumentParser( | ||
| 73 | + description="Hattin import ettigi ama beyan edilmeyen bagimliliklari bulur" | ||
| 74 | + ) | ||
| 75 | + parser.add_argument("root", nargs="?", default="vendor/pipeline") | ||
| 76 | + parser.add_argument("--strict", action="store_true") | ||
| 77 | + args = parser.parse_args() | ||
| 78 | + | ||
| 79 | + if not os.path.isdir(args.root): | ||
| 80 | + print("[scanner] HATA: dizin yok: %s" % args.root, flush=True) | ||
| 81 | + return 2 | ||
| 82 | + | ||
| 83 | + used = collect_imports(args.root) | ||
| 84 | + declared = declared_packages(args.root) | ||
| 85 | + stdlib = getattr(sys, "stdlib_module_names", frozenset()) | ||
| 86 | + | ||
| 87 | + missing = [] | ||
| 88 | + transitive = [] | ||
| 89 | + for module in sorted(used): | ||
| 90 | + if module in LOCAL or module in stdlib or module in DELIBERATELY_ABSENT: | ||
| 91 | + continue | ||
| 92 | + package = ALIASES.get(module, module).lower().replace("-", "_").replace(".", "_") | ||
| 93 | + if package in declared or module.lower().replace("-", "_") in declared: | ||
| 94 | + continue | ||
| 95 | + if importlib.util.find_spec(module) is not None: | ||
| 96 | + transitive.append(module) | ||
| 97 | + continue | ||
| 98 | + missing.append(module) | ||
| 99 | + | ||
| 100 | + print("[scanner] kok=%s import=%d beyan=%d" % (args.root, len(used), len(declared)), flush=True) | ||
| 101 | + for module, reason in sorted(DELIBERATELY_ABSENT.items()): | ||
| 102 | + if module in used: | ||
| 103 | + print("[scanner] bilerek yok: %-22s %s" % (module, reason), flush=True) | ||
| 104 | + if transitive: | ||
| 105 | + print("[scanner] beyan yok ama KURULU (gecisli): %s" % ", ".join(transitive), flush=True) | ||
| 106 | + print("[scanner] bunlar baska bir paket uzerinden geliyor; pin YOK, kirilgan.", flush=True) | ||
| 107 | + if missing: | ||
| 108 | + print("[scanner] BEYAN EDILMEMIS VE KURULU DEGIL: %s" % ", ".join(missing), flush=True) | ||
| 109 | + print("[scanner] kod bunlari import ediyor, ortamda YOK -> calisma-zamani hatasi.", flush=True) | ||
| 110 | + return 1 | ||
| 111 | + if transitive and args.strict: | ||
| 112 | + return 1 | ||
| 113 | + print("[scanner] TAMAM: eksik bagimlilik yok", flush=True) | ||
| 114 | + return 0 | ||
| 115 | + | ||
| 116 | + | ||
| 117 | +if __name__ == "__main__": | ||
| 118 | + sys.exit(main()) | ||
tools/fuzz_test.pyadded+453 -0
| @@ -0,0 +1,453 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import argparse | ||
| 4 | +import asyncio | ||
| 5 | +import json | ||
| 6 | +import random | ||
| 7 | +import struct | ||
| 8 | +import sys | ||
| 9 | +import traceback | ||
| 10 | +from pathlib import Path | ||
| 11 | + | ||
| 12 | +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) | ||
| 13 | + | ||
| 14 | +from src import capabilities, protocol | ||
| 15 | + | ||
| 16 | +LONG = 70000 | ||
| 17 | +CONTROL = "".join(chr(c) for c in range(32)) | ||
| 18 | + | ||
| 19 | +CATEGORY_STRINGS = { | ||
| 20 | + "uzunluk": [ | ||
| 21 | + "", | ||
| 22 | + " ", | ||
| 23 | + "A", | ||
| 24 | + "A" * 255, | ||
| 25 | + "A" * 65535, | ||
| 26 | + "A" * LONG, | ||
| 27 | + "\u00e7" * 40000, | ||
| 28 | + "\U0001f600" * 20000, | ||
| 29 | + ], | ||
| 30 | + "sayi_sinirlari": [ | ||
| 31 | + "0", | ||
| 32 | + "-0", | ||
| 33 | + "-1", | ||
| 34 | + "2147483647", | ||
| 35 | + "-2147483648", | ||
| 36 | + "9223372036854775807", | ||
| 37 | + "-9223372036854775808", | ||
| 38 | + "18446744073709551616", | ||
| 39 | + "1e309", | ||
| 40 | + "-1e309", | ||
| 41 | + "0.1", | ||
| 42 | + "NaN", | ||
| 43 | + "Infinity", | ||
| 44 | + "-Infinity", | ||
| 45 | + ], | ||
| 46 | + "ozel_degerler": [ | ||
| 47 | + "\x00", | ||
| 48 | + "abc\x00def", | ||
| 49 | + "\n", | ||
| 50 | + "\r\n", | ||
| 51 | + "satir\nikinci", | ||
| 52 | + "\x1a", | ||
| 53 | + "\x04", | ||
| 54 | + "\ufeff", | ||
| 55 | + "\u202e", | ||
| 56 | + "null", | ||
| 57 | + "None", | ||
| 58 | + "undefined", | ||
| 59 | + "true", | ||
| 60 | + ], | ||
| 61 | + "bicimlendirici": [ | ||
| 62 | + "%s", | ||
| 63 | + "%x", | ||
| 64 | + "%n", | ||
| 65 | + "%s%s%s%s%s%s%s%s", | ||
| 66 | + "%n%n%n%n", | ||
| 67 | + "{}", | ||
| 68 | + "{0}", | ||
| 69 | + "{job_id}", | ||
| 70 | + "${jndi:ldap://x}", | ||
| 71 | + "%%d", | ||
| 72 | + ], | ||
| 73 | + "noktalama": [ | ||
| 74 | + ";", | ||
| 75 | + "'", | ||
| 76 | + '"', | ||
| 77 | + "\\", | ||
| 78 | + "/", | ||
| 79 | + "../", | ||
| 80 | + "../../../../etc/passwd", | ||
| 81 | + "..\\..\\windows\\system32", | ||
| 82 | + "a';--", | ||
| 83 | + "`ls`", | ||
| 84 | + "$(ls)", | ||
| 85 | + "|ls", | ||
| 86 | + "<script>", | ||
| 87 | + "&", | ||
| 88 | + CONTROL, | ||
| 89 | + ], | ||
| 90 | + "anahtar_kelimeler": [ | ||
| 91 | + "halt", | ||
| 92 | + "return", | ||
| 93 | + "DROP TABLES", | ||
| 94 | + "DROP TABLE jobs;--", | ||
| 95 | + "tek_ogretici", | ||
| 96 | + "ogrenci_hoca", | ||
| 97 | + "duz_okuma", | ||
| 98 | + "podcast.submit", | ||
| 99 | + "podcast.cancel", | ||
| 100 | + "welcome", | ||
| 101 | + "ok", | ||
| 102 | + "err", | ||
| 103 | + protocol.PROTOCOL, | ||
| 104 | + "hab/2", | ||
| 105 | + "__init__", | ||
| 106 | + "__class__", | ||
| 107 | + "..", | ||
| 108 | + ], | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +CATEGORY_SCALARS = { | ||
| 112 | + "uzunluk": [[], {}, [[]] * 200], | ||
| 113 | + "sayi_sinirlari": [ | ||
| 114 | + 0, | ||
| 115 | + -1, | ||
| 116 | + 1, | ||
| 117 | + 2**31 - 1, | ||
| 118 | + -(2**31), | ||
| 119 | + 2**63 - 1, | ||
| 120 | + -(2**63), | ||
| 121 | + 2**70, | ||
| 122 | + -(2**70), | ||
| 123 | + 0.0, | ||
| 124 | + -0.0, | ||
| 125 | + 1e308, | ||
| 126 | + -1e308, | ||
| 127 | + float("inf"), | ||
| 128 | + float("-inf"), | ||
| 129 | + float("nan"), | ||
| 130 | + True, | ||
| 131 | + False, | ||
| 132 | + ], | ||
| 133 | + "ozel_degerler": [None], | ||
| 134 | + "bicimlendirici": [], | ||
| 135 | + "noktalama": [], | ||
| 136 | + "anahtar_kelimeler": [], | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +SEED_FRAMES = [ | ||
| 140 | + {"id": "01SEED", "capability": "podcast.submit", | ||
| 141 | + "payload": {"file_id": "01FILE", "format": "duz_okuma"}, "deadline_ms": 30000}, | ||
| 142 | + {"id": "01SEED", "capability": "podcast.status", "payload": {"job_id": "01JOB"}}, | ||
| 143 | + {"id": "01SEED", "capability": "podcast.result", "payload": {"job_id": "01JOB"}}, | ||
| 144 | + {"id": "01SEED", "capability": "podcast.cancel", "payload": {"job_id": "01JOB"}}, | ||
| 145 | +] | ||
| 146 | + | ||
| 147 | +SEED_GREETINGS = [ | ||
| 148 | + {"type": "welcome", "worker_id": "w1", "protocol": protocol.PROTOCOL}, | ||
| 149 | + {"type": "rejected", "code": "unauthorized", "message": "token"}, | ||
| 150 | +] | ||
| 151 | + | ||
| 152 | +SEED_API = [ | ||
| 153 | + {"outcome": "ok", "id": "r1", "status": 200, "body": {"role": "student"}}, | ||
| 154 | + {"outcome": "err", "id": "r1", "code": "path_not_allowed", "message": "x"}, | ||
| 155 | +] | ||
| 156 | + | ||
| 157 | +GRAMMAR = { | ||
| 158 | + "frame": [["{", "pairs", "}"], ["value"]], | ||
| 159 | + "pairs": [["pair"], ["pair", ",", "pairs"]], | ||
| 160 | + "pair": [["key", ":", "value"]], | ||
| 161 | + "key": [['"id"'], ['"capability"'], ['"payload"'], ['"deadline_ms"'], | ||
| 162 | + ['"outcome"'], ['"status"'], ['"type"'], ['"protocol"'], ['"body"']], | ||
| 163 | + "value": [["scalar"], ["{", "pairs", "}"], ["[", "items", "]"]], | ||
| 164 | + "items": [["value"], ["value", ",", "items"]], | ||
| 165 | + "scalar": [["null"], ["true"], ["false"], ["0"], ["-1"], ["1e309"], | ||
| 166 | + ['""'], ['"x"'], ['"tek_ogretici"'], ["{}"], ["[]"]], | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | + | ||
| 170 | +def derive(rng: random.Random, symbol: str = "frame", depth: int = 0) -> str: | ||
| 171 | + if depth > 6 or symbol not in GRAMMAR: | ||
| 172 | + return symbol | ||
| 173 | + rule = rng.choice(GRAMMAR[symbol]) | ||
| 174 | + return "".join(derive(rng, part, depth + 1) for part in rule) | ||
| 175 | + | ||
| 176 | + | ||
| 177 | +def mutate_value(rng: random.Random, value, pool: list): | ||
| 178 | + roll = rng.random() | ||
| 179 | + if roll < 0.35: | ||
| 180 | + return rng.choice(pool) | ||
| 181 | + if roll < 0.5: | ||
| 182 | + return None | ||
| 183 | + if roll < 0.65 and isinstance(value, str): | ||
| 184 | + if not value: | ||
| 185 | + return rng.choice(pool) | ||
| 186 | + cut = rng.randrange(len(value)) | ||
| 187 | + return value[:cut] + str(rng.choice(pool[:8]))[:8] + value[cut + 1:] | ||
| 188 | + if roll < 0.8: | ||
| 189 | + return [value] | ||
| 190 | + if roll < 0.9: | ||
| 191 | + return {"nested": value} | ||
| 192 | + return value | ||
| 193 | + | ||
| 194 | + | ||
| 195 | +def mutate_frame(rng: random.Random, seed: dict, pool: list): | ||
| 196 | + frame = json.loads(json.dumps(seed, default=str)) | ||
| 197 | + action = rng.randrange(5) | ||
| 198 | + keys = list(frame.keys()) | ||
| 199 | + if action == 0 and keys: | ||
| 200 | + del frame[rng.choice(keys)] | ||
| 201 | + elif action == 1 and keys: | ||
| 202 | + target = rng.choice(keys) | ||
| 203 | + frame[target] = mutate_value(rng, frame[target], pool) | ||
| 204 | + elif action == 2: | ||
| 205 | + frame[str(rng.choice(pool))[:40]] = rng.choice(pool) | ||
| 206 | + elif action == 3 and isinstance(frame.get("payload"), dict): | ||
| 207 | + inner = frame["payload"] | ||
| 208 | + inner_keys = list(inner.keys()) | ||
| 209 | + if inner_keys: | ||
| 210 | + target = rng.choice(inner_keys) | ||
| 211 | + inner[target] = mutate_value(rng, inner[target], pool) | ||
| 212 | + else: | ||
| 213 | + return rng.choice([frame, [frame], rng.choice(pool)]) | ||
| 214 | + return frame | ||
| 215 | + | ||
| 216 | + | ||
| 217 | +def mutate_bytes(rng: random.Random, blob: bytes) -> bytes: | ||
| 218 | + if not blob: | ||
| 219 | + return b"\x00" | ||
| 220 | + data = bytearray(blob) | ||
| 221 | + for _ in range(rng.randrange(1, 5)): | ||
| 222 | + action = rng.randrange(4) | ||
| 223 | + if not data: | ||
| 224 | + break | ||
| 225 | + index = rng.randrange(len(data)) | ||
| 226 | + if action == 0: | ||
| 227 | + data[index] = rng.randrange(256) | ||
| 228 | + elif action == 1: | ||
| 229 | + del data[index] | ||
| 230 | + elif action == 2: | ||
| 231 | + data.insert(index, rng.randrange(256)) | ||
| 232 | + else: | ||
| 233 | + data[index] ^= 1 << rng.randrange(8) | ||
| 234 | + return bytes(data) | ||
| 235 | + | ||
| 236 | + | ||
| 237 | +class Tracer: | ||
| 238 | + def __init__(self, suffixes: tuple[str, ...]) -> None: | ||
| 239 | + self.suffixes = suffixes | ||
| 240 | + self.seen: set[tuple[str, int]] = set() | ||
| 241 | + self.fresh: set[tuple[str, int]] = set() | ||
| 242 | + | ||
| 243 | + def _trace(self, frame, event, arg): | ||
| 244 | + if event != "line": | ||
| 245 | + return self._trace | ||
| 246 | + name = frame.f_code.co_filename | ||
| 247 | + if not name.endswith(self.suffixes): | ||
| 248 | + return self._trace | ||
| 249 | + point = (name, frame.f_lineno) | ||
| 250 | + if point not in self.seen: | ||
| 251 | + self.seen.add(point) | ||
| 252 | + self.fresh.add(point) | ||
| 253 | + return self._trace | ||
| 254 | + | ||
| 255 | + def watch(self, call): | ||
| 256 | + self.fresh = set() | ||
| 257 | + previous = sys.gettrace() | ||
| 258 | + sys.settrace(self._trace) | ||
| 259 | + try: | ||
| 260 | + return call() | ||
| 261 | + finally: | ||
| 262 | + sys.settrace(previous) | ||
| 263 | + | ||
| 264 | + | ||
| 265 | +class Report: | ||
| 266 | + def __init__(self) -> None: | ||
| 267 | + self.runs = 0 | ||
| 268 | + self.coverage = 0 | ||
| 269 | + self.findings: list[dict] = [] | ||
| 270 | + self.by_category: dict[str, int] = {} | ||
| 271 | + self.seen: set[tuple[str, str, str]] = set() | ||
| 272 | + | ||
| 273 | + def note(self, surface: str, category: str, payload, exc: BaseException) -> None: | ||
| 274 | + try: | ||
| 275 | + where = traceback.extract_tb(exc.__traceback__)[-1].name | ||
| 276 | + except Exception: | ||
| 277 | + where = "?" | ||
| 278 | + signature = (surface, type(exc).__name__, where) | ||
| 279 | + if signature in self.seen: | ||
| 280 | + return | ||
| 281 | + self.seen.add(signature) | ||
| 282 | + try: | ||
| 283 | + shown = repr(payload) | ||
| 284 | + except Exception: | ||
| 285 | + shown = "<repr basarisiz>" | ||
| 286 | + if len(shown) > 240: | ||
| 287 | + shown = shown[:240] + "...(kirpildi)" | ||
| 288 | + self.findings.append({ | ||
| 289 | + "surface": surface, | ||
| 290 | + "category": category, | ||
| 291 | + "exception": type(exc).__name__, | ||
| 292 | + "message": str(exc)[:200], | ||
| 293 | + "where": where, | ||
| 294 | + "input": shown, | ||
| 295 | + }) | ||
| 296 | + | ||
| 297 | + | ||
| 298 | +ALLOWED_REQUEST = (protocol.CapabilityError, ValueError, EOFError) | ||
| 299 | +ALLOWED_GREETING = (protocol.HandshakeRejected, ValueError, EOFError) | ||
| 300 | +ALLOWED_API = (protocol.ApiRefused, ValueError, EOFError) | ||
| 301 | +ALLOWED_DISPATCH = (protocol.CapabilityError,) | ||
| 302 | + | ||
| 303 | + | ||
| 304 | +def probe(report: Report, surface: str, category: str, payload, call, | ||
| 305 | + allowed: tuple, tracer: Tracer) -> bool: | ||
| 306 | + report.runs += 1 | ||
| 307 | + report.by_category[category] = report.by_category.get(category, 0) + 1 | ||
| 308 | + try: | ||
| 309 | + tracer.watch(call) | ||
| 310 | + except allowed: | ||
| 311 | + pass | ||
| 312 | + except RecursionError: | ||
| 313 | + pass | ||
| 314 | + except BaseException as exc: | ||
| 315 | + report.note(surface, category, payload, exc) | ||
| 316 | + return bool(tracer.fresh) | ||
| 317 | + | ||
| 318 | + | ||
| 319 | +def read_frame_bytes(blob: bytes): | ||
| 320 | + async def run(): | ||
| 321 | + stream = protocol.FrameStream() | ||
| 322 | + stream.feed(blob, end=True) | ||
| 323 | + return await stream.read_frame() | ||
| 324 | + | ||
| 325 | + return asyncio.run(run()) | ||
| 326 | + | ||
| 327 | + | ||
| 328 | +def fuzz(cases: int, seed: int, verbose: bool) -> Report: | ||
| 329 | + rng = random.Random(seed) | ||
| 330 | + report = Report() | ||
| 331 | + tracer = Tracer(("protocol.py", "capabilities.py")) | ||
| 332 | + pool: list = [] | ||
| 333 | + for name, values in CATEGORY_STRINGS.items(): | ||
| 334 | + pool.extend(values) | ||
| 335 | + pool.extend(CATEGORY_SCALARS.get(name, [])) | ||
| 336 | + corpus = list(SEED_FRAMES) | ||
| 337 | + byte_corpus = [protocol.encode_frame(f) for f in SEED_FRAMES] | ||
| 338 | + | ||
| 339 | + for name, values in CATEGORY_STRINGS.items(): | ||
| 340 | + every = list(values) + list(CATEGORY_SCALARS.get(name, [])) | ||
| 341 | + for value in every: | ||
| 342 | + for field in ("id", "capability", "payload", "deadline_ms"): | ||
| 343 | + frame = dict(SEED_FRAMES[0]) | ||
| 344 | + frame[field] = value | ||
| 345 | + probe(report, "parse_request", name, frame, | ||
| 346 | + lambda f=frame: protocol.parse_request(f), ALLOWED_REQUEST, tracer) | ||
| 347 | + for field in ("type", "protocol", "worker_id", "code"): | ||
| 348 | + greeting = dict(SEED_GREETINGS[0]) | ||
| 349 | + greeting[field] = value | ||
| 350 | + probe(report, "parse_greeting", name, greeting, | ||
| 351 | + lambda g=greeting: protocol.parse_greeting(g), ALLOWED_GREETING, tracer) | ||
| 352 | + for field in ("outcome", "id", "status", "body", "code"): | ||
| 353 | + answer = dict(SEED_API[0]) | ||
| 354 | + answer[field] = value | ||
| 355 | + probe(report, "parse_api_response", name, answer, | ||
| 356 | + lambda a=answer: protocol.parse_api_response(a), ALLOWED_API, tracer) | ||
| 357 | + probe(report, "encode_frame", name, value, | ||
| 358 | + lambda v=value: protocol.encode_frame({"payload": v}), | ||
| 359 | + (protocol.CapabilityError, ValueError), tracer) | ||
| 360 | + probe(report, "build_api_request", name, value, | ||
| 361 | + lambda v=value: protocol.build_api_request( | ||
| 362 | + "r", v if isinstance(v, str) else "/notes"), | ||
| 363 | + (protocol.ApiRefused, ValueError), tracer) | ||
| 364 | + for capability in capabilities.names(): | ||
| 365 | + body = {"job_id": value, "file_id": value, "format": value} | ||
| 366 | + probe(report, "dispatch", name, (capability, body), | ||
| 367 | + lambda c=capability, b=body: capabilities.dispatch(c, b), | ||
| 368 | + ALLOWED_DISPATCH, tracer) | ||
| 369 | + | ||
| 370 | + for index in range(cases): | ||
| 371 | + style = rng.randrange(4) | ||
| 372 | + if style == 0: | ||
| 373 | + candidate = mutate_frame(rng, rng.choice(corpus), pool) | ||
| 374 | + gained = probe(report, "parse_request", "sablon", candidate, | ||
| 375 | + lambda c=candidate: protocol.parse_request(c), | ||
| 376 | + ALLOWED_REQUEST, tracer) | ||
| 377 | + if gained and isinstance(candidate, dict) and len(corpus) < 400: | ||
| 378 | + corpus.append(candidate) | ||
| 379 | + elif style == 1: | ||
| 380 | + blob = mutate_bytes(rng, rng.choice(byte_corpus)) | ||
| 381 | + gained = probe(report, "read_frame", "bayt", blob, | ||
| 382 | + lambda b=blob: read_frame_bytes(b), | ||
| 383 | + ALLOWED_REQUEST + (struct.error,), tracer) | ||
| 384 | + if gained and len(byte_corpus) < 400: | ||
| 385 | + byte_corpus.append(blob) | ||
| 386 | + elif style == 2: | ||
| 387 | + text = derive(rng) | ||
| 388 | + encoded = text.encode("utf-8") | ||
| 389 | + | ||
| 390 | + def run_text(e=encoded): | ||
| 391 | + return read_frame_bytes(struct.pack(">I", len(e)) + e) | ||
| 392 | + | ||
| 393 | + gained = probe(report, "read_frame", "grammar", text, run_text, | ||
| 394 | + ALLOWED_REQUEST + (struct.error,), tracer) | ||
| 395 | + if gained and len(byte_corpus) < 400: | ||
| 396 | + byte_corpus.append(encoded) | ||
| 397 | + else: | ||
| 398 | + candidate = mutate_frame(rng, rng.choice(SEED_API), pool) | ||
| 399 | + probe(report, "parse_api_response", "sablon", candidate, | ||
| 400 | + lambda c=candidate: protocol.parse_api_response(c), | ||
| 401 | + ALLOWED_API, tracer) | ||
| 402 | + if verbose and (index + 1) % 2000 == 0: | ||
| 403 | + print(" [fuzz] %d/%d kosu, %d bulgu, %d kapsam noktasi" | ||
| 404 | + % (index + 1, cases, len(report.findings), len(tracer.seen)), flush=True) | ||
| 405 | + | ||
| 406 | + report.coverage = len(tracer.seen) | ||
| 407 | + return report | ||
| 408 | + | ||
| 409 | + | ||
| 410 | +def main() -> int: | ||
| 411 | + parser = argparse.ArgumentParser( | ||
| 412 | + description="Slayt kategorileriyle fuzzing: uzunluk, sayi sinirlari, ozel " | ||
| 413 | + "degerler, bicimlendirici, noktalama, anahtar kelimeler") | ||
| 414 | + parser.add_argument("--cases", type=int, default=20000) | ||
| 415 | + parser.add_argument("--seed", type=int, default=1) | ||
| 416 | + parser.add_argument("--quiet", action="store_true") | ||
| 417 | + parser.add_argument("--fail-on-finding", action="store_true") | ||
| 418 | + args = parser.parse_args() | ||
| 419 | + | ||
| 420 | + capabilities.configure(None, False) | ||
| 421 | + print("[fuzz] tohum : %d" % args.seed, flush=True) | ||
| 422 | + print("[fuzz] kosu : %d rastgele + tum kategori kombinasyonlari" % args.cases, | ||
| 423 | + flush=True) | ||
| 424 | + print("", flush=True) | ||
| 425 | + report = fuzz(args.cases, args.seed, not args.quiet) | ||
| 426 | + | ||
| 427 | + print("", flush=True) | ||
| 428 | + print("=" * 58, flush=True) | ||
| 429 | + print("FUZZING SONUCU", flush=True) | ||
| 430 | + print(" toplam kosu : %d" % report.runs, flush=True) | ||
| 431 | + print(" kapsanan satir : %d" % report.coverage, flush=True) | ||
| 432 | + print(" benzersiz bulgu: %d" % len(report.findings), flush=True) | ||
| 433 | + print("", flush=True) | ||
| 434 | + print(" kategori dagilimi:", flush=True) | ||
| 435 | + for name in sorted(report.by_category): | ||
| 436 | + print(" %-18s %d" % (name, report.by_category[name]), flush=True) | ||
| 437 | + if report.findings: | ||
| 438 | + print("", flush=True) | ||
| 439 | + print("BULGULAR (beyan edilmemis istisna):", flush=True) | ||
| 440 | + for item in report.findings: | ||
| 441 | + print("", flush=True) | ||
| 442 | + print(" %s / %s" % (item["surface"], item["category"]), flush=True) | ||
| 443 | + print(" istisna : %s: %s" % (item["exception"], item["message"]), flush=True) | ||
| 444 | + print(" nerede : %s" % item["where"], flush=True) | ||
| 445 | + print(" girdi : %s" % item["input"], flush=True) | ||
| 446 | + else: | ||
| 447 | + print("", flush=True) | ||
| 448 | + print(" bulgu yok: tum girdiler beyan edilen istisnalarla karsilandi", flush=True) | ||
| 449 | + return 1 if (report.findings and args.fail_on_finding) else 0 | ||
| 450 | + | ||
| 451 | + | ||
| 452 | +if __name__ == "__main__": | ||
| 453 | + sys.exit(main()) | ||
tools/mutation_test.pyadded+221 -0
| @@ -0,0 +1,221 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import argparse | ||
| 4 | +import ast | ||
| 5 | +import io | ||
| 6 | +import os | ||
| 7 | +import shutil | ||
| 8 | +import subprocess | ||
| 9 | +import sys | ||
| 10 | +import time | ||
| 11 | +import tempfile | ||
| 12 | +from pathlib import Path | ||
| 13 | + | ||
| 14 | +ROR = { | ||
| 15 | + ast.Lt: (ast.Gt, ast.LtE, ast.GtE, ast.Eq, ast.NotEq), | ||
| 16 | + ast.Gt: (ast.Lt, ast.LtE, ast.GtE, ast.Eq, ast.NotEq), | ||
| 17 | + ast.LtE: (ast.Lt, ast.Gt, ast.GtE), | ||
| 18 | + ast.GtE: (ast.Lt, ast.Gt, ast.LtE), | ||
| 19 | + ast.Eq: (ast.NotEq, ast.Lt, ast.Gt), | ||
| 20 | + ast.NotEq: (ast.Eq, ast.Lt, ast.Gt), | ||
| 21 | + ast.In: (ast.NotIn,), | ||
| 22 | + ast.NotIn: (ast.In,), | ||
| 23 | + ast.Is: (ast.IsNot,), | ||
| 24 | + ast.IsNot: (ast.Is,), | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +AOR = { | ||
| 28 | + ast.Add: (ast.Sub, ast.Mult), | ||
| 29 | + ast.Sub: (ast.Add, ast.Mult), | ||
| 30 | + ast.Mult: (ast.Add, ast.Div), | ||
| 31 | + ast.Div: (ast.Mult, ast.Sub), | ||
| 32 | + ast.Mod: (ast.Mult, ast.Div), | ||
| 33 | + ast.Pow: (ast.Mult,), | ||
| 34 | + ast.FloorDiv: (ast.Div,), | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +COR = {ast.And: ast.Or, ast.Or: ast.And} | ||
| 38 | + | ||
| 39 | +SKIP_DELETE = (ast.Return, ast.Raise, ast.Pass, ast.Import, ast.ImportFrom, | ||
| 40 | + ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef) | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +def sites(source: str) -> list[tuple[str, int, int, int, object]]: | ||
| 44 | + tree = ast.parse(source) | ||
| 45 | + found = [] | ||
| 46 | + for order, node in enumerate(ast.walk(tree)): | ||
| 47 | + if isinstance(node, ast.Compare): | ||
| 48 | + for slot, op in enumerate(node.ops): | ||
| 49 | + for new in ROR.get(type(op), ()): | ||
| 50 | + found.append(("ROR", order, slot, node.lineno, new)) | ||
| 51 | + elif isinstance(node, ast.BinOp): | ||
| 52 | + for new in AOR.get(type(node.op), ()): | ||
| 53 | + found.append(("AOR", order, 0, node.lineno, new)) | ||
| 54 | + elif isinstance(node, ast.BoolOp): | ||
| 55 | + new = COR.get(type(node.op)) | ||
| 56 | + if new is not None: | ||
| 57 | + found.append(("COR", order, 0, node.lineno, new)) | ||
| 58 | + elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not): | ||
| 59 | + found.append(("UOI", order, 0, node.lineno, None)) | ||
| 60 | + body = getattr(node, "body", None) | ||
| 61 | + if isinstance(body, list) and len(body) > 1: | ||
| 62 | + for slot, statement in enumerate(body): | ||
| 63 | + if isinstance(statement, SKIP_DELETE): | ||
| 64 | + continue | ||
| 65 | + found.append(("SDL", order, slot, statement.lineno, None)) | ||
| 66 | + return found | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +def apply(source: str, operator: str, order: int, slot: int, new) -> str | None: | ||
| 70 | + tree = ast.parse(source) | ||
| 71 | + nodes = list(ast.walk(tree)) | ||
| 72 | + if order >= len(nodes): | ||
| 73 | + return None | ||
| 74 | + node = nodes[order] | ||
| 75 | + if operator == "ROR" and isinstance(node, ast.Compare): | ||
| 76 | + node.ops[slot] = new() | ||
| 77 | + elif operator == "AOR" and isinstance(node, ast.BinOp): | ||
| 78 | + node.op = new() | ||
| 79 | + elif operator == "COR" and isinstance(node, ast.BoolOp): | ||
| 80 | + node.op = new() | ||
| 81 | + elif operator == "UOI" and isinstance(node, ast.UnaryOp): | ||
| 82 | + parent_fixed = _replace_not(tree, order) | ||
| 83 | + if not parent_fixed: | ||
| 84 | + return None | ||
| 85 | + elif operator == "SDL": | ||
| 86 | + body = getattr(node, "body", None) | ||
| 87 | + if not isinstance(body, list) or slot >= len(body): | ||
| 88 | + return None | ||
| 89 | + body.pop(slot) | ||
| 90 | + if not body: | ||
| 91 | + body.append(ast.Pass()) | ||
| 92 | + else: | ||
| 93 | + return None | ||
| 94 | + try: | ||
| 95 | + return ast.unparse(ast.fix_missing_locations(tree)) | ||
| 96 | + except Exception: | ||
| 97 | + return None | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +def _replace_not(tree: ast.AST, order: int) -> bool: | ||
| 101 | + target = list(ast.walk(tree))[order] | ||
| 102 | + | ||
| 103 | + class Drop(ast.NodeTransformer): | ||
| 104 | + def __init__(self) -> None: | ||
| 105 | + self.done = False | ||
| 106 | + | ||
| 107 | + def visit_UnaryOp(self, node: ast.UnaryOp): | ||
| 108 | + self.generic_visit(node) | ||
| 109 | + if node is target: | ||
| 110 | + self.done = True | ||
| 111 | + return node.operand | ||
| 112 | + return node | ||
| 113 | + | ||
| 114 | + dropper = Drop() | ||
| 115 | + dropper.visit(tree) | ||
| 116 | + return dropper.done | ||
| 117 | + | ||
| 118 | + | ||
| 119 | +def run_suite(workdir: Path, timeout: float, env: dict | None = None) -> str: | ||
| 120 | + try: | ||
| 121 | + done = subprocess.run( | ||
| 122 | + [sys.executable, "-m", "unittest", "discover", "-s", "tests", | ||
| 123 | + "-t", ".", "--failfast"], | ||
| 124 | + cwd=str(workdir), capture_output=True, timeout=timeout, env=env) | ||
| 125 | + except subprocess.TimeoutExpired: | ||
| 126 | + return "timeout" | ||
| 127 | + return "survived" if done.returncode == 0 else "killed" | ||
| 128 | + | ||
| 129 | + | ||
| 130 | +def time_suite(workdir: Path, timeout: float, env: dict | None = None) -> tuple: | ||
| 131 | + started = time.time() | ||
| 132 | + status = run_suite(workdir, timeout, env) | ||
| 133 | + return status, time.time() - started | ||
| 134 | + | ||
| 135 | + | ||
| 136 | +def main() -> int: | ||
| 137 | + parser = argparse.ArgumentParser( | ||
| 138 | + description="Slayt operatorleriyle mutasyon testi: ROR, AOR, COR, UOI, SDL") | ||
| 139 | + parser.add_argument("target") | ||
| 140 | + parser.add_argument("--timeout", type=float, default=180.0) | ||
| 141 | + parser.add_argument("--limit", type=int, default=0) | ||
| 142 | + args = parser.parse_args() | ||
| 143 | + | ||
| 144 | + repo = Path.cwd() | ||
| 145 | + target = Path(args.target) | ||
| 146 | + source = io.open(target, encoding="utf-8").read() | ||
| 147 | + plans = sites(source) | ||
| 148 | + if args.limit: | ||
| 149 | + plans = plans[: args.limit] | ||
| 150 | + | ||
| 151 | + print("[mutasyon] hedef : %s" % target, flush=True) | ||
| 152 | + print("[mutasyon] mutant : %d" % len(plans), flush=True) | ||
| 153 | + print("[mutasyon] operatorler : ROR AOR COR UOI SDL", flush=True) | ||
| 154 | + print("", flush=True) | ||
| 155 | + | ||
| 156 | + workdir = Path(tempfile.mkdtemp(prefix="mutasyon-")) | ||
| 157 | + for name in ("src", "tests", "tools"): | ||
| 158 | + shutil.copytree(repo / name, workdir / name, | ||
| 159 | + ignore=shutil.ignore_patterns("__pycache__")) | ||
| 160 | + env = dict(os.environ) | ||
| 161 | + vendored = repo / "vendor" / "pipeline" | ||
| 162 | + if vendored.is_dir(): | ||
| 163 | + env["PODCAST_PIPELINE_PATH"] = str(vendored) | ||
| 164 | + elif (repo.parent / "router" / "hat.py").is_file(): | ||
| 165 | + env["PODCAST_PIPELINE_PATH"] = str(repo.parent) | ||
| 166 | + baseline, baseline_secs = time_suite(workdir, args.timeout, env) | ||
| 167 | + limit = max(args.timeout, baseline_secs * 10.0) | ||
| 168 | + print("[mutasyon] temel kosu : %.1f sn, mutant siniri %.1f sn" | ||
| 169 | + % (baseline_secs, limit), flush=True) | ||
| 170 | + if baseline != "survived": | ||
| 171 | + print("[mutasyon] HATA: mutasyonsuz paket GECMIYOR (%s)" % baseline, flush=True) | ||
| 172 | + print("[mutasyon] PODCAST_PIPELINE_PATH=%s" | ||
| 173 | + % env.get("PODCAST_PIPELINE_PATH", "(yok)"), flush=True) | ||
| 174 | + shutil.rmtree(workdir, ignore_errors=True) | ||
| 175 | + return 2 | ||
| 176 | + | ||
| 177 | + tally = {"killed": 0, "survived": 0, "timeout": 0, "invalid": 0} | ||
| 178 | + alive = [] | ||
| 179 | + for index, (operator, order, slot, lineno, new) in enumerate(plans, 1): | ||
| 180 | + mutated = apply(source, operator, order, slot, new) | ||
| 181 | + if mutated is None or mutated == source: | ||
| 182 | + tally["invalid"] += 1 | ||
| 183 | + continue | ||
| 184 | + io.open(workdir / target, "w", encoding="utf-8").write(mutated) | ||
| 185 | + status = run_suite(workdir, limit, env) | ||
| 186 | + if status == "timeout": | ||
| 187 | + status = run_suite(workdir, limit * 2.0, env) | ||
| 188 | + tally[status] += 1 | ||
| 189 | + if status == "survived": | ||
| 190 | + alive.append((operator, lineno)) | ||
| 191 | + print(" [%3d/%3d] %-3s satir %-4d %s" | ||
| 192 | + % (index, len(plans), operator, lineno, status), flush=True) | ||
| 193 | + io.open(workdir / target, "w", encoding="utf-8").write(source) | ||
| 194 | + | ||
| 195 | + total = tally["killed"] + tally["survived"] + tally["timeout"] | ||
| 196 | + detected = tally["killed"] + tally["timeout"] | ||
| 197 | + print("", flush=True) | ||
| 198 | + print("=" * 58, flush=True) | ||
| 199 | + print("MUTASYON SONUCU: %s" % target, flush=True) | ||
| 200 | + print(" oldurulen : %d" % tally["killed"], flush=True) | ||
| 201 | + print(" asili kaldi: %d (sonsuz dongu; paket sonlanmayarak yakaladi)" | ||
| 202 | + % tally["timeout"], flush=True) | ||
| 203 | + print(" hayatta : %d" % tally["survived"], flush=True) | ||
| 204 | + print(" gecersiz : %d" % tally["invalid"], flush=True) | ||
| 205 | + if total: | ||
| 206 | + print(" HAM SKOR : %.1f%%" % (100.0 * detected / total), flush=True) | ||
| 207 | + print(" asili kalan mutant OLDURULMUS sayilir: paket onu sonlanmayarak", flush=True) | ||
| 208 | + print(" tespit eder (mutmut ve PIT ayni kurali kullanir).", flush=True) | ||
| 209 | + print(" slayt formulu: killed / (toplam - esdeger); esdeger ELLE isaretlenir", | ||
| 210 | + flush=True) | ||
| 211 | + if alive: | ||
| 212 | + print("", flush=True) | ||
| 213 | + print("HAYATTA KALANLAR (her biri icin karar gerekir):", flush=True) | ||
| 214 | + for operator, lineno in alive: | ||
| 215 | + print(" %-3s satir %d" % (operator, lineno), flush=True) | ||
| 216 | + shutil.rmtree(workdir, ignore_errors=True) | ||
| 217 | + return 0 | ||
| 218 | + | ||
| 219 | + | ||
| 220 | +if __name__ == "__main__": | ||
| 221 | + sys.exit(main()) | ||
tools/smoke_test.pyadded+113 -0
| @@ -0,0 +1,113 @@ | |||
| 1 | +from __future__ import annotations | ||
| 2 | + | ||
| 3 | +import argparse | ||
| 4 | +import os | ||
| 5 | +import sys | ||
| 6 | +import time | ||
| 7 | + | ||
| 8 | +DEFAULT_PIPELINE = r"C:\PROJECTS\podcast" | ||
| 9 | +DEFAULT_MEDIA = r"C:\PROJECTS\podcast\samples" | ||
| 10 | +DEFAULT_SOURCE = "kisa_slayt.pdf" | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +def build_parser() -> argparse.ArgumentParser: | ||
| 14 | + parser = argparse.ArgumentParser( | ||
| 15 | + description="Gercek hatta tek is kosturur (--validate'in parcasi DEGIL)" | ||
| 16 | + ) | ||
| 17 | + parser.add_argument("--pipeline-path", default=os.environ.get("PODCAST_PIPELINE_PATH", DEFAULT_PIPELINE)) | ||
| 18 | + parser.add_argument("--media-root", default=os.environ.get("PODCAST_MEDIA_ROOT", DEFAULT_MEDIA)) | ||
| 19 | + parser.add_argument("--source", default=DEFAULT_SOURCE) | ||
| 20 | + parser.add_argument("--format", default="duz_okuma") | ||
| 21 | + parser.add_argument("--job-root", default=os.path.join(os.getcwd(), "out", "smoke", "jobs")) | ||
| 22 | + parser.add_argument("--output-root", default=os.path.join(os.getcwd(), "out", "smoke", "output")) | ||
| 23 | + parser.add_argument("--ledger", default=os.path.join(os.getcwd(), "out", "smoke", "ledger.sqlite")) | ||
| 24 | + parser.add_argument("--timeout", type=float, default=7200.0) | ||
| 25 | + parser.add_argument("--cancel-after", type=float, default=0.0) | ||
| 26 | + return parser | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def main() -> int: | ||
| 30 | + args = build_parser().parse_args() | ||
| 31 | + | ||
| 32 | + os.environ["PODCAST_MODE"] = "real" | ||
| 33 | + os.environ["PODCAST_PIPELINE_PATH"] = args.pipeline_path | ||
| 34 | + os.environ["PODCAST_MEDIA_ROOT"] = args.media_root | ||
| 35 | + os.environ["PODCAST_JOB_ROOT"] = args.job_root | ||
| 36 | + os.environ["PODCAST_OUTPUT_ROOT"] = args.output_root | ||
| 37 | + os.environ["PODCAST_LEDGER_DB"] = args.ledger | ||
| 38 | + os.environ.setdefault("LOG_LEVEL", "debug") | ||
| 39 | + | ||
| 40 | + sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | ||
| 41 | + | ||
| 42 | + from src import capabilities, config, jobs, pipeline | ||
| 43 | + | ||
| 44 | + settings = config.load(require_token=False) | ||
| 45 | + print(f"[smoke] yapilandirma: {settings.summary()}", flush=True) | ||
| 46 | + | ||
| 47 | + try: | ||
| 48 | + runner, probe = pipeline.build_runner(settings) | ||
| 49 | + except pipeline.PipelineUnavailable as exc: | ||
| 50 | + print(f"[smoke] gercek hat yuklenemedi: {exc}", flush=True) | ||
| 51 | + return 2 | ||
| 52 | + print( | ||
| 53 | + "[smoke] defter=%s LLM=%s (%s)" | ||
| 54 | + % (args.ledger, "HAZIR" if probe["llm_ready"] else "YOK", | ||
| 55 | + probe["llm_reason"][:80]), | ||
| 56 | + flush=True, | ||
| 57 | + ) | ||
| 58 | + | ||
| 59 | + store = jobs.JobStore( | ||
| 60 | + root=settings.job_root, | ||
| 61 | + workers=1, | ||
| 62 | + max_jobs=2, | ||
| 63 | + stage_secs=0.0, | ||
| 64 | + runner=runner, | ||
| 65 | + stages=pipeline.REAL_STAGES, | ||
| 66 | + job_secs=pipeline.REAL_ETA_SECS, | ||
| 67 | + ) | ||
| 68 | + store.start() | ||
| 69 | + capabilities.configure(store, bool(probe["llm_ready"])) | ||
| 70 | + | ||
| 71 | + submitted = capabilities.dispatch( | ||
| 72 | + "podcast.submit", {"source_id": args.source, "format": args.format} | ||
| 73 | + ) | ||
| 74 | + job_id = submitted["job_id"] | ||
| 75 | + print(f"[smoke] is verildi: {job_id} eta={submitted['eta_secs']}s", flush=True) | ||
| 76 | + | ||
| 77 | + terminal = (jobs.STATE_DONE, jobs.STATE_FAILED, jobs.STATE_CANCELLED) | ||
| 78 | + began = time.monotonic() | ||
| 79 | + cancelled = False | ||
| 80 | + last = "" | ||
| 81 | + try: | ||
| 82 | + while True: | ||
| 83 | + record = store.get(job_id) | ||
| 84 | + if record["state"] in terminal: | ||
| 85 | + break | ||
| 86 | + line = f"{record['state']} {record['stage']} {record['progress']}" | ||
| 87 | + if line != last: | ||
| 88 | + print(f"[smoke] {line}", flush=True) | ||
| 89 | + last = line | ||
| 90 | + elapsed = time.monotonic() - began | ||
| 91 | + if args.cancel_after > 0 and not cancelled and elapsed >= args.cancel_after: | ||
| 92 | + print(f"[smoke] {elapsed:.0f}s sonra iptal isteniyor", flush=True) | ||
| 93 | + capabilities.dispatch("podcast.cancel", {"job_id": job_id}) | ||
| 94 | + cancelled = True | ||
| 95 | + if elapsed > args.timeout: | ||
| 96 | + print(f"[smoke] zaman asimi {args.timeout}s", flush=True) | ||
| 97 | + break | ||
| 98 | + time.sleep(1.0) | ||
| 99 | + finally: | ||
| 100 | + store.shutdown() | ||
| 101 | + | ||
| 102 | + record = store.get(job_id) | ||
| 103 | + print(f"[smoke] durum={record['state']} hata={record['error_code']}", flush=True) | ||
| 104 | + if record["state"] == jobs.STATE_DONE: | ||
| 105 | + payload = capabilities.dispatch("podcast.result", {"job_id": job_id}) | ||
| 106 | + for key in ("audio_id", "script_id", "duration_secs", "audio_ids", "script_ids"): | ||
| 107 | + print(f"[smoke] {key} = {payload.get(key)}", flush=True) | ||
| 108 | + return 0 | ||
| 109 | + return 1 | ||
| 110 | + | ||
| 111 | + | ||
| 112 | +if __name__ == "__main__": | ||
| 113 | + sys.exit(main()) | ||