forge
Explore
Log in

Don't you dare go Hollow

🔧 compose stack, hab/2 protocol and VPS deploy workflow

Browse files at this commit

e013725e3af3335d1da02896fe2e3b87a9c5ca28Ahmet Kaan GümüşParent: 559d04d
  • chore
    • 🔧 compose stack, hab/2 protocol and VPS deploy workflow
Show full message
chore: 🔧 compose stack, hab/2 protocol and VPS deploy workflow
- compose.yaml: env-file driven single service that joins the backend's
  podman network and dials QUIC 8090; no ports, no environment block, so
  nothing can shadow the operator's hezarfen_chatbot.env
- Containerfile is the single source of the deployment defaults (AI_* ENV
  block) and now CMDs the bridge; AI_BACKEND_URL points at the backend's
  own port 7656 instead of the stale 8080
- bridge.py speaks hab/2: the backend pins AI_PROTOCOL/AI_ALPN to hab/2 and
  rejects any other hello, so the bridge could never register
- deploy/: operator env example + systemd user unit (compose up --no-build
  with both --env-file arguments)
- .github/workflows/main.yml: validate ∥ build-and-test (unittest suite,
  Composefile image, release artifact) then an SSH deploy that rotates
  HEZARFEN_TAG in a deploy-owned stack.env, installs the unit, restarts and
  gates on the backend accepting the registration, rolling back on failure
.github/workflows/main.ymladded+407 -0
@@ -0,0 +1,407 @@
1+# VPS deploy, compose-style, frontend ile aynı şekil (hata toparlama ucuz olsun):
2+#
3+# Validate — katalog doğrulaması + derleme kontrolü, kendi runner'ında.
4+# Build and test — unittest süiti (regresyon eşikleri içinde), sonra repo
5+# Containerfile'ından imaj (ENV bloğu dağıtım
6+# varsayılanlarının TEK kaynağıdır) ve imaj tarball'ı +
7+# compose dosyaları koşunun artefaktı olarak yüklenir.
8+# Deploy — SSH: imajı yükle, deploy sahipli stack.env'in
9+# HEZARFEN_TAG'ini ona çevir, compose.yaml + unit'i kur,
10+# stack'i yeniden başlat, köprünün backend'e KAYIT
11+# olduğunu loglardan doğrula, olmazsa önceki tag'e dön,
12+# ardından bağımsız doğrulama.
13+#
14+# Validate ile Build and test paralel koşar; Deploy ikisi de yeşilse çalışır.
15+# Yeni bir push aynı ref'teki Validate/Build'i iptal eder; uçuştaki Deploy'u
16+# ASLA iptal etmez (iki deploy iç içe geçerse stack karışır).
17+#
18+# Bölünmenin amacı toparlama hikâyesi:
19+# * Deploy adımı düşen bir koşuda "Re-run failed jobs" SADECE ~1 dakikalık
20+# deploy işini yeniden koşar — imaj hâlâ koşunun artefaktında.
21+# * workflow_dispatch (Actions → Run workflow, ya da
22+# `gh workflow run main.yml --ref main`) süiti koşmadan en yeni yeşil
23+# build'in artefaktını deploy eder.
24+#
25+# Bir seferlik ön koşullar (workflow'un erişimi dışında):
26+# * repo secret'ları SSH_PRIVATE_KEY / SSH_HOST / SSH_USER — backend ve
27+# frontend deploy'unun kullandığı üç isim;
28+# * sunucuda `loginctl enable-linger <user>` (kullanıcı unit'leri için);
29+# * sunucuda podman + bir compose sağlayıcı (deploy ikisini de kontrol eder);
30+# * operatörün ~/hezarfen_chatbot/hezarfen_chatbot.env (0600) dosyası;
31+# * BACKEND tarafı açık olmalı: hezarfen_backend.env içinde
32+# AI_QUIC_ADDR=0.0.0.0:8090 ve AI_SHARED_TOKEN bu köprününkiyle AYNI.
33+# (127.0.0.1 yazılıysa backend yalnız kendi loopback'ine bağlanır ve köprü
34+# asla kayıt olamaz — deploy bunu logda görüp geri döner.)
35+
36+name: VPS deploy
37+
38+on:
39+ push:
40+ branches:
41+ - main
42+ # Elle yeniden deploy kapısı — yukarıdaki başlık yorumuna bakın.
43+ workflow_dispatch:
44+
45+# Deploy serileştirmesi workflow'da değil deploy işinde: yeni bir push, uçuştaki
46+# VPS değişimine dokunmadan bayat Validate/Build'i iptal edebilmeli.
47+
48+env:
49+ # systemd kullanıcı unit'i. Bkz. deploy/hezarfen_chatbot_compose.service.
50+ SERVICE: hezarfen_chatbot_compose
51+ # Deploy, SSH kullanıcısının home'u altındaki bu alt dizinde yaşar ($HOME
52+ # sunucuda çözülür, yani kullanıcı değişince yol da onunla gelir).
53+ DEPLOY_SUBDIR: hezarfen_chatbot
54+ # Köprünün ayar dosyası; deploy yalnız varlığını kontrol eder, yazmaz.
55+ ENV_FILE_NAME: hezarfen_chatbot.env
56+ # Sağlık kapısı: backend'in verdiği kayıt onayı logda bu satırdır.
57+ READY_MARKER: "kayıt başarılı"
58+ # Köprünün backend sertifikasını çektiği yol (HTTP, backend konteynerinin portu).
59+ CERT_PATH: /ai/certificate
60+
61+jobs:
62+ validate:
63+ name: Validate
64+ if: github.event_name == 'push'
65+ runs-on: ubuntu-24.04
66+ concurrency:
67+ group: ci-${{ github.workflow }}-${{ github.ref }}-validate
68+ cancel-in-progress: true
69+ steps:
70+ - name: Checkout
71+ uses: actions/checkout@v4
72+ - name: Set up Python
73+ uses: actions/setup-python@v5
74+ with:
75+ # Containerfile ile aynı satır (python:3.13-slim).
76+ python-version: "3.13"
77+ - name: Install dependencies
78+ run: pip install --requirement requirements.txt
79+ - name: Compile every module
80+ run: python -m compileall -q src tests
81+ - name: Validate the catalog
82+ run: python -m src.main --validate
83+
84+ build:
85+ name: Build and test
86+ # Pushes only: elle yeniden deploy süiti tekrar ödemek yerine en yeni yeşil
87+ # artefaktı kullanır.
88+ if: github.event_name == 'push'
89+ concurrency:
90+ group: ci-${{ github.workflow }}-${{ github.ref }}-build
91+ cancel-in-progress: true
92+ runs-on: ubuntu-24.04
93+ steps:
94+ - name: Checkout
95+ uses: actions/checkout@v4
96+ - name: Set up Python
97+ uses: actions/setup-python@v5
98+ with:
99+ python-version: "3.13"
100+ - name: Install dependencies
101+ run: pip install --requirement requirements.txt
102+
103+ # Bozuk bir build sunucuya ASLA ulaşmamalı: regresyon eşikleri
104+ # (macro-F1 ≥ 0.80, OOS recall ≥ 0.70, kapsama ≥ 0.95, gizlilik recall
105+ # = 1.0, kural precision = 1.0) bu süitin içinde yaşar.
106+ - name: Test
107+ run: python -m unittest discover -s tests -t . -v
108+
109+ # Laptop ve CI aynı Containerfile'ı kullanır: ENV bloğu ne diyorsa o
110+ # gönderilir, ayrı bir CI ikizi yok.
111+ - name: Build the image
112+ run: |
113+ set -euo pipefail
114+ docker build -f Containerfile -t localhost/hezarfen_chatbot:$GITHUB_SHA .
115+
116+ - name: Stage the release bundle
117+ run: |
118+ set -euo pipefail
119+ mkdir -p stage
120+ docker save localhost/hezarfen_chatbot:$GITHUB_SHA | gzip > stage/hezarfen_chatbot.tar.gz
121+ cp compose.yaml deploy/hezarfen_chatbot_compose.service stage/
122+ echo -n "$GITHUB_SHA" > stage/tag
123+ # Sunucuda kurulacak her şey burada olmalı; eksik parça burada,
124+ # sunucuda değil, patlar.
125+ test -f stage/hezarfen_chatbot.tar.gz
126+ test -f stage/compose.yaml
127+ test -f stage/hezarfen_chatbot_compose.service
128+ test -f stage/tag
129+ ls -l stage
130+
131+ # Deploy işi (ve elle yeniden deploy) bunu tüketir. 30 gün, dispatch
132+ # kapısının geri uzanma penceresidir.
133+ - name: Upload the release
134+ uses: actions/upload-artifact@v4
135+ with:
136+ name: release
137+ path: stage
138+ retention-days: 30
139+
140+ deploy:
141+ name: Deploy
142+ needs: [validate, build]
143+ concurrency:
144+ group: deploy
145+ cancel-in-progress: false
146+ # Push: yalnız validate VE build yeşilse — ikisi de sunucuyu kapılar.
147+ # Dispatch: iki CI işi bilerek atlanır (if'lerine bakın) ve `always()`
148+ # bu atlamanın bu kapıyı geçmesini engeller.
149+ if: >-
150+ always() &&
151+ ((needs.validate.result == 'success' && needs.build.result == 'success') ||
152+ (github.event_name == 'workflow_dispatch' &&
153+ needs.validate.result == 'skipped' &&
154+ needs.build.result == 'skipped'))
155+ runs-on: ubuntu-24.04
156+ steps:
157+ # Push deploy'u bu koşunun ürettiği ve kapıladığı sürümü alır.
158+ - name: Fetch this run's release
159+ if: github.event_name == 'push'
160+ uses: actions/download-artifact@v4
161+ with:
162+ name: release
163+ path: stage
164+
165+ # Elle yeniden deploy, BUILD işi yeşil olan en yeni koşuyu alır — en yeni
166+ # tamamen yeşil koşuyu değil: bir koşu sağlık kapısında düşmüş olabilir
167+ # ama build'i tam da geri almak istediğimiz sürümdür.
168+ - name: Find the newest green build
169+ if: github.event_name == 'workflow_dispatch'
170+ env:
171+ GH_TOKEN: ${{ github.token }}
172+ run: |
173+ set -euo pipefail
174+ run_id=""
175+ for rid in $(gh run list --workflow main.yml --branch main --event push --limit 15 --json databaseId --jq '.[].databaseId'); do
176+ if [ "$(gh run view "$rid" --json jobs --jq '.jobs[] | select(.name=="Build and test") | .conclusion')" = "success" ]; then
177+ run_id=$rid
178+ break
179+ fi
180+ done
181+ if [ -z "$run_id" ]; then
182+ echo 'no run on main has a green Build-and-test job (or its artifact has expired)' >&2
183+ exit 1
184+ fi
185+ echo "redeploying the release from run $run_id"
186+ echo "run_id=$run_id" >> "$GITHUB_ENV"
187+
188+ - name: Fetch the green release
189+ if: github.event_name == 'workflow_dispatch'
190+ uses: actions/download-artifact@v4
191+ with:
192+ name: release
193+ path: stage
194+ run-id: ${{ env.run_id }}
195+ github-token: ${{ github.token }}
196+
197+ # Dispatch yolu günler öncesine ait bir artefakt indirebilir; sunucuya
198+ # dokunmadan önce paketin bütün olduğunu yeniden kontrol et.
199+ - name: Check the release is complete
200+ run: |
201+ set -euo pipefail
202+ test -f stage/hezarfen_chatbot.tar.gz
203+ test -f stage/compose.yaml
204+ test -f stage/hezarfen_chatbot_compose.service
205+ test -f stage/tag
206+
207+ - name: Install SSH keys
208+ run: |
209+ mkdir -p ~/.ssh
210+ echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa
211+ ssh-keyscan -H ${{ secrets.SSH_HOST }} > ~/.ssh/known_hosts
212+
213+ - name: Upload the release
214+ run: |
215+ set -euo pipefail
216+ ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
217+
218+ # Sunucunun login shell'i bash değil, ssh bu betiği ona verirdi;
219+ # `bash -s` betiği stdin'den alır, login shell yalnız tek düz komut
220+ # görür.
221+ ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE'
222+ set -euo pipefail
223+ case "$1" in
224+ ''|/*|*..*)
225+ echo "Refusing a broad deploy subdirectory: '$1'" >&2
226+ exit 1
227+ ;;
228+ esac
229+ deploy_path=$HOME/$1
230+ # Bu dizin operatörün hezarfen_chatbot.env dosyasını, compose
231+ # dosyalarını ve tag dosyalarını tutar; hiçbiri toptan silinmez.
232+ mkdir -p -- "$deploy_path"
233+ REMOTE
234+ # stdin paketi taşıyor, betik taşıyamaz; çıkarma yine bash -c ile
235+ # çünkü login shell bash değil ve $HOME'u genişletmez. Sunucuya
236+ # yalnız dört deploy dosyası kurulur.
237+ tar -C stage -czf - hezarfen_chatbot.tar.gz compose.yaml hezarfen_chatbot_compose.service tag | ssh "$ssh_target" "bash -c 'exec tar -xzf - -C \"\$HOME/\$1\"' -- '$DEPLOY_SUBDIR'"
238+
239+ - name: Load the image and restart the bridge
240+ run: |
241+ set -euo pipefail
242+ ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
243+
244+ # bash -s, yukarıdakiyle aynı sebeple: login shell bu betiği asla
245+ # görmemeli.
246+ ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$ENV_FILE_NAME' '$CERT_PATH' '$READY_MARKER'" <<'REMOTE'
247+ set -euo pipefail
248+ deploy_path=$HOME/$1
249+ service=$2
250+ env_file=$deploy_path/$3
251+ cert_path=$4
252+ ready_marker=$5
253+ export XDG_RUNTIME_DIR=/run/user/$(id -u)
254+ # compose.yaml çalışma dizininden çözülür: unit'in ExecStart'ı
255+ # WorkingDirectory taşır ama rollback'in compose up'ı ve ilk deploy'un
256+ # down'ı tam buradan koşar.
257+ cd -- "$deploy_path"
258+
259+ # Hiçbir şey oynamadan önce oku: ayar dosyası operatörün, sunucuda,
260+ # elle bir kez yazılır (anahtarlar için bkz.
261+ # deploy/hezarfen_chatbot.env.example). Deploy onu asla oluşturmaz,
262+ # ezmez.
263+ if [ ! -f "$env_file" ]; then
264+ echo "missing $env_file — create it (0600) from deploy/hezarfen_chatbot.env.example" >&2
265+ exit 1
266+ fi
267+ chmod 0600 -- "$env_file"
268+
269+ # Rootless podman + compose sağlayıcı; üç adım sonra çıplak
270+ # command-not-found yerine çözümü söyle.
271+ command -v podman >/dev/null || {
272+ echo "podman not found — install podman and a compose provider (e.g. dnf install podman podman-compose)" >&2
273+ exit 1
274+ }
275+ podman compose version >/dev/null 2>&1 || {
276+ echo "'podman compose' unavailable — install a compose provider (podman-compose or docker-compose)" >&2
277+ exit 1
278+ }
279+
280+ # Ön koşul: backend köprüsü açık olmalı (AI_QUIC_ADDR=0.0.0.0:8090) —
281+ # sertifika ucu bunun kanıtı ve köprü ona her bağlanmada ihtiyaç duyar.
282+ served_cert=$(curl -fsS "http://127.0.0.1:7656$cert_path" 2>/dev/null) || true
283+ case "$served_cert" in
284+ *certificate_pem*) ;;
285+ *)
286+ echo "backend $cert_path did not answer with a certificate — is the AI bridge enabled (AI_QUIC_ADDR=0.0.0.0:8090)?" >&2
287+ exit 1
288+ ;;
289+ esac
290+
291+ # BU build'in imajını yükle ve build'in damgaladığı tag'i oku
292+ # (build zamanı ile deploy zamanı neyin gittiğinde anlaşmalı).
293+ gunzip -c "$deploy_path/hezarfen_chatbot.tar.gz" | podman load
294+ tag=$(cat -- "$deploy_path/tag")
295+
296+ # Tag rotasyonu: previous_tag geri dönüş hedefidir (ilk deploy'da
297+ # yok); current_tag şu an çalışması gerekeni kaydeder.
298+ if [ -f "$deploy_path/current_tag" ]; then
299+ cp -- "$deploy_path/current_tag" "$deploy_path/previous_tag"
300+ fi
301+ printf '%s\n' "$tag" > "$deploy_path/current_tag"
302+
303+ # stack.env deploy sahipli (operatörün ayar dosyasından farklı):
304+ # yalnız imaj tag'ini taşır ve --env-file sırası HEZARFEN_TAG'de onu
305+ # kazanan yapar.
306+ printf 'HEZARFEN_TAG=%s\n' "$tag" > "$deploy_path/stack.env"
307+
308+ chmod 0644 -- "$deploy_path/compose.yaml" "$deploy_path/hezarfen_chatbot_compose.service"
309+ # İmaj tarball'ı yalnız taşıyıcıydı; imaj artık podman deposunda.
310+ rm -f -- "$deploy_path/hezarfen_chatbot.tar.gz"
311+
312+ compose_up() {
313+ podman compose --env-file "$env_file" --env-file "$deploy_path/stack.env" up -d --no-build
314+ }
315+ rollback() {
316+ if [ -f "$deploy_path/previous_tag" ]; then
317+ prev=$(cat -- "$deploy_path/previous_tag")
318+ printf 'HEZARFEN_TAG=%s\n' "$prev" > "$deploy_path/stack.env"
319+ printf '%s\n' "$prev" > "$deploy_path/current_tag"
320+ compose_up
321+ echo "rolled back to $prev" >&2
322+ else
323+ # İlk deploy: geri dönülecek bir şey yok, yarı ayakta stack'i
324+ # durdur. Düz down — köprü durumsuzdur.
325+ podman compose --env-file "$env_file" --env-file "$deploy_path/stack.env" down
326+ echo 'first deploy failed; stack stopped' >&2
327+ fi
328+ }
329+
330+ # Unit sürümle birlikte gelir: yeni kurulmuş bir kutuda ilk deploy'a
331+ # kadar unit yoktur ve değişen unit onu gerektiren compose ile iner.
332+ mkdir -p -- "$HOME/.config/systemd/user"
333+ install -m 0644 -- "$deploy_path/hezarfen_chatbot_compose.service" "$HOME/.config/systemd/user/$service.service"
334+ systemctl --user daemon-reload
335+
336+ # Unit RemainAfterExit'li bir oneshot: aktif (exited) unit'te `start`
337+ # no-op olurdu — her deploy ExecStart'ı yeniden koşmak için restart
338+ # eder. Düşen bir restart (kötü interpolasyon, sağlayıcı aksaklığı)
339+ # yine de aşağıdaki sağlık kapısına ulaşmalı: kararı o verir.
340+ systemctl --user enable -- "$service"
341+ systemctl --user restart "$service" || true
342+
343+ # Köprünün HAZIR olması = backend'in kaydı kabul etmesi. Portu yok,
344+ # o yüzden kapı logdadır: backend'in greeting'i 'kayıt başarılı' satırını
345+ # yazdırır. 60 deneme, çünkü sertifika + QUIC el sıkışması ve olası
346+ # yeniden bağlanma aralıkları zaman alır.
347+ ready_ok=0
348+ for _ in $(seq 1 60); do
349+ if podman logs --tail 200 hezarfen_chatbot 2>&1 | grep -q "$ready_marker"; then
350+ ready_ok=1
351+ break
352+ fi
353+ sleep 1
354+ done
355+ if [ "$ready_ok" -ne 1 ]; then
356+ echo "the bridge never registered with the backend ('$ready_marker' missing); rolling back" >&2
357+ podman logs --tail 30 hezarfen_chatbot 2>&1 >&2 || true
358+ rollback
359+ exit 1
360+ fi
361+
362+ # Eski bir stack de cevap verebilir; çalışan konteyner BU build'in
363+ # imajı olmalı, yoksa geri dönülür.
364+ image=$(podman inspect -f '{{.Config.Image}}' hezarfen_chatbot)
365+ case "$image" in
366+ *"$tag"*) ;;
367+ *)
368+ echo "the bridge registered, but the container runs '$image' — not this build ($tag); rolling back" >&2
369+ rollback
370+ exit 1
371+ ;;
372+ esac
373+ echo 'hezarfen_chatbot_compose is up'
374+ REMOTE
375+
376+ # Bağımsız son kontrol: cevap veren konteyner hâlâ güncel tag'in olmalı ve
377+ # köprü kayıtlı kalmalı.
378+ - name: Verify the bridge is registered
379+ run: |
380+ set -euo pipefail
381+ ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
382+ ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$READY_MARKER'" <<'REMOTE'
383+ set -euo pipefail
384+ deploy_path=$HOME/$1
385+ ready_marker=$2
386+ export XDG_RUNTIME_DIR=/run/user/$(id -u)
387+ cd -- "$deploy_path"
388+ tag=$(cat -- "$deploy_path/current_tag")
389+ image=$(podman inspect -f '{{.Config.Image}}' hezarfen_chatbot)
390+ case "$image" in
391+ *"$tag"*) ;;
392+ *)
393+ echo "container runs '$image', not the current tag '$tag'" >&2
394+ exit 1
395+ ;;
396+ esac
397+ status=$(podman inspect -f '{{.State.Status}}' hezarfen_chatbot)
398+ [ "$status" = "running" ] || { echo "container status is '$status', not running" >&2; exit 1; }
399+ podman logs --tail 200 hezarfen_chatbot 2>&1 | grep -q "$ready_marker" || {
400+ echo "the bridge is not registered with the backend" >&2
401+ exit 1
402+ }
403+ echo 'bridge registered, container is this build'
404+ REMOTE
405+
406+ - name: Cleaning
407+ run: rm -rf ~/.ssh
.gitignoremodified+9 -0
@@ -22,3 +22,12 @@ data/stress_benchmark_results.jsonl
22 # benchmark_qa_report.py --strict makine çıktısı (~1.6 MiB, yeniden üretilebilir).22 # benchmark_qa_report.py --strict makine çıktısı (~1.6 MiB, yeniden üretilebilir).
23 # Okunabilir Markdown raporu repoda tutulur; ham JSON tutulmaz.23 # Okunabilir Markdown raporu repoda tutulur; ham JSON tutulmaz.
24 data/benchmark_results.json24 data/benchmark_results.json
25+
26+# Compose/sistem ortam dosyaları: operatörün ayarları (hezarfen_chatbot.env) ve
27+# deploy sahipli tag taşıyıcısı (stack.env) makineye özeldir, git'e girmez.
28+# Şablon: deploy/hezarfen_chatbot.env.example
29+hezarfen_chatbot.env
30+stack.env
31+
32+# CI deploy paketi (imaj tarball'ı + compose dosyaları + tag).
33+stage/
Containerfilemodified+21 -2
@@ -14,9 +14,28 @@ COPY src ./src
14 COPY tests ./tests14 COPY tests ./tests
15 COPY data ./data15 COPY data ./data
16 16
17-# Container'ı root olmayan kullanıcıyla çalıştır.17+# Konteynerı root olmayan kullanıcıyla çalıştır.
18 RUN useradd --create-home --uid 10001 chatbot \18 RUN useradd --create-home --uid 10001 chatbot \
19 && chown -R chatbot:chatbot /app19 && chown -R chatbot:chatbot /app
20 USER chatbot20 USER chatbot
21 21
22-CMD ["python", "-m", "src.main", "--validate"]22+# Dağıtım varsayılanları — TEK yazıldıkları yer. Sunucu bunları
23+# hezarfen_chatbot.env (env_file) ile ezer; compose dosyası hiçbir anahtar
24+# listelemez, böylece operatörün dosyası gölgelenemez.
25+#
26+# AI_BACKEND_URL köprünün sertifikayı çektiği HTTP kökü: backend konteynerinin
27+# kendi portu (compose'da PORT=7656). Sertifika her (yeniden) bağlanmada
28+# tazelenir.
29+ENV AI_BRIDGE_HOST=hezarfen-backend \
30+ AI_BRIDGE_PORT=8090 \
31+ AI_BACKEND_URL=http://hezarfen-backend:7656 \
32+ AI_SHARED_TOKEN=change-me \
33+ AI_TLS_SERVER_NAME=localhost \
34+ AI_SERVICE_NAME=celebi \
35+ HEZARFEN_ASSISTANT_ROLE=ogrenci \
36+ AI_MAX_CONCURRENT=8 \
37+ AI_RECONNECT_SECS=3
38+
39+# Konteynerın işi köprüyü çalıştırmak. Katalog/benchmark komutları bu imajın
40+# içinde elle koşulur: `podman run --rm IMAGE python -m src.main --validate`.
41+CMD ["python", "-m", "src.bridge"]
ReadMe.mdmodified+2 -2
@@ -9,7 +9,7 @@ backend'e bağlanan QUIC köprüsüdür (`src/bridge.py`, `aioquic`).
9 Bilgi kaynağı: [`docs/hezarfen-site-rehberi.md`](docs/hezarfen-site-rehberi.md).9 Bilgi kaynağı: [`docs/hezarfen-site-rehberi.md`](docs/hezarfen-site-rehberi.md).
10 10
11 > **Backend'e bağlanıyor:** Çelebi, backend'in QUIC AI köprüsüne (protokol11 > **Backend'e bağlanıyor:** Çelebi, backend'in QUIC AI köprüsüne (protokol
12-> `hab/1`) dial-in eden istemciyle bağlanır — **[`src/bridge.py`](src/bridge.py)**;12+> `hab/2`) dial-in eden istemciyle bağlanır — **[`src/bridge.py`](src/bridge.py)**;
13 > `chat.reply` yeteneğini sunar, backend'in doğrulanmış oturum rolünü13 > `chat.reply` yeteneğini sunar, backend'in doğrulanmış oturum rolünü
14 > `asker_role` alanından alır. Çalıştırma ve ortam değişkenleri dosya başındaki14 > `asker_role` alanından alır. Çalıştırma ve ortam değişkenleri dosya başındaki
15 > docstring'de.15 > docstring'de.
@@ -32,7 +32,7 @@ Hezarfen-Rule-Based-Chatbot/
32 │32 │
33 ├─ src/ # ── ASISTAN MOTORU ──33 ├─ src/ # ── ASISTAN MOTORU ──
34 │ ├─ engine.py # 🚪 GİRİŞ NOKTASI: handle_request(payload)->dict; boru hattını yönetir34 │ ├─ engine.py # 🚪 GİRİŞ NOKTASI: handle_request(payload)->dict; boru hattını yönetir
35-│ ├─ bridge.py # 🔌 backend QUIC köprü istemcisi (hab/1, chat.reply) — aioquic35+│ ├─ bridge.py # 🔌 backend QUIC köprü istemcisi (hab/2, chat.reply) — aioquic
36 │ ├─ bridge_contract.py # 🔐 backend asker_role -> motor oturumu sözleşmesi (stdlib)36 │ ├─ bridge_contract.py # 🔐 backend asker_role -> motor oturumu sözleşmesi (stdlib)
37 │ ├─ catalog.py # 📚 VERİ: 98 intent + cevap metinleri + route + rol modeli + rol yetenekleri37 │ ├─ catalog.py # 📚 VERİ: 98 intent + cevap metinleri + route + rol modeli + rol yetenekleri
38 │ ├─ rules.py # kural katmanı (yüksek kesinlik, anahtar kelime eşleşmesi)38 │ ├─ rules.py # kural katmanı (yüksek kesinlik, anahtar kelime eşleşmesi)
compose.yamlmodified+21 -16
@@ -1,26 +1,31 @@
1-# Çelebi ürün köprüsü — bu compose yalnızca TEK chatbot container'ı oluşturur.1+# Çelebi QUIC köprüsü — bu compose yalnızca TEK chatbot container'ı oluşturur.
2-# Önce backend compose ayakta olmalı; backend ağına bağlanıp QUIC/UDP ile2+# Backend compose ayakta olmalı; bu servis backend'in ağına katılır ve oradan
3-# hezarfen-backend:8090 adresine dial-in eder. Host portu veya demo web UI açmaz.3+# QUIC/UDP ile `hezarfen-backend:8090` adresine dial-in eder. Host portu veya
4+# demo web arayüzü AÇMAZ (web.py yalnız geliştirici aracıdır).
5+#
6+# Varsayılanların TEK kaynağı Containerfile'ın ENV bloğudur; bu dosya hiçbir
7+# `environment:` girdisi taşımaz, böylece hiçbir şey operatörün dosyasını
8+# gölgeleyemez. Sunucuda ~/hezarfen_chatbot/hezarfen_chatbot.env ile ezilir.
4 #9 #
5 # podman compose up -d --build10 # podman compose up -d --build
11+#
12+# Ön koşul: backend'de AI köprüsü AÇIK olmalı — hezarfen_backend.env içinde
13+# AI_QUIC_ADDR=0.0.0.0:8090 (127.0.0.1 DEĞİL: konteyner kendi loopback'ine
14+# bağlanırsa dışarıdan hiçbir servis ulaşamaz) ve AI_SHARED_TOKEN buradaki
15+# token ile AYNI olmalı.
6 services:16 services:
7- bridge:17+ chatbot:
8 build:18 build:
9 context: .19 context: .
10 dockerfile: Containerfile20 dockerfile: Containerfile
11- image: localhost/rule-based-chatbot:local21+ # HEZARFEN_TAG deploy tarafından yazılan stack.env'den gelir (--env-file).
12- container_name: hezarfen-chatbot-bridge22+ image: localhost/hezarfen_chatbot:${HEZARFEN_TAG:-latest}
23+ container_name: hezarfen_chatbot
13 init: true24 init: true
14- command: ["python", "-m", "src.bridge"]25+ env_file:
15- environment:26+ # Sunucuda elle yazılır (0600); laptopta yoktur.
16- AI_BRIDGE_HOST: hezarfen-backend # backend container'ının adı27+ - path: hezarfen_chatbot.env
17- # aioquic bu hedefe UDP ile bağlanır; burada TCP port yayını yoktur.28+ required: false
18- AI_BRIDGE_PORT: "8090"
19- AI_BACKEND_URL: http://hezarfen-backend:8080
20- AI_SHARED_TOKEN: change-me # backend ile AYNI olmalı
21- AI_TLS_SERVER_NAME: localhost # self-signed sertifikanın SAN'ı
22- AI_SERVICE_NAME: celebi
23- HEZARFEN_ASSISTANT_ROLE: ogrenci
24 restart: unless-stopped29 restart: unless-stopped
25 networks:30 networks:
26 - backend_net31 - backend_net
deploy/hezarfen_chatbot.env.exampleadded+52 -0
@@ -0,0 +1,52 @@
1+# hezarfen_chatbot.env — Çelebi köprüsünün sunucu ayarları.
2+#
3+# Sunucuda TEK SEFERLİK, elle:
4+# mkdir -p ~/hezarfen_chatbot
5+# cp hezarfen_chatbot.env.example ~/hezarfen_chatbot/hezarfen_chatbot.env
6+# <değerleri doldur>
7+# chmod 0600 ~/hezarfen_chatbot/hezarfen_chatbot.env
8+#
9+# Hiçbir otomasyon bu dosyayı oluşturmaz, ezmez, yüklemez — operatörün malıdır;
10+# compose yalnız okur (`env_file`). Satırlar düz KEY=value: tırnak yok, `export`
11+# yok, satır sonu yorumu yok.
12+#
13+# Buradaki her anahtar Containerfile ENV bloğundaki varsayılanı EZER. Değerler
14+# konteyner BAŞLARKEN okunur: değişiklikten sonra yeniden oluştur
15+# (`podman compose up -d` ya da `systemctl --user restart hezarfen_chatbot_compose`).
16+
17+# ── Backend tarafı (ZORUNLU: ikisi backend ile aynı olmalı) ───────────────────
18+# Backend'in QUIC köprüsü dinleyicisi. hezarfen_backend.env içinde
19+# AI_QUIC_ADDR=0.0.0.0:8090 OLMALI — 127.0.0.1 yazılıysa backend yalnız kendi
20+# konteyner loopback'ine bağlanır ve HİÇBİR servis dial-in edemez (Çelebi 503
21+# "no AI service is connected" verir). Değiştirdikten sonra:
22+# systemctl --user restart hezarfen_backend_compose
23+AI_BRIDGE_HOST=hezarfen-backend
24+AI_BRIDGE_PORT=8090
25+
26+# Sertifikanın çekildiği HTTP kökü — backend konteynerinin kendi portu.
27+AI_BACKEND_URL=http://hezarfen-backend:7656
28+
29+# Paylaşılan sır: backend'in AI_SHARED_TOKEN'ı ile BİREBİR aynı olmalı.
30+# 'change-me' yalnız geliştirme değeridir; prod'da iki tarafı birlikte değiştir.
31+AI_SHARED_TOKEN=change-me
32+
33+# ── Servis kimliği ────────────────────────────────────────────────────────────
34+# Sertifikadaki SAN (self-signed, backend her açılışta yeniler).
35+AI_TLS_SERVER_NAME=localhost
36+# Loglarda ve backend kaydında görünen ad.
37+AI_SERVICE_NAME=celebi
38+# Backend rol göndermezse kullanılacak yedek rol (ziyaretci|veli|ogrenci|ogretmen|yonetici|admin).
39+HEZARFEN_ASSISTANT_ROLE=ogrenci
40+
41+# ── Dayanıklılık ──────────────────────────────────────────────────────────────
42+# Aynı anda kabul edilen istek ve kopunca yeniden deneme aralığı (saniye).
43+AI_MAX_CONCURRENT=8
44+AI_RECONNECT_SECS=3
45+
46+# ── Sürüm etiketi ─────────────────────────────────────────────────────────────
47+# BURADAN OKUNMAZ: HEZARFEN_TAG yalnız compose interpolasyonudur ve deploy'un
48+# sahip olduğu stack.env içinde taşınır (ikinci `--env-file`, çakışan anahtarda
49+# o kazanır). Unit `--no-build` ile başlar, yani imaj sunucuda VAR olmalı:
50+# podman compose build # burada derle
51+# podman load -i image.tar # ya da hazır imajı yükle
52+#HEZARFEN_TAG=latest
deploy/hezarfen_chatbot_compose.serviceadded+40 -0
@@ -0,0 +1,40 @@
1+# systemd KULLANICI unit'i: Çelebi köprüsünü podman compose ile çalıştırır.
2+# %h/hezarfen_chatbot içinde beklenen dosyalar:
3+# compose.yaml bu repodan (ya da deploy artefaktından)
4+# hezarfen_chatbot.env 0600, deploy/hezarfen_chatbot.env.example'dan
5+# ELLE yazılır — otomasyon oluşturmaz/ezmez
6+# stack.env deploy sahipli; HEZARFEN_TAG taşır
7+#
8+# Unit `--no-build` ile başlar, yani imaj sunucuda zaten olmalı:
9+# podman compose build # burada derle
10+# podman load -i image.tar # ya da hazır imajı yükle
11+#
12+# hezarfen_chatbot.env içindeki anahtarlar (tam belge: deploy/hezarfen_chatbot.env.example).
13+# Hepsinin varsayılanı imajın ENV bloğundadır (Containerfile) — bu dosya ezer:
14+# AI_BRIDGE_HOST / AI_BRIDGE_PORT backend'in QUIC dinleyicisi (ağ içi ad)
15+# AI_BACKEND_URL sertifikanın çekildiği HTTP kökü
16+# AI_SHARED_TOKEN backend ile AYNI olmalı
17+# HEZARFEN_ASSISTANT_ROLE yedek rol
18+#
19+# Sadece ortam değişkeni değiştiğinde yeniden başlatma (ExecStart'ı yeniden
20+# koşar, ortamı değişen konteynerı yeniden oluşturur):
21+# systemctl --user restart hezarfen_chatbot_compose
22+
23+[Unit]
24+Description=Hezarfen Celebi QUIC bridge (rule-based chatbot)
25+After=network-online.target
26+Wants=network-online.target
27+
28+[Service]
29+Type=oneshot
30+RemainAfterExit=yes
31+WorkingDirectory=%h/hezarfen_chatbot
32+# Sonraki --env-file çakışan anahtarda kazanır: önce operatörün ayar dosyası,
33+# sonra deploy sahipli stack.env (HEZARFEN_TAG).
34+ExecStart=/usr/bin/podman compose --env-file %h/hezarfen_chatbot/hezarfen_chatbot.env --env-file %h/hezarfen_chatbot/stack.env up -d --no-build
35+# -v yok: isimli volume'lar stop'ta yaşamalı (köprü durumsuzdur ama şekil aynı).
36+ExecStop=/usr/bin/podman compose down
37+TimeoutStartSec=180
38+
39+[Install]
40+WantedBy=default.target
src/bridge.pymodified+6 -3
@@ -3,7 +3,7 @@
3 Backend (``hezarfen_backend``) bir QUIC **sunucusudur**: AI servisleri ona3 Backend (``hezarfen_backend``) bir QUIC **sunucusudur**: AI servisleri ona
4 *dial-in* eder, sundukları yetenekleri (`capabilities`) kaydeder ve backend her4 *dial-in* eder, sundukları yetenekleri (`capabilities`) kaydeder ve backend her
5 sohbet turunu bu bağlantı üzerinden bir isteğe çevirir. Bu modül o istemcinin5 sohbet turunu bu bağlantı üzerinden bir isteğe çevirir. Bu modül o istemcinin
6-Python tarafıdır; wire protokolü backend'deki ``src/ai/protocol.rs`` ("hab/1")6+Python tarafıdır; wire protokolü backend'deki ``src/ai/protocol.rs`` ("hab/2")
7 ile birebir aynıdır.7 ile birebir aynıdır.
8 8
9 Akış (bkz. backend ``src/ai/mod.rs`` ve ``server.rs``):9 Akış (bkz. backend ``src/ai/mod.rs`` ve ``server.rs``):
@@ -11,7 +11,7 @@ Akış (bkz. backend ``src/ai/mod.rs`` ve ``server.rs``):
11 1. Backend'in HTTP'sinden sertifikayı çek (``GET /ai/certificate``) ve pinle.11 1. Backend'in HTTP'sinden sertifikayı çek (``GET /ai/certificate``) ve pinle.
12 Self-signed sertifika her açılışta yenilendiği için her (yeniden) bağlanmada12 Self-signed sertifika her açılışta yenilendiği için her (yeniden) bağlanmada
13 tazelenir.13 tazelenir.
14-2. QUIC ile ``AI_QUIC_ADDR``'e bağlan (ALPN ``hab/1``).14+2. QUIC ile ``AI_QUIC_ADDR``'e bağlan (ALPN ``hab/2``).
15 3. İlk *client-initiated* çift yönlü akış = **kontrol akışı**: bir ``Hello``15 3. İlk *client-initiated* çift yönlü akış = **kontrol akışı**: bir ``Hello``
16 yaz, bir ``Greeting`` oku, akışı hayat boyu açık tut (kapanması = kayıttan16 yaz, bir ``Greeting`` oku, akışı hayat boyu açık tut (kapanması = kayıttan
17 düşme sinyali).17 düşme sinyali).
@@ -67,7 +67,10 @@ from .bridge_contract import resolve_session
67 from .engine import Engine, RequestError, get_default_engine67 from .engine import Engine, RequestError, get_default_engine
68 68
69 # --- Protokol sabitleri (backend src/constant.rs ile eşleşir) ---------------69 # --- Protokol sabitleri (backend src/constant.rs ile eşleşir) ---------------
70-PROTOCOL = "hab/1"70+# AI_PROTOCOL/AI_ALPN backend'de "hab/2": sunucu hello.protocol'u bununla
71+# karşılaştırır ve ALPN listesi de aynı dizedir. Sürüm burada geride kalırsa
72+# backend kaydı reddeder ("this backend speaks hab/2, the service announced …").
73+PROTOCOL = "hab/2"
71 CHAT_CAPABILITY = "chat.reply"74 CHAT_CAPABILITY = "chat.reply"
72 MAX_FRAME_BYTES = 8 * 1024 * 102475 MAX_FRAME_BYTES = 8 * 1024 * 1024
73 KEEPALIVE_SECS = 10 # backend AI_IDLE_TIMEOUT_SECS=30; altında tutulur76 KEEPALIVE_SECS = 10 # backend AI_IDLE_TIMEOUT_SECS=30; altında tutulur