22 Commits

Author SHA1 Message Date
xfy
383e6f6b43 fix(db): expand source chain for all DB error logging
The previous fix only covered migration errors. The same truncation
affected two more places, both because tokio_postgres::Error's Display
prints only "db error" while the real message lives in source():

- api/error.rs: AppError::{db_conn,query,tx} logged with {e}, so every
  runtime DB failure showed as "Query failed: db error". The
  constructors' bound is tightened from impl Display+Debug to
  impl std::error::Error so the source chain can be walked; the
  user-facing message stays sanitized (existing tests still pass).
- db/pool.rs: ensure_database formatted tokio_postgres::Error directly
  into the String returned to main.rs' exit(1) path, collapsing to
  "failed to query pg_database: db error" etc.

Adds a shared crate::db::format_with_sources helper (walks source()
with de-dup of placeholder layers) and reuses it from MigrateError's
Display, the AppError constructors, and pool.rs.
2026-07-04 21:54:54 +08:00
xfy
e9f0b032b7 fix(db): expand migration error display to walk source chain
tokio_postgres::Error's Display prints only the placeholder "db error"
for DB-side failures; the actual message (e.g. column already exists,
SQLSTATE, constraint name) lives in source() as DbError. Without
traversing the chain, startup logs showed the useless
"migration 001 failed: db error", making failures impossible to
diagnose.

MigrateError::Display now appends each source layer with ": " and
exposes source() so error-reporting layers that walk the chain
themselves also benefit.
2026-07-04 21:47:24 +08:00
xfy
373498870a style: apply cargo fmt to workspace
Some checks failed
CI / check (push) Failing after 5m35s
CI / build (push) Has been skipped
2026-06-29 13:47:40 +08:00
xfy
4ec8d72b66 feat(db): 启动期自动创建目标数据库
把 scripts/migrate.sh 里 CREATE DATABASE 的逻辑内置进二进制启动流程,
全新部署不再需要手动建库即可首次启动。

- src/db/pool.rs: 新增 ensure_database(),连接 postgres 维护库做
  CREATE DATABASE IF NOT EXISTS 等价逻辑(SELECT EXISTS + CREATE)。
  复用 MIGRATE_STARTUP_TIMEOUT_SECS 窗口应对 DB 起得慢;目标库名经
  is_simple_ident 校验后才拼到 SQL,不合法的名字跳过让正常路径报错。
  tokio_postgres::Config 不 Clone,故逐字段拷贝到新 Config。
- src/main.rs: 在 get_conn_for_startup() 之前调用 ensure_database(),
  失败走统一的 tracing::error! + exit(1) 路径。
- src/db/migrate.rs: 文档注释补明目标库存在性由 ensure_database 上游保证。

新增 2 个 is_simple_ident 单测(392 → 402 tests)。
2026-06-25 11:46:50 +08:00
xfy
b24cfdcabc fix(startup): replace migration panic with friendly exit + configurable retry window
DB migration failure at startup panicked via .expect() (main.rs:223),
dumping a raw backtrace for what is usually just "PostgreSQL isn't running
yet". Worse, the 1.6s runtime retry budget was reused at startup, so it
almost always failed against a cold/slow DB (docker-compose without
healthchecks, local Postgres not started, etc.).

Changes:
- pool: extract build_pg_config() (returns Result, no panic); add
  validate_database_url() so URL-format / DB_POOL_SIZE errors surface as
  friendly exit(1) instead of hitting the LazyLock's unreachable .expect()
- pool: add get_conn_for_startup() — a startup-only retry loop with a
  configurable total-duration window (MIGRATE_STARTUP_TIMEOUT_SECS,
  default 30s, 500ms interval), separate from the runtime get_conn()
  anti-avalanche fast retry (untouched)
- migrate: split run() into run_on_conn(&mut conn) so callers control the
  connection-acquisition strategy; main.rs pairs this with the startup
  retry. Advisory-lock release comment updated: exit(1) terminates the
  process just like panic, so the session-level lock is still freed
- main: startup fatal errors (bad URL, DB unreachable, migration failed)
  now each emit tracing::error! + eprintln! ERROR + targeted HINT, then
  exit(1) — no panic, no backtrace nudge
- .env.example / AGENTS.md: document MIGRATE_STARTUP_TIMEOUT_SECS

No runtime behavior change: get_conn() and its ~40 call sites are
unchanged. Advisory-lock safety preserved (documented in migrate.rs).
2026-06-22 11:24:13 +08:00
xfy
283d8b5f4d feat(db): implement migrate::run() with advisory lock and per-migration transactions 2026-06-18 15:59:45 +08:00
xfy
920e26e213 test(db): assert migrations/*.sql files are registered in MIGRATIONS 2026-06-18 15:47:53 +08:00
xfy
d044304969 feat(db): scaffold migrate module with MIGRATIONS constant and error type 2026-06-18 15:41:31 +08:00
xfy
1e2e3c9332 perf(db): add statement_timeout; skip retry on pool Timeout errors
- 连接配置 statement_timeout(默认 30s,STATEMENT_TIMEOUT_SECS 可调),
  防慢查询长时间占用连接拖垮池(L6)
- get_conn 对 Timeout(池满)错误立即返回不再 sleep 重试,避免雪崩;
  仅 Backend/Postgres 错误才退避重试
2026-06-18 13:35:33 +08:00
xfy
2dda168b19 perf(db): switch pool recycling method from Verified to Fast
Verified 每次取连接都会额外发 SELECT 1 验证;Fast 直接复用,
依赖 tokio-postgres 在使用时自然报错,由 get_conn 的退避重试兜底。
2026-06-18 11:08:14 +08:00
xfy
54f7bd481a perf(db): replace fixed 2s retry with exponential backoff + jitter
get_conn 现在按 base*2^attempt + 随机 jitter 退避(200ms 起步),
避免连接池抖动时多请求同步重试形成惊群。
2026-06-18 11:06:57 +08:00
xfy
104ff427f9 perf(db): add exponential backoff retry helper with tests
引入 src/db/retry.rs,提供 base * 2^attempt + jitter 的退避序列,
取代 pool.rs 中固定 2s 重试。MAX_RETRIES 将在下一个提交中被 get_conn 使用。
2026-06-18 11:05:22 +08:00
xfy
d826afbe15 fix(db): 为 deadpool-postgres 连接池指定 Tokio1 runtime
Some checks failed
CI / check (push) Failing after 6m5s
CI / build (push) Has been skipped
2026-06-17 11:07:23 +08:00
xfy
449a545886 security: fix critical issues from repository review
Some checks failed
CI / build (push) Has been cancelled
CI / check (push) Has been cancelled
P0 blockers:
- Fix migration numbering conflict and duplicate indexes
- Change comments.post_id FK to ON DELETE CASCADE
- Restrict public post detail endpoint to published posts only
- Fix rate-limiting IP extraction and fallback to ConnectInfo
- Harden HTML sanitizer: deny unknown URL schemes, restrict data URIs
- Remove session token from login response body
- Enforce image pixel/dimension limits on upload and serving

P1 high-risk:
- Validate uploads by magic bytes and decode GIF/WebP
- Add pagination/rate-limiting to search, tag posts, and comments
- Make first-admin registration and slug uniqueness check atomic
- HTML-escape comment author fields
- Improve HTML minify cache key and skip admin/error responses
- Add mobile navigation menu

P2 accessibility/quality:
- Associate form labels with inputs
- Key PostDetail article by slug to re-init scripts on navigation
- Improve image viewer keyboard accessibility
- Make theme toggle SSR-friendly and add aria-label
- Invalidate slug 404 cache on create and pending count on new comment
- Deduplicate tags case-insensitively

P3 cleanup:
- Remove unused tower-http dependency, expand make clean
- Configure DB pool timeouts and verified recycling
- Run background cleanup tasks immediately on startup
- Use SHA-256 for stable disk cache keys
- Log DB errors with Display instead of Debug
- Update README migration instructions

All tests pass (321), clippy clean, dx check clean.
2026-06-17 10:34:14 +08:00
xfy
2db652137d docs(models, db, cache): 补充中文注释 2026-06-12 18:56:56 +08:00
xfy
294d60afab style: format rust code
Some checks failed
CI / build (push) Has been cancelled
CI / check (push) Has been cancelled
2026-06-12 17:14:31 +08:00
xfy
bd9e87128d perf(ssr): optimize request throughput by 32%
- Cache ammonia::Builder with LazyLock (was rebuilt per request)
- Enable tracing release_max_level_info to strip tracing overhead at compile time
- Remove TraceLayer and tower-http trace feature from production
- Increase DB pool size 10→20 (configurable via DB_POOL_SIZE)
- Increase SSR cache TTL 300s→3600s (configurable via SSR_CACHE_SECS)

Benchmark: 7,444 → 9,840 req/s, P99 latency 27.6ms → 11.1ms
2026-06-12 09:36:53 +08:00
xfy
593666135c feat: add DB connection retry logic with get_conn() helper 2026-06-04 10:03:56 +08:00
xfy
cbf19b3f47 Fix remaining clippy/formatting warnings
- Merge unnecessary line splits in db/pool.rs and pages/admin.rs
- Prefix unused variable with underscore in login.rs

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 18:25:48 +08:00
xfy
c4dfd1f445 Fix additional clippy warnings and update progress
- Add #[allow(dead_code)] to temporarily unused functions
- Remove unused is_expired() and UserRole::as_str()
- Fix unused variable warnings (token, theme)
- Update progress.txt: mark all stories complete

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 17:02:14 +08:00
xfy
6df0a7ee19 US-006: 验证 + 修复编译和运行时问题
- 修复 migration: role 从 ENUM 改为 VARCHAR(20) 以兼容 tokio-postgres
- 修复 Cargo.toml: 将 chrono/argon2/uuid/rand 改为非 optional,添加 wasm-bindgen/getrandom js
- 修复 main.rs: Tokio runtime panic,改用 std::thread + Runtime::new
- 修复 db/mod.rs wasm stub: DummyPool 替代 deadpool_postgres
- 修复 login/admin.rs: wasm_bindgen::JsCast 条件编译
- 验证通过: 注册✓ 登录✓ get_current_user✓ 重复注册拒绝✓ 错误密码✓

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 16:49:43 +08:00
xfy
031a7aa0f2 US-001: 数据库配置与建表
- 添加依赖: tokio-postgres, deadpool-postgres, argon2, uuid, chrono, regex, dotenvy
- 创建 .env 文件模板 (DATABASE_URL)
- 创建 migrations/001_init.sql: users 表 + sessions 表 + 部分唯一索引
- 创建 src/db/mod.rs 和 src/db/pool.rs: std::sync::LazyLock 全局初始化 deadpool

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 16:15:47 +08:00