From e013725e3af3335d1da02896fe2e3b87a9c5ca28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 15 Sep 2026 20:58:59 +0300 Subject: [PATCH] =?UTF-8?q?chore:=20=F0=9F=94=A7=20compose=20stack,=20hab/?= =?UTF-8?q?2=20protocol=20and=20VPS=20deploy=20workflow=20-=20compose.yaml?= =?UTF-8?q?:=20env-file=20driven=20single=20service=20that=20joins=20the?= =?UTF-8?q?=20backend's=20=20=20podman=20network=20and=20dials=20QUIC=2080?= =?UTF-8?q?90;=20no=20ports,=20no=20environment=20block,=20so=20=20=20noth?= =?UTF-8?q?ing=20can=20shadow=20the=20operator's=20hezarfen=5Fchatbot.env?= =?UTF-8?q?=20-=20Containerfile=20is=20the=20single=20source=20of=20the=20?= =?UTF-8?q?deployment=20defaults=20(AI=5F*=20ENV=20=20=20block)=20and=20no?= =?UTF-8?q?w=20CMDs=20the=20bridge;=20AI=5FBACKEND=5FURL=20points=20at=20t?= =?UTF-8?q?he=20backend's=20=20=20own=20port=207656=20instead=20of=20the?= =?UTF-8?q?=20stale=208080=20-=20bridge.py=20speaks=20hab/2:=20the=20backe?= =?UTF-8?q?nd=20pins=20AI=5FPROTOCOL/AI=5FALPN=20to=20hab/2=20and=20=20=20?= =?UTF-8?q?rejects=20any=20other=20hello,=20so=20the=20bridge=20could=20ne?= =?UTF-8?q?ver=20register=20-=20deploy/:=20operator=20env=20example=20+=20?= =?UTF-8?q?systemd=20user=20unit=20(compose=20up=20--no-build=20=20=20with?= =?UTF-8?q?=20both=20--env-file=20arguments)=20-=20.github/workflows/main.?= =?UTF-8?q?yml:=20validate=20=E2=88=A5=20build-and-test=20(unittest=20suit?= =?UTF-8?q?e,=20=20=20Composefile=20image,=20release=20artifact)=20then=20?= =?UTF-8?q?an=20SSH=20deploy=20that=20rotates=20=20=20HEZARFEN=5FTAG=20in?= =?UTF-8?q?=20a=20deploy-owned=20stack.env,=20installs=20the=20unit,=20res?= =?UTF-8?q?tarts=20and=20=20=20gates=20on=20the=20backend=20accepting=20th?= =?UTF-8?q?e=20registration,=20rolling=20back=20on=20failure?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/main.yml | 407 ++++++++++++++++++++++++ .gitignore | 9 + Containerfile | 23 +- ReadMe.md | 4 +- compose.yaml | 37 ++- deploy/hezarfen_chatbot.env.example | 52 +++ deploy/hezarfen_chatbot_compose.service | 40 +++ src/bridge.py | 9 +- 8 files changed, 558 insertions(+), 23 deletions(-) create mode 100644 .github/workflows/main.yml create mode 100644 deploy/hezarfen_chatbot.env.example create mode 100644 deploy/hezarfen_chatbot_compose.service diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..709c30c --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,407 @@ +# VPS deploy, compose-style, frontend ile aynı şekil (hata toparlama ucuz olsun): +# +# Validate — katalog doğrulaması + derleme kontrolü, kendi runner'ında. +# Build and test — unittest süiti (regresyon eşikleri içinde), sonra repo +# Containerfile'ından imaj (ENV bloğu dağıtım +# varsayılanlarının TEK kaynağıdır) ve imaj tarball'ı + +# compose dosyaları koşunun artefaktı olarak yüklenir. +# Deploy — SSH: imajı yükle, deploy sahipli stack.env'in +# HEZARFEN_TAG'ini ona çevir, compose.yaml + unit'i kur, +# stack'i yeniden başlat, köprünün backend'e KAYIT +# olduğunu loglardan doğrula, olmazsa önceki tag'e dön, +# ardından bağımsız doğrulama. +# +# Validate ile Build and test paralel koşar; Deploy ikisi de yeşilse çalışır. +# Yeni bir push aynı ref'teki Validate/Build'i iptal eder; uçuştaki Deploy'u +# ASLA iptal etmez (iki deploy iç içe geçerse stack karışır). +# +# Bölünmenin amacı toparlama hikâyesi: +# * Deploy adımı düşen bir koşuda "Re-run failed jobs" SADECE ~1 dakikalık +# deploy işini yeniden koşar — imaj hâlâ koşunun artefaktında. +# * workflow_dispatch (Actions → Run workflow, ya da +# `gh workflow run main.yml --ref main`) süiti koşmadan en yeni yeşil +# build'in artefaktını deploy eder. +# +# Bir seferlik ön koşullar (workflow'un erişimi dışında): +# * repo secret'ları SSH_PRIVATE_KEY / SSH_HOST / SSH_USER — backend ve +# frontend deploy'unun kullandığı üç isim; +# * sunucuda `loginctl enable-linger ` (kullanıcı unit'leri için); +# * sunucuda podman + bir compose sağlayıcı (deploy ikisini de kontrol eder); +# * operatörün ~/hezarfen_chatbot/hezarfen_chatbot.env (0600) dosyası; +# * BACKEND tarafı açık olmalı: hezarfen_backend.env içinde +# AI_QUIC_ADDR=0.0.0.0:8090 ve AI_SHARED_TOKEN bu köprününkiyle AYNI. +# (127.0.0.1 yazılıysa backend yalnız kendi loopback'ine bağlanır ve köprü +# asla kayıt olamaz — deploy bunu logda görüp geri döner.) + +name: VPS deploy + +on: + push: + branches: + - main + # Elle yeniden deploy kapısı — yukarıdaki başlık yorumuna bakın. + workflow_dispatch: + +# Deploy serileştirmesi workflow'da değil deploy işinde: yeni bir push, uçuştaki +# VPS değişimine dokunmadan bayat Validate/Build'i iptal edebilmeli. + +env: + # systemd kullanıcı unit'i. Bkz. deploy/hezarfen_chatbot_compose.service. + SERVICE: hezarfen_chatbot_compose + # Deploy, SSH kullanıcısının home'u altındaki bu alt dizinde yaşar ($HOME + # sunucuda çözülür, yani kullanıcı değişince yol da onunla gelir). + DEPLOY_SUBDIR: hezarfen_chatbot + # Köprünün ayar dosyası; deploy yalnız varlığını kontrol eder, yazmaz. + ENV_FILE_NAME: hezarfen_chatbot.env + # Sağlık kapısı: backend'in verdiği kayıt onayı logda bu satırdır. + READY_MARKER: "kayıt başarılı" + # Köprünün backend sertifikasını çektiği yol (HTTP, backend konteynerinin portu). + CERT_PATH: /ai/certificate + +jobs: + validate: + name: Validate + if: github.event_name == 'push' + runs-on: ubuntu-24.04 + concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }}-validate + cancel-in-progress: true + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + # Containerfile ile aynı satır (python:3.13-slim). + python-version: "3.13" + - name: Install dependencies + run: pip install --requirement requirements.txt + - name: Compile every module + run: python -m compileall -q src tests + - name: Validate the catalog + run: python -m src.main --validate + + build: + name: Build and test + # Pushes only: elle yeniden deploy süiti tekrar ödemek yerine en yeni yeşil + # artefaktı kullanır. + if: github.event_name == 'push' + concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }}-build + cancel-in-progress: true + runs-on: ubuntu-24.04 + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.13" + - name: Install dependencies + run: pip install --requirement requirements.txt + + # Bozuk bir build sunucuya ASLA ulaşmamalı: regresyon eşikleri + # (macro-F1 ≥ 0.80, OOS recall ≥ 0.70, kapsama ≥ 0.95, gizlilik recall + # = 1.0, kural precision = 1.0) bu süitin içinde yaşar. + - name: Test + run: python -m unittest discover -s tests -t . -v + + # Laptop ve CI aynı Containerfile'ı kullanır: ENV bloğu ne diyorsa o + # gönderilir, ayrı bir CI ikizi yok. + - name: Build the image + run: | + set -euo pipefail + docker build -f Containerfile -t localhost/hezarfen_chatbot:$GITHUB_SHA . + + - name: Stage the release bundle + run: | + set -euo pipefail + mkdir -p stage + docker save localhost/hezarfen_chatbot:$GITHUB_SHA | gzip > stage/hezarfen_chatbot.tar.gz + cp compose.yaml deploy/hezarfen_chatbot_compose.service stage/ + echo -n "$GITHUB_SHA" > stage/tag + # Sunucuda kurulacak her şey burada olmalı; eksik parça burada, + # sunucuda değil, patlar. + test -f stage/hezarfen_chatbot.tar.gz + test -f stage/compose.yaml + test -f stage/hezarfen_chatbot_compose.service + test -f stage/tag + ls -l stage + + # Deploy işi (ve elle yeniden deploy) bunu tüketir. 30 gün, dispatch + # kapısının geri uzanma penceresidir. + - name: Upload the release + uses: actions/upload-artifact@v4 + with: + name: release + path: stage + retention-days: 30 + + deploy: + name: Deploy + needs: [validate, build] + concurrency: + group: deploy + cancel-in-progress: false + # Push: yalnız validate VE build yeşilse — ikisi de sunucuyu kapılar. + # Dispatch: iki CI işi bilerek atlanır (if'lerine bakın) ve `always()` + # bu atlamanın bu kapıyı geçmesini engeller. + if: >- + always() && + ((needs.validate.result == 'success' && needs.build.result == 'success') || + (github.event_name == 'workflow_dispatch' && + needs.validate.result == 'skipped' && + needs.build.result == 'skipped')) + runs-on: ubuntu-24.04 + steps: + # Push deploy'u bu koşunun ürettiği ve kapıladığı sürümü alır. + - name: Fetch this run's release + if: github.event_name == 'push' + uses: actions/download-artifact@v4 + with: + name: release + path: stage + + # Elle yeniden deploy, BUILD işi yeşil olan en yeni koşuyu alır — en yeni + # tamamen yeşil koşuyu değil: bir koşu sağlık kapısında düşmüş olabilir + # ama build'i tam da geri almak istediğimiz sürümdür. + - name: Find the newest green build + if: github.event_name == 'workflow_dispatch' + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + run_id="" + for rid in $(gh run list --workflow main.yml --branch main --event push --limit 15 --json databaseId --jq '.[].databaseId'); do + if [ "$(gh run view "$rid" --json jobs --jq '.jobs[] | select(.name=="Build and test") | .conclusion')" = "success" ]; then + run_id=$rid + break + fi + done + if [ -z "$run_id" ]; then + echo 'no run on main has a green Build-and-test job (or its artifact has expired)' >&2 + exit 1 + fi + echo "redeploying the release from run $run_id" + echo "run_id=$run_id" >> "$GITHUB_ENV" + + - name: Fetch the green release + if: github.event_name == 'workflow_dispatch' + uses: actions/download-artifact@v4 + with: + name: release + path: stage + run-id: ${{ env.run_id }} + github-token: ${{ github.token }} + + # Dispatch yolu günler öncesine ait bir artefakt indirebilir; sunucuya + # dokunmadan önce paketin bütün olduğunu yeniden kontrol et. + - name: Check the release is complete + run: | + set -euo pipefail + test -f stage/hezarfen_chatbot.tar.gz + test -f stage/compose.yaml + test -f stage/hezarfen_chatbot_compose.service + test -f stage/tag + + - name: Install SSH keys + run: | + mkdir -p ~/.ssh + echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa + ssh-keyscan -H ${{ secrets.SSH_HOST }} > ~/.ssh/known_hosts + + - name: Upload the release + run: | + set -euo pipefail + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" + + # Sunucunun login shell'i bash değil, ssh bu betiği ona verirdi; + # `bash -s` betiği stdin'den alır, login shell yalnız tek düz komut + # görür. + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE' + set -euo pipefail + case "$1" in + ''|/*|*..*) + echo "Refusing a broad deploy subdirectory: '$1'" >&2 + exit 1 + ;; + esac + deploy_path=$HOME/$1 + # Bu dizin operatörün hezarfen_chatbot.env dosyasını, compose + # dosyalarını ve tag dosyalarını tutar; hiçbiri toptan silinmez. + mkdir -p -- "$deploy_path" + REMOTE + # stdin paketi taşıyor, betik taşıyamaz; çıkarma yine bash -c ile + # çünkü login shell bash değil ve $HOME'u genişletmez. Sunucuya + # yalnız dört deploy dosyası kurulur. + 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'" + + - name: Load the image and restart the bridge + run: | + set -euo pipefail + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" + + # bash -s, yukarıdakiyle aynı sebeple: login shell bu betiği asla + # görmemeli. + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$ENV_FILE_NAME' '$CERT_PATH' '$READY_MARKER'" <<'REMOTE' + set -euo pipefail + deploy_path=$HOME/$1 + service=$2 + env_file=$deploy_path/$3 + cert_path=$4 + ready_marker=$5 + export XDG_RUNTIME_DIR=/run/user/$(id -u) + # compose.yaml çalışma dizininden çözülür: unit'in ExecStart'ı + # WorkingDirectory taşır ama rollback'in compose up'ı ve ilk deploy'un + # down'ı tam buradan koşar. + cd -- "$deploy_path" + + # Hiçbir şey oynamadan önce oku: ayar dosyası operatörün, sunucuda, + # elle bir kez yazılır (anahtarlar için bkz. + # deploy/hezarfen_chatbot.env.example). Deploy onu asla oluşturmaz, + # ezmez. + if [ ! -f "$env_file" ]; then + echo "missing $env_file — create it (0600) from deploy/hezarfen_chatbot.env.example" >&2 + exit 1 + fi + chmod 0600 -- "$env_file" + + # Rootless podman + compose sağlayıcı; üç adım sonra çıplak + # command-not-found yerine çözümü söyle. + command -v podman >/dev/null || { + echo "podman not found — install podman and a compose provider (e.g. dnf install podman podman-compose)" >&2 + exit 1 + } + podman compose version >/dev/null 2>&1 || { + echo "'podman compose' unavailable — install a compose provider (podman-compose or docker-compose)" >&2 + exit 1 + } + + # Ön koşul: backend köprüsü açık olmalı (AI_QUIC_ADDR=0.0.0.0:8090) — + # sertifika ucu bunun kanıtı ve köprü ona her bağlanmada ihtiyaç duyar. + served_cert=$(curl -fsS "http://127.0.0.1:7656$cert_path" 2>/dev/null) || true + case "$served_cert" in + *certificate_pem*) ;; + *) + echo "backend $cert_path did not answer with a certificate — is the AI bridge enabled (AI_QUIC_ADDR=0.0.0.0:8090)?" >&2 + exit 1 + ;; + esac + + # BU build'in imajını yükle ve build'in damgaladığı tag'i oku + # (build zamanı ile deploy zamanı neyin gittiğinde anlaşmalı). + gunzip -c "$deploy_path/hezarfen_chatbot.tar.gz" | podman load + tag=$(cat -- "$deploy_path/tag") + + # Tag rotasyonu: previous_tag geri dönüş hedefidir (ilk deploy'da + # yok); current_tag şu an çalışması gerekeni kaydeder. + if [ -f "$deploy_path/current_tag" ]; then + cp -- "$deploy_path/current_tag" "$deploy_path/previous_tag" + fi + printf '%s\n' "$tag" > "$deploy_path/current_tag" + + # stack.env deploy sahipli (operatörün ayar dosyasından farklı): + # yalnız imaj tag'ini taşır ve --env-file sırası HEZARFEN_TAG'de onu + # kazanan yapar. + printf 'HEZARFEN_TAG=%s\n' "$tag" > "$deploy_path/stack.env" + + chmod 0644 -- "$deploy_path/compose.yaml" "$deploy_path/hezarfen_chatbot_compose.service" + # İmaj tarball'ı yalnız taşıyıcıydı; imaj artık podman deposunda. + rm -f -- "$deploy_path/hezarfen_chatbot.tar.gz" + + compose_up() { + podman compose --env-file "$env_file" --env-file "$deploy_path/stack.env" up -d --no-build + } + rollback() { + if [ -f "$deploy_path/previous_tag" ]; then + prev=$(cat -- "$deploy_path/previous_tag") + printf 'HEZARFEN_TAG=%s\n' "$prev" > "$deploy_path/stack.env" + printf '%s\n' "$prev" > "$deploy_path/current_tag" + compose_up + echo "rolled back to $prev" >&2 + else + # İlk deploy: geri dönülecek bir şey yok, yarı ayakta stack'i + # durdur. Düz down — köprü durumsuzdur. + podman compose --env-file "$env_file" --env-file "$deploy_path/stack.env" down + echo 'first deploy failed; stack stopped' >&2 + fi + } + + # Unit sürümle birlikte gelir: yeni kurulmuş bir kutuda ilk deploy'a + # kadar unit yoktur ve değişen unit onu gerektiren compose ile iner. + mkdir -p -- "$HOME/.config/systemd/user" + install -m 0644 -- "$deploy_path/hezarfen_chatbot_compose.service" "$HOME/.config/systemd/user/$service.service" + systemctl --user daemon-reload + + # Unit RemainAfterExit'li bir oneshot: aktif (exited) unit'te `start` + # no-op olurdu — her deploy ExecStart'ı yeniden koşmak için restart + # eder. Düşen bir restart (kötü interpolasyon, sağlayıcı aksaklığı) + # yine de aşağıdaki sağlık kapısına ulaşmalı: kararı o verir. + systemctl --user enable -- "$service" + systemctl --user restart "$service" || true + + # Köprünün HAZIR olması = backend'in kaydı kabul etmesi. Portu yok, + # o yüzden kapı logdadır: backend'in greeting'i 'kayıt başarılı' satırını + # yazdırır. 60 deneme, çünkü sertifika + QUIC el sıkışması ve olası + # yeniden bağlanma aralıkları zaman alır. + ready_ok=0 + for _ in $(seq 1 60); do + if podman logs --tail 200 hezarfen_chatbot 2>&1 | grep -q "$ready_marker"; then + ready_ok=1 + break + fi + sleep 1 + done + if [ "$ready_ok" -ne 1 ]; then + echo "the bridge never registered with the backend ('$ready_marker' missing); rolling back" >&2 + podman logs --tail 30 hezarfen_chatbot 2>&1 >&2 || true + rollback + exit 1 + fi + + # Eski bir stack de cevap verebilir; çalışan konteyner BU build'in + # imajı olmalı, yoksa geri dönülür. + image=$(podman inspect -f '{{.Config.Image}}' hezarfen_chatbot) + case "$image" in + *"$tag"*) ;; + *) + echo "the bridge registered, but the container runs '$image' — not this build ($tag); rolling back" >&2 + rollback + exit 1 + ;; + esac + echo 'hezarfen_chatbot_compose is up' + REMOTE + + # Bağımsız son kontrol: cevap veren konteyner hâlâ güncel tag'in olmalı ve + # köprü kayıtlı kalmalı. + - name: Verify the bridge is registered + run: | + set -euo pipefail + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$READY_MARKER'" <<'REMOTE' + set -euo pipefail + deploy_path=$HOME/$1 + ready_marker=$2 + export XDG_RUNTIME_DIR=/run/user/$(id -u) + cd -- "$deploy_path" + tag=$(cat -- "$deploy_path/current_tag") + image=$(podman inspect -f '{{.Config.Image}}' hezarfen_chatbot) + case "$image" in + *"$tag"*) ;; + *) + echo "container runs '$image', not the current tag '$tag'" >&2 + exit 1 + ;; + esac + status=$(podman inspect -f '{{.State.Status}}' hezarfen_chatbot) + [ "$status" = "running" ] || { echo "container status is '$status', not running" >&2; exit 1; } + podman logs --tail 200 hezarfen_chatbot 2>&1 | grep -q "$ready_marker" || { + echo "the bridge is not registered with the backend" >&2 + exit 1 + } + echo 'bridge registered, container is this build' + REMOTE + + - name: Cleaning + run: rm -rf ~/.ssh diff --git a/.gitignore b/.gitignore index 32cad7b..2234149 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,12 @@ data/stress_benchmark_results.jsonl # benchmark_qa_report.py --strict makine çıktısı (~1.6 MiB, yeniden üretilebilir). # Okunabilir Markdown raporu repoda tutulur; ham JSON tutulmaz. data/benchmark_results.json + +# Compose/sistem ortam dosyaları: operatörün ayarları (hezarfen_chatbot.env) ve +# deploy sahipli tag taşıyıcısı (stack.env) makineye özeldir, git'e girmez. +# Şablon: deploy/hezarfen_chatbot.env.example +hezarfen_chatbot.env +stack.env + +# CI deploy paketi (imaj tarball'ı + compose dosyaları + tag). +stage/ diff --git a/Containerfile b/Containerfile index 746cc79..6373be8 100644 --- a/Containerfile +++ b/Containerfile @@ -14,9 +14,28 @@ COPY src ./src COPY tests ./tests COPY data ./data -# Container'ı root olmayan kullanıcıyla çalıştır. +# Konteynerı root olmayan kullanıcıyla çalıştır. RUN useradd --create-home --uid 10001 chatbot \ && chown -R chatbot:chatbot /app USER chatbot -CMD ["python", "-m", "src.main", "--validate"] +# Dağıtım varsayılanları — TEK yazıldıkları yer. Sunucu bunları +# hezarfen_chatbot.env (env_file) ile ezer; compose dosyası hiçbir anahtar +# listelemez, böylece operatörün dosyası gölgelenemez. +# +# AI_BACKEND_URL köprünün sertifikayı çektiği HTTP kökü: backend konteynerinin +# kendi portu (compose'da PORT=7656). Sertifika her (yeniden) bağlanmada +# tazelenir. +ENV AI_BRIDGE_HOST=hezarfen-backend \ + AI_BRIDGE_PORT=8090 \ + AI_BACKEND_URL=http://hezarfen-backend:7656 \ + AI_SHARED_TOKEN=change-me \ + AI_TLS_SERVER_NAME=localhost \ + AI_SERVICE_NAME=celebi \ + HEZARFEN_ASSISTANT_ROLE=ogrenci \ + AI_MAX_CONCURRENT=8 \ + AI_RECONNECT_SECS=3 + +# Konteynerın işi köprüyü çalıştırmak. Katalog/benchmark komutları bu imajın +# içinde elle koşulur: `podman run --rm IMAGE python -m src.main --validate`. +CMD ["python", "-m", "src.bridge"] diff --git a/ReadMe.md b/ReadMe.md index 8f0d426..ae6b0e3 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -9,7 +9,7 @@ backend'e bağlanan QUIC köprüsüdür (`src/bridge.py`, `aioquic`). Bilgi kaynağı: [`docs/hezarfen-site-rehberi.md`](docs/hezarfen-site-rehberi.md). > **Backend'e bağlanıyor:** Çelebi, backend'in QUIC AI köprüsüne (protokol -> `hab/1`) dial-in eden istemciyle bağlanır — **[`src/bridge.py`](src/bridge.py)**; +> `hab/2`) dial-in eden istemciyle bağlanır — **[`src/bridge.py`](src/bridge.py)**; > `chat.reply` yeteneğini sunar, backend'in doğrulanmış oturum rolünü > `asker_role` alanından alır. Çalıştırma ve ortam değişkenleri dosya başındaki > docstring'de. @@ -32,7 +32,7 @@ Hezarfen-Rule-Based-Chatbot/ │ ├─ src/ # ── ASISTAN MOTORU ── │ ├─ engine.py # 🚪 GİRİŞ NOKTASI: handle_request(payload)->dict; boru hattını yönetir -│ ├─ bridge.py # 🔌 backend QUIC köprü istemcisi (hab/1, chat.reply) — aioquic +│ ├─ bridge.py # 🔌 backend QUIC köprü istemcisi (hab/2, chat.reply) — aioquic │ ├─ bridge_contract.py # 🔐 backend asker_role -> motor oturumu sözleşmesi (stdlib) │ ├─ catalog.py # 📚 VERİ: 98 intent + cevap metinleri + route + rol modeli + rol yetenekleri │ ├─ rules.py # kural katmanı (yüksek kesinlik, anahtar kelime eşleşmesi) diff --git a/compose.yaml b/compose.yaml index d683cb1..2742d0c 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,26 +1,31 @@ -# Çelebi ürün köprüsü — bu compose yalnızca TEK chatbot container'ı oluşturur. -# Önce backend compose ayakta olmalı; backend ağına bağlanıp QUIC/UDP ile -# hezarfen-backend:8090 adresine dial-in eder. Host portu veya demo web UI açmaz. +# Çelebi QUIC köprüsü — bu compose yalnızca TEK chatbot container'ı oluşturur. +# Backend compose ayakta olmalı; bu servis backend'in ağına katılır ve oradan +# QUIC/UDP ile `hezarfen-backend:8090` adresine dial-in eder. Host portu veya +# demo web arayüzü AÇMAZ (web.py yalnız geliştirici aracıdır). +# +# Varsayılanların TEK kaynağı Containerfile'ın ENV bloğudur; bu dosya hiçbir +# `environment:` girdisi taşımaz, böylece hiçbir şey operatörün dosyasını +# gölgeleyemez. Sunucuda ~/hezarfen_chatbot/hezarfen_chatbot.env ile ezilir. # # podman compose up -d --build +# +# Ön koşul: backend'de AI köprüsü AÇIK olmalı — hezarfen_backend.env içinde +# AI_QUIC_ADDR=0.0.0.0:8090 (127.0.0.1 DEĞİL: konteyner kendi loopback'ine +# bağlanırsa dışarıdan hiçbir servis ulaşamaz) ve AI_SHARED_TOKEN buradaki +# token ile AYNI olmalı. services: - bridge: + chatbot: build: context: . dockerfile: Containerfile - image: localhost/rule-based-chatbot:local - container_name: hezarfen-chatbot-bridge + # HEZARFEN_TAG deploy tarafından yazılan stack.env'den gelir (--env-file). + image: localhost/hezarfen_chatbot:${HEZARFEN_TAG:-latest} + container_name: hezarfen_chatbot init: true - command: ["python", "-m", "src.bridge"] - environment: - AI_BRIDGE_HOST: hezarfen-backend # backend container'ının adı - # aioquic bu hedefe UDP ile bağlanır; burada TCP port yayını yoktur. - AI_BRIDGE_PORT: "8090" - AI_BACKEND_URL: http://hezarfen-backend:8080 - AI_SHARED_TOKEN: change-me # backend ile AYNI olmalı - AI_TLS_SERVER_NAME: localhost # self-signed sertifikanın SAN'ı - AI_SERVICE_NAME: celebi - HEZARFEN_ASSISTANT_ROLE: ogrenci + env_file: + # Sunucuda elle yazılır (0600); laptopta yoktur. + - path: hezarfen_chatbot.env + required: false restart: unless-stopped networks: - backend_net diff --git a/deploy/hezarfen_chatbot.env.example b/deploy/hezarfen_chatbot.env.example new file mode 100644 index 0000000..905ff1c --- /dev/null +++ b/deploy/hezarfen_chatbot.env.example @@ -0,0 +1,52 @@ +# hezarfen_chatbot.env — Çelebi köprüsünün sunucu ayarları. +# +# Sunucuda TEK SEFERLİK, elle: +# mkdir -p ~/hezarfen_chatbot +# cp hezarfen_chatbot.env.example ~/hezarfen_chatbot/hezarfen_chatbot.env +# +# chmod 0600 ~/hezarfen_chatbot/hezarfen_chatbot.env +# +# Hiçbir otomasyon bu dosyayı oluşturmaz, ezmez, yüklemez — operatörün malıdır; +# compose yalnız okur (`env_file`). Satırlar düz KEY=value: tırnak yok, `export` +# yok, satır sonu yorumu yok. +# +# Buradaki her anahtar Containerfile ENV bloğundaki varsayılanı EZER. Değerler +# konteyner BAŞLARKEN okunur: değişiklikten sonra yeniden oluştur +# (`podman compose up -d` ya da `systemctl --user restart hezarfen_chatbot_compose`). + +# ── Backend tarafı (ZORUNLU: ikisi backend ile aynı olmalı) ─────────────────── +# Backend'in QUIC köprüsü dinleyicisi. hezarfen_backend.env içinde +# AI_QUIC_ADDR=0.0.0.0:8090 OLMALI — 127.0.0.1 yazılıysa backend yalnız kendi +# konteyner loopback'ine bağlanır ve HİÇBİR servis dial-in edemez (Çelebi 503 +# "no AI service is connected" verir). Değiştirdikten sonra: +# systemctl --user restart hezarfen_backend_compose +AI_BRIDGE_HOST=hezarfen-backend +AI_BRIDGE_PORT=8090 + +# Sertifikanın çekildiği HTTP kökü — backend konteynerinin kendi portu. +AI_BACKEND_URL=http://hezarfen-backend:7656 + +# Paylaşılan sır: backend'in AI_SHARED_TOKEN'ı ile BİREBİR aynı olmalı. +# 'change-me' yalnız geliştirme değeridir; prod'da iki tarafı birlikte değiştir. +AI_SHARED_TOKEN=change-me + +# ── Servis kimliği ──────────────────────────────────────────────────────────── +# Sertifikadaki SAN (self-signed, backend her açılışta yeniler). +AI_TLS_SERVER_NAME=localhost +# Loglarda ve backend kaydında görünen ad. +AI_SERVICE_NAME=celebi +# Backend rol göndermezse kullanılacak yedek rol (ziyaretci|veli|ogrenci|ogretmen|yonetici|admin). +HEZARFEN_ASSISTANT_ROLE=ogrenci + +# ── Dayanıklılık ────────────────────────────────────────────────────────────── +# Aynı anda kabul edilen istek ve kopunca yeniden deneme aralığı (saniye). +AI_MAX_CONCURRENT=8 +AI_RECONNECT_SECS=3 + +# ── Sürüm etiketi ───────────────────────────────────────────────────────────── +# BURADAN OKUNMAZ: HEZARFEN_TAG yalnız compose interpolasyonudur ve deploy'un +# sahip olduğu stack.env içinde taşınır (ikinci `--env-file`, çakışan anahtarda +# o kazanır). Unit `--no-build` ile başlar, yani imaj sunucuda VAR olmalı: +# podman compose build # burada derle +# podman load -i image.tar # ya da hazır imajı yükle +#HEZARFEN_TAG=latest diff --git a/deploy/hezarfen_chatbot_compose.service b/deploy/hezarfen_chatbot_compose.service new file mode 100644 index 0000000..6427c61 --- /dev/null +++ b/deploy/hezarfen_chatbot_compose.service @@ -0,0 +1,40 @@ +# systemd KULLANICI unit'i: Çelebi köprüsünü podman compose ile çalıştırır. +# %h/hezarfen_chatbot içinde beklenen dosyalar: +# compose.yaml bu repodan (ya da deploy artefaktından) +# hezarfen_chatbot.env 0600, deploy/hezarfen_chatbot.env.example'dan +# ELLE yazılır — otomasyon oluşturmaz/ezmez +# stack.env deploy sahipli; HEZARFEN_TAG taşır +# +# Unit `--no-build` ile başlar, yani imaj sunucuda zaten olmalı: +# podman compose build # burada derle +# podman load -i image.tar # ya da hazır imajı yükle +# +# hezarfen_chatbot.env içindeki anahtarlar (tam belge: deploy/hezarfen_chatbot.env.example). +# Hepsinin varsayılanı imajın ENV bloğundadır (Containerfile) — bu dosya ezer: +# AI_BRIDGE_HOST / AI_BRIDGE_PORT backend'in QUIC dinleyicisi (ağ içi ad) +# AI_BACKEND_URL sertifikanın çekildiği HTTP kökü +# AI_SHARED_TOKEN backend ile AYNI olmalı +# HEZARFEN_ASSISTANT_ROLE yedek rol +# +# Sadece ortam değişkeni değiştiğinde yeniden başlatma (ExecStart'ı yeniden +# koşar, ortamı değişen konteynerı yeniden oluşturur): +# systemctl --user restart hezarfen_chatbot_compose + +[Unit] +Description=Hezarfen Celebi QUIC bridge (rule-based chatbot) +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +RemainAfterExit=yes +WorkingDirectory=%h/hezarfen_chatbot +# Sonraki --env-file çakışan anahtarda kazanır: önce operatörün ayar dosyası, +# sonra deploy sahipli stack.env (HEZARFEN_TAG). +ExecStart=/usr/bin/podman compose --env-file %h/hezarfen_chatbot/hezarfen_chatbot.env --env-file %h/hezarfen_chatbot/stack.env up -d --no-build +# -v yok: isimli volume'lar stop'ta yaşamalı (köprü durumsuzdur ama şekil aynı). +ExecStop=/usr/bin/podman compose down +TimeoutStartSec=180 + +[Install] +WantedBy=default.target diff --git a/src/bridge.py b/src/bridge.py index a767236..f5a8d68 100644 --- a/src/bridge.py +++ b/src/bridge.py @@ -3,7 +3,7 @@ Backend (``hezarfen_backend``) bir QUIC **sunucusudur**: AI servisleri ona *dial-in* eder, sundukları yetenekleri (`capabilities`) kaydeder ve backend her sohbet turunu bu bağlantı üzerinden bir isteğe çevirir. Bu modül o istemcinin -Python tarafıdır; wire protokolü backend'deki ``src/ai/protocol.rs`` ("hab/1") +Python tarafıdır; wire protokolü backend'deki ``src/ai/protocol.rs`` ("hab/2") ile birebir aynıdır. Akış (bkz. backend ``src/ai/mod.rs`` ve ``server.rs``): @@ -11,7 +11,7 @@ Akış (bkz. backend ``src/ai/mod.rs`` ve ``server.rs``): 1. Backend'in HTTP'sinden sertifikayı çek (``GET /ai/certificate``) ve pinle. Self-signed sertifika her açılışta yenilendiği için her (yeniden) bağlanmada tazelenir. -2. QUIC ile ``AI_QUIC_ADDR``'e bağlan (ALPN ``hab/1``). +2. QUIC ile ``AI_QUIC_ADDR``'e bağlan (ALPN ``hab/2``). 3. İlk *client-initiated* çift yönlü akış = **kontrol akışı**: bir ``Hello`` yaz, bir ``Greeting`` oku, akışı hayat boyu açık tut (kapanması = kayıttan düşme sinyali). @@ -67,7 +67,10 @@ from .bridge_contract import resolve_session from .engine import Engine, RequestError, get_default_engine # --- Protokol sabitleri (backend src/constant.rs ile eşleşir) --------------- -PROTOCOL = "hab/1" +# AI_PROTOCOL/AI_ALPN backend'de "hab/2": sunucu hello.protocol'u bununla +# karşılaştırır ve ALPN listesi de aynı dizedir. Sürüm burada geride kalırsa +# backend kaydı reddeder ("this backend speaks hab/2, the service announced …"). +PROTOCOL = "hab/2" CHAT_CAPABILITY = "chat.reply" MAX_FRAME_BYTES = 8 * 1024 * 1024 KEEPALIVE_SECS = 10 # backend AI_IDLE_TIMEOUT_SECS=30; altında tutulur