diff --git a/.dockerignore b/.dockerignore index 90bda34..bd03601 100644 --- a/.dockerignore +++ b/.dockerignore @@ -12,6 +12,15 @@ coverage backend/target backend/.mvn/wrapper/maven-wrapper.jar +# Geliştirme araçları, belgeler ve native projeler. İki Dockerfile da +# bunları kullanmıyor: frontend dosyaları tek tek sayıyor, backend yalnızca +# backend/ ve src/content/tr'yi kopyalıyor. Dışlanmaları, ileride yazılacak +# geniş bir COPY'nin (ör. `COPY . .`) bunları imaja taşımasını engeller. +android +ios +docs +scripts + .env .env.local .idea diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7b7cb02..d9e763d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,10 +14,14 @@ on: - "package.json" - "package-lock.json" - "vite.config.ts" + - "capacitor.config.ts" + - "scripts/**" - "tsconfig*.json" - "eslint.config.js" + - "privacy/**" - "backend/**" - "Dockerfile.frontend" + - ".dockerignore" - "deploy/**" - "docker-compose.prod.yml" - ".github/workflows/**" @@ -40,6 +44,9 @@ jobs: - run: npm ci - run: npm run lint + # Betiklerin ve içerik denetiminin tipleri; build'in tsc -b'si + # yalnızca production projelerini kontrol ediyor. + - run: npm run typecheck - run: npm test # tsc -b tip hatalarını da yakalar; derlenemeyen kod image'a gitmesin. - run: npm run build @@ -63,3 +70,36 @@ jobs: # mvnw Windows'ta commit'lendiği için git'te çalıştırma izni yok. # Testcontainers runner'daki Docker'ı kullanır, ek kurulum gerekmez. - run: chmod +x mvnw && ./mvnw -B verify + + # Testler tam checkout'ta çalışıyor, Dockerfile'lar ise dosyaları tek tek + # kopyalıyor: kopyalanmayan bir dosyaya bağımlılık testlerde görünmez, + # yalnızca imajda düşer (PR #58'den sonra dört deploy böyle kaldı). Bu yüzden + # PR'da iki image da push edilmeden derlenir. deploy.yml bu workflow'u + # çağırdığında atlanır; orada build job'u aynı image'ları zaten derliyor. + images: + name: Image derlemesi (${{ matrix.image }}) + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + strategy: + # Biri düşse de diğeri sonuna kadar derlensin, ikisinin durumu da görünsün. + fail-fast: false + matrix: + include: + - image: slot-frontend + dockerfile: Dockerfile.frontend + - image: slot-backend + dockerfile: backend/Dockerfile + steps: + - uses: actions/checkout@v4 + + - uses: docker/setup-buildx-action@v3 + + # Bağlam ve cache kapsamı deploy.yml'deki ile aynı, böylece main'in + # deploy cache'inden okur. Cache'e yazmaz: PR'ların cache'i depo + # kotasında main'inkini itmesin. + - uses: docker/build-push-action@v6 + with: + context: . + file: ${{ matrix.dockerfile }} + push: false + cache-from: type=gha,scope=${{ matrix.image }} diff --git a/CLAUDE.md b/CLAUDE.md index 6425939..c4b5f2b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -91,6 +91,24 @@ shadcn/ui bileşenleri ihtiyaç oldukça tek tek eklenir, toplu kurulmaz. - Soru içeriğini başka sitelerden kopyalama. İçerik özgün yazılır, `source` alanında türetildiği konu belirtilir. +## Derleme ve CI + +- **`tsc -b` yalnızca production projelerini derler.** Kök `tsconfig.json`'ın + references'ı `Dockerfile.frontend`'in kopyaladığı dosyalarla sınırlı: + app ve node (yalnızca `vite.config.ts`). Betikler ve `capacitor.config.ts` + `tsconfig.scripts.json`'da, içerik denetimi `tsconfig.content-check.json`'da; + tiplerini `npm run typecheck` kontrol eder, CI'da çalışır. Kök references'a + araç eklenirse imajda dosya bulunamaz: PR #58'de böyle oldu, dört deploy + kurulmadı, CI tam checkout'ta derlediği için yeşil kaldı. +- **PR'da iki image push edilmeden derlenir** (`ci.yml`, `images` job'u). + Testler tam checkout'ta, Dockerfile'lar tek tek sayılan dosyalarla + çalışıyor; aradaki fark yalnızca image derlemesinde görünür. Job + `deploy.yml`'den çağrıldığında atlanır, orada build job'u aynı işi yapıyor. +- **Bir image düşerse hiçbiri kurulmaz.** Compose ikisini tek `IMAGE_TAG` + ile çeker; frontend derlenemezse backend ve soru seeder'ı da eski sürümde + kalır. Canlı içeriğin bir commit'le aynı olup olmadığını + `npm run check:live -- [revizyon]` gösterir. + ## Backend (`backend/`) - **Sadece senkron için.** Uygulama backend'siz tam çalışır diff --git a/Dockerfile.frontend b/Dockerfile.frontend index c8df25f..a50069a 100644 --- a/Dockerfile.frontend +++ b/Dockerfile.frontend @@ -11,7 +11,9 @@ COPY package.json package-lock.json ./ RUN npm ci # Derleme için gereken dosyalar tek tek sayılıyor; backend/ gibi ilgisiz -# dizinler bağlama girse de imaja kopyalanmıyor. +# dizinler bağlama girse de imaja kopyalanmıyor. tsconfig.json'ın +# references'ındaki her proje ve kapsadığı dosyalar burada olmalı; +# geliştirme araçlarının tsconfig'leri bilerek orada değil. COPY index.html vite.config.ts tsconfig.json tsconfig.app.json tsconfig.node.json ./ COPY public public COPY src src diff --git a/docs/deploy.md b/docs/deploy.md index eda4b67..ff289a6 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -22,11 +22,16 @@ internet ──443──> host nginx (TLS) | Tetik | Workflow | Ne yapar | |---|---|---| -| PR (kod değişikliği) | `ci.yml` | Frontend: lint, test, build. Backend: `./mvnw verify` (Testcontainers ile gerçek Postgres). | +| PR (kod değişikliği) | `ci.yml` | Frontend: lint, typecheck, test, build. Backend: `./mvnw verify` (Testcontainers ile gerçek Postgres). İki image push edilmeden derlenir. | | `main`'e push | `deploy.yml` | Testler → iki image'ı derle, ghcr.io'ya it → compose dosyasını scp ile kopyala → SSH ile `pull` + `up -d` → `/api/health` 200 dönene kadar 3 dk bekle. | -Testler geçmezse `build` ve `deploy` job'ları hiç çalışmaz. Yalnızca -`docs/` ya da `.md` değişen push'lar deploy tetiklemez. +Testler geçmezse `build` ve `deploy` job'ları hiç çalışmaz. İki image'dan +biri derlenemezse hiçbiri kurulmaz: compose ikisini aynı `IMAGE_TAG` ile +çeker, yalnızca backend'i kurmanın yolu yok. Yalnızca `docs/` ya da `.md` +değişen push'lar deploy tetiklemez. + +Canlıdaki soru içeriğinin bir commit'le aynı olup olmadığını +`npm run check:live -- [revizyon]` gösterir (varsayılan `HEAD`, fark varsa çıkış kodu 1). `ci.yml` yalnızca ilgili yollar değişince çalışır. Branch protection'da bu job'lar zorunlu kontrol yapılırsa, yalnızca doküman değiştiren bir PR diff --git a/package.json b/package.json index 1259e4e..954bc2a 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "dev": "vite", "build": "tsc -b && vite build", "lint": "eslint .", + "typecheck": "tsc -b tsconfig.json tsconfig.scripts.json tsconfig.content-check.json", "preview": "vite preview", "cap:sync": "npm run build && cap sync android", "android:open": "cap open android", @@ -25,7 +26,8 @@ "store:screenshots": "node scripts/store-screenshots.mjs", "feature-graphic": "node scripts/generate-feature-graphic.mjs", "merge-questions": "node scripts/merge-questions.ts", - "check:content": "node scripts/content-check.ts" + "check:content": "node scripts/content-check.ts", + "check:live": "node scripts/check-live.ts" }, "dependencies": { "@capacitor/android": "8.5.2", diff --git a/scripts/check-live.ts b/scripts/check-live.ts new file mode 100644 index 0000000..194f18b --- /dev/null +++ b/scripts/check-live.ts @@ -0,0 +1,142 @@ +/* ------------------------------------------------------------------ */ +/* Canlı içerik kontrolü — sunucudaki soruları repodakiyle karşılaştırır */ +/* */ +/* npm run check:live -- [revizyon] [--url https://...] */ +/* */ +/* Sunucunun /api/questions yanıtı, verilen revizyondaki (varsayılan */ +/* HEAD) src/content/tr ile soru soru karşılaştırılır. Deploy sonrası */ +/* seeder'ın içeriği yazdığını doğrulamak için: fark yoksa çıkış kodu */ +/* 0, varsa 1. */ +/* ------------------------------------------------------------------ */ + +import { execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; + +const REPO_ROOT = fileURLToPath(new URL("..", import.meta.url)); +const CONTENT_PATH = "src/content/tr"; +const DEFAULT_URL = "https://slot.meteucar.com"; +const USAGE = "Kullanım: npm run check:live -- [revizyon] [--url ]"; + +/** Seeder'ın veritabanına yazdığı ve /api/questions'ın döndürdüğü alanlar. */ +const FIELDS = ["category", "topic", "difficulty", "kind", "prompt", "modelAnswer", "keyConcepts", "followUps", "source"]; + +/** Listelenen örnek id sayısı; geri kalanı yalnızca sayılır. */ +const SAMPLE_SIZE = 5; + +type RawQuestion = { id: string; category: string } & Record; +type Pool = Map; + +async function main(argv: string[]): Promise { + const options = readOptions(argv); + if (!options) { + console.error(USAGE); + return 2; + } + const { revision, baseUrl } = options; + + const repo = loadRevision(revision); + const live = await loadLive(baseUrl); + + console.log(`Canlı: ${baseUrl} — ${live.size} soru`); + console.log(`Repo: ${git("rev-parse", "--short", revision).trim()} (${revision}) — ${repo.size} soru\n`); + printCategoryCounts(live, repo); + + const missing = [...repo.keys()].filter((id) => !live.has(id)); + const extra = [...live.keys()].filter((id) => !repo.has(id)); + const changed = [...repo.keys()].filter((id) => live.has(id) && live.get(id)?.fingerprint !== repo.get(id)?.fingerprint); + + printGroup("Canlıda yok", missing); + printGroup("Repoda yok", extra); + printGroup("İçerik farklı", changed); + + if (missing.length + extra.length + changed.length === 0) { + console.log("\nCanlı içerik bu revizyonla aynı."); + return 0; + } + console.log("\nCanlı içerik bu revizyondan farklı: deploy edilmemiş ya da seeder çalışmamış olabilir."); + return 1; +} + +/** Geçersiz kullanımda null; bilinmeyen seçenek de kullanım hatası sayılır. */ +function readOptions(argv: string[]): { revision: string; baseUrl: string } | null { + try { + const { values, positionals } = parseArgs({ args: argv, options: { url: { type: "string" } }, allowPositionals: true }); + if (positionals.length > 1) return null; + return { revision: positionals[0] ?? "HEAD", baseUrl: values.url ?? DEFAULT_URL }; + } catch { + return null; + } +} + +/** Bir git revizyonundaki içerik; çalışma ağacına dokunmadan `git show` ile okunur. */ +function loadRevision(revision: string): Pool { + const questions = git("ls-tree", "--name-only", revision, `${CONTENT_PATH}/`) + .split("\n") + .filter((path) => path.endsWith(".json")) + .flatMap((path) => (JSON.parse(git("show", `${revision}:${path}`)) as { questions: RawQuestion[] }).questions); + return toPool(questions); +} + +async function loadLive(baseUrl: string): Promise { + const url = new URL("/api/questions", baseUrl); + // fetch'in kendi mesajı yalnızca "fetch failed"; asıl neden cause'ta. + const response = await fetch(url).catch((error: Error) => { + throw new Error(`${url}: ${(error.cause as Error | undefined)?.message ?? error.message}`); + }); + if (!response.ok) throw new Error(`${url}: HTTP ${response.status}`); + return toPool((await response.json()) as RawQuestion[]); +} + +function toPool(questions: RawQuestion[]): Pool { + return new Map(questions.map((question) => [question.id, { category: question.category, fingerprint: fingerprint(question) }])); +} + +function fingerprint(question: RawQuestion): string { + return canonical(Object.fromEntries(FIELDS.map((field) => [field, question[field]]))); +} + +/** + * Anahtarları sıralı, boş (null/undefined) alanları atlanmış JSON. JSONB + * anahtar sırasını korumuyor, API de dosyada olmayan alanı null döndürüyor; + * ikisi de içerik farkı sayılmamalı. + */ +function canonical(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`; + if (value !== null && typeof value === "object") { + const entries = Object.entries(value) + .filter(([, field]) => field !== null && field !== undefined) + .sort(([a], [b]) => (a < b ? -1 : 1)); + return `{${entries.map(([key, field]) => `${JSON.stringify(key)}:${canonical(field)}`).join(",")}}`; + } + return JSON.stringify(value); +} + +function printCategoryCounts(live: Pool, repo: Pool): void { + const count = (pool: Pool, category: string) => [...pool.values()].filter((q) => q.category === category).length; + const categories = [...new Set([...live.values(), ...repo.values()].map((q) => q.category))].sort(); + console.log(`${"kategori".padEnd(16)}${"canlı".padStart(6)}${"repo".padStart(6)}`); + for (const category of categories) { + const [liveCount, repoCount] = [count(live, category), count(repo, category)]; + const marker = liveCount === repoCount ? "" : " ←"; + console.log(`${category.padEnd(16)}${String(liveCount).padStart(6)}${String(repoCount).padStart(6)}${marker}`); + } + console.log(); +} + +function printGroup(label: string, ids: string[]): void { + console.log(`${label}: ${ids.length}`); + for (const id of ids.slice(0, SAMPLE_SIZE)) console.log(` - ${id}`); + if (ids.length > SAMPLE_SIZE) console.log(` … ve ${ids.length - SAMPLE_SIZE} tane daha`); +} + +function git(...args: string[]): string { + return execFileSync("git", args, { cwd: REPO_ROOT, encoding: "utf8", maxBuffer: 1e8 }); +} + +try { + process.exitCode = await main(process.argv.slice(2)); +} catch (error) { + console.error((error as Error).message); + process.exitCode = 1; +} diff --git a/tsconfig.json b/tsconfig.json index 4a20417..732b00a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,8 +1,14 @@ { + /* + Yalnızca production derlemesinin (npm run build → tsc -b) projeleri. + Dockerfile.frontend bunları ve kapsadıkları dosyaları tek tek kopyalıyor; + buraya eklenen her proje orada da kopyalanmalı. Geliştirme araçlarının + projeleri (tsconfig.scripts.json, tsconfig.content-check.json) bilerek + burada değil, tipleri npm run typecheck'te kontrol ediliyor. + */ "files": [], "references": [ { "path": "./tsconfig.app.json" }, - { "path": "./tsconfig.node.json" }, - { "path": "./tsconfig.content-check.json" } + { "path": "./tsconfig.node.json" } ] } diff --git a/tsconfig.node.json b/tsconfig.node.json index b35dbc1..30942e7 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -19,7 +19,6 @@ "erasableSyntaxOnly": true, "noFallthroughCasesInSwitch": true }, - "include": ["vite.config.ts", "capacitor.config.ts", "scripts/**/*.ts"], - /* src/domain'i import ediyor; kendi ayarıyla tsconfig.content-check.json'da */ - "exclude": ["scripts/content-check.ts", "scripts/content-check/**"] + /* Yalnızca derlemenin kendisi; betikler ve capacitor.config.ts tsconfig.scripts.json'da */ + "include": ["vite.config.ts"] } diff --git a/tsconfig.scripts.json b/tsconfig.scripts.json new file mode 100644 index 0000000..96f286a --- /dev/null +++ b/tsconfig.scripts.json @@ -0,0 +1,29 @@ +{ + /* + Geliştirme araçları: Node'da doğrudan çalışan betikler ve Capacitor + yapılandırması. Production derlemesine girmez (Dockerfile.frontend + bunları kopyalamıyor); tipleri npm run typecheck kontrol ediyor. + */ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.scripts.tsbuildinfo", + "target": "es2023", + "lib": ["ES2023"], + "types": ["node"], + "skipLibCheck": true, + + "module": "nodenext", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + + /* Linting */ + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["capacitor.config.ts", "scripts/**/*.ts"], + /* src/domain'i import ediyor; kendi ayarıyla tsconfig.content-check.json'da */ + "exclude": ["scripts/content-check.ts", "scripts/content-check/**"] +}