12-factor-apps

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

12-Factor App Compliance Analysis

12-Factor App合规性分析

Overview

概述

The 12-Factor App methodology is a set of best practices for building Software-as-a-Service applications that are:
  • Portable across execution environments
  • Scalable without architectural changes
  • Suitable for continuous deployment
  • Maintainable with minimal friction
12-Factor App方法论是一套构建软件即服务(SaaS)应用的最佳实践,这类应用具备以下特性:
  • 可在不同执行环境间移植
  • 无需修改架构即可实现扩容
  • 适合持续部署
  • 维护成本低、摩擦小

Input Parameters

输入参数

ParameterDescriptionRequired
codebase_path
Root path of the codebase to analyzeRequired
参数描述是否必填
codebase_path
待分析代码库的根路径必填

Analysis Framework

分析框架

Factor I: Codebase

要素I:代码库

Principle: One codebase tracked in revision control, many deploys.
Search Patterns:
bash
undefined
原则: 一个代码库对应版本控制追踪,可部署到多个环境。
搜索模式:
bash
undefined

Check for version control

检查版本控制

ls -la .git 2>/dev/null || ls -la .hg 2>/dev/null
ls -la .git 2>/dev/null || ls -la .hg 2>/dev/null

Check for multiple apps sharing codebase

检查是否有多个应用共享代码库

find . -name "package.json" -o -name "pyproject.toml" -o -name "setup.py" | head -20
find . -name "package.json" -o -name "pyproject.toml" -o -name "setup.py" | head -20

Check for environment-specific code branches

检查是否有环境特定的代码分支

grep -r "if.production|if.development|if.staging" --include=".py" --include=".js" --include=".ts"

**File Patterns:** `.git/`, `package.json`, `pyproject.toml`, deployment configs

**Compliance Criteria:**

| Level | Criteria |
|-------|----------|
| **Strong** | Single Git repo, same codebase for all environments, no env-specific code branches |
| **Partial** | Single repo but some environment-specific code paths |
| **Weak** | Multiple repos for same app or significant code duplication across environments |

**Anti-patterns:**
- Multiple Git repositories for the same application
- Environment-specific code branches (`if production: ...`)
- Different source files for dev vs prod
- Shared code not extracted to libraries

---
grep -r "if.production|if.development|if.staging" --include=".py" --include=".js" --include=".ts"

**文件模式:** `.git/`, `package.json`, `pyproject.toml`, 部署配置文件

**合规标准:**

| 等级 | 标准 |
|-------|----------|
| **强合规** | 单一Git仓库,所有环境使用同一代码库,无环境特定代码分支 |
| **部分合规** | 单一仓库但存在部分环境特定代码路径 |
| **弱合规** | 同一应用对应多个仓库,或不同环境间存在大量代码重复 |

**反模式:**
- 同一应用对应多个Git仓库
- 环境特定代码分支(如`if production: ...`)
- 开发环境与生产环境使用不同源文件
- 共享代码未提取为独立库

---

Factor II: Dependencies

要素II:依赖

Principle: Explicitly declare and isolate dependencies.
Search Patterns:
bash
undefined
原则: 显式声明并隔离依赖。
搜索模式:
bash
undefined

Python dependency files

Python依赖文件

find . -name "requirements.txt" -o -name "pyproject.toml" -o -name "setup.py" -o -name "Pipfile" -o -name "uv.lock"
find . -name "requirements.txt" -o -name "pyproject.toml" -o -name "setup.py" -o -name "Pipfile" -o -name "uv.lock"

JavaScript/TypeScript dependency files

JavaScript/TypeScript依赖文件

find . -name "package.json" -o -name "package-lock.json" -o -name "yarn.lock" -o -name "pnpm-lock.yaml"
find . -name "package.json" -o -name "package-lock.json" -o -name "yarn.lock" -o -name "pnpm-lock.yaml"

Check for system tool assumptions

检查是否依赖系统工具

grep -r "subprocess.*curl|subprocess.*wget|os.system.ffmpeg|shutil.which" --include=".py" grep -r "exec.curl|child_process.curl" --include=".js" --include=".ts"
grep -r "subprocess.*curl|subprocess.*wget|os.system.ffmpeg|shutil.which" --include=".py" grep -r "exec.curl|child_process.curl" --include=".js" --include=".ts"

Docker/container isolation

Docker/容器隔离

find . -name "Dockerfile" -o -name "docker-compose*.yml"

**File Patterns:** `**/requirements*.txt`, `**/package.json`, `**/*.lock`, `**/Dockerfile`

**Compliance Criteria:**

| Level | Criteria |
|-------|----------|
| **Strong** | Lock files present, dependency isolation (venv/Docker), no implicit system tools |
| **Partial** | Dependencies declared but no lock files or isolation |
| **Weak** | Dependencies in documentation only, relies on system-installed packages |

**Anti-patterns:**
- Missing lock files (non-deterministic builds)
- Assuming system tools (curl, ImageMagick, ffmpeg) are available
- Different dependency managers in dev vs production
- No virtual environment or container isolation

---
find . -name "Dockerfile" -o -name "docker-compose*.yml"

**文件模式:** `**/requirements*.txt`, `**/package.json`, `**/*.lock`, `**/Dockerfile`

**合规标准:**

| 等级 | 标准 |
|-------|----------|
| **强合规** | 存在锁定文件,依赖隔离(虚拟环境/Docker),无隐式系统工具依赖 |
| **部分合规** | 已声明依赖但无锁定文件或隔离措施 |
| **弱合规** | 仅在文档中提及依赖,依赖系统预装包 |

**反模式:**
- 缺少锁定文件(构建结果不确定)
- 假设系统已安装特定工具(curl、ImageMagick、ffmpeg等)
- 开发与生产环境使用不同依赖管理器
- 无虚拟环境或容器隔离

---

Factor III: Config

要素III:配置

Principle: Store config in the environment.
Search Patterns:
bash
undefined
原则: 在环境中存储配置。
搜索模式:
bash
undefined

Environment variable usage

环境变量使用情况

grep -r "os.environ|os.getenv|process.env|ENV[" --include=".py" --include=".js" --include=".ts" --include=".rb"
grep -r "os.environ|os.getenv|process.env|ENV[" --include=".py" --include=".js" --include=".ts" --include=".rb"

Hardcoded credentials (anti-pattern)

硬编码凭证(反模式)

grep -r "password.=.['"]" --include=".py" --include=".js" --include=".ts" | grep -v "test|spec|example" grep -r "api_key.=.['"]" --include=".py" --include=".js" --include=".ts" | grep -v "test|spec|example" grep -r "secret.=.['"]" --include=".py" --include=".js" --include="*.ts" | grep -v "test|spec|example"
grep -r "password.=.['"]" --include=".py" --include=".js" --include=".ts" | grep -v "test|spec|example" grep -r "api_key.=.['"]" --include=".py" --include=".js" --include=".ts" | grep -v "test|spec|example" grep -r "secret.=.['"]" --include=".py" --include=".js" --include="*.ts" | grep -v "test|spec|example"

Environment-specific config files (anti-pattern)

环境特定配置文件(反模式)

find . -name "config.dev." -o -name "config.prod." -o -name "settings.development." -o -name "settings.production."
find . -name "config.dev." -o -name "config.prod." -o -name "settings.development." -o -name "settings.production."

Database URLs in code

代码中的数据库URL

grep -r "postgresql://|mysql://|mongodb://|redis://" --include=".py" --include=".js" --include="*.ts" | grep -v ".env|test|example"

**File Patterns:** `**/.env*`, `**/config/*.py`, `**/settings.py`, environment files

**Compliance Criteria:**

| Level | Criteria |
|-------|----------|
| **Strong** | All config via environment variables, no hardcoded secrets, could open-source without leaks |
| **Partial** | Most config externalized but some hardcoded defaults |
| **Weak** | Hardcoded credentials, environment-specific config files |

**Anti-patterns:**
- Hardcoded database URLs, API keys, passwords in source
- Config files like `config/production.yml` vs `config/development.yml`
- Environment grouping (`if ENV == 'production': ...`)
- Secrets committed to version control

---
grep -r "postgresql://|mysql://|mongodb://|redis://" --include=".py" --include=".js" --include="*.ts" | grep -v ".env|test|example"

**文件模式:** `**/.env*`, `**/config/*.py`, `**/settings.py`, 环境配置文件

**合规标准:**

| 等级 | 标准 |
|-------|----------|
| **强合规** | 所有配置通过环境变量传递,无硬编码密钥,开源代码不会导致信息泄露 |
| **部分合规** | 大部分配置已外部化,但存在部分硬编码默认值 |
| **弱合规** | 硬编码凭证,存在环境特定配置文件 |

**反模式:**
- 代码中硬编码数据库URL、API密钥、密码
- 存在`config/production.yml`与`config/development.yml`这类配置文件
- 按环境分组的逻辑(如`if ENV == 'production': ...`)
- 密钥已提交到版本控制

---

Factor IV: Backing Services

要素IV:后端服务

Principle: Treat backing services as attached resources.
Search Patterns:
bash
undefined
原则: 将后端服务视为附加资源。
搜索模式:
bash
undefined

Database connection via config

通过配置连接数据库

grep -r "DATABASE_URL|DB_HOST|REDIS_URL|CACHE_URL" --include=".py" --include=".js" --include="*.ts"
grep -r "DATABASE_URL|DB_HOST|REDIS_URL|CACHE_URL" --include=".py" --include=".js" --include="*.ts"

Service initialization

服务初始化

grep -r "create_engine|MongoClient|Redis|Celery|boto3" --include=".py" grep -r "createPool|createClient|new Redis|S3Client" --include=".js" --include="*.ts"
grep -r "create_engine|MongoClient|Redis|Celery|boto3" --include=".py" grep -r "createPool|createClient|new Redis|S3Client" --include=".js" --include="*.ts"

Hardcoded service locations (anti-pattern)

硬编码服务地址(反模式)

grep -r "localhost:5432|localhost:6379|localhost:27017|127.0.0.1" --include=".py" --include=".js" --include="*.ts" | grep -v "test|spec|example|default"

**File Patterns:** `**/database/*.py`, `**/services/*.py`, `**/db.py`, connection configurations

**Compliance Criteria:**

| Level | Criteria |
|-------|----------|
| **Strong** | All services via URL/connection string in config, swappable without code changes |
| **Partial** | Most services configurable but some hardcoded defaults |
| **Weak** | Hardcoded service locations, different code paths per environment |

**Anti-patterns:**
- Hardcoded `localhost` for services in production code
- Conditional logic for local vs cloud services (`if USE_S3: ... else: local_storage`)
- Service-specific code paths based on environment
- Different drivers for dev vs prod

---
grep -r "localhost:5432|localhost:6379|localhost:27017|127.0.0.1" --include=".py" --include=".js" --include="*.ts" | grep -v "test|spec|example|default"

**文件模式:** `**/database/*.py`, `**/services/*.py`, `**/db.py`, 连接配置文件

**合规标准:**

| 等级 | 标准 |
|-------|----------|
| **强合规** | 所有服务通过配置中的URL/连接字符串访问,无需修改代码即可替换 |
| **部分合规** | 大部分服务可配置,但存在部分硬编码默认值 |
| **弱合规** | 硬编码服务地址,不同环境对应不同代码路径 |

**反模式:**
- 生产代码中硬编码`localhost`作为服务地址
- 区分本地与云服务的条件逻辑(如`if USE_S3: ... else: local_storage`)
- 基于环境的服务特定代码路径
- 开发与生产环境使用不同驱动

---

Factor V: Build, Release, Run

要素V:构建、发布、运行

Principle: Strictly separate build and run stages.
Search Patterns:
bash
undefined
原则: 严格分离构建与运行阶段。
搜索模式:
bash
undefined

Build/deploy configuration

构建/部署配置

find . -name "Dockerfile" -o -name "Makefile" -o -name "build.sh" -o -name "deploy.sh" find . -name ".github/workflows/*.yml" -o -name ".gitlab-ci.yml" -o -name "Jenkinsfile"
find . -name "Dockerfile" -o -name "Makefile" -o -name "build.sh" -o -name "deploy.sh" find . -name ".github/workflows/*.yml" -o -name ".gitlab-ci.yml" -o -name "Jenkinsfile"

Build scripts in package.json

package.json中的构建脚本

grep -A5 '"scripts"' package.json 2>/dev/null | grep -E "build|start|deploy"
grep -A5 '"scripts"' package.json 2>/dev/null | grep -E "build|start|deploy"

Check for runtime compilation (anti-pattern)

检查运行时编译(反模式)

grep -r "compile|transpile|webpack" --include="*.py" | grep -v "test|build"

**File Patterns:** `**/Dockerfile`, `**/Makefile`, `**/.github/workflows/**`, CI/CD configs

**Compliance Criteria:**

| Level | Criteria |
|-------|----------|
| **Strong** | Immutable releases, clear build/release/run stages, unique release IDs |
| **Partial** | Build and run separated but release not immutable |
| **Weak** | Runtime code modifications, asset compilation at startup |

**Anti-patterns:**
- Runtime code modifications
- Asset compilation during application startup
- Configuration baked into build artifacts
- No release versioning

---
grep -r "compile|transpile|webpack" --include="*.py" | grep -v "test|build"

**文件模式:** `**/Dockerfile`, `**/Makefile`, `**/.github/workflows/**`, CI/CD配置文件

**合规标准:**

| 等级 | 标准 |
|-------|----------|
| **强合规** | 不可变发布版本,构建/发布/运行阶段清晰,发布版本ID唯一 |
| **部分合规** | 构建与运行阶段分离,但发布版本并非不可变 |
| **弱合规** | 运行时修改代码,启动时编译资源 |

**反模式:**
- 运行时修改代码
- 应用启动时编译资源
- 配置被固化到构建产物中
- 无发布版本控制

---

Factor VI: Processes

要素VI:进程

Principle: Execute the app as one or more stateless processes.
Search Patterns:
bash
undefined
原则: 以一个或多个无状态进程的形式运行应用。
搜索模式:
bash
undefined

Session storage patterns

会话存储模式

grep -r "session|Session" --include=".py" --include=".js" --include="*.ts" | head -20
grep -r "session|Session" --include=".py" --include=".js" --include="*.ts" | head -20

In-process state (anti-pattern)

进程内状态(反模式)

grep -r "global.cache|process_local|instance_cache" --include=".py" grep -r "global..=|module.exports.cache" --include=".js" --include="*.ts"
grep -r "global.cache|process_local|instance_cache" --include=".py" grep -r "global..=|module.exports.cache" --include=".js" --include="*.ts"

External session stores (good pattern)

外部会话存储(推荐模式)

grep -r "redis.session|memcached.session|session.redis" --include=".py" --include=".js" --include=".ts"
grep -r "redis.session|memcached.session|session.redis" --include=".py" --include=".js" --include=".ts"

Sticky session configuration (anti-pattern)

粘性会话配置(反模式)

grep -r "sticky.session|session.affinity" --include=".yml" --include=".yaml" --include="*.json"

**File Patterns:** `**/middleware/*.py`, `**/session/*.py`, server configurations

**Compliance Criteria:**

| Level | Criteria |
|-------|----------|
| **Strong** | Stateless processes, all state in external datastores (Redis, DB) |
| **Partial** | Mostly stateless but some in-process caching |
| **Weak** | Sticky sessions, in-process session storage, shared memory state |

**Anti-patterns:**
- In-process session storage (`user_sessions = {}`)
- Sticky sessions or session affinity
- File-based caching between requests
- Global mutable state shared across requests

---
grep -r "sticky.session|session.affinity" --include=".yml" --include=".yaml" --include="*.json"

**文件模式:** `**/middleware/*.py`, `**/session/*.py`, 服务器配置文件

**合规标准:**

| 等级 | 标准 |
|-------|----------|
| **强合规** | 无状态进程,所有状态存储在外部数据存储(Redis、数据库)中 |
| **部分合规** | 大部分为无状态,但存在部分进程内缓存 |
| **弱合规** | 使用粘性会话,进程内存储会话,共享内存状态 |

**反模式:**
- 进程内存储会话(如`user_sessions = {}`)
- 粘性会话或会话亲和性
- 请求间基于文件的缓存
- 请求间共享的全局可变状态

---

Factor VII: Port Binding

要素VII:端口绑定

Principle: Export services via port binding.
Search Patterns:
bash
undefined
原则: 通过端口绑定对外提供服务。
搜索模式:
bash
undefined

Self-contained port binding

自包含端口绑定

grep -r "app.run|server.listen|serve|uvicorn" --include=".py" grep -r "app.listen|server.listen|createServer" --include=".js" --include="*.ts"
grep -r "app.run|server.listen|serve|uvicorn" --include=".py" grep -r "app.listen|server.listen|createServer" --include=".js" --include="*.ts"

PORT environment variable

PORT环境变量

grep -r "PORT|port" --include=".py" --include=".js" --include="*.ts" | grep -i "environ|process.env"
grep -r "PORT|port" --include=".py" --include=".js" --include="*.ts" | grep -i "environ|process.env"

Webserver as dependency

Web服务器作为依赖

grep -r "uvicorn|gunicorn|flask|fastapi|express|koa|hapi" package.json pyproject.toml requirements.txt 2>/dev/null

**File Patterns:** `**/main.py`, `**/server.py`, `**/app.py`, `**/index.js`

**Compliance Criteria:**

| Level | Criteria |
|-------|----------|
| **Strong** | Self-contained app binds to PORT, webserver is a dependency |
| **Partial** | Port binding but not configurable via environment |
| **Weak** | Relies on external webserver container (Apache, Nginx) to provide HTTP |

**Anti-patterns:**
- Relying on Apache/Nginx/Tomcat to inject webserver functionality
- Hardcoded port numbers
- No PORT environment variable support
- CGI scripts or server modules

---
grep -r "uvicorn|gunicorn|flask|fastapi|express|koa|hapi" package.json pyproject.toml requirements.txt 2>/dev/null

**文件模式:** `**/main.py`, `**/server.py`, `**/app.py`, `**/index.js`

**合规标准:**

| 等级 | 标准 |
|-------|----------|
| **强合规** | 自包含应用绑定到PORT环境变量指定的端口,Web服务器作为依赖 |
| **部分合规** | 支持端口绑定,但无法通过环境变量配置 |
| **弱合规** | 依赖外部Web服务器容器(Apache、Nginx)提供HTTP服务 |

**反模式:**
- 依赖Apache/Nginx/Tomcat注入Web服务器功能
- 硬编码端口号
- 不支持PORT环境变量
- CGI脚本或服务器模块

---

Factor VIII: Concurrency

要素VIII:并发

Principle: Scale out via the process model.
Search Patterns:
bash
undefined
原则: 通过进程模型实现横向扩容。
搜索模式:
bash
undefined

Process definitions

进程定义文件

find . -name "Procfile" -o -name "process.yml" -o -name ".foreman"
find . -name "Procfile" -o -name "process.yml" -o -name ".foreman"

Multiple entry points

多个入口文件

find . -name "worker.py" -o -name "scheduler.py" -o -name "web.py"
find . -name "worker.py" -o -name "scheduler.py" -o -name "web.py"

Background job systems

后台任务系统

grep -r "celery|rq|sidekiq|bull|agenda" --include=".py" --include=".js" --include=".ts" grep -r "Celery|Worker|BackgroundJob" --include=".py" --include=".js" --include=".ts"

**File Patterns:** `**/Procfile`, `**/worker.py`, `**/scheduler.py`, queue configurations

**Compliance Criteria:**

| Level | Criteria |
|-------|----------|
| **Strong** | Explicit process types (web, worker, scheduler), horizontal scaling |
| **Partial** | Multiple process types but not easily scalable |
| **Weak** | Single monolithic process, no separation of concerns |

**Anti-patterns:**
- Single process handling all workloads
- Hard-coded worker counts in code
- No separation between web and background processes
- Vertical scaling only (bigger server, not more processes)

---
grep -r "celery|rq|sidekiq|bull|agenda" --include=".py" --include=".js" --include=".ts" grep -r "Celery|Worker|BackgroundJob" --include=".py" --include=".js" --include=".ts"

**文件模式:** `**/Procfile`, `**/worker.py`, `**/scheduler.py`, 队列配置文件

**合规标准:**

| 等级 | 标准 |
|-------|----------|
| **强合规** | 明确的进程类型(Web、Worker、Scheduler),支持横向扩容 |
| **部分合规** | 存在多个进程类型,但不易扩容 |
| **弱合规** | 单一单体进程,无职责分离 |

**反模式:**
- 单一进程处理所有工作负载
- 代码中硬编码Worker数量
- Web与后台进程未分离
- 仅支持纵向扩容(升级服务器配置,而非增加进程数)

---

Factor IX: Disposability

要素IX:可处置性

Principle: Maximize robustness with fast startup and graceful shutdown.
Search Patterns:
bash
undefined
原则: 通过快速启动与优雅关闭提升健壮性。
搜索模式:
bash
undefined

Signal handlers

信号处理器

grep -r "signal.signal|SIGTERM|SIGINT|atexit" --include="*.py" grep -r "process.on.SIGTERM|process.on.SIGINT" --include=".js" --include=".ts"
grep -r "signal.signal|SIGTERM|SIGINT|atexit" --include="*.py" grep -r "process.on.SIGTERM|process.on.SIGINT" --include=".js" --include=".ts"

Graceful shutdown

优雅关闭

grep -r "graceful.shutdown|shutdown_handler|cleanup" --include=".py" --include=".js" --include=".ts"
grep -r "graceful.shutdown|shutdown_handler|cleanup" --include=".py" --include=".js" --include=".ts"

Startup time

启动时间

grep -r "startup|initialize|bootstrap" --include=".py" --include=".js" --include="*.ts" | head -20

**File Patterns:** `**/main.py`, `**/server.py`, lifecycle management code

**Compliance Criteria:**

| Level | Criteria |
|-------|----------|
| **Strong** | Fast startup (<10s), SIGTERM handling, graceful shutdown, jobs returnable to queue |
| **Partial** | Graceful shutdown but slow startup |
| **Weak** | No signal handling, jobs lost on process death, slow startup |

**Anti-patterns:**
- No SIGTERM/SIGINT handlers
- Slow startup (>30 seconds)
- Jobs lost if process crashes
- No cleanup on shutdown

---
grep -r "startup|initialize|bootstrap" --include=".py" --include=".js" --include="*.ts" | head -20

**文件模式:** `**/main.py`, `**/server.py`, 生命周期管理代码

**合规标准:**

| 等级 | 标准 |
|-------|----------|
| **强合规** | 启动快速(<10秒),支持SIGTERM处理,优雅关闭,任务可重新入队 |
| **部分合规** | 支持优雅关闭但启动缓慢 |
| **弱合规** | 无信号处理,进程终止时丢失任务,启动缓慢 |

**反模式:**
- 无SIGTERM/SIGINT处理器
- 启动缓慢(>30秒)
- 进程崩溃时丢失任务
- 关闭时无清理操作

---

Factor X: Dev/Prod Parity

要素X:开发/生产环境一致性

Principle: Keep development, staging, and production as similar as possible.
Search Patterns:
bash
undefined
原则: 保持开发、 staging与生产环境尽可能相似。
搜索模式:
bash
undefined

Different services per environment (anti-pattern)

不同环境使用不同服务(反模式)

grep -r "if.development.sqlite|if.production.postgres" --include=".py" --include=".js" --include=".ts" grep -r "development.SQLite|production.PostgreSQL" --include=".py" --include=".js" --include=".ts"
grep -r "if.development.sqlite|if.production.postgres" --include=".py" --include=".js" --include=".ts" grep -r "development.SQLite|production.PostgreSQL" --include=".py" --include=".js" --include=".ts"

Docker for parity

使用Docker保证一致性

find . -name "docker-compose*.yml" -o -name "Dockerfile"
find . -name "docker-compose*.yml" -o -name "Dockerfile"

Environment-specific backends

环境特定后端

grep -r "USE_LOCAL_|LOCAL_STORAGE|MOCK_" --include=".py" --include=".js" --include="*.ts"

**File Patterns:** `**/docker-compose*.yml`, environment configurations

**Compliance Criteria:**

| Level | Criteria |
|-------|----------|
| **Strong** | Same services everywhere (PostgreSQL in dev and prod), containerized |
| **Partial** | Mostly same but some lightweight dev alternatives |
| **Weak** | SQLite in dev, PostgreSQL in prod; different backing services |

**Anti-patterns:**
- SQLite for development, PostgreSQL for production
- In-memory cache in dev, Redis in prod
- Different service versions across environments
- "It works on my machine" issues

---
grep -r "USE_LOCAL_|LOCAL_STORAGE|MOCK_" --include=".py" --include=".js" --include="*.ts"

**文件模式:** `**/docker-compose*.yml`, 环境配置文件

**合规标准:**

| 等级 | 标准 |
|-------|----------|
| **强合规** | 所有环境使用相同服务(开发与生产均用PostgreSQL),已容器化 |
| **部分合规** | 大部分服务一致,但开发环境使用部分轻量替代方案 |
| **弱合规** | 开发用SQLite,生产用PostgreSQL;后端服务差异大 |

**反模式:**
- 开发用SQLite,生产用PostgreSQL
- 开发用内存缓存,生产用Redis
- 不同环境使用不同版本的服务
- 出现"在我机器上能运行"的问题

---

Factor XI: Logs

要素XI:日志

Principle: Treat logs as event streams.
Search Patterns:
bash
undefined
原则: 将日志视为事件流。
搜索模式:
bash
undefined

Stdout logging

标准输出日志

grep -r "print(|logging.info|logger.info|console.log" --include=".py" --include=".js" --include="*.ts" | head -20
grep -r "print(|logging.info|logger.info|console.log" --include=".py" --include=".js" --include="*.ts" | head -20

File-based logging (anti-pattern)

文件日志(反模式)

grep -r "FileHandler|open..log|writeFile.log|fs.appendFile.log" --include=".py" --include=".js" --include=".ts" grep -r "/var/log|/tmp/..log|logs/" --include=".py" --include=".js" --include=".ts" | grep -v "test|example"
grep -r "FileHandler|open..log|writeFile.log|fs.appendFile.log" --include=".py" --include=".js" --include=".ts" grep -r "/var/log|/tmp/..log|logs/" --include=".py" --include=".js" --include=".ts" | grep -v "test|example"

Structured logging

结构化日志

grep -r "structlog|json_logger|pino|winston" --include=".py" --include=".js" --include="*.ts"

**File Patterns:** `**/logging.py`, `**/logger.py`, logging configurations

**Compliance Criteria:**

| Level | Criteria |
|-------|----------|
| **Strong** | Unbuffered stdout only, structured logging (JSON), no file management |
| **Partial** | Stdout logging but with some file handlers |
| **Weak** | Application writes to log files, manages rotation |

**Anti-patterns:**
- Writing logs to files (`FileHandler`, `open('/var/log/app.log')`)
- Log rotation logic in application code
- Log archival managed by application
- Buffered logging

---
grep -r "structlog|json_logger|pino|winston" --include=".py" --include=".js" --include="*.ts"

**文件模式:** `**/logging.py`, `**/logger.py`, 日志配置文件

**合规标准:**

| 等级 | 标准 |
|-------|----------|
| **强合规** | 仅输出到标准输出且无缓冲,使用结构化日志(JSON格式),不管理日志文件 |
| **部分合规** | 输出到标准输出,但存在部分文件处理器 |
| **弱合规** | 应用写入日志文件并管理日志轮转 |

**反模式:**
- 写入日志文件(如`FileHandler`, `open('/var/log/app.log')`)
- 应用代码中包含日志轮转逻辑
- 应用管理日志归档
- 缓冲日志

---

Factor XII: Admin Processes

要素XII:管理进程

Principle: Run admin/management tasks as one-off processes.
Search Patterns:
bash
undefined
原则: 以一次性进程的形式运行管理/运维任务。
搜索模式:
bash
undefined

Management commands

管理命令

find . -name "manage.py" -o -name "Rakefile" -o -name "artisan" grep -r "@cli.command|@click.command|typer.command" --include="*.py"
find . -name "manage.py" -o -name "Rakefile" -o -name "artisan" grep -r "@cli.command|@click.command|typer.command" --include="*.py"

Migration scripts

迁移脚本

find . -name "migrations" -type d find . -name "migration.py" -o -name "migrate.py"
find . -name "migrations" -type d find . -name "migration.py" -o -name "migrate.py"

Admin scripts with proper isolation

具备隔离性的管理脚本

grep -r "bundle exec|source.venv|uv run" --include=".sh" --include="Makefile"

**File Patterns:** `**/manage.py`, `**/cli.py`, `**/migrations/**`, admin scripts

**Compliance Criteria:**

| Level | Criteria |
|-------|----------|
| **Strong** | Admin tasks use same dependencies/config, proper isolation, idempotent |
| **Partial** | Admin tasks exist but different setup from app |
| **Weak** | Manual database manipulation, scripts without isolation |

**Anti-patterns:**
- Admin scripts not using app's dependency manager
- Direct SQL manipulation outside of migrations
- Admin scripts with hardcoded credentials
- Non-idempotent migrations

---
grep -r "bundle exec|source.venv|uv run" --include=".sh" --include="Makefile"

**文件模式:** `**/manage.py`, `**/cli.py`, `**/migrations/**`, 管理脚本

**合规标准:**

| 等级 | 标准 |
|-------|----------|
| **强合规** | 管理任务使用与应用相同的依赖/配置,具备适当隔离性,操作具有幂等性 |
| **部分合规** | 存在管理任务,但设置与应用不同 |
| **弱合规** | 手动操作数据库,脚本无隔离性 |

**反模式:**
- 管理脚本未使用应用的依赖管理器
- 在迁移之外直接操作SQL
- 管理脚本中硬编码凭证
- 非幂等的迁移操作

---

Output Format

输出格式

Executive Summary Table

执行摘要表格

markdown
| Factor | Status | Notes |
|--------|--------|-------|
| I. Codebase | **Strong/Partial/Weak** | [Key finding] |
| II. Dependencies | **Strong/Partial/Weak** | [Key finding] |
| III. Config | **Strong/Partial/Weak** | [Key finding] |
| IV. Backing Services | **Strong/Partial/Weak** | [Key finding] |
| V. Build/Release/Run | **Strong/Partial/Weak** | [Key finding] |
| VI. Processes | **Strong/Partial/Weak** | [Key finding] |
| VII. Port Binding | **Strong/Partial/Weak** | [Key finding] |
| VIII. Concurrency | **Strong/Partial/Weak** | [Key finding] |
| IX. Disposability | **Strong/Partial/Weak** | [Key finding] |
| X. Dev/Prod Parity | **Strong/Partial/Weak** | [Key finding] |
| XI. Logs | **Strong/Partial/Weak** | [Key finding] |
| XII. Admin Processes | **Strong/Partial/Weak** | [Key finding] |

**Overall**: X Strong, Y Partial, Z Weak
markdown
| 要素 | 状态 | 备注 |
|--------|--------|-------|
| I. 代码库 | **强合规/部分合规/弱合规** | [关键发现] |
| II. 依赖 | **强合规/部分合规/弱合规** | [关键发现] |
| III. 配置 | **强合规/部分合规/弱合规** | [关键发现] |
| IV. 后端服务 | **强合规/部分合规/弱合规** | [关键发现] |
| V. 构建/发布/运行 | **强合规/部分合规/弱合规** | [关键发现] |
| VI. 进程 | **强合规/部分合规/弱合规** | [关键发现] |
| VII. 端口绑定 | **强合规/部分合规/弱合规** | [关键发现] |
| VIII. 并发 | **强合规/部分合规/弱合规** | [关键发现] |
| IX. 可处置性 | **强合规/部分合规/弱合规** | [关键发现] |
| X. 开发/生产一致性 | **强合规/部分合规/弱合规** | [关键发现] |
| XI. 日志 | **强合规/部分合规/弱合规** | [关键发现] |
| XII. 管理进程 | **强合规/部分合规/弱合规** | [关键发现] |

**总体**: X项强合规,Y项部分合规,Z项弱合规

Per-Factor Analysis

分要素分析

For each factor, provide:
  1. Current Implementation
    • Evidence with file:line references
    • Code snippets showing patterns
  2. Compliance Level
    • Strong/Partial/Weak with justification
  3. Gaps
    • What's missing vs. 12-Factor ideal
  4. Recommendations
    • Actionable improvements with code examples

针对每个要素,需提供:
  1. 当前实现
    • 带文件:行号引用的证据
    • 展示模式的代码片段
  2. 合规等级
    • 强合规/部分合规/弱合规及理由
  3. 差距
    • 与12-Factor理想状态的差异
  4. 建议
    • 可落地的改进方案及代码示例

Analysis Workflow

分析流程

  1. Initial Scan
    • Run search patterns for all factors
    • Identify key files for each factor
    • Note any existing compliance documentation
  2. Deep Dive (per factor)
    • Read identified files
    • Evaluate against compliance criteria
    • Document evidence with file paths
  3. Gap Analysis
    • Compare current vs. 12-Factor ideal
    • Identify anti-patterns present
    • Prioritize by impact
  4. Recommendations
    • Provide actionable improvements
    • Include before/after code examples
    • Reference best practices
  5. Summary
    • Compile executive summary table
    • Highlight strengths and critical gaps
    • Suggest priority order for improvements

  1. 初始扫描
    • 针对所有要素运行搜索模式
    • 识别每个要素对应的关键文件
    • 记录已有的合规文档
  2. 深度分析(按要素)
    • 阅读识别出的文件
    • 对照合规标准进行评估
    • 记录带文件路径的证据
  3. 差距分析
    • 对比当前实现与12-Factor理想状态
    • 识别存在的反模式
    • 按影响优先级排序
  4. 建议输出
    • 提供可落地的改进方案
    • 包含改进前后的代码示例
    • 参考最佳实践
  5. 总结
    • 整理执行摘要表格
    • 突出优势与关键差距
    • 建议改进的优先级顺序

Quick Reference: Compliance Scoring

快速参考:合规评分

ScoreMeaningAction
StrongFully implements principleMaintain, minor optimizations
PartialSome implementation, significant gapsPlanned improvements
WeakMinimal or no implementationHigh priority for roadmap
评分含义行动建议
强合规完全实现该原则保持现状,可进行小幅优化
部分合规部分实现,存在显著差距规划改进方案
弱合规极少或未实现该原则作为路线图的高优先级任务

When to Use This Skill

何时使用该技能

  • Evaluating new SaaS applications
  • Reviewing cloud-native architecture decisions
  • Auditing production applications for scalability
  • Planning migration to cloud platforms
  • Comparing application architectures
  • Preparing for containerization/Kubernetes deployment
  • 评估新的SaaS应用
  • 审查云原生架构决策
  • 审计生产应用的可扩展性
  • 规划向云平台的迁移
  • 对比不同应用架构
  • 为容器化/Kubernetes部署做准备