YiBi Dev Docs
架構

後端 Clean Architecture 分層架構

版本: 2.0 | 日期: 2026-03-06 前提文件: system-overview.mdscalability-plan.mdvoice-lab-learnings.md

1. 架構概覽

yibi-mvp 後端採用 Clean Architecture 四層分離,參考 voice-lab 在 195+ commits 中驗證的架構(詳見 voice-lab-learnings.md §2.1)。

Presentation (routes, DI, API handlers)
    ↓ depends on
Application (use cases/services, DTOs/schemas)
    ↓ depends on
Domain (pure business logic, interfaces/protocols)
    ↓ implemented by
Infrastructure (SQLAlchemy models, provider implementations, workers, config)

2. 目錄結構

backend/src/
├── main.py                           # Composition root
├── celery_app.py                     # Celery composition root

├── presentation/                     # 路由、DI、API handlers
│   ├── dependencies.py               # get_current_user, CurrentUser, OAuth2
│   └── api/v1/
│       ├── __init__.py               # router 組裝
│       ├── auth.py
│       ├── children.py
│       ├── content.py
│       └── health.py

├── application/                      # Use cases、DTOs
│   ├── schemas/
│   │   ├── auth.py
│   │   ├── child.py
│   │   ├── common.py
│   │   ├── content.py
│   │   └── generation_job.py
│   └── services/
│       ├── auth_service.py
│       ├── child_service.py
│       ├── content_service.py
│       └── story_engine.py

├── domain/                           # 純業務邏輯,零外部依賴
│   ├── story/
│   │   ├── schemas.py                # StoryScript, StorySegment
│   │   ├── safety.py                 # check_content_safety()
│   │   ├── prompts.py                # build_system_prompt/user_prompt
│   │   └── errors.py                 # ContentUnsafeError
│   └── interfaces/
│       ├── storage.py                # IStorageProvider (Protocol)
│       └── tts.py                    # ITTSProvider (Protocol)

├── data/                             # 靜態資料
│   ├── default_options.py
│   └── milestones.py

└── infrastructure/                   # 所有實作細節
    ├── config/
    │   ├── settings.py               # Settings class
    │   ├── database.py               # AsyncSession, get_db
    │   └── security.py               # JWT, password hashing
    ├── persistence/
    │   ├── base.py                   # SQLAlchemy Base, mixins
    │   └── models/
    │       ├── __init__.py           # re-export all models + Base
    │       ├── user.py
    │       ├── family.py
    │       ├── family_member.py
    │       ├── child_profile.py
    │       ├── content.py
    │       └── generation_job.py
    ├── providers/
    │   ├── ai/
    │   │   └── gemini_client.py
    │   ├── storage/
    │   │   ├── local.py
    │   │   ├── gcs.py
    │   │   └── factory.py
    │   └── tts/
    │       └── google_tts.py
    └── workers/
        └── content_generation.py     # Celery task

3. 各層職責

Presentation

  • FastAPI 路由定義與 request/response 處理
  • 依賴注入(get_current_userget_db
  • 錯誤攔截與 HTTP status code 映射
  • 不包含業務邏輯

Application

  • Services: 業務流程編排(呼叫 domain logic、操作 DB、串接 providers)
  • Schemas: Pydantic DTOs,定義 API 輸入/輸出格式
  • 目前 services 直接操作 AsyncSession + ORM,暫未引入 Repository pattern

Domain

  • 純業務邏輯:prompt 建構、安全檢查、資料結構定義
  • Interfaces: Protocol 定義 provider 契約(storage、TTS)
  • 零外部依賴:不 import FastAPI、SQLAlchemy 等框架
  • 獨立可測試,無需 mock

Infrastructure

  • Config: 應用程式設定、DB 連線、JWT/密碼處理
  • Persistence: SQLAlchemy model 定義(entity + persistence 合一)
  • Providers: 外部服務實作(Gemini AI、Google TTS、Storage)
  • Workers: Celery 非同步任務

4. 依賴規則

presentation → application → domain

              infrastructure
  • Presentation 可 import Application 和 Infrastructure(config、database)
  • Application 可 import Domain 和 Infrastructure(models、config)
  • Domain 不 import 任何其他層
  • Infrastructure 可 import Domain(實作 interfaces)和 Application(schemas)

5. 命名慣例

與 voice-lab 一致,確保跨專案的認知一致性:

類別命名規則範例
Provider interfaceI{Name}ProviderITTSProvider, IStorageProvider
Repository interfaceI{Entity}RepositoryIStoryRepository, IUserRepository
Provider 實作{Vendor}{Type}ProviderGoogleTTSProvider, GCSStorageProvider
Repository 實作SqlAlchemy{Entity}RepositorySqlAlchemyStoryRepository
Factoryget_{type}_provider()get_storage_provider()
Domain error{Name}ErrorContentUnsafeError

6. 可直接複製的 voice-lab 元件

元件voice-lab 路徑yibi 用途複製難度
ITTSProvider ABCinfrastructure/providers/tts/factory.pyTTS 多 provider 切換直接複製
ILLMProvider ABCinfrastructure/providers/llm/factory.pyLLM model 切換直接複製
Job Workerinfrastructure/workers/job_worker.pyStory/Music 生成直接複製
Error hierarchydomain/errors.py統一錯誤處理直接複製
Repository patterninfrastructure/persistence/DB 存取抽象需適配 yibi schema

詳細的元件清單與改造說明見 voice-lab-learnings.md §5


7. 未來演進方向

  • Repository pattern: 當 services 需要大量 mock DB 做單元測試時,引入 I{Entity}Repository 抽象
  • Domain entity: 當業務規則複雜到需獨立於 ORM 時,引入 dataclass entity
  • Use case 類: 當 service 方法過多時,拆分為獨立的 Use case 類

8. 與其他架構文件的關係

文件關注點與本文件的關係
system-overview.md系統全貌、分層說明、技術選型本文件細化「邏輯與 API 層」的內部結構
scalability-plan.md按裝置數量的基礎設施升級本文件關注程式碼分層,與基礎設施升級正交
voice-lab-learnings.mdvoice-lab 的完整知識轉移本文件從中提取後端分層的具體架構

On this page