docs: Add commercialization, technical debt, and frontend documentation, and update project READMEs.

This commit is contained in:
2569718930@qq.com
2026-03-12 12:01:29 +08:00
parent f4fea03f35
commit 987aec2fa6
8 changed files with 666 additions and 841 deletions
+135 -200
View File
@@ -1,130 +1,90 @@
# PolyWeather API 文档(v1.3
本文档描述当前后端真实可用接口`web/app.py`
前端一般通过 Next.js BFF 路由代理访问这些接口
本文档基于当前代码`web/app.py` + `frontend/app/api/*`)整理
前端默认通过 Next.js BFF 路由访问后端
---
## 1. 基础信息
- 本地地址`http://127.0.0.1:8000`
- 生产地址`http://<vps-ip>:8000` 或你绑定的 HTTPS 域名
- 后端直连`http://127.0.0.1:8000`
- 前端 BFF`https://polyweather-pro.vercel.app/api/*`
- 返回格式:`application/json`
- 缓存策略
- 后端分析缓存:默认 5 分钟(Ankara 特殊口径 60 秒)
- 前端详情缓存:5 分钟 + revision 检查 + 后台静默刷新
- 前端 BFF HTTP 缓存(Vercel 层):
- `/api/cities``ETag` + `Cache-Control``s-maxage=300`
- `/api/city/{name}/summary``ETag` + `Cache-Control``s-maxage=20`
- `/api/history/{name}``ETag` + `Cache-Control``s-maxage=60`
- `summary?force_refresh=true``Cache-Control: no-store`
- 手动刷新:`force_refresh=true` 强制绕过缓存
- 口径说明
- 结算导向分析以温度最高值和温度桶概率为核心。
- Ankara 增强使用 MGM,主站固定 `17130`
- Meteoblue 已移除,不再出现在任何有效字段中。
---
## 2. API 思维导图
## 2. 请求链路
```mermaid
flowchart TD
A["PolyWeather API"]
subgraph E["接口分组"]
E1["GET /api/cities"]
E2["GET /api/city/{name}"]
E3["GET /api/city/{name}/summary"]
E4["GET /api/city/{name}/detail"]
E5["GET /api/history/{name}"]
end
subgraph O["关键对象"]
O1["current"]
O2["forecast"]
O3["probabilities (mu + distribution)"]
O4["multi_model / multi_model_daily"]
O5["market_scan (P0 只读)"]
end
A --> E
A --> O
flowchart LR
FE["Browser / Dashboard"] --> BFF["Next.js Route Handlers (/api/*)"]
BFF --> API["FastAPI (/web/app.py)"]
API --> WX["Weather Collector"]
API --> ANA["DEB + Trend + Probabilities + Market Scan"]
ANA --> PM["Polymarket Read-only Layer"]
```
---
## 3. 接口总览
| 接口 | 方法 | 用途 |
| :------------------------- | :--- | :------------------------------------ |
| `/api/cities` | GET | 城市清单与地图基础信息 |
| `/api/city/{name}` | GET | 城市主分析数据(侧栏/今日分析主来源 |
| `/api/city/{name}/summary` | GET | 轻量摘要(首屏预热/低开销更新) |
| `/api/city/{name}/detail` | GET | 聚合详情 + Polymarket P0 只读市场层 |
| `/api/history/{name}` | GET | 历史对账数据 |
| 接口 | 方法 | 用途 |
| :-- | :-- | :-- |
| `/api/cities` | GET | 监控城市列表(地图/侧栏) |
| `/api/city/{name}` | GET | 城市主分析(今日分析核心数据) |
| `/api/city/{name}/summary` | GET | 轻量摘要(首屏预热/低成本轮询) |
| `/api/city/{name}/detail` | GET | 聚合详情(含 `market_scan` |
| `/api/history/{name}` | GET | 历史对账数据 |
---
## 4. 关键接口详解
## 4. 关键接口说明
### 4.1 `GET /api/cities`
返回监控城市列表(地图 Marker 与侧边栏基础数据)
返回监控城市清单
示例
关键字段
```json
{
"cities": [
{
"name": "ankara",
"display_name": "Ankara",
"lat": 39.9334,
"lon": 32.8597,
"risk_level": "medium",
"risk_emoji": "🟠",
"airport": "Esenboğa",
"icao": "LTAC",
"temp_unit": "celsius",
"is_major": true
}
]
}
```
- `name`, `display_name`
- `lat`, `lon`
- `risk_level`, `risk_emoji`
- `airport`, `icao`
- `temp_unit``celsius` / `fahrenheit`
### 4.2 `GET /api/city/{name}`
数据接口,前端详情面板和今日分析最常用
分析接口,返回当前实况、预报、概率、趋势、AI 分析等
可选参数:
- `force_refresh=true|false`
核心字段:
关键字段:
- `name`, `display_name`, `local_date`, `local_time`, `temp_symbol`
- `risk`
- `current`
- `forecast`
- `current`(温度、今日最高、METAR 观测时间、原始 METAR
- `forecast`(今日及多日高温、日出日落、日照时长)
- `mgm`, `mgm_nearby`
- `multi_model`, `multi_model_daily`
- `deb`
- `ensemble`
- `deb`, `ensemble`
- `probabilities``mu` + `distribution`
- `trend`, `peak`
- `hourly`, `hourly_next_48h`
- `source_forecasts`(当前只保留 `weather_gov`
- `market_scan`
- `updated_at`
说明:
- `current.raw_metar` 是原始 METAR 报文。
- Ankara 专项增强使用 MGM 站网,领先站固定 `17130`
- Meteoblue 已彻底移除,不再出现在接口字段中。
- `source_forecasts.weather_gov`
### 4.3 `GET /api/city/{name}/summary`
轻量温度摘要,用于地图首屏预热和低成本刷新
轻量摘要接口,适合高频刷新列表
典型字段
可选参数
- `force_refresh=true|false`
关键字段:
- `name`, `display_name`, `icao`
- `local_time`, `temp_symbol`
@@ -133,21 +93,17 @@ flowchart TD
- `risk.level`, `risk.warning`
- `updated_at`
缓存说明:
- 通过前端 BFF 访问时,默认返回 `ETag` 与可缓存 `Cache-Control`
-`force_refresh=true` 时,BFF 强制 `no-store`,用于人工排障与即时刷新。
### 4.4 `GET /api/city/{name}/detail`
聚合视图接口,包含天气分析和市场只读层
聚合详情接口,市场分析与未来日期分析都依赖该接口
可选参数:
- `force_refresh=true|false`
- `market_slug=<slug>`(调试/定向市场匹配)
- `market_slug=<slug>`
- `target_date=YYYY-MM-DD`
关键结构
关键返回块
- `overview`
- `official`
@@ -158,133 +114,112 @@ flowchart TD
- `risk`
- `ai_analysis`
`market_scan`P0 只读)重点字段:
`market_scan` 重点字段:
- `primary_market`, `selected_condition_id`, `selected_slug`
- `yes_token`, `no_token`
- `available`, `selected_date`, `selected_slug`, `signal_label`
- `yes_buy`, `yes_sell`, `no_buy`, `no_sell`
- `market_price`, `model_probability`, `edge_percent`
- `temperature_bucket`
- `top_buckets`(前端展示前会再去重
- `signal_label``BUY YES` / `BUY NO` / `MONITOR`
- `websocket.asset_ids`, `websocket.condition_ids`(订阅标识,不涉及下单)
- `primary_market.tradable`(是否可交易)
- `primary_market.tradable_reason`(不可交易原因)
- `primary_market.ended_at_utc`UTC 结束时刻)
- `primary_market.accepting_orders`(是否仍接收订单)
- `temperature_bucket`, `forecast_bucket`, `top_buckets`
- `anchor_model`, `anchor_high`, `anchor_settlement`
- `open_meteo_settlement`(兼容旧字段,当前与 `anchor_settlement` 同值
- `primary_market.tradable`, `primary_market.tradable_reason`
- `primary_market.accepting_orders`, `primary_market.ended_at_utc`
注意
说明
- 后端已做温度桶去重与方向优先(优先与主市场同方向的 `or higher`/`or lower` 桶)
- 前端还有二次去重兜底,避免重复温度桶刷屏
- 错价雷达推送前会二次校验交易状态,若市场已不可交易(`closed` / inactive / 不接单 / 过 `endDate`)会跳过。
- 当前错价锚点不是单一 Open-Meteo,而是“多模型最高温锚点”
- 推送层会再次校验市场可交易性,不可交易市场会跳过
### 4.5 `GET /api/history/{name}`
历史对账数据来源
历史对账接口
示例
关键字段
```json
{
"history": [
{
"date": "2026-03-07",
"actual": 7.0,
"deb": 6.5,
"mu": 7.2,
"mgm": 8.0
}
]
}
- `date`
- `actual`
- `deb`
- `mu`
- `mgm`
---
## 5. 缓存与刷新策略(当前已实现)
### 5.1 FastAPI 后端缓存
- `_analyze` 结果内存缓存:默认 5 分钟
- Ankara 特例:60 秒
- `force_refresh=true`:绕过后端缓存
### 5.2 Next.js BFF HTTP 缓存(Vercel
- `GET /api/cities`
- `ETag`
- `Cache-Control: public, max-age=0, s-maxage=300, stale-while-revalidate=1800`
- `GET /api/city/{name}/summary`
- `ETag`
- `Cache-Control: public, max-age=0, s-maxage=20, stale-while-revalidate=60`
- `GET /api/history/{name}`
- `ETag`
- `Cache-Control: public, max-age=0, s-maxage=60, stale-while-revalidate=300`
- `summary?force_refresh=true`
- `Cache-Control: no-store`
### 5.3 前端本地缓存
- `sessionStorage`
- 城市详情缓存(5 分钟 TTL + revision 探测)
- `localStorage`
- 上次选中城市
- 侧栏风险分组折叠状态
### 5.4 尚未引入(当前明确未做)
- Service Worker Cache API
- IndexedDB
---
## 6. 常用调试示例
### 6.1 查询未来日期 `market_scan`
```bash
curl -s "http://127.0.0.1:8000/api/city/ankara/detail?force_refresh=true&target_date=2026-03-12" \
| python3 -c "import sys,json; m=json.load(sys.stdin).get('market_scan',{}); print({k:m.get(k) for k in ['available','selected_date','anchor_model','anchor_high','anchor_settlement','yes_buy','no_buy']})"
```
---
## 5. 请求链路(以 `/api/city/{name}` 为例)
```mermaid
sequenceDiagram
participant FE as Frontend
participant API as FastAPI
participant WX as Weather Collector
participant PM as Polymarket RO Layer
FE->>API: GET /api/city/{name}?force_refresh=...
API->>WX: fetch_all_sources(city)
WX-->>API: METAR / MGM / Open-Meteo / weather.gov / Multi-model
API->>API: DEB + trend + probability
API->>PM: build_market_scan(...)
PM-->>API: market_scan (read-only)
API-->>FE: merged city payload
```
---
## 6. 数据口径
### 6.1 主观测
- Aviation Weather / METAR 是全局主观测源。
- Ankara:结算主站仍是 `LTAC`,领先信号强化使用 MGM`17130`)。
### 6.2 预测源
- Open-Meteo
- weather.gov(美国城市)
- 多模型:ECMWF / GFS / ICON / GEM / JMA
### 6.3 概率口径
- `mu`:动态分布中心,不是固定结算值。
- `distribution`:按温度桶输出概率分布,面向结算决策而非通用天气展示。
---
## 7. 常见问题
### 7.1 接口 500
- 先检查容器是否启动:`docker compose ps`
- 查看日志:`docker compose logs -f polyweather_web`
### 7.2 METAR 看起来“延迟”
优先核对:
- `current.obs_time`
- `current.report_time`
- `current.receipt_time`
通常是上游发布节奏,不一定是本地轮询问题。
### 7.3 前端仍显示旧内容
- 确认 Vercel 已部署最新构建
- 浏览器强刷(`Ctrl+F5`
- 检查是否命中前端 5 分钟 TTL
### 7.4 为什么 VPS `:8000` 看不到 `ETag`
- `:8000` 是 FastAPI 后端直连口径,主要负责分析与数据聚合。
- `ETag/304` 主要由前端 BFF 路由返回(Vercel 域名下的 `/api/*`)。
- 验证缓存头请用前端域名,而不是后端直连 IP。
---
## 8. 验收脚本
项目内置缓存验收脚本:
### 6.2 验证前端缓存头
```bash
./scripts/validate_frontend_cache.sh "https://polyweather-pro.vercel.app"
```
输出 `Result: PASS` 代表以下链路均正常:
### 6.3 观察错价雷达跳过原因
- `ETag` 返回
- `If-None-Match -> 304`
- `force_refresh=true -> no-store`
```bash
docker compose logs -f polyweather | egrep "market not tradable|trade alert pushed|mispricing cap"
```
---
## 7. 常见问题
### 7.1 VPS `:8000` 为什么看不到 `ETag`
- `:8000` 是 FastAPI 直连层,主要负责聚合分析。
- `ETag/304` 在前端 BFFVercel 的 `/api/*`)侧实现。
### 7.2 为什么 `target_date` 有时没有市场价格?
- 该日期可能没有可交易市场。
- 或目标桶在市场里无可用报价(`yes_buy/no_buy` 缺失)。
- 可先看 `market_scan.available``primary_market.tradable`
### 7.3 如何确认 Bot 后台循环是否启动?
- Telegram 里发送 `/diag`
- 查看三类循环状态:错价雷达、Polygon 钱包监听、Polymarket 钱包异动监听。
---
+73 -75
View File
@@ -6,115 +6,113 @@ Target: make PolyWeather a sustainable paid weather-intelligence product.
## 1. Product Positioning
PolyWeather is not a generic weather app.
It is a decision-support layer for temperature-settlement markets:
PolyWeather is not a generic weather app. It is a settlement decision layer for temperature markets:
- observation-first (METAR/MGM),
- settlement-aware probability modeling (DEB + mu/buckets),
- market mapping (Polymarket read-only) for actionable edge detection.
- settlement-aware modeling (DEB + mu/buckets),
- market mapping (Polymarket read-only) for actionable mispricing checks.
---
## 2. Business Overview Diagram
## 2. Current Monetization Readiness (2026-03-12)
| Capability | Status | Notes |
| :-- | :-- | :-- |
| Frontend entitlement gate | Implemented | Next middleware supports token gate + session cookie |
| Backend entitlement guard | Implemented | `POLYWEATHER_REQUIRE_ENTITLEMENT` + backend token header |
| Bot command entitlement pre-hook | Implemented | `/city` and `/deb` can be protected (`POLYWEATHER_BOT_REQUIRE_ENTITLEMENT`) |
| Payment event ingestion | Not implemented | No automated USDC payment reconciliation yet |
| Subscriber persistence | Not implemented | Still missing managed subscriber DB |
| Self-serve billing UI | Not implemented | No user billing center yet |
---
## 3. Access Model
```mermaid
flowchart TD
A["PolyWeather Monetization"]
flowchart LR
U["User"] --> FE["Frontend (Vercel)"]
FE --> MW["Entitlement Middleware"]
MW --> BFF["BFF /api/*"]
BFF --> API["FastAPI"]
API --> G["Backend Entitlement Guard"]
subgraph P["Product"]
P1["Telegram Signal Channel"]
P2["Web Dashboard"]
P3["VIP Bundle"]
end
subgraph R["Pricing"]
R1["Entry 1 USD"]
R2["Dashboard 5 USD"]
R3["Bundle 5.5 USD"]
end
subgraph AC["Access Control"]
AC1["Manual activation (P1)"]
AC2["Wallet/USDC detection (P2)"]
AC3["Entitlement middleware"]
end
subgraph G["Growth"]
G1["Accuracy reports"]
G2["Retention analytics"]
G3["User preference center"]
end
A --> P
A --> R
A --> AC
A --> G
P["Payment Source (USDC / Wallet)"] --> S["Subscriber State (to build)"]
S --> MW
S --> API
```
### Do we need login/register to start charging?
Short answer: **no for phase 1, yes for scale**.
- Phase 1 can run with token/wallet-based entitlement and manual ops.
- For scale (self-serve renewals, refunds, support, analytics), account identity and subscriber DB become mandatory.
---
## 3. Packaging and Pricing
## 4. Packaging and Pricing (Draft)
| Tier | Price | Value |
| :--------------- | :----------- | :---------------------------------------- |
| Telegram Channel | $1 / month | Low-noise proactive signal feed |
| Web Dashboard | $5 / month | Full multi-model context + reconciliation |
| VIP Bundle | $5.5 / month | Dashboard + signal stream |
| Tier | Price | Value |
| :-- | :-- | :-- |
| Telegram Signal Channel | $1 / month | Low-noise proactive signal stream |
| Web Dashboard | $5 / month | Full model context + historical reconciliation |
| VIP Bundle | $5.5 / month | Dashboard + signal stream |
Payment direction:
- Currency: Polygon USDC
- Phasing: manual activation first, then automated entitlement sync
- Settlement/network: Polygon USDC
- Rollout: manual confirmation first, then automated entitlement sync
---
## 4. Execution Phases
## 5. Execution Phases
```mermaid
graph LR
P1[Phase 1 Manual Beta] --> P2[Phase 2 Payment Automation]
P2 --> P3[Phase 3 Growth and B2B]
```
### Phase 1: Manual Paid Beta
### Phase 1: Manual Beta
- Keep paid channel small, optimize signal quality first.
- Manual payment confirmation + manual entitlement grant.
- Invite-gated dashboard while access control hardens.
- Keep user set small and quality-focused.
- Manual payment confirmation + manual entitlement issue.
- Weekly accuracy report as trust anchor.
### Phase 2: Payment Automation
- Detect wallet payment events (USDC).
- Auto-issue/refresh entitlement.
- Enforce route-level and API-level access guards.
- Ingest payment events (wallet/tx).
- Auto-issue and auto-expire entitlement.
- Full parity across frontend middleware, backend API, and bot command guard.
### Phase 3: Growth and Expansion
### Phase 3: Growth and B2B
- Self-serve billing and subscription panel.
- Operator analytics and feature usage telemetry.
- Optional B2B API package for quant teams.
- Self-serve billing and subscriber console.
- Retention analytics and feature usage telemetry.
- Optional B2B/API package.
---
## 5. Technical Dependencies for Revenue
## 6. P0/P1 Commercial Engineering Backlog
| Dependency | Why it matters |
| :------------------- | :--------------------------------------------------------------- |
| Entitlement guard | Prevents unpaid dashboard/API access |
| Subscriber store | Persistent paid user state |
| Audit trail | Explains why each alert fired |
| Observability | Detects degradation before churn |
| Frontend performance | Impacts conversion and retention (Speed Insights now integrated) |
### P0 (before public paid launch)
1. Subscriber store (managed PostgreSQL/Supabase) with entitlement expiry.
2. Payment event pipeline (idempotent ingest + reconciliation + retry).
3. Unified entitlement policy matrix (frontend/backend/bot).
4. Ops audit trail for alerts and entitlement changes.
### P1 (after initial paid users)
1. Billing/entitlement admin console.
2. User-level support tooling (manual override, extension, refund notes).
3. Conversion and retention dashboards.
4. Churn diagnostics linked to alert quality and latency.
---
## 6. Immediate Commercial Priorities
## 7. Commercial Risk Controls
1. Finish robust entitlement middleware in frontend and backend.
2. Persist subscriber/payment state in managed DB.
3. Publish transparent monthly accuracy and signal-quality reports.
4. Add support playbooks for false-alert and stale-data incidents.
- Revenue leakage: deny by default when entitlement token/state is missing.
- Signal quality drift: publish monthly transparent accuracy summary.
- Support load: keep alert evidence standardized in push payloads.
- Compliance/ops: preserve immutable entitlement and push logs.
---
Last Updated: `2026-03-11`
Last Updated: `2026-03-12`
+38 -39
View File
@@ -4,91 +4,90 @@ Purpose: keep engineering debt explicit while shipping production features.
---
## 1. Debt Landscape
## 1. Debt Snapshot
Current estimate: **90% stable / 10% debt**.
```mermaid
flowchart TD
A["Tech Debt"]
subgraph AR["Architecture"]
AR1["Monolithic bot entry"]
AR2["Shared runtime coupling"]
end
subgraph PI["Product Infra"]
PI1["Entitlement hardening"]
PI2["Subscription persistence"]
subgraph PI["Payment Infra"]
PI1["Payment event ingestion"]
PI2["Subscriber persistence"]
PI3["Entitlement parity"]
end
subgraph Q["Quality"]
Q1["Replay harness"]
Q2["Broader regression tests"]
Q2["Mixed integration tests"]
end
subgraph O["Observability"]
O1["Alert evidence trace"]
O2["SLO dashboards"]
O1["Alert evidence schema"]
O2["Ops dashboards"]
end
A --> AR
A --> PI
A --> Q
A --> O
```
Current system health estimate: **86% stable / 14% debt**.
---
## 2. Recently Closed (2026-03-12)
- Meteoblue API path fully removed from backend, frontend, config and docs.
- Market top-bucket duplicate temperature issue fixed (backend dedupe + frontend guard).
- Detail panel a11y conflict fixed (`aria-hidden` focus conflict resolved with `inert` + blur).
- Vercel Speed Insights integrated for frontend performance telemetry.
- Frontend BFF `ETag + Cache-Control` landed for cities/summary/history (`force_refresh` keeps `no-store`).
- Mispricing radar now hard-skips non-tradable markets (closed/inactive/not accepting orders/past endDate).
- AI analysis now includes peak-window hard constraints (before-window cannot claim "locked"/"confirmed floor").
- Bot entry refactor completed:
- `bot_listener.py` simplified to thin entrypoint.
- Runtime split into orchestrator/handlers/services/analysis/guard/coordinator layers.
- Startup diagnostics landed:
- `/diag` command
- loop-level startup status reporting (trade alerts, polygon watcher, polymarket watcher)
- Multi-model anchor migration completed for mispricing radar (replaced single Open-Meteo anchor).
- Non-tradable market hard-skip guard completed (closed/inactive/not accepting orders/past end time).
- Wallet activity watcher upgraded with alias parsing, link preview switch, and anti-spam debounce/immediate controls.
- Frontend BFF HTTP caching (`ETag`/`304`) completed for cities/summary/history.
- Meteoblue fully removed from runtime paths and docs.
---
## 3. High Priority Debt
## 3. Active High-Priority Debt
| Item | Impact | Suggested Work |
| :-- | :-- | :-- |
| Monolithic bot entry (`bot_listener.py`) | Hard to test and safely refactor | Split orchestration, IO and analysis modules |
| Entitlement enforcement consistency | Revenue leakage risk | Align frontend middleware and backend enforcement |
| Subscriber persistence model | Manual operations do not scale | Move to managed PostgreSQL/Supabase state |
| Alert explainability | Operator trust and debugging cost | Standardize evidence payload per alert |
| Payment event ingestion pipeline | Cannot automate paid access reliably | Build idempotent onchain payment ingest + reconciliation worker |
| Subscriber persistence model | Manual entitlement ops do not scale | Add managed PostgreSQL/Supabase subscriber state |
| Entitlement parity matrix | Access leaks/false denies across channels | Unify policy across frontend middleware, backend API, and bot guard |
| Alert evidence contract | Harder to debug false positives quickly | Standardize machine-readable evidence schema for each push |
---
## 4. Medium Priority Debt
## 4. Active Medium-Priority Debt
| Item | Impact | Suggested Work |
| :-- | :-- | :-- |
| Replay simulation harness | Hard to reproduce edge cases | Build deterministic replay over stored records |
| Chart/UI regression coverage | Visual regressions can slip | Add snapshot + interaction test coverage |
| Config centralization | Threshold changes are error-prone | Consolidate runtime knobs into structured config |
| Naming cleanup | Legacy terms reduce clarity | Refactor naming in market/weather boundary layer |
| Replay simulation harness | Edge-case regressions hard to reproduce | Deterministic replay from stored weather + market snapshots |
| End-to-end integration coverage | Runtime regressions can slip | Add integration tests for `/api/city/{name}/detail` + push decisions |
| Config sprawl | Tuning is error-prone | Consolidate env knobs into structured config groups |
| Naming and data contracts | Boundary confusion persists | Normalize model/market field naming and compatibility aliases |
---
## 5. Low Priority Debt
## 5. Active Low-Priority Debt
| Item | Impact | Suggested Work |
| :-- | :-- | :-- |
| Cold-start behavior | First request latency variance | Add warming strategy for top city routes |
| Storage abstraction | Local file assumptions remain | Continue moving state to remote services |
| Cold-start variance | First request latency jitter | Add prewarm strategy for top city routes |
| Local state files | Harder multi-instance scaling | Continue migration to managed storage |
---
## 6. Next Milestones
1. Entitlement parity: one policy across frontend and backend.
2. Subscriber DB integration and migration scripts.
3. Alert evidence schema + tooling for quick operator audit.
4. Replay runner for weather/market mixed regression scenarios.
1. Land subscriber DB + entitlement expiry model.
2. Ship payment ingest + automatic entitlement sync.
3. Add replay harness for weather/market mixed scenarios.
4. Publish alert evidence schema and operator tooling.
---
+44 -45
View File
@@ -1,94 +1,93 @@
# 技术债与工程待办
目标:在持续交付的同时,把关键技术债显式化、可追踪化
目标:在持续交付的同时,让技术债可见、可追踪、可关闭
---
## 1. 技术债全景
## 1. 债务快照
当前估计:**90% 稳定 / 10% 技术债**。
```mermaid
flowchart TD
A["技术债"]
subgraph AR["架构层"]
AR1["机器人入口过于集中"]
AR2["共享运行时耦合"]
end
subgraph PI["产品基础设施"]
PI1["订阅权限一致性"]
PI2["付费用户持久化"]
subgraph PI["支付基础设施"]
PI1["支付事件入库与对账"]
PI2["订阅用户持久化"]
PI3["权限策略一致化"]
end
subgraph Q["质量保障"]
Q1["回放测试能力"]
Q2["UI 回归覆盖不足"]
Q1["回放仿真能力"]
Q2["端到端集成覆盖"]
end
subgraph O["可观测性"]
O1["告警证据"]
O2["SLO 看板"]
O1["告警证据标准"]
O2["运维看板"]
end
A --> AR
A --> PI
A --> Q
A --> O
```
当前系统健康度估计:**86% 稳定 / 14% 技术债**。
---
## 2. 近期已关闭(2026-03-12
- Bot 入口重构完成:
- `bot_listener.py` 已收敛为薄入口。
- 运行时拆分为编排层/处理层/服务层/分析层/守卫层/协调层。
- 启动诊断完成:
- 新增 `/diag` 指令
- 后台循环启动状态可视化(错价雷达、Polygon 钱包、Polymarket 异动)
- 错价锚点完成升级:从单一 Open-Meteo 改为多模型最高温锚点。
- 不可交易市场硬拦截完成:`closed`/inactive/不接单/超结束时间全部跳过。
- 钱包异动监听增强完成:昵称映射、链接预览开关、去抖与即时推送控制。
- 前端 BFF `ETag/304` 缓存完成(cities/summary/history)。
- Meteoblue 已从运行链路与文档中彻底移除。
---
## 2. 最近已关闭项(2026-03-12
- Meteoblue API 全链路移除(后端/前端/配置/文档)。
- 市场温度桶重复刷屏问题修复(后端去重 + 前端兜底)。
- 详情面板可访问性告警修复(`aria-hidden` 焦点冲突改为 `inert + blur`)。
- 前端已接入 Vercel Speed Insights。
- 前端 BFF 增加 `ETag + Cache-Control`cities/summary/history)与 `force_refresh=no-store` 语义。
- 错价雷达增加“不可交易市场硬拦截”(closed/inactive/不接单/过 endDate)。
- AI 分析增加峰值时段硬约束(before 状态禁止“已锁定/已确认底线”)。
---
## 3. 高优先级技术债
## 3. 当前高优先级技术债
| 项目 | 影响 | 建议动作 |
| :-- | :-- | :-- |
| 机器人入口单体化(`bot_listener.py`) | 测试和重构风险高 | 拆分为编排层、IO 层、分析层 |
| 订阅权限策略不完全统一 | 可能造成付费泄露 | 前后端统一权限校验策略 |
| 付费用户状态持久化不足 | 人工运营不可扩展 | 迁移到托管 DBPostgreSQL/Supabase |
| 告警可解释性不足 | 运维排障成本高 | 统一告警证据字段(Evidence Schema |
| 支付事件采集与对账流水线 | 无法稳定自动开通付费权限 | 构建幂等 payment ingest + reconciliation worker |
| 订阅用户持久化模型 | 人工开通不可扩展 | 落地 PostgreSQL/Supabase 订阅状态 |
| 权限策略一致性矩阵 | 存在漏放行/误拦截风险 | 统一前端中间件、后端 API、Bot 守卫策略 |
| 告警证据协议 | 假阳性排障成本高 | 统一机器可读 Evidence Schema |
---
## 4. 中优先级技术债
## 4. 当前中优先级技术债
| 项目 | 影响 | 建议动作 |
| :-- | :-- | :-- |
| 回放仿真能力不足 | 边缘场景难复现 | 基于历史记录构建可重复 Replay |
| 图表/UI 回归覆盖不足 | 视觉回归风险 | 增加快照与交互自动化测试 |
| 阈值配置分散 | 改动成本高且易错 | 统一收口到结构化配置 |
| 命名历史包袱 | 认知成本高 | 系统化命名治理 |
| 回放仿真能力不足 | 边缘场景回归难复现 | 基于天气+市场快照构建确定性 Replay |
| 端到端集成覆盖不足 | 运行时回归难提前发现 | 增加 `/api/city/{name}/detail` 与推送链路集成测试 |
| 配置分散 | 阈值调优易出错 | 将关键 env 聚合为结构化配置分组 |
| 命名与字段兼容历史包袱 | 认知与维护成本高 | 统一模型/市场字段命名与兼容层 |
---
## 5. 低优先级技术债
## 5. 当前低优先级技术债
| 项目 | 影响 | 建议动作 |
| :-- | :-- | :-- |
| 冷启动波动 | 首次请求延迟不稳定 | 热点城市路由预热 |
| 本地文件状态依赖 | 云端弹性场景受限 | 续迁移到远程存储 |
| 冷启动波动 | 首次请求延迟抖动 | 热点城市路由预热 |
| 本地文件状态依赖 | 多实例扩展受限 | 续迁移到托管存储 |
---
## 6. 下阶段里程碑
1. 完成前后端订阅权限一致化
2. 上线付费用户持久化与迁移脚本
3. 建立告警证据标准并接入运维排障流
4. 落地天气+市场混合回放回归测试
1. 上线订阅用户 DB 与权限过期模型
2. 完成支付事件入库与自动授权同步
3. 落地天气+市场混合回放回归
4. 发布告警证据标准与运维排障工具
---