返回文章列表

AI-DLC 中文文档系列 10:完整示例:科学计算器 API 技术环境

lyj

以 CalcEngine 为例展示如何约束 Python、FastAPI、AWS Serverless、安全和测试标准。

技术环境文档:CalcEngine 科学计算器 API

项目技术摘要

  • 项目名称:CalcEngine
  • 项目类型:Greenfield
  • 主要运行环境:Cloud
  • 云提供商:AWS
  • 目标部署模型:Serverless(API Gateway + Lambda)
  • 包管理器:uv
  • 团队规模:4 人(2 名后端开发者、1 名文档门户前端开发者、1 名 QA 工程师)
  • 团队经验:Python 后端经验丰富,AWS 经验中等,此前没有数学库开发经验。团队专业使用过 FastAPI 和 Flask。熟悉 pytest。CDK 经验有限(需要示例)。

编程语言

必需语言

语言 版本 用途 理由
Python 3.12+ API 服务、数学引擎、Lambda handler、CDK 基础设施 团队主要语言。数学生态丰富(mpmath、numpy、scipy)。uv 提供快速、可靠的依赖管理。
HTML/CSS/JS ES2022+ 文档门户(静态站点) API 文档所需的最小前端。不需要框架;使用 Jinja2 模板进行静态生成。

允许语言

语言 使用条件
Rust 如果 Python 性能不足,可批准用于性能关键数学函数(例如表达式解析器)。采用前需要 profiling 证据。通过 PyO3/maturin 暴露给 Python。
TypeScript 如果团队更偏好 TypeScript CDK 而不是 Python CDK,可批准用于 CDK 基础设施。该决策必须在 construction 开始前做出,不得在项目中途改变。

禁止语言

语言 原因 替代方案
Java 团队无相关经验。增加运维复杂度(Lambda 中 JVM 冷启动)。 Python
Go 团队无相关经验。Python 覆盖当前所有需求。 Python
C/C++ 原生扩展维护负担高。 如需原生性能,使用通过 PyO3 暴露的 Rust

包和环境管理

uv 作为标准工具

uv 是本项目唯一的包和环境管理工具。不要使用 pip、pip-tools、poetry、pipenv 或 conda。

uv 使用标准

# Project initialization (already done; do not re-run)
uv init calcengine
cd calcengine

# Adding dependencies
uv add fastapi                      # Add a runtime dependency
uv add uvicorn[standard]            # Add with extras
uv add --dev pytest pytest-cov      # Add a development dependency
uv add --dev mypy ruff              # Add dev tooling

# Removing dependencies
uv remove requests                  # Remove a dependency

# Running commands in the project environment
uv run python -m calcengine.main    # Run application
uv run pytest                       # Run tests
uv run mypy src/                    # Run type checker
uv run ruff check src/              # Run linter

# Syncing environment from lockfile
uv sync                             # Install all dependencies from uv.lock
uv sync --dev                       # Include dev dependencies

# Lockfile management
# uv.lock is auto-generated. NEVER edit it manually.
# uv.lock MUST be committed to version control.

依赖文件标准

文件 用途 提交到 Git
pyproject.toml 项目元数据、依赖声明、工具配置 是
uv.lock 包含精确解析版本的确定性 lockfile 是
.python-version 固定项目 Python 版本(例如 3.12) 是

pyproject.toml 约定

所有项目配置都放在 pyproject.toml 中。对于支持 pyproject.toml 配置的工具,不要创建单独配置文件。

[project]
name = "calcengine"
version = "0.1.0"
description = "Scientific calculator REST API"
requires-python = ">=3.12"
dependencies = [
    # Runtime dependencies listed here by uv add
]

[dependency-groups]
dev = [
    # Dev dependencies listed here by uv add --dev
]

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-v --tb=short --strict-markers"
markers = [
    "unit: Unit tests (fast, no external dependencies)",
    "integration: Integration tests (may require services)",
    "accuracy: Mathematical accuracy validation tests",
]

[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true

[tool.ruff]
target-version = "py312"
line-length = 100

[tool.ruff.lint]
select = ["E", "F", "W", "I", "N", "UP", "B", "A", "SIM", "TCH"]

[tool.coverage.run]
source = ["src/calcengine"]
branch = true

[tool.coverage.report]
fail_under = 90
show_missing = true

框架和库

必需框架

框架/库 版本 领域 理由
FastAPI 0.115+ REST API 框架 支持 async、自动生成 OpenAPI spec、Pydantic 校验、与 Python 类型系统集成良好。
Pydantic 2.x 请求/响应校验、settings 管理 类型安全数据模型、JSON 序列化,是 FastAPI 的核心组成。
uvicorn 0.30+ ASGI server FastAPI 的标准生产 server。通过 Mangum 在 Lambda 中使用,也用于本地运行。
Mangum 1.x Lambda adapter 将 FastAPI ASGI app 包装为 AWS Lambda handler。零配置 adapter。
pytest 8.x 测试框架 团队标准。插件生态丰富。
mypy 1.x 静态类型检查 在运行前捕获类型错误。强制严格模式。
ruff 0.8+ Lint 和格式化 用一个快速工具替代 flake8、isort 和 black。
structlog 24.x+ 结构化 JSON 日志 所有 Lambda handler 和 API endpoint 必须输出结构化 JSON 日志。在共享模块中统一配置。
aws-cdk-lib 2.x Infrastructure as Code AWS 部署。所有基础设施使用 Python CDK construct。

首选库

需要相应能力时使用这些库。不要预先添加。

库 用途 使用时机
mpmath 任意精度算术 第 2 阶段:实现任意精度模式时。MVP 不需要(IEEE 754 double 足够)。
numpy 数组运算、线性代数 第 2 阶段:实现矩阵/向量运算时。不要用于基础算术。
scipy 统计分布、数值积分 第 2 阶段及以后:实现高级统计和微积分时。
httpx Async HTTP client 对外 HTTP 调用(例如第 3 阶段获取汇率)。出于 async 兼容性,优先于 requests。
boto3 AWS SDK 任何部署时不由 CDK 处理的直接 AWS 服务交互(例如 DynamoDB 查询、运行时读取 Secrets Manager)。
pytest-cov 测试覆盖率报告 始终使用。从项目开始就包含在 dev dependency 中。
pytest-asyncio Async 测试支持 测试 async FastAPI endpoint 或 async 函数时。
hypothesis 基于性质的测试 数学函数测试。生成随机输入以发现边界情况。强烈建议所有数学模块使用。
freezegun 时间 mock 测试时间相关逻辑(限流、token 过期、审计时间戳)时。

禁止库

库 原因 替代方案
Flask 项目使用 FastAPI。不要混用 Web framework。 FastAPI
Django 对 API 服务来说过重。不需要 ORM。 FastAPI + 直接 DynamoDB 访问
requests 仅同步。会阻塞 FastAPI 中的 async event loop。 httpx
sympy 对 MVP 范围来说过重。会引入大型依赖树。 直接实现表达式解析器。第 3 阶段符号计算时重新评估。
pandas 不需要。CalcEngine 处理单次计算,不处理 dataframe。 需要时使用标准 Python 或 numpy 进行数组运算。
SQLAlchemy MVP 中没有关系数据库。DynamoDB 是数据存储。 boto3 DynamoDB resource/client
celery 对 MVP 来说复杂度不必要。所有计算均为同步且快速(<50ms)。 第 3 阶段批处理时重新评估。如更早需要 async,使用 SQS + Lambda。
poetry / pipenv / pip-tools 项目只使用 uv。不要引入替代包管理器。 uv
black / isort / flake8 已由 ruff 替代,ruff 合并了三者能力。 ruff

库审批流程

要添加不在必需或首选列表中的库:

  1. 打开标题为 "Dependency Request: [library-name]" 的 GitHub issue
  2. 包含:用途、已考虑的替代方案、license(必须是 MIT、Apache 2.0 或 BSD)、维护状态(最近发布日期、open issue 数量)以及体积影响
  3. Tech lead 审查并批准或拒绝
  4. 如果批准,通过 uv add 添加并更新本文档

云环境

云提供商

  • 主要提供商:AWS
  • 账户结构:MVP 使用单个 AWS 账户。第 2 阶段拆分 dev/staging/prod 账户。
  • 区域:us-east-1(主区域)。MVP 不设置灾备区域。第 2 阶段规划多区域。

服务允许列表

服务 批准用例 约束
AWS Lambda API request handler、数学计算 Python 3.12 runtime。MVP 最大 256MB 内存(如 profiling 显示需要可增加)。30 秒 timeout。
Amazon API Gateway (HTTP API) 公开 REST API endpoint HTTP API 类型(不是 REST API 类型)。带 TLS 的自定义域名。使用 usage plan 进行限流。
Amazon DynamoDB API key 存储、使用量计量、限流计数器 On-demand capacity mode。单表设计。限流窗口使用 TTL。
Amazon S3 OpenAPI spec 托管、静态文档站点、Lambda 部署包 启用 bucket 加密。除 docs site bucket(CloudFront distribution)外阻止 public access。
Amazon CloudFront 文档门户和 API spec 的 CDN 仅 HTTPS。积极缓存静态资源。
Amazon CloudWatch 日志、指标、告警、仪表板 所有 Lambda 输出结构化 JSON 日志。为计算次数、延迟百分位、错误率设置自定义指标。
AWS Secrets Manager Stripe API key、签名 key 支持时自动轮换。Lambda 在 cold start 读取,并缓存在内存中。
AWS Certificate Manager 自定义域名 TLS 证书 与 API Gateway 和 CloudFront 配合使用。
Amazon Cognito 文档门户和 API key 管理的开发者账户认证 用于开发者注册/登录的 user pool。不用于 API 调用认证(API key 用于此目的)。
Amazon SQS 失败 async 操作的 dead-letter queue Standard queue。用于失败的 billing event 和错误捕获。MVP 中不用于计算请求。
AWS CDK Infrastructure as Code 部署 Python CDK。所有基础设施都在 CDK 中定义。无手工控制台变更。
AWS CloudTrail API 审计日志 启用所有 management event。生产中为 S3 和 Lambda 启用 data event。
AWS IAM 服务权限 每个 Lambda function 使用最小权限策略。无 wildcard resource 权限。

服务禁止列表

服务 原因 替代方案
Amazon EC2 运维开销。首选 serverless 模型。 Lambda 用于 compute。
Amazon ECS / Fargate 对 MVP request/response workload 来说过度设计。 Lambda。如果 cold start 成为问题再重新评估。
Amazon RDS / Aurora 不需要关系数据库。API key 和 usage 数据适合 DynamoDB。 DynamoDB。
Amazon ElastiCache / Redis MVP 不需要缓存层。计算是无状态且快速的。 如有需要,在 Lambda execution context 内使用内存缓存。
AWS Elastic Beanstalk 不适合 IaC 模型。 CDK + Lambda。
Amazon Kinesis 不需要 streaming。所有计算都是同步 request/response。 如果需要 async processing,使用 SQS。
AWS Step Functions MVP 中没有多步骤编排。 直接 Lambda invocation。第 3 阶段批处理时重新评估。
Amazon SNS MVP 不需要 pub/sub。 SQS 用于 dead-letter queue。

服务审批流程

要使用不在允许列表中的服务:

  1. 打开标题为 "AWS Service Request: [service-name]" 的 GitHub issue
  2. 包含:用例、成本估算(月度)、安全影响、运维负担,以及为什么允许服务不能满足需求
  3. Tech lead 审查。访问 PII 或有网络暴露的服务需要额外安全审查。
  4. 如果批准,添加 CDK construct 并更新本文档

首选技术和模式

架构模式

作为 serverless function 部署的模块化单体。

CalcEngine 是一个单一 Python package,包含内部模块(arithmetic、trigonometry、statistics 等),通过单个 FastAPI 应用暴露,并部署到 API Gateway 后的 AWS Lambda。这不是微服务架构。

决策 选择 理由
架构风格 模块化单体 小团队(4 人)、单一领域、MVP 中没有按模块独立扩缩容的需求。
部署模型 通过 Mangum 由单个 Lambda function 服务所有 API route 简单。一个部署制品。cold start 可在所有 endpoint 间摊销。
模块边界 src/calcengine/ 内的 Python package 在不承担独立服务运维成本的情况下保持清晰内部边界。如果某些 endpoint 需要不同 memory/timeout,之后可提取到独立 Lambda。

API 设计标准

  • 风格:基于 HTTPS 的 REST。JSON 请求和响应体。
  • Base URL:https://api.calcengine.io/v1/
  • 版本管理:URL path prefix(/v1/、/v2/)。仅 major version。非破坏性变更不增加版本。
  • 文档:FastAPI 自动生成 OpenAPI 3.1 specification。托管在 https://docs.calcengine.io。
  • 命名约定:JSON 字段名使用 snake_case(Python 约定)。URL path 使用 kebab-case。
  • Content Type:所有请求和响应均为 application/json。不支持 XML。

标准请求格式:

{
  "expression": "sin(pi/4) * 2 + sqrt(16)",
  "options": {
    "angle_mode": "radians",
    "precision": 15
  }
}

标准成功响应格式:

{
  "result": 5.414213562373095,
  "expression": "sin(pi/4) * 2 + sqrt(16)",
  "computation_time_ms": 2.3,
  "engine_version": "0.1.0"
}

标准错误响应格式:

{
  "error": {
    "code": "DOMAIN_ERROR",
    "message": "Cannot compute logarithm of a negative number",
    "detail": "log(-5) is undefined for real numbers",
    "parameter": "expression",
    "documentation_url": "https://docs.calcengine.io/errors/DOMAIN_ERROR"
  }
}

错误码(MVP):

代码 HTTP 状态码 含义
PARSE_ERROR 400 表达式无法解析。语法格式错误。
DOMAIN_ERROR 422 数学上未定义(log(-1)、sqrt(-1)、除零)。
OVERFLOW_ERROR 422 结果超出可表示范围。
INVALID_PARAMETER 400 请求参数类型或值无效。
EXPRESSION_TOO_LONG 400 表达式超过允许的最大长度。
RATE_LIMIT_EXCEEDED 429 API key 超出限流。
UNAUTHORIZED 401 缺失或无效 API key。
INTERNAL_ERROR 500 意外 server error。

数据模式

  • 主要数据存储:DynamoDB(单表设计)
  • DynamoDB 中的实体:API key、usage counter(每 key 每月)、rate limit window(每 key 每分钟)
  • 访问模式:所有读写都通过 primary key(API key ID)。无 scan。无复杂查询。
  • 缓存:无外部缓存。Lambda 在 warm invocation 间复用 DynamoDB connection。API key 校验结果在 Lambda 内存中缓存 60 秒。
  • 无关系数据库:如果需要关系查询(报表、分析),在添加 RDS 前先评估 DynamoDB export to S3 + Athena。

日志模式

所有日志输出必须通过 structlog 生成结构化 JSON。人类可读 console 输出仅用于本地开发。

import structlog

logger = structlog.get_logger()

# Standard log call
logger.info(
    "calculation_completed",
    expression=expression,
    result=result,
    computation_time_ms=elapsed,
    api_key_id=api_key_id,
)

# Error log call
logger.error(
    "calculation_failed",
    expression=expression,
    error_code="DOMAIN_ERROR",
    error_detail=str(e),
    api_key_id=api_key_id,
)

每个 API 请求的必需日志字段:

字段 描述
request_id 每个请求的唯一 ID(来自 API Gateway 或生成)
api_key_id Hash 后的 API key 标识符(绝不记录原始 key)
endpoint 被调用的 API path
http_method GET、POST 等
http_status 响应状态码
duration_ms 请求处理总耗时
timestamp ISO 8601 时间戳

安全要求

认证和授权

  • API 调用认证:在 Authorization: Bearer {key} header 中传递 API key。API key 是 32 字符随机字符串,以 bcrypt hash 形式存储在 DynamoDB 中。
  • 开发者门户认证:Amazon Cognito user pool。使用 email + password 注册,并要求 email verification。
  • 授权模型:扁平模型。所有 API key 都可访问所有 endpoint。基于 tier 的 rate limit(free、starter、professional)由使用量计量强制执行,而不是 endpoint 级权限。
  • API Key 管理:开发者通过开发者门户创建、轮换、吊销 key。每个账户最多 3 个 active key。

数据保护

  • 静态加密:DynamoDB 使用 AWS-managed KMS key 加密。S3 bucket 使用 SSE-S3 加密。
  • 传输加密:API Gateway 自定义域和 CloudFront distribution 强制 TLS 1.2+。无 HTTP(明文)endpoint。
  • PII 处理:开发者账户存储 email 和 hashed password。不收集其他 PII。数学表达式不是 PII。表达式会为调试记录日志,但不永久存储(CloudWatch log retention:30 天)。
  • 数据分类:API key = Confidential。开发者 email = Internal。数学表达式和结果 = Public。

输入校验

  • 表达式长度限制:最大 4,096 字符。更长表达式以 EXPRESSION_TOO_LONG 拒绝。
  • 表达式字符 allowlist:字母数字、算术运算符(+ - * / ^ %)、括号、小数点、逗号、空白和已识别函数名。拒绝未识别字符。
  • 无代码执行:表达式解析器绝不能调用 eval()、exec()、compile() 或任何动态代码执行。表达式被解析为 AST,并由数学引擎求值。
  • 递归深度限制:表达式解析器将嵌套深度限制为 100 层。防止类似 (((((...)))) 的深层嵌套表达式导致 stack overflow。
  • 数值范围校验:超出 IEEE 754 双精度范围的结果返回 OVERFLOW_ERROR,而不是 Infinity 或 NaN。

Secret 管理

  • Stripe API Keys:存储在 AWS Secrets Manager 中。Lambda 在 cold start 读取,并缓存在内存中。
  • Cognito Client Secret:存储在 AWS Secrets Manager 中。
  • 禁止做法:
    • 不得将 secret 放入提交到 Git 的 pyproject.toml、源代码或 .env 文件
    • 不得将 secret 放入 Lambda 环境变量(运行时使用 Secrets Manager)
    • 代码中不得放 AWS access key(Lambda 使用 IAM execution role)
    • .env 文件仅用于本地开发,并列入 .gitignore

依赖安全

  • 扫描:为 Python 依赖启用 GitHub Dependabot。已知漏洞会触发 alert。
  • License 策略:允许:MIT、Apache 2.0、BSD(2-clause 和 3-clause)、PSF、ISC。禁止:GPL、LGPL、AGPL、SSPL、proprietary。添加新依赖前用 uv tree 检查。
  • 更新策略:Critical/High CVE 在 7 天内修复。Medium 在 30 天内修复。Low 按季度评估。

OWASP Top 10 合规(2021)

A01:2021 - Broken Access Control

控制项 CalcEngine 实现
授权强制执行 每个请求在 route handler 执行前,都在 FastAPI middleware(api/middleware/auth.py)中校验 API key。没有有效 key 时任何 endpoint 都不可访问。
默认拒绝 API Gateway 在 gateway 层拒绝没有 Authorization header 的请求(401)。Lambda handler 拒绝无效或已吊销的 key(401)。
资源所有权 每个 API key 都绑定到一个 Cognito 账户。开发者只能列出、轮换和吊销自己的 key。DynamoDB 查询限定在已认证用户的 partition key 中。
限流 在 middleware(api/middleware/rate_limit.py)中按 key 强制限流。Free:10,000 calls/month、10 calls/second。Starter:1M/month、50/second。Professional:10M/month、200/second。超限返回 429。
CORS 策略 API Gateway CORS 配置为只允许文档门户 origin(https://docs.calcengine.io)。无 wildcard origin。仅允许 GET 和 POST 方法。
Directory traversal / path manipulation 不适用。CalcEngine 不提供文件服务,也不接受文件路径作为输入。

A02:2021 - Cryptographic Failures

控制项 CalcEngine 实现
传输中数据 API Gateway 自定义域和 CloudFront 强制 TLS 1.2+。不存在 HTTP endpoint。API Gateway 配置 SecurityPolicy: TLS_1_2。
静态数据 DynamoDB 使用 AWS-managed KMS key 加密。S3 bucket 使用 SSE-S3 加密。CloudWatch logs 使用 service-managed key 加密。
密码/凭据存储 开发者门户密码用 bcrypt hash(由 Cognito 管理)。API key 以 bcrypt hash 存储在 DynamoDB。原始 API key 只在创建时返回一次,绝不存储或记录日志。
响应中的敏感数据 API 响应绝不包含 API key、账户凭据或内部标识符。错误消息不泄露 table name、ARN 或 stack trace。
日志中的敏感数据 记录 API key ID(hash 后标识符,不是 key 本身)。绝不记录原始 API key。计算日志中不包含开发者 email。

A03:2021 - Injection

控制项 CalcEngine 实现
表达式注入 表达式解析器基于严格 grammar 构建 AST。它不使用 eval()、exec()、compile() 或任何 Python 代码执行机制。仅接受已识别 token(数字、运算符、括号、白名单函数名)。未识别 token 触发 PARSE_ERROR(400)。
字符 allowlist 表达式输入限制为:数字、小数点、算术运算符(+ - * / ^ %)、括号、逗号、空白,以及固定函数名集合(sin、cos、tan、log、sqrt 等)。所有其他字符在解析前拒绝。
NoSQL injection DynamoDB 查询使用 boto3 SDK 和参数化 key condition。不会把用户输入字符串拼接进 query expression。Partition key 和 sort key 由程序设置,绝不从 request body 插值。
HTTP header injection FastAPI 和 Pydantic 校验并类型检查所有请求输入。响应 header 由框架程序化设置,不来自用户输入。
Log injection structlog 会转义日志值中的特殊字符。用户提供的表达式作为结构化 JSON 字段中的字符串值记录,而不是插入日志格式字符串。

A04:2021 - Insecure Design

控制项 CalcEngine 实现
威胁建模 在 AIDLC NFR Requirements stage 创建 threat model。新增 endpoint 或 integration point 时审查。主要威胁:表达式注入、资源耗尽、API key 滥用。
纵深防御 三层校验:(1) API Gateway request validation,(2) FastAPI 中 Pydantic model validation,(3) engine function 中 domain validation。每层都独立拒绝。
业务逻辑限制 表达式长度上限为 4,096 字符。Parser recursion depth 上限为 100 层。Statistics endpoint 最大数组大小:10,000 个元素。这些限制在不影响合法使用的情况下防止资源耗尽。
滥用场景测试 测试套件包含 negative/abuse tests:超大表达式、深层括号嵌套、旨在导致慢求值的表达式、超过限流的快速请求、无效/过期/已吊销 API key。

A05:2021 - Security Misconfiguration

控制项 CalcEngine 实现
Infrastructure as Code 所有基础设施都在 AWS CDK(Python)中定义。无手工控制台变更。部署前在 pull request 中审查 CDK diff。
默认凭据 任何环境中都没有默认 API key、admin account 或硬编码密码。Cognito user pool 要求 email verification。
错误消息 生产错误响应返回 CalcEngine 错误码、用户友好消息和 documentation URL。绝不暴露 Python traceback、Lambda ARN、DynamoDB table name 或内部文件路径。生产中 FastAPI debug=False。
不必要功能 生产 Lambda 不暴露 /docs 或 /redoc 交互式 endpoint。OpenAPI spec 仅从静态文档站点提供。不提供会泄露超出 engine_version 之外版本细节的 health-check endpoint。
安全 header API Gateway 响应包含:Strict-Transport-Security: max-age=31536000; includeSubDomains、X-Content-Type-Options: nosniff、X-Frame-Options: DENY、API 响应上 Cache-Control: no-store。CloudFront 为文档站点添加安全 header。
Lambda 配置 Lambda function 使用最低所需内存(256MB)。Timeout 设置为 30 秒。配置 reserved concurrency 防止 runaway scaling。无包含 secret 的环境变量(运行时使用 Secrets Manager)。

A06:2021 - Vulnerable and Outdated Components

控制项 CalcEngine 实现
依赖扫描 启用 GitHub Dependabot。扫描 pyproject.toml 和 uv.lock 中的已知漏洞。Alert 自动创建 GitHub issue。
修补 SLA Critical/High CVE:7 天内修补。Medium:30 天。Low:按季度评估。
License 合规 允许:MIT、Apache 2.0、BSD、PSF、ISC。禁止:GPL、LGPL、AGPL、SSPL、proprietary。添加依赖前用 uv tree 检查。
Lockfile 完整性 uv.lock 提交到 Git 并在 CI 中强制执行。CI pipeline 中 uv sync --locked 如 lockfile 过期则失败。CI 中不进行临时 uv add。
最小依赖 禁止库列表防止臃肿依赖树(MVP 中无 pandas、Django、SQLAlchemy、sympy)。每个新依赖都需要带理由的 GitHub issue。

A07:2021 - Identification and Authentication Failures

控制项 CalcEngine 实现
API key hashing API key 是 32 字符加密随机字符串(通过 secrets.token_urlsafe)。以 bcrypt hash 存储。Lookup 使用 key prefix(前 8 个字符,明文存储)查找记录,然后 bcrypt verify 确认完整 key。
暴力破解防护 API Gateway throttling:所有 endpoint 每 IP 每秒 100 请求。失败认证尝试(invalid key)记录 api_key_prefix 和 source IP。单个 IP 5 分钟内 50 次认证失败后,通过 WAF rule 临时封禁 IP。
开发者门户认证 Cognito 强制:最小 12 字符密码、需要 email verification、5 次登录失败后 account lockout。
Key 轮换 开发者可在吊销旧 key 前创建新 key(用于 zero-downtime rotation 的重叠期)。每个账户最多 3 个 active key 防止 key hoarding。
凭据暴露 API key 在创建时只返回一次(HTTP response body)。任何地方都不以明文存储。不包含在 email 中。创建后不在开发者门户可见。
多因素认证 MVP 不要求。Cognito MFA 支持可用,并将在第 2 阶段引入 team/enterprise account 时作为选项启用。

A08:2021 - Software and Data Integrity Failures

控制项 CalcEngine 实现
CI/CD pipeline 安全 GitHub Actions。main branch 受保护:要求 PR、至少 1 次 review、所有 CI check 通过。禁止直接 push 到 main。Deploy workflow 仅在 merge 到 main 后触发。
依赖完整性 uv.lock 包含所有依赖的 hash。uv sync --locked 在安装时验证 hash。PR 中显式审查 lockfile 变更。
部署制品完整性 Lambda 部署包在 CI 中从干净的 uv sync --locked install 构建。生产不部署本地构建。CDK deploy 仅从 CI pipeline 运行,不从开发者机器运行。
反序列化安全 Pydantic v2 models 解析并校验所有传入 JSON。不使用 pickle、yaml.load()(unsafe loader)或 marshal。仅通过 Pydantic 的 JSON parsing 使用 json.loads()。Pydantic model_config 设置 extra = "forbid" 拒绝意外字段。

A09:2021 - Security Logging and Monitoring Failures

控制项 CalcEngine 实现
安全事件日志 以下所有事件均作为结构化 JSON 记录到 CloudWatch:认证失败(invalid/expired/revoked key)、rate limit exceeded(429)、input validation failures(400)、authorization anomalies、所有 5xx errors。
日志保护 CloudWatch logs 保留 30 天。Log group resource policy 防止 Lambda execution role 删除。CloudTrail 将 management events 记录到带 object lock 的独立 S3 bucket。
告警 CloudWatch Alarms 配置:5xx error rate 5 分钟内 > 1%、authentication failure rate > 100/minute、单个 API key 生成超过其 rate limit 10 倍的尝试、Lambda concurrent execution > reserved concurrency 的 80%。告警通过 SNS 通知 on-call email/SMS。
监控仪表板 CloudWatch dashboard 显示:request count、error rate(4xx 和 5xx)、p50/p95/p99 latency、auth failure count、rate limit hit count、Lambda cold start percentage、DynamoDB consumed capacity。每周审查。

A10:2021 - Server-Side Request Forgery (SSRF)

控制项 CalcEngine 实现
适用性 MVP 低风险。 CalcEngine 不会基于用户输入发起 outbound HTTP request。表达式解析器只求值数学表达式;它不会获取 URL、解析 hostname 或发起网络调用。
Outbound request Lambda 唯一的 outbound network call 是:(1) 通过 AWS SDK 查询 DynamoDB(endpoint 由 AWS region 决定,不由用户输入决定),(2) cold start 时读取 Secrets Manager(secret name 在 config 中硬编码,不来自用户输入)。
第 3 阶段考虑 添加货币换算时(第 3 阶段),服务会从金融数据提供商获取汇率。届时:provider URL 将是环境变量(不是用户输入),请求会使用 allowlisted hostname,响应在使用前会按预期 schema 校验。本节必须在第 3 阶段发布前更新。
网络分段 Lambda function 在 AWS-managed VPC 中运行(MVP 无 customer VPC)。它们只能通过 public endpoint 访问 AWS 服务。在此配置中,Lambda 无法访问内部服务、数据库或 metadata endpoint。

测试要求

测试策略概览

测试类型 必需 覆盖目标 工具
Unit Tests Yes 90% line, 80% branch pytest + pytest-cov
Mathematical Accuracy Tests Yes 已实现函数 100% pytest + hypothesis
Integration Tests Yes 所有 API endpoint、DynamoDB interaction pytest + moto(AWS mocking)
Load Tests Yes(发布前) 1,000 concurrent requests, p50 < 50ms Locust
Security Tests Yes 输入校验、注入防护 pytest(custom)+ manual OWASP review
End-to-End Tests Conditional 部署到 staging 后的关键用户旅程 pytest + httpx against live API

单元测试标准

  • 最低覆盖率:90% line coverage,80% branch coverage。通过 pyproject.toml 中 fail_under = 90 的 pytest-cov 强制执行。
  • Mock 策略:使用 moto mock AWS 服务(DynamoDB、Secrets Manager)。使用 freezegun mock 时间。不要 mock 内部数学函数。数学函数必须使用真实计算测试。
  • 命名约定:测试文件镜像源文件。src/calcengine/trig.py 由 tests/unit/test_trig.py 测试。测试函数命名为 test_<function>_<scenario>(例如 test_sin_zero_returns_zero、test_sin_negative_pi_returns_zero)。
  • 测试位置:独立的 tests/ 目录树。不与源码并置。
tests/
  unit/
    test_arithmetic.py
    test_trig.py
    test_statistics.py
    test_expression_parser.py
    test_error_handling.py
  integration/
    test_api_evaluate.py
    test_api_trig.py
    test_api_keys.py
    test_rate_limiting.py
  accuracy/
    test_trig_accuracy.py
    test_arithmetic_accuracy.py
    test_statistics_accuracy.py
  conftest.py

数学准确性测试

这是 CalcEngine 特有的测试类别,大多数项目中不存在。

  • 参考实现:每个数学函数都必须与 Python 的 math 模块、mpmath 库(高精度)或公开数学表进行比对测试。
  • 使用 hypothesis 进行基于性质的测试:使用 hypothesis 生成随机有效输入并验证性质成立(例如 sin(x)^2 + cos(x)^2 == 1、log(a*b) == log(a) + log(b))。
  • 边界情况:每个函数都必须有显式测试覆盖:零、负零、非常小的数(接近 epsilon)、非常大的数、定义域边界(例如 asin(1)、asin(1.0000001)以及特殊值(pi、e、三角函数中 pi/2 的倍数)。
  • 容差:基础函数结果必须在 1 ULP(unit in the last place)内匹配参考值。任何接受更宽容差的函数都必须记录理由。

准确性测试示例模式:

import math
import pytest
from hypothesis import given, strategies as st
from calcengine.trig import sin, cos

class TestSinAccuracy:
    """Validate sin() accuracy against math.sin and known exact values."""

    @pytest.mark.accuracy
    @pytest.mark.parametrize("input_val, expected", [
        (0, 0.0),
        (math.pi / 6, 0.5),
        (math.pi / 4, math.sqrt(2) / 2),
        (math.pi / 2, 1.0),
        (math.pi, 0.0),
        (3 * math.pi / 2, -1.0),
        (2 * math.pi, 0.0),
        (-math.pi / 2, -1.0),
    ])
    def test_sin_known_values(self, input_val: float, expected: float) -> None:
        result = sin(input_val)
        assert result == pytest.approx(expected, abs=1e-15)

    @pytest.mark.accuracy
    @given(st.floats(min_value=-1e6, max_value=1e6, allow_nan=False, allow_infinity=False))
    def test_sin_matches_stdlib(self, x: float) -> None:
        assert sin(x) == pytest.approx(math.sin(x), rel=1e-15)

    @pytest.mark.accuracy
    @given(st.floats(min_value=-1e6, max_value=1e6, allow_nan=False, allow_infinity=False))
    def test_pythagorean_identity(self, x: float) -> None:
        assert sin(x) ** 2 + cos(x) ** 2 == pytest.approx(1.0, abs=1e-14)

集成测试标准

  • 范围:通过 FastAPI test client 测试完整 API request/response cycle。使用 moto 测试 DynamoDB interaction。
  • 环境:本地。无需部署服务。moto mock 所有 AWS 服务。
  • 数据管理:每个测试通过 moto fixture 创建自己的 DynamoDB table,结束后拆除。不共享测试状态。

CI/CD 测试 Gate

Pipeline Stage 必需测试 工具 失败动作
Pre-commit ruff check, ruff format --check, mypy ruff, mypy via pre-commit hooks 阻止 commit
Pull Request Unit tests, accuracy tests, integration tests, coverage check pytest, GitHub Actions 阻止 merge
Pre-deploy (staging) 所有 PR tests + load test(100 concurrent, 60 seconds) pytest + Locust, GitHub Actions 阻止 deploy
Post-deploy (production) Smoke tests(对 live API 做 10 个代表性计算) pytest + httpx 通知 on-call。如果 >50% failure,则自动 rollback。

本地运行测试

# Run all tests
uv run pytest

# Run only unit tests
uv run pytest tests/unit/ -m unit

# Run only accuracy tests
uv run pytest tests/accuracy/ -m accuracy

# Run with coverage report
uv run pytest --cov --cov-report=term-missing

# Run type checking
uv run mypy src/

# Run linter
uv run ruff check src/ tests/

# Run formatter check (no changes)
uv run ruff format --check src/ tests/

# Run formatter (apply changes)
uv run ruff format src/ tests/

项目结构

calcengine/
  .github/
    workflows/
      ci.yml                         # GitHub Actions: lint, type check, test on PR
      deploy.yml                     # GitHub Actions: CDK deploy on merge to main
  src/
    calcengine/
      __init__.py
      main.py                        # FastAPI app creation, Mangum handler
      config.py                      # Settings via Pydantic BaseSettings
      api/
        __init__.py
        router.py                    # Top-level API router
        endpoints/
          __init__.py
          evaluate.py                # POST /v1/evaluate (expression evaluation)
          arithmetic.py              # POST /v1/arithmetic/{operation}
          trigonometry.py            # POST /v1/trigonometry/{function}
          statistics.py              # POST /v1/statistics/{function}
          constants.py               # GET  /v1/constants/{name}
        middleware/
          __init__.py
          auth.py                    # API key validation middleware
          rate_limit.py              # Rate limiting middleware
          request_logging.py         # Structured request/response logging
        models/
          __init__.py
          requests.py                # Pydantic request models
          responses.py               # Pydantic response models
          errors.py                  # Error response models and error codes
      engine/
        __init__.py
        expression_parser.py         # Tokenizer, AST builder, evaluator
        arithmetic.py                # Basic math operations
        trigonometry.py              # Trig functions with domain validation
        statistics.py                # Descriptive statistics functions
        constants.py                 # Mathematical constants
        combinatorics.py             # Factorial, permutations, combinations
        logarithmic.py               # Log, ln, exp functions
        validation.py                # Input validation, domain checking
        errors.py                    # Math-domain exception types
      storage/
        __init__.py
        dynamodb.py                  # DynamoDB client, table operations
        api_keys.py                  # API key CRUD, validation, hashing
        usage.py                     # Usage metering, rate limit counters
      logging.py                     # structlog configuration
  infrastructure/
    app.py                           # CDK app entry point
    stacks/
      __init__.py
      api_stack.py                   # Lambda, API Gateway, custom domain
      data_stack.py                  # DynamoDB tables
      monitoring_stack.py            # CloudWatch dashboards, alarms
      auth_stack.py                  # Cognito user pool
      docs_stack.py                  # S3 + CloudFront for documentation site
  tests/
    unit/
      test_arithmetic.py
      test_trig.py
      test_statistics.py
      test_expression_parser.py
      test_combinatorics.py
      test_logarithmic.py
      test_validation.py
      test_api_keys.py
    integration/
      test_api_evaluate.py
      test_api_arithmetic.py
      test_api_trig.py
      test_api_statistics.py
      test_api_auth.py
      test_api_rate_limiting.py
    accuracy/
      test_trig_accuracy.py
      test_arithmetic_accuracy.py
      test_statistics_accuracy.py
      test_logarithmic_accuracy.py
      test_expression_parser_accuracy.py
    conftest.py                      # Shared fixtures (FastAPI test client, moto mocks)
  examples/
    api-endpoint/
      README.md
      example_endpoint.py
      test_example_endpoint.py
    math-function/
      README.md
      example_function.py
      test_example_function.py
    cdk-construct/
      README.md
      example_stack.py
  docs/
    static/                          # Documentation portal source (Jinja2 templates)
  pyproject.toml
  uv.lock
  .python-version                    # Contains: 3.12
  .gitignore
  .pre-commit-config.yaml
  README.md

目录规则

目录 包含内容 规则
src/calcengine/ 所有应用源代码 仅 Python。无配置文件、无测试、无文档。
src/calcengine/engine/ 纯数学函数 无 AWS import。无 HTTP import。无副作用。仅纯函数。必须无需任何 mock 即可测试。
src/calcengine/api/ FastAPI routes、middleware、models 仅 HTTP 层。调用 engine function。不包含数学逻辑。
src/calcengine/storage/ DynamoDB 访问层 所有 AWS 数据访问隔离在这里。无业务逻辑。
infrastructure/ CDK stacks 仅 Python CDK。无应用代码。
tests/ 所有测试 镜像 src/ 结构。拆分 unit/、integration/、accuracy/ 目录。
examples/ 模式模板代码 带测试和 README 的可运行代码。标准变化时更新。

示例和模板代码

示例 1:API Endpoint 模式

examples/api-endpoint/README.md:

# API Endpoint Pattern

## What This Demonstrates
Standard pattern for adding a new calculation endpoint to CalcEngine.
Shows: route definition, Pydantic models, engine call, error handling, logging.

## When to Use
- Adding any new calculation endpoint
- Adding any new HTTP route to the API

## When Not to Use
- Internal engine functions (see math-function example)
- Infrastructure changes (see cdk-construct example)

## Customization Guide
| Element | Customize? | Notes |
|---------|-----------|-------|
| Route path and method | Yes | Follow /v1/{category}/{function} convention |
| Request/response models | Yes | Define Pydantic models specific to the endpoint |
| Engine function call | Yes | Call the appropriate engine module function |
| Error handling structure | No | Always use CalcEngineError hierarchy and error_response() |
| Logging calls | No | Always log with request_id, api_key_id, duration_ms |
| Response envelope | No | Always return {"result": ..., "expression": ..., "computation_time_ms": ..., "engine_version": ...} |

examples/api-endpoint/example_endpoint.py:

"""Example: Standard API endpoint pattern for CalcEngine."""

import time

import structlog
from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field

from calcengine.api.middleware.auth import get_api_key_id
from calcengine.api.models.errors import error_response
from calcengine.api.models.responses import CalculationResponse
from calcengine.engine.errors import CalcEngineError
from calcengine.engine.trigonometry import sin

logger = structlog.get_logger()

router = APIRouter()


class SinRequest(BaseModel):
    """Request model for sine calculation."""

    value: float = Field(..., description="Input angle")
    angle_mode: str = Field(
        default="radians",
        pattern="^(radians|degrees)$",
        description="Angle unit: 'radians' or 'degrees'",
    )


@router.post("/v1/trigonometry/sin", response_model=CalculationResponse)
async def calculate_sin(
    request: SinRequest,
    api_key_id: str = Depends(get_api_key_id),
) -> CalculationResponse | dict:
    """Calculate the sine of the given value."""
    start = time.perf_counter()

    try:
        result = sin(request.value, angle_mode=request.angle_mode)
        elapsed = (time.perf_counter() - start) * 1000

        logger.info(
            "calculation_completed",
            endpoint="/v1/trigonometry/sin",
            input_value=request.value,
            angle_mode=request.angle_mode,
            result=result,
            computation_time_ms=round(elapsed, 3),
            api_key_id=api_key_id,
        )

        return CalculationResponse(
            result=result,
            expression=f"sin({request.value})",
            computation_time_ms=round(elapsed, 3),
        )

    except CalcEngineError as e:
        elapsed = (time.perf_counter() - start) * 1000
        logger.warning(
            "calculation_failed",
            endpoint="/v1/trigonometry/sin",
            input_value=request.value,
            error_code=e.code,
            error_detail=str(e),
            computation_time_ms=round(elapsed, 3),
            api_key_id=api_key_id,
        )
        return error_response(e)

examples/api-endpoint/test_example_endpoint.py:

"""Example: Standard test pattern for a CalcEngine API endpoint."""

import math

import pytest
from fastapi.testclient import TestClient

from calcengine.main import app


@pytest.fixture
def client() -> TestClient:
    """Create a test client with a mocked API key."""
    return TestClient(app)


class TestSinEndpoint:
    """Tests for POST /v1/trigonometry/sin."""

    @pytest.mark.unit
    def test_sin_zero_radians(self, client: TestClient) -> None:
        response = client.post(
            "/v1/trigonometry/sin",
            json={"value": 0, "angle_mode": "radians"},
            headers={"Authorization": "Bearer test-api-key"},
        )
        assert response.status_code == 200
        data = response.json()
        assert data["result"] == pytest.approx(0.0)
        assert "computation_time_ms" in data

    @pytest.mark.unit
    def test_sin_pi_over_2_radians(self, client: TestClient) -> None:
        response = client.post(
            "/v1/trigonometry/sin",
            json={"value": math.pi / 2, "angle_mode": "radians"},
            headers={"Authorization": "Bearer test-api-key"},
        )
        assert response.status_code == 200
        assert response.json()["result"] == pytest.approx(1.0)

    @pytest.mark.unit
    def test_sin_90_degrees(self, client: TestClient) -> None:
        response = client.post(
            "/v1/trigonometry/sin",
            json={"value": 90, "angle_mode": "degrees"},
            headers={"Authorization": "Bearer test-api-key"},
        )
        assert response.status_code == 200
        assert response.json()["result"] == pytest.approx(1.0)

    @pytest.mark.unit
    def test_sin_invalid_angle_mode(self, client: TestClient) -> None:
        response = client.post(
            "/v1/trigonometry/sin",
            json={"value": 1.0, "angle_mode": "gradians"},
            headers={"Authorization": "Bearer test-api-key"},
        )
        assert response.status_code == 422  # Pydantic validation error

    @pytest.mark.unit
    def test_sin_missing_auth(self, client: TestClient) -> None:
        response = client.post(
            "/v1/trigonometry/sin",
            json={"value": 0},
        )
        assert response.status_code == 401

示例 2:纯数学函数模式

examples/math-function/README.md:

# Math Function Pattern

## What This Demonstrates
Standard pattern for implementing a pure math function in the engine layer.
Shows: function signature, type hints, domain validation, error raising, docstring format.

## When to Use
- Adding any new mathematical function to src/calcengine/engine/

## When Not to Use
- API endpoints (see api-endpoint example)
- Functions that require AWS or HTTP access (those belong in api/ or storage/)

## Key Rules
- No imports from api/, storage/, or any external service
- Pure functions only: same input always produces same output
- Raise CalcEngineError subclasses for domain errors, never return None or NaN
- Type hints on all parameters and return values

examples/math-function/example_function.py:

"""Example: Standard pattern for a pure math function in CalcEngine engine layer."""

import math

from calcengine.engine.errors import DomainError


def log_base(value: float, base: float = 10.0) -> float:
    """Compute the logarithm of a value with the given base.

    Args:
        value: The number to compute the logarithm of. Must be positive.
        base: The logarithm base. Must be positive and not equal to 1.
              Defaults to 10 (common logarithm).

    Returns:
        The logarithm of value in the given base.

    Raises:
        DomainError: If value <= 0, base <= 0, or base == 1.
    """
    if value <= 0:
        raise DomainError(
            code="DOMAIN_ERROR",
            message=f"Cannot compute logarithm of {value}",
            detail="Logarithm is only defined for positive numbers",
            parameter="value",
        )

    if base <= 0:
        raise DomainError(
            code="DOMAIN_ERROR",
            message=f"Cannot use {base} as logarithm base",
            detail="Logarithm base must be positive",
            parameter="base",
        )

    if base == 1.0:
        raise DomainError(
            code="DOMAIN_ERROR",
            message="Cannot use 1 as logarithm base",
            detail="Logarithm base 1 is undefined (division by zero in change-of-base)",
            parameter="base",
        )

    return math.log(value) / math.log(base)

examples/math-function/test_example_function.py:

"""Example: Standard test pattern for a pure math function."""

import math

import pytest
from hypothesis import given, strategies as st

from calcengine.engine.errors import DomainError
from calcengine.engine.logarithmic import log_base


class TestLogBase:
    """Tests for log_base function."""

    # --- Known values ---

    @pytest.mark.unit
    def test_log10_of_100(self) -> None:
        assert log_base(100, 10) == pytest.approx(2.0)

    @pytest.mark.unit
    def test_log2_of_8(self) -> None:
        assert log_base(8, 2) == pytest.approx(3.0)

    @pytest.mark.unit
    def test_ln_of_e(self) -> None:
        assert log_base(math.e, math.e) == pytest.approx(1.0)

    @pytest.mark.unit
    def test_log_of_1_any_base(self) -> None:
        assert log_base(1, 10) == pytest.approx(0.0)
        assert log_base(1, 2) == pytest.approx(0.0)
        assert log_base(1, math.e) == pytest.approx(0.0)

    # --- Default base ---

    @pytest.mark.unit
    def test_default_base_is_10(self) -> None:
        assert log_base(1000) == pytest.approx(3.0)

    # --- Domain errors ---

    @pytest.mark.unit
    def test_log_of_zero_raises_domain_error(self) -> None:
        with pytest.raises(DomainError, match="Cannot compute logarithm"):
            log_base(0)

    @pytest.mark.unit
    def test_log_of_negative_raises_domain_error(self) -> None:
        with pytest.raises(DomainError, match="Cannot compute logarithm"):
            log_base(-5)

    @pytest.mark.unit
    def test_log_base_zero_raises_domain_error(self) -> None:
        with pytest.raises(DomainError, match="Cannot use 0"):
            log_base(10, 0)

    @pytest.mark.unit
    def test_log_base_one_raises_domain_error(self) -> None:
        with pytest.raises(DomainError, match="Cannot use 1"):
            log_base(10, 1)

    @pytest.mark.unit
    def test_log_base_negative_raises_domain_error(self) -> None:
        with pytest.raises(DomainError, match="Cannot use -2"):
            log_base(10, -2)

    # --- Property-based: accuracy against stdlib ---

    @pytest.mark.accuracy
    @given(
        st.floats(min_value=1e-300, max_value=1e300, allow_nan=False, allow_infinity=False),
    )
    def test_log10_matches_stdlib(self, x: float) -> None:
        assert log_base(x, 10) == pytest.approx(math.log10(x), rel=1e-14)

    @pytest.mark.accuracy
    @given(
        st.floats(min_value=1e-300, max_value=1e300, allow_nan=False, allow_infinity=False),
    )
    def test_log2_matches_stdlib(self, x: float) -> None:
        assert log_base(x, 2) == pytest.approx(math.log2(x), rel=1e-14)

    # --- Property-based: mathematical identity ---

    @pytest.mark.accuracy
    @given(
        a=st.floats(min_value=1e-100, max_value=1e100, allow_nan=False, allow_infinity=False),
        b=st.floats(min_value=1e-100, max_value=1e100, allow_nan=False, allow_infinity=False),
    )
    def test_log_product_identity(self, a: float, b: float) -> None:
        """log(a * b) should equal log(a) + log(b)."""
        if a * b > 0:
            assert log_base(a * b, 10) == pytest.approx(
                log_base(a, 10) + log_base(b, 10), rel=1e-10
            )

示例 3:CDK Construct 模式

examples/cdk-construct/README.md:

# CDK Construct Pattern

## What This Demonstrates
Standard pattern for defining a CDK stack for CalcEngine infrastructure.
Shows: Lambda function, API Gateway integration, DynamoDB table, IAM permissions.

## When to Use
- Adding new infrastructure resources to the project

## Key Rules
- All infrastructure in infrastructure/stacks/ directory
- One stack per logical group (api, data, monitoring, auth, docs)
- Use environment variables from CDK context, never hardcode
- Least-privilege IAM: each Lambda gets only the permissions it needs

examples/cdk-construct/example_stack.py:

"""Example: Standard CDK stack pattern for CalcEngine."""

from aws_cdk import Duration, Stack
from aws_cdk import aws_apigatewayv2 as apigwv2
from aws_cdk import aws_dynamodb as dynamodb
from aws_cdk import aws_lambda as lambda_
from aws_cdk import aws_logs as logs
from aws_cdk.aws_apigatewayv2_integrations import HttpLambdaIntegration
from constructs import Construct


class ExampleApiStack(Stack):
    """Example stack showing Lambda + API Gateway + DynamoDB pattern."""

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # DynamoDB table - single table design
        table = dynamodb.Table(
            self,
            "ExampleTable",
            partition_key=dynamodb.Attribute(
                name="PK", type=dynamodb.AttributeType.STRING
            ),
            sort_key=dynamodb.Attribute(
                name="SK", type=dynamodb.AttributeType.STRING
            ),
            billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
            encryption=dynamodb.TableEncryption.AWS_MANAGED,
            point_in_time_recovery=True,
        )

        # Lambda function
        handler = lambda_.Function(
            self,
            "ExampleHandler",
            runtime=lambda_.Runtime.PYTHON_3_12,
            handler="calcengine.main.handler",
            code=lambda_.Code.from_asset("src/"),
            memory_size=256,
            timeout=Duration.seconds(30),
            environment={
                "TABLE_NAME": table.table_name,
                "LOG_LEVEL": "INFO",
            },
            log_retention=logs.RetentionDays.ONE_MONTH,
        )

        # Grant Lambda read/write access to DynamoDB (least privilege)
        table.grant_read_write_data(handler)

        # HTTP API Gateway with Lambda integration
        api = apigwv2.HttpApi(
            self,
            "ExampleHttpApi",
            api_name="calcengine-api",
            default_integration=HttpLambdaIntegration(
                "LambdaIntegration",
                handler,
            ),
        )

本文档如何输入 AI-DLC

部分 AI-DLC 阶段 使用方式
Project Technical Summary Workspace Detection Greenfield 分类、团队上下文
Programming Languages Code Generation 强制 Python 3.12,未经批准不得使用其他语言
uv Standards Code Generation 所有依赖操作使用 uv,pyproject.toml 是唯一配置来源
Frameworks and Libraries Code Generation, NFR Design FastAPI + Pydantic + Mangum 技术栈,强制执行禁止库
Cloud Services Allow/Disallow Infrastructure Design MVP 仅使用 Lambda + API Gateway + DynamoDB
Architecture Pattern Application Design 模块化单体,engine/、api/、storage/ 的模块边界
API Design Standards Functional Design, Code Generation Endpoint 约定、错误码、响应格式
Security Requirements NFR Requirements, NFR Design 输入校验规则、禁止 eval()、API key 认证模式
Testing Requirements Code Generation, Build and Test pytest + hypothesis、90% 覆盖率、强制准确性测试
Project Structure Code Generation 精确目录布局和文件放置规则
Example Code Code Generation endpoint、engine function、CDK stack 的规范模式

参考链接