Compare commits

...
12 Commits
Author SHA1 Message Date
linkong 04cebdc504 release: bump version to 0.82.0
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
2026-12-01 18:43:57 +08:00
linkong b3d2d9e9f1 release: bump version to 0.81.0
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
2026-11-30 19:39:29 +08:00
linkong 6d310f4dbe release: bump version to 0.80.3
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-11-30 14:35:38 +08:00
linkong 2c439b7235 release: bump version to 0.80.2
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-11-30 11:06:33 +08:00
linkong 4b2004b7d8 release: bump version to 0.80.1
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-11-26 19:41:17 +08:00
linkong 41059ca42a release: bump version to 0.80.0
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-11-26 10:50:38 +08:00
linkong b7772f664c release: bump version to 0.79.2
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-11-25 19:38:13 +08:00
linkong 352b34e7c6 release: bump version to 0.79.1
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-11-24 21:00:42 +08:00
linkong 1e9508f2f1 ci: deploy published Planet releases by image digest
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-11-24 17:27:54 +08:00
linkong e53c3af355 release: bump version to 0.79.0
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release / images (push) Canceled after 0s
release / client_release (push) Canceled after 0s
2026-11-24 15:40:10 +08:00
linkong 5fc698d738 release: bump version to 0.78.0
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release / images (push) Canceled after 0s
release / client_release (push) Canceled after 0s
2026-11-23 22:40:11 +08:00
linkong e6aa8c539b fix: verify Gitea release assets before publishing
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-11-22 14:23:20 +08:00
354 changed files with 60908 additions and 4513 deletions

No files matched your search

+76 -4
View File
@@ -1,15 +1,15 @@
---
name: release
description: Use when the user asks to release, bump version, update changelog/version files, or commit/push a repository release for the Planet repo. Determines version bump type from changes, updates all required version-bearing files, updates changelog and version-history, runs minimal validation, then commits, tags, and pushes.
description: Use when the user asks to release, deploy, bump version, update changelog/version files, or commit/push a repository release (`发版`, `部署`, `发版部署`) for the Planet repo. Covers version bumps, validation, commit/tag/push, Gitea/OCI publication, production host script/config sync, and live deployment verification.
---
# Release Workflow
Use this skill for release-oriented work in this repository.
Use this skill for release and production deployment work in this repository.
## When To Use
- The user asks to `发版`
- The user asks to `发版`, `部署`, `发版部署`, `上线`, or `deploy`
- The user asks to bump a version
- The user asks to update `CHANGELOG`, `version-history`, or version files as part of a release
- The user asks to commit/push a release or a publishable bugfix/feature bundle
@@ -176,7 +176,76 @@ Push to remote:
```
- If remote publication was not requested or remote access is restricted, report the commit and tag as complete and output the push commands for manual execution.
### Step 9 — Completion summary
### Step 9 — Publish and verify the Gitea Release
When remote publication is requested, verify the remote tag points to the
release commit. For `gitea.rclaw.top/linkong/planet`, publish from the workstation
using the command below. The publisher inspects changed files against the previous
stable release (`scripts/release_scope.py`), pushes OCI `release-manifest:<tag>`,
and builds/uploads **only** the affected targets:
- `admin` / `backend` / `aiprovider`-only changes (`client.mode == "none"`): builds/pushes only the changed
service image(s) + OCI `release-manifest:<tag>`, **skips creating a Gitea Release**,
skips desktop packaging and client hotfix updates, and deploys only the changed container(s) on production.
- `frontend/public/earth/**`-only changes (`client.mode == "hotfix"`): emits only the L1 Earth hotfix bundle
(`./planet.sh bundle --hotfix`) while keeping the prior desktop `shell_version`, and creates a Gitea Release with `release-manifest.json` + hotfix bundle.
- `client/**` changes (`client.mode == "full"`): builds cross-platform desktop installers (`--all`) plus the
L1 hotfix bundle, and creates a Gitea Release with installers + `release-manifest.json`.
Use `--scope auto` (default) or override explicitly with `--scope admin`,
`--scope hotfix`, `--scope backend,admin`, or `--scope full`:
```bash
python3 scripts/release_publish.py --tag vx.x.x --dry-run
python3 scripts/release_publish.py --tag vx.x.x --use-git-credential
```
When verified desktop artifacts for the exact tag already exist, pass their
directory explicitly. A queued Gitea Actions run does not block local publication.
```bash
python3 scripts/release_publish.py --tag vx.x.x --assets-dir client/release --dry-run
python3 scripts/release_publish.py --tag vx.x.x --assets-dir client/release --use-git-credential
```
Use `GITEA_TOKEN` instead of `--use-git-credential` when publishing with a
configured token. The publish script uploads to a draft and checks the
attachment names and sizes before publishing. Verify the published Release URL
and expected attachments through Gitea before reporting success. If Gitea is
unreachable, report the tag and package state and why publication is incomplete.
### Step 9.5 — Production Host Sync & Live Deployment Verification (Required for `部署` / `发版部署` / `上线`)
Publishing images/manifests/Gitea assets in Step 9 does **not** deploy or update host-managed files (`发版 ≠ 已部署`). Whenever the user asks to `部署`, `发版部署`, or `上线`, run all four sub-checks before claiming deployment succeeded:
1. **Detect host-side file drift** against the previous release tag (`<prev_tag>`):
```bash
git diff --name-only <prev_tag>..vx.x.x -- \
scripts/production_deploy.py \
scripts/production_registry.py \
scripts/release_publish.py \
deploy/ \
docker-compose.deploy.yml
```
2. **Sync changed host-managed files BEFORE rollout/retry** (using the operator's configured SSH access; never hardcode IPs or secrets in repo files):
- If `scripts/production_deploy.py`, `scripts/production_registry.py`, or `scripts/release_publish.py` changed -> install onto the production host `/usr/local/lib/planet-release/` **before** triggering or retrying deployment so stale host checks (e.g. newly added `401` auth gates) cannot trigger a false-positive rollback.
- If `deploy/systemd/planet-release-deploy.{service,timer}` changed -> install to `/etc/systemd/system/` and run `sudo systemctl daemon-reload`.
- If `docker-compose.deploy.yml` or `deploy/nginx/*` changed -> sync env/compose additions into `/opt/planet/current/` or host Nginx sites and run `sudo nginx -t && sudo systemctl reload nginx`.
3. **Trigger or observe production rollout on host**:
- Inspect service status and trigger/retry as needed:
- Check logs: `journalctl -u planet-release-deploy.service -n 50 --no-pager`
- Verify state / manifest match: `sudo python3 /usr/local/lib/planet-release/production_deploy.py --check`
- If an earlier timer run failed (e.g. due to a host-script mismatch) and skipped `vx.x.x`, clear the skip after syncing host scripts by running `sudo python3 /usr/local/lib/planet-release/production_deploy.py --retry` (or `sudo systemctl start planet-release-deploy.service`).
- Confirm running containers (`backend`, `admin`, `aiprovider`) are `healthy` and their image digests match OCI `release-manifest:vx.x.x`.
4. **Verify live public endpoints reflect `vx.x.x`**:
- Confirm `https://api.rclaw.top/health/ready` returns HTTP 200 and live version matches `x.x.x`.
- When `client.mode != "none"`, confirm `https://rclaw.top/api/v1/client/update-manifest` returns `version == "x.x.x"` and the expected bundle SHA-256.
- **Never claim `已部署` if host SSH is unavailable or live endpoints still show an older version**: report publication complete (`dev` / `vx.x.x` / Gitea / OCI) separately from the exact pending host sync / deploy commands.
### Step 10 — Completion summary
```
✓ Version bumped: 0.76.18 → 0.76.19
@@ -187,6 +256,9 @@ Push to remote:
✓ commit: release: bump version to 0.76.19
✓ tag: v0.76.19
✓ Pushed to origin/dev (or reported pending manual push)
✓ Gitea Release and attachments verified (when publication was requested)
✓ Host-side deploy scripts / Compose / Nginx drift checked & synced (when deployment was requested)
✓ Production rollout & live endpoints verified at target version (or pending host steps listed explicitly)
```
## Notes
+1
View File
@@ -16,6 +16,7 @@
!scripts/
!scripts/build_earth_boundary_china_pov_geojson.py
!scripts/build_earth_boundary_pmtiles.py
!scripts/db_migrate.py
!scripts/earth_boundary_policy.py
!resources/
!resources/earth/
+14 -20
View File
@@ -4,8 +4,7 @@ on:
push:
branches:
- main
tags:
- "v*"
# Tagged production releases are published on demand from the workstation.
workflow_dispatch:
env:
@@ -17,18 +16,18 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Resolve image tags
id: meta
run: |
echo "sha_tag=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
if printf "%s" "${GITHUB_REF}" | grep -q '^refs/tags/v'; then
echo "release_tag=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT"
else
echo "release_tag=" >> "$GITHUB_OUTPUT"
fi
- name: Login to registry
run: echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login "$REGISTRY" -u "${{ secrets.REGISTRY_USER }}" --password-stdin
- name: Build and push images
env:
REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
run: printf '%s' "$REGISTRY_PASSWORD" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin
- name: Publish immutable production images
if: startsWith(github.ref, 'refs/tags/v')
run: |
export PLANET_RELEASE_DOCKER_CONFIG="${DOCKER_CONFIG:-$HOME/.docker}"
python3 scripts/production_release.py "$GITHUB_REF_NAME"
- name: Build and push staging images
if: "!startsWith(github.ref, 'refs/tags/v')"
run: |
for service in frontend admin backend aiprovider; do
extra_build_args=""
@@ -52,18 +51,13 @@ jobs:
;;
esac
image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.sha_tag }}"
image="$REGISTRY/$IMAGE_NAMESPACE/$service:$GITHUB_SHA"
docker build $extra_build_args -t "$image" -f "$dockerfile" "$context"
docker push "$image"
if [ -n "${{ steps.meta.outputs.release_tag }}" ]; then
release_image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.release_tag }}"
docker tag "$image" "$release_image"
docker push "$release_image"
fi
done
client_release:
needs: images
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
steps:
+2
View File
@@ -6,8 +6,10 @@
# 敏感文件
# ----------------------
.env
.env.deploy
.env.local
.env.*.local
backups/
config/earth-boundary-sources.local.json
*.pem
*.key
+22
View File
@@ -90,6 +90,7 @@ the user's login interactive shell instead of assuming a specific dotfile.
- `planet.sh` owns local lifecycle, ports, WSL/LAN behavior, and destructive
`destroy` cleanup.
- Frontend package management is Bun-only. Do not use npm, pnpm, or yarn.
- **Local Frontend Dev Uses Vite, Not Static Nginx**: Local frontend/Admin development defaults to the host Vite HMR server (`./planet.sh start` / `./planet.sh restart -f`); do not run or rebuild the static Nginx `planet_admin` container (`./planet.sh admin ...`) unless the user explicitly asks to simulate production locally (`本地模拟线上`).
- Frontend changes must satisfy `scripts/harness/frontend-rules-check.sh`; use
rendered smoke evidence for public pages, auth guards, authenticated admin
route/section availability, safe navigation/search/tab interactions, mobile
@@ -98,6 +99,12 @@ the user's login interactive shell instead of assuming a specific dotfile.
one-screen (`一屏` / `首屏`) height chain: route roots use `height: 100%`,
intermediate wrappers keep `min-height: 0`, and only the intended child owns
scrolling.
- **Admin Control Design Contract**: Inline controls in the same row must share
a `rules.md` density tier (`--an-control-xs/sm/md/lg`, e.g., `32px` filter bar
with `0px` height jump on filter reset), centered table selection/switch
columns, rounded-square shadowless `.tui-switch`, labeled `操作` columns, and
`.an-detail-link` navigation cues; enforced by
`scripts/harness/frontend-rules-check.sh` and `scripts/harness/frontend-smoke.mjs`.
- **Existing-UI Context Inspection Before Editing**: Whenever changing or
extending an existing interface (any non-new screen, such as `/earth/` HUD
overlays or existing Admin/Docs pages), inspect surrounding sibling controls,
@@ -120,6 +127,21 @@ the user's login interactive shell instead of assuming a specific dotfile.
committed files.
- Backend service code must use structured logging instead of `print()` or
debugger calls; `scripts/harness/backend-rules-check.sh` enforces this.
- **Client-Only Gitea Releases**: Releases without client updates
(`client.mode == "none"`) push only changed container images plus OCI
`release-manifest:<tag>` and must **not** create a Gitea Release; only
`hotfix` or `full` client releases create a Gitea Release, and production
`planet-release-deploy` reconciles from Git tags + OCI `release-manifest:<tag>`.
- **Release Publish vs. Production Deployment (`发版 ≠ 已部署`)**:
`scripts/release_publish.py` only publishes container images, OCI
`release-manifest:<tag>`, and optional Gitea Releases; it never updates
host-side files or verifies rollout. Whenever the user asks to `部署`,
`发版部署`, or `上线`, follow `.codex/skills/release/SKILL.md` to diff
host-managed files (`scripts/production_deploy.py`, `deploy/`,
`docker-compose.deploy.yml`) against the prior tag, sync any changed host
files before rollout/retry, inspect `planet-release-deploy.service`, and
verify live public endpoints reflect the target version before claiming
deployment succeeded.
### Conflict Policy
+69 -50
View File
@@ -13,42 +13,35 @@
- **Admin 运维台**:支持通过 `PLANET_FRONTEND_TARGET=admin` 构建剔除 Earth 静态资源(约 110 MB)的轻量 Nginx 容器 `planet_admin`,也可保留在一体化 Web 开发服务中。
- **后端与模型适配层**:FastAPI 数据与 AI 编排后端 + `aiprovider` 独立模型协议适配层。
```
┌─────────────────────────────────────────────────────────────────────┐
│ 浏览器展示与运维层 │
│ ┌──────────────────────────────┐ ┌──────────────────────────────┐ │
│ │ Web Earth │ │ React 运维台 │ │
│ │ frontend/public/earth │ │ frontend/src │ │
│ │ Three.js 地球 / HUD / 新闻 │ │ 数据源 / 告警 / AI 设置 │ │
│ │ 国界精度 / 品牌内容配置 │ │ 提示词配置 / 用户与系统配置 │ │
│ └──────────────────────────────┘ └──────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘
│ REST / WebSocket
▼
┌─────────────────────────────────────────────────────────────────────┐
│ FastAPI 业务与编排后端 │
│ ┌────────────────────┐ ┌────────────────────┐ ┌─────────────────┐ │
│ │ 数据 API 与认证 │ │ Earth 新闻增强 │ │ 告警与态势简报 │ │
│ │ JWT / 权限 / 审计 │ │ 位置推断 / 本地化 │ │ BGP / 告警研判 │ │
│ └────────────────────┘ └────────────────────┘ └─────────────────┘ │
│ ┌────────────────────┐ ┌────────────────────┐ ┌─────────────────┐ │
│ │ 系统运行配置 │ │ 默认提示词注册表 │ │ 未来 Agent Runtime│ │
│ │ system_settings │ │ 代码发布 + DB 覆盖 │ │ 工具/证据/工作流 │ │
│ └────────────────────┘ └────────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘
│ SQLAlchemy / Redis Stream │ 纯净 LLM 调用
▼ ▼
┌──────────────────────────────┐ ┌──────────────────────────────┐
│ PostgreSQL / Redis │ │ aiprovider │
│ 用户、配置、采集结果、新闻 │ │ provider + protocol adapter │
│ Stream、缓存、运行状态 │ │ OpenAI / MiniMax / Ollama 等 │
└──────────────────────────────┘ └──────────────────────────────┘
▲
│ 采集器 / 外部数据源
▼
┌─────────────────────────────────────────────────────────────────────┐
│ RSS 新闻、BGP 观测、公开数据源、后续 WebSearch/OCR/语音识别等工具 │
└─────────────────────────────────────────────────────────────────────┘
```mermaid
flowchart TD
subgraph UI["展示与运维端"]
Earth["Web / Electron Earth (frontend/public/earth + client)"]
Admin["React 运维台与 AI 参谋 (frontend/src/admin)"]
end
subgraph Backend["FastAPI 业务与 AI 编排后端 (backend/)"]
API["业务 API、认证与反爬网关"]
DAG["DAG 多节点工作流引擎与工具白名单"]
Evolve["三层工作流自进化与宪法校验内核"]
Settings["系统配置与默认提示词 (system_settings / default_prompts)"]
end
subgraph Infra["数据存储与模型协议层"]
PG["PostgreSQL / Redis (数据、快照、运行轨迹与进化台账)"]
AIP["aiprovider 独立协议网关 (OpenAI / MiniMax / Ollama 等)"]
Sources["外部采集源 (RSS / BGP / PeeringDB / 海缆 / 卫星 / WebSearch)"]
end
Earth -->|"REST / SSE / WebSocket"| API
Admin -->|"REST / SSE"| API
API --> DAG
API --> Settings
DAG -->|"运行遥测与灰度检查"| Evolve
Evolve -->|"受宪法约束写回草稿 / 发布 / 回滚"| PG
API --> PG
DAG -->|"纯净模型请求"| AIP
Sources -->|"采集与增强写入"| PG
```
架构边界:
@@ -57,7 +50,32 @@
- `aiprovider` 只负责把纯净模型请求适配到不同供应商或协议,不内置具体业务提示词。
- 默认提示词随代码发布并保存在 `backend/app/ai_tasks/default_prompts.json`,运维台可在数据库中保存覆盖值,重置时回到当前代码版本的默认提示词。
- Earth 新闻保留英文原文,中文展示结果存入 `localizations`,前端默认展示 `zh-CN` 的 `display_title`、`display_summary` 和中文地域/状态文案。
- Earth LLM 指令、语音识别、多角色态势研判属于后续 Agent Runtime 方向,计划见 [docs/plans/agents-earth-command-runtime-plan.md](/home/ray/dev/linkong/planet/docs/plans/agents-earth-command-runtime-plan.md)。
- AI 工作流支持可视化编排、自进化调优与地球交互联动,规划与演进记录见 [AI 参谋工作流与自进化方案](docs/plans/ai-advisor-workflow-and-location-agent-plan.md) 与 [Earth 贴地影响范围与三维视觉升级方案](docs/plans/earth-influence-zones-and-vfx-upgrade-plan.md)。
## AI 工作流自进化与元进化
为避免“人工写死工作流无法随新模型与真实运行退化持续迭代”,系统内置了 **零改表、三层有界自举架构**(详见 [workflow_evolver.py](backend/app/services/ai/workflow_evolver.py)):
- **Tier 0 · 不可变宪法内核(Python 硬约束)**:AI 永远无法修改底层校验代码。强制执行单层元递归锁(禁止自定义 `meta.*`)、冻结元引擎 `verify_output` 节点、限制单次自动改动半径(`<= 2` 个且 `<= 40%` 节点)、强制冷却期与每日自动预算上限,以及 **5 次运行灰度自动回滚**。
- **Tier 1 · 业务工作流自优化与模型适配**:零成本采集 `WorkflowRun.budget_used` 中的模型名、耗时、版本号与 👍/👎 反馈;结合 0-Token 健康诊断、模型能力漂移检测、DGM 历史最佳父版本分支与 AFlow 正负经验生成最小节点补丁,并支持 Fixture A/B 对照与从高频问题孵化新工作流。可在管理台 `/advisor/workflows` 顶栏随时切换 `关闭(手动)` / `自动写草稿` / `自动发布 + 灰度回滚` 模式及单工作流锁定开关。
- **Tier 2 · 元进化(`meta.workflow_evolver` 自举)**:内置三节点元工作流直接在工作流画布可见、可回滚;在独立开启元进化开关后,可依据历史台账验证/回滚客观结果迭代自身诊断与补丁合成策略,并受 7 天冷却与下游 3 次结果窗口自动回退保护。
```mermaid
flowchart TD
Run["Playground / Earth 工作流运行 (记录 model_used / latency / 版本号)"] --> FB["管理员 👍 / 👎 反馈与失败轨迹"]
FB --> Health["0-Token 健康与模型漂移诊断 (信号检测 + DGM 最佳父版本)"]
Health -->|"手动触发或满足冷却/预算后异步触发"| Meta["Tier 2 元引擎 meta.workflow_evolver (diag_node -> patch_node -> verify_output)"]
Ledger["进化台账 system_settings.ai_evolution_ledger (正负经验 / 已验证 / 已回滚)"] -->|"AFlow 经验注入"| Meta
Meta -->|"生成最小节点 Diff 补丁"| Tier0{"Tier 0 不可变宪法内核:白名单 / 半径锁 / 禁清空提示词 / 禁 meta 递归"}
Tier0 -->|"拦截"| Block["记入台账 blocked 并保留原版本"]
Tier0 -->|"通过"| Mode{"策略模式 (off / draft / auto)"}
Mode -->|"draft"| Draft["写入 draft_graph 待人工审核 / Fixture A-B 对照"]
Mode -->|"auto (未锁定且未超日上限)"| Canary["自动发布新版本 + 开启 5 次运行灰度窗口"]
Canary -->|"连续 2 次失败或差评率超阈"| Rollback["自动回滚上一稳定版本 & 记为 rolled_back"]
Canary -->|"通过 5 次运行验证"| Verified["晋升为 verified 经验;积累 >=5 条后可触发元引擎自举"]
Verified --> Ledger
Rollback --> Ledger
```
## 四大核心要素
@@ -239,7 +257,7 @@ bun run build
推荐按下面顺序排查和配置。
端口占用、`iphlpsvc` / portproxy、摄像头和依赖问题的集中排障入口见 [常见问题](/home/ray/dev/linkong/planet/docs/technical/zh/faq.md)。
端口占用、`iphlpsvc` / portproxy、摄像头和依赖问题的集中排障入口见 [常见问题](docs/technical/zh/faq.md)。
### 1. 在 WSL 中启动服务
@@ -381,7 +399,7 @@ DATABASE_RETRY_INTERVAL=10 \
- 运维台 AI 设置可维护 provider、模型、协议、超时、token 等运行配置。
- 运维台 AI 设置中的“提示词”页可选择不同功能入口,手动覆盖提示词,并一键重置到默认值。
- 默认提示词随代码发布,位于 [backend/app/ai_tasks/default_prompts.json](/home/ray/dev/linkong/planet/backend/app/ai_tasks/default_prompts.json)。
- 默认提示词随代码发布,位于 [backend/app/ai_tasks/default_prompts.json](backend/app/ai_tasks/default_prompts.json)。
- 覆盖值保存在数据库运行配置中,升级代码后可继续保留现场配置,也可重置到新版本默认提示词。
- 态势摘要、告警研判、新闻本地化等入口应使用各自任务提示词;调用 `aiprovider` 时只传递当前任务所需的 `prompt` / `system_prompt`。
@@ -427,8 +445,8 @@ AI_ANTHROPIC_VERSION=2023-06-01
如果你要本地直接起模型适配层,项目里已经补了模板:
- [aiprovider/.env.example](/home/ray/dev/linkong/planet/aiprovider/.env.example)
- [docker-compose.local-model.yml](/home/ray/dev/linkong/planet/docker-compose.local-model.yml)
- [aiprovider/.env.example](aiprovider/.env.example)
- [docker-compose.local-model.yml](docker-compose.local-model.yml)
运行与调用补充:
@@ -439,13 +457,14 @@ AI_ANTHROPIC_VERSION=2023-06-01
详细文档:
- [docs/technical/zh/agents-aiprovider.md](/home/ray/dev/linkong/planet/docs/technical/zh/agents-aiprovider.md)
- [docs/technical/en/agents-aiprovider.md](/home/ray/dev/linkong/planet/docs/technical/en/agents-aiprovider.md)
- [aiprovider/README.md](/home/ray/dev/linkong/planet/aiprovider/README.md)
- [docs/technical/frontend-layout-guidelines.md](/home/ray/dev/linkong/planet/docs/technical/frontend-layout-guidelines.md)
- [docs/plans/frontend-ai-playground-development-plan.md](/home/ray/dev/linkong/planet/docs/plans/frontend-ai-playground-development-plan.md)
- [docs/plans/agents-situational-awareness-foundation-plan.md](/home/ray/dev/linkong/planet/docs/plans/agents-situational-awareness-foundation-plan.md)
- [docs/plans/agents-earth-command-runtime-plan.md](/home/ray/dev/linkong/planet/docs/plans/agents-earth-command-runtime-plan.md)
- [docs/technical/zh/agents-aiprovider.md](docs/technical/zh/agents-aiprovider.md)
- [docs/technical/en/agents-aiprovider.md](docs/technical/en/agents-aiprovider.md)
- [aiprovider/README.md](aiprovider/README.md)
- [docs/technical/zh/frontend-layout-guidelines.md](docs/technical/zh/frontend-layout-guidelines.md)
- [docs/plans/ai-advisor-workflow-and-location-agent-plan.md](docs/plans/ai-advisor-workflow-and-location-agent-plan.md)
- [docs/plans/earth-influence-zones-and-vfx-upgrade-plan.md](docs/plans/earth-influence-zones-and-vfx-upgrade-plan.md)
- [docs/plans/agents-situational-awareness-foundation-plan.md](docs/plans/agents-situational-awareness-foundation-plan.md)
- [docs/plans/agents-earth-command-runtime-plan.md](docs/plans/agents-earth-command-runtime-plan.md)
## 前端页面布局规范
@@ -458,8 +477,8 @@ AI_ANTHROPIC_VERSION=2023-06-01
当前推荐参考实现:
- [frontend/src/pages/BGP/BGP.tsx](/home/ray/dev/linkong/planet/frontend/src/pages/BGP/BGP.tsx)
- [docs/technical/frontend-layout-guidelines.md](/home/ray/dev/linkong/planet/docs/technical/frontend-layout-guidelines.md)
- [frontend/src/admin/pages/AdvisorWorkflows.tsx](frontend/src/admin/pages/AdvisorWorkflows.tsx)
- [docs/technical/zh/frontend-layout-guidelines.md](docs/technical/zh/frontend-layout-guidelines.md)
## License
+1 -1
View File
@@ -1 +1 @@
0.77.0
0.82.0
+13 -8
View File
@@ -1,6 +1,7 @@
# Shared service settings
SERVICE_NAME=planet-ai-provider
SERVICE_VERSION=0.1.0
APP_ENV=development
AI_PROVIDER_SERVICE_TOKEN=change_me
AI_TIMEOUT_SECONDS=60
AI_HTTP_RETRY_ATTEMPTS=2
@@ -28,18 +29,22 @@ AI_MODEL=MiniMax-M2.7
# MiniMax CN Anthropic-compatible example
AI_BASE_URL=https://api.minimaxi.com/anthropic
AI_API_KEY=sk-cp-change-me
AI_API_KEY=replace-with-provider-key
AI_MAX_TOKENS=1200
AI_ANTHROPIC_VERSION=2023-06-01
# Optional provider-specific keys used by Settings fallback before AI_API_KEY
# MINIMAX_API_KEY=sk-cp-change-me
# OPENAI_API_KEY=sk-change-me
# ANTHROPIC_API_KEY=sk-ant-change-me
# DEEPSEEK_API_KEY=sk-change-me
# DASHSCOPE_API_KEY=sk-change-me
# MOONSHOT_API_KEY=sk-change-me
# OPENROUTER_API_KEY=sk-or-change-me
# MINIMAX_API_KEY=replace-with-minimax-key
# OPENAI_API_KEY=replace-with-openai-key
# ANTHROPIC_API_KEY=replace-with-anthropic-key
# DEEPSEEK_API_KEY=replace-with-deepseek-key
# DASHSCOPE_API_KEY=replace-with-dashscope-key
# MOONSHOT_API_KEY=replace-with-moonshot-key
# ZHIPU_API_KEY=replace-with-zhipu-key
# META_MODEL_API_KEY=replace-with-meta-key
# GEMINI_API_KEY=replace-with-gemini-key
# XAI_API_KEY=replace-with-xai-key
# OPENROUTER_API_KEY=replace-with-openrouter-key
# OpenAI-compatible example (vLLM / LM Studio / One API / local gateway)
# AI_PROVIDER=openai
+6
View File
@@ -7,6 +7,7 @@ from pydantic_settings import BaseSettings
class Settings(BaseSettings):
SERVICE_NAME: str = "planet-ai-provider"
SERVICE_VERSION: str = "0.1.0"
APP_ENV: str = "development"
AI_PROVIDER: str = "disabled"
AI_PROVIDER_API: str = "auto"
@@ -20,9 +21,14 @@ class Settings(BaseSettings):
AI_PROVIDER_SERVICE_TOKEN: str = ""
@property
def is_production(self) -> bool:
return str(self.APP_ENV or "").strip().lower() == "production"
class Config:
env_file = Path(__file__).parent / ".env"
case_sensitive = True
extra = "ignore"
@lru_cache()
+63 -2
View File
@@ -1,6 +1,10 @@
from contextlib import asynccontextmanager
import hmac
import json
from uuid import uuid4
from fastapi import Depends, FastAPI, Header, HTTPException, Request, Response, status
from fastapi.responses import StreamingResponse
from aiprovider.config import settings
from aiprovider.provider_service import ProviderService
@@ -10,10 +14,30 @@ from aiprovider.schemas import (
SituationalAnalysisResponse,
)
WEAK_TOKEN_PLACEHOLDERS = frozenset({"", "change-me", "change_me", "replace-with-internal-token"})
def validate_provider_security() -> None:
if not settings.is_production:
return
token = str(settings.AI_PROVIDER_SERVICE_TOKEN or "").strip()
if token in WEAK_TOKEN_PLACEHOLDERS:
raise RuntimeError(
"AI_PROVIDER_SERVICE_TOKEN must be configured (not empty or placeholder) when APP_ENV=production"
)
@asynccontextmanager
async def lifespan(_app: FastAPI):
validate_provider_security()
yield
app = FastAPI(
title=settings.SERVICE_NAME,
version=settings.SERVICE_VERSION,
description="AI provider adapter service for Planet",
lifespan=lifespan,
)
@@ -27,10 +51,15 @@ async def request_id_middleware(request: Request, call_next):
def verify_service_token(x_provider_token: str | None = Header(default=None)) -> None:
expected = settings.AI_PROVIDER_SERVICE_TOKEN
expected = str(settings.AI_PROVIDER_SERVICE_TOKEN or "")
if not expected:
if settings.is_production:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Provider service token not configured",
)
return
if x_provider_token != expected:
if not x_provider_token or not hmac.compare_digest(x_provider_token, expected):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid provider service token",
@@ -97,3 +126,35 @@ async def analyze(
):
response.headers["X-Request-ID"] = request.state.request_id
return await provider_service.analyze(payload)
@app.post(
"/v1/analyze/stream",
dependencies=[Depends(verify_service_token)],
)
async def analyze_stream(
payload: SituationalAnalysisRequest,
request: Request,
provider_service: ProviderService = Depends(get_provider_service),
):
request_id = request.state.request_id
async def event_generator():
try:
async for item in provider_service.stream_analyze(payload):
event_name = str(item.get("event") or "message")
yield f"event: {event_name}\ndata: {json.dumps(item, ensure_ascii=False)}\n\n"
except Exception as exc:
detail = exc.detail if isinstance(exc, HTTPException) else exc
err_payload = {"event": "error", "detail": str(detail)}
yield f"event: error\ndata: {json.dumps(err_payload, ensure_ascii=False)}\n\n"
return StreamingResponse(
event_generator(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
"X-Request-ID": request_id,
},
)
File diff suppressed because it is too large. Load diff
+30 -2
View File
@@ -1,8 +1,28 @@
from typing import Any
from typing import Any, Literal
from pydantic import BaseModel, Field
class ChatMessage(BaseModel):
role: Literal["user", "assistant", "tool"]
content: str = Field(default="", max_length=24000)
tool_call_id: str | None = Field(default=None, max_length=200)
name: str | None = Field(default=None, max_length=200)
tool_calls: list[dict[str, Any]] | None = None
class ToolCallRecord(BaseModel):
id: str
name: str
arguments: dict[str, Any] = Field(default_factory=dict)
class ImageAttachment(BaseModel):
mime_type: str = Field(..., pattern=r"^image/(png|jpeg|jpg|webp|gif)$")
data_base64: str = Field(..., min_length=8, max_length=6_000_000)
name: str = Field(default="", max_length=200)
class AIContentBlock(BaseModel):
type: str
text: str | None = None
@@ -13,13 +33,19 @@ class AIContentBlock(BaseModel):
class SituationalAnalysisRequest(BaseModel):
title: str = Field(..., min_length=1, max_length=200)
objective: str = Field(..., min_length=1, max_length=20000)
objective: str = Field(..., min_length=1, max_length=24000)
context: dict[str, Any] = Field(default_factory=dict)
observations: list[str] = Field(default_factory=list)
constraints: list[str] = Field(default_factory=list)
system_prompt: str | None = Field(default=None, max_length=8000)
preferred_model: str | None = Field(default=None, max_length=200)
thinking: dict[str, Any] | None = None
messages: list[ChatMessage] = Field(default_factory=list, max_length=48)
tools: list[dict[str, Any]] | None = None
tool_choice: str | dict[str, Any] | None = None
response_format: dict[str, Any] | None = None
native_web_search: bool = False
images: list[ImageAttachment] = Field(default_factory=list, max_length=8)
class SituationalAnalysisResponse(BaseModel):
@@ -29,6 +55,8 @@ class SituationalAnalysisResponse(BaseModel):
content_blocks: list[AIContentBlock] = Field(default_factory=list)
text_blocks: list[str] = Field(default_factory=list)
thinking_blocks: list[str] = Field(default_factory=list)
tool_calls: list[ToolCallRecord] = Field(default_factory=list)
stop_reason: str | None = None
raw_response: dict[str, Any] = Field(default_factory=dict)
+21 -3
View File
@@ -1,10 +1,24 @@
PROJECT_NAME=Intelligent Planet Plan
APP_VERSION=0.23.0
APP_ENV=development
PLANET_ROLE=all
SECRET_KEY=change_me_to_a_random_secret
SECRET_KEY=change_me_to_a_random_32_plus_char_secret
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=0
REFRESH_TOKEN_EXPIRE_DAYS=0
ACCESS_TOKEN_EXPIRE_MINUTES=60
REFRESH_TOKEN_EXPIRE_DAYS=7
CORS_ORIGINS=["http://localhost:3000","http://127.0.0.1:3000","http://localhost:8000","http://127.0.0.1:8000","planet://earth"]
# Optional bootstrap super_admin on fresh/production DB
INITIAL_ADMIN_USERNAME=
INITIAL_ADMIN_EMAIL=
INITIAL_ADMIN_PASSWORD=
# Optional encryption key for persisted SMTP & integration API keys
SETTINGS_ENCRYPTION_KEY=
LOGIN_RATE_LIMIT_MAX_ATTEMPTS=10
LOGIN_RATE_LIMIT_WINDOW_SECONDS=300
POSTGRES_SERVER=localhost
POSTGRES_USER=postgres
@@ -15,8 +29,12 @@ DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/planet_db
REDIS_SERVER=localhost
REDIS_PORT=6379
REDIS_DB=0
REDIS_PASSWORD=
REDIS_URL=redis://localhost:6379/0
COLLECTOR_MAX_CONCURRENCY=2
COLLECTOR_HEAVY_CONCURRENCY=1
AI_PROVIDER_SERVICE_URL=http://localhost:8010
AI_PROVIDER_SERVICE_TOKEN=change_me
AI_PROVIDER_TIMEOUT_SECONDS=60
+1
View File
@@ -31,6 +31,7 @@ COPY backend /app/backend
COPY config/earth-boundary-pov-policy.china-v1.json /app/config/earth-boundary-pov-policy.china-v1.json
COPY scripts/build_earth_boundary_china_pov_geojson.py /app/scripts/build_earth_boundary_china_pov_geojson.py
COPY scripts/build_earth_boundary_pmtiles.py /app/scripts/build_earth_boundary_pmtiles.py
COPY scripts/db_migrate.py /app/scripts/db_migrate.py
COPY scripts/earth_boundary_policy.py /app/scripts/earth_boundary_policy.py
COPY resources/earth/boundary-pov-geometry.china-v1.json /app/resources/earth/boundary-pov-geometry.china-v1.json
COPY frontend/public/earth/assets/cards/manifest.json /app/frontend/public/earth/assets/cards/manifest.json
+16
View File
@@ -102,5 +102,21 @@
"version": "2026-11-11.1",
"system_prompt": "你是算力白皮书数据核验提取器。仅提取原文明确写出的国家算力份额、FP32 规模或内部结构数值,输出严格 JSON 候选数组供管理员审核,严禁估算或补齐未出现的国家。",
"prompt": "从提供的报告摘录与来源元数据中提取待审核的算力观测候选记录。"
},
{
"key": "earth.news.analysis",
"label": "Earth 新闻深层分析",
"group": "Earth 新闻",
"version": "2026-11-30.1",
"system_prompt": "你是智能星球地球热点新闻与地缘基础设施分析师。请基于新闻全文、位置上下文与基础设施邻近关系,给出客观、可溯源的深层研判(Markdown,包含事实摘要、影响范围、关联基础设施与观察建议)。",
"prompt": "围绕选中的新闻事件与关联空间坐标展开深度分析,突出对海底光缆、算力枢纽与跨境路由的潜在影响。"
},
{
"key": "memory.compact",
"label": "Earth Copilot 会话记忆压缩",
"group": "态势参谋",
"version": "2026-11-30.1",
"system_prompt": "你是对话上下文压缩器。提取已确认事实、关注实体 ID、时间范围与未决问题,输出简洁要点以供后续多轮追问继承。",
"prompt": "将较早的多轮地球参谋对话历史压缩为高信息密度记忆摘要,保留实体键与核心结论。"
}
]
+20 -1
View File
@@ -124,7 +124,26 @@ async def get_effective_prompt(db: AsyncSession | None, task_key: str) -> Effect
if db is None:
return _effective_prompt(definition, None)
overrides = await get_prompt_overrides(db)
return _effective_prompt(definition, overrides.get(task_key))
override = overrides.get(task_key)
if not override:
try:
from app.services.ai.workflow_registry import resolve_prompt_override_from_workflows
wf_prompt = await resolve_prompt_override_from_workflows(db, task_key)
except Exception:
wf_prompt = None
if wf_prompt is not None:
sys_p, user_p = wf_prompt
has_wf = bool((sys_p or "").strip() or (user_p or "").strip())
if has_wf and (
sys_p != definition.system_prompt or user_p != definition.prompt
):
override = {
"system_prompt": sys_p,
"prompt": user_p,
"updated_at": "",
}
return _effective_prompt(definition, override)
async def save_prompt_override(
+4
View File
@@ -2,12 +2,14 @@ from app.api.v1 import card_images
from fastapi import APIRouter
from app.api.v1 import (
ai,
api_keys,
auth,
users,
datasource_config,
datasources,
docs,
earth,
client_updates,
tasks,
dashboard,
alerts,
@@ -40,11 +42,13 @@ api_router.include_router(datasources.router, prefix="/datasources", tags=["data
api_router.include_router(collected_data.router, prefix="/collected", tags=["collected-data"])
api_router.include_router(docs.router, prefix="/docs", tags=["docs"])
api_router.include_router(earth.router, prefix="/earth", tags=["earth"])
api_router.include_router(client_updates.router, prefix="/client", tags=["client-updates"])
api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"])
api_router.include_router(dashboard.router, prefix="/dashboard", tags=["dashboard"])
api_router.include_router(alerts.router, prefix="/alerts", tags=["alerts"])
api_router.include_router(settings.router, prefix="/settings", tags=["settings"])
api_router.include_router(system_control.router, prefix="/system", tags=["system"])
api_router.include_router(api_keys.router, prefix="/system/api-keys", tags=["api-keys"])
api_router.include_router(data_products.router, prefix="/data-products", tags=["data-products"])
api_router.include_router(compute_intelligence.router, prefix="/data-products/compute", tags=["compute"])
api_router.include_router(
+2
View File
@@ -49,8 +49,10 @@ from app.services.playground_chat_service import (
)
from app.services.situational_alert_ai_brief import build_situational_alert_brief_request
from app.services.business_logs import emit_business_log, exception_context
from app.api.v1.ai_workflows import router as ai_workflows_router
router = APIRouter()
router.include_router(ai_workflows_router)
logger = get_logger(__name__, service="api")
File diff suppressed because it is too large. Load diff
+85
View File
@@ -0,0 +1,85 @@
"""Admin endpoints for managing internal UE5 and external partner API keys."""
from __future__ import annotations
from typing import Optional
from fastapi import APIRouter, Depends, status
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_admin_user
from app.db.session import get_db
from app.models.user import User
from app.services.api_keys import (
EARTH_ALL_READ_SCOPE,
EARTH_READ_SCOPES,
create_api_key,
delete_api_key,
list_api_keys,
revoke_api_key,
serialize_api_key,
)
router = APIRouter()
class ApiKeyCreateRequest(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
name: str = Field(min_length=1, max_length=120)
scopes: list[str] = Field(default_factory=lambda: [EARTH_ALL_READ_SCOPE])
rate_limit_per_minute: Optional[int] = Field(default=None, ge=0, le=100_000)
expires_in_days: Optional[int] = Field(default=None, ge=0, le=3650)
@router.get("")
async def get_api_keys(
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
items = [serialize_api_key(record) for record in await list_api_keys(db)]
return {
"items": items,
"available_scopes": [EARTH_ALL_READ_SCOPE, *sorted(EARTH_READ_SCOPES)],
}
@router.post("", status_code=status.HTTP_201_CREATED)
async def create_new_api_key(
payload: ApiKeyCreateRequest,
admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
record, raw_key = await create_api_key(
db,
name=payload.name,
scopes=payload.scopes,
rate_limit_per_minute=payload.rate_limit_per_minute,
expires_in_days=payload.expires_in_days,
created_by_user_id=admin.id,
)
return {
"item": serialize_api_key(record),
"api_key": raw_key,
}
@router.post("/{key_id}/revoke")
async def revoke_existing_api_key(
key_id: int,
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
record = await revoke_api_key(db, key_id)
return {"item": serialize_api_key(record)}
@router.delete("/{key_id}")
async def delete_existing_api_key(
key_id: int,
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
await delete_api_key(db, key_id)
return {"status": "deleted", "id": key_id}
+229 -21
View File
@@ -1,16 +1,35 @@
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
import asyncio
from hashlib import sha256
import ipaddress
import time
from typing import Literal, Optional
from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel, ConfigDict
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import text
from app.core.access_gate import (
EARTH_SESSION_COOKIE,
check_sliding_rate_limit,
create_earth_session_token,
verify_desktop_handshake,
verify_turnstile_token,
verify_web_same_origin,
)
from app.core.config import settings
from app.core.enums import OtpPurpose, UserRole
from app.core.logging import get_logger
from app.core.security import (
_AsyncRedisClient,
create_access_token,
create_refresh_token,
get_current_user,
get_current_user_refresh,
get_password_hash,
revoke_token,
verify_password,
)
from app.db.session import get_db
@@ -34,6 +53,123 @@ from app.services.email import (
logger = get_logger(__name__)
router = APIRouter()
optional_bearer = HTTPBearer(auto_error=False)
_LOCAL_LOGIN_FAILURES: dict[str, tuple[int, float]] = {}
_LOCAL_LOGIN_FAILURES_MAX = 10_000
class LogoutRequest(BaseModel):
refresh_token: Optional[str] = None
_TRUSTED_PROXY_NETWORKS = (
ipaddress.ip_network("127.0.0.0/8"),
ipaddress.ip_network("10.0.0.0/8"),
ipaddress.ip_network("172.16.0.0/12"),
ipaddress.ip_network("192.168.0.0/16"),
ipaddress.ip_network("169.254.0.0/16"),
ipaddress.ip_network("100.64.0.0/10"),
ipaddress.ip_network("::1/128"),
ipaddress.ip_network("fc00::/7"),
ipaddress.ip_network("fe80::/10"),
)
def _is_trusted_proxy_peer(host: str) -> bool:
cleaned = host.strip()
if not cleaned:
return False
if cleaned in {"testclient", "localhost"}:
return True
try:
parsed = ipaddress.ip_address(cleaned)
except ValueError:
return False
if isinstance(parsed, ipaddress.IPv6Address) and parsed.ipv4_mapped is not None:
parsed = parsed.ipv4_mapped
return any(parsed in network for network in _TRUSTED_PROXY_NETWORKS)
def _client_ip(request: Request) -> str:
peer_host = request.client.host if (request.client and request.client.host) else ""
if _is_trusted_proxy_peer(peer_host):
real_ip = (request.headers.get("X-Real-IP") or "").strip()
if real_ip:
return real_ip
forwarded = request.headers.get("X-Forwarded-For") or ""
if forwarded:
parts = [part.strip() for part in forwarded.split(",") if part.strip()]
if parts:
return parts[-1]
if peer_host:
return peer_host
return "unknown"
def _login_rate_key(client_ip: str, username: str) -> str:
digest = sha256(f"{client_ip}:{username.strip().lower()}".encode("utf-8")).hexdigest()
return f"auth:login_fail:{digest}"
def _prune_local_login_failures(now: float) -> None:
expired = [key for key, (_cnt, expires_at) in _LOCAL_LOGIN_FAILURES.items() if expires_at <= now]
for key in expired:
_LOCAL_LOGIN_FAILURES.pop(key, None)
while len(_LOCAL_LOGIN_FAILURES) > _LOCAL_LOGIN_FAILURES_MAX:
_LOCAL_LOGIN_FAILURES.pop(next(iter(_LOCAL_LOGIN_FAILURES)), None)
async def check_login_rate_limit(client_ip: str, username: str) -> int:
max_attempts = int(settings.LOGIN_RATE_LIMIT_MAX_ATTEMPTS)
window_seconds = max(1, int(settings.LOGIN_RATE_LIMIT_WINDOW_SECONDS))
if max_attempts <= 0:
return 0
key = _login_rate_key(client_ip, username)
try:
client = _AsyncRedisClient.get_client()
raw = await asyncio.wait_for(client.get(key), timeout=1.5)
if raw is not None and int(raw) >= max_attempts:
ttl = await asyncio.wait_for(client.ttl(key), timeout=1.5)
return max(1, int(ttl) if isinstance(ttl, int) and ttl > 0 else window_seconds)
return 0
except Exception:
now = time.monotonic()
_prune_local_login_failures(now)
entry = _LOCAL_LOGIN_FAILURES.get(key)
if entry and entry[1] > now and entry[0] >= max_attempts:
return max(1, int(entry[1] - now))
return 0
async def record_login_failure(client_ip: str, username: str) -> None:
max_attempts = int(settings.LOGIN_RATE_LIMIT_MAX_ATTEMPTS)
window_seconds = max(1, int(settings.LOGIN_RATE_LIMIT_WINDOW_SECONDS))
if max_attempts <= 0:
return
key = _login_rate_key(client_ip, username)
try:
client = _AsyncRedisClient.get_client()
count = await asyncio.wait_for(client.incr(key), timeout=1.5)
if int(count) == 1:
await asyncio.wait_for(client.expire(key, window_seconds), timeout=1.5)
except Exception:
now = time.monotonic()
_prune_local_login_failures(now)
count, expires_at = _LOCAL_LOGIN_FAILURES.get(key, (0, now + window_seconds))
if expires_at <= now:
count = 0
expires_at = now + window_seconds
_LOCAL_LOGIN_FAILURES[key] = (count + 1, expires_at)
async def clear_login_failures(client_ip: str, username: str) -> None:
key = _login_rate_key(client_ip, username)
_LOCAL_LOGIN_FAILURES.pop(key, None)
try:
client = _AsyncRedisClient.get_client()
await asyncio.wait_for(client.delete(key), timeout=1.5)
except Exception:
pass
def _token_response(user: User) -> dict:
@@ -83,9 +219,23 @@ async def _load_user_by_email(db: AsyncSession, email: str) -> User | None:
@router.post("/login", response_model=Token)
async def login(
request: Request,
form_data: OAuth2PasswordRequestForm = Depends(),
db: AsyncSession = Depends(get_db),
):
client_ip = _client_ip(request)
retry_after = await check_login_rate_limit(client_ip, form_data.username)
if retry_after > 0:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
headers={"Retry-After": str(retry_after)},
detail={
"code": "RATE_LIMITED",
"message": "Too many failed login attempts",
"retry_after_seconds": retry_after,
},
)
result = await db.execute(
text(
"SELECT id, username, email, password_hash, role, is_active, gatekeeper_groups, email_verified "
@@ -95,6 +245,7 @@ async def login(
)
row = result.fetchone()
if row is None:
await record_login_failure(client_ip, form_data.username)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
@@ -111,11 +262,13 @@ async def login(
user.email_verified = bool(row[7])
if not verify_password(form_data.password, user.password_hash):
await record_login_failure(client_ip, form_data.username)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
)
if not user.is_active:
await record_login_failure(client_ip, form_data.username)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User is inactive",
@@ -126,34 +279,26 @@ async def login(
detail={"code": "EMAIL_NOT_VERIFIED", "email": user.email},
)
await clear_login_failures(client_ip, form_data.username)
return _token_response(user)
@router.post("/refresh", response_model=Token)
async def refresh_token(
current_user: User = Depends(get_current_user),
current_user: User = Depends(get_current_user_refresh),
):
access_token = create_access_token(data={"sub": current_user.id})
expires_in = None
if settings.ACCESS_TOKEN_EXPIRE_MINUTES > 0:
expires_in = settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60
return {
"access_token": access_token,
"token_type": "bearer",
"expires_in": expires_in,
"user": {
"id": current_user.id,
"username": current_user.username,
"role": current_user.role,
"gatekeeper_groups": current_user.gatekeeper_groups or [],
},
}
return _token_response(current_user)
@router.post("/logout")
async def logout():
async def logout(
credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer),
body: LogoutRequest | None = Body(default=None),
):
if credentials and credentials.credentials:
await revoke_token(credentials.credentials)
if body and body.refresh_token:
await revoke_token(body.refresh_token)
return {"message": "Successfully logged out"}
@@ -351,3 +496,66 @@ async def reset_password(payload: ResetPasswordRequest, db: AsyncSession = Depen
)
await db.commit()
return {"status": "ok"}
class EarthSessionRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
client_type: Literal["web", "desktop"] = "web"
turnstile_token: Optional[str] = None
def _is_https_request(request: Request) -> bool:
forwarded_proto = (request.headers.get("x-forwarded-proto") or "").split(",")[0].strip().lower()
return forwarded_proto == "https" or request.url.scheme == "https"
@router.post("/earth-session")
async def create_earth_session(
request: Request,
response: Response,
payload: EarthSessionRequest | None = Body(default=None),
):
"""Mint a short-lived Earth session credential for zero-login Web or Desktop Earth."""
body = payload or EarthSessionRequest()
client_ip = _client_ip(request)
if body.client_type == "desktop":
await check_sliding_rate_limit(
f"earth_session:desktop:{client_ip}",
limit=120,
window_seconds=3600,
detail="Too many desktop Earth session requests",
)
client_header = await verify_desktop_handshake(request)
token, ttl_seconds = create_earth_session_token("desktop", client_id=client_header)
return {
"token": token,
"expires_in": ttl_seconds,
"client_type": "desktop",
}
await check_sliding_rate_limit(
f"earth_session:web:{client_ip}",
limit=60,
window_seconds=3600,
detail="Too many web Earth session requests",
)
verify_web_same_origin(request)
await verify_turnstile_token(body.turnstile_token, client_ip)
token, ttl_seconds = create_earth_session_token("web", client_id=client_ip)
response.set_cookie(
key=EARTH_SESSION_COOKIE,
value=token,
max_age=ttl_seconds,
httponly=True,
samesite="strict",
secure=_is_https_request(request),
path="/",
)
return {
"expires_in": ttl_seconds,
"ws_token": token,
"client_type": "web",
"turnstile_required": bool(str(settings.TURNSTILE_SECRET_KEY or "").strip()),
}
+3 -2
View File
@@ -5,6 +5,7 @@ from fastapi.responses import FileResponse
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.concurrency import run_in_threadpool
from app.core.access_gate import require_earth_or_api_access
from app.core.enums import UserRole
from app.core.security import get_current_user
from app.db.session import get_db
@@ -57,7 +58,7 @@ async def upload_image(file: UploadFile = File(...), _actor: User = Depends(imag
return await run_in_threadpool(store_image, content, (file.filename or "Image")[:200])
@router.get("/files/{filename}")
@router.get("/files/{filename}", dependencies=[Depends(require_earth_or_api_access("earth:read", allow_query_api_key=True))])
async def image_file(filename: str):
path = uploaded_path(filename)
if not path.is_file():
@@ -83,7 +84,7 @@ async def targets(
return {"items": await search_targets(db, entity_type, scope, q.strip(), limit)}
@router.get("/resolve")
@router.get("/resolve", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def resolve(
response: Response,
entity_type: EntityType,
+317
View File
@@ -0,0 +1,317 @@
"""Client L1 Earth hot-update manifest and bundle hosting endpoints."""
from __future__ import annotations
import hashlib
import hmac
import io
import json
import os
import re
import tarfile
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from uuid import uuid4
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile, status
from fastapi.responses import FileResponse, JSONResponse
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings
from app.core.logging import get_logger
from app.core.security import get_current_user
from app.db.session import get_db
router = APIRouter()
logger = get_logger(__name__, service="api")
bearer_optional = HTTPBearer(auto_error=False)
DEFAULT_CLIENT_UPDATES_DIR = Path(__file__).resolve().parents[3] / "data" / "client-updates"
MAX_HOTFIX_BUNDLE_BYTES = 32 * 1024 * 1024
MAX_HOTFIX_FILES = 2000
MAX_HOTFIX_UNCOMPRESSED_BYTES = 64 * 1024 * 1024
SEMVER_PATTERN = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$")
SAFE_BUNDLE_FILENAME_PATTERN = re.compile(r"^planet-earth-bundle-[0-9A-Za-z._-]+\.tar\.gz$")
def get_client_updates_dir() -> Path:
configured = str(settings.CLIENT_UPDATES_DIR or "").strip()
if configured:
return Path(configured)
return DEFAULT_CLIENT_UPDATES_DIR
def _manifest_path(updates_dir: Path) -> Path:
return updates_dir / "manifest.json"
def _atomic_write_bytes(target: Path, content: bytes) -> None:
target.parent.mkdir(parents=True, exist_ok=True)
tmp_path = target.with_name(f".{target.name}.{os.getpid()}.{uuid4().hex}.tmp")
try:
tmp_path.write_bytes(content)
os.replace(tmp_path, target)
except Exception:
tmp_path.unlink(missing_ok=True)
raise
def _validate_hotfix_tar_gz(content: bytes) -> dict[str, int]:
if not content:
raise HTTPException(status_code=400, detail="Hotfix bundle archive is empty")
file_count = 0
total_size = 0
has_index_html = False
try:
with tarfile.open(fileobj=io.BytesIO(content), mode="r:gz") as archive:
for member in archive.getmembers():
raw_name = member.name or ""
if "\\" in raw_name or "\0" in raw_name:
raise HTTPException(status_code=400, detail=f"Unsafe archive entry path: {raw_name!r}")
if member.issym() or member.islnk() or member.isdev() or member.ischr() or member.isblk() or member.isfifo():
raise HTTPException(status_code=400, detail=f"Unsupported special archive entry: {raw_name!r}")
stripped = raw_name.lstrip("./") if raw_name.startswith("./") else raw_name
while stripped.startswith("./"):
stripped = stripped[2:]
stripped = stripped.rstrip("/")
if raw_name.startswith("/"):
raise HTTPException(status_code=400, detail=f"Absolute archive entry path is forbidden: {raw_name!r}")
if stripped in ("", "."):
if member.isdir():
continue
raise HTTPException(status_code=400, detail="Empty archive file path")
segments = stripped.split("/")
if any(seg in ("", ".", "..") for seg in segments):
raise HTTPException(status_code=400, detail=f"Path traversal forbidden in archive: {raw_name!r}")
if member.isdir():
continue
if not member.isreg():
raise HTTPException(status_code=400, detail=f"Unsupported archive entry type: {raw_name!r}")
file_count += 1
if file_count > MAX_HOTFIX_FILES:
raise HTTPException(status_code=400, detail="Archive exceeds maximum allowed file count")
total_size += max(0, int(member.size))
if total_size > MAX_HOTFIX_UNCOMPRESSED_BYTES:
raise HTTPException(status_code=400, detail="Archive exceeds maximum uncompressed size limit")
if stripped == "index.html":
has_index_html = True
except HTTPException:
raise
except (tarfile.TarError, EOFError, OSError, ValueError) as exc:
raise HTTPException(status_code=400, detail=f"Invalid gzip tar archive: {exc}") from exc
if not has_index_html:
raise HTTPException(status_code=400, detail="Hotfix bundle must include index.html at root")
return {"filesCount": file_count, "uncompressedBytes": total_size}
def _default_manifest() -> dict[str, Any]:
return {
"shell": {
"version": settings.VERSION,
"minRequired": settings.CLIENT_MIN_SHELL_VERSION,
"downloadUrl": settings.CLIENT_RELEASE_PAGE_URL,
"releaseNotes": "",
},
"bundle": None,
}
def _read_manifest(updates_dir: Path) -> dict[str, Any]:
manifest_file = _manifest_path(updates_dir)
if not manifest_file.is_file():
return _default_manifest()
try:
payload = json.loads(manifest_file.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
return _default_manifest()
return payload
except (OSError, json.JSONDecodeError):
return _default_manifest()
async def _require_update_publisher(
request: Request,
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_optional),
db: AsyncSession = Depends(get_db),
) -> str:
publish_token = request.headers.get("X-Client-Update-Token")
if publish_token is not None:
expected = str(settings.CLIENT_UPDATE_PUBLISH_TOKEN or "").strip()
if not expected or not hmac.compare_digest(publish_token.strip(), expected):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid client update publish token",
)
return "ci-token"
if credentials is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
)
user = await get_current_user(credentials=credentials, db=db)
if getattr(user, "role", None) != "admin":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Admin privileges required",
)
return f"admin:{user.username}"
def _validate_semver(value: str, field_name: str) -> str:
cleaned = str(value or "").strip().lstrip("vV")
if not SEMVER_PATTERN.match(cleaned):
raise HTTPException(
status_code=400,
detail=f"Invalid semantic version for {field_name}: {value!r}",
)
return cleaned
@router.get("/update-manifest")
async def get_client_update_manifest(
platform: str = "",
arch: str = "",
shell: str = "",
bundle: str = "",
):
updates_dir = get_client_updates_dir()
manifest = _read_manifest(updates_dir)
bundle_info = manifest.get("bundle")
if isinstance(bundle_info, dict):
filename = Path(str(bundle_info.get("url") or "")).name
if not SAFE_BUNDLE_FILENAME_PATTERN.match(filename) or not (updates_dir / filename).is_file():
manifest = {**manifest, "bundle": None}
logger.debug_event(
"Served client update manifest",
event="client_updates.manifest.read",
context={
"platform": platform or None,
"arch": arch or None,
"shell": shell or None,
"bundle": bundle or None,
"has_bundle": bool(manifest.get("bundle")),
},
)
return JSONResponse(content=manifest, headers={"Cache-Control": "no-store"})
@router.get("/updates/files/{filename}")
async def download_client_hotfix_bundle(filename: str):
if not SAFE_BUNDLE_FILENAME_PATTERN.match(filename):
raise HTTPException(status_code=400, detail="Invalid client hotfix bundle filename")
updates_dir = get_client_updates_dir().resolve()
target = (updates_dir / filename).resolve()
if target.parent != updates_dir or not target.is_file():
raise HTTPException(status_code=404, detail="Client hotfix bundle not found")
return FileResponse(
path=target,
media_type="application/gzip",
filename=filename,
headers={"Cache-Control": "public, max-age=31536000, immutable"},
)
@router.post("/updates/bundle")
async def publish_client_hotfix_bundle(
file: UploadFile = File(...),
version: str = Form(...),
min_shell_version: str = Form(""),
release_notes: str = Form(""),
shell_version: str = Form(""),
shell_min_required: str = Form(""),
shell_download_url: str = Form(""),
publisher: str = Depends(_require_update_publisher),
):
normalized_version = _validate_semver(version, "version")
normalized_min_shell = _validate_semver(
min_shell_version or settings.CLIENT_MIN_SHELL_VERSION or normalized_version,
"min_shell_version",
)
content = await file.read(MAX_HOTFIX_BUNDLE_BYTES + 1)
if len(content) > MAX_HOTFIX_BUNDLE_BYTES:
raise HTTPException(status_code=400, detail="Hotfix bundle exceeds 32 MiB limit")
archive_meta = _validate_hotfix_tar_gz(content)
sha256_hex = hashlib.sha256(content).hexdigest()
bundle_filename = f"planet-earth-bundle-{normalized_version}.tar.gz"
updates_dir = get_client_updates_dir()
_atomic_write_bytes(updates_dir / bundle_filename, content)
existing_manifest = _read_manifest(updates_dir)
existing_shell = existing_manifest.get("shell") if isinstance(existing_manifest.get("shell"), dict) else {}
resolved_shell_version = (
_validate_semver(shell_version, "shell_version")
if str(shell_version or "").strip()
else str(existing_shell.get("version") or settings.VERSION)
)
resolved_shell_min = (
_validate_semver(shell_min_required, "shell_min_required")
if str(shell_min_required or "").strip()
else str(existing_shell.get("minRequired") or settings.CLIENT_MIN_SHELL_VERSION)
)
resolved_shell_url = str(shell_download_url or "").strip() or str(
existing_shell.get("downloadUrl") or settings.CLIENT_RELEASE_PAGE_URL
)
if not resolved_shell_url.startswith(("https://", "http://")):
raise HTTPException(status_code=400, detail="shell_download_url must start with http:// or https://")
cleaned_notes = str(release_notes or "").strip()[:4000]
manifest: dict[str, Any] = {
"shell": {
"version": resolved_shell_version,
"minRequired": resolved_shell_min,
"downloadUrl": resolved_shell_url,
"releaseNotes": cleaned_notes or str(existing_shell.get("releaseNotes") or ""),
},
"bundle": {
"version": normalized_version,
"minShellVersion": normalized_min_shell,
"url": f"/api/v1/client/updates/files/{bundle_filename}",
"sha256": sha256_hex,
"size": len(content),
"releaseNotes": cleaned_notes,
"publishedAt": datetime.now(UTC).isoformat(),
**archive_meta,
},
}
_atomic_write_bytes(
_manifest_path(updates_dir),
(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n").encode("utf-8"),
)
logger.info_event(
"Published client L1 hotfix bundle",
event="client_updates.bundle_published",
context={
"publisher": publisher,
"version": normalized_version,
"min_shell_version": normalized_min_shell,
"bytes": len(content),
"sha256": sha256_hex,
"files_count": archive_meta["filesCount"],
},
)
return {"status": "published", "manifest": manifest}
+3 -2
View File
@@ -5,6 +5,7 @@ from typing import Literal
from app.core.compute_types import COMPUTE_SITE_TYPES, compute_record_filter, compute_site_type_expression
from app.api.v1.visualization import convert_compute_centers_to_geojson
from app.core.access_gate import require_earth_or_api_access
from app.core.earth_geography_policy import display_country
from app.core.enums import UserRole
from app.core.logging import get_logger
@@ -64,7 +65,7 @@ def selected_countries(countries: str) -> list[str]:
return codes
@router.get("/series")
@router.get("/series", dependencies=[Depends(require_earth_or_api_access("data_products:read"))])
async def get_series(
response: Response,
countries: str = "CN,US",
@@ -182,7 +183,7 @@ async def sample_query(db: AsyncSession, countries: list[str], year: int | None)
return query
@router.get("/facilities")
@router.get("/facilities", dependencies=[Depends(require_earth_or_api_access("data_products:read"))])
async def get_facilities(
countries: str = "CN,US",
year: int | None = Query(None, ge=2000, le=2100),
+2 -1
View File
@@ -4,10 +4,11 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.visualization import get_visualization_geo_summary
from app.core.access_gate import require_earth_or_api_access
from app.core.time import to_iso8601_utc
from app.db.session import get_db
router = APIRouter()
router = APIRouter(dependencies=[Depends(require_earth_or_api_access("data_products:read"))])
PRODUCT_DEFINITIONS: dict[str, dict] = {
"vessels": {
+36 -13
View File
@@ -690,24 +690,47 @@ async def delete_config(
deleted_records = {
"collected_data": 0,
"ais_raw_observations": 0,
"vessel_current_state": 0,
"ais_source_health": 0,
}
if delete_source_data:
collected_result = await db.execute(
delete(CollectedData).where(CollectedData.source == config.name)
from app.models.vessel import VesselCurrentState
sibling_result = await db.execute(
select(DataSourceConfig.id)
.where(DataSourceConfig.name == config.name, DataSourceConfig.id != config_id)
.limit(1)
)
raw_result = await db.execute(
delete(AISRawObservation).where(AISRawObservation.source == config.name)
)
health_result = await db.execute(
delete(AISSourceHealth).where(AISSourceHealth.source == config.name)
)
deleted_records = {
"collected_data": collected_result.rowcount or 0,
"ais_raw_observations": raw_result.rowcount or 0,
"ais_source_health": health_result.rowcount or 0,
}
has_same_name_sibling = sibling_result.scalar_one_or_none() is not None
if has_same_name_sibling:
collected_result = await db.execute(
delete(CollectedData).where(
CollectedData.source == config.name,
CollectedData.entity_key.like(f"datasource_config:{config_id}:%"),
)
)
deleted_records["collected_data"] = collected_result.rowcount or 0
else:
collected_result = await db.execute(
delete(CollectedData).where(CollectedData.source == config.name)
)
raw_result = await db.execute(
delete(AISRawObservation).where(AISRawObservation.source == config.name)
)
current_vessel_result = await db.execute(
delete(VesselCurrentState).where(VesselCurrentState.source == config.name)
)
health_result = await db.execute(
delete(AISSourceHealth).where(AISSourceHealth.source == config.name)
)
deleted_records = {
"collected_data": collected_result.rowcount or 0,
"ais_raw_observations": raw_result.rowcount or 0,
"vessel_current_state": current_vessel_result.rowcount or 0,
"ais_source_health": health_result.rowcount or 0,
}
if delete_mappings or delete_source_data:
mapping_result = await db.execute(
+172 -19
View File
@@ -7,7 +7,7 @@ from sqlalchemy import func, or_, select, text
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.core.enums import JobStatus, SnapshotStatus
from app.core.enums import JobStatus, SnapshotStatus, UserRole
from app.core.time import to_iso8601_utc
from app.core.security import get_current_user
from app.core.data_sources import get_data_sources_config
@@ -19,7 +19,7 @@ from app.models.datasource import DataSource
from app.models.datasource_config import DataSourceConfig
from app.models.task import CollectionTask
from app.models.user import User
from app.models.vessel import AISRawObservation
from app.models.vessel import AISRawObservation, VesselCurrentState
from app.services.scheduler import (
sync_datasource_job,
)
@@ -39,6 +39,7 @@ from app.services.business_logs import emit_business_log
router = APIRouter()
logger = get_logger(__name__, service="api")
STALE_RUNNING_TASK_TIMEOUT_MINUTES = 90
DATASOURCE_ADMIN_ROLES = {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}
PRODUCT_SOURCE_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
@@ -65,6 +66,20 @@ class DatasourceBatchTriggerRequest(BaseModel):
q: Optional[str] = None
class DatasourceBatchStatusRequest(BaseModel):
source_ids: list[int] = Field(min_length=1, max_length=500)
is_active: bool
def _require_datasource_admin(current_user: User) -> None:
role = getattr(current_user.role, "value", current_user.role)
if role not in DATASOURCE_ADMIN_ROLES:
raise HTTPException(
status_code=403,
detail="Only administrators can change datasource scheduling",
)
def format_frequency_label(minutes: int) -> str:
if minutes % 1440 == 0:
return f"{minutes // 1440}d"
@@ -228,6 +243,16 @@ async def _load_collected_record_counts(
if source in vessel_sources:
counts[source] = max(counts.get(source, 0), int(round(total_rows * freq)))
missing_vessel_sources = [source for source in vessel_sources if counts.get(source, 0) == 0]
if missing_vessel_sources:
current_result = await db.execute(
select(VesselCurrentState.source, func.count(VesselCurrentState.mmsi))
.where(VesselCurrentState.source.in_(missing_vessel_sources))
.group_by(VesselCurrentState.source)
)
for source, count in current_result.all():
counts[source] = max(counts.get(source, 0), int(count or 0))
return counts
@@ -343,6 +368,78 @@ def serialize_datasource_row(
return row
async def _serialize_datasource_rows(
db: AsyncSession,
datasources: list[DataSource],
) -> list[dict]:
if not datasources:
return []
config = get_data_sources_config()
running_tasks, latest_tasks, endpoint_overrides = await _load_datasource_list_context(
db,
datasources,
include_endpoint=False,
)
record_counts = await _load_collected_record_counts(
db, [datasource.source for datasource in datasources]
)
return [
serialize_datasource_row(
datasource,
running_tasks=running_tasks,
latest_tasks=latest_tasks,
record_counts=record_counts,
endpoint_overrides=endpoint_overrides,
config=config,
include_endpoint=False,
)
for datasource in datasources
]
async def _load_datasource_status_counts(db: AsyncSession) -> dict[str, int]:
result = await db.execute(
select(DataSource.is_active, func.count(DataSource.id)).group_by(DataSource.is_active)
)
active = 0
inactive = 0
for is_active, count in result.all():
if is_active:
active += int(count or 0)
else:
inactive += int(count or 0)
return {"all": active + inactive, "active": active, "inactive": inactive}
async def _apply_datasource_activation(
db: AsyncSession,
datasources: list[DataSource],
is_active: bool,
) -> tuple[list[DataSource], list[int]]:
"""Persist scheduling state, then reconcile scheduler jobs for changed rows only."""
changed = [datasource for datasource in datasources if bool(datasource.is_active) != is_active]
for datasource in changed:
datasource.is_active = is_active
if changed:
await db.commit()
sync_failed: list[int] = []
for datasource in changed:
try:
await sync_datasource_job(datasource.id)
except Exception as exc:
sync_failed.append(datasource.id)
logger.warning_event(
"Datasource scheduler sync failed",
event="collector.schedule.sync_failed",
context={
"datasource_id": datasource.id,
"source": datasource.source,
"error_type": type(exc).__name__,
},
)
return changed, sync_failed
def _apply_datasource_query_filters(
query,
*,
@@ -807,7 +904,55 @@ async def list_datasources(
)
)
return {"total": len(collector_list), "data": collector_list}
return {
"total": len(collector_list),
"data": collector_list,
"counts": await _load_datasource_status_counts(db),
}
@router.post("/batch-status")
async def update_datasource_batch_status(
payload: DatasourceBatchStatusRequest,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
_require_datasource_admin(current_user)
requested_ids = list(dict.fromkeys(payload.source_ids))
result = await db.execute(
select(DataSource)
.where(DataSource.id.in_(requested_ids))
.order_by(DataSource.module, DataSource.id)
)
datasources = list(result.scalars().all())
found_ids = {datasource.id for datasource in datasources}
changed, sync_failed = await _apply_datasource_activation(db, datasources, payload.is_active)
changed_ids = {datasource.id for datasource in changed}
await emit_business_log(
logger,
event="collector.schedule.batch_status",
message="Datasource scheduling batch update completed",
category="collector",
service="api",
module=__name__,
user_id=current_user.id,
context={
"is_active": payload.is_active,
"requested_count": len(requested_ids),
"updated_count": len(changed),
"sync_failed_count": len(sync_failed),
},
)
return {
"is_active": payload.is_active,
"updated": await _serialize_datasource_rows(db, changed),
"unchanged": [
datasource.id for datasource in datasources if datasource.id not in changed_ids
],
"not_found": [source_id for source_id in requested_ids if source_id not in found_ids],
"sync_failed": sync_failed,
"counts": await _load_datasource_status_counts(db),
}
@router.post("/trigger-all")
@@ -977,20 +1122,35 @@ async def get_datasource_row(
}
async def _set_single_datasource_active(
db: AsyncSession,
source_id: str,
current_user: User,
is_active: bool,
) -> dict:
_require_datasource_admin(current_user)
datasource = await get_datasource_record(db, source_id)
if not datasource:
raise HTTPException(status_code=404, detail="Data source not found")
_changed, sync_failed = await _apply_datasource_activation(db, [datasource], is_active)
rows = await _serialize_datasource_rows(db, [datasource])
return {
"status": "enabled" if is_active else "disabled",
"source_id": datasource.id,
"data": rows[0] if rows else None,
"sync_failed": bool(sync_failed),
"counts": await _load_datasource_status_counts(db),
}
@router.post("/{source_id}/enable")
async def enable_datasource(
source_id: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
datasource = await get_datasource_record(db, source_id)
if not datasource:
raise HTTPException(status_code=404, detail="Data source not found")
datasource.is_active = True
await db.commit()
await sync_datasource_job(datasource.id)
return {"status": "enabled", "source_id": datasource.id}
return await _set_single_datasource_active(db, source_id, current_user, True)
@router.post("/{source_id}/disable")
@@ -999,14 +1159,7 @@ async def disable_datasource(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
datasource = await get_datasource_record(db, source_id)
if not datasource:
raise HTTPException(status_code=404, detail="Data source not found")
datasource.is_active = False
await db.commit()
await sync_datasource_job(datasource.id)
return {"status": "disabled", "source_id": datasource.id}
return await _set_single_datasource_active(db, source_id, current_user, False)
@router.get("/{source_id}/stats")
+14 -8
View File
@@ -12,9 +12,15 @@ from pydantic import BaseModel, Field
from sqlalchemy import delete, func, select, text
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_earth_or_api_access
from app.core.config import settings as app_settings
from app.core.logging import get_logger
from app.core.security import decode_token, get_current_user, redis_client
from app.core.security import (
decode_token,
get_current_user,
is_token_blacklisted,
redis_client,
)
from app.core.websocket.broadcaster import broadcaster
from app.db.session import get_db
from app.models.collected_data import CollectedData
@@ -251,7 +257,7 @@ async def _get_optional_current_user(
if credentials is None:
return None
token = credentials.credentials
if redis_client.sismember("blacklisted_tokens", token):
if await is_token_blacklisted(token, legacy_sync_client=redis_client):
return None
payload = decode_token(token)
if payload is None or payload.get("type") != "access":
@@ -291,7 +297,7 @@ async def _broadcast_earth_config_update(layer: str) -> None:
logger.warning("Failed to broadcast %s update: %s", layer, exc)
@router.get("/brand")
@router.get("/brand", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_brand(db: AsyncSession = Depends(get_db)):
return await _get_earth_brand_payload(db)
@@ -361,7 +367,7 @@ async def upload_earth_brand_asset(
return {"url": asset_url, "filename": safe_name, "content_type": file.content_type}
@router.get("/about")
@router.get("/about", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_about(db: AsyncSession = Depends(get_db)):
return await _get_earth_about_payload(db)
@@ -396,7 +402,7 @@ async def reset_earth_about(
return {"status": "reset", "about": _normalize_earth_about_payload(None), "is_default": True}
@router.get("/news-sources")
@router.get("/news-sources", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_news_sources(db: AsyncSession = Depends(get_db)):
return await get_earth_news_sources_payload(db)
@@ -601,7 +607,7 @@ async def reprocess_earth_news_item_admin(
return {"status": "queued" if queued else "not_queued", "queued": queued, "id": item_id}
@router.get("/oobe-status")
@router.get("/oobe-status", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_oobe_status(
current_user: User | None = Depends(_get_optional_current_user),
db: AsyncSession = Depends(get_db),
@@ -666,7 +672,7 @@ async def get_earth_oobe_status(
}
@router.get("/boundaries/status")
@router.get("/boundaries/status", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_boundary_status():
return get_boundary_status()
@@ -713,6 +719,6 @@ async def build_earth_boundary_assets(
) from exc
@router.get("/boundaries/build/status")
@router.get("/boundaries/build/status", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_boundary_build_status():
return get_boundary_build_status()
+4 -3
View File
@@ -9,6 +9,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from pydantic import BaseModel, Field, field_validator
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_earth_or_api_access
from app.core.security import get_current_user
from app.db.session import get_db
from app.models.earth_interactable import EarthInteractable
@@ -67,7 +68,7 @@ class InteractableUpdate(BaseModel):
properties: dict[str, Any] | None = None
@router.get("")
@router.get("", dependencies=[Depends(require_earth_or_api_access("interactables:read"))])
async def get_interactables(
response: Response,
layer: str | None = Query(default=None),
@@ -79,7 +80,7 @@ async def get_interactables(
return {"items": [serialize_interactable(item) for item in items]}
@router.get("/geojson")
@router.get("/geojson", dependencies=[Depends(require_earth_or_api_access("interactables:read"))])
async def get_interactables_geojson(
response: Response,
layer: str | None = Query(default=None),
@@ -135,7 +136,7 @@ async def create_interactable(
return {"item": serialize_interactable(record)}
@router.get("/{interactable_id}")
@router.get("/{interactable_id}", dependencies=[Depends(require_earth_or_api_access("interactables:read"))])
async def get_interactable(interactable_id: str, db: AsyncSession = Depends(get_db)):
record = await db.get(EarthInteractable, interactable_id)
if record is None or record.is_deleted:
+2 -1
View File
@@ -13,9 +13,10 @@ from app.api.v1.visualization import (
get_satellites_geojson,
)
from app.api.v1.vessels import build_vessel_snapshot_response
from app.core.access_gate import require_earth_or_api_access
from app.db.session import get_db
router = APIRouter()
router = APIRouter(dependencies=[Depends(require_earth_or_api_access("layers:read"))])
DEFAULT_LAYER_LIMIT = 1000
MAX_LAYER_LIMIT = 5000
+32 -4
View File
@@ -1,8 +1,13 @@
from fastapi import APIRouter, Depends, HTTPException, Query, status
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from uuid import UUID
from app.core.access_gate import (
EarthAccessContext,
check_sliding_rate_limit,
require_earth_or_api_access,
)
from app.db.session import get_db
from app.services.earth_news import (
ALLOWED_NEWS_CATEGORY_KEYS,
@@ -70,7 +75,24 @@ def _parse_locale(raw: str | None) -> str:
return requested
@router.post("/refresh", status_code=status.HTTP_202_ACCEPTED)
async def _require_news_refresh_cooldown(
request: Request,
access: EarthAccessContext = Depends(require_earth_or_api_access("news:read")),
) -> None:
peer = request.client.host if (request.client and request.client.host) else "unknown"
await check_sliding_rate_limit(
f"news_refresh:{access.actor_key}:{peer}",
limit=3,
window_seconds=60,
detail="News refresh cooldown active; please retry shortly.",
)
@router.post(
"/refresh",
status_code=status.HTTP_202_ACCEPTED,
dependencies=[Depends(_require_news_refresh_cooldown)],
)
async def request_earth_news_refresh(payload: EarthNewsRefreshRequest):
requested_region = payload.region.strip().lower() if payload.region else None
if requested_region and requested_region not in REGION_ANCHORS:
@@ -97,7 +119,10 @@ async def request_earth_news_refresh(payload: EarthNewsRefreshRequest):
) from exc
@router.get("/refresh/{refresh_id}")
@router.get(
"/refresh/{refresh_id}",
dependencies=[Depends(require_earth_or_api_access("news:read"))],
)
async def get_earth_news_refresh(refresh_id: UUID):
from app.services.earth_news_refresh import get_earth_news_refresh_status
@@ -124,7 +149,10 @@ async def get_earth_news_refresh(refresh_id: UUID):
}
@router.get("/earth-feed")
@router.get(
"/earth-feed",
dependencies=[Depends(require_earth_or_api_access("news:read"))],
)
async def get_earth_feed(
lat: float | None = Query(None, description="Current Earth view center latitude"),
lon: float | None = Query(None, description="Current Earth view center longitude"),
+40 -8
View File
@@ -15,7 +15,8 @@ from app.db.session import get_db
from app.models.datasource import DataSource
from app.models.datasource_config import DataSourceConfig
from app.models.user import User
from app.models.vessel import AISRawObservation, AISSourceHealth
from app.models.vessel import AISRawObservation, AISSourceHealth, VesselCurrentState
from app.services.storage_policy import resolve_collector_storage_policy
from app.services.custom_datasource_runtime import (
get_custom_stream_status,
start_custom_stream,
@@ -77,14 +78,45 @@ async def _load_realtime_stats(db: AsyncSession, source: str) -> dict[str, Any]:
.where(AISRawObservation.source == source)
)
row = result.mappings().one()
mode, _ = await resolve_collector_storage_policy(db, source)
total_obs = int(row["total_observations"] or 0)
if total_obs > 0:
return {
"total_observations": total_obs,
"observations_24h": int(row["observations_24h"] or 0),
"observations_1h": int(row["observations_1h"] or 0),
"unique_mmsi_total": int(row["unique_mmsi_total"] or 0),
"unique_mmsi_24h": int(row["unique_mmsi_24h"] or 0),
"latest_observed_at": to_iso8601_utc(row["latest_observed_at"]),
"latest_collected_at": to_iso8601_utc(row["latest_collected_at"]),
"storage_mode": mode,
}
current_result = await db.execute(
select(
func.count(VesselCurrentState.mmsi).label("total_vessels"),
func.count(VesselCurrentState.mmsi)
.filter(VesselCurrentState.observed_at >= observed_24h)
.label("vessels_24h"),
func.count(VesselCurrentState.mmsi)
.filter(VesselCurrentState.observed_at >= observed_1h)
.label("vessels_1h"),
func.max(VesselCurrentState.observed_at).label("latest_observed_at"),
func.max(VesselCurrentState.updated_at).label("latest_collected_at"),
).where(VesselCurrentState.source == source)
)
current_row = current_result.mappings().one()
total_vessels = int(current_row["total_vessels"] or 0)
vessels_24h = int(current_row["vessels_24h"] or 0)
return {
"total_observations": int(row["total_observations"] or 0),
"observations_24h": int(row["observations_24h"] or 0),
"observations_1h": int(row["observations_1h"] or 0),
"unique_mmsi_total": int(row["unique_mmsi_total"] or 0),
"unique_mmsi_24h": int(row["unique_mmsi_24h"] or 0),
"latest_observed_at": to_iso8601_utc(row["latest_observed_at"]),
"latest_collected_at": to_iso8601_utc(row["latest_collected_at"]),
"total_observations": total_vessels,
"observations_24h": vessels_24h,
"observations_1h": int(current_row["vessels_1h"] or 0),
"unique_mmsi_total": total_vessels,
"unique_mmsi_24h": vessels_24h,
"latest_observed_at": to_iso8601_utc(current_row["latest_observed_at"]),
"latest_collected_at": to_iso8601_utc(current_row["latest_collected_at"]),
"storage_mode": mode,
}
+360 -26
View File
@@ -2,7 +2,7 @@ from copy import deepcopy
from datetime import UTC, datetime
import os
from pathlib import Path
from typing import Optional
from typing import Literal, Optional
from urllib.parse import urlsplit
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
@@ -12,6 +12,7 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.core.secret_crypto import decrypt_setting_payload, encrypt_setting_payload
from app.core.enums import ProviderApi, TVSourceType, UserRole
from app.core.security import get_current_user
from app.core.time import to_iso8601_utc
@@ -65,11 +66,31 @@ from app.services.llm_provider_catalog import (
list_fallback_llm_provider_presets,
refresh_llm_provider_preset,
)
from app.services.llm_model_catalog import catalog_error_message, fetch_model_catalog
from app.services.llm_model_catalog import (
LLMProviderCatalogConfigError,
can_refresh_catalog_without_api_key,
catalog_error_message,
catalog_requires_api_key,
fetch_model_catalog,
)
from app.services.scheduler import sync_datasource_job
from app.services.tv_streams import DEFAULT_TV_SETTINGS, get_tv_settings_payload, normalize_tv_settings
from app.services.persistent_logs import record_audit_log
from app.services.business_logs import emit_business_log, exception_context
from app.services.storage_policy import (
ANNUAL_ELIGIBLE_SOURCES,
HIGH_VOLUME_SOURCES,
GlobalSnapshotAction,
SnapshotMode,
StoragePolicyLockedError,
apply_global_snapshot_action,
get_storage_policy,
mutate_storage_policy,
normalize_storage_policy,
resolve_snapshot_mode,
set_source_snapshot_mode,
summarize_storage_policy,
)
router = APIRouter()
logger = get_logger(__name__, service="api")
@@ -78,6 +99,14 @@ AI_CONNECTION_TEST_PROMPT_KEY = "ai.connection_test"
SECRET_REVEAL_ROLES = {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}
LLM_PROVIDER_PRESET_CATEGORY_PREFIX = "llm_provider_preset:"
def _require_admin(current_user: User, detail: str) -> None:
if current_user.role not in SECRET_REVEAL_ROLES:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=detail,
)
DEFAULT_SETTINGS = {
"system": {
"system_name": "智能星球",
@@ -231,6 +260,19 @@ class CollectorSettingsUpdate(BaseModel):
is_active: bool
priority: str = Field(default="P1")
frequency_minutes: int = Field(default=60, ge=1, le=10080)
snapshot_mode: Optional[SnapshotMode] = None
class StoragePolicyUpdate(BaseModel):
action: Optional[GlobalSnapshotAction] = None
global_single_lock: Optional[bool] = None
default_mode: Optional[SnapshotMode] = None
overrides: Optional[dict[str, SnapshotMode]] = None
source_mode: Optional[dict[str, SnapshotMode]] = None
history_retention_days: Optional[int] = Field(default=None, ge=1, le=3650)
bgp_observation_retention_days: Optional[int] = Field(default=None, ge=1, le=365)
bgp_single_batch_max_rows: Optional[int] = Field(default=None, ge=50, le=5000)
auto_prune_enabled: Optional[bool] = None
class TVStreamSourceUpdate(BaseModel):
@@ -355,12 +397,27 @@ def merge_with_defaults(category: str, payload: Optional[dict]) -> dict:
defaults = DEFAULT_SETTINGS[category]
merged = deepcopy(defaults)
if payload:
merged.update(payload)
merged.update(decrypt_setting_payload(category, payload))
return merged
async def get_setting_record(db: AsyncSession, category: str) -> Optional[SystemSetting]:
result = await db.execute(select(SystemSetting).where(SystemSetting.category == category))
async def get_setting_record(
db: AsyncSession,
category: str,
*,
for_update: bool = False,
) -> Optional[SystemSetting]:
stmt = select(SystemSetting).where(SystemSetting.category == category)
if hasattr(stmt, "execution_options"):
stmt = stmt.execution_options(populate_existing=True)
if for_update and hasattr(stmt, "with_for_update") and callable(getattr(db, "get_bind", None)):
try:
bind = db.get_bind()
if getattr(getattr(bind, "dialect", None), "name", "") == "postgresql":
stmt = stmt.with_for_update()
except Exception:
pass
result = await db.execute(stmt)
return result.scalar_one_or_none()
@@ -389,17 +446,27 @@ async def get_setting_payload(db: AsyncSession, category: str) -> dict:
return merge_with_defaults(category, record.payload if record else None)
async def save_setting_payload(db: AsyncSession, category: str, payload: dict) -> dict:
async def save_setting_payload(
db: AsyncSession,
category: str,
payload: dict,
*,
commit: bool = True,
for_update: bool = False,
) -> dict:
merged = merge_with_defaults(category, payload)
record = await get_setting_record(db, category)
persisted_payload = encrypt_setting_payload(category, payload)
record = await get_setting_record(db, category, for_update=for_update)
if record is None:
record = SystemSetting(category=category, payload=payload)
record = SystemSetting(category=category, payload=persisted_payload)
db.add(record)
else:
record.payload = payload
record.payload = persisted_payload
await db.commit()
await db.refresh(record)
if commit:
await db.commit()
if hasattr(db, "refresh"):
await db.refresh(record)
return merged
@@ -779,7 +846,7 @@ async def _check_ai_provider_lightweight(llm_config: dict, timeout_seconds: int)
}
if not base_url or not model:
return {**result, "message": "当前 provider/base_url/model 未完整配置。"}
if provider_api != ProviderApi.OLLAMA_GENERATE.value and not api_key:
if provider != "ollama" and provider_api != ProviderApi.OLLAMA_GENERATE.value and not api_key:
return {**result, "message": "当前 provider 未配置 API Key。"}
try:
catalog = await fetch_model_catalog(
@@ -1223,8 +1290,14 @@ async def get_ais_source_health_by_source(db: AsyncSession) -> dict[str, dict]:
return {item.source: item.to_dict() for item in result.scalars().all()}
def serialize_collector(datasource: DataSource, ais_health_by_source: dict[str, dict] | None = None) -> dict:
def serialize_collector(
datasource: DataSource,
ais_health_by_source: dict[str, dict] | None = None,
storage_policy: dict | None = None,
) -> dict:
defaults = DEFAULT_DATASOURCES.get(datasource.source, {})
effective_mode = resolve_snapshot_mode(storage_policy, datasource.source)
overrides = (storage_policy or {}).get("overrides") or {}
return {
"id": datasource.id,
"name": datasource.name,
@@ -1243,6 +1316,11 @@ def serialize_collector(datasource: DataSource, ais_health_by_source: dict[str,
"credential_provider": defaults.get("credential_provider"),
"credential_status": defaults.get("credential_status", "none"),
"ais_health": (ais_health_by_source or {}).get(datasource.source),
"snapshot_mode": effective_mode,
"snapshot_overridden": datasource.source in overrides,
"snapshot_locked": bool((storage_policy or {}).get("global_single_lock", False)),
"supports_annual": datasource.source in ANNUAL_ELIGIBLE_SOURCES,
"high_volume_warning": HIGH_VOLUME_SOURCES.get(datasource.source),
}
@@ -1260,10 +1338,131 @@ async def update_system_settings(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
payload = await save_setting_payload(db, "system", settings.model_dump())
_require_admin(current_user, "Only administrators can change system settings")
raw_system = settings.model_dump()
# Canonical lock order: advisory lock -> collection_storage -> system, committed atomically.
await mutate_storage_policy(
db,
lambda current_policy: {
**current_policy,
"history_retention_days": raw_system["data_retention_days"],
},
sync_system_retention=False,
commit=False,
)
payload = await save_setting_payload(
db,
"system",
raw_system,
commit=True,
for_update=True,
)
return {"status": "updated", "system": payload}
async def _load_known_collector_sources(db: AsyncSession) -> list[str]:
result = await db.execute(select(DataSource.source))
return [str(source) for source in result.scalars().all() if source]
@router.get("/storage-policy")
async def get_storage_policy_settings(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
policy = await get_storage_policy(db)
sources = await _load_known_collector_sources(db)
return {"storage_policy": summarize_storage_policy(policy, sources)}
@router.put("/storage-policy")
async def update_storage_policy_settings(
update: StoragePolicyUpdate,
request: Request,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
_require_admin(current_user, "Only administrators can change storage policy settings")
def _apply_policy_update(current_policy: dict) -> dict:
next_policy = dict(current_policy)
if update.action is not None:
next_policy = apply_global_snapshot_action(next_policy, update.action)
if update.global_single_lock is not None:
next_policy = normalize_storage_policy(
{**next_policy, "global_single_lock": update.global_single_lock}
)
if next_policy.get("global_single_lock"):
requests_non_single_default = (
update.default_mode is not None and update.default_mode != "single"
)
requests_non_single_override = any(
mode != "single" for mode in (update.overrides or {}).values()
)
requests_non_single_source = any(
mode != "single" for mode in (update.source_mode or {}).values()
)
if (
requests_non_single_default
or requests_non_single_override
or requests_non_single_source
):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="全局「全部单份」已开启,禁止单独开启历史或年末快照;请先切换为默认推荐或关闭全局单份锁定。",
)
if update.default_mode is not None:
next_policy = normalize_storage_policy({**next_policy, "default_mode": update.default_mode})
if update.overrides is not None:
next_policy = normalize_storage_policy({**next_policy, "overrides": update.overrides})
if update.source_mode is not None:
try:
for source, mode in update.source_mode.items():
next_policy = set_source_snapshot_mode(next_policy, source, mode)
except StoragePolicyLockedError as exc:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="全局「全部单份」已开启,禁止单独开启历史或年末快照;请先切换为默认推荐或关闭全局单份锁定。",
) from exc
patch: dict = {}
if update.history_retention_days is not None:
patch["history_retention_days"] = update.history_retention_days
if update.bgp_observation_retention_days is not None:
patch["bgp_observation_retention_days"] = update.bgp_observation_retention_days
if update.bgp_single_batch_max_rows is not None:
patch["bgp_single_batch_max_rows"] = update.bgp_single_batch_max_rows
if update.auto_prune_enabled is not None:
patch["auto_prune_enabled"] = update.auto_prune_enabled
if patch:
next_policy = normalize_storage_policy({**next_policy, **patch})
return next_policy
saved = await mutate_storage_policy(db, _apply_policy_update, sync_system_retention=True)
sources = await _load_known_collector_sources(db)
summarized = summarize_storage_policy(saved, sources)
await record_audit_log(
action="settings.storage_policy.update",
actor_id=getattr(current_user, "id", None),
actor_name=_user_display_name(current_user),
target_type="system_setting",
target_id="collection_storage",
result="success",
ip=_request_client_ip(request),
details={
"default_mode": summarized["default_mode"],
"global_single_lock": summarized["global_single_lock"],
"overrides": summarized["overrides"],
"history_retention_days": summarized["history_retention_days"],
"auto_prune_enabled": summarized["auto_prune_enabled"],
"master_state": summarized["master_state"],
},
)
return {"status": "updated", "storage_policy": summarized}
@router.get("/notifications")
async def get_notification_settings(
current_user: User = Depends(get_current_user),
@@ -1278,6 +1477,7 @@ async def update_notification_settings(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
_require_admin(current_user, "Only administrators can change notification settings")
payload = await save_setting_payload(db, "notifications", settings.model_dump())
return {"status": "updated", "notifications": payload}
@@ -1296,6 +1496,7 @@ async def update_security_settings(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
_require_admin(current_user, "Only administrators can change security settings")
payload = await save_setting_payload(db, "security", settings.model_dump())
return {"status": "updated", "security": payload}
@@ -1405,6 +1606,7 @@ async def update_tv_settings(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
_require_admin(current_user, "Only administrators can change TV settings")
payload = normalize_tv_settings(settings.model_dump())
saved = await save_setting_payload(db, "tv", payload)
return {"status": "updated", "tv": normalize_tv_settings(saved)}
@@ -1949,6 +2151,74 @@ async def get_ai_provider_presets(
}
async def refresh_public_llm_provider_presets(db: AsyncSession) -> dict:
current_payload = await get_setting_payload(db, "external_integrations")
ai_payload = _normalize_ai_provider_payload(current_payload.get("ai_provider") or {})
results: list[dict] = []
for preset in list_fallback_llm_provider_presets():
provider_id = preset["provider"]
provider_config = ai_payload["providers"].get(provider_id) or _provider_defaults(provider_id)
base_url = str(provider_config.get("base_url") or preset["base_url"] or "")
provider_api = str(provider_config.get("provider_api") or preset["provider_api"] or "")
if not can_refresh_catalog_without_api_key(provider_id, base_url, provider_api):
continue
try:
refreshed = await refresh_llm_provider_preset(
provider_id,
api_key="",
base_url=base_url,
provider_api=provider_api,
anthropic_version=provider_config.get("anthropic_version") or "2023-06-01",
)
except Exception as exc:
logger.warning(
"LLM provider catalog refresh failed",
extra={
"event": "settings.ai_provider.catalog.failed",
"context": {
"provider": provider_id,
"error_type": type(exc).__name__,
},
},
)
results.append(
{
"provider": provider_id,
"status": "failed",
"error": f"{catalog_error_message(exc)} 已保留上次模型列表。",
}
)
continue
refreshed["refreshed_at"] = to_iso8601_utc(datetime.now(UTC))
await save_setting_payload(
db, f"{LLM_PROVIDER_PRESET_CATEGORY_PREFIX}{provider_id}", refreshed
)
results.append(
{
"provider": provider_id,
"status": "refreshed",
"models_count": len(refreshed["models"]),
"refreshed_at": refreshed["refreshed_at"],
"source": refreshed["source"],
}
)
return {
"data": results,
"refreshed": [item["provider"] for item in results if item["status"] == "refreshed"],
"failed": [item["provider"] for item in results if item["status"] == "failed"],
}
@router.post("/integrations/ai-provider/presets/refresh-public")
async def refresh_public_ai_provider_presets(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
_require_admin(current_user, "Only administrators can refresh AI provider presets")
return await refresh_public_llm_provider_presets(db)
@router.post("/integrations/ai-provider/presets/{provider}/refresh")
async def refresh_ai_provider_preset(
provider: str,
@@ -1956,9 +2226,10 @@ async def refresh_ai_provider_preset(
db: AsyncSession = Depends(get_db),
payload: AIProviderIntegrationUpdate | None = None,
):
_require_admin(current_user, "Only administrators can refresh AI provider presets")
try:
provider_id = _normalize_provider_id(provider)
get_fallback_llm_provider_preset(provider_id)
fallback = get_fallback_llm_provider_preset(provider_id)
except ValueError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
@@ -1970,17 +2241,25 @@ async def refresh_ai_provider_preset(
else:
ai_payload = _normalize_ai_provider_payload(current_payload.get("ai_provider") or {})
provider_config = ai_payload["providers"].get(provider_id) or _provider_defaults(provider_id)
resolved_base_url = str(provider_config.get("base_url") or fallback["base_url"] or "")
resolved_api = str(provider_config.get("provider_api") or fallback["provider_api"] or "")
api_key, _api_key_source = _resolve_provider_api_key(provider_id, provider_config)
if not api_key and provider_id not in {"ollama", "opencode-go", "openrouter"}:
if not api_key and not can_refresh_catalog_without_api_key(
provider_id, resolved_base_url, resolved_api
):
raise HTTPException(
status_code=400, detail="请先配置当前供应商的 API Key,再刷新模型列表。",
)
try:
refreshed = await refresh_llm_provider_preset(
provider_id, api_key=api_key, base_url=provider_config.get("base_url"),
provider_api=provider_config.get("provider_api"),
provider_id,
api_key=api_key,
base_url=resolved_base_url,
provider_api=resolved_api,
anthropic_version=provider_config.get("anthropic_version") or "2023-06-01",
)
except LLMProviderCatalogConfigError as exc:
raise HTTPException(status_code=400, detail=catalog_error_message(exc)) from exc
except Exception as exc:
logger.warning(
"LLM provider catalog refresh failed",
@@ -2008,6 +2287,7 @@ async def update_external_integrations(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
_require_admin(current_user, "Only administrators can change integration settings")
saved = await save_external_integrations_payload(db, payload)
return {"status": "updated", "integrations": saved}
@@ -2020,7 +2300,17 @@ async def get_collector_settings(
result = await db.execute(select(DataSource).order_by(DataSource.module, DataSource.id))
datasources = result.scalars().all()
ais_health_by_source = await get_ais_source_health_by_source(db)
return {"collectors": [serialize_collector(datasource, ais_health_by_source) for datasource in datasources]}
storage_policy = await get_storage_policy(db)
return {
"collectors": [
serialize_collector(datasource, ais_health_by_source, storage_policy)
for datasource in datasources
],
"storage_policy": summarize_storage_policy(
storage_policy,
[datasource.source for datasource in datasources],
),
}
@router.put("/collectors/{datasource_id}")
@@ -2030,18 +2320,54 @@ async def update_collector_settings(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
_require_admin(current_user, "Only administrators can change collector settings")
datasource = await db.get(DataSource, datasource_id)
if not datasource:
raise HTTPException(status_code=404, detail="Data source not found")
datasource.is_active = settings.is_active
datasource.priority = settings.priority
datasource.frequency_minutes = settings.frequency_minutes
await db.commit()
await db.refresh(datasource)
if settings.snapshot_mode is not None:
requested_mode = settings.snapshot_mode
def _apply_collector_snapshot_mode(current_policy: dict) -> dict:
try:
return set_source_snapshot_mode(
current_policy,
datasource.source,
requested_mode,
)
except StoragePolicyLockedError as exc:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="全局「全部单份」已开启,无法单独开启该数据源的历史或年末快照。",
) from exc
storage_policy = await mutate_storage_policy(
db,
_apply_collector_snapshot_mode,
sync_system_retention=False,
commit=False,
)
datasource.is_active = settings.is_active
datasource.priority = settings.priority
datasource.frequency_minutes = settings.frequency_minutes
await db.commit()
await db.refresh(datasource)
else:
datasource.is_active = settings.is_active
datasource.priority = settings.priority
datasource.frequency_minutes = settings.frequency_minutes
await db.commit()
await db.refresh(datasource)
storage_policy = await get_storage_policy(db)
await sync_datasource_job(datasource.id)
ais_health_by_source = await get_ais_source_health_by_source(db)
return {"status": "updated", "collector": serialize_collector(datasource, ais_health_by_source)}
sources = await _load_known_collector_sources(db)
return {
"status": "updated",
"collector": serialize_collector(datasource, ais_health_by_source, storage_policy),
"storage_policy": summarize_storage_policy(storage_policy, sources),
}
@router.get("")
@@ -2056,12 +2382,20 @@ async def get_all_settings(
["system", "notifications", "security"],
)
ais_health_by_source = await get_ais_source_health_by_source(db)
storage_policy = await get_storage_policy(db)
return {
"system": setting_payloads["system"],
"notifications": setting_payloads["notifications"],
"security": setting_payloads["security"],
"tv": await get_tv_settings_payload(db),
"integrations": await serialize_external_integrations(db),
"collectors": [serialize_collector(datasource, ais_health_by_source) for datasource in datasources],
"collectors": [
serialize_collector(datasource, ais_health_by_source, storage_policy)
for datasource in datasources
],
"storage_policy": summarize_storage_policy(
storage_policy,
[datasource.source for datasource in datasources],
),
"generated_at": to_iso8601_utc(datetime.now(UTC)),
}
+107 -4
View File
@@ -7,12 +7,14 @@ from datetime import UTC, datetime
import uuid
from typing import Any, Literal
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import desc, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.compute_intelligence import configuration_admin, selected_countries
from app.core.access_gate import require_earth_or_api_access
from app.db.session import get_db
from app.models.situational_assessment import (
ComputeEvidenceCandidate,
@@ -53,6 +55,7 @@ from app.services.ai.workflow_runtime import (
get_active_run_handle,
read_frozen_result_revision,
)
from app.services.ai.stream_turn import stream_session_turn
from app.services.ai_client import AIProviderClient, get_ai_provider_client
from app.services.compute_history import ComputeSeriesMode
@@ -79,10 +82,32 @@ class SessionPinUpdateRequest(BaseModel):
pinned_items: list[dict[str, Any]] = Field(default_factory=list, max_length=12)
class HistoryMessageItem(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
role: Literal["user", "assistant"]
content: str = Field(min_length=1, max_length=6000)
class EarthTargetItem(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
entity_type: str = Field(min_length=1, max_length=64)
entity_id: str | None = Field(default=None, max_length=160)
label: str = Field(default="", max_length=200)
latitude: float | None = None
longitude: float | None = None
layer: str | None = Field(default=None, max_length=80)
kind: str | None = Field(default=None, max_length=80)
properties: dict[str, Any] = Field(default_factory=dict)
class SessionTurnRequest(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
question: str = Field(min_length=2, max_length=1000)
workflow_id: str | None = Field(default=None, max_length=80, pattern=r"^[A-Za-z0-9_.-]+$")
targets: list[EarthTargetItem] = Field(default_factory=list, max_length=8)
domain: WorkbenchDomain | None = None
selected_codes: list[str] | None = Field(default=None, max_length=12)
mode: ComputeSeriesMode | None = None
@@ -95,6 +120,11 @@ class SessionTurnRequest(BaseModel):
preset: ViewPreset | None = None
prefer_llm: bool | Literal["auto"] = False
external_urls: list[str] = Field(default_factory=list, max_length=3)
news_context: dict[str, Any] | None = None
history: list[HistoryMessageItem] = Field(default_factory=list, max_length=40)
conversation_summary: str | None = Field(default=None, max_length=2400)
memory_notes: list[str] = Field(default_factory=list, max_length=12)
pinned_summaries: list[str] = Field(default_factory=list, max_length=8)
run_id: str | None = Field(default=None, min_length=4, max_length=64, pattern=r"^[A-Za-z0-9_-]+$")
@@ -340,6 +370,70 @@ async def create_session_turn(
return turn_result
@router.post("/sessions/{session_id}/turns/stream")
async def stream_investigation_session_turn(
session_id: str,
payload: SessionTurnRequest,
request: Request,
response: Response,
access: AccessContext = Depends(resolve_access_context),
db: AsyncSession = Depends(get_db),
ai_client: AIProviderClient = Depends(get_ai_provider_client),
) -> StreamingResponse:
"""Adaptive SSE endpoint streaming LLM reasoning & answer when configured, else grounded baseline."""
session_row: InvestigationSession | None = None
effective_access = access
issued_token: str | None = None
if session_id == "stateless":
owner_key, issued_token = ensure_session_owner_identity(access, response)
effective_access = replace(access, actor_key=owner_key, has_session_credential=True)
else:
session_row = await _load_owned_session_or_fail(session_id, access, db)
codes = (
selected_countries(",".join(payload.selected_codes))
if payload.selected_codes
else None
)
overrides = {
"domain": payload.domain,
"selected_codes": codes,
"mode": payload.mode,
"focus_year": payload.focus_year,
"entity_id": payload.entity_id,
"visible_layers": payload.visible_layers,
"time_basis": payload.time_basis,
"cutoff_at": payload.cutoff_at,
"include_drill": payload.include_drill,
}
headers = {
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
}
return StreamingResponse(
stream_session_turn(
db,
request=request,
session=session_row,
question=payload.question,
context_override=overrides,
news_context=payload.news_context,
history=[item.model_dump() for item in payload.history],
conversation_summary=payload.conversation_summary,
memory_notes=payload.memory_notes,
pinned_summaries=payload.pinned_summaries,
workflow_id=payload.workflow_id,
targets=[t.model_dump() for t in payload.targets],
access=effective_access,
ai_client=ai_client,
client_run_id=payload.run_id,
issued_session_token=issued_token,
),
media_type="text/event-stream",
headers=headers,
)
# ============================================================================
# Group 3: WorkflowRun Inspection & Explicit Cancellation
# ============================================================================
@@ -418,7 +512,10 @@ async def cancel_workflow_run(
# ============================================================================
@router.get("/results/{result_id:path}/revisions/{revision}")
@router.get(
"/results/{result_id:path}/revisions/{revision}",
dependencies=[Depends(require_earth_or_api_access("situational:read"))],
)
async def get_frozen_result_revision(
result_id: str,
revision: int,
@@ -442,7 +539,10 @@ async def get_frozen_result_revision(
# ============================================================================
@router.get("/presentations")
@router.get(
"/presentations",
dependencies=[Depends(require_earth_or_api_access("situational:read"))],
)
async def get_presentations(
response: Response,
after_cursor: int = Query(0, ge=0),
@@ -465,7 +565,10 @@ async def get_presentations(
)
@router.get("/presentations/{presentation_key:path}")
@router.get(
"/presentations/{presentation_key:path}",
dependencies=[Depends(require_earth_or_api_access("situational:read"))],
)
async def get_presentation_by_key(
presentation_key: str,
response: Response,
+112
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import copy
import os
import secrets
import subprocess
@@ -12,6 +13,7 @@ from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import ROOT_DIR, settings
from app.core.enums import UserRole
from app.core.security import get_current_user
from app.db.session import get_db
from app.models.user import User
@@ -634,3 +636,113 @@ async def ingest_admin_client_log(
payload=payload,
request=request,
)
_EXTERNAL_OPENAPI_PREFIXES = (
"/health",
"/api/v1/auth/login",
"/api/v1/auth/refresh",
"/api/v1/visualization/",
"/api/v1/layers/",
"/api/v1/vessels/",
"/api/v1/news/",
"/api/v1/data-products",
"/api/v1/earth/",
"/api/v1/interactables",
"/api/v1/tv/",
"/api/v1/client/update-manifest",
)
_EXTERNAL_OPENAPI_EXCLUDED_SUBSTRINGS = (
"collect-location",
"/location",
"/configuration",
"/upload",
"/preview",
"/targets",
"/brand/assets",
"/boundaries/build",
"/boundaries/config",
"/news-groups",
"/news-items",
)
_EXTERNAL_ALLOWED_POST_PATHS = frozenset(
{
"/api/v1/auth/login",
"/api/v1/auth/refresh",
"/api/v1/visualization/terrain/terrarium/batch",
"/api/v1/visualization/geo/path",
"/api/v1/news/refresh",
}
)
def _require_docs_developer_or_admin(current_user: User = Depends(get_current_user)) -> User:
role = (
current_user.role.value
if hasattr(current_user.role, "value")
else str(current_user.role or "")
)
groups = {str(g).strip() for g in (current_user.gatekeeper_groups or []) if g}
if (
role in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}
or "docs_developer" in groups
or "docs_admin" in groups
):
return current_user
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Developer docs or administrator permission required",
)
def _build_external_openapi_schema(raw_schema: dict) -> dict:
schema = copy.deepcopy(raw_schema)
raw_paths = schema.get("paths") or {}
filtered_paths: dict = {}
for path, path_item in raw_paths.items():
if not isinstance(path_item, dict):
continue
if not any(path.startswith(prefix) for prefix in _EXTERNAL_OPENAPI_PREFIXES):
continue
if any(sub in path for sub in _EXTERNAL_OPENAPI_EXCLUDED_SUBSTRINGS):
continue
allowed_methods: dict = {}
for method, operation in path_item.items():
lower_method = str(method).lower()
if lower_method == "get":
allowed_methods[method] = operation
elif lower_method == "post" and path in _EXTERNAL_ALLOWED_POST_PATHS:
allowed_methods[method] = operation
if allowed_methods:
filtered_paths[path] = allowed_methods
schema["paths"] = filtered_paths
components = schema.setdefault("components", {})
security_schemes = components.setdefault("securitySchemes", {})
security_schemes["ApiKeyAuth"] = {
"type": "apiKey",
"in": "header",
"name": "X-API-Key",
}
schema["security"] = [{"ApiKeyAuth": []}]
info = schema.setdefault("info", {})
info["title"] = f"{info.get('title', 'Planet API')} (External & UE5 Read-Only)"
return schema
@router.get("/openapi.json")
async def get_controlled_openapi_schema(
request: Request,
_user: User = Depends(_require_docs_developer_or_admin),
):
"""Return full OpenAPI schema for authenticated administrators and docs_developer users."""
return request.app.openapi()
@router.get("/openapi-external.json")
async def get_external_openapi_schema(
request: Request,
_user: User = Depends(_require_docs_developer_or_admin),
):
"""Return curated external/UE5 OpenAPI schema excluding internal admin endpoints."""
return _build_external_openapi_schema(request.app.openapi())
+3 -2
View File
@@ -6,6 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import Response
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_earth_or_api_access
from app.db.session import get_db
from app.services.tv_catalog import get_tv_catalog_page
from app.services.tv_streams import get_public_tv_payload, is_allowed_tv_proxy_url
@@ -33,7 +34,7 @@ def _should_strip_hls_metadata_line(line: str) -> bool:
return normalized.startswith("#EXT-X-MEDIA:") and "TYPE=SUBTITLES" in normalized
@router.get("/streams")
@router.get("/streams", dependencies=[Depends(require_earth_or_api_access("tv:read"))])
async def list_public_tv_streams(
offset: int = Query(0, ge=0),
limit: int = Query(50, ge=1, le=100),
@@ -44,7 +45,7 @@ async def list_public_tv_streams(
return await get_tv_catalog_page(db, offset=offset, limit=limit, q=q, selected_id=selected_id)
@router.get("/proxy")
@router.get("/proxy", dependencies=[Depends(require_earth_or_api_access("tv:read", allow_query_api_key=True))])
async def proxy_tv_stream(
url: str = Query(..., description="Upstream TV stream or manifest URL"),
db: AsyncSession = Depends(get_db),
+1 -1
View File
@@ -13,7 +13,7 @@ from app.schemas.user import UserCreate, UserUpdate
router = APIRouter()
VALID_GATEKEEPER_GROUPS = {"docs_user", "docs_developer", "docs_admin"}
VALID_GATEKEEPER_GROUPS = {"docs_user", "docs_developer", "docs_admin", "api_access"}
ADMIN_ROLES = [UserRole.SUPER_ADMIN.value, UserRole.ADMIN.value]
SUPER_ADMIN_ROLES = [UserRole.SUPER_ADMIN.value]
+2 -1
View File
@@ -6,13 +6,14 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.visualization import _parse_bbox, build_vessel_snapshot_response
from app.core.access_gate import require_earth_or_api_access
from app.db.session import get_db
from app.services.vessel_ais_aggregation import MAX_SNAPSHOT_LIMIT
router = APIRouter()
@router.get("/snapshot")
@router.get("/snapshot", dependencies=[Depends(require_earth_or_api_access("vessels:read"))])
async def get_vessel_snapshot(
bbox: Optional[str] = Query(None, description="Snapshot bbox as lon_min,lat_min,lon_max,lat_max"),
zoom: float = Query(..., ge=1, le=20, description="Current map zoom level"),
+293 -106
View File
@@ -7,16 +7,18 @@ Returns GeoJSON format compatible with Three.js, CesiumJS, and Unreal Cesium.
import asyncio
import base64
from collections import OrderedDict
from contextlib import aclosing
from datetime import UTC, datetime, timedelta
import math
import re
import httpx
from fastapi import APIRouter, HTTPException, Depends, Query, Response
from fastapi import APIRouter, HTTPException, Depends, Query, Request, Response
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from typing import List, Dict, Any, Optional
from app.core.access_gate import require_admin_user, require_earth_or_api_access
from app.core.compute_types import COMPUTE_SITE_TYPES, COMPUTE_SOURCES, compute_site_type, compute_record_filter, compute_site_type_expression
from app.core.collected_data_fields import get_record_field
from app.core.enums import BGPStatus
@@ -28,6 +30,7 @@ from app.models.bgp_anomaly import BGPAnomaly
from app.models.bgp_incident import BGPIncident
from app.models.bgp_observation import BGPObservation
from app.models.collected_data import CollectedData
from app.models.user import User
from app.models.vessel import AISSourceHealth, VesselCurrentState, VesselPosition, VesselStatic
from app.services.bgp_collectors import build_bgp_collector_coverage
from app.services.cable_graph import build_graph_from_data, CableGraph, haversine_distance
@@ -36,6 +39,7 @@ from app.services.compute_center_locations import (
ResolutionDiagnostic,
build_compute_center_location_query,
collect_location_candidates,
get_compute_center_location_dict,
refresh_compute_center_location_cache,
resolve_compute_center_location_full,
upsert_compute_center_location,
@@ -47,6 +51,10 @@ from app.services.location.llm_fallback import (
collect_llm_location_fallback_candidate,
collect_location_search_evidence,
)
from app.services.location.agent_resolver import (
run_controlled_location_agent,
run_l1_structured_facility_resolvers,
)
from app.services.persistent_logs import record_system_log
from app.services.vessel_ais_aggregation import (
build_field_conflict_candidates,
@@ -63,12 +71,14 @@ from app.services.earth_layer_cache import (
earth_layer_cache,
format_bbox_key,
get_or_build_layer_payload,
get_or_build_layer_response,
quantize_bbox,
)
from app.core.logging import get_logger
router = APIRouter()
logger = get_logger(__name__, service="api")
_vis_read_dep = Depends(require_earth_or_api_access("visualization:read"))
TERRAIN_TILE_URL_TEMPLATE = (
"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
)
@@ -278,36 +288,43 @@ def convert_landing_point_to_geojson(records: List[CollectedData], city_to_cable
return {"type": "FeatureCollection", "features": features}
def _extract_satellite_record(record: CollectedData) -> tuple[dict[str, Any], Any, Optional[str], Optional[str], Optional[str], str] | None:
metadata = record.extra_data or {}
norad_id = metadata.get("norad_cat_id")
if not norad_id:
return None
tle_line1 = metadata.get("tle_line1")
tle_line2 = metadata.get("tle_line2")
if not tle_line1 or not tle_line2:
tle_line1, tle_line2 = build_tle_lines_from_elements(
norad_cat_id=norad_id,
epoch=metadata.get("epoch"),
inclination=metadata.get("inclination"),
raan=metadata.get("raan"),
eccentricity=metadata.get("eccentricity"),
arg_of_perigee=metadata.get("arg_of_perigee"),
mean_anomaly=metadata.get("mean_anomaly"),
mean_motion=metadata.get("mean_motion"),
)
constellation_group = _normalize_satellite_constellation_group(
metadata.get("constellation_group"),
record.name,
)
footprint_policy = _get_satellite_footprint_policy(constellation_group)
return metadata, norad_id, tle_line1, tle_line2, constellation_group, footprint_policy
def convert_satellite_to_geojson(records: List[CollectedData]) -> Dict[str, Any]:
"""Convert satellite TLE records to GeoJSON"""
features = []
for record in records:
metadata = record.extra_data or {}
norad_id = metadata.get("norad_cat_id")
if not norad_id:
extracted = _extract_satellite_record(record)
if extracted is None:
continue
tle_line1 = metadata.get("tle_line1")
tle_line2 = metadata.get("tle_line2")
if not tle_line1 or not tle_line2:
tle_line1, tle_line2 = build_tle_lines_from_elements(
norad_cat_id=norad_id,
epoch=metadata.get("epoch"),
inclination=metadata.get("inclination"),
raan=metadata.get("raan"),
eccentricity=metadata.get("eccentricity"),
arg_of_perigee=metadata.get("arg_of_perigee"),
mean_anomaly=metadata.get("mean_anomaly"),
mean_motion=metadata.get("mean_motion"),
)
constellation_group = _normalize_satellite_constellation_group(
metadata.get("constellation_group"),
record.name,
)
footprint_policy = _get_satellite_footprint_policy(constellation_group)
metadata, norad_id, tle_line1, tle_line2, constellation_group, footprint_policy = extracted
features.append(
{
@@ -340,6 +357,43 @@ def convert_satellite_to_geojson(records: List[CollectedData]) -> Dict[str, Any]
return {"type": "FeatureCollection", "features": features}
def convert_satellite_to_compact_rows(records: List[CollectedData]) -> List[List[Any]]:
"""Convert satellite TLE records into compact array rows while keeping full catalog fidelity."""
rows: List[List[Any]] = []
for record in records:
extracted = _extract_satellite_record(record)
if extracted is None:
continue
metadata, norad_id, tle_line1, tle_line2, constellation_group, _footprint_policy = extracted
row: List[Any] = [
record.id,
norad_id,
record.name,
constellation_group,
tle_line1,
tle_line2,
]
if not tle_line1 or not tle_line2:
row.append(
[
metadata.get("inclination"),
metadata.get("raan"),
metadata.get("eccentricity"),
metadata.get("arg_of_perigee"),
metadata.get("mean_anomaly"),
metadata.get("mean_motion"),
metadata.get("epoch"),
metadata.get("international_designator"),
metadata.get("classification_type"),
metadata.get("bstar"),
]
)
rows.append(row)
return rows
def _get_satellite_footprint_policy(constellation_group: Optional[str]) -> str:
if constellation_group == "starlink":
@@ -1546,7 +1600,7 @@ def convert_bgp_incidents_to_geojson(
# ============== API Endpoints ==============
@router.get("/geo/cables")
@router.get("/geo/cables", dependencies=[_vis_read_dep])
async def get_cables_geojson(db: AsyncSession = Depends(get_db), response: Response = None):
"""获取海底电缆 GeoJSON 数据 (LineString)"""
async def build_payload() -> dict[str, Any]:
@@ -1584,7 +1638,7 @@ async def _build_cables_geojson(db: AsyncSession) -> dict[str, Any]:
raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")
@router.get("/geo/landing-points")
@router.get("/geo/landing-points", dependencies=[_vis_read_dep])
async def get_landing_points_geojson(db: AsyncSession = Depends(get_db), response: Response = None):
async def build_payload() -> dict[str, Any]:
return await _build_landing_points_geojson(db)
@@ -1639,7 +1693,7 @@ async def _build_landing_points_geojson(db: AsyncSession) -> dict[str, Any]:
raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")
@router.get("/terrain/terrarium/{z}/{x}/{y}.png")
@router.get("/terrain/terrarium/{z}/{x}/{y}.png", dependencies=[_vis_read_dep])
async def get_terrarium_tile(z: int, x: int, y: int):
"""Proxy Terrarium elevation tiles through the backend to avoid browser CORS issues."""
if not _is_valid_terrain_tile(z, x, y):
@@ -1729,7 +1783,7 @@ async def _fetch_terrain_tile(
return content, content_type, dict(headers)
@router.post("/terrain/terrarium/batch")
@router.post("/terrain/terrarium/batch", dependencies=[_vis_read_dep])
async def get_terrarium_tile_batch(payload: TerrariumTileBatchRequest):
"""Fetch Terrarium elevation tiles in batches so the browser avoids many tiny requests."""
unique_tiles: list[TerrariumTileRequest] = []
@@ -1795,7 +1849,7 @@ async def get_terrarium_tile_batch(payload: TerrariumTileBatchRequest):
}
@router.get("/geo/all")
@router.get("/geo/all", dependencies=[_vis_read_dep])
async def get_all_geojson(db: AsyncSession = Depends(get_db)):
records_by_source = await _load_current_collected_data_by_sources(
db,
@@ -1834,34 +1888,57 @@ async def get_all_geojson(db: AsyncSession = Depends(get_db)):
}
@router.get("/geo/satellites")
@router.get("/geo/satellites", dependencies=[_vis_read_dep])
async def get_satellites_geojson(
request: Request = None,
limit: Optional[int] = Query(
None,
ge=1,
description="Maximum number of satellites to return. Omit for no limit.",
),
format: Optional[str] = Query(
None,
pattern="^(geojson|compact)$",
description="Response payload format: default GeoJSON or compact full-catalog rows.",
),
db: AsyncSession = Depends(get_db),
response: Response = None,
):
"""获取卫星 TLE GeoJSON 数据"""
"""获取卫星 TLE 数据(支持完整 GeoJSON 与全量紧凑数组格式)"""
compact = format == "compact"
cache_key = (
earth_layer_cache.key("satellites", format="compact", limit=limit or "all")
if compact
else earth_layer_cache.key("satellites", limit=limit or "all")
)
async def build_payload() -> dict[str, Any]:
if compact:
return await _build_satellites_compact(limit=limit, db=db)
return await _build_satellites_geojson(limit=limit, db=db)
return await get_or_build_layer_payload(
key=earth_layer_cache.key("satellites", limit=limit or "all"),
if request is None:
return await get_or_build_layer_payload(
key=cache_key,
policy=SATELLITE_CACHE_POLICY,
builder=build_payload,
response=response,
)
return await get_or_build_layer_response(
key=cache_key,
policy=SATELLITE_CACHE_POLICY,
builder=build_payload,
request=request,
response=response,
)
async def _build_satellites_geojson(
async def _stream_satellite_batches(
*,
limit: int | None,
db: AsyncSession,
) -> dict[str, Any]:
features: list[dict[str, Any]] = []
):
source = "celestrak_tle"
for current_only in (True, False):
if current_only:
@@ -1887,16 +1964,53 @@ async def _build_satellites_geojson(
try:
async for batch in records.partitions(SATELLITE_QUERY_BATCH_SIZE):
found_records = True
features.extend(convert_satellite_to_geojson(batch)["features"])
yield batch
finally:
await records.close()
if found_records:
break
async def _build_satellites_geojson(
*,
limit: int | None,
db: AsyncSession,
) -> dict[str, Any]:
features: list[dict[str, Any]] = []
async with aclosing(_stream_satellite_batches(limit=limit, db=db)) as batches:
async for batch in batches:
features.extend(convert_satellite_to_geojson(batch)["features"])
return {"type": "FeatureCollection", "features": features, "count": len(features)}
@router.get("/geo/supercomputers")
async def _build_satellites_compact(
*,
limit: int | None,
db: AsyncSession,
) -> dict[str, Any]:
rows: list[list[Any]] = []
async with aclosing(_stream_satellite_batches(limit=limit, db=db)) as batches:
async for batch in batches:
rows.extend(convert_satellite_to_compact_rows(batch))
return {
"format": "satellite_compact_v1",
"count": len(rows),
"fields": [
"id",
"norad_cat_id",
"name",
"constellation_group",
"tle_line1",
"tle_line2",
"fallback_elements",
],
"satellites": rows,
}
@router.get("/geo/supercomputers", dependencies=[_vis_read_dep])
async def get_supercomputers_geojson(
limit: int = 500,
db: AsyncSession = Depends(get_db),
@@ -1919,7 +2033,7 @@ async def get_supercomputers_geojson(
}
@router.get("/geo/gpu-clusters")
@router.get("/geo/gpu-clusters", dependencies=[_vis_read_dep])
async def get_gpu_clusters_geojson(
limit: int = 100,
db: AsyncSession = Depends(get_db),
@@ -1942,7 +2056,7 @@ async def get_gpu_clusters_geojson(
}
@router.get("/geo/compute-centers")
@router.get("/geo/compute-centers", dependencies=[_vis_read_dep])
async def get_compute_centers_geojson(
limit: int = Query(200, ge=1, le=1000),
db: AsyncSession = Depends(get_db),
@@ -2051,6 +2165,7 @@ class CollectComputeCenterLocationRequest(BaseModel):
organization: Optional[str] = None
city: Optional[str] = None
country: Optional[str] = None
force: bool = False
record_id: Optional[int] = Field(default=None, alias="id")
model_config = {"populate_by_name": True}
@@ -2087,12 +2202,12 @@ async def _compute_center_location_web_search_capability(db: AsyncSession) -> Di
"reason": f"WebSearch 配置读取失败:{exc}",
}
provider_config = config.active_provider_config
has_api_key = bool((provider_config.api_key or "").strip())
has_api_key = bool((provider_config.api_key or "").strip()) or not provider_config.api_key_env
if not config.enabled:
return {
"enabled": False,
"provider": config.default_provider,
"reason": "WebSearch 未开启,无法进行事实核查定位。",
"reason": "WebSearch 未开启,将仅使用确定性设施知识库与地理编码。",
}
if not has_api_key:
return {
@@ -2107,7 +2222,7 @@ async def _compute_center_location_web_search_capability(db: AsyncSession) -> Di
}
@router.get("/compute-centers/location-capability")
@router.get("/compute-centers/location-capability", dependencies=[_vis_read_dep])
async def get_compute_center_location_capability(
db: AsyncSession = Depends(get_db),
):
@@ -2115,27 +2230,19 @@ async def get_compute_center_location_capability(
return await _compute_center_location_web_search_capability(db)
_TERMINAL_UNLOCATABLE_STATUSES = frozenset({"undisclosed", "multi_site", "anonymous"})
@router.post("/compute-centers/{source_id}/collect-location")
async def collect_compute_center_location(
source_id: str,
payload: CollectComputeCenterLocationRequest,
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
"""Run the full multi-query location collection pipeline for a record.
The endpoint accepts the source_id of a compute center plus contextual
fields (name/operator/site/city/country/...) and returns ranked candidate
locations from source coordinates, open organization lookups, and online
geocoding combinations. The caller never has to type coordinates by hand:
if any candidate is accepted it can be applied directly. If no candidate
can reach city-level precision the response includes an explicit
``failure_reason`` and the list of attempted queries.
"""
"""Run deterministic facility lookups, Wikidata/PeeringDB, and controlled Tool-Calling location resolution."""
if not source_id or not source_id.strip():
raise HTTPException(status_code=400, detail="source_id is required")
capability = await _compute_center_location_web_search_capability(db)
if not capability.get("enabled"):
raise HTTPException(status_code=409, detail=capability)
record = await _load_compute_center_record(db, source_id)
name = payload.name or (record.name if record else None)
@@ -2148,8 +2255,36 @@ async def collect_compute_center_location(
country = payload.country or (get_record_field(record, "country") if record else None)
source = payload.source or (record.source if record else None)
record_id = payload.record_id or (record.id if record else None)
raw_sources = metadata.get("sources") if isinstance(metadata.get("sources"), list) else []
source_url = metadata.get("source_url") or metadata.get("detail_url")
builds_upon = metadata.get("builds_upon")
source_raw_country = metadata.get("raw_country")
candidates, attempted_queries = collect_location_candidates(
if not payload.force and source and source_id:
cached = get_compute_center_location_dict(source, source_id)
cached_status = str(cached.get("verification_status") or "").strip().lower()
if cached_status in _TERMINAL_UNLOCATABLE_STATUSES:
return {
"source_id": source_id,
"record_id": record_id,
"name": name,
"success": False,
"terminal_status": cached_status,
"failure_reason": cached.get("source_note") or f"Marked as {cached_status}",
"candidates": [],
"attempted_queries": [],
"llm_failure_reason": None,
"context": {
"name": name,
"operator": operator,
"site": site,
"city": city,
"country": country,
},
}
candidates, attempted_queries = await asyncio.to_thread(
collect_location_candidates,
name=name,
source=source,
source_id=source_id,
@@ -2159,52 +2294,103 @@ async def collect_compute_center_location(
city=city,
country=country,
record_id=record_id,
sources=raw_sources,
source_url=source_url,
builds_upon=builds_upon,
source_raw_country=source_raw_country,
)
llm_failure_reason = None
terminal_status: str | None = None
query = build_compute_center_location_query(
name=name,
source=source,
source_id=source_id,
operator=operator,
site=site,
organization=organization,
city=city,
country=country,
sources=raw_sources,
source_url=source_url,
builds_upon=builds_upon,
source_raw_country=source_raw_country,
)
if not candidates:
query = build_compute_center_location_query(
name=name,
source=source,
source_id=source_id,
operator=operator,
site=site,
organization=organization,
city=city,
country=country,
l1_candidates, l1_queries, _allow_low_short_circuit = await run_l1_structured_facility_resolvers(
query, db=db
)
if l1_candidates:
candidates = l1_candidates
attempted_queries = [*attempted_queries, *l1_queries]
if not candidates:
capability = await _compute_center_location_web_search_capability(db)
llm_result = None
try:
web_search_client = await get_web_search_client(db)
search_result = await collect_location_search_evidence(
web_search_client=web_search_client,
query=query,
entity_type="compute_center",
)
attempted_queries = [*attempted_queries, *search_result.attempted_queries]
if not search_result.evidence:
llm_failure_reason = search_result.failure_reason
raise RuntimeError(search_result.failure_reason or "no WebSearch evidence")
provider_client = await get_ai_provider_client(db)
llm_result = await collect_llm_location_fallback_candidate(
provider_client=provider_client,
query=query,
entity_type="compute_center",
db=db,
attempted_queries=attempted_queries,
search_evidence=search_result.evidence,
)
except Exception as exc:
if llm_failure_reason is None:
llm_failure_reason = f"LLM location factcheck unavailable: {exc}"
attempted_queries = [
*attempted_queries,
f"llm_factcheck:compute_center:{name or source_id or 'unknown'}",
]
if not capability.get("enabled") and not raw_sources and not source_url:
llm_failure_reason = str(capability.get("reason") or "WebSearch unavailable")
else:
try:
provider_client = await get_ai_provider_client(db)
web_search_client = await get_web_search_client(db)
if hasattr(provider_client, "analyze"):
llm_result, terminal_status = await run_controlled_location_agent(
provider_client=provider_client,
web_search_client=web_search_client,
query=query,
entity_type="compute_center",
db=db,
attempted_queries=[],
)
else:
search_result = await collect_location_search_evidence(
web_search_client=web_search_client,
query=query,
entity_type="compute_center",
)
attempted_queries = [*attempted_queries, *search_result.attempted_queries]
if not search_result.evidence:
llm_failure_reason = search_result.failure_reason
raise RuntimeError(search_result.failure_reason or "no WebSearch evidence")
llm_result = await collect_llm_location_fallback_candidate(
provider_client=provider_client,
query=query,
entity_type="compute_center",
db=db,
attempted_queries=attempted_queries,
search_evidence=search_result.evidence,
)
except Exception as exc:
if llm_failure_reason is None:
llm_failure_reason = f"LLM location factcheck unavailable: {exc}"
attempted_queries = [
*attempted_queries,
f"llm_factcheck:compute_center:{name or source_id or 'unknown'}",
]
if llm_result is not None:
attempted_queries = [*attempted_queries, *llm_result.attempted_queries]
candidates = llm_result.candidates
llm_failure_reason = llm_result.failure_reason
if terminal_status in _TERMINAL_UNLOCATABLE_STATUSES:
return {
"source_id": source_id,
"record_id": record_id,
"name": name,
"success": False,
"terminal_status": terminal_status,
"failure_reason": llm_failure_reason or f"Marked as {terminal_status}",
"candidates": [],
"attempted_queries": list(attempted_queries),
"llm_failure_reason": llm_failure_reason,
"context": {
"name": name,
"operator": operator,
"site": site,
"city": city,
"country": country,
},
}
if not candidates:
logger.warning_event(
"Compute center location collection returned no candidates",
@@ -2288,6 +2474,7 @@ async def collect_compute_center_location(
async def save_compute_center_location(
source_id: str,
payload: SaveComputeCenterLocationRequest,
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
"""Persist the user-selected compute-center location candidate."""
@@ -2394,7 +2581,7 @@ async def _load_raw_vessel_snapshot_features(
"legacy_fallback_used": False,
}
@router.get("/vessels/custom-supplements")
@router.get("/vessels/custom-supplements", dependencies=[_vis_read_dep])
async def get_vessel_custom_supplements(db: AsyncSession = Depends(get_db)):
"""Group custom vessel_ais sources by their declared merge target for diagnostics."""
@@ -2413,7 +2600,7 @@ async def get_vessel_custom_supplements(db: AsyncSession = Depends(get_db)):
return {"groups": list(grouped.values())}
@router.get("/vessels/name-fallbacks")
@router.get("/vessels/name-fallbacks", dependencies=[_vis_read_dep])
async def get_vessel_name_fallbacks(
limit: int = Query(500, ge=0, description="Maximum fallback-name vessels to return. 0 means no limit."),
db: AsyncSession = Depends(get_db),
@@ -2482,7 +2669,7 @@ async def get_vessel_name_fallbacks(
}
@router.get("/vessels/{mmsi}")
@router.get("/vessels/{mmsi}", dependencies=[_vis_read_dep])
async def get_vessel_detail(mmsi: int, db: AsyncSession = Depends(get_db)):
from app.services.vessel_enrichment import get_vessel_enrichment_bundle
@@ -2517,7 +2704,7 @@ async def get_vessel_detail(mmsi: int, db: AsyncSession = Depends(get_db)):
}
@router.get("/vessels/{mmsi}/track")
@router.get("/vessels/{mmsi}/track", dependencies=[_vis_read_dep])
async def get_vessel_track(
mmsi: int,
hours: int = Query(6, ge=1, le=24),
@@ -2584,7 +2771,7 @@ async def get_vessel_track(
}
@router.get("/vessels/{mmsi}/observations")
@router.get("/vessels/{mmsi}/observations", dependencies=[_vis_read_dep])
async def get_vessel_observations(
mmsi: int,
limit: int = Query(100, ge=1, le=500),
@@ -2601,7 +2788,7 @@ async def get_vessel_observations(
}
@router.get("/vessels/{mmsi}/conflicts")
@router.get("/vessels/{mmsi}/conflicts", dependencies=[_vis_read_dep])
async def get_vessel_conflicts(mmsi: int, db: AsyncSession = Depends(get_db)):
"""Return recorded AIS conflicts plus current raw-observation candidates."""
@@ -2615,7 +2802,7 @@ async def get_vessel_conflicts(mmsi: int, db: AsyncSession = Depends(get_db)):
}
@router.get("/geo/bgp-anomalies")
@router.get("/geo/bgp-anomalies", dependencies=[_vis_read_dep])
async def get_bgp_anomalies_geojson(
severity: Optional[str] = Query(None),
status: Optional[str] = Query("active"),
@@ -2659,7 +2846,7 @@ async def _build_bgp_anomalies_geojson(
return {**geojson, "count": len(geojson.get("features", []))}
@router.get("/geo/bgp-incidents")
@router.get("/geo/bgp-incidents", dependencies=[_vis_read_dep])
async def get_bgp_incidents_geojson(
severity: Optional[str] = Query(None),
status: Optional[str] = Query("active"),
@@ -2703,7 +2890,7 @@ async def _build_bgp_incidents_geojson(
return {**geojson, "count": len(geojson.get("features", []))}
@router.get("/geo/bgp-collectors")
@router.get("/geo/bgp-collectors", dependencies=[_vis_read_dep])
async def get_bgp_collectors_geojson(db: AsyncSession = Depends(get_db), response: Response = None):
async def build_payload() -> dict[str, Any]:
return await _build_bgp_collectors_geojson(db)
@@ -2732,7 +2919,7 @@ async def _build_bgp_collectors_geojson(db: AsyncSession) -> dict[str, Any]:
return {**geojson, "count": len(geojson.get("features", []))}
@router.get("/geo/summary")
@router.get("/geo/summary", dependencies=[_vis_read_dep])
async def get_visualization_geo_summary(db: AsyncSession = Depends(get_db), response: Response = None):
"""Return lightweight Earth HUD counts without loading layer GeoJSON payloads."""
async def build_payload() -> dict[str, Any]:
@@ -2842,7 +3029,7 @@ async def _build_visualization_geo_summary(db: AsyncSession) -> dict[str, Any]:
}
@router.get("/all")
@router.get("/all", dependencies=[_vis_read_dep])
async def get_all_visualization_data(db: AsyncSession = Depends(get_db)):
"""获取所有可视化数据的统一端点
@@ -2948,7 +3135,7 @@ async def get_cable_graph(db: AsyncSession) -> CableGraph:
return _cable_graph
@router.post("/geo/path")
@router.post("/geo/path", dependencies=[_vis_read_dep])
async def find_path(
start: List[float],
end: List[float],
+82 -6
View File
@@ -4,16 +4,18 @@ import asyncio
from datetime import UTC, datetime
from typing import Optional
from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Query
from fastapi import APIRouter, HTTPException, Query, WebSocket, WebSocketDisconnect
from jose import jwt, JWTError
from sqlalchemy import text
from app.core.access_gate import authenticate_ws_earth_or_api_key
from app.core.config import settings
from app.core.enums import UserRole
from app.core.logging import get_logger
from app.core.security import is_token_blacklisted
from app.core.time import to_iso8601_utc
from app.core.websocket.manager import manager
from app.db.session import async_session_factory
from app.db.session import async_session_factory, get_db
from app.services.log_tail import LOG_TAIL_CHANNEL, log_tail_manager
logger = get_logger(__name__, service="api")
@@ -23,6 +25,12 @@ EARTH_UPDATES_CHANNEL = "earth_updates"
async def authenticate_token(token: str) -> Optional[dict]:
"""Authenticate WebSocket connection via token"""
if await is_token_blacklisted(token):
logger.warning_event(
"WebSocket auth failed: revoked token",
event="auth.websocket.revoked_token",
)
return None
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
if payload.get("type") != "access":
@@ -67,12 +75,24 @@ async def load_websocket_user_role(user_id: str | None) -> str | None:
async def websocket_endpoint(
websocket: WebSocket,
token: str | None = Query(None),
api_key: str | None = Query(None),
earth_token: str | None = Query(None),
):
"""WebSocket endpoint for real-time data"""
logger.info_event(
"WebSocket connection attempt",
event="auth.websocket.connection_attempt",
context={"token_preview": f"{token[:8]}..." if token else "anonymous"},
context={
"token_preview": f"{token[:8]}..." if token else (
"api_key" if (api_key or websocket.headers.get("X-API-Key")) else (
"earth_session" if (
earth_token
or websocket.headers.get("X-Planet-Earth-Token")
or websocket.cookies.get("planet_earth_session")
) else "anonymous"
)
)
},
)
payload = await authenticate_token(token) if token else None
if token and payload is None:
@@ -83,8 +103,61 @@ async def websocket_endpoint(
await websocket.close(code=4001)
return
ws_earth_or_key_actor: str | None = None
if payload is None:
has_api_key = bool((api_key or "").strip() or (websocket.headers.get("X-API-Key") or "").strip())
try:
if has_api_key:
override_get_db = websocket.app.dependency_overrides.get(get_db)
if override_get_db is not None:
db_gen = override_get_db()
db = await anext(db_gen)
try:
authed, ws_earth_or_key_actor = await authenticate_ws_earth_or_api_key(
websocket,
api_key_query=api_key,
earth_token_query=earth_token,
db=db,
)
finally:
await db_gen.aclose()
else:
async with async_session_factory() as db:
authed, ws_earth_or_key_actor = await authenticate_ws_earth_or_api_key(
websocket,
api_key_query=api_key,
earth_token_query=earth_token,
db=db,
)
else:
authed, ws_earth_or_key_actor = await authenticate_ws_earth_or_api_key(
websocket,
api_key_query=None,
earth_token_query=earth_token,
db=None, # type: ignore[arg-type]
)
except HTTPException:
logger.warning_event(
"WebSocket API key or Earth session rejected",
event="auth.websocket.connection_rejected",
)
await websocket.close(code=4001)
return
if not authed and settings.effective_earth_api_auth_mode == "enforce":
logger.warning_event(
"Unauthenticated WebSocket connection rejected in enforce mode",
event="auth.websocket.unauthenticated_rejected",
)
await websocket.close(code=4001)
return
is_anonymous = payload is None
user_id = str(payload.get("sub")) if payload else f"anonymous:{id(websocket)}"
user_id = (
str(payload.get("sub"))
if payload
else (ws_earth_or_key_actor or f"anonymous:{id(websocket)}")
)
user_role = await load_websocket_user_role(user_id) if payload else None
supported_channels = ["vessels", "earth_news", EARTH_UPDATES_CHANNEL] if is_anonymous else [
"gpu_clusters",
@@ -210,9 +283,12 @@ async def websocket_endpoint(
await websocket.send_json({"type": "ack", "data": {"received": True}})
except asyncio.TimeoutError:
await websocket.send_json({"type": "heartbeat", "data": {"action": "ping"}})
try:
await websocket.send_json({"type": "heartbeat", "data": {"action": "ping"}})
except Exception:
break
except WebSocketDisconnect:
except (WebSocketDisconnect, RuntimeError):
pass
finally:
await log_tail_manager.disconnect(websocket)
+492
View File
@@ -0,0 +1,492 @@
"""Unified access gate for first-party Earth sessions, API keys, and authorized JWT callers."""
from __future__ import annotations
import asyncio
from collections import defaultdict, deque
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
import hashlib
import hmac
import secrets
import time
from typing import Any, Literal
from urllib.parse import urlsplit
from uuid import uuid4
from fastapi import Depends, HTTPException, Request, WebSocket, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
import httpx
from jose import JWTError, jwt
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings
from app.core.enums import UserRole
from app.core.logging import get_logger
from app.core.security import (
REDIS_OP_TIMEOUT_SECONDS,
_AsyncRedisClient,
_load_active_user,
decode_token,
get_current_user,
is_token_blacklisted,
)
from app.db.session import get_db
from app.models.user import User
from app.services.api_keys import authenticate_api_key
logger = get_logger(__name__, service="access_gate")
EARTH_SESSION_COOKIE = "planet_earth_session"
EARTH_TOKEN_HEADER = "X-Planet-Earth-Token"
API_KEY_HEADER = "X-API-Key"
API_ACCESS_GROUP = "api_access"
DESKTOP_CLIENT_PREFIX = "planet-earth-desktop/"
TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
_EARTH_SESSION_TOKEN_TYPE = "earth_session"
_MAX_DESKTOP_CLOCK_SKEW_SECONDS = 300
_EARTH_SESSION_RATE_LIMIT_PER_MIN = 600
_LOCAL_SLIDING_WINDOWS: dict[str, deque[float]] = defaultdict(deque)
_LOCAL_NONCES: dict[str, float] = {}
_MAX_LOCAL_ENTRIES = 20_000
optional_bearer = HTTPBearer(auto_error=False)
@dataclass(frozen=True, slots=True)
class EarthAccessContext:
"""Resolved caller identity for Earth data and external API routes."""
channel: Literal["api_key", "jwt", "earth_web", "earth_desktop", "dev_open"]
actor_key: str
user: User | None = None
api_key_id: int | None = None
def reset_access_gate_caches() -> None:
"""Clear in-process rate-limit and nonce caches (used by tests)."""
_LOCAL_SLIDING_WINDOWS.clear()
_LOCAL_NONCES.clear()
def _prune_local_nonces(now: float) -> None:
expired = [key for key, exp in _LOCAL_NONCES.items() if exp <= now]
for key in expired:
_LOCAL_NONCES.pop(key, None)
while len(_LOCAL_NONCES) > _MAX_LOCAL_ENTRIES:
_LOCAL_NONCES.pop(next(iter(_LOCAL_NONCES)), None)
async def check_sliding_rate_limit(
bucket: str,
*,
limit: int,
window_seconds: int,
detail: str = "Rate limit exceeded",
) -> None:
"""Enforce a bounded sliding/fixed window limit via Redis with local fallback."""
if limit <= 0 or window_seconds <= 0:
return
redis_key = f"access_gate:{bucket}"
try:
client = _AsyncRedisClient.get_client()
count = await asyncio.wait_for(
client.incr(redis_key),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
if int(count) == 1:
await asyncio.wait_for(
client.expire(redis_key, window_seconds),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
if int(count) > limit:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=detail,
)
return
except HTTPException:
raise
except Exception:
pass
now = time.monotonic()
dq = _LOCAL_SLIDING_WINDOWS[bucket]
cutoff = now - float(window_seconds)
while dq and dq[0] <= cutoff:
dq.popleft()
if len(dq) >= limit:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=detail,
)
dq.append(now)
if len(_LOCAL_SLIDING_WINDOWS) > _MAX_LOCAL_ENTRIES:
_LOCAL_SLIDING_WINDOWS.pop(next(iter(_LOCAL_SLIDING_WINDOWS)), None)
async def _register_nonce_once(nonce: str, ttl_seconds: int) -> bool:
key = f"earth_nonce:{hashlib.sha256(nonce.encode('utf-8')).hexdigest()}"
try:
client = _AsyncRedisClient.get_client()
stored = await asyncio.wait_for(
client.set(key, "1", ex=ttl_seconds, nx=True),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
return bool(stored)
except Exception:
pass
now = time.monotonic()
_prune_local_nonces(now)
if key in _LOCAL_NONCES and _LOCAL_NONCES[key] > now:
return False
_LOCAL_NONCES[key] = now + float(ttl_seconds)
return True
def create_earth_session_token(
channel: Literal["web", "desktop"],
client_id: str | None = None,
) -> tuple[str, int]:
"""Mint a short-lived signed JWT for Web Earth or Desktop Earth zero-login access."""
ttl_minutes = max(5, int(settings.EARTH_SESSION_TTL_MINUTES or 30))
ttl_seconds = ttl_minutes * 60
expire = datetime.now(UTC) + timedelta(seconds=ttl_seconds)
cid = (client_id or uuid4().hex[:16]).strip()[:64]
payload = {
"type": _EARTH_SESSION_TOKEN_TYPE,
"channel": channel,
"cid": cid,
"jti": uuid4().hex,
"exp": expire,
}
token = jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return token, ttl_seconds
def verify_earth_session_token(token: str) -> dict[str, Any] | None:
"""Verify a signed Earth session token and return its claims or None."""
cleaned = str(token or "").strip()
if not cleaned:
return None
try:
payload = jwt.decode(cleaned, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
except JWTError:
return None
if payload.get("type") != _EARTH_SESSION_TOKEN_TYPE:
return None
if payload.get("channel") not in {"web", "desktop"}:
return None
return payload
def _extract_host_port(raw_url_or_host: str) -> str:
value = str(raw_url_or_host or "").strip()
if not value:
return ""
if "://" in value:
parsed = urlsplit(value)
return (parsed.netloc or "").lower()
return value.lower()
def _allowed_web_origins(request: Request) -> set[str]:
allowed: set[str] = set()
req_host = _extract_host_port(request.headers.get("host") or request.url.netloc or "")
if req_host:
allowed.add(req_host)
for raw in [*(settings.EARTH_WEB_ALLOWED_ORIGINS or []), *(settings.CORS_ORIGINS or [])]:
host = _extract_host_port(str(raw))
if host and host != "*":
allowed.add(host)
return allowed
def verify_web_same_origin(request: Request) -> None:
"""Require first-party browser same-origin / allowed-origin headers for web session minting."""
sec_fetch_site = (request.headers.get("sec-fetch-site") or "").strip().lower()
if sec_fetch_site in {"cross-site"}:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Cross-site Earth session requests are forbidden",
)
origin_host = _extract_host_port(request.headers.get("origin") or "")
referer_host = _extract_host_port(request.headers.get("referer") or "")
allowed = _allowed_web_origins(request)
if origin_host:
if origin_host not in allowed:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Origin not permitted for Earth web session",
)
return
if referer_host:
if referer_host not in allowed:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Referer not permitted for Earth web session",
)
return
if sec_fetch_site in {"same-origin", "same-site"}:
return
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Same-origin browser headers required for Earth web session",
)
async def verify_turnstile_token(token: str | None, remote_ip: str) -> None:
"""Verify Cloudflare Turnstile token when `TURNSTILE_SECRET_KEY` is configured."""
secret = str(settings.TURNSTILE_SECRET_KEY or "").strip()
if not secret:
return
cleaned = str(token or "").strip()
if not cleaned:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Turnstile verification token is required",
)
try:
async with httpx.AsyncClient(timeout=5.0) as client:
resp = await client.post(
TURNSTILE_VERIFY_URL,
data={
"secret": secret,
"response": cleaned,
"remoteip": remote_ip,
},
)
resp.raise_for_status()
body = resp.json()
except httpx.HTTPError as exc:
logger.warning_event(
"Turnstile verification request failed",
event="access_gate.turnstile.error",
context={"error": str(exc)},
)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Human verification service temporarily unavailable",
) from exc
if not bool(body.get("success")):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Turnstile verification failed",
)
async def verify_desktop_handshake(request: Request) -> str:
"""Verify Planet Earth Desktop client identity and optional HMAC handshake."""
client_header = (request.headers.get("X-Planet-Client") or "").strip()
if not client_header.startswith(DESKTOP_CLIENT_PREFIX) or len(client_header) <= len(
DESKTOP_CLIENT_PREFIX
):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Desktop client header is required",
)
secret = str(settings.EARTH_DESKTOP_HANDSHAKE_SECRET or "").strip()
if not secret:
return client_header
ts_raw = (request.headers.get("X-Planet-Client-Timestamp") or "").strip()
nonce = (request.headers.get("X-Planet-Client-Nonce") or "").strip()
signature = (request.headers.get("X-Planet-Client-Signature") or "").strip().lower()
if not ts_raw or not nonce or not signature or len(nonce) > 128:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Desktop handshake signature headers required",
)
try:
ts_val = int(ts_raw)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid desktop handshake timestamp",
) from exc
now_ts = int(time.time())
if abs(now_ts - ts_val) > _MAX_DESKTOP_CLOCK_SKEW_SECONDS:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Desktop handshake timestamp expired",
)
expected = hmac.new(
secret.encode("utf-8"),
f"{ts_raw}.{nonce}.{client_header}".encode("utf-8"),
hashlib.sha256,
).hexdigest()
if not hmac.compare_digest(signature, expected):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid desktop handshake signature",
)
fresh = await _register_nonce_once(nonce, _MAX_DESKTOP_CLOCK_SKEW_SECONDS)
if not fresh:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Replay desktop handshake nonce rejected",
)
return client_header
def user_has_api_access(user: User) -> bool:
"""Return True if the authenticated user is allowed to call Earth/external APIs."""
role = user.role.value if hasattr(user.role, "value") else str(user.role or "")
if role in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
return True
groups = {str(g).strip() for g in (user.gatekeeper_groups or []) if g}
return API_ACCESS_GROUP in groups
async def require_admin_user(current_user: User = Depends(get_current_user)) -> User:
"""FastAPI dependency requiring `admin` or `super_admin` role."""
role = current_user.role.value if hasattr(current_user.role, "value") else str(current_user.role or "")
if role not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Administrator privileges required",
)
return current_user
async def _validate_bearer_api_user(
token: str,
db: AsyncSession,
) -> User:
if await is_token_blacklisted(token):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token has been revoked",
)
payload = decode_token(token)
if payload is None or payload.get("type") != "access" or payload.get("sub") is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token",
)
user = await _load_active_user(str(payload["sub"]), db)
if not user_has_api_access(user):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Account lacks api_access permission",
)
return user
def require_earth_or_api_access(
scope: str,
*,
allow_query_api_key: bool = False,
):
"""Build a FastAPI dependency allowing API Keys, authorized JWT users, or Earth sessions."""
async def _dependency(
request: Request,
credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer),
db: AsyncSession = Depends(get_db),
) -> EarthAccessContext:
raw_api_key = (request.headers.get(API_KEY_HEADER) or "").strip()
if not raw_api_key and allow_query_api_key:
raw_api_key = (request.query_params.get("api_key") or "").strip()
if raw_api_key:
record = await authenticate_api_key(db, raw_api_key, scope)
return EarthAccessContext(
channel="api_key",
actor_key=f"api_key:{record.id}",
api_key_id=int(record.id),
)
if credentials is not None and credentials.credentials:
user = await _validate_bearer_api_user(credentials.credentials, db)
return EarthAccessContext(
channel="jwt",
actor_key=f"user:{user.id}",
user=user,
)
earth_header = (request.headers.get(EARTH_TOKEN_HEADER) or "").strip()
earth_cookie = (request.cookies.get(EARTH_SESSION_COOKIE) or "").strip()
earth_token = earth_header or earth_cookie
if earth_token:
claims = verify_earth_session_token(earth_token)
if claims is not None:
channel = "earth_desktop" if claims.get("channel") == "desktop" else "earth_web"
cid = str(claims.get("cid") or "anon")
await check_sliding_rate_limit(
f"earth:{channel}:{cid}",
limit=_EARTH_SESSION_RATE_LIMIT_PER_MIN,
window_seconds=60,
detail="Earth session rate limit exceeded",
)
return EarthAccessContext(
channel=channel,
actor_key=f"{channel}:{cid}",
)
if settings.effective_earth_api_auth_mode == "enforce":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired Earth session",
)
if settings.effective_earth_api_auth_mode == "enforce":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required",
)
return EarthAccessContext(channel="dev_open", actor_key="dev:open")
return _dependency
async def authenticate_ws_earth_or_api_key(
websocket: WebSocket,
*,
api_key_query: str | None,
earth_token_query: str | None,
db: AsyncSession,
) -> tuple[bool, str | None]:
"""Authenticate non-JWT WebSocket connections via API key or Earth session token.
Returns `(authenticated, actor_id)`. Raises HTTPException on explicit invalid credentials.
"""
raw_api_key = (
(websocket.headers.get(API_KEY_HEADER) or "").strip()
or (api_key_query or "").strip()
)
if raw_api_key:
record = await authenticate_api_key(db, raw_api_key, "ws:connect")
return True, f"api_key:{record.id}"
raw_earth_token = (
(websocket.headers.get(EARTH_TOKEN_HEADER) or "").strip()
or (earth_token_query or "").strip()
or (websocket.cookies.get(EARTH_SESSION_COOKIE) or "").strip()
)
if raw_earth_token:
claims = verify_earth_session_token(raw_earth_token)
if claims is None:
if settings.effective_earth_api_auth_mode == "enforce":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired Earth WebSocket session",
)
return False, None
channel = str(claims.get("channel") or "web")
cid = str(claims.get("cid") or secrets.token_hex(4))
return True, f"earth_{channel}:{cid}"
return False, None
+143 -8
View File
@@ -1,13 +1,34 @@
from functools import lru_cache
from pathlib import Path
from typing import List
import os
from pathlib import Path
from typing import List, Optional
from urllib.parse import quote, urlsplit, urlunsplit
from pydantic_settings import BaseSettings
ROOT_DIR = Path(__file__).parent.parent.parent.parent
VERSION_FILE = ROOT_DIR / "VERSION"
WEAK_SECRET_PLACEHOLDERS = frozenset(
{
"",
"change-me",
"change_me",
"change_me_to_a_random_secret",
"change_me_to_a_random_32_plus_char_secret",
"your-secret-key-change-in-production",
"replace-with-strong-32-char-random-secret",
}
)
WEAK_SERVICE_TOKEN_PLACEHOLDERS = frozenset(
{
"",
"change-me",
"change_me",
"replace-with-internal-token",
}
)
VALID_PLANET_ROLES = frozenset({"all", "api", "worker"})
class Settings(BaseSettings):
@@ -16,23 +37,46 @@ class Settings(BaseSettings):
os.getenv("APP_VERSION")
or (VERSION_FILE.read_text(encoding="utf-8").strip() if VERSION_FILE.exists() else "0.19.0")
)
APP_ENV: str = "development"
PLANET_ROLE: str = "all"
ENABLE_SCHEDULER: Optional[bool] = None
API_V1_STR: str = "/api/v1"
SECRET_KEY: str = "your-secret-key-change-in-production"
ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 0
REFRESH_TOKEN_EXPIRE_DAYS: int = 0
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60
REFRESH_TOKEN_EXPIRE_DAYS: int = 7
SEED_DEFAULT_DEV_USERS: Optional[bool] = None
INITIAL_ADMIN_USERNAME: str = ""
INITIAL_ADMIN_EMAIL: str = ""
INITIAL_ADMIN_PASSWORD: str = ""
SETTINGS_ENCRYPTION_KEY: str = ""
LOGIN_RATE_LIMIT_MAX_ATTEMPTS: int = 10
LOGIN_RATE_LIMIT_WINDOW_SECONDS: int = 300
POSTGRES_SERVER: str = "localhost"
POSTGRES_USER: str = "postgres"
POSTGRES_PASSWORD: str = "postgres"
POSTGRES_DB: str = "planet_db"
DATABASE_URL: str = f"postgresql+asyncpg://postgres:postgres@localhost:5432/planet_db"
DATABASE_URL: str = "postgresql+asyncpg://postgres:postgres@localhost:5432/planet_db"
REDIS_SERVER: str = "localhost"
REDIS_PORT: int = 6379
REDIS_DB: int = 0
REDIS_PASSWORD: str = ""
CORS_ORIGINS: List[str] = ["http://localhost:3000", "http://localhost:8000"]
CORS_ORIGINS: List[str] = [
"http://localhost:3000",
"http://127.0.0.1:3000",
"http://localhost:8000",
"http://127.0.0.1:8000",
"planet://earth",
]
COLLECTOR_MAX_CONCURRENCY: int = 2
COLLECTOR_HEAVY_CONCURRENCY: int = 1
SPACETRACK_USERNAME: str = ""
SPACETRACK_PASSWORD: str = ""
@@ -43,11 +87,66 @@ class Settings(BaseSettings):
AI_PROVIDER_RETRY_ATTEMPTS: int = 2
OBSERVABILITY_INGEST_TOKEN: str = ""
CLIENT_UPDATES_DIR: str = ""
CLIENT_UPDATE_PUBLISH_TOKEN: str = ""
CLIENT_MIN_SHELL_VERSION: str = "0.78.0"
CLIENT_RELEASE_PAGE_URL: str = "https://gitea.rclaw.top/linkong/planet/releases"
EARTH_API_AUTH_MODE: str = ""
EARTH_SESSION_TTL_MINUTES: int = 30
EARTH_WEB_ALLOWED_ORIGINS: List[str] = []
EARTH_DESKTOP_HANDSHAKE_SECRET: str = ""
TURNSTILE_SECRET_KEY: str = ""
@property
def is_production(self) -> bool:
return str(self.APP_ENV or "").strip().lower() == "production"
@property
def effective_earth_api_auth_mode(self) -> str:
raw = str(self.EARTH_API_AUTH_MODE or "").strip().lower()
if raw in {"enforce", "off"}:
return raw
return "enforce" if self.is_production else "off"
@property
def normalized_role(self) -> str:
role = str(self.PLANET_ROLE or "all").strip().lower()
return role if role in VALID_PLANET_ROLES else "all"
@property
def should_run_scheduler(self) -> bool:
if self.ENABLE_SCHEDULER is not None:
return bool(self.ENABLE_SCHEDULER)
return self.normalized_role in {"all", "worker"}
@property
def should_run_workers(self) -> bool:
return self.normalized_role in {"all", "worker"}
@property
def should_seed_default_dev_users(self) -> bool:
if self.SEED_DEFAULT_DEV_USERS is not None:
return bool(self.SEED_DEFAULT_DEV_USERS)
return not self.is_production
@property
def REDIS_URL(self) -> str:
return os.getenv(
"REDIS_URL", f"redis://{self.REDIS_SERVER}:{self.REDIS_PORT}/{self.REDIS_DB}"
raw = os.getenv(
"REDIS_URL",
f"redis://{self.REDIS_SERVER}:{self.REDIS_PORT}/{self.REDIS_DB}",
)
password = str(self.REDIS_PASSWORD or "")
if password:
parsed = urlsplit(raw)
if parsed.scheme in {"redis", "rediss"} and parsed.password is None and parsed.hostname:
user_part = parsed.username or ""
encoded_pw = quote(password, safe="")
netloc = f"{user_part}:{encoded_pw}@{parsed.hostname}"
if parsed.port:
netloc = f"{netloc}:{parsed.port}"
return urlunsplit((parsed.scheme, netloc, parsed.path, parsed.query, parsed.fragment))
return raw
class Config:
env_file = Path(__file__).parent.parent.parent / ".env"
@@ -55,6 +154,42 @@ class Settings(BaseSettings):
extra = "ignore"
def validate_production_security(cfg: Settings) -> None:
"""Fail fast on insecure defaults when APP_ENV=production."""
raw_role = str(cfg.PLANET_ROLE or "all").strip().lower()
if raw_role not in VALID_PLANET_ROLES:
raise RuntimeError(
f"Invalid PLANET_ROLE={cfg.PLANET_ROLE!r}; expected one of {sorted(VALID_PLANET_ROLES)}"
)
if not cfg.is_production:
return
errors: list[str] = []
secret_key = str(cfg.SECRET_KEY or "").strip()
if secret_key in WEAK_SECRET_PLACEHOLDERS or len(secret_key) < 32:
errors.append("SECRET_KEY must be set to a random string of at least 32 characters")
if int(cfg.ACCESS_TOKEN_EXPIRE_MINUTES) <= 0:
errors.append("ACCESS_TOKEN_EXPIRE_MINUTES must be > 0 in production")
if int(cfg.REFRESH_TOKEN_EXPIRE_DAYS) <= 0:
errors.append("REFRESH_TOKEN_EXPIRE_DAYS must be > 0 in production")
if "*" in (cfg.CORS_ORIGINS or []):
errors.append("CORS_ORIGINS must not contain '*' in production")
ai_url = str(cfg.AI_PROVIDER_SERVICE_URL or "").strip()
ai_token = str(cfg.AI_PROVIDER_SERVICE_TOKEN or "").strip()
if ai_url and ai_token in WEAK_SERVICE_TOKEN_PLACEHOLDERS:
errors.append(
"AI_PROVIDER_SERVICE_TOKEN must be configured (not empty or placeholder) in production"
)
if errors:
raise RuntimeError("Production security validation failed: " + "; ".join(errors))
@lru_cache()
def get_settings() -> Settings:
return Settings()
+110
View File
@@ -0,0 +1,110 @@
"""Symmetric encryption helpers for persisted sensitive settings."""
from __future__ import annotations
import base64
from copy import deepcopy
import hashlib
from typing import Any
from cryptography.fernet import Fernet, InvalidToken
from app.core.config import settings
from app.core.logging import get_logger
logger = get_logger(__name__, service="secret_crypto")
ENCRYPTED_PREFIX = "enc:v1:"
ENCRYPTED_CATEGORIES = frozenset({"smtp", "external_integrations"})
SECRET_FIELD_NAMES = frozenset(
{
"api_key",
"service_token",
"client_secret",
"password",
"token",
"access_token",
"bearer_token",
}
)
def _derive_fernet_key(raw_key: str) -> bytes:
cleaned = raw_key.strip()
candidate = cleaned.encode("utf-8")
try:
Fernet(candidate)
return candidate
except Exception:
digest = hashlib.sha256(candidate).digest()
return base64.urlsafe_b64encode(digest)
def _get_fernet() -> Fernet | None:
raw_key = str(getattr(settings, "SETTINGS_ENCRYPTION_KEY", "") or "").strip()
if not raw_key:
return None
return Fernet(_derive_fernet_key(raw_key))
def encrypt_secret(value: str) -> str:
"""Encrypt a secret string when SETTINGS_ENCRYPTION_KEY is configured."""
if not value or value.startswith(ENCRYPTED_PREFIX):
return value
fernet = _get_fernet()
if fernet is None:
return value
token = fernet.encrypt(value.encode("utf-8")).decode("ascii")
return f"{ENCRYPTED_PREFIX}{token}"
def decrypt_secret(value: str) -> str:
"""Decrypt a secret string; transparently passes through legacy plaintext."""
if not value or not value.startswith(ENCRYPTED_PREFIX):
return value
fernet = _get_fernet()
if fernet is None:
logger.warning_event(
"Encrypted setting encountered without SETTINGS_ENCRYPTION_KEY configured",
event="settings.secret.key_missing",
)
return ""
ciphertext = value[len(ENCRYPTED_PREFIX) :].encode("ascii")
try:
return fernet.decrypt(ciphertext).decode("utf-8")
except (InvalidToken, ValueError):
logger.warning_event(
"Failed to decrypt persisted setting secret",
event="settings.secret.decrypt_failed",
)
return ""
def _transform_payload(value: Any, *, encrypt: bool) -> Any:
if isinstance(value, dict):
transformed: dict[str, Any] = {}
for key, item in value.items():
if key in SECRET_FIELD_NAMES and isinstance(item, str):
transformed[key] = encrypt_secret(item) if encrypt else decrypt_secret(item)
else:
transformed[key] = _transform_payload(item, encrypt=encrypt)
return transformed
if isinstance(value, list):
return [_transform_payload(item, encrypt=encrypt) for item in value]
return value
def encrypt_setting_payload(category: str, payload: dict[str, Any]) -> dict[str, Any]:
"""Return a deep copy of payload with sensitive fields encrypted if enabled."""
copied = deepcopy(payload)
if category not in ENCRYPTED_CATEGORIES:
return copied
return _transform_payload(copied, encrypt=True)
def decrypt_setting_payload(category: str, payload: dict[str, Any]) -> dict[str, Any]:
"""Return a deep copy of payload with encrypted sensitive fields decrypted."""
copied = deepcopy(payload)
if category not in ENCRYPTED_CATEGORIES:
return copied
return _transform_payload(copied, encrypt=False)
+197 -7
View File
@@ -1,20 +1,32 @@
import asyncio
from datetime import UTC, datetime, timedelta
from typing import Optional
import hashlib
import time
from typing import Any, Optional
from uuid import uuid4
import bcrypt
import redis
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from jose import JWTError, jwt
import redis
import redis.asyncio as aioredis
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings
from app.core.logging import get_logger
from app.db.session import get_db
from app.models.user import User
logger = get_logger(__name__, service="security")
oauth2_scheme = HTTPBearer()
REVOKED_KEY_PREFIX = "revoked_jwt:"
LOCAL_REVOKED_MAX_ENTRIES = 10_000
REDIS_OP_TIMEOUT_SECONDS = 1.5
_LOCAL_REVOKED_TOKENS: dict[str, float] = {}
class _RedisClient:
_client = None
@@ -23,7 +35,7 @@ class _RedisClient:
def get_client(cls):
if cls._client is None:
redis_url = settings.REDIS_URL
if redis_url.startswith("redis://"):
if redis_url.startswith(("redis://", "rediss://")):
cls._client = redis.from_url(
redis_url,
decode_responses=True,
@@ -35,6 +47,7 @@ class _RedisClient:
host=settings.REDIS_SERVER,
port=settings.REDIS_PORT,
db=settings.REDIS_DB,
password=settings.REDIS_PASSWORD or None,
decode_responses=True,
socket_connect_timeout=2,
socket_timeout=2,
@@ -42,9 +55,95 @@ class _RedisClient:
return cls._client
class _AsyncRedisClient:
_client: aioredis.Redis | None = None
_loop: asyncio.AbstractEventLoop | None = None
@classmethod
def get_client(cls) -> aioredis.Redis:
loop = asyncio.get_running_loop()
if cls._client is None or cls._loop is not loop:
redis_url = settings.REDIS_URL
if redis_url.startswith(("redis://", "rediss://")):
cls._client = aioredis.from_url(
redis_url,
decode_responses=True,
socket_connect_timeout=1.5,
socket_timeout=1.5,
)
else:
cls._client = aioredis.Redis(
host=settings.REDIS_SERVER,
port=settings.REDIS_PORT,
db=settings.REDIS_DB,
password=settings.REDIS_PASSWORD or None,
decode_responses=True,
socket_connect_timeout=1.5,
socket_timeout=1.5,
)
cls._loop = loop
return cls._client
redis_client = _RedisClient.get_client()
def _token_digest(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def _prune_local_revocations(now: float | None = None) -> None:
current = now if now is not None else time.monotonic()
expired = [key for key, deadline in _LOCAL_REVOKED_TOKENS.items() if deadline <= current]
for key in expired:
_LOCAL_REVOKED_TOKENS.pop(key, None)
while len(_LOCAL_REVOKED_TOKENS) > LOCAL_REVOKED_MAX_ENTRIES:
oldest_key = next(iter(_LOCAL_REVOKED_TOKENS))
_LOCAL_REVOKED_TOKENS.pop(oldest_key, None)
def _record_local_revocation(token_digest: str, ttl_seconds: int) -> None:
now = time.monotonic()
_prune_local_revocations(now)
_LOCAL_REVOKED_TOKENS[token_digest] = now + max(60, ttl_seconds)
def _is_locally_revoked(token_digest: str) -> bool:
now = time.monotonic()
deadline = _LOCAL_REVOKED_TOKENS.get(token_digest)
if deadline is None:
return False
if deadline <= now:
_LOCAL_REVOKED_TOKENS.pop(token_digest, None)
return False
return True
def _is_monkeypatched_sync_redis(candidate: Any) -> bool:
if candidate is None:
return False
if not isinstance(candidate, redis.Redis):
return True
return "sismember" in getattr(candidate, "__dict__", {})
def _token_revocation_ttl_seconds(
token: str,
default_ttl: int | None = None,
*,
decoded_payload: dict[str, Any] | None = None,
) -> int:
fallback = default_ttl if default_ttl is not None else max(settings.REFRESH_TOKEN_EXPIRE_DAYS, 7) * 86400
payload = decoded_payload if decoded_payload is not None else decode_token(token)
if payload and payload.get("exp") is not None:
try:
remaining = int(float(payload["exp"]) - datetime.now(UTC).timestamp())
return max(60, remaining)
except (TypeError, ValueError):
pass
return max(60, int(fallback))
def verify_password(plain_password: str, hashed_password: str) -> bool:
return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())
@@ -63,7 +162,7 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -
expire = None
if expire:
to_encode.update({"exp": expire})
to_encode.update({"type": "access"})
to_encode.update({"type": "access", "jti": uuid4().hex})
if "sub" in to_encode:
to_encode["sub"] = str(to_encode["sub"])
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
@@ -74,7 +173,7 @@ def create_refresh_token(data: dict) -> str:
if settings.REFRESH_TOKEN_EXPIRE_DAYS > 0:
expire = datetime.now(UTC) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
to_encode.update({"exp": expire})
to_encode.update({"type": "refresh"})
to_encode.update({"type": "refresh", "jti": uuid4().hex})
if "sub" in to_encode:
to_encode["sub"] = str(to_encode["sub"])
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
@@ -88,6 +187,76 @@ def decode_token(token: str) -> Optional[dict]:
return None
async def revoke_token(token: str, *, ttl_seconds: int | None = None) -> None:
"""Revoke a verified, unexpired JWT in Redis with bounded TTL plus local fallback."""
if not token:
return
payload = decode_token(token)
if payload is None:
return
digest = _token_digest(token)
ttl = _token_revocation_ttl_seconds(
token,
default_ttl=ttl_seconds,
decoded_payload=payload,
)
_record_local_revocation(digest, ttl)
try:
client = _AsyncRedisClient.get_client()
await asyncio.wait_for(
client.set(f"{REVOKED_KEY_PREFIX}{digest}", "1", ex=ttl),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
except Exception as exc:
logger.warning_event(
"Failed to persist revoked token to Redis; kept in local revocation cache",
event="auth.redis_revoke.unavailable",
context={"error": str(exc)},
)
async def is_token_blacklisted(token: str, *, legacy_sync_client: Any = None) -> bool:
"""Check whether a JWT was revoked without blocking the event loop or failing 500 on Redis outage."""
if not token:
return False
digest = _token_digest(token)
if _is_locally_revoked(digest):
return True
for candidate in (legacy_sync_client, redis_client):
if _is_monkeypatched_sync_redis(candidate):
try:
return bool(candidate.sismember("blacklisted_tokens", token))
except Exception as exc:
logger.warning_event(
"Sync token blacklist check failed; degrading safely",
event="auth.redis_blacklist.sync_unavailable",
context={"error": str(exc)},
)
return False
try:
client = _AsyncRedisClient.get_client()
if await asyncio.wait_for(
client.exists(f"{REVOKED_KEY_PREFIX}{digest}"),
timeout=REDIS_OP_TIMEOUT_SECONDS,
):
return True
return bool(
await asyncio.wait_for(
client.sismember("blacklisted_tokens", token),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
)
except Exception as exc:
logger.warning_event(
"Async token blacklist check failed; degrading safely",
event="auth.redis_blacklist.unavailable",
context={"error": str(exc)},
)
return False
async def _load_active_user(user_id: str, db: AsyncSession) -> User:
try:
parsed_id = int(user_id)
@@ -108,7 +277,7 @@ async def get_current_user(
db: AsyncSession = Depends(get_db),
) -> User:
token = credentials.credentials
if redis_client.sismember("blacklisted_tokens", token):
if await is_token_blacklisted(token):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token has been revoked",
@@ -133,6 +302,11 @@ async def get_current_user_refresh(
db: AsyncSession = Depends(get_db),
) -> User:
token = credentials.credentials
if await is_token_blacklisted(token):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token has been revoked",
)
payload = decode_token(token)
if payload is None or payload.get("type") != "refresh":
raise HTTPException(
@@ -149,4 +323,20 @@ async def get_current_user_refresh(
def blacklist_token(token: str) -> None:
redis_client.sadd("blacklisted_tokens", token)
"""Best-effort revocation helper for legacy synchronous callers."""
if not token:
return
payload = decode_token(token)
if payload is None:
return
digest = _token_digest(token)
ttl = _token_revocation_ttl_seconds(token, decoded_payload=payload)
_record_local_revocation(digest, ttl)
try:
redis_client.set(f"{REVOKED_KEY_PREFIX}{digest}", "1", ex=ttl)
except Exception as exc:
logger.warning_event(
"Failed to write sync token revocation to Redis",
event="auth.redis_revoke.sync_unavailable",
context={"error": str(exc)},
)
+112 -20
View File
@@ -24,32 +24,124 @@ class DataBroadcaster:
self._vessel_flush_interval = 1.0
async def get_dashboard_stats(self) -> Dict[str, Any]:
"""Get dashboard statistics"""
return {
"total_datasources": 9,
"active_datasources": 8,
"tasks_today": 45,
"success_rate": 97.8,
"last_updated": to_iso8601_utc(datetime.now(UTC)),
"alerts": {"critical": 0, "warning": 2, "info": 5},
"""Get dashboard statistics from PostgreSQL."""
from sqlalchemy import func, select
from app.core.enums import AlertSeverity, AlertStatus, JobStatus
from app.db.session import async_session_factory
from app.models.alert import Alert
from app.models.datasource import DataSource
from app.models.task import CollectionTask
alerts_summary = {
AlertSeverity.CRITICAL.value: 0,
AlertSeverity.WARNING.value: 0,
AlertSeverity.INFO.value: 0,
}
now_utc = datetime.now(UTC)
today_start = now_utc.replace(hour=0, minute=0, second=0, microsecond=0)
try:
async with async_session_factory() as db:
total_datasources = int(
(await db.scalar(select(func.count(DataSource.id)))) or 0
)
active_datasources = int(
(
await db.scalar(
select(func.count(DataSource.id)).where(DataSource.is_active.is_(True))
)
)
or 0
)
tasks_today = int(
(
await db.scalar(
select(func.count(CollectionTask.id)).where(
CollectionTask.created_at >= today_start
)
)
)
or 0
)
finished_rows = (
await db.execute(
select(CollectionTask.status, func.count(CollectionTask.id))
.where(
CollectionTask.created_at >= today_start,
CollectionTask.status.in_(
[JobStatus.SUCCESS.value, JobStatus.FAILED.value]
),
)
.group_by(CollectionTask.status)
)
).all()
finished_counts = {str(status): int(count) for status, count in finished_rows}
success_count = finished_counts.get(JobStatus.SUCCESS.value, 0)
total_finished = success_count + finished_counts.get(JobStatus.FAILED.value, 0)
success_rate = (
round(success_count * 100.0 / total_finished, 1)
if total_finished > 0
else 100.0
)
alert_rows = (
await db.execute(
select(Alert.severity, func.count(Alert.id))
.where(Alert.status == AlertStatus.ACTIVE)
.group_by(Alert.severity)
)
).all()
for severity, count in alert_rows:
key = severity.value if hasattr(severity, "value") else str(severity).lower()
if key in alerts_summary:
alerts_summary[key] = int(count)
return {
"total_datasources": total_datasources,
"active_datasources": active_datasources,
"tasks_today": tasks_today,
"success_rate": success_rate,
"last_updated": to_iso8601_utc(now_utc),
"alerts": alerts_summary,
}
except Exception as exc:
logger.warning_event(
"Failed to query dashboard stats; returning empty fallback",
event="dashboard.stats.query_failed",
context={"error": str(exc)},
)
return {
"total_datasources": 0,
"active_datasources": 0,
"tasks_today": 0,
"success_rate": 100.0,
"last_updated": to_iso8601_utc(now_utc),
"alerts": alerts_summary,
}
async def broadcast_stats(self, interval: int = 5):
"""Broadcast dashboard stats periodically"""
"""Broadcast dashboard stats periodically only when subscribers are attached."""
while self.running:
try:
stats = await self.get_dashboard_stats()
await manager.broadcast(
{
"type": "data_frame",
"channel": "dashboard",
"timestamp": to_iso8601_utc(datetime.now(UTC)),
"payload": {"stats": stats},
},
channel="dashboard",
if manager.channel_subscriptions.get("dashboard"):
stats = await self.get_dashboard_stats()
await manager.broadcast(
{
"type": "data_frame",
"channel": "dashboard",
"timestamp": to_iso8601_utc(datetime.now(UTC)),
"payload": {"stats": stats},
},
channel="dashboard",
publish=False,
)
except Exception as exc:
logger.warning_event(
"Failed to broadcast dashboard stats",
event="dashboard.stats.broadcast_failed",
context={"error": str(exc)},
)
except Exception:
pass
await asyncio.sleep(interval)
async def broadcast_alert(self, alert: Dict[str, Any]):
+162 -29
View File
@@ -1,26 +1,150 @@
"""WebSocket Connection Manager"""
"""WebSocket Connection Manager with optional cross-replica Redis Pub/Sub relay."""
import asyncio
from contextlib import suppress
from datetime import UTC, datetime
from typing import Any, Dict, Set, Optional
import json
from typing import Any, Dict, Optional, Set
from uuid import uuid4
from fastapi import WebSocket
import redis.asyncio as redis
from app.core.config import settings
from app.core.logging import get_logger
logger = get_logger(__name__, service="websocket")
MAX_VESSEL_SUBSCRIPTION_LIMIT = 5000
MAX_VESSEL_WS_MESSAGE_ITEMS = 1000
MAX_VESSEL_BBOX_AREA = 2500.0
PLANET_WS_PUBSUB_CHANNEL = "planet:ws:broadcast"
def _create_async_redis_client(*, socket_timeout: float = 2.0) -> redis.Redis:
redis_url = settings.REDIS_URL
if redis_url.startswith(("redis://", "rediss://")):
return redis.from_url(
redis_url,
decode_responses=True,
socket_connect_timeout=2.0,
socket_timeout=socket_timeout,
)
return redis.Redis(
host=settings.REDIS_SERVER,
port=settings.REDIS_PORT,
db=settings.REDIS_DB,
password=settings.REDIS_PASSWORD or None,
decode_responses=True,
socket_connect_timeout=2.0,
socket_timeout=socket_timeout,
)
class ConnectionManager:
"""Manages WebSocket connections"""
"""Manages WebSocket connections and cross-replica Pub/Sub fanout."""
def __init__(self):
self.active_connections: Dict[str, Set[WebSocket]] = {} # user_id -> connections
self.active_connections: Dict[str, Set[WebSocket]] = {}
self.channel_subscriptions: Dict[str, Set[WebSocket]] = {}
self.websocket_channels: Dict[WebSocket, Set[str]] = {}
self.vessel_subscriptions: Dict[WebSocket, dict[str, Any]] = {}
self.redis_client: Optional[redis.Redis] = None
self.instance_id: str = uuid4().hex[:12]
self._pubsub_enabled: bool = False
self._pubsub_publish_only: bool = False
self._pubsub_task: Optional[asyncio.Task[Any]] = None
self._pubsub_client: Optional[redis.Redis] = None
async def start_pubsub(self, *, publish_only: bool = False) -> None:
self._pubsub_enabled = True
self._pubsub_publish_only = publish_only
if not publish_only and (self._pubsub_task is None or self._pubsub_task.done()):
self._pubsub_task = asyncio.create_task(self._pubsub_loop())
async def stop_pubsub(self) -> None:
self._pubsub_enabled = False
task = self._pubsub_task
self._pubsub_task = None
if task is not None:
task.cancel()
with suppress(asyncio.CancelledError):
await task
if self._pubsub_client is not None:
with suppress(Exception):
await self._pubsub_client.aclose()
self._pubsub_client = None
async def _publish_pubsub_envelope(self, envelope: dict[str, Any]) -> None:
if not self._pubsub_enabled:
return
try:
if self._pubsub_client is None:
self._pubsub_client = _create_async_redis_client(socket_timeout=2.0)
payload = json.dumps({"origin": self.instance_id, **envelope}, default=str)
await self._pubsub_client.publish(PLANET_WS_PUBSUB_CHANNEL, payload)
except Exception as exc:
logger.warning_event(
"Failed to publish WebSocket broadcast to Redis Pub/Sub",
event="websocket.pubsub.publish_failed",
context={"error": str(exc)},
)
async def handle_pubsub_payload(self, raw_payload: str | bytes) -> bool:
text = raw_payload.decode("utf-8") if isinstance(raw_payload, bytes) else str(raw_payload)
try:
envelope = json.loads(text)
except json.JSONDecodeError:
return False
if not isinstance(envelope, dict):
return False
if envelope.get("origin") == self.instance_id:
return False
kind = envelope.get("kind")
if kind == "channel" and isinstance(envelope.get("message"), dict):
await self._deliver_local_broadcast(
envelope["message"],
channel=str(envelope.get("channel") or "all"),
)
return True
if kind == "vessels" and isinstance(envelope.get("data"), dict):
await self._deliver_local_vessels(envelope["data"])
return True
return False
async def _pubsub_loop(self) -> None:
while self._pubsub_enabled and not self._pubsub_publish_only:
client: Optional[redis.Redis] = None
pubsub = None
try:
client = _create_async_redis_client(socket_timeout=5.0)
pubsub = client.pubsub()
await pubsub.subscribe(PLANET_WS_PUBSUB_CHANNEL)
while self._pubsub_enabled and not self._pubsub_publish_only:
message = await pubsub.get_message(
ignore_subscribe_messages=True,
timeout=1.0,
)
if message and message.get("data") is not None:
await self.handle_pubsub_payload(message["data"])
except asyncio.CancelledError:
raise
except Exception as exc:
logger.warning_event(
"WebSocket Redis Pub/Sub listener reconnecting after error",
event="websocket.pubsub.listener_error",
context={"error": str(exc)},
)
await asyncio.sleep(2.0)
finally:
if pubsub is not None:
with suppress(Exception):
await pubsub.unsubscribe(PLANET_WS_PUBSUB_CHANNEL)
await pubsub.aclose()
if client is not None:
with suppress(Exception):
await client.aclose()
async def connect(self, websocket: WebSocket, user_id: str):
await websocket.accept()
@@ -29,16 +153,7 @@ class ConnectionManager:
self.active_connections[user_id].add(websocket)
if self.redis_client is None:
redis_url = settings.REDIS_URL
if redis_url.startswith("redis://"):
self.redis_client = redis.from_url(redis_url, decode_responses=True)
else:
self.redis_client = redis.Redis(
host=settings.REDIS_SERVER,
port=settings.REDIS_PORT,
db=settings.REDIS_DB,
decode_responses=True,
)
self.redis_client = _create_async_redis_client(socket_timeout=2.0)
def disconnect(self, websocket: WebSocket, user_id: str):
if user_id in self.active_connections:
@@ -129,15 +244,15 @@ class ConnectionManager:
async def send_personal_message(self, message: dict, user_id: str):
if user_id in self.active_connections:
for connection in self.active_connections[user_id]:
for connection in list(self.active_connections[user_id]):
try:
await connection.send_json(message)
except Exception:
pass
async def broadcast(self, message: dict, channel: str = "all"):
async def _deliver_local_broadcast(self, message: dict, channel: str = "all") -> None:
if channel == "all":
for user_id in self.active_connections:
for user_id in list(self.active_connections):
await self.send_personal_message(message, user_id)
else:
for connection in list(self.channel_subscriptions.get(channel, set())):
@@ -146,7 +261,14 @@ class ConnectionManager:
except Exception:
self.unsubscribe_all(connection)
async def broadcast_vessels(self, data: dict[str, Any]):
async def broadcast(self, message: dict, channel: str = "all", *, publish: bool = True):
await self._deliver_local_broadcast(message, channel=channel)
if publish:
await self._publish_pubsub_envelope(
{"kind": "channel", "channel": channel, "message": message}
)
async def _deliver_local_vessels(self, data: dict[str, Any]) -> None:
vessels = data.get("vessels") if isinstance(data, dict) else None
if not isinstance(vessels, list) or not vessels:
return
@@ -158,7 +280,7 @@ class ConnectionManager:
if self._vessel_matches_subscription(vessel, subscription)
]
if subscription.get("scope") != "global":
matched = matched[:subscription["limit"]]
matched = matched[: subscription["limit"]]
if not matched:
continue
subscription["last_sent_at"] = datetime.now(UTC)
@@ -179,16 +301,25 @@ class ConnectionManager:
}
try:
for offset in range(0, len(matched), MAX_VESSEL_WS_MESSAGE_ITEMS):
await connection.send_json({
**message,
"payload": {
**message["payload"],
"vessels": matched[offset:offset + MAX_VESSEL_WS_MESSAGE_ITEMS],
},
})
await connection.send_json(
{
**message,
"payload": {
**message["payload"],
"vessels": matched[offset : offset + MAX_VESSEL_WS_MESSAGE_ITEMS],
},
}
)
except Exception:
self.unsubscribe_all(connection)
async def broadcast_vessels(self, data: dict[str, Any]):
vessels = data.get("vessels") if isinstance(data, dict) else None
if not isinstance(vessels, list) or not vessels:
return
await self._deliver_local_vessels(data)
await self._publish_pubsub_envelope({"kind": "vessels", "data": data})
def _vessel_matches_subscription(
self,
vessel: dict[str, Any],
@@ -211,9 +342,11 @@ class ConnectionManager:
return any(requested_type in type_name for requested_type in requested_types)
async def close_all(self):
for user_id in self.active_connections:
for connection in self.active_connections[user_id]:
await connection.close()
await self.stop_pubsub()
for user_id in list(self.active_connections):
for connection in list(self.active_connections[user_id]):
with suppress(Exception):
await connection.close()
self.active_connections.clear()
self.channel_subscriptions.clear()
self.websocket_channels.clear()
@@ -0,0 +1,13 @@
"""Baseline schema migration matching Base.metadata and init_db DDL."""
from __future__ import annotations
VERSION = "0001"
NAME = "baseline_schema"
async def upgrade(conn) -> None:
"""Create any missing SQLAlchemy baseline tables without altering existing rows."""
from app.db.session import Base
await conn.run_sync(Base.metadata.create_all)
@@ -0,0 +1,18 @@
"""Fix earth table update notify trigger so non-id tables (e.g. vessel_current_state) update cleanly."""
from __future__ import annotations
from sqlalchemy import text
VERSION = "0002"
NAME = "fix_earth_notify_trigger"
async def upgrade(conn) -> None:
"""Replace planet_notify_earth_table_changed_statement without USING (id) on transition tables."""
if getattr(getattr(conn, "dialect", None), "name", "") != "postgresql":
return
from app.db.session import PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL
await conn.execute(text(PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL))
@@ -0,0 +1,23 @@
"""Enforce deferred single-mode publish guard on data_snapshots at commit time."""
from __future__ import annotations
from sqlalchemy import text
VERSION = "0003"
NAME = "enforce_storage_policy_publish_guard"
async def upgrade(conn) -> None:
"""Install deferred storage-policy constraint trigger on PostgreSQL data_snapshots."""
if getattr(getattr(conn, "dialect", None), "name", "") != "postgresql":
return
from app.db.session import (
PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL,
PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_TRIGGER_STATEMENTS,
)
await conn.execute(text(PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL))
for statement in PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_TRIGGER_STATEMENTS:
await conn.execute(text(statement))
@@ -0,0 +1,65 @@
"""Create api_keys table for external and internal UE5 API key authentication."""
from __future__ import annotations
from sqlalchemy import text
VERSION = "0004"
NAME = "add_api_keys_table"
async def upgrade(conn) -> None:
"""Create api_keys table and indexes idempotently across PostgreSQL and SQLite."""
dialect = getattr(getattr(conn, "dialect", None), "name", "")
if dialect == "postgresql":
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS api_keys (
id SERIAL PRIMARY KEY,
name VARCHAR(120) NOT NULL,
key_prefix VARCHAR(32) NOT NULL,
key_hash VARCHAR(64) NOT NULL UNIQUE,
scopes JSONB NOT NULL DEFAULT '[]'::jsonb,
rate_limit_per_minute INTEGER NULL,
expires_at TIMESTAMP WITH TIME ZONE NULL,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_by_user_id INTEGER NULL,
last_used_at TIMESTAMP WITH TIME ZONE NULL,
revoked_at TIMESTAMP WITH TIME ZONE NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
)
"""
)
)
else:
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS api_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(120) NOT NULL,
key_prefix VARCHAR(32) NOT NULL,
key_hash VARCHAR(64) NOT NULL UNIQUE,
scopes JSON NOT NULL DEFAULT '[]',
rate_limit_per_minute INTEGER NULL,
expires_at TIMESTAMP NULL,
is_active BOOLEAN NOT NULL DEFAULT 1,
created_by_user_id INTEGER NULL,
last_used_at TIMESTAMP NULL,
revoked_at TIMESTAMP NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
"""
)
)
await conn.execute(
text("CREATE INDEX IF NOT EXISTS ix_api_keys_key_prefix ON api_keys (key_prefix)")
)
await conn.execute(
text("CREATE UNIQUE INDEX IF NOT EXISTS ix_api_keys_key_hash ON api_keys (key_hash)")
)
await conn.execute(
text("CREATE INDEX IF NOT EXISTS ix_api_keys_is_active ON api_keys (is_active)")
)
@@ -0,0 +1,127 @@
"""Create ai_workflows, ai_workflow_revisions, and ai_workflow_fixtures tables."""
from __future__ import annotations
from sqlalchemy import text
VERSION = "0005"
NAME = "add_ai_workflows"
async def upgrade(conn) -> None:
"""Create workflow management tables and indexes idempotently across PostgreSQL and SQLite."""
dialect = getattr(getattr(conn, "dialect", None), "name", "")
if dialect == "postgresql":
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS ai_workflows (
id SERIAL PRIMARY KEY,
workflow_id VARCHAR(80) NOT NULL UNIQUE,
name VARCHAR(160) NOT NULL,
name_en VARCHAR(160) NOT NULL DEFAULT '',
category VARCHAR(60) NOT NULL DEFAULT 'advisor',
description TEXT NOT NULL DEFAULT '',
description_en TEXT NOT NULL DEFAULT '',
is_default BOOLEAN NOT NULL DEFAULT FALSE,
is_builtin BOOLEAN NOT NULL DEFAULT TRUE,
active_revision INTEGER NOT NULL DEFAULT 1,
published_graph JSONB NOT NULL DEFAULT '{}'::jsonb,
draft_graph JSONB NULL,
updated_by VARCHAR(120) NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
)
"""
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS ai_workflow_revisions (
id SERIAL PRIMARY KEY,
workflow_id VARCHAR(80) NOT NULL,
revision INTEGER NOT NULL,
status VARCHAR(24) NOT NULL DEFAULT 'published',
graph_json JSONB NOT NULL DEFAULT '{}'::jsonb,
change_summary TEXT NOT NULL DEFAULT '',
created_by VARCHAR(120) NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
)
"""
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS ai_workflow_fixtures (
id SERIAL PRIMARY KEY,
workflow_id VARCHAR(80) NOT NULL,
name VARCHAR(160) NOT NULL,
sample_question TEXT NOT NULL DEFAULT '',
context_json JSONB NOT NULL DEFAULT '{}'::jsonb,
created_by VARCHAR(120) NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
)
"""
)
)
else:
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS ai_workflows (
id INTEGER PRIMARY KEY AUTOINCREMENT,
workflow_id VARCHAR(80) NOT NULL UNIQUE,
name VARCHAR(160) NOT NULL,
name_en VARCHAR(160) NOT NULL DEFAULT '',
category VARCHAR(60) NOT NULL DEFAULT 'advisor',
description TEXT NOT NULL DEFAULT '',
description_en TEXT NOT NULL DEFAULT '',
is_default BOOLEAN NOT NULL DEFAULT 0,
is_builtin BOOLEAN NOT NULL DEFAULT 1,
active_revision INTEGER NOT NULL DEFAULT 1,
published_graph JSON NOT NULL DEFAULT '{}',
draft_graph JSON NULL,
updated_by VARCHAR(120) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
"""
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS ai_workflow_revisions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
workflow_id VARCHAR(80) NOT NULL,
revision INTEGER NOT NULL,
status VARCHAR(24) NOT NULL DEFAULT 'published',
graph_json JSON NOT NULL DEFAULT '{}',
change_summary TEXT NOT NULL DEFAULT '',
created_by VARCHAR(120) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
"""
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS ai_workflow_fixtures (
id INTEGER PRIMARY KEY AUTOINCREMENT,
workflow_id VARCHAR(80) NOT NULL,
name VARCHAR(160) NOT NULL,
sample_question TEXT NOT NULL DEFAULT '',
context_json JSON NOT NULL DEFAULT '{}',
created_by VARCHAR(120) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
"""
)
)
await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_ai_workflows_category ON ai_workflows (category)"))
await conn.execute(text("CREATE INDEX IF NOT EXISTS idx_ai_workflow_revisions_wf_rev ON ai_workflow_revisions (workflow_id, revision)"))
await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_ai_workflow_fixtures_wf ON ai_workflow_fixtures (workflow_id)"))
@@ -0,0 +1,30 @@
"""Add bindings JSON/JSONB column to ai_workflows for Earth interaction bindings."""
from __future__ import annotations
from sqlalchemy import text
VERSION = "0006"
NAME = "add_ai_workflow_bindings"
async def upgrade(conn) -> None:
"""Add bindings column to ai_workflows idempotently across PostgreSQL and SQLite."""
dialect = getattr(getattr(conn, "dialect", None), "name", "")
if dialect == "postgresql":
await conn.execute(
text(
"""
ALTER TABLE ai_workflows
ADD COLUMN IF NOT EXISTS bindings JSONB NOT NULL DEFAULT '{}'::jsonb
"""
)
)
return
res = await conn.execute(text("PRAGMA table_info(ai_workflows)"))
columns = {str(row[1]) for row in res.fetchall()}
if columns and "bindings" not in columns:
await conn.execute(
text("ALTER TABLE ai_workflows ADD COLUMN bindings JSON NOT NULL DEFAULT '{}'")
)
@@ -0,0 +1 @@
"""Versioned database migration steps package."""
+217
View File
@@ -0,0 +1,217 @@
"""Versioned schema migration tracker and runner for PostgreSQL/SQLite."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import UTC, datetime
import hashlib
import importlib.util
from pathlib import Path
import re
from typing import Any, Awaitable, Callable
from sqlalchemy import text
from app.core.logging import get_logger
logger = get_logger(__name__, service="migrations")
DEFAULT_STEPS_DIR = Path(__file__).resolve().parent / "migration_steps"
MIGRATION_FILE_RE = re.compile(r"^(?P<version>\d{4})_(?P<slug>[a-z0-9_]+)\.py$")
MIGRATION_LOCK_KEY = (17001613, 4)
CREATE_MIGRATIONS_TABLE_SQL = """
CREATE TABLE IF NOT EXISTS schema_migrations (
version VARCHAR(64) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
checksum VARCHAR(64) NOT NULL,
applied_at TIMESTAMP WITH TIME ZONE NOT NULL
)
"""
@dataclass(frozen=True)
class MigrationStep:
version: str
name: str
checksum: str
path: Path
upgrade: Callable[[Any], Awaitable[None]]
def discover_migrations(steps_dir: Path | None = None) -> list[MigrationStep]:
"""Load ordered migration modules matching NNNN_name.py."""
directory = steps_dir or DEFAULT_STEPS_DIR
if not directory.exists():
return []
steps: list[MigrationStep] = []
for path in sorted(directory.glob("*.py")):
match = MIGRATION_FILE_RE.match(path.name)
if not match:
continue
raw_bytes = path.read_bytes()
checksum = hashlib.sha256(raw_bytes).hexdigest()
module_name = f"planet_migration_{match.group('version')}_{match.group('slug')}"
spec = importlib.util.spec_from_file_location(module_name, path)
if spec is None or spec.loader is None:
raise RuntimeError(f"Could not load migration module: {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
version = str(getattr(module, "VERSION", match.group("version")))
name = str(getattr(module, "NAME", match.group("slug")))
upgrade_fn = getattr(module, "upgrade", None)
if not callable(upgrade_fn):
raise RuntimeError(f"Migration {path.name} does not define callable upgrade(conn)")
steps.append(
MigrationStep(
version=version,
name=name,
checksum=checksum,
path=path,
upgrade=upgrade_fn,
)
)
steps.sort(key=lambda item: item.version)
return steps
async def ensure_migrations_table(conn: Any) -> None:
await conn.execute(text(CREATE_MIGRATIONS_TABLE_SQL))
async def _fetch_applied_map(conn: Any) -> dict[str, tuple[str, str]]:
result = await conn.execute(
text("SELECT version, name, checksum FROM schema_migrations ORDER BY version")
)
return {str(row[0]): (str(row[1]), str(row[2])) for row in result.fetchall()}
async def _record_migration(conn: Any, step: MigrationStep) -> None:
await conn.execute(
text(
"INSERT INTO schema_migrations (version, name, checksum, applied_at) "
"VALUES (:version, :name, :checksum, :applied_at)"
),
{
"version": step.version,
"name": step.name,
"checksum": step.checksum,
"applied_at": datetime.now(UTC),
},
)
async def ensure_baseline_stamped(conn: Any, steps_dir: Path | None = None) -> bool:
"""Ensure schema_migrations exists and stamp baseline 0001 if no version is recorded."""
await ensure_migrations_table(conn)
applied = await _fetch_applied_map(conn)
if applied:
return False
steps = discover_migrations(steps_dir)
if not steps:
return False
baseline = steps[0]
await _record_migration(conn, baseline)
return True
async def get_migration_status(engine: Any, steps_dir: Path | None = None) -> dict[str, Any]:
"""Return applied versions, pending versions, and checksum mismatches."""
steps = discover_migrations(steps_dir)
async with engine.begin() as conn:
await ensure_migrations_table(conn)
applied_map = await _fetch_applied_map(conn)
mismatches: list[dict[str, str]] = []
pending: list[str] = []
for step in steps:
recorded = applied_map.get(step.version)
if recorded is None:
pending.append(step.version)
elif recorded[1] != step.checksum:
mismatches.append(
{
"version": step.version,
"expected": recorded[1],
"actual": step.checksum,
}
)
return {
"applied": sorted(applied_map.keys()),
"pending": pending,
"mismatches": mismatches,
}
async def run_migrations(
engine: Any,
steps_dir: Path | None = None,
*,
verify_checksums: bool = True,
) -> list[str]:
"""Run all pending migrations transactionally under a PostgreSQL advisory lock."""
steps = discover_migrations(steps_dir)
newly_applied: list[str] = []
async with engine.begin() as conn:
if getattr(conn.dialect, "name", "") == "postgresql":
await conn.execute(
text("SELECT pg_advisory_xact_lock(:k1, :k2)"),
{"k1": MIGRATION_LOCK_KEY[0], "k2": MIGRATION_LOCK_KEY[1]},
)
await ensure_migrations_table(conn)
applied_map = await _fetch_applied_map(conn)
for step in steps:
recorded = applied_map.get(step.version)
if recorded is not None:
if verify_checksums and recorded[1] != step.checksum:
raise RuntimeError(
f"Checksum mismatch for already-applied migration {step.version} ({step.name})"
)
continue
logger.info_event(
"Applying database migration",
event="db.migration.applying",
context={"version": step.version, "name": step.name},
)
await step.upgrade(conn)
await _record_migration(conn, step)
newly_applied.append(step.version)
logger.info_event(
"Applied database migration",
event="db.migration.applied",
context={"version": step.version, "name": step.name},
)
return newly_applied
async def stamp_migrations(
engine: Any,
target_version: str,
steps_dir: Path | None = None,
) -> list[str]:
"""Record migrations up to target_version as applied without executing SQL."""
steps = discover_migrations(steps_dir)
known_versions = {step.version for step in steps}
if target_version not in known_versions:
raise ValueError(f"Unknown migration version: {target_version}")
stamped: list[str] = []
async with engine.begin() as conn:
await ensure_migrations_table(conn)
applied_map = await _fetch_applied_map(conn)
for step in steps:
if step.version > target_version:
break
if step.version in applied_map:
continue
await _record_migration(conn, step)
stamped.append(step.version)
return stamped
+409 -155
View File
@@ -1,3 +1,4 @@
from contextlib import asynccontextmanager
from typing import AsyncGenerator
from sqlalchemy import bindparam, text
@@ -28,6 +29,240 @@ async_session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_o
Base = declarative_base()
PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL = """
CREATE OR REPLACE FUNCTION planet_notify_earth_table_changed_statement()
RETURNS trigger AS $$
DECLARE
change_source TEXT;
source_record_count INTEGER;
source_entity_keys TEXT[];
BEGIN
IF TG_OP = 'INSERT' THEN
FOR change_source IN
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) changed_rows
LOOP
SELECT
COUNT(*),
ARRAY(
SELECT DISTINCT COALESCE(
NULLIF(row_data->>'entity_key', ''),
NULLIF(row_data->>'source_id', ''),
NULLIF(row_data->>'incident_key', ''),
NULLIF(row_data->>'id', ''),
NULLIF(row_data->>'mmsi', '')
)
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) rows_for_keys
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
LIMIT 20
)
INTO source_record_count, source_entity_keys
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) rows_for_count
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
PERFORM planet_emit_earth_data_changed_statement(
TG_TABLE_NAME,
TG_OP,
change_source,
source_record_count,
source_entity_keys
);
END LOOP;
ELSIF TG_OP = 'DELETE' THEN
FOR change_source IN
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) changed_rows
LOOP
SELECT
COUNT(*),
ARRAY(
SELECT DISTINCT COALESCE(
NULLIF(row_data->>'entity_key', ''),
NULLIF(row_data->>'source_id', ''),
NULLIF(row_data->>'incident_key', ''),
NULLIF(row_data->>'id', ''),
NULLIF(row_data->>'mmsi', '')
)
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) rows_for_keys
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
LIMIT 20
)
INTO source_record_count, source_entity_keys
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) rows_for_count
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
PERFORM planet_emit_earth_data_changed_statement(
TG_TABLE_NAME,
TG_OP,
change_source,
source_record_count,
source_entity_keys
);
END LOOP;
ELSIF TG_OP = 'UPDATE' THEN
IF TG_TABLE_NAME = 'earth_news_items' THEN
IF NOT EXISTS (
SELECT 1
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) AS current_row
FULL JOIN (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) AS previous_row
ON current_row.row_data->>'id' = previous_row.row_data->>'id'
WHERE (current_row.row_data - 'last_seen_at' - 'updated_at')
IS DISTINCT FROM
(previous_row.row_data - 'last_seen_at' - 'updated_at')
) THEN
RETURN NULL;
END IF;
END IF;
FOR change_source IN
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
FROM (
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
UNION ALL
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
) changed_rows
LOOP
SELECT
COUNT(*),
ARRAY(
SELECT DISTINCT COALESCE(
NULLIF(row_data->>'entity_key', ''),
NULLIF(row_data->>'source_id', ''),
NULLIF(row_data->>'incident_key', ''),
NULLIF(row_data->>'id', ''),
NULLIF(row_data->>'mmsi', '')
)
FROM (
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
UNION ALL
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
) rows_for_keys
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
LIMIT 20
)
INTO source_record_count, source_entity_keys
FROM (
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
UNION ALL
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
) rows_for_count
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
PERFORM planet_emit_earth_data_changed_statement(
TG_TABLE_NAME,
TG_OP,
change_source,
source_record_count,
source_entity_keys
);
END LOOP;
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
"""
PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL = """
CREATE OR REPLACE FUNCTION planet_enforce_storage_policy_on_snapshot_publish()
RETURNS trigger AS $$
DECLARE
is_new_publish BOOLEAN := FALSE;
still_published BOOLEAN := FALSE;
policy_payload JSONB;
global_locked BOOLEAN := FALSE;
default_mode TEXT := 'single';
override_mode TEXT;
effective_mode TEXT := 'single';
has_other_success BOOLEAN := FALSE;
BEGIN
IF TG_OP = 'INSERT' THEN
is_new_publish := COALESCE(NEW.is_current, FALSE) = TRUE OR NEW.status = 'success';
ELSIF TG_OP = 'UPDATE' THEN
is_new_publish := (COALESCE(NEW.is_current, FALSE) = TRUE OR NEW.status = 'success')
AND COALESCE(OLD.is_current, FALSE) = FALSE
AND COALESCE(OLD.status, '') <> 'success';
END IF;
IF NOT is_new_publish THEN
RETURN NULL;
END IF;
SELECT EXISTS (
SELECT 1
FROM data_snapshots
WHERE id = NEW.id
AND (COALESCE(is_current, FALSE) = TRUE OR status = 'success')
)
INTO still_published;
IF NOT still_published THEN
RETURN NULL;
END IF;
PERFORM pg_advisory_xact_lock_shared(17001614, 2);
SELECT payload::jsonb
INTO policy_payload
FROM system_settings
WHERE category = 'collection_storage'
LIMIT 1
FOR SHARE;
IF policy_payload IS NULL THEN
RETURN NULL;
END IF;
global_locked := LOWER(COALESCE(policy_payload->>'global_single_lock', 'false')) IN ('true', '1', 'yes', 'on');
IF global_locked THEN
effective_mode := 'single';
ELSE
default_mode := LOWER(COALESCE(NULLIF(policy_payload->>'default_mode', ''), 'single'));
override_mode := LOWER(COALESCE(NULLIF((policy_payload->'overrides')->>NEW.source, ''), ''));
IF override_mode <> '' THEN
effective_mode := override_mode;
ELSE
effective_mode := default_mode;
END IF;
END IF;
IF effective_mode <> 'single' THEN
RETURN NULL;
END IF;
IF TG_OP = 'INSERT' AND NOT global_locked AND COALESCE(NEW.is_current, FALSE) <> TRUE THEN
RETURN NULL;
END IF;
SELECT EXISTS (
SELECT 1
FROM data_snapshots
WHERE source = NEW.source
AND id IS DISTINCT FROM NEW.id
AND status = 'success'
)
INTO has_other_success;
IF has_other_success THEN
RAISE EXCEPTION 'planet_storage_policy_single_violation: snapshot % for source % cannot be published while single storage mode is active', NEW.id, NEW.source
USING ERRCODE = 'P0001';
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
"""
PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_TRIGGER_STATEMENTS = (
"DROP TRIGGER IF EXISTS tr_planet_enforce_storage_policy_publish ON data_snapshots",
"""
CREATE CONSTRAINT TRIGGER tr_planet_enforce_storage_policy_publish
AFTER INSERT OR UPDATE ON data_snapshots
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW
EXECUTE FUNCTION planet_enforce_storage_policy_on_snapshot_publish()
""",
)
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with async_session_factory() as session:
@@ -39,19 +274,32 @@ async def get_db() -> AsyncGenerator[AsyncSession, None]:
raise
def _is_postgresql_session(session: AsyncSession | None) -> bool:
if session is None or not callable(getattr(session, "get_bind", None)):
return False
try:
bind = session.get_bind()
return getattr(getattr(bind, "dialect", None), "name", "") == "postgresql"
except Exception:
return False
async def seed_default_datasources(session: AsyncSession):
from app.core.datasource_defaults import DEFAULT_DATASOURCES
from app.models.datasource import DataSource
if _is_postgresql_session(session):
await session.execute(text("SELECT pg_advisory_xact_lock(17001613, 6)"))
for source, info in DEFAULT_DATASOURCES.items():
existing = await session.get(DataSource, info["id"])
if existing:
existing.name = info["name"]
existing.source = source
existing.module = info["module"]
existing.priority = info["priority"]
existing.frequency_minutes = info["frequency_minutes"]
existing.collector_class = source
if not existing.source:
existing.source = source
if not existing.module:
existing.module = info["module"]
if not existing.collector_class:
existing.collector_class = source
if existing.config is None:
existing.config = "{}"
continue
@@ -161,29 +409,69 @@ async def ensure_default_admin_user(session: AsyncSession):
from app.core.security import get_password_hash
from app.models.user import User
for default_user in DEFAULT_LOGIN_USERS:
result = await session.execute(
text("SELECT id FROM users WHERE username = :username"),
{"username": default_user["username"]},
)
if result.fetchone():
continue
if _is_postgresql_session(session):
await session.execute(text("SELECT pg_advisory_xact_lock(17001613, 5)"))
session.add(
User(
username=default_user["username"],
email=default_user["email"],
password_hash=get_password_hash(default_user["password"]),
role=default_user["role"],
is_active=True,
email_verified=True,
custom_username = str(settings.INITIAL_ADMIN_USERNAME or "").strip()
custom_password = str(settings.INITIAL_ADMIN_PASSWORD or "").strip()
custom_email = str(settings.INITIAL_ADMIN_EMAIL or "").strip() or (
f"{custom_username}@planet.local" if custom_username else ""
)
if custom_username and custom_password:
existing_custom = (
await session.execute(
text("SELECT id FROM users WHERE username = :username"),
{"username": custom_username},
)
)
).fetchone()
if existing_custom is None:
session.add(
User(
username=custom_username,
email=custom_email,
password_hash=get_password_hash(custom_password),
role="super_admin",
is_active=True,
email_verified=True,
)
)
await session.flush()
if settings.should_seed_default_dev_users:
for default_user in DEFAULT_LOGIN_USERS:
result = await session.execute(
text("SELECT id FROM users WHERE username = :username"),
{"username": default_user["username"]},
)
if result.fetchone():
continue
session.add(
User(
username=default_user["username"],
email=default_user["email"],
password_hash=get_password_hash(default_user["password"]),
role=default_user["role"],
is_active=True,
email_verified=True,
)
)
else:
user_count = (await session.execute(text("SELECT COUNT(*) FROM users"))).scalar() or 0
if int(user_count) == 0:
logger.warning_event(
"No users exist and default dev accounts are disabled in production; configure INITIAL_ADMIN_USERNAME and INITIAL_ADMIN_PASSWORD",
event="auth.bootstrap.no_users",
)
await session.commit()
async def init_db():
import app.models.user # noqa: F401
import app.models.api_key # noqa: F401
import app.models.ai_workflow # noqa: F401
import app.models.gpu_cluster # noqa: F401
import app.models.task # noqa: F401
import app.models.data_snapshot # noqa: F401
@@ -219,6 +507,34 @@ async def init_db():
},
)
async with _init_db_advisory_lock():
await _init_db_ddl_and_seed()
@asynccontextmanager
async def _init_db_advisory_lock():
"""Serialize full DDL + seed startup across concurrent PostgreSQL replicas."""
if getattr(getattr(engine, "dialect", None), "name", "") != "postgresql":
yield
return
async with engine.connect() as base_conn:
lock_conn = await base_conn.execution_options(isolation_level="AUTOCOMMIT")
await lock_conn.execute(text("SELECT pg_advisory_lock(17001613, 4)"))
try:
yield
finally:
try:
await lock_conn.execute(text("SELECT pg_advisory_unlock(17001613, 4)"))
except Exception as exc:
logger.warning_event(
"Failed to release init_db advisory lock cleanly",
event="database.init_db.unlock_failed",
context={"error": str(exc)},
)
async def _init_db_ddl_and_seed():
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
await install_bgp_prefix_geo_functions(conn)
@@ -258,6 +574,7 @@ async def init_db():
ADD COLUMN IF NOT EXISTS previous_record_id INTEGER,
ADD COLUMN IF NOT EXISTS change_type VARCHAR(20),
ADD COLUMN IF NOT EXISTS change_summary JSONB DEFAULT '{}'::jsonb,
ADD COLUMN IF NOT EXISTS content_hash VARCHAR(64),
ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ
"""
)
@@ -367,139 +684,7 @@ async def init_db():
"""
)
)
await conn.execute(
text(
"""
CREATE OR REPLACE FUNCTION planet_notify_earth_table_changed_statement()
RETURNS trigger AS $$
DECLARE
change_source TEXT;
source_record_count INTEGER;
source_entity_keys TEXT[];
BEGIN
IF TG_OP = 'INSERT' THEN
FOR change_source IN
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) changed_rows
LOOP
SELECT
COUNT(*),
ARRAY(
SELECT DISTINCT COALESCE(
NULLIF(row_data->>'entity_key', ''),
NULLIF(row_data->>'source_id', ''),
NULLIF(row_data->>'incident_key', ''),
NULLIF(row_data->>'id', ''),
NULLIF(row_data->>'mmsi', '')
)
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) rows_for_keys
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
LIMIT 20
)
INTO source_record_count, source_entity_keys
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) rows_for_count
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
PERFORM planet_emit_earth_data_changed_statement(
TG_TABLE_NAME,
TG_OP,
change_source,
source_record_count,
source_entity_keys
);
END LOOP;
ELSIF TG_OP = 'DELETE' THEN
FOR change_source IN
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) changed_rows
LOOP
SELECT
COUNT(*),
ARRAY(
SELECT DISTINCT COALESCE(
NULLIF(row_data->>'entity_key', ''),
NULLIF(row_data->>'source_id', ''),
NULLIF(row_data->>'incident_key', ''),
NULLIF(row_data->>'id', ''),
NULLIF(row_data->>'mmsi', '')
)
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) rows_for_keys
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
LIMIT 20
)
INTO source_record_count, source_entity_keys
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) rows_for_count
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
PERFORM planet_emit_earth_data_changed_statement(
TG_TABLE_NAME,
TG_OP,
change_source,
source_record_count,
source_entity_keys
);
END LOOP;
ELSIF TG_OP = 'UPDATE' THEN
IF TG_TABLE_NAME = 'earth_news_items' AND NOT EXISTS (
SELECT 1
FROM new_rows AS current_row
FULL JOIN old_rows AS previous_row USING (id)
WHERE (to_jsonb(current_row) - 'last_seen_at' - 'updated_at')
IS DISTINCT FROM
(to_jsonb(previous_row) - 'last_seen_at' - 'updated_at')
) THEN
RETURN NULL;
END IF;
FOR change_source IN
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
FROM (
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
UNION ALL
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
) changed_rows
LOOP
SELECT
COUNT(*),
ARRAY(
SELECT DISTINCT COALESCE(
NULLIF(row_data->>'entity_key', ''),
NULLIF(row_data->>'source_id', ''),
NULLIF(row_data->>'incident_key', ''),
NULLIF(row_data->>'id', ''),
NULLIF(row_data->>'mmsi', '')
)
FROM (
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
UNION ALL
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
) rows_for_keys
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
LIMIT 20
)
INTO source_record_count, source_entity_keys
FROM (
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
UNION ALL
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
) rows_for_count
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
PERFORM planet_emit_earth_data_changed_statement(
TG_TABLE_NAME,
TG_OP,
change_source,
source_record_count,
source_entity_keys
);
END LOOP;
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
"""
)
)
await conn.execute(text(PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL))
await conn.execute(
text(
"""
@@ -677,6 +862,10 @@ async def init_db():
"DROP TRIGGER IF EXISTS tr_planet_situational_assessments_changed_delete ON situational_assessments",
):
await conn.execute(text(drop_stmt))
if conn.dialect.name == "postgresql":
await conn.execute(text(PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL))
for stmt in PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_TRIGGER_STATEMENTS:
await conn.execute(text(stmt))
await conn.execute(
text(
"""
@@ -722,6 +911,14 @@ async def init_db():
"""
)
)
await conn.execute(
text(
"""
ALTER TABLE ai_workflows
ADD COLUMN IF NOT EXISTS bindings JSONB NOT NULL DEFAULT '{}'::jsonb
"""
)
)
await conn.execute(
text(
"""
@@ -866,6 +1063,58 @@ async def init_db():
"""
)
)
duplicate_current_exists = (
await conn.execute(
text(
"""
SELECT 1
FROM collected_data
WHERE COALESCE(is_current, TRUE) = TRUE
AND deleted_at IS NULL
AND entity_key IS NOT NULL
GROUP BY source, entity_key
HAVING COUNT(*) > 1
LIMIT 1
"""
)
)
).fetchone() is not None
if duplicate_current_exists:
# Demote older duplicate is_current rows safely; never delete existing dev history.
await conn.execute(
text(
"""
WITH ranked AS (
SELECT id,
ROW_NUMBER() OVER (
PARTITION BY source, entity_key
ORDER BY collected_at DESC NULLS LAST, id DESC
) AS rn
FROM collected_data
WHERE COALESCE(is_current, TRUE) = TRUE
AND deleted_at IS NULL
AND entity_key IS NOT NULL
)
UPDATE collected_data
SET is_current = FALSE
WHERE id IN (SELECT id FROM ranked WHERE rn > 1)
"""
)
)
await conn.execute(
text(
"""
CREATE UNIQUE INDEX IF NOT EXISTS uq_collected_data_current_entity
ON collected_data (source, entity_key)
WHERE COALESCE(is_current, TRUE) = TRUE
AND deleted_at IS NULL
AND entity_key IS NOT NULL
"""
)
)
from app.db.migrations import ensure_baseline_stamped
await ensure_baseline_stamped(conn)
async with async_session_factory() as session:
from app.services.bgp_collector_locations import (
@@ -874,9 +1123,14 @@ async def init_db():
from app.services.compute_center_locations import (
seed_compute_center_locations_from_source_coords,
)
from app.services.storage_policy import ensure_default_storage_policy
await seed_default_bgp_collector_locations(session)
await seed_compute_center_locations_from_source_coords(session)
await seed_default_datasources(session)
await purge_legacy_earth_boundary_datasources(session)
await ensure_default_admin_user(session)
await ensure_default_storage_policy(session)
from app.services.ai.workflow_registry import ensure_builtin_workflows
await ensure_builtin_workflows(session)
+191 -36
View File
@@ -1,44 +1,58 @@
import asyncio
from contextlib import asynccontextmanager
from pathlib import Path
from uuid import uuid4
from fastapi import FastAPI
from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
from starlette.middleware.base import BaseHTTPMiddleware
from app.api.main import api_router
from app.api.v1 import websocket
from app.core.config import settings
from app.core.logging import configure_logging
from app.core.config import settings, validate_production_security
from app.core.logging import configure_logging, get_logger
from app.core.request_context import set_request_id
from app.core.security import _AsyncRedisClient, get_current_user
from app.core.websocket.broadcaster import broadcaster
from app.db.session import init_db
from app.services.scheduler import (
cleanup_stale_running_tasks,
start_scheduler,
stop_scheduler,
sync_scheduler_with_datasources,
from app.core.websocket.manager import manager
from app.db.session import async_session_factory, init_db
from app.models.user import User
from app.services.data_jobs import start_data_job_worker, stop_data_job_worker
from app.services.earth_db_change_listener import (
start_earth_db_change_listener,
stop_earth_db_change_listener,
)
from app.services.earth_news_worker import (
start_earth_news_target_worker,
stop_earth_news_target_worker,
)
from app.services.earth_db_change_listener import (
start_earth_db_change_listener,
stop_earth_db_change_listener,
from app.services.scheduler import (
acquire_scheduler_leader_lock,
cleanup_stale_running_tasks,
release_scheduler_leader_lock,
start_scheduler,
stop_scheduler,
sync_scheduler_with_datasources,
)
from app.services.data_jobs import start_data_job_worker, stop_data_job_worker
configure_logging()
logger = get_logger(__name__, service="main")
class WebSocketCORSMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
if request.url.path.startswith("/ws") and request.method == "GET":
response = await call_next(request)
response.headers["Access-Control-Allow-Origin"] = "*"
allow_origins = settings.CORS_ORIGINS or []
origin = request.headers.get("origin")
if "*" in allow_origins:
response.headers["Access-Control-Allow-Origin"] = "*"
elif origin and origin in allow_origins:
response.headers["Access-Control-Allow-Origin"] = origin
response.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "*"
return response
@@ -59,20 +73,107 @@ class RequestContextMiddleware(BaseHTTPMiddleware):
@asynccontextmanager
async def lifespan(app: FastAPI):
validate_production_security(settings)
await init_db()
await cleanup_stale_running_tasks()
start_scheduler()
await sync_scheduler_with_datasources()
broadcaster.start()
start_data_job_worker()
start_earth_db_change_listener()
start_earth_news_target_worker()
yield
await stop_earth_news_target_worker()
await stop_earth_db_change_listener()
await stop_data_job_worker()
broadcaster.stop()
stop_scheduler()
pubsub_started = False
leader_lock_acquired = False
scheduler_started = False
workers_started = False
broadcaster_started = False
listener_started = False
try:
await manager.start_pubsub()
pubsub_started = True
if settings.should_run_scheduler:
if await acquire_scheduler_leader_lock():
leader_lock_acquired = True
await cleanup_stale_running_tasks()
start_scheduler()
scheduler_started = True
await sync_scheduler_with_datasources()
else:
logger.warning_event(
"Scheduler leader lock held by another instance; skipping scheduler startup",
event="scheduler.leader_lock.skipped",
context={"role": settings.normalized_role},
)
if settings.should_run_workers:
start_data_job_worker()
start_earth_news_target_worker()
workers_started = True
broadcaster.start()
broadcaster_started = True
start_earth_db_change_listener()
listener_started = True
yield
finally:
if listener_started:
try:
await stop_earth_db_change_listener()
except Exception as exc:
logger.warning_event(
"Failed stopping earth db change listener during shutdown",
event="app.shutdown.listener_error",
context={"error": str(exc)},
)
if broadcaster_started:
try:
broadcaster.stop()
except Exception as exc:
logger.warning_event(
"Failed stopping broadcaster during shutdown",
event="app.shutdown.broadcaster_error",
context={"error": str(exc)},
)
if workers_started:
try:
await stop_earth_news_target_worker()
except Exception as exc:
logger.warning_event(
"Failed stopping earth news worker during shutdown",
event="app.shutdown.earth_news_error",
context={"error": str(exc)},
)
try:
await stop_data_job_worker()
except Exception as exc:
logger.warning_event(
"Failed stopping data job worker during shutdown",
event="app.shutdown.data_job_error",
context={"error": str(exc)},
)
if scheduler_started:
try:
stop_scheduler()
except Exception as exc:
logger.warning_event(
"Failed stopping scheduler during shutdown",
event="app.shutdown.scheduler_error",
context={"error": str(exc)},
)
if leader_lock_acquired:
try:
await release_scheduler_leader_lock()
except Exception as exc:
logger.warning_event(
"Failed releasing scheduler leader lock during shutdown",
event="app.shutdown.leader_lock_error",
context={"error": str(exc)},
)
if pubsub_started:
try:
await manager.stop_pubsub()
except Exception as exc:
logger.warning_event(
"Failed stopping pubsub during shutdown",
event="app.shutdown.pubsub_error",
context={"error": str(exc)},
)
app = FastAPI(
@@ -81,14 +182,35 @@ app = FastAPI(
description="智能星球计划 - 态势感知系统\n\n## 功能模块\n\n- **用户认证**: JWT-based authentication\n- **数据源管理**: 多源数据采集器管理\n- **任务调度**: 定时任务调度与监控\n- **实时更新**: WebSocket实时数据推送\n- **告警系统**: 多级告警管理\n\n## 数据层级\n\n- **L1**: 核心数据 (TOP500, Epoch AI GPU)\n- **L2**: 扩展数据 (HuggingFace, PeeringDB, 海缆)\n- **L3**: 分析数据\n- **L4**: 决策支持",
lifespan=lifespan,
docs_url=None,
redoc_url="/docs",
openapi_url="/openapi.json",
redoc_url=None if settings.is_production else "/docs",
openapi_url=None if settings.is_production else "/openapi.json",
)
class NonStreamingGZipMiddleware:
"""Apply GZip compression while skipping SSE streaming responses so events flush immediately."""
def __init__(self, app, minimum_size: int = 1024) -> None:
self.app = app
self.gzip_app = GZipMiddleware(app, minimum_size=minimum_size)
async def __call__(self, scope, receive, send) -> None:
if scope.get("type") == "http":
path = str(scope.get("path") or "")
headers = dict(scope.get("headers") or [])
accept = headers.get(b"accept", b"").lower()
if path.endswith("/stream") or b"text/event-stream" in accept:
await self.app(scope, receive, send)
return
await self.gzip_app(scope, receive, send)
app.add_middleware(NonStreamingGZipMiddleware, minimum_size=1024)
configured_origins = list(settings.CORS_ORIGINS or [])
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_origins=configured_origins,
allow_credentials="*" not in configured_origins and bool(configured_origins),
allow_methods=["*"],
allow_headers=["*"],
)
@@ -113,18 +235,51 @@ async def health_check():
return {"status": "healthy", "version": settings.VERSION}
@app.get("/health/live")
async def health_live():
return {"status": "alive", "version": settings.VERSION, "role": settings.normalized_role}
@app.get("/health/ready")
async def health_ready():
checks = {"database": "error", "redis": "error"}
try:
async with async_session_factory() as db:
await asyncio.wait_for(db.execute(text("SELECT 1")), timeout=2.0)
checks["database"] = "ok"
except Exception:
checks["database"] = "error"
try:
client = _AsyncRedisClient.get_client()
pong = await asyncio.wait_for(client.ping(), timeout=2.0)
checks["redis"] = "ok" if pong else "error"
except Exception:
checks["redis"] = "error"
all_ok = all(value == "ok" for value in checks.values())
payload = {
"status": "ready" if all_ok else "degraded",
"version": settings.VERSION,
"role": settings.normalized_role,
"checks": checks,
}
if not all_ok:
return JSONResponse(status_code=503, content=payload)
return payload
@app.get("/")
async def root():
return {
"name": settings.PROJECT_NAME,
"version": settings.VERSION,
"docs": "/docs",
"redoc": "/redoc",
"docs": None if settings.is_production else "/docs",
}
@app.get("/api/v1/scheduler/jobs")
async def get_scheduler_jobs():
async def get_scheduler_jobs(_current_user: User = Depends(get_current_user)):
from app.services.scheduler import get_scheduler_jobs
return {"jobs": get_scheduler_jobs()}
return {"jobs": get_scheduler_jobs()}
+6
View File
@@ -1,4 +1,6 @@
from app.models.user import User
from app.models.api_key import ApiKey
from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision
from app.models.gpu_cluster import GPUCluster
from app.models.task import CollectionTask
from app.models.data_snapshot import DataSnapshot
@@ -29,6 +31,10 @@ from app.models.situational_assessment import (
)
__all__ = [
"AIWorkflow",
"AIWorkflowFixture",
"AIWorkflowRevision",
"ApiKey",
"User",
"GPUCluster",
"CollectionTask",
+114
View File
@@ -0,0 +1,114 @@
"""Persistent AI workflow definitions, versioned revisions, and local test fixtures."""
from __future__ import annotations
from sqlalchemy import Boolean, Column, DateTime, Index, Integer, JSON, String, Text
from sqlalchemy.sql import func
from app.core.time import to_iso8601_utc
from app.db.session import Base
class AIWorkflow(Base):
"""Managed AI Advisor workflow graph (published + optional draft revision)."""
__tablename__ = "ai_workflows"
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
workflow_id = Column(String(80), nullable=False, unique=True, index=True)
name = Column(String(160), nullable=False)
name_en = Column(String(160), nullable=False, default="")
category = Column(String(60), nullable=False, default="advisor", index=True)
description = Column(Text, nullable=False, default="")
description_en = Column(Text, nullable=False, default="")
is_default = Column(Boolean, nullable=False, default=False, index=True)
is_builtin = Column(Boolean, nullable=False, default=True)
active_revision = Column(Integer, nullable=False, default=1)
published_graph = Column(JSON, nullable=False, default=dict)
draft_graph = Column(JSON(none_as_null=True), nullable=True)
bindings = Column(JSON, nullable=False, default=dict)
updated_by = Column(String(120), nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
updated_at = Column(
DateTime(timezone=True),
server_default=func.now(),
onupdate=func.now(),
nullable=False,
)
def to_dict(self) -> dict:
return {
"id": self.id,
"workflow_id": self.workflow_id,
"name": self.name,
"name_en": self.name_en or self.name,
"category": self.category,
"description": self.description or "",
"description_en": self.description_en or self.description or "",
"is_default": bool(self.is_default),
"is_builtin": bool(self.is_builtin),
"active_revision": int(self.active_revision or 1),
"has_draft": self.draft_graph is not None,
"published_graph": self.published_graph or {},
"draft_graph": self.draft_graph,
"bindings": self.bindings or {},
"updated_by": self.updated_by,
"created_at": to_iso8601_utc(self.created_at),
"updated_at": to_iso8601_utc(self.updated_at),
}
class AIWorkflowRevision(Base):
"""Immutable revision history for AI workflows enabling safe rollback."""
__tablename__ = "ai_workflow_revisions"
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
workflow_id = Column(String(80), nullable=False, index=True)
revision = Column(Integer, nullable=False)
status = Column(String(24), nullable=False, default="published", index=True)
graph_json = Column(JSON, nullable=False, default=dict)
change_summary = Column(Text, nullable=False, default="")
created_by = Column(String(120), nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
__table_args__ = (
Index("idx_ai_workflow_revisions_wf_rev", "workflow_id", "revision"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"workflow_id": self.workflow_id,
"revision": int(self.revision),
"status": self.status,
"graph_json": self.graph_json or {},
"change_summary": self.change_summary or "",
"created_by": self.created_by,
"created_at": to_iso8601_utc(self.created_at),
}
class AIWorkflowFixture(Base):
"""Explicitly saved anonymized regression test fixture for an AI workflow."""
__tablename__ = "ai_workflow_fixtures"
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
workflow_id = Column(String(80), nullable=False, index=True)
name = Column(String(160), nullable=False)
sample_question = Column(Text, nullable=False, default="")
context_json = Column(JSON, nullable=False, default=dict)
created_by = Column(String(120), nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
def to_dict(self) -> dict:
return {
"id": self.id,
"workflow_id": self.workflow_id,
"name": self.name,
"sample_question": self.sample_question or "",
"context_json": self.context_json or {},
"created_by": self.created_by,
"created_at": to_iso8601_utc(self.created_at),
}
+30
View File
@@ -0,0 +1,30 @@
"""Database model for internal/external API keys."""
from __future__ import annotations
from sqlalchemy import Boolean, Column, DateTime, Integer, JSON, String
from sqlalchemy.sql import func
from app.db.session import Base
class ApiKey(Base):
"""Hashed API key for UE5, internal scripts, and external partner integrations."""
__tablename__ = "api_keys"
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
name = Column(String(120), nullable=False)
key_prefix = Column(String(32), nullable=False, index=True)
key_hash = Column(String(64), nullable=False, unique=True, index=True)
scopes = Column(JSON, nullable=False, default=list)
rate_limit_per_minute = Column(Integer, nullable=True)
expires_at = Column(DateTime(timezone=True), nullable=True)
is_active = Column(Boolean, nullable=False, default=True, index=True)
created_by_user_id = Column(Integer, nullable=True)
last_used_at = Column(DateTime(timezone=True), nullable=True)
revoked_at = Column(DateTime(timezone=True), nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
def __repr__(self) -> str:
return f"<ApiKey id={self.id} name={self.name!r} prefix={self.key_prefix!r}>"
+1
View File
@@ -43,6 +43,7 @@ class CollectedData(Base):
previous_record_id = Column(Integer, ForeignKey("collected_data.id"), nullable=True, index=True)
change_type = Column(String(20), nullable=True)
change_summary = Column(JSON, default={})
content_hash = Column(String(64), nullable=True)
deleted_at = Column(DateTime(timezone=True), nullable=True)
# Indexes for common queries
+31 -2
View File
@@ -1,9 +1,30 @@
from typing import Any
from typing import Any, Literal
from pydantic import BaseModel, Field
from app.core.enums import PlaygroundMessageKind, PlaygroundMessageRole, PlaygroundMessageStatus
class ChatMessage(BaseModel):
role: Literal["user", "assistant", "tool"]
content: str = Field(default="", max_length=24000)
tool_call_id: str | None = Field(default=None, max_length=200)
name: str | None = Field(default=None, max_length=200)
tool_calls: list[dict[str, Any]] | None = None
class ToolCallRecord(BaseModel):
id: str
name: str
arguments: dict[str, Any] = Field(default_factory=dict)
class ImageAttachment(BaseModel):
mime_type: str = Field(..., pattern=r"^image/(png|jpeg|jpg|webp|gif)$")
data_base64: str = Field(..., min_length=8, max_length=6_000_000)
name: str = Field(default="", max_length=200)
class AIContentBlock(BaseModel):
type: str
text: str | None = None
@@ -14,13 +35,19 @@ class AIContentBlock(BaseModel):
class SituationalAnalysisRequest(BaseModel):
title: str = Field(..., min_length=1, max_length=200)
objective: str = Field(..., min_length=1, max_length=20000)
objective: str = Field(..., min_length=1, max_length=24000)
context: dict[str, Any] = Field(default_factory=dict)
observations: list[str] = Field(default_factory=list)
constraints: list[str] = Field(default_factory=list)
system_prompt: str | None = Field(default=None, max_length=8000)
preferred_model: str | None = Field(default=None, max_length=200)
thinking: dict[str, Any] | None = None
messages: list[ChatMessage] = Field(default_factory=list, max_length=48)
tools: list[dict[str, Any]] | None = None
tool_choice: str | dict[str, Any] | None = None
response_format: dict[str, Any] | None = None
native_web_search: bool = False
images: list[ImageAttachment] = Field(default_factory=list, max_length=8)
class BGPBriefRequest(BaseModel):
@@ -49,6 +76,8 @@ class SituationalAnalysisResponse(BaseModel):
content_blocks: list[AIContentBlock] = Field(default_factory=list)
text_blocks: list[str] = Field(default_factory=list)
thinking_blocks: list[str] = Field(default_factory=list)
tool_calls: list[ToolCallRecord] = Field(default_factory=list)
stop_reason: str | None = None
raw_response: dict[str, Any] = Field(default_factory=dict)
+1
View File
@@ -8,6 +8,7 @@ class Token(BaseModel):
access_token: str
token_type: str = "bearer"
expires_in: Optional[int] = None
refresh_token: Optional[str] = None
user: dict
+12 -12
View File
@@ -19,7 +19,13 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.enums import UserRole
from app.core.logging import get_logger
from app.core.security import _load_active_user, decode_token, get_current_user, redis_client
from app.core.security import (
_load_active_user,
decode_token,
get_current_user,
is_token_blacklisted,
redis_client,
)
from app.db.session import get_db
from app.models.situational_assessment import WorkflowRun
from app.models.system_setting import SystemSetting
@@ -130,17 +136,11 @@ async def _try_load_bearer_user(
if credentials is None or not credentials.credentials:
return None
token = credentials.credentials
try:
if redis_client.sismember("blacklisted_tokens", token):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token has been revoked",
)
except HTTPException:
raise
except Exception:
# Redis offline in unit tests should not block valid JWT verification
pass
if await is_token_blacklisted(token, legacy_sync_client=redis_client):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token has been revoked",
)
payload = decode_token(token)
if payload is None or payload.get("type") != "access" or payload.get("sub") is None:
@@ -0,0 +1,209 @@
"""Multi-turn conversation sanitization, rolling compaction, and lightweight memory formatting."""
from __future__ import annotations
import asyncio
from typing import Any
from app.core.logging import get_logger
from app.schemas.ai import SituationalAnalysisRequest
from app.services.ai.thinking_sanitizer import prepare_situational_ai_call, strip_thinking_text
from app.services.ai_client import AIProviderClient
logger = get_logger(__name__, service="ai_memory")
RECENT_WINDOW_TURNS = 4
COMPACT_TRIGGER_CHARS = 7500
MAX_MESSAGE_CHARS = 1800
MAX_SUMMARY_CHARS = 1600
MAX_MEMORY_NOTES = 12
MAX_PINNED_SUMMARIES = 8
def _truncate_text(text: str, limit: int) -> str:
cleaned = str(text or "").strip()
if len(cleaned) <= limit:
return cleaned
return f"{cleaned[: max(0, limit - 1)].rstrip()}…"
def sanitize_history_messages(raw_messages: list[Any] | None) -> list[dict[str, str]]:
"""Strip inline thinking blocks, truncate extremes, and normalize alternating user/assistant turns."""
normalized: list[dict[str, str]] = []
for item in raw_messages or []:
if isinstance(item, dict):
role = str(item.get("role") or "").strip().lower()
raw_content = item.get("content")
else:
role = str(getattr(item, "role", "") or "").strip().lower()
raw_content = getattr(item, "content", "")
if role not in {"user", "assistant"}:
continue
content = str(raw_content or "").strip()
if not content:
continue
if role == "assistant":
clean_content, _ = strip_thinking_text(content)
content = clean_content or content
content = _truncate_text(content, MAX_MESSAGE_CHARS)
if not content:
continue
if not normalized and role == "assistant":
continue
if normalized and normalized[-1]["role"] == role:
merged = f"{normalized[-1]['content']}\n\n{content}"
normalized[-1]["content"] = _truncate_text(merged, MAX_MESSAGE_CHARS)
else:
normalized.append({"role": role, "content": content})
return normalized
def _sanitize_short_list(items: list[Any] | None, *, max_items: int, max_chars: int = 200) -> list[str]:
result: list[str] = []
seen: set[str] = set()
for raw in items or []:
text = _truncate_text(str(raw or "").replace("\r", " ").replace("\n", " "), max_chars)
if not text or text in seen:
continue
seen.add(text)
result.append(text)
if len(result) >= max_items:
break
return result
def sanitize_memory_notes(notes: list[Any] | None) -> list[str]:
"""Return deduplicated short user memory notes within configured cap."""
return _sanitize_short_list(notes, max_items=MAX_MEMORY_NOTES)
def sanitize_pinned_summaries(items: list[Any] | None) -> list[str]:
"""Return deduplicated short pinned comparison summaries within configured cap."""
return _sanitize_short_list(items, max_items=MAX_PINNED_SUMMARIES)
def build_deterministic_compaction_summary(
existing_summary: str,
dropped_messages: list[dict[str, str]],
) -> str:
"""Build a bounded structured summary when older turns overflow the active window."""
lines: list[str] = []
prior = str(existing_summary or "").strip()
if prior:
lines.append(prior)
pair_lines: list[str] = []
idx = 0
while idx < len(dropped_messages):
msg = dropped_messages[idx]
if msg["role"] == "user":
q = _truncate_text(msg["content"].replace("\n", " "), 120)
a = ""
if idx + 1 < len(dropped_messages) and dropped_messages[idx + 1]["role"] == "assistant":
a = _truncate_text(dropped_messages[idx + 1]["content"].replace("\n", " "), 180)
idx += 2
else:
idx += 1
pair_lines.append(f"- 问:{q}" + (f" → 结:{a}" if a else ""))
else:
a = _truncate_text(msg["content"].replace("\n", " "), 160)
pair_lines.append(f"- 历史结论:{a}")
idx += 1
if pair_lines:
block = "\n".join(pair_lines)
if prior and not prior.startswith("### 前序对话摘要"):
lines = [f"### 前序对话摘要\n{prior}", block]
elif prior:
lines = [prior, block]
else:
lines = [f"### 前序对话摘要\n{block}"]
combined = "\n".join(lines).strip()
if len(combined) > MAX_SUMMARY_CHARS:
head = "### 前序对话摘要\n"
tail_budget = MAX_SUMMARY_CHARS - len(head) - 2
combined = f"{head}…{combined[-tail_budget:].lstrip()}"
return combined
async def compact_conversation_history(
raw_messages: list[Any] | None,
existing_summary: str = "",
*,
ai_client: AIProviderClient | None = None,
ai_ready: bool = False,
recent_window_turns: int = RECENT_WINDOW_TURNS,
char_budget: int = COMPACT_TRIGGER_CHARS,
) -> dict[str, Any]:
"""Keep recent window verbatim and compact overflow turns into a rolling summary."""
sanitized = sanitize_history_messages(raw_messages)
summary = _truncate_text(existing_summary or "", MAX_SUMMARY_CHARS)
keep_limit = max(2, recent_window_turns * 2)
split_idx = max(0, len(sanitized) - keep_limit)
if split_idx < len(sanitized) and sanitized[split_idx]["role"] == "assistant":
split_idx += 1
older = sanitized[:split_idx]
recent = sanitized[split_idx:]
total_chars = len(summary) + sum(len(m["content"]) for m in recent)
while not older and total_chars > char_budget and len(recent) > 2:
move_count = 2 if (len(recent) >= 4 and recent[0]["role"] == "user" and recent[1]["role"] == "assistant") else 1
older.extend(recent[:move_count])
recent = recent[move_count:]
total_chars = len(summary) + sum(len(m["content"]) for m in recent)
if not older:
return {
"summary": summary,
"recent_messages": recent,
"compacted": False,
"compacted_count": 0,
}
next_summary = ""
if ai_ready and ai_client is not None:
try:
effective_client = ai_client
if type(ai_client) is AIProviderClient and ai_client.llm_config:
effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=900)
transcript = "\n".join(
f"{'用户' if m['role'] == 'user' else 'AI 参谋'}: {m['content']}" for m in older
)
compact_req = SituationalAnalysisRequest(
title="Planet 多轮对话上下文压缩摘要",
objective=(
"请将以下较早的多轮对话与既有摘要压缩为简明中文备忘(不超过 280 字),"
"保留:1) 用户聚焦的图层/国家/新闻实体与口径边界;2) 已核验关键数据结论;"
"3) 尚未完结的追问线索。严禁保留客套或编造数值。"
),
system_prompt="你是精准的对话上下文压缩器,只输出精炼中文要点摘要。",
context={
"existing_summary": summary or None,
"archived_dialogue": transcript,
},
thinking=None,
)
resp = await asyncio.wait_for(effective_client.analyze(compact_req), timeout=12.0)
clean_resp, _ = strip_thinking_text(str(getattr(resp, "content", "") or ""))
next_summary = _truncate_text(clean_resp, MAX_SUMMARY_CHARS)
except asyncio.CancelledError:
raise
except Exception as exc:
logger.warning_event(
"LLM conversation compaction fell back to deterministic summary",
event="ai_memory.compaction.fallback",
context={"error": str(exc), "older_count": len(older)},
)
if not next_summary:
next_summary = build_deterministic_compaction_summary(summary, older)
return {
"summary": next_summary,
"recent_messages": recent,
"compacted": True,
"compacted_count": len(older),
}
+823
View File
@@ -0,0 +1,823 @@
"""Lightweight topological DAG workflow executor for AI Advisor and Earth Copilot."""
from __future__ import annotations
import asyncio
from collections import defaultdict, deque
import json
import re
from typing import Any, AsyncIterator
from app.core.logging import get_logger
from app.schemas.ai import ChatMessage, ImageAttachment, SituationalAnalysisRequest
from app.services.ai.thinking_sanitizer import strip_thinking_text
from app.services.ai.tool_registry import (
TimeBasis,
isolate_untrusted_external_text,
query_bgp_incidents_tool,
query_cable_posture_tool,
query_compute_posture_tool,
query_global_situational_tool,
query_recent_earth_news_tool,
query_satellite_posture_tool,
query_vessel_posture_tool,
safe_web_fetch,
)
from app.services.ai.workflow_registry import MAX_WORKFLOW_NODES
from app.services.compute_center_locations import build_compute_center_location_query
from app.services.location.agent_resolver import run_l1_structured_facility_resolvers
logger = get_logger(__name__, service="ai_dag_executor")
_TEMPLATE_VAR_RE = re.compile(r"\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}")
_L1_KNOWLEDGE_TOOL_IDS = frozenset(
{"builds_upon_inherit", "wikidata_lookup", "peeringdb_fac_lookup", "ror_lookup"}
)
def summarize_targets(targets: list[dict[str, Any]] | None) -> str:
"""Format selected Earth targets into a concise deterministic summary."""
if not targets:
return "全球多域当前态势"
parts: list[str] = []
for item in targets[:8]:
etype = str(item.get("entity_type") or item.get("type") or "entity").strip()
label = str(item.get("label") or item.get("name") or item.get("entity_id") or "").strip()
lat = item.get("latitude")
lon = item.get("longitude")
coord = ""
if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
coord = f"({lat:.2f}, {lon:.2f})"
token = f"{etype}「{label or etype}」{coord}"
parts.append(token)
return "; ".join(parts)
def render_workflow_template(
template: str,
*,
question: str = "",
targets: list[dict[str, Any]] | None = None,
node_outputs: dict[str, str] | None = None,
) -> str:
"""Interpolate `{{...}}` placeholders safely without Python `.format` or eval."""
raw = str(template or "")
if not raw or "{{" not in raw:
return raw
first = targets[0] if targets else {}
outputs = node_outputs or {}
targets_summary = summarize_targets(targets)
def _lookup(key: str) -> str:
if key == "question":
return question
if key == "targets_summary":
return targets_summary
if key.startswith("target."):
sub = key[len("target.") :]
if sub == "label":
return str(first.get("label") or first.get("name") or "")
if sub == "type":
return str(first.get("entity_type") or first.get("type") or "")
if sub == "id":
return str(first.get("entity_id") or first.get("id") or "")
if sub == "lat":
val = first.get("latitude")
return f"{val:.4f}" if isinstance(val, (int, float)) else ""
if sub == "lon":
val = first.get("longitude")
return f"{val:.4f}" if isinstance(val, (int, float)) else ""
if sub in {"kind", "layer"}:
return str(first.get(sub) or "")
return ""
if key.startswith("node."):
nid = key[len("node.") :]
return str(outputs.get(nid) or "")[:4000]
if key.endswith(".output"):
nid = key[: -len(".output")]
return str(outputs.get(nid) or "")[:4000]
return ""
return _TEMPLATE_VAR_RE.sub(lambda m: _lookup(m.group(1)), raw)
def _extract_target_ids_and_codes(
targets: list[dict[str, Any]],
earth_context: dict[str, Any],
) -> tuple[str | None, list[str], str]:
first = targets[0] if targets else {}
primary_id = str(
first.get("entity_id")
or first.get("id")
or earth_context.get("entity_id")
or ""
).strip() or None
codes = earth_context.get("selected_codes")
if not isinstance(codes, list) or not codes:
codes = ["CN", "US"]
else:
codes = [str(c).strip().upper() for c in codes if str(c).strip()][:12] or ["CN", "US"]
mode = str(earth_context.get("mode") or "global_share")
return primary_id, codes, mode
async def _execute_tool(
db: Any,
tool_id: str,
*,
question: str,
targets: list[dict[str, Any]],
earth_context: dict[str, Any],
allow_external_tools: bool,
) -> dict[str, Any]:
"""Execute one whitelisted read-only or controlled external tool cleanly."""
primary_id, codes, mode = _extract_target_ids_and_codes(targets, earth_context)
time_basis: TimeBasis = str(earth_context.get("time_basis") or "retrospective") # type: ignore[assignment]
if time_basis not in {"live", "as_known_then", "retrospective"}:
time_basis = "retrospective"
cutoff_at = earth_context.get("cutoff_at")
visible_layers = earth_context.get("visible_layers")
visible_layers_dict = visible_layers if isinstance(visible_layers, dict) else None
if tool_id == "query_global_situational":
return await query_global_situational_tool(
db,
selected_codes=codes,
visible_layers=visible_layers_dict,
time_basis=time_basis,
cutoff_at=cutoff_at,
)
if tool_id == "query_compute_posture":
return await query_compute_posture_tool(
db,
countries=codes,
mode=mode,
time_basis=time_basis,
cutoff_at=cutoff_at,
)
if tool_id == "query_bgp_incidents":
incidents = await query_bgp_incidents_tool(
db,
incident_key=primary_id if any(t.get("entity_type") == "bgp" for t in targets) else None,
limit=8,
time_basis=time_basis,
cutoff_at=cutoff_at,
)
return {"items": incidents, "count": len(incidents)}
if tool_id == "query_cable_posture":
return await query_cable_posture_tool(
db,
time_basis=time_basis,
cutoff_at=cutoff_at,
entity_id=primary_id if any(t.get("entity_type") in {"cable", "landing_point"} for t in targets) else None,
)
if tool_id == "query_satellite_posture":
return await query_satellite_posture_tool(
db,
time_basis=time_basis,
cutoff_at=cutoff_at,
entity_id=primary_id if any(t.get("entity_type") == "satellite" for t in targets) else None,
)
if tool_id == "query_vessel_posture":
return await query_vessel_posture_tool(
db,
time_basis=time_basis,
cutoff_at=cutoff_at,
entity_id=primary_id if any(t.get("entity_type") == "vessel" for t in targets) else None,
)
if tool_id == "query_recent_earth_news":
news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {}
region = str(news_ctx.get("region_key") or "").strip() or None
return await query_recent_earth_news_tool(db, region=region, limit=10)
if tool_id in _L1_KNOWLEDGE_TOOL_IDS:
target_name = str(
(targets[0].get("label") if targets else "")
or question
or "Unknown Facility"
).strip()
query = build_compute_center_location_query(name=target_name)
candidates, resolver_log, _ = await run_l1_structured_facility_resolvers(query, db=db)
return {
"candidates": [
{
"display_name": c.display_name,
"country": c.country,
"latitude": c.latitude,
"longitude": c.longitude,
"precision": c.precision,
"confidence": c.confidence,
"source": c.source,
"source_note": c.source_note,
}
for c in candidates[:5]
],
"resolver_log": resolver_log,
}
if tool_id == "web_search":
if not allow_external_tools:
return {"skipped": "external_web_search_admin_only"}
from app.api.v1.settings import get_web_search_client
client = await get_web_search_client(db)
search_q = " ".join(
part for part in [summarize_targets(targets) if targets else "", question] if part
).strip()[:200]
if not search_q:
return {"items": []}
hits = await client.search(search_q, max_results=5)
return {
"items": [
{
"title": h.title,
"url": h.url,
"snippet": h.compact_text(400),
"source_provider": h.source_provider,
}
for h in hits
]
}
if tool_id in {"safe_web_fetch", "fetch_source_url"}:
if not allow_external_tools:
return {"skipped": "external_fetch_admin_only"}
news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {}
target_props = targets[0].get("properties") if targets and isinstance(targets[0].get("properties"), dict) else {}
url = str(news_ctx.get("url") or target_props.get("url") or "").strip()
if not url:
return {"skipped": "no_target_url"}
fetched = await safe_web_fetch(url)
return isolate_untrusted_external_text(fetched.final_url or fetched.url, fetched.title, fetched.text)
return {"skipped": f"unsupported_tool:{tool_id}"}
def _has_meaningful_tool_data(tool_results: dict[str, Any]) -> bool:
for val in tool_results.values():
if not isinstance(val, dict):
continue
if val.get("skipped") or val.get("error"):
continue
for key in ("items", "candidates", "cables", "landing_points", "series", "satellites", "vessels"):
seq = val.get(key)
if isinstance(seq, list) and len(seq) > 0:
return True
if val.get("excerpt") or val.get("summary"):
return True
return False
def _topological_sort_nodes(
nodes: list[dict[str, Any]],
edges: list[dict[str, Any]],
) -> tuple[list[dict[str, Any]], dict[str, list[dict[str, Any]]], dict[str, list[str]]]:
enabled_nodes = [n for n in nodes if isinstance(n, dict) and n.get("enabled", True)][:MAX_WORKFLOW_NODES]
node_map = {str(n["id"]): n for n in enabled_nodes if n.get("id")}
adj: dict[str, list[str]] = {nid: [] for nid in node_map}
incoming: dict[str, list[dict[str, Any]]] = defaultdict(list)
indeg: dict[str, int] = {nid: 0 for nid in node_map}
for edge in edges:
if not isinstance(edge, dict):
continue
src = str(edge.get("source") or "")
tgt = str(edge.get("target") or "")
if src in node_map and tgt in node_map and src != tgt:
adj[src].append(tgt)
incoming[tgt].append(edge)
indeg[tgt] += 1
queue = deque(nid for nid, d in indeg.items() if d == 0)
ordered: list[dict[str, Any]] = []
while queue:
nid = queue.popleft()
ordered.append(node_map[nid])
for nxt in adj[nid]:
indeg[nxt] -= 1
if indeg[nxt] == 0:
queue.append(nxt)
# Fallback: preserve enabled order if partial edge misalignment occurs.
seen = {str(n["id"]) for n in ordered}
for n in enabled_nodes:
if str(n["id"]) not in seen:
ordered.append(n)
return ordered, incoming, adj
def _has_downstream_llm(
start_id: str,
adj: dict[str, list[str]],
node_types: dict[str, str],
) -> bool:
visited: set[str] = set()
stack = list(adj.get(start_id) or [])
while stack:
cur = stack.pop()
if cur in visited:
continue
visited.add(cur)
if node_types.get(cur) in {"llm_agent", "tool_agent"}:
return True
stack.extend(adj.get(cur) or [])
return False
def _eval_edge_condition(
edge: dict[str, Any],
pred_state: dict[str, Any],
targets: list[dict[str, Any]],
) -> bool:
cond = str(edge.get("condition") or "always").strip()
if cond in {"always", "", "interactive", "ingest", "not_terminal", "high_confidence_hit", "fallback_to_agent"}:
return True
if cond == "on_empty_or_low_confidence":
return bool(pred_state.get("is_empty")) or float(pred_state.get("confidence", 1.0)) < 0.6
if cond == "on_entity_type":
raw_val = str(edge.get("condition_value") or "").strip()
if not raw_val:
return False
wanted = {item.strip().lower() for item in raw_val.split(",") if item.strip()}
target_types = {str(t.get("entity_type") or t.get("type") or "").strip().lower() for t in targets}
return bool(wanted & target_types)
return True
def _build_deterministic_fallback_markdown(
*,
workflow_name: str,
question: str,
targets: list[dict[str, Any]],
tool_results: dict[str, Any],
ai_configured: bool,
) -> str:
lines = [f"### {workflow_name}", ""]
if targets:
lines.append(f"- **聚焦目标**:{summarize_targets(targets)}")
if question:
lines.append(f"- **分析问题**:{question}")
if tool_results:
lines.append("- **已加载遥测工具**:" + "、".join(f"`{k}`" for k in tool_results.keys()))
lines.append("")
if not ai_configured:
lines.append("> 当前系统尚未配置可用 AI Provider,以上为确定性规则与遥测快照摘要;配置模型后可启用深度推理节点。")
elif tool_results:
preview = json.dumps(tool_results, ensure_ascii=False, default=str)[:1200]
lines.append(f"```json\n{preview}\n```")
return "\n".join(lines).strip()
async def run_workflow_dag_stream(
*,
db: Any,
workflow: dict[str, Any],
question: str,
use_draft: bool = False,
targets: list[dict[str, Any]] | None = None,
earth_context: dict[str, Any] | None = None,
attachments: list[dict[str, Any]] | None = None,
images: list[dict[str, Any]] | None = None,
history: list[dict[str, Any]] | None = None,
ai_client: Any = None,
request: Any = None,
run_id: str = "",
model_override: str | None = None,
allow_external_tools: bool = False,
extra_meta: dict[str, Any] | None = None,
) -> AsyncIterator[dict[str, Any]]:
"""Execute a workflow DAG topologically and emit structured SSE-ready events."""
wf_id = str(workflow.get("workflow_id") or "default.general")
wf_name = str(workflow.get("name") or wf_id)
active_rev = int(workflow.get("active_revision") or 1)
bindings = workflow.get("bindings") if isinstance(workflow.get("bindings"), dict) else {}
graph = (
workflow.get("draft_graph")
if use_draft and isinstance(workflow.get("draft_graph"), dict)
else workflow.get("published_graph")
) or {}
raw_nodes = list(graph.get("nodes") or [])
raw_edges = list(graph.get("edges") or [])
ordered_nodes, incoming_map, adj = _topological_sort_nodes(raw_nodes, raw_edges)
node_types = {str(n["id"]): str(n.get("node_type") or "llm_agent") for n in ordered_nodes}
clean_targets = [t for t in (targets or []) if isinstance(t, dict)][:8]
clean_earth_ctx = dict(earth_context or {})
planned_ids = [str(n["id"]) for n in ordered_nodes]
yield {
"event": "meta",
"data": {
"run_id": run_id,
"workflow_id": wf_id,
"workflow_name": wf_name,
"active_revision": active_rev,
"use_draft": use_draft,
"targets_count": len(clean_targets),
"planned_nodes": planned_ids,
"nodes": planned_ids,
**(extra_meta or {}),
},
}
ai_ready = False
provider_name = ""
default_model = ""
if ai_client is not None and hasattr(ai_client, "is_ready"):
try:
ai_ready, provider_name, default_model = await ai_client.is_ready()
except Exception:
ai_ready = False
node_states: dict[str, dict[str, Any]] = {}
node_outputs: dict[str, str] = {}
tool_results: dict[str, Any] = {}
evidence: dict[str, Any] = {}
executed_trace: list[str] = []
effective_question = question.strip()
final_answer_md = ""
final_reasoning_md = ""
generation_mode = "deterministic_baseline"
zero_token = True
resolved_provider: str | None = None
resolved_model: str | None = None
scene_spec: dict[str, Any] | None = None
last_llm_output: str = ""
for node in ordered_nodes:
nid = str(node["id"])
ntype = str(node.get("node_type") or "llm_agent")
ntitle = str(node.get("title") or nid)
inc_edges = incoming_map.get(nid) or []
if inc_edges:
passed = False
for edge in inc_edges:
pred_id = str(edge.get("source") or "")
pred_state = node_states.get(pred_id)
if not pred_state or pred_state.get("skipped"):
continue
if _eval_edge_condition(edge, pred_state, clean_targets):
passed = True
break
if not passed:
node_states[nid] = {"skipped": True, "confidence": 1.0, "is_empty": False}
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "skipped"},
}
continue
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "running"},
}
if ntype in {"trigger", "input"}:
tmpl = str(bindings.get("prompt_template") or node.get("prompt") or "").strip()
if not effective_question and tmpl:
effective_question = render_workflow_template(
tmpl,
question=effective_question,
targets=clean_targets,
node_outputs=node_outputs,
).strip()
summary = summarize_targets(clean_targets)
node_outputs[nid] = summary
node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False}
executed_trace.append(nid)
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
}
continue
if ntype == "deterministic":
local_results: dict[str, Any] = {}
l1_ran = False
for tid in node.get("tools") or []:
if tid in _L1_KNOWLEDGE_TOOL_IDS:
if l1_ran:
continue
l1_ran = True
result_key = "l1_facility_lookup"
else:
result_key = tid
try:
res = await _execute_tool(
db,
tid,
question=effective_question or question,
targets=clean_targets,
earth_context=clean_earth_ctx,
allow_external_tools=allow_external_tools,
)
local_results[result_key] = res
tool_results[result_key] = res
if isinstance(res, dict) and isinstance(res.get("evidence"), dict):
evidence.update(res["evidence"])
executed_trace.append(f"{nid}:{tid}")
except Exception as exc:
logger.warning_event(
"Deterministic DAG tool failed",
event="ai_dag.tool.failed",
context={"workflow_id": wf_id, "node_id": nid, "tool_id": tid, "error": str(exc)},
)
local_results[result_key] = {"error": str(exc)}
has_data = _has_meaningful_tool_data(local_results)
node_outputs[nid] = json.dumps(local_results, ensure_ascii=False, default=str)[:4000]
node_states[nid] = {
"skipped": False,
"confidence": 0.9 if has_data else 0.4,
"is_empty": not has_data,
}
if nid not in executed_trace:
executed_trace.append(nid)
yield {
"event": "node",
"data": {
"node_id": nid,
"title": ntitle,
"node_type": ntype,
"status": "completed",
"tools_count": len(local_results),
},
}
continue
if ntype in {"llm_agent", "tool_agent"}:
has_next_llm = _has_downstream_llm(nid, adj, node_types)
sys_prompt = render_workflow_template(
str(node.get("system_prompt") or "").strip()
or "你是智能星球(Planet)AI 参谋。结合当前地球上下文、选中交互物件与工具证据,给出严谨客观的中文分析。",
question=effective_question or question,
targets=clean_targets,
node_outputs=node_outputs,
)
node_prompt = render_workflow_template(
str(node.get("prompt") or "").strip(),
question=effective_question or question,
targets=clean_targets,
node_outputs=node_outputs,
)
objective = (
f"{node_prompt}\n\n用户请求:{effective_question or question}"
if node_prompt
else (effective_question or question)
).strip()
# Execute any extra read-only tools configured directly on the LLM node before inference.
node_tool_results: dict[str, Any] = {}
for tid in node.get("tools") or []:
if tid in tool_results or tid in _L1_KNOWLEDGE_TOOL_IDS:
continue
try:
res = await _execute_tool(
db,
tid,
question=effective_question or question,
targets=clean_targets,
earth_context=clean_earth_ctx,
allow_external_tools=allow_external_tools,
)
node_tool_results[tid] = res
tool_results[tid] = res
if isinstance(res, dict) and isinstance(res.get("evidence"), dict):
evidence.update(res["evidence"])
except Exception as exc:
node_tool_results[tid] = {"error": str(exc)}
ctx_payload: dict[str, Any] = {
"targets": clean_targets,
"targets_summary": summarize_targets(clean_targets),
"tool_results": tool_results,
"upstream_outputs": {k: v[:2000] for k, v in node_outputs.items()},
"evidence": evidence,
}
if clean_earth_ctx:
ctx_payload["earth_context"] = clean_earth_ctx
if attachments:
ctx_payload["attachments"] = attachments[:8]
parsed_images: list[ImageAttachment] = []
if not has_next_llm and images:
for raw_img in images[:8]:
try:
parsed_images.append(ImageAttachment.model_validate(raw_img))
except Exception:
continue
chat_msgs = [
ChatMessage(role=str(m["role"]), content=str(m["content"])) # type: ignore[arg-type]
for m in (history or [])[-12:]
if isinstance(m, dict) and m.get("role") in {"user", "assistant"} and m.get("content")
]
preferred_model = (
str(model_override or "").strip()
or str(node.get("model_override") or "").strip()
or None
)
req = SituationalAnalysisRequest(
title=f"Planet AI Advisor · {wf_name}",
objective=objective[:24000],
system_prompt=sys_prompt[:8000],
context=ctx_payload,
preferred_model=preferred_model,
thinking={"mode": "auto"} if bool(node.get("thinking_enabled", True)) else {"mode": "off"},
native_web_search=bool(node.get("native_web_search", False)) and allow_external_tools,
messages=[] if has_next_llm else chat_msgs,
images=parsed_images,
)
if not ai_ready or ai_client is None:
fallback_md = _build_deterministic_fallback_markdown(
workflow_name=wf_name,
question=effective_question or question,
targets=clean_targets,
tool_results=tool_results,
ai_configured=False,
)
node_outputs[nid] = fallback_md
node_states[nid] = {"skipped": False, "confidence": 0.65, "is_empty": False}
executed_trace.append(nid)
if not has_next_llm:
final_answer_md = fallback_md
yield {"event": "text", "data": {"delta": fallback_md}}
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
}
continue
timeout_sec = max(5, min(int(node.get("timeout_seconds") or 60), 300))
if has_next_llm:
resp = await asyncio.wait_for(ai_client.analyze(req), timeout=timeout_sec)
clean_text, inline_thoughts = strip_thinking_text(str(getattr(resp, "content", "") or ""))
node_outputs[nid] = clean_text or str(getattr(resp, "content", "") or "")
if node_outputs[nid]:
last_llm_output = node_outputs[nid]
resolved_provider = getattr(resp, "provider", None) or provider_name
resolved_model = getattr(resp, "model", None) or preferred_model or default_model
if inline_thoughts:
final_reasoning_md = f"{final_reasoning_md}\n\n" + "\n\n".join(inline_thoughts)
final_reasoning_md = final_reasoning_md.strip()
generation_mode = "llm_verified"
zero_token = False
node_states[nid] = {
"skipped": False,
"confidence": 0.85 if node_outputs[nid] else 0.4,
"is_empty": not bool(node_outputs[nid].strip()),
}
executed_trace.append(nid)
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
}
else:
text_parts: list[str] = []
reasoning_parts: list[str] = []
resolved_provider = provider_name or None
resolved_model = preferred_model or default_model or None
async for ev in ai_client.stream_analyze(req, request_id=run_id):
if request is not None and await request.is_disconnected():
return
ev_type = str(ev.get("event") or "")
if ev_type == "start":
if isinstance(ev.get("provider"), str) and ev["provider"]:
resolved_provider = ev["provider"]
if isinstance(ev.get("model"), str) and ev["model"]:
resolved_model = ev["model"]
elif ev_type == "reasoning" and ev.get("delta"):
delta = str(ev["delta"])
reasoning_parts.append(delta)
yield {"event": "reasoning", "data": {"delta": delta}}
elif ev_type == "text" and ev.get("delta"):
delta = str(ev["delta"])
text_parts.append(delta)
yield {"event": "text", "data": {"delta": delta}}
elif ev_type == "done":
if isinstance(ev.get("provider"), str) and ev["provider"]:
resolved_provider = ev["provider"]
if isinstance(ev.get("model"), str) and ev["model"]:
resolved_model = ev["model"]
elif ev_type == "error":
err_msg = str(ev.get("message") or ev.get("detail") or "AI stream error")
raise RuntimeError(err_msg)
raw_text = "".join(text_parts)
clean_text, inline_thoughts = strip_thinking_text(raw_text)
final_answer_md = (clean_text or raw_text).strip()
if inline_thoughts:
reasoning_parts.extend(inline_thoughts)
if reasoning_parts:
joined = "".join(reasoning_parts).strip()
final_reasoning_md = f"{final_reasoning_md}\n\n{joined}".strip() if final_reasoning_md else joined
generation_mode = "llm_verified"
zero_token = False
node_outputs[nid] = final_answer_md
node_states[nid] = {
"skipped": False,
"confidence": 0.9 if final_answer_md else 0.35,
"is_empty": not bool(final_answer_md),
}
executed_trace.append(nid)
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
}
continue
if ntype == "guardrail":
gr = node.get("guardrails") if isinstance(node.get("guardrails"), dict) else {}
passed = True
warnings: list[str] = []
if gr.get("require_evidence") and not evidence:
passed = False
warnings.append("缺少结构化证据条目(require_evidence)")
min_chars = int(gr.get("min_output_chars") or 0)
if min_chars > 0 and len(final_answer_md) < min_chars:
passed = False
warnings.append(f"输出长度低于最低阈值({min_chars} 字符)")
forbidden = gr.get("forbidden_phrases")
if isinstance(forbidden, list) and final_answer_md:
hits = [str(p) for p in forbidden if str(p) and str(p) in final_answer_md]
if hits:
passed = False
warnings.append("命中禁用表述: " + ", ".join(hits[:5]))
disclaimer = str(gr.get("append_disclaimer") or "").strip()
if disclaimer and final_answer_md and disclaimer not in final_answer_md:
extra_block = f"\n\n> {disclaimer}"
final_answer_md += extra_block
yield {"event": "text", "data": {"delta": extra_block}}
node_states[nid] = {
"skipped": False,
"confidence": 0.95 if passed else 0.45,
"is_empty": False,
"warnings": warnings,
}
executed_trace.append(nid)
yield {
"event": "node",
"data": {
"node_id": nid,
"title": ntitle,
"node_type": ntype,
"status": "completed",
"guardrail_passed": passed,
},
}
continue
if ntype == "output":
params = node.get("params") if isinstance(node.get("params"), dict) else {}
fly_enabled = bool(params.get("fly_to_target", True))
if fly_enabled and clean_targets:
first = clean_targets[0]
lat = first.get("latitude")
lon = first.get("longitude")
if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
scene_spec = {
"fly_to": {
"lat": float(lat),
"lon": float(lon),
"zoom": float(params.get("fly_zoom") or 1.45),
},
"highlight_entities": [
str(t.get("entity_id") or t.get("id"))
for t in clean_targets
if t.get("entity_id") or t.get("id")
],
}
node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False}
executed_trace.append(nid)
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
}
if not final_answer_md:
final_answer_md = last_llm_output or _build_deterministic_fallback_markdown(
workflow_name=wf_name,
question=effective_question or question,
targets=clean_targets,
tool_results=tool_results,
ai_configured=ai_ready,
)
yield {"event": "text", "data": {"delta": final_answer_md}}
yield {
"event": "done",
"data": {
"run_id": run_id,
"workflow_id": wf_id,
"workflow_name": wf_name,
"status": "completed",
"generation_mode": generation_mode,
"zero_token": zero_token,
"provider": resolved_provider,
"model": resolved_model,
"nodes": executed_trace,
"evidence": evidence,
"scene_spec": scene_spec,
"answer_markdown": final_answer_md,
"reasoning_markdown": final_reasoning_md,
"text_length": len(final_answer_md),
},
}
+5 -2
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
from typing import Literal
WorkbenchDomain = Literal["global", "compute", "bgp", "cable", "satellite", "vessel"]
WorkbenchDomain = Literal["global", "compute", "bgp", "cable", "satellite", "vessel", "news"]
SpatialDomain = Literal["global", "cable", "satellite", "vessel"]
ReportSubjectType = Literal[
"global_posture",
@@ -13,11 +13,12 @@ ReportSubjectType = Literal[
"cable_posture",
"satellite_posture",
"vessel_posture",
"news_brief",
]
SPATIAL_POSTURE_DOMAINS: frozenset[str] = frozenset({"global", "cable", "satellite", "vessel"})
SUPPORTED_WORKBENCH_DOMAINS: frozenset[str] = frozenset(
{"global", "compute", "bgp", "cable", "satellite", "vessel"}
{"global", "compute", "bgp", "cable", "satellite", "vessel", "news"}
)
DOMAIN_TO_SUBJECT_TYPE: dict[str, ReportSubjectType] = {
@@ -27,6 +28,7 @@ DOMAIN_TO_SUBJECT_TYPE: dict[str, ReportSubjectType] = {
"cable": "cable_posture",
"satellite": "satellite_posture",
"vessel": "vessel_posture",
"news": "news_brief",
}
SUBJECT_TYPE_TO_DOMAIN: dict[str, WorkbenchDomain] = {
@@ -36,6 +38,7 @@ SUBJECT_TYPE_TO_DOMAIN: dict[str, WorkbenchDomain] = {
"cable_posture": "cable",
"satellite_posture": "satellite",
"vessel_posture": "vessel",
"news_brief": "news",
}
@@ -520,7 +520,7 @@ async def investigate_spatial_domain(
timeout=35.0,
)
_raise_if_cancelled(cancel_event)
raw_text = (llm_resp.answer or "").strip()
raw_text = (llm_resp.content or "").strip()
assert_no_thinking_leak(raw_text)
parsed = extract_json_object(raw_text)
if not isinstance(parsed, dict):
+774
View File
@@ -0,0 +1,774 @@
"""Adaptive SSE streaming turn orchestrator with thinking process, model attribution, and news context."""
from __future__ import annotations
import asyncio
from collections import defaultdict, deque
from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta
import json
import os
from typing import Any
import uuid
from fastapi import HTTPException, Request, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.models.ai_workflow import AIWorkflow
from app.models.situational_assessment import InvestigationSession, WorkflowRun
from app.schemas.ai import ChatMessage, SituationalAnalysisRequest
from app.services.ai.access_policy import AccessContext
from app.services.ai.conversation_memory import (
compact_conversation_history,
sanitize_memory_notes,
sanitize_pinned_summaries,
)
from app.services.ai.dag_executor import run_workflow_dag_stream
from app.services.ai.thinking_sanitizer import prepare_situational_ai_call, strip_thinking_text
from app.services.ai.tool_registry import (
TimeBasis,
query_global_situational_tool,
query_recent_earth_news_tool,
)
from app.services.ai.workflow_evolver import schedule_post_run_evolution
from app.services.ai.workflow_registry import _fallback_workflow_dict, ensure_builtin_workflows
from app.services.ai.workflow_runtime import classify_turn_intent, execute_session_turn
from app.services.ai_client import AIProviderClient
logger = get_logger(__name__, service="ai_stream")
_STREAM_QUOTA_WINDOW: dict[str, deque[datetime]] = defaultdict(deque)
_GEOPOLITICAL_OR_NEWS_KEYWORDS = (
"国际局势",
"全球局势",
"地缘",
"新闻",
"报道",
"外交",
"冲突",
"制裁",
"关税",
"战争",
"和平",
"热点",
"geopolit",
"headline",
"news",
"international situation",
"world situation",
)
def reset_stream_quota_ledger() -> None:
"""Reset in-memory public stream rate limiter state (for deterministic tests)."""
_STREAM_QUOTA_WINDOW.clear()
def check_stream_quota(access: AccessContext) -> None:
"""Enforce bounded hourly quota on adaptive streaming AI turns across all access tiers."""
default_public_cap = int(os.getenv("PLANET_PUBLIC_AI_STREAM_HOURLY_QUOTA", "60"))
limit = access.hourly_paid_quota if access.hourly_paid_quota > 0 else default_public_cap
if limit <= 0:
return
now = datetime.now(UTC)
window_start = now - timedelta(hours=1)
dq = _STREAM_QUOTA_WINDOW[access.actor_key]
while dq and dq[0] < window_start:
dq.popleft()
if len(dq) >= limit:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=f"Hourly AI stream quota ({limit}) exceeded.",
)
dq.append(now)
def build_streaming_thinking_config(ai_client: AIProviderClient) -> dict[str, Any] | None:
"""Enable streamed reasoning tokens for MiniMax/Anthropic providers when streaming turns."""
llm_cfg = getattr(ai_client, "llm_config", None) or {}
provider = str(llm_cfg.get("provider") or "").strip().lower()
provider_api = str(llm_cfg.get("provider_api") or "").strip().lower()
model = str(llm_cfg.get("model") or "").strip().lower()
if "minimax-m3" in model:
return {"type": "adaptive", "effort": "medium"}
if provider == "minimax" or provider_api == "anthropic-messages" or "anthropic" in provider or "claude" in model:
return {"type": "enabled", "budget_tokens": 2048}
return None
def _is_geopolitical_or_news_question(
question: str,
*,
domain: str,
news_context: dict[str, Any] | None,
) -> bool:
if domain == "news" or news_context:
return True
q = (question or "").strip().lower()
return any(kw in q for kw in _GEOPOLITICAL_OR_NEWS_KEYWORDS)
def _format_sse(event: str, payload: dict[str, Any]) -> str:
return f"event: {event}\ndata: {json.dumps(payload, ensure_ascii=False, default=str)}\n\n"
def _build_news_fallback_markdown(
*,
question: str,
news_context: dict[str, Any] | None,
recent_news: dict[str, Any],
ai_configured: bool,
fallback_reason: str | None = None,
) -> str:
lines: list[str] = []
if news_context:
title = str(news_context.get("title") or "新闻速递").strip()
source = str(news_context.get("source") or "").strip()
region = str(news_context.get("region") or news_context.get("region_key") or "").strip()
published_at = str(news_context.get("published_at") or "").strip()
summary = str(news_context.get("summary") or "").strip()
lines.append(f"### 新闻焦点:{title}")
meta_parts = [p for p in (source, region, published_at) if p]
if meta_parts:
lines.append(f"- **来源与时间**:{' · '.join(meta_parts)}")
if summary:
lines.append(f"- **报道摘要**:{summary}")
else:
lines.append("### 全球局势与新闻态势速览")
if question:
lines.append(f"- **当前问题**:{question}")
items = list(recent_news.get("items") or [])
if items:
lines.append("")
lines.append("#### 近期关联动态")
for item in items[:5]:
item_title = str(item.get("title") or "").strip()
item_src = str(item.get("source") or "").strip()
item_reg = str(item.get("region") or "").strip()
if item_title:
meta = f"({item_src}{' · ' + item_reg if item_reg else ''})" if item_src else ""
lines.append(f"- {item_title}{meta}")
if not ai_configured:
lines.append("")
lines.append("> 当前后台尚未接入可用 AI 大模型,以上为内置新闻与遥测结构化汇总。")
elif fallback_reason:
lines.append("")
lines.append(f"> AI 流式生成暂时不可用({fallback_reason}),已自动回退为内置结构化汇总。")
return "\n".join(lines).strip()
def _build_news_analysis_request(
*,
question: str,
news_context: dict[str, Any] | None,
recent_news: dict[str, Any],
global_snapshot: dict[str, Any],
thinking_cfg: dict[str, Any] | None,
conversation_messages: list[ChatMessage] | None = None,
conversation_summary: str = "",
memory_notes: list[str] | None = None,
pinned_summaries: list[str] | None = None,
) -> SituationalAnalysisRequest:
context: dict[str, Any] = {
"focused_news": news_context or None,
"recent_news_headlines": (recent_news.get("items") or [])[:10],
"global_infrastructure_summary": global_snapshot.get("domain_summaries") or [],
}
if conversation_summary:
context["conversation_summary"] = conversation_summary
if memory_notes:
context["user_memory_notes"] = memory_notes
if pinned_summaries:
context["pinned_comparisons"] = pinned_summaries
return SituationalAnalysisRequest(
title="Planet 全球新闻与国际局势研判",
objective=(
f"用户提问:{question}\n\n"
"请结合多轮对话延续性与记忆备忘,直接使用中文(若用户用英文提问则用英文)输出结构清晰的 Markdown 深度分析,包括:\n"
"1. **核心事实与背景脉络**(紧扣聚焦新闻或近期头条);\n"
"2. **地缘、产业与基础设施影响**(可结合海缆/算力/航运/卫星/BGP 背景若相关,无直接关联则勿强行牵连);\n"
"3. **后续重点观察信号与不确定边界**。\n"
"请直接输出面向用户的 Markdown 正文,不要包在 JSON 里。"
),
system_prompt=(
"你是 Planet(智能星球计划)的全球新闻与国际局势分析参谋。"
"如有前序对话与用户备忘录,请保持指代与口径延续。"
"请严谨区分已报道事实与推演研判,禁止虚构具体伤亡、断缆或未经报道的内部消息。"
),
context=context,
constraints=[
"Output clean user-facing Markdown directly (not JSON).",
"Distinguish reported facts from analytical outlook.",
],
thinking=thinking_cfg,
messages=conversation_messages or [],
)
def _build_telemetry_stream_request(
*,
domain: str,
question: str,
base_answer_md: str,
evidence: dict[str, Any],
view_spec: dict[str, Any] | None,
recent_news: dict[str, Any] | None,
thinking_cfg: dict[str, Any] | None,
conversation_messages: list[ChatMessage] | None = None,
conversation_summary: str = "",
memory_notes: list[str] | None = None,
pinned_summaries: list[str] | None = None,
) -> SituationalAnalysisRequest:
context: dict[str, Any] = {
"domain": domain,
"verified_baseline_summary": base_answer_md,
"evidence": evidence,
"view_headline": (view_spec or {}).get("headline"),
}
if recent_news and recent_news.get("items"):
context["recent_news_headlines"] = (recent_news.get("items") or [])[:10]
if conversation_summary:
context["conversation_summary"] = conversation_summary
if memory_notes:
context["user_memory_notes"] = memory_notes
if pinned_summaries:
context["pinned_comparisons"] = pinned_summaries
return SituationalAnalysisRequest(
title=f"Planet 态势参谋分析({domain})",
objective=(
f"用户问题:{question}\n\n"
"请严格基于 context 中的已核验内置遥测结论、证据源、前序对话摘要/记忆备忘与关联新闻头条,"
"使用清晰自然的 Markdown 直接回答用户问题,给出结构化洞察与口径边界,不要输出 JSON 对象。"
),
system_prompt=(
"你是 Planet 空间与网络基础设施态势参谋。如有前序对话与用户记忆备忘,请延续语境与偏好;"
"所有具体数值必须与 context 一致,不得编造未给出的实时数值或故障原因;直接输出高质量 Markdown 分析正文。"
),
context=context,
constraints=[
"Output clean Markdown directly (not JSON).",
"Do not invent telemetry counts or unverified outages outside context.",
],
thinking=thinking_cfg,
messages=conversation_messages or [],
)
async def stream_session_turn(
db: AsyncSession,
*,
request: Request | None,
session: InvestigationSession | None,
question: str,
context_override: dict[str, Any] | None,
news_context: dict[str, Any] | None,
access: AccessContext,
ai_client: AIProviderClient | None,
client_run_id: str | None = None,
issued_session_token: str | None = None,
history: list[dict[str, Any]] | None = None,
conversation_summary: str | None = None,
memory_notes: list[str] | None = None,
pinned_summaries: list[str] | None = None,
workflow_id: str | None = None,
targets: list[dict[str, Any]] | None = None,
) -> AsyncIterator[str]:
"""Adaptive SSE generator: streams real LLM + thinking when AI is configured, else grounded baseline."""
check_stream_quota(access)
session_id_val = str(session.id) if session is not None else "stateless"
run_id = client_run_id or f"run-{uuid.uuid4().hex[:12]}"
merged_ctx: dict[str, Any] = {}
if session is not None and isinstance(session.context_state, dict):
merged_ctx.update(session.context_state)
if context_override:
for k, v in context_override.items():
if v is not None:
merged_ctx[k] = v
raw_history = history if history else merged_ctx.get("recent_messages")
existing_summary = str(
conversation_summary
if conversation_summary is not None
else merged_ctx.get("conversation_summary") or ""
)
clean_memory_notes = sanitize_memory_notes(memory_notes)
clean_pinned_summaries = sanitize_pinned_summaries(
pinned_summaries
if pinned_summaries is not None
else [
f"{p.get('pin_id', 'PIN')}: {p.get('title', '')}"
for p in ((getattr(session, "pinned_items", None) or []) if session is not None else [])
if isinstance(p, dict) and p.get("title")
]
)
routed = classify_turn_intent(question, merged_ctx)
explicit_domain = str((context_override or {}).get("domain") or "").strip().lower()
domain = "news" if news_context or explicit_domain == "news" else str(routed.get("domain") or "global")
is_pure_view = bool(routed.get("is_pure_projection") or routed.get("auto_play_presentation"))
geo_or_news_query = _is_geopolitical_or_news_question(
question,
domain=domain,
news_context=news_context,
)
time_basis: TimeBasis = (context_override or {}).get("time_basis") or merged_ctx.get("time_basis") or "retrospective"
cutoff_at: str | None = (context_override or {}).get("cutoff_at") or merged_ctx.get("cutoff_at")
codes = list((context_override or {}).get("selected_codes") or merged_ctx.get("selected_codes") or ["CN", "US"])
visible_layers = dict((context_override or {}).get("visible_layers") or merged_ctx.get("visible_layers") or {})
ai_ready = False
provider_name = ""
model_name = ""
if ai_client is not None:
ai_ready, provider_name, model_name = await ai_client.is_ready()
compaction = await compact_conversation_history(
raw_history,
existing_summary,
ai_client=ai_client,
ai_ready=ai_ready,
)
compacted_summary = str(compaction.get("summary") or "")
recent_history = list(compaction.get("recent_messages") or [])
compacted_flag = bool(compaction.get("compacted"))
memory_used_flag = bool(compacted_summary or recent_history or clean_memory_notes or clean_pinned_summaries)
if workflow_id:
wf_dict: dict[str, Any] | None = None
try:
await ensure_builtin_workflows(db)
wf_row = (
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
).scalar_one_or_none()
if wf_row is not None:
wf_dict = wf_row.to_dict()
except Exception:
wf_dict = None
if wf_dict is None:
wf_dict = _fallback_workflow_dict(workflow_id)
if wf_dict is not None:
wf_started_at = datetime.now(UTC)
wf_trace: list[str] = []
wf_status = "completed"
wf_error = ""
wf_answer = ""
wf_model = str(model_name or "")
wf_provider = str(provider_name or "")
wf_revision = int(wf_dict.get("active_revision") or 1)
try:
wf_earth_ctx: dict[str, Any] = {
**merged_ctx,
"domain": domain,
"selected_codes": codes,
"visible_layers": visible_layers,
"time_basis": time_basis,
"cutoff_at": cutoff_at,
}
if news_context:
wf_earth_ctx["news_context"] = news_context
if clean_memory_notes:
wf_earth_ctx["user_memory_notes"] = clean_memory_notes
effective_client = ai_client
if ai_ready and ai_client is not None and type(ai_client) is AIProviderClient and ai_client.llm_config:
cur_max = int(ai_client.llm_config.get("max_tokens") or 0)
if cur_max < 3200:
effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=3200)
allow_external = getattr(access, "access_tier", "public_zero_cost") == "admin"
async for item in run_workflow_dag_stream(
db=db,
workflow=wf_dict,
question=question,
use_draft=False,
targets=targets,
earth_context=wf_earth_ctx,
history=recent_history,
ai_client=effective_client,
request=request,
run_id=run_id,
allow_external_tools=allow_external,
extra_meta={
"session_id": session_id_val,
"domain": domain,
"ai_enabled": ai_ready,
"provider": provider_name if ai_ready else None,
"model": model_name if ai_ready else None,
"compacted": compacted_flag,
"conversation_summary": compacted_summary,
"memory_used": memory_used_flag,
"context_state": {**merged_ctx, "domain": domain},
**({"session_token": issued_session_token} if issued_session_token else {}),
},
):
ev_name = str(item.get("event") or "")
ev_data = dict(item.get("data") or {})
if ev_name == "node" and ev_data.get("status") == "completed":
nid = str(ev_data.get("node_id") or "")
if nid and nid not in wf_trace:
wf_trace.append(nid)
elif ev_name == "done":
if isinstance(ev_data.get("nodes"), list):
wf_trace = [str(n) for n in ev_data["nodes"] if n]
if ev_data.get("model"):
wf_model = str(ev_data["model"])
if ev_data.get("provider"):
wf_provider = str(ev_data["provider"])
wf_answer = str(ev_data.get("answer_markdown") or "")
ev_data.setdefault("usage", {})
ev_data["compacted"] = compacted_flag
ev_data["conversation_summary"] = compacted_summary
ev_data["memory_used"] = memory_used_flag
if session is not None and isinstance(session.context_state, dict):
updated_recent = [*recent_history, {"role": "user", "content": question}]
if wf_answer:
updated_recent.append({"role": "assistant", "content": wf_answer[:1800]})
session.context_state = {
**session.context_state,
"conversation_summary": compacted_summary,
"recent_messages": updated_recent[-8:],
}
elif ev_name == "error":
wf_status = "failed"
wf_error = str(ev_data.get("message") or ev_data.get("detail") or "Workflow DAG error")
yield _format_sse(ev_name, ev_data)
except asyncio.CancelledError:
wf_status = "cancelled"
raise
except Exception as exc:
wf_status = "failed"
wf_error = str(exc)
logger.warning_event(
"Bound Earth workflow DAG stream failed",
event="ai_stream.workflow_dag.failed",
context={"workflow_id": workflow_id, "run_id": run_id, "error": wf_error},
)
yield _format_sse("error", {"detail": wf_error, "message": wf_error, "partial": bool(wf_answer)})
finally:
try:
wf_completed_at = datetime.now(UTC)
wf_latency_ms = max(0, int((wf_completed_at - wf_started_at).total_seconds() * 1000))
db.add(
WorkflowRun(
id=run_id,
session_id=session.id if session is not None else None,
workflow_id=workflow_id,
status=wf_status,
access_tier=getattr(access, "access_tier", "public_zero_cost"),
actor_key=getattr(access, "actor_key", "anonymous"),
question=question[:500],
input_params={
"domain": domain,
"targets_count": len(targets or []),
"source": "earth_copilot",
},
tool_trace=wf_trace,
budget_used={
"steps": len(wf_trace),
"model_used": wf_model,
"provider": wf_provider,
"latency_ms": wf_latency_ms,
"workflow_revision": wf_revision,
},
error_message=wf_error[:500],
started_at=wf_started_at,
completed_at=wf_completed_at,
)
)
if hasattr(db, "commit"):
await db.commit()
schedule_post_run_evolution(workflow_id, run_id)
except Exception:
if hasattr(db, "rollback"):
try:
await db.rollback()
except Exception:
pass
return
view_spec: dict[str, Any] | None = None
scene_spec: dict[str, Any] | None = None
evidence: dict[str, Any] = {}
subject_key = "global"
revision = 1
base_answer_md = ""
context_state: dict[str, Any] = {**merged_ctx, "domain": domain}
recent_news: dict[str, Any] = {"items": [], "evidence": {}}
if news_context or domain == "news":
news_region = str((news_context or {}).get("region_key") or "").strip() or None
recent_news = await query_recent_earth_news_tool(db, region=news_region, limit=10)
global_snap = await query_global_situational_tool(
db,
selected_codes=codes,
visible_layers=visible_layers,
time_basis=time_basis,
cutoff_at=cutoff_at,
)
evidence = {**(recent_news.get("evidence") or {}), **(global_snap.get("evidence") or {})}
if news_context and news_context.get("url"):
evidence["ev-news-focus"] = {
"id": "ev-news-focus",
"title": str(news_context.get("title") or "聚焦新闻"),
"publisher": str(news_context.get("source") or "Planet News"),
"url": str(news_context.get("url") or ""),
"published_at": str(news_context.get("published_at") or ""),
"locator": str(news_context.get("region") or news_context.get("region_key") or "news"),
}
subject_key = f"news:{(news_context or {}).get('id') or news_region or 'global'}"
base_answer_md = _build_news_fallback_markdown(
question=question,
news_context=news_context,
recent_news=recent_news,
ai_configured=ai_ready,
)
else:
base_turn = await execute_session_turn(
db,
session=session,
question=question,
context_override=context_override,
prefer_llm=False,
access=access,
ai_client=None,
client_run_id=None,
)
view_spec = base_turn.get("view_spec")
scene_spec = base_turn.get("scene_spec")
evidence = base_turn.get("evidence") or {}
subject_key = str(base_turn.get("subject_key") or domain)
revision = int(base_turn.get("revision") or 1)
base_answer_md = str((base_turn.get("reply") or {}).get("answer_markdown") or "")
if isinstance(base_turn.get("context_state"), dict):
context_state = base_turn["context_state"]
if domain == "global" and (geo_or_news_query or ai_ready):
recent_news = await query_recent_earth_news_tool(db, limit=10)
evidence = {**evidence, **(recent_news.get("evidence") or {})}
if geo_or_news_query and not is_pure_view:
# Conversational international/news questions should focus on the narrative, not a static bar chart.
view_spec = None
scene_spec = None
if not ai_ready:
base_answer_md = _build_news_fallback_markdown(
question=question,
news_context=None,
recent_news=recent_news,
ai_configured=False,
)
meta_payload: dict[str, Any] = {
"session_id": session_id_val,
"run_id": run_id,
"domain": domain,
"subject_key": subject_key,
"revision": revision,
"ai_enabled": ai_ready and not is_pure_view,
"provider": provider_name if (ai_ready and not is_pure_view) else None,
"model": model_name if (ai_ready and not is_pure_view) else None,
"compacted": compacted_flag,
"conversation_summary": compacted_summary,
"memory_used": memory_used_flag,
"view_spec": view_spec,
"scene_spec": scene_spec,
"evidence": evidence,
"context_state": context_state,
}
if issued_session_token:
meta_payload["session_token"] = issued_session_token
yield _format_sse("meta", meta_payload)
def _persist_session_memory(answer_text: str) -> None:
if session is None or not isinstance(session.context_state, dict):
return
updated_recent = [*recent_history, {"role": "user", "content": question}]
if answer_text:
updated_recent.append({"role": "assistant", "content": answer_text[:1800]})
session.context_state = {
**session.context_state,
"conversation_summary": compacted_summary,
"recent_messages": updated_recent[-8:],
}
if not ai_ready or is_pure_view or ai_client is None:
_persist_session_memory(base_answer_md)
if base_answer_md:
yield _format_sse("text", {"delta": base_answer_md})
yield _format_sse(
"done",
{
"status": "completed",
"generation_mode": "deterministic_baseline",
"zero_token": True,
"provider": None,
"model": None,
"usage": {},
"compacted": compacted_flag,
"conversation_summary": compacted_summary,
"memory_used": memory_used_flag,
"answer_markdown": base_answer_md,
"reasoning_markdown": "",
},
)
return
conversation_messages = [
ChatMessage(role=m["role"], content=m["content"]) for m in recent_history
]
thinking_cfg = build_streaming_thinking_config(ai_client)
effective_client = ai_client
current_max = int((getattr(ai_client, "llm_config", None) or {}).get("max_tokens") or 0)
if type(ai_client) is AIProviderClient and ai_client.llm_config and current_max < 3200:
effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=3200)
analysis_req = (
_build_news_analysis_request(
question=question,
news_context=news_context,
recent_news=recent_news,
global_snapshot=await query_global_situational_tool(
db,
selected_codes=codes,
visible_layers=visible_layers,
time_basis=time_basis,
cutoff_at=cutoff_at,
),
thinking_cfg=thinking_cfg,
conversation_messages=conversation_messages,
conversation_summary=compacted_summary,
memory_notes=clean_memory_notes,
pinned_summaries=clean_pinned_summaries,
)
if (news_context or domain == "news")
else _build_telemetry_stream_request(
domain=domain,
question=question,
base_answer_md=base_answer_md,
evidence=evidence,
view_spec=view_spec,
recent_news=recent_news if domain == "global" else None,
thinking_cfg=thinking_cfg,
conversation_messages=conversation_messages,
conversation_summary=compacted_summary,
memory_notes=clean_memory_notes,
pinned_summaries=clean_pinned_summaries,
)
)
text_chunks: list[str] = []
reasoning_chunks: list[str] = []
resolved_provider = provider_name
resolved_model = model_name
final_usage: dict[str, Any] = {}
try:
async for ev in effective_client.stream_analyze(analysis_req, request_id=run_id):
if request is not None and await request.is_disconnected():
return
ev_type = str(ev.get("event") or "")
if ev_type == "start":
if isinstance(ev.get("provider"), str) and ev["provider"]:
resolved_provider = ev["provider"]
if isinstance(ev.get("model"), str) and ev["model"]:
resolved_model = ev["model"]
elif ev_type == "reasoning":
delta = ev.get("delta")
if isinstance(delta, str) and delta:
reasoning_chunks.append(delta)
yield _format_sse("reasoning", {"delta": delta})
elif ev_type == "text":
delta = ev.get("delta")
if isinstance(delta, str) and delta:
text_chunks.append(delta)
yield _format_sse("text", {"delta": delta})
elif ev_type == "done":
if isinstance(ev.get("provider"), str) and ev["provider"]:
resolved_provider = ev["provider"]
if isinstance(ev.get("model"), str) and ev["model"]:
resolved_model = ev["model"]
if isinstance(ev.get("usage"), dict):
final_usage = ev["usage"]
elif ev_type == "error":
raise RuntimeError(str(ev.get("detail") or "AI stream error"))
combined_text = "".join(text_chunks).strip()
if not combined_text:
raise RuntimeError("AI provider stream returned empty response")
clean_text, inline_thoughts = strip_thinking_text(combined_text)
combined_reasoning = "".join(reasoning_chunks).strip()
if inline_thoughts:
extra_thought = "\n\n".join(inline_thoughts)
combined_reasoning = f"{combined_reasoning}\n\n{extra_thought}".strip() if combined_reasoning else extra_thought
final_answer_md = clean_text or combined_text
_persist_session_memory(final_answer_md)
if hasattr(db, "commit"):
try:
await db.commit()
except Exception:
pass
yield _format_sse(
"done",
{
"status": "completed",
"generation_mode": "llm_verified",
"zero_token": False,
"provider": resolved_provider,
"model": resolved_model,
"usage": final_usage,
"compacted": compacted_flag,
"conversation_summary": compacted_summary,
"memory_used": memory_used_flag,
"answer_markdown": final_answer_md,
"reasoning_markdown": combined_reasoning,
},
)
except asyncio.CancelledError:
raise
except Exception as exc:
logger.warning_event(
"AI stream turn failed",
event="ai_stream.llm.fallback",
context={"domain": domain, "emitted_text": bool(text_chunks), "error": str(exc)},
)
if text_chunks:
yield _format_sse("error", {"detail": str(exc), "partial": True})
return
fallback_md = (
_build_news_fallback_markdown(
question=question,
news_context=news_context,
recent_news=recent_news,
ai_configured=True,
fallback_reason=str(exc),
)
if (news_context or domain == "news" or geo_or_news_query)
else f"{base_answer_md}\n\n> AI 流式研判暂时回退:{exc}".strip()
)
if fallback_md:
yield _format_sse("text", {"delta": fallback_md})
yield _format_sse(
"done",
{
"status": "completed",
"generation_mode": "deterministic_fallback",
"zero_token": True,
"provider": None,
"model": None,
"usage": {},
"answer_markdown": fallback_md,
"reasoning_markdown": "".join(reasoning_chunks).strip(),
"fallback_reason": str(exc),
},
)
+93 -5
View File
@@ -11,11 +11,13 @@ from urllib.parse import urljoin, urlparse
import httpx
from bs4 import BeautifulSoup
from sqlalchemy import select
from sqlalchemy import desc, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.models.bgp_incident import BGPIncident
from app.models.collected_data import CollectedData
from app.models.earth_news import EarthNewsItem
from app.schemas.compute_configuration import ComputeConfiguration
from app.services.ai_tools.schemas import FetchedEvidence
from app.services.compute_configuration import read_configuration
@@ -610,7 +612,20 @@ async def query_satellite_posture_tool(
safe_limit = max(50, min(int(limit or 1200), 3000))
features: list[dict[str, Any]] = []
catalog_total: int | None = None
limitations: list[str] = []
try:
count_stmt = select(func.count(CollectedData.id)).where(
CollectedData.source == "celestrak_tle",
CollectedData.is_current.is_(True),
CollectedData.name != "Unknown",
)
counted = (await db.execute(count_stmt)).scalar_one_or_none()
if isinstance(counted, int) and counted > 0:
catalog_total = counted
except Exception:
catalog_total = None
try:
sat_fc = await _build_satellites_geojson(limit=safe_limit, db=db)
features = list(sat_fc.get("features") or [])
@@ -622,6 +637,8 @@ async def query_satellite_posture_tool(
)
limitations.append("内置卫星 TLE 查询受限")
effective_total = catalog_total if catalog_total is not None and catalog_total >= len(features) else len(features)
by_constellation: dict[str, int] = {}
by_orbit_regime: dict[str, int] = {}
sample_satellites: list[dict[str, Any]] = []
@@ -657,15 +674,18 @@ async def query_satellite_posture_tool(
sorted_constellations = dict(
sorted(by_constellation.items(), key=lambda kv: kv[1], reverse=True)[:10]
)
if len(features) >= safe_limit:
limitations.append(f"本次卫星样本按性能上限截取前 {safe_limit} 颗轨道目标,不代表全库总编目。")
if effective_total > len(features):
limitations.append(
f"在轨卫星全库共 {effective_total} 颗;星座/轨道分布基于最新 {len(features)} 颗样本统计。"
)
if time_basis == "as_known_then":
limitations.append("在轨星历基于最新同步批次(celestrak_tle),未按历史截点回卷旧 TLE。")
return {
"domain": "satellite",
"available": len(features) > 0,
"satellites_total": len(features),
"available": effective_total > 0,
"satellites_total": effective_total,
"sampled_count": len(features),
"sample_limit": safe_limit,
"by_constellation": sorted_constellations,
"by_orbit_regime": by_orbit_regime,
@@ -678,6 +698,74 @@ async def query_satellite_posture_tool(
}
async def query_recent_earth_news_tool(
db: AsyncSession,
*,
region: str | None = None,
limit: int = 12,
) -> dict[str, Any]:
"""Read-only built-in snapshot of recent global/regional Earth news items for geopolitical & news copilot turns."""
base_ev_id = "ev-news-1"
evidence = {
base_ev_id: {
"id": base_ev_id,
"title": "Planet 全球态势新闻聚合快照(earth_news_items)",
"publisher": "Planet Global News Monitor",
"url": "/api/v1/earth/news",
"published_at": datetime.now(UTC).date().isoformat(),
"locator": f"builtin:earth_news:{region or 'global'}:limit={limit}",
}
}
if not hasattr(db, "execute"):
return {"domain": "news", "available": False, "items": [], "evidence": evidence}
safe_limit = max(1, min(int(limit or 12), 25))
items: list[dict[str, Any]] = []
try:
stmt = (
select(EarthNewsItem)
.where(EarthNewsItem.resolved_at.is_(None))
.order_by(desc(EarthNewsItem.published_at), desc(EarthNewsItem.last_seen_at))
.limit(safe_limit)
)
if region:
stmt = stmt.where(EarthNewsItem.region == region)
rows = (await db.execute(stmt)).scalars().all()
for row in rows:
loc_meta = dict(row.location_meta or {})
news_meta = loc_meta.get("news_meta") if isinstance(loc_meta.get("news_meta"), dict) else {}
localizations = row.localizations if isinstance(row.localizations, dict) else {}
zh_loc = localizations.get("zh-CN") if isinstance(localizations.get("zh-CN"), dict) else {}
items.append(
{
"id": row.id,
"title": zh_loc.get("title") or row.title,
"summary": (zh_loc.get("summary") or row.summary or "")[:400],
"source": row.source or row.feed_name,
"region": row.region,
"location_label": row.location_label,
"category": news_meta.get("category") or "other",
"breaking_level": news_meta.get("breaking_level") or "none",
"published_at": row.published_at.isoformat() if row.published_at else None,
"url": row.url,
}
)
except Exception as exc:
logger.warning_event(
"Recent earth news query degraded",
event="ai_tool.earth_news.degraded",
context={"error": str(exc)},
)
return {
"domain": "news",
"available": len(items) > 0,
"count": len(items),
"items": items,
"evidence": evidence,
}
async def query_vessel_posture_tool(
db: AsyncSession,
*,
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+77
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
from collections.abc import AsyncIterator
import json
from time import perf_counter
@@ -45,6 +46,82 @@ class AIProviderClient:
)
self.llm_config = llm_config or {}
async def is_ready(self) -> tuple[bool, str, str]:
"""Return `(configured_and_enabled, provider, model)` without calling LLM inference."""
if not self.service_url:
return False, "unconfigured", ""
if isinstance(self.llm_config, dict) and self.llm_config:
provider = str(self.llm_config.get("provider") or "").strip().lower()
provider_api = str(self.llm_config.get("provider_api") or "").strip().lower()
base_url = str(self.llm_config.get("base_url") or "").strip()
model = str(self.llm_config.get("model") or "").strip()
api_key = str(self.llm_config.get("api_key") or "").strip()
if not provider or provider == "disabled":
return False, provider or "disabled", model
needs_key = provider != "ollama" and provider_api != "ollama-generate"
configured = bool(base_url and model and (api_key or not needs_key))
return configured, provider, model
try:
status_resp = await self.get_status()
return (
bool(status_resp.enabled and status_resp.configured),
str(status_resp.provider or ""),
str(status_resp.model or ""),
)
except Exception:
return False, "unavailable", ""
async def stream_analyze(
self,
payload: SituationalAnalysisRequest,
request_id: str | None = None,
) -> AsyncIterator[dict]:
"""Stream structured SSE events (`start`, `reasoning`, `text`, `done`, `error`) from aiprovider."""
if not self.service_url:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="AI provider service URL is not configured.",
)
async with httpx.AsyncClient(timeout=self.timeout) as client:
async with client.stream(
"POST",
f"{self.service_url}/v1/analyze/stream",
headers=self._headers(request_id),
json=payload.model_dump(),
) as response:
if response.status_code >= 400:
detail = (await response.aread()).decode("utf-8", errors="replace")
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"AI provider service request failed: {detail or response.status_code}",
)
event_name = ""
data_lines: list[str] = []
async for raw_line in response.aiter_lines():
line = raw_line.rstrip("\r")
if line == "":
if data_lines:
raw_json = "\n".join(data_lines)
event_name_cur = event_name
event_name = ""
data_lines = []
parsed = json.loads(raw_json)
if isinstance(parsed, dict):
parsed.setdefault("event", event_name_cur or "message")
yield parsed
continue
if line.startswith(":"):
continue
if line.startswith("event:"):
event_name = line[6:].strip()
elif line.startswith("data:"):
data_lines.append(line[5:].lstrip())
if data_lines:
parsed = json.loads("\n".join(data_lines))
if isinstance(parsed, dict):
parsed.setdefault("event", event_name or "message")
yield parsed
def _headers(self, request_id: str | None = None) -> dict[str, str]:
headers = {"Content-Type": "application/json"}
if self.service_token:
+74 -2
View File
@@ -1,13 +1,16 @@
from __future__ import annotations
from collections import Counter
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.alert import Alert, AlertSeverity, AlertStatus
from app.schemas.ai import AlertBriefRequest, SituationalAnalysisRequest
from app.models.alert import Alert, AlertStatus
from app.models.datasource import DataSource
from app.models.task import CollectionTask
from app.schemas.ai import SituationalAnalysisRequest
from app.ai_tasks.prompts import get_effective_prompt
ALERT_BRIEF_PROMPT_KEY = "alerts.brief"
@@ -19,6 +22,50 @@ def _format_counter(counter: Counter[str], empty_text: str = "无") -> str:
return ",".join(f"{key} {value}" for key, value in counter.items())
async def _collect_operational_health(db: AsyncSession) -> dict[str, Any]:
"""Query failed collection tasks and unhealthy data sources, degrading safely."""
summary: dict[str, Any] = {
"failed_tasks_24h": 0,
"recent_failed_tasks": [],
"failed_datasources": [],
}
try:
cutoff = datetime.now(UTC) - timedelta(hours=24)
failed_24h_count = await db.execute(
select(func.count(CollectionTask.id))
.where(CollectionTask.status == "failed")
.where(CollectionTask.created_at >= cutoff)
)
failed_tasks_rows = await db.execute(
select(CollectionTask)
.where(CollectionTask.status == "failed")
.order_by(CollectionTask.created_at.desc(), CollectionTask.id.desc())
.limit(6)
)
failed_sources_rows = await db.execute(
select(DataSource)
.where(DataSource.is_active.is_(True))
.where(DataSource.last_status.in_(["failed", "error"]))
)
summary["failed_tasks_24h"] = int(failed_24h_count.scalar() or 0)
summary["recent_failed_tasks"] = [
{
"source": task.source or f"datasource:{task.datasource_id}",
"task_type": task.task_type,
"error": (task.error_message or "")[:160],
}
for task in failed_tasks_rows.scalars().all()
]
summary["failed_datasources"] = [
{"source": ds.source, "name": ds.name, "status": ds.last_status}
for ds in failed_sources_rows.scalars().all()
]
except Exception:
# Keep brief generation resilient even in minimal test DB fixtures.
pass
return summary
async def build_alert_brief_request(
db: AsyncSession,
*,
@@ -76,6 +123,28 @@ async def build_alert_brief_request(
)
)
health = await _collect_operational_health(db)
failed_sources = health["failed_datasources"]
failed_tasks = health["recent_failed_tasks"]
facts.append(
f"近 24 小时采集任务失败 {health['failed_tasks_24h']} 次,"
f"当前处于异常/失败状态的活跃数据源 {len(failed_sources)} 个。"
)
if failed_sources:
facts.append(
"异常数据源:"
+ "、".join(f"{item['name']} ({item['source']})" for item in failed_sources[:6])
+ "。"
)
if failed_tasks:
facts.append(
"最近失败任务摘录:"
+ ";".join(
f"{item['source']} [{item['task_type']}] {item['error'] or 'failed'}"
for item in failed_tasks[:4]
)
)
context = {
"source": "alerts",
"total_alerts": total_alerts,
@@ -86,6 +155,9 @@ async def build_alert_brief_request(
"status_distribution": dict(status_counts),
"top_datasources": dict(datasource_counts.most_common(6)),
"top_active_datasources": dict(active_datasource_counts.most_common(5)),
"failed_tasks_24h": health["failed_tasks_24h"],
"recent_failed_tasks": failed_tasks,
"failed_datasources": failed_sources,
}
prompt = await get_effective_prompt(db, ALERT_BRIEF_PROMPT_KEY)
+315
View File
@@ -0,0 +1,315 @@
"""API key lifecycle, scope evaluation, hashing, and rate-limited validation."""
from __future__ import annotations
import asyncio
from collections import defaultdict, deque
from datetime import UTC, datetime, timedelta
import hashlib
import secrets
import time
from typing import Any
from fastapi import HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.core.security import REDIS_OP_TIMEOUT_SECONDS, _AsyncRedisClient
from app.core.time import to_iso8601_utc
from app.models.api_key import ApiKey
logger = get_logger(__name__, service="api_keys")
API_KEY_PREFIX = "plt_live_"
EARTH_ALL_READ_SCOPE = "earth:all_read"
EARTH_READ_SCOPES: frozenset[str] = frozenset(
{
"visualization:read",
"layers:read",
"vessels:read",
"news:read",
"data_products:read",
"situational:read",
"earth:read",
"interactables:read",
"tv:read",
"ws:connect",
}
)
VALID_API_KEY_SCOPES: frozenset[str] = frozenset({EARTH_ALL_READ_SCOPE, *EARTH_READ_SCOPES})
_LAST_USED_TOUCH_CACHE: dict[int, float] = {}
_LOCAL_KEY_RATE_WINDOWS: dict[str, deque[float]] = defaultdict(deque)
_LAST_USED_MIN_INTERVAL_SECONDS = 60.0
def reset_api_key_runtime_caches() -> None:
"""Clear in-process caches (intended for deterministic tests)."""
_LAST_USED_TOUCH_CACHE.clear()
_LOCAL_KEY_RATE_WINDOWS.clear()
def hash_api_key(raw_key: str) -> str:
"""Compute SHA-256 hex digest of a raw API key."""
return hashlib.sha256(raw_key.strip().encode("utf-8")).hexdigest()
def mask_api_key_prefix(raw_key: str) -> str:
"""Return a short non-sensitive prefix for UI display and logging."""
cleaned = raw_key.strip()
return f"{cleaned[:16]}..." if len(cleaned) > 16 else f"{cleaned[:8]}..."
def normalize_api_key_scopes(scopes: list[str] | None) -> list[str]:
"""Validate and deduplicate requested API key scopes."""
if not scopes:
return [EARTH_ALL_READ_SCOPE]
normalized: list[str] = []
seen: set[str] = set()
invalid: list[str] = []
for raw in scopes:
scope = str(raw or "").strip()
if not scope:
continue
if scope not in VALID_API_KEY_SCOPES:
invalid.append(scope)
continue
if scope not in seen:
seen.add(scope)
normalized.append(scope)
if invalid:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Unsupported API key scope(s): {', '.join(invalid)}",
)
if not normalized:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="At least one valid scope is required",
)
return normalized
def api_key_allows_scope(key_scopes: list[str] | None, required_scope: str) -> bool:
"""Return True if the key scopes authorize `required_scope`."""
scopes = {str(item).strip() for item in (key_scopes or []) if item}
if required_scope in scopes:
return True
if EARTH_ALL_READ_SCOPE in scopes and required_scope in EARTH_READ_SCOPES:
return True
return False
def _ensure_utc(dt: datetime | None) -> datetime | None:
if dt is None:
return None
if dt.tzinfo is None:
return dt.replace(tzinfo=UTC)
return dt.astimezone(UTC)
def serialize_api_key(record: ApiKey) -> dict[str, Any]:
"""Serialize ApiKey metadata safely without exposing key_hash or raw secret."""
now = datetime.now(UTC)
expires_at = _ensure_utc(record.expires_at)
is_expired = bool(expires_at is not None and expires_at <= now)
status_label = "revoked" if not record.is_active else ("expired" if is_expired else "active")
return {
"id": record.id,
"name": record.name,
"key_prefix": record.key_prefix,
"scopes": list(record.scopes or []),
"rate_limit_per_minute": record.rate_limit_per_minute,
"expires_at": to_iso8601_utc(expires_at),
"is_active": bool(record.is_active),
"is_expired": is_expired,
"status": status_label,
"created_by_user_id": record.created_by_user_id,
"last_used_at": to_iso8601_utc(_ensure_utc(record.last_used_at)),
"revoked_at": to_iso8601_utc(_ensure_utc(record.revoked_at)),
"created_at": to_iso8601_utc(_ensure_utc(record.created_at)),
}
async def _enforce_api_key_rate_limit(key_id: int, limit_per_minute: int | None) -> None:
if limit_per_minute is None or int(limit_per_minute) <= 0:
return
limit = int(limit_per_minute)
window = 60
bucket = f"rate:api_key:{key_id}"
try:
client = _AsyncRedisClient.get_client()
current_count = await asyncio.wait_for(
client.incr(bucket),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
if int(current_count) == 1:
await asyncio.wait_for(client.expire(bucket, window), timeout=REDIS_OP_TIMEOUT_SECONDS)
if int(current_count) > limit:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="API key rate limit exceeded",
)
return
except HTTPException:
raise
except Exception:
pass
now = time.monotonic()
dq = _LOCAL_KEY_RATE_WINDOWS[bucket]
cutoff = now - float(window)
while dq and dq[0] <= cutoff:
dq.popleft()
if len(dq) >= limit:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="API key rate limit exceeded",
)
dq.append(now)
async def create_api_key(
db: AsyncSession,
*,
name: str,
scopes: list[str] | None,
rate_limit_per_minute: int | None,
expires_in_days: int | None,
created_by_user_id: int | None,
) -> tuple[ApiKey, str]:
"""Create and persist a new API key, returning `(record, raw_plaintext_once)`."""
cleaned_name = str(name or "").strip()
if not cleaned_name:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="API key name is required",
)
normalized_scopes = normalize_api_key_scopes(scopes)
normalized_limit = (
int(rate_limit_per_minute)
if rate_limit_per_minute is not None and int(rate_limit_per_minute) > 0
else None
)
expires_at: datetime | None = None
if expires_in_days is not None and int(expires_in_days) > 0:
expires_at = datetime.now(UTC) + timedelta(days=int(expires_in_days))
raw_key = f"{API_KEY_PREFIX}{secrets.token_urlsafe(32)}"
record = ApiKey(
name=cleaned_name[:120],
key_prefix=mask_api_key_prefix(raw_key),
key_hash=hash_api_key(raw_key),
scopes=normalized_scopes,
rate_limit_per_minute=normalized_limit,
expires_at=expires_at,
is_active=True,
created_by_user_id=created_by_user_id,
)
db.add(record)
await db.commit()
await db.refresh(record)
logger.info_event(
"Created API key",
event="api_key.created",
context={
"key_id": record.id,
"key_prefix": record.key_prefix,
"scopes": normalized_scopes,
"has_expiry": expires_at is not None,
"rate_limit_per_minute": normalized_limit,
"created_by_user_id": created_by_user_id,
},
)
return record, raw_key
async def list_api_keys(db: AsyncSession) -> list[ApiKey]:
result = await db.execute(select(ApiKey).order_by(ApiKey.created_at.desc(), ApiKey.id.desc()))
return list(result.scalars().all())
async def revoke_api_key(db: AsyncSession, key_id: int) -> ApiKey:
result = await db.execute(select(ApiKey).where(ApiKey.id == key_id))
record = result.scalar_one_or_none()
if record is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="API key not found")
if record.is_active:
record.is_active = False
record.revoked_at = datetime.now(UTC)
await db.commit()
await db.refresh(record)
logger.info_event(
"Revoked API key",
event="api_key.revoked",
context={"key_id": record.id, "key_prefix": record.key_prefix},
)
return record
async def delete_api_key(db: AsyncSession, key_id: int) -> None:
result = await db.execute(select(ApiKey).where(ApiKey.id == key_id))
record = result.scalar_one_or_none()
if record is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="API key not found")
prefix = record.key_prefix
await db.delete(record)
await db.commit()
logger.info_event(
"Deleted API key",
event="api_key.deleted",
context={"key_id": key_id, "key_prefix": prefix},
)
async def authenticate_api_key(
db: AsyncSession,
raw_key: str,
required_scope: str,
) -> ApiKey:
"""Validate an incoming raw API key for active status, expiration, scope, and rate limit."""
cleaned = str(raw_key or "").strip()
if not cleaned:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid API key",
)
digest = hash_api_key(cleaned)
result = await db.execute(select(ApiKey).where(ApiKey.key_hash == digest))
record = result.scalar_one_or_none()
if record is None or not record.is_active:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or revoked API key",
)
expires_at = _ensure_utc(record.expires_at)
if expires_at is not None and expires_at <= datetime.now(UTC):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="API key has expired",
)
if not api_key_allows_scope(list(record.scopes or []), required_scope):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"API key lacks required scope: {required_scope}",
)
await _enforce_api_key_rate_limit(int(record.id), record.rate_limit_per_minute)
now_mono = time.monotonic()
last_touched = _LAST_USED_TOUCH_CACHE.get(int(record.id), 0.0)
if now_mono - last_touched >= _LAST_USED_MIN_INTERVAL_SECONDS:
_LAST_USED_TOUCH_CACHE[int(record.id)] = now_mono
try:
record.last_used_at = datetime.now(UTC)
await db.commit()
except Exception:
await db.rollback()
return record
+103 -5
View File
@@ -4,6 +4,7 @@ from datetime import UTC, datetime
import asyncio
import json
import os
import time
from typing import Any
from sqlalchemy import select
@@ -14,10 +15,13 @@ from app.core.time import to_iso8601_utc
from app.core.websocket.broadcaster import broadcaster
from app.models.datasource_config import DataSourceConfig
from app.models.task import CollectionTask
from app.services.collectors.base import BaseCollector
from app.models.vessel import VesselCurrentState
from app.services.collectors.base import BaseCollector, _StoragePolicyDowngradedToSingle
from app.services.storage_policy import is_storage_policy_single_violation
from app.services.vessel_ais_aggregation import (
AISSTREAM_DELIVERY_MODE,
AISSTREAM_TRANSPORT,
prune_expired_vessel_track_points,
record_vessel_ais_observation,
update_ais_source_health,
)
@@ -282,12 +286,98 @@ class AISStreamCollector(BaseCollector):
records.append(record)
return records
async def _has_existing_current_data(self, db: AsyncSession | None) -> bool:
if db is None or not callable(getattr(db, "execute", None)):
return False
try:
result = await db.execute(
select(VesselCurrentState.mmsi)
.where(VesselCurrentState.source == self.name)
.limit(1)
)
except Exception:
return False
if result is None or not callable(getattr(result, "scalar_one_or_none", None)):
return False
return result.scalar_one_or_none() is not None
async def _should_persist_raw_ais(
self,
db: AsyncSession,
*,
force_refresh: bool = False,
) -> tuple[bool, str]:
now_mono = time.monotonic()
cached_at = float(getattr(self, "_stream_mode_checked_at", 0.0))
if (
not force_refresh
and (now_mono - cached_at) < 2.0
and self._snapshot_mode is not None
):
return self._snapshot_mode == "history", self._snapshot_mode
if callable(getattr(db, "execute", None)):
mode, _ = await self._resolve_storage_policy(db)
self._stream_mode_checked_at = now_mono
return mode == "history", mode
mode = self._snapshot_mode or "single"
return mode == "history", mode
async def _save_data(
self,
db: AsyncSession,
data: list[dict[str, Any]],
task_id: int | None = None,
snapshot_id: int | None = None,
) -> int:
persist_raw, mode = await self._should_persist_raw_ais(db, force_refresh=True)
snapshot_id = await self._reconcile_snapshot_for_mode_switch(
db,
mode=mode,
task_id=task_id,
snapshot_id=snapshot_id,
)
try:
records_added = await self._write_aisstream_batch(
db,
data,
persist_raw=persist_raw,
mode=mode,
snapshot_id=snapshot_id,
)
if persist_raw:
await self._assert_versioned_publish_allowed(db, snapshot_id=snapshot_id)
await db.commit()
except Exception as exc:
if (
(not isinstance(exc, _StoragePolicyDowngradedToSingle) and not is_storage_policy_single_violation(exc))
or self._previous_current_snapshot_id is None
):
raise
downgraded_snapshot_id = await self._downgrade_pending_snapshot_to_single(
db,
task_id=task_id,
snapshot_id=snapshot_id,
)
records_added = await self._write_aisstream_batch(
db,
data,
persist_raw=False,
mode="single",
snapshot_id=downgraded_snapshot_id,
)
await db.commit()
await self.update_progress(records_added, force=True)
return records_added
async def _write_aisstream_batch(
self,
db: AsyncSession,
data: list[dict[str, Any]],
*,
persist_raw: bool,
mode: str,
snapshot_id: int | None,
) -> int:
now = datetime.now(UTC)
records_added = 0
@@ -305,13 +395,17 @@ class AISStreamCollector(BaseCollector):
source_message_id=item.get("_source_message_id"),
observed_at=observed_at,
collected_at=now,
persist_raw=persist_raw,
)
if observation is not None:
records_added += 1
if isinstance(observed_at, datetime) and observed_at > latest_observed_at:
latest_observed_at = observed_at
if (index + 1) % 1000 == 0:
await self.update_progress(index + 1, commit=True)
await self.update_progress(index + 1, commit=False)
if not persist_raw:
await prune_expired_vessel_track_points(db, now=now)
await update_ais_source_health(
db,
@@ -327,6 +421,7 @@ class AISStreamCollector(BaseCollector):
snapshot = await db.get(DataSnapshot, snapshot_id)
if snapshot:
await self._promote_snapshot_to_current(db, snapshot)
snapshot.record_count = records_added
snapshot.status = "success"
snapshot.completed_at = now
@@ -335,13 +430,13 @@ class AISStreamCollector(BaseCollector):
"updated": 0,
"unchanged": 0,
"deleted": 0,
"storage": "ais_raw_observations",
"storage": "ais_raw_observations" if persist_raw else "vessel_current_state_and_24h_track",
"storage_mode": mode,
}
await db.commit()
await self.update_progress(records_added, force=True)
return records_added
async def _save_stream_record(self, db: AsyncSession, item: dict[str, Any]) -> bool:
persist_raw, _mode = await self._should_persist_raw_ais(db)
now = datetime.now(UTC)
observed_at = item.get("received_at") or now
observation = await record_vessel_ais_observation(
@@ -355,7 +450,10 @@ class AISStreamCollector(BaseCollector):
source_message_id=item.get("_source_message_id"),
observed_at=observed_at,
collected_at=now,
persist_raw=persist_raw,
)
if not persist_raw:
await prune_expired_vessel_track_points(db, now=now)
await update_ais_source_health(
db,
source=self.name,
File diff suppressed because it is too large. Load diff
+70 -15
View File
@@ -4,15 +4,14 @@ from __future__ import annotations
import hashlib
from collections import defaultdict
from datetime import UTC, datetime
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import select
from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.bgp_anomaly import BGPAnomaly
from app.models.bgp_observation import BGPObservation
from app.models.collected_data import CollectedData
from app.services.bgp_collector_locations import (
RIPE_RIS_COLLECTOR_COORDS,
get_bgp_collector_location_dict,
@@ -37,11 +36,49 @@ from app.services.bgp_enrichment import enrich_bgp_events_for_batch, extract_bgp
__all__ = [
"RIPE_RIS_COLLECTOR_COORDS",
"normalize_bgp_event",
"slim_bgp_events_for_collected_data",
"compact_bgp_raw_payload",
"save_bgp_observations_for_batch",
"create_bgp_anomalies_for_batch",
]
def compact_bgp_raw_payload(metadata: dict[str, Any]) -> dict[str, Any]:
"""Build a compact BGP observation summary payload without raw verbose envelopes."""
compact: dict[str, Any] = {}
for key in (
"event_type",
"prefix",
"origin_asn",
"as_path",
"collector",
"peer_ip",
"peer_asn",
"next_hop",
"communities",
"timestamp",
):
value = metadata.get(key)
if value not in (None, [], ""):
compact[key] = value
return compact
def slim_bgp_events_for_collected_data(
events: list[dict[str, Any]],
*,
max_rows: int = 500,
) -> list[dict[str, Any]]:
"""Strip heavyweight `raw_message` payloads and bound single-copy BGP batch size."""
selected = events[-max_rows:] if max_rows > 0 and len(events) > max_rows else list(events)
slimmed: list[dict[str, Any]] = []
for event in selected:
metadata = dict(event.get("metadata") or {})
metadata.pop("raw_message", None)
slimmed.append({**event, "metadata": metadata})
return slimmed
def _safe_int(value: Any) -> int | None:
try:
if value in (None, ""):
@@ -184,6 +221,7 @@ async def save_bgp_observations_for_batch(
snapshot_id: int | None,
task_id: int | None,
events: list[dict[str, Any]],
compact_raw_payload: bool = False,
) -> int:
if not events:
return 0
@@ -197,6 +235,11 @@ async def save_bgp_observations_for_batch(
observed_at = _parse_timestamp(
metadata.get("timestamp") or event.get("reference_date")
)
raw_payload = (
compact_bgp_raw_payload(metadata)
if compact_raw_payload
else (metadata.get("raw_message") or {})
)
db.add(
BGPObservation(
@@ -216,7 +259,7 @@ async def save_bgp_observations_for_batch(
communities=metadata.get("communities") or [],
observed_at=observed_at,
collector_geo=collector_location,
raw_payload=metadata.get("raw_message") or {},
raw_payload=raw_payload,
note=event.get("description"),
)
)
@@ -224,8 +267,8 @@ async def save_bgp_observations_for_batch(
if created:
await db.commit()
for source in {"ris_live_bgp", "bgpstream_bgp"}:
invalidate_earth_layer_cache_for_source(source)
for cache_source in {"ris_live_bgp", "bgpstream_bgp"}:
invalidate_earth_layer_cache_for_source(cache_source)
return created
@@ -255,17 +298,29 @@ async def create_bgp_anomalies_for_batch(
previous_origin_map: dict[str, set[int]] = defaultdict(set)
if prefixes:
previous_query = await db.execute(
select(CollectedData).where(
CollectedData.source == source,
CollectedData.snapshot_id != snapshot_id,
CollectedData.extra_data["prefix"].as_string().in_(sorted(prefixes)),
lookback_since = datetime.now(UTC) - timedelta(days=7)
baseline_filters = [
BGPObservation.source == source,
BGPObservation.prefix.in_(sorted(prefixes)),
BGPObservation.origin_asn.is_not(None),
BGPObservation.observed_at >= lookback_since,
]
if task_id is not None:
baseline_filters.append(
or_(BGPObservation.task_id.is_(None), BGPObservation.task_id != task_id)
)
)
elif snapshot_id is not None:
baseline_filters.append(
or_(BGPObservation.snapshot_id.is_(None), BGPObservation.snapshot_id != snapshot_id)
)
previous_query = await db.execute(select(BGPObservation).where(*baseline_filters))
for record in previous_query.scalars().all():
metadata = record.extra_data or {}
prefix = metadata.get("prefix")
origin = _safe_int(metadata.get("origin_asn"))
prefix = getattr(record, "prefix", None)
origin = _safe_int(getattr(record, "origin_asn", None))
if (prefix is None or origin is None) and hasattr(record, "extra_data"):
metadata = record.extra_data or {}
prefix = prefix or metadata.get("prefix")
origin = origin if origin is not None else _safe_int(metadata.get("origin_asn"))
if prefix and origin is not None:
previous_origin_map[prefix].add(origin)
@@ -14,6 +14,7 @@ from app.services.collectors.bgp_common import (
create_bgp_anomalies_for_batch,
normalize_bgp_event,
save_bgp_observations_for_batch,
slim_bgp_events_for_collected_data,
)
@@ -96,6 +97,29 @@ class BGPStreamBackfillCollector(BaseCollector):
self._latest_transformed_batch = transformed
return transformed
async def _save_data(
self,
db,
data: list[dict[str, Any]],
task_id: int | None = None,
snapshot_id: int | None = None,
) -> int:
if callable(getattr(db, "execute", None)):
mode, policy = await self._resolve_storage_policy(db)
else:
mode = self._snapshot_mode
policy = self._storage_policy or {}
prepared_data = data
if (mode or "single") == "single":
max_rows = int(policy.get("bgp_single_batch_max_rows", 500))
prepared_data = slim_bgp_events_for_collected_data(data, max_rows=max_rows)
return await super()._save_data(
db,
prepared_data,
task_id=task_id,
snapshot_id=snapshot_id,
)
async def run(self, db):
result = await super().run(db)
if result.get("status") != "success":
@@ -108,6 +132,7 @@ class BGPStreamBackfillCollector(BaseCollector):
snapshot_id=snapshot_id,
task_id=result.get("task_id"),
events=getattr(self, "_latest_transformed_batch", []),
compact_raw_payload=(self._snapshot_mode != "history"),
)
anomaly_count = await create_bgp_anomalies_for_batch(
db,
@@ -121,6 +146,10 @@ class BGPStreamBackfillCollector(BaseCollector):
return result
async def _resolve_snapshot_id(self, db, task_id: int | None) -> int | None:
if getattr(self, "_deduped_unchanged_snapshot_id", None) is not None:
return self._deduped_unchanged_snapshot_id
if getattr(self, "_reused_snapshot_id", None) is not None:
return self._reused_snapshot_id
if task_id is None:
return None
from sqlalchemy import select
@@ -98,7 +98,18 @@ class CelesTrakTLECollector(BaseCollector):
progress_callback=self._report_download_progress,
validate_existing=self._validate_json_file,
)
file_sha256 = self._downloader.get_file_sha256(url, ".json", body_path)
if file_sha256:
self._last_source_file_sha256 = file_sha256
short_snap = await self._can_short_circuit_unchanged_file(
self._db_session,
file_sha256=file_sha256,
)
if short_snap is not None:
self._short_circuited_snapshot_id = short_snap.id
return []
data = await self._load_downloaded_payload(body_path, url)
self._mark_fetch_complete(True)
await emit_business_log(
logger,
event="collector.celestrak.download.success",
@@ -124,7 +135,18 @@ class CelesTrakTLECollector(BaseCollector):
validate_existing=self._validate_json_file,
)
if cached_path is not None:
file_sha256 = self._downloader.get_file_sha256(url, ".json", cached_path)
if file_sha256:
self._last_source_file_sha256 = file_sha256
short_snap = await self._can_short_circuit_unchanged_file(
self._db_session,
file_sha256=file_sha256,
)
if short_snap is not None:
self._short_circuited_snapshot_id = short_snap.id
return []
data = await self._load_downloaded_payload(cached_path, url)
self._mark_fetch_complete(True)
await emit_business_log(
logger,
event="collector.celestrak.download.cached_not_updated",
@@ -295,6 +317,7 @@ class CelesTrakTLECollector(BaseCollector):
if not records:
raise RuntimeError("CelesTrak fallback group mode produced no satellite records")
self._mark_fetch_complete(False)
await emit_business_log(
logger,
event="collector.celestrak.fallback_groups.success",
@@ -465,6 +488,7 @@ class CelesTrakTLECollector(BaseCollector):
return None
def _get_sample_data(self) -> List[Dict[str, Any]]:
self._mark_sample_fallback("celestrak_tle_sample_fallback")
return [
{
"name": "STARLINK-1000",
@@ -14,6 +14,7 @@ from app.services.collectors.base import BaseCollector
class ComputeCollector(BaseCollector):
fail_on_empty = True
preserve_snapshot_on_failure = True
full_snapshot_reconcile = True
async def _create_snapshot(
self, db: AsyncSession, task_id: int, data: list[dict], started_at: datetime
@@ -16,6 +16,18 @@ ProgressCallback = Callable[[int, int | None], Awaitable[None]]
ValidateCallback = Callable[[Path], bool]
def compute_file_sha256(path: Path, *, chunk_size: int = 1024 * 1024) -> str:
"""Compute SHA-256 hex digest of a local file without loading it all into memory."""
hasher = hashlib.sha256()
with path.open("rb") as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
hasher.update(chunk)
return hasher.hexdigest()
class DownloadHTTPStatusError(RuntimeError):
"""HTTP status error that keeps the upstream response body for caller-specific handling."""
@@ -105,6 +117,47 @@ class ResumableFileDownloader:
def _save_meta(meta_path: Path, payload: dict[str, Any]) -> None:
meta_path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
@staticmethod
def compute_combined_sha256(digests: list[str]) -> str:
"""Combine multiple file SHA-256 digests deterministically."""
return hashlib.sha256("|".join(digests).encode("utf-8")).hexdigest()
def get_file_sha256(
self,
url: str,
extension: str,
path: Path | None = None,
) -> str | None:
"""Return cached or freshly computed SHA-256 digest for a downloaded dataset."""
target_path = path or self.cached_file_path(url, extension)
if not target_path.exists():
return None
_, _, meta_path = self._cache_paths(url, extension)
stat = target_path.stat()
meta = self._load_meta(meta_path)
cached_digest = meta.get("sha256")
if (
isinstance(cached_digest, str)
and cached_digest
and meta.get("file_size") == stat.st_size
and meta.get("file_mtime_ns") == stat.st_mtime_ns
):
return cached_digest
digest = compute_file_sha256(target_path)
if meta_path.parent.exists():
self._save_meta(
meta_path,
{
**meta,
"url": meta.get("url") or url,
"sha256": digest,
"file_size": stat.st_size,
"file_mtime_ns": stat.st_mtime_ns,
},
)
return digest
@staticmethod
def _validators_match(meta: dict[str, Any], remote: dict[str, Any]) -> bool:
etag = str(remote.get("etag") or "").strip()
@@ -262,6 +315,8 @@ class ResumableFileDownloader:
part_path.unlink(missing_ok=True)
raise RuntimeError(f"Downloaded file validation failed for {url}")
part_path.replace(final_path)
stat = final_path.stat()
file_sha256 = compute_file_sha256(final_path)
self._save_meta(
meta_path,
{
@@ -269,6 +324,9 @@ class ResumableFileDownloader:
"etag": remote.get("etag"),
"last_modified": remote.get("last_modified"),
"content_length": expected_size,
"sha256": file_sha256,
"file_size": stat.st_size,
"file_mtime_ns": stat.st_mtime_ns,
"updated_at": datetime.now(UTC).isoformat(),
},
)
+36 -12
View File
@@ -65,29 +65,40 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
raise RuntimeError(f"IPtoASN dataset parsed empty rows: {file_path.name}")
return rows
async def _fetch_dataset_rows(
async def _download_dataset_file(
self,
client: httpx.AsyncClient,
url: str,
*,
progress_callback=None,
) -> list[dict[str, Any]]:
file_path = await self._downloader.download_file(
) -> Path:
return await self._downloader.download_file(
client,
url,
extension=".tsv.gz",
progress_callback=progress_callback,
validate_existing=lambda p: self._validate_gzip_dataset(p),
)
return self._parse_rows_from_gzip_file(file_path)
def _validate_gzip_dataset(self, file_path: Path) -> bool:
try:
self._parse_rows_from_gzip_file(file_path)
return True
with gzip.open(file_path, "rt", encoding="utf-8", errors="replace") as f:
for raw_line in f:
line = raw_line.strip()
if line and not line.startswith("#") and len(line.split("\t")) >= 5:
for _ in f:
pass
return True
return False
except Exception:
return False
def _parse_dataset_files(self, dataset_paths: list[Path]) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
for path in dataset_paths:
rows.extend(self._parse_rows_from_gzip_file(path))
return rows
async def fetch(self) -> list[dict[str, Any]]:
if not self._resolved_url:
raise RuntimeError("IPtoASN combined URL is not configured")
@@ -149,9 +160,9 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
)
await self.update_progress(current, commit=True)
batches = await asyncio.gather(
dataset_paths = await asyncio.gather(
*(
self._fetch_dataset_rows(
self._download_dataset_file(
client,
url,
progress_callback=lambda downloaded, total, u=url: on_url_progress(u, downloaded, total),
@@ -168,10 +179,23 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
)
await self.update_progress(total_expected, commit=True, force=True)
rows: list[dict[str, Any]] = []
for batch in batches:
rows.extend(batch)
return rows
digests = [
self._downloader.get_file_sha256(url, ".tsv.gz", path)
for url, path in zip(dataset_urls, dataset_paths)
]
if digests and all(isinstance(d, str) and d for d in digests):
combined_sha256 = self._downloader.compute_combined_sha256([str(d) for d in digests])
self._last_source_file_sha256 = combined_sha256
short_snap = await self._can_short_circuit_unchanged_file(
self._db_session,
file_sha256=combined_sha256,
)
if short_snap is not None:
self._short_circuited_snapshot_id = short_snap.id
return []
self._mark_fetch_complete(True)
return await asyncio.to_thread(self._parse_dataset_files, dataset_paths)
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
reference_date = datetime.now(UTC).isoformat()
@@ -6,8 +6,10 @@ allocation geography as prefix-centric fallback hints.
from __future__ import annotations
import asyncio
import ipaddress
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
import httpx
@@ -64,42 +66,57 @@ class NRODelegatedPrefixGeoCollector(BaseCollector):
extension=".txt",
progress_callback=on_progress,
)
body = body_path.read_text(encoding="utf-8", errors="replace")
file_sha256 = self._downloader.get_file_sha256(self._resolved_url, ".txt", body_path)
if file_sha256:
self._last_source_file_sha256 = file_sha256
short_snap = await self._can_short_circuit_unchanged_file(
self._db_session,
file_sha256=file_sha256,
)
if short_snap is not None:
self._short_circuited_snapshot_id = short_snap.id
return []
self._mark_fetch_complete(True)
return await asyncio.to_thread(self._parse_delegated_file, body_path)
def _parse_delegated_file(self, body_path: Path) -> list[dict[str, Any]]:
"""Stream and parse NRO delegated stats line-by-line off the event loop."""
rows: list[dict[str, Any]] = []
for raw_line in body.splitlines():
line = raw_line.strip()
if not line or line.startswith("#"):
continue
with body_path.open("r", encoding="utf-8", errors="replace") as handle:
for raw_line in handle:
line = raw_line.strip()
if not line or line.startswith("#"):
continue
parts = line.split("|")
if len(parts) < 7:
continue
parts = line.split("|")
if len(parts) < 7:
continue
rir = (parts[0] or "").strip().lower()
country_code = (parts[1] or "").strip().upper()
record_type = (parts[2] or "").strip().lower()
start = (parts[3] or "").strip()
value = (parts[4] or "").strip()
allocated_date = (parts[5] or "").strip()
status = (parts[6] or "").strip().lower()
rir = (parts[0] or "").strip().lower()
country_code = (parts[1] or "").strip().upper()
record_type = (parts[2] or "").strip().lower()
start = (parts[3] or "").strip()
value = (parts[4] or "").strip()
allocated_date = (parts[5] or "").strip()
status = (parts[6] or "").strip().lower()
if record_type not in {"ipv4", "ipv6"}:
continue
if not start or not value:
continue
if record_type not in {"ipv4", "ipv6"}:
continue
if not start or not value:
continue
rows.append(
{
"rir": rir,
"country_code": country_code,
"type": record_type,
"start": start,
"value": value,
"allocated_date": allocated_date,
"status": status,
}
)
rows.append(
{
"rir": rir,
"country_code": country_code,
"type": record_type,
"start": start,
"value": value,
"allocated_date": allocated_date,
"status": status,
}
)
return rows
@@ -65,6 +65,16 @@ class OpenGeoFeedPrefixGeoCollector(BaseCollector):
extension=".csv",
progress_callback=on_progress,
)
file_sha256 = self._downloader.get_file_sha256(self._resolved_url, ".csv", body_path)
if file_sha256:
self._last_source_file_sha256 = file_sha256
short_snap = await self._can_short_circuit_unchanged_file(
self._db_session,
file_sha256=file_sha256,
)
if short_snap is not None:
self._short_circuited_snapshot_id = short_snap.id
return []
body = body_path.read_text(encoding="utf-8", errors="replace")
rows: list[dict[str, Any]] = []
@@ -17,6 +17,7 @@ from app.services.collectors.bgp_common import (
create_bgp_anomalies_for_batch,
normalize_bgp_event,
save_bgp_observations_for_batch,
slim_bgp_events_for_collected_data,
)
logger = get_logger(__name__, service="collector")
@@ -177,6 +178,29 @@ class RISLiveCollector(BaseCollector):
self._latest_transformed_batch = transformed
return transformed
async def _save_data(
self,
db,
data: list[dict[str, Any]],
task_id: int | None = None,
snapshot_id: int | None = None,
) -> int:
if callable(getattr(db, "execute", None)):
mode, policy = await self._resolve_storage_policy(db)
else:
mode = self._snapshot_mode
policy = self._storage_policy or {}
prepared_data = data
if (mode or "single") == "single":
max_rows = int(policy.get("bgp_single_batch_max_rows", 500))
prepared_data = slim_bgp_events_for_collected_data(data, max_rows=max_rows)
return await super()._save_data(
db,
prepared_data,
task_id=task_id,
snapshot_id=snapshot_id,
)
async def run(self, db):
result = await super().run(db)
if result.get("status") != "success":
@@ -189,6 +213,7 @@ class RISLiveCollector(BaseCollector):
snapshot_id=snapshot_id,
task_id=result.get("task_id"),
events=getattr(self, "_latest_transformed_batch", []),
compact_raw_payload=(self._snapshot_mode != "history"),
)
anomaly_count = await create_bgp_anomalies_for_batch(
db,
@@ -202,6 +227,10 @@ class RISLiveCollector(BaseCollector):
return result
async def _resolve_snapshot_id(self, db, task_id: int | None) -> int | None:
if getattr(self, "_deduped_unchanged_snapshot_id", None) is not None:
return self._deduped_unchanged_snapshot_id
if getattr(self, "_reused_snapshot_id", None) is not None:
return self._reused_snapshot_id
if task_id is None:
return None
from sqlalchemy import select
@@ -213,6 +213,7 @@ class SpaceTrackTLECollector(BaseCollector):
def _get_sample_data(self) -> List[Dict[str, Any]]:
"""Return sample TLE data for testing"""
self._mark_sample_fallback("spacetrack_tle_sample_fallback")
return [
{
"name": "ISS (ZARYA)",
@@ -119,6 +119,7 @@ class TeleGeographyCableCollector(BaseCollector):
def _get_sample_data(self) -> List[Dict[str, Any]]:
"""Return sample submarine cable data"""
self._mark_sample_fallback("telegeography_cables_sample_fallback")
return [
{
"source_id": "telegeo_sample_1",
@@ -235,6 +236,7 @@ class TeleGeographyLandingPointCollector(BaseCollector):
def _get_sample_data(self) -> List[Dict[str, Any]]:
"""Return sample landing point data"""
self._mark_sample_fallback("telegeography_landing_sample_fallback")
return [
{
"source_id": "telegeo_lp_sample_1",
@@ -306,6 +308,7 @@ class TeleGeographyCableSystemCollector(BaseCollector):
def _get_sample_data(self) -> List[Dict[str, Any]]:
"""Return sample cable system data"""
self._mark_sample_fallback("telegeography_systems_sample_fallback")
return [
{
"source_id": "telegeo_sys_sample_1",
+89 -6
View File
@@ -4,20 +4,24 @@ from datetime import UTC, datetime
from typing import Any
import httpx
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.enums import SnapshotStatus
from app.core.time import to_iso8601_utc
from app.core.websocket.broadcaster import broadcaster
from app.models.vessel import VesselCurrentState
from app.services.barentswatch import (
BARENTSWATCH_LATEST_URL,
fetch_barentswatch_access_token,
resolve_barentswatch_config,
)
from app.services.collectors.base import BaseCollector
from app.services.collectors.base import BaseCollector, _StoragePolicyDowngradedToSingle
from app.services.storage_policy import is_storage_policy_single_violation
from app.services.vessel_ais_aggregation import (
BARENTSWATCH_DELIVERY_MODE,
BARENTSWATCH_TRANSPORT,
prune_expired_vessel_track_points,
record_vessel_ais_observation,
update_ais_source_health,
)
@@ -80,12 +84,87 @@ class VesselAISCollector(BaseCollector):
transformed.append(record)
return transformed
async def _has_existing_current_data(self, db: AsyncSession | None) -> bool:
if db is None or not callable(getattr(db, "execute", None)):
return False
try:
result = await db.execute(
select(VesselCurrentState.mmsi)
.where(VesselCurrentState.source == self.name)
.limit(1)
)
except Exception:
return False
if result is None or not callable(getattr(result, "scalar_one_or_none", None)):
return False
return result.scalar_one_or_none() is not None
async def _save_data(
self,
db: AsyncSession,
data: list[dict[str, Any]],
task_id: int | None = None,
snapshot_id: int | None = None,
) -> int:
if callable(getattr(db, "execute", None)):
mode, _ = await self._resolve_storage_policy(db)
else:
mode = self._snapshot_mode or "single"
if self._fetch_is_sample_fallback and await self._has_existing_current_data(db):
raise RuntimeError(
f"Collector {self.name} refused to save sample fallback data over existing vessels"
)
persist_raw = mode == "history"
snapshot_id = await self._reconcile_snapshot_for_mode_switch(
db,
mode=mode,
task_id=task_id,
snapshot_id=snapshot_id,
)
try:
records_added = await self._write_ais_batch(
db,
data,
persist_raw=persist_raw,
mode=mode,
snapshot_id=snapshot_id,
)
if persist_raw:
await self._assert_versioned_publish_allowed(db, snapshot_id=snapshot_id)
await db.commit()
except Exception as exc:
if (
(not isinstance(exc, _StoragePolicyDowngradedToSingle) and not is_storage_policy_single_violation(exc))
or self._previous_current_snapshot_id is None
):
raise
downgraded_snapshot_id = await self._downgrade_pending_snapshot_to_single(
db,
task_id=task_id,
snapshot_id=snapshot_id,
)
records_added = await self._write_ais_batch(
db,
data,
persist_raw=False,
mode="single",
snapshot_id=downgraded_snapshot_id,
)
await db.commit()
await self._broadcast_vessel_snapshot(data)
await self.update_progress(records_added, force=True)
return records_added
async def _write_ais_batch(
self,
db: AsyncSession,
data: list[dict[str, Any]],
*,
persist_raw: bool,
mode: str,
snapshot_id: int | None,
) -> int:
now = datetime.now(UTC)
records_added = 0
@@ -101,11 +180,15 @@ class VesselAISCollector(BaseCollector):
transport=BARENTSWATCH_TRANSPORT,
observed_at=observed_at,
collected_at=now,
persist_raw=persist_raw,
)
records_added += 1
if (index + 1) % 1000 == 0:
await self.update_progress(index + 1, commit=True)
await self.update_progress(index + 1, commit=False)
if not persist_raw:
await prune_expired_vessel_track_points(db, now=now)
latest_observed_at = max(
(item.get("received_at") for item in data if item.get("received_at")),
@@ -125,6 +208,7 @@ class VesselAISCollector(BaseCollector):
snapshot = await db.get(DataSnapshot, snapshot_id)
if snapshot:
await self._promote_snapshot_to_current(db, snapshot)
snapshot.record_count = records_added
snapshot.status = SnapshotStatus.SUCCESS.value
snapshot.completed_at = now
@@ -133,11 +217,9 @@ class VesselAISCollector(BaseCollector):
"updated": 0,
"unchanged": 0,
"deleted": 0,
"storage": "ais_raw_observations",
"storage": "ais_raw_observations" if persist_raw else "vessel_current_state_and_24h_track",
"storage_mode": mode,
}
await db.commit()
await self._broadcast_vessel_snapshot(data)
await self.update_progress(records_added, force=True)
return records_added
async def _broadcast_vessel_snapshot(self, data: list[dict[str, Any]]) -> None:
@@ -219,6 +301,7 @@ class VesselAISCollector(BaseCollector):
}
def _get_sample_data(self) -> list[dict[str, Any]]:
self._mark_sample_fallback("barentswatch_vessels_sample_fallback")
return [
{
"mmsi": 257123000,
@@ -276,6 +276,66 @@ def _organization_label(organization: dict[str, Any], fallback: str) -> str:
return fallback
_COMMERCIAL_HYPERSCALER_TOKENS = frozenset(
{
"amazon",
"aws",
"microsoft",
"azure",
"google",
"alphabet",
"meta",
"facebook",
"openai",
"xai",
"oracle",
"alibaba",
"tencent",
"bytedance",
"nvidia",
"apple",
"coreweave",
"lambda",
}
)
_ROR_SIMILARITY_STOPWORDS = frozenset({"the", "of", "for", "and", "inc", "ltd", "corp", "llc", "co"})
def _ror_is_plausible_facility_match(
ror_query: str,
organization: dict[str, Any],
display_name: str,
) -> bool:
query_norm = normalize_text(ror_query)
if not query_norm:
return False
query_tokens = {
tok
for tok in query_norm.split()
if len(tok) >= 3 and tok not in _ROR_SIMILARITY_STOPWORDS
}
org_types = {str(t).strip().lower() for t in (organization.get("types") or []) if t}
is_commercial = "company" in org_types or any(
tok in query_tokens for tok in _COMMERCIAL_HYPERSCALER_TOKENS
)
if is_commercial:
return False
candidate_labels = [display_name]
for entry in organization.get("names") or []:
if isinstance(entry, dict) and entry.get("value"):
candidate_labels.append(str(entry["value"]))
combined_norm = normalize_text(" ".join(candidate_labels))
if not combined_norm:
return False
if query_norm in combined_norm or combined_norm in query_norm:
return True
if not query_tokens:
return False
label_tokens = set(combined_norm.split())
return bool(query_tokens & label_tokens)
class ROROrganizationResolver:
"""Resolve source-provided organization/site text through the open ROR API."""
@@ -308,6 +368,9 @@ class ROROrganizationResolver:
continue
if not isinstance(organization, dict):
continue
display_name = _organization_label(organization, ror_query)
if not _ror_is_plausible_facility_match(ror_query, organization, display_name):
continue
locations = organization.get("locations")
if not isinstance(locations, list) or not locations:
continue
@@ -328,7 +391,6 @@ class ROROrganizationResolver:
city = coerce_str(details.get("name")) or None
region = coerce_str(details.get("country_subdivision_name")) or None
display_name = _organization_label(organization, ror_query)
ror_id = coerce_str(organization.get("id"))
geonames_id = location.get("geonames_id")
source_note = (
@@ -551,6 +613,9 @@ def _record_context(record: Any, metadata: dict[str, Any]) -> dict[str, Any]:
"organization": coerce_str(metadata.get("organization")),
"source_location": metadata.get("location"),
"source_raw_country": metadata.get("raw_country"),
"sources": metadata.get("sources") if isinstance(metadata.get("sources"), list) else [],
"source_url": coerce_str(metadata.get("source_url") or metadata.get("detail_url")),
"builds_upon": coerce_str(metadata.get("builds_upon")),
}
@@ -580,6 +645,9 @@ def _context_to_query(
"organization": context.get("organization") or "",
"source_location": context.get("source_location"),
"source_raw_country": context.get("source_raw_country"),
"sources": list(context.get("sources") or []),
"source_url": context.get("source_url") or "",
"builds_upon": context.get("builds_upon") or "",
},
)
@@ -656,6 +724,61 @@ def _compute_center_candidate_sort_key(candidate: LocationCandidate) -> tuple[in
return (source_rank, precision_rank, -float(candidate.confidence or 0))
class BuildsUponComputeCenterResolver:
"""Inherit coordinates from a previously resolved parent cluster via `builds_upon`."""
name = "inherited"
def resolve(self, query: LocationQuery) -> ResolverOutput:
extra = query.extra or {}
parent_ref = coerce_str(extra.get("builds_upon"))
if not parent_ref:
return ResolverOutput()
parent_norm = normalize_text(parent_ref)
candidates: list[LocationCandidate] = []
seen_coords: set[tuple[str, str]] = set()
for entry in COMPUTE_CENTER_LOCATION_CACHE.values():
if not isinstance(entry, dict):
continue
prec = coerce_str(entry.get("precision"))
if prec not in RENDERABLE_PRECISIONS:
continue
lat = parse_float(entry.get("latitude"))
lon = parse_float(entry.get("longitude"))
if lat in (None, 0.0) or lon in (None, 0.0):
continue
entry_id = normalize_text(entry.get("source_id"))
entry_name = normalize_text(entry.get("name"))
if parent_norm not in {entry_id, entry_name}:
continue
coord_key = (f"{lat:.4f}", f"{lon:.4f}")
if coord_key in seen_coords:
continue
seen_coords.add(coord_key)
candidates.append(
LocationCandidate(
latitude=lat,
longitude=lon,
display_name=coerce_str(entry.get("name")) or parent_ref,
precision="site" if prec == "precise" else prec,
confidence=0.82 if not entry.get("needs_confirmation") else 0.72,
query=f"builds_upon:{parent_ref}",
source=self.name,
source_note=f"Inherited from parent cluster '{coerce_str(entry.get('name')) or parent_ref}' via builds_upon",
matched_fields=("builds_upon",),
needs_confirmation=True,
city=coerce_str(entry.get("city")) or None,
country=coerce_str(entry.get("country")) or query.country,
matched_location_name=coerce_str(entry.get("name")) or parent_ref,
)
)
return ResolverOutput(
candidates=tuple(candidates),
attempted_queries=(f"builds_upon:{parent_ref}",),
)
COMPUTE_CENTER_PIPELINE = LocationPipeline(
[
ComputeCenterSourceCoordinatesResolver(),
@@ -673,6 +796,7 @@ COMPUTE_CENTER_COLLECTION_PIPELINE = LocationPipeline(
[
ComputeCenterSourceCoordinatesResolver(),
VerifiedComputeSiteResolver(),
BuildsUponComputeCenterResolver(),
ROROrganizationResolver(),
NominatimResolver(
query_plan_builder=_compute_center_query_plan,
@@ -871,12 +995,12 @@ def collect_location_candidates(
country: str | None = None,
organization: str | None = None,
record_id: int | None = None,
sources: list[str] | None = None,
source_url: str | None = None,
builds_upon: str | None = None,
source_raw_country: str | None = None,
) -> tuple[list[LocationCandidate], list[str]]:
"""Run the full resolution chain and return ranked candidates with attempted queries.
The unused ``source`` / ``source_id`` / ``record_id`` arguments are kept
for backward compatibility with the API handler that calls this function.
"""
"""Run the full resolution chain and return ranked candidates with attempted queries."""
query = build_compute_center_location_query(
name=name,
source=source,
@@ -886,6 +1010,10 @@ def collect_location_candidates(
city=city,
country=country,
organization=organization,
sources=sources,
source_url=source_url,
builds_upon=builds_upon,
source_raw_country=source_raw_country,
)
return COMPUTE_CENTER_COLLECTION_PIPELINE.collect_candidates(query)
@@ -900,6 +1028,10 @@ def build_compute_center_location_query(
city: str | None = None,
country: str | None = None,
organization: str | None = None,
sources: list[str] | None = None,
source_url: str | None = None,
builds_upon: str | None = None,
source_raw_country: str | None = None,
) -> LocationQuery:
name_value = coerce_str(name)
context: dict[str, Any] = {
@@ -912,6 +1044,10 @@ def build_compute_center_location_query(
"site": coerce_str(site or organization),
"operator": coerce_str(operator or organization),
"organization": coerce_str(organization),
"sources": [str(item).strip() for item in (sources or []) if item],
"source_url": coerce_str(source_url),
"builds_upon": coerce_str(builds_upon),
"source_raw_country": coerce_str(source_raw_country),
}
return _context_to_query(context)
+203 -46
View File
@@ -299,47 +299,80 @@ async def persist_mapped_records(
mapping_version: int,
delivery_mode: str | None = None,
transport: str | None = None,
snapshot_mode: str | None = None,
) -> int:
"""Persist validated mapped records to the destination for a target schema."""
from app.services.storage_policy import (
acquire_storage_policy_publish_lock,
compute_record_content_hash,
resolve_collector_storage_policy,
)
can_query_db = callable(getattr(db, "execute", None))
if can_query_db:
resolved_mode, policy = await resolve_collector_storage_policy(db, datasource_name)
if policy.get("global_single_lock"):
effective_mode = "single"
elif snapshot_mode is not None:
effective_mode = snapshot_mode
else:
effective_mode = resolved_mode
else:
effective_mode = snapshot_mode or "single"
if target_schema == "vessel_ais":
from app.core.time import to_iso8601_utc
from app.core.websocket.broadcaster import broadcaster
from app.services.vessel_ais_aggregation import (
prune_expired_vessel_track_points,
record_vessel_ais_observation,
update_ais_source_health,
)
now = datetime.now(UTC)
latest_observed_at = now
written_count = 0
for record in records:
observed_at = _parse_datetime(record.get("received_at")) or now
observation = await record_vessel_ais_observation(
for attempt in range(2):
now = datetime.now(UTC)
latest_observed_at = now
written_count = 0
persist_raw = effective_mode == "history"
for record in records:
observed_at = _parse_datetime(record.get("received_at")) or now
observation = await record_vessel_ais_observation(
db,
source=datasource_name,
normalized_payload=record,
raw_payload=record,
delivery_mode=delivery_mode or "polling",
transport=transport or "http",
message_type="PositionReport",
observed_at=observed_at,
collected_at=now,
persist_raw=persist_raw,
)
if observation is not None:
written_count += 1
if observed_at > latest_observed_at:
latest_observed_at = observed_at
if not persist_raw:
await prune_expired_vessel_track_points(db, now=now)
await update_ais_source_health(
db,
source=datasource_name,
normalized_payload=record,
raw_payload=record,
delivery_mode=delivery_mode or "polling",
transport=transport or "http",
message_type="PositionReport",
observed_at=observed_at,
collected_at=now,
connection_state="connected",
observed_count=len(records),
last_seen_at=latest_observed_at,
last_success_at=now if records else None,
lag_seconds=max((now - latest_observed_at).total_seconds(), 0),
)
if observation is not None:
written_count += 1
if observed_at > latest_observed_at:
latest_observed_at = observed_at
await update_ais_source_health(
db,
source=datasource_name,
connection_state="connected",
observed_count=len(records),
last_seen_at=latest_observed_at,
last_success_at=now if records else None,
lag_seconds=max((now - latest_observed_at).total_seconds(), 0),
)
await db.commit()
if persist_raw and can_query_db and attempt == 0:
latest_mode, _ = await acquire_storage_policy_publish_lock(db, datasource_name)
if latest_mode == "single":
await db.rollback()
effective_mode = "single"
continue
await db.commit()
break
if records:
await broadcaster.broadcast_custom(
"vessels",
@@ -369,9 +402,11 @@ async def persist_mapped_records(
)
return written_count
from sqlalchemy import select
from app.models.collected_data import CollectedData
collected_at = datetime.now(UTC)
prepared_by_key: dict[str, dict[str, Any]] = {}
for index, record in enumerate(records):
if target_schema == "geo_points":
source_id = record.get("source_id") or f"{datasource_config_id}:{index}"
@@ -383,6 +418,7 @@ async def persist_mapped_records(
"mapping_version": mapping_version,
"target_schema": target_schema,
**(record.get("metadata") or {}),
"datasource_config_id": datasource_config_id,
}
reference_date = _parse_datetime(record.get("observed_at"))
else:
@@ -392,26 +428,147 @@ async def persist_mapped_records(
"data": record.get("data") or {},
"mapping_version": mapping_version,
"target_schema": target_schema,
"datasource_config_id": datasource_config_id,
}
reference_date = _parse_datetime(record.get("observed_at"))
db.add(
CollectedData(
source=datasource_name,
source_id=str(source_id),
entity_key=f"{datasource_name}:{source_id}",
data_type=target_schema,
name=name,
title=name,
extra_data=metadata,
collected_at=collected_at,
reference_date=reference_date,
is_valid=1,
is_current=True,
change_type="created",
change_summary={},
)
source_id_str = str(source_id)
# Scope entity identity by datasource_config_id so same-named configs stay isolated.
entity_key = f"datasource_config:{datasource_config_id}:{source_id_str}"
content_hash = compute_record_content_hash(
{
"name": name,
"title": name,
"metadata": metadata,
"reference_date": reference_date.isoformat() if reference_date else None,
}
)
prepared_by_key[entity_key] = {
"source_id": source_id_str,
"entity_key": entity_key,
"name": name,
"metadata": metadata,
"reference_date": reference_date,
"content_hash": content_hash,
}
await db.commit()
return len(records)
if not prepared_by_key:
return 0
if not can_query_db:
for item in prepared_by_key.values():
db.add(
CollectedData(
source=datasource_name,
source_id=item["source_id"],
entity_key=item["entity_key"],
data_type=target_schema,
name=item["name"],
title=item["name"],
extra_data=item["metadata"],
collected_at=collected_at,
reference_date=item["reference_date"],
is_valid=1,
is_current=True,
change_type="created",
change_summary={},
content_hash=item["content_hash"],
)
)
await db.commit()
return len(prepared_by_key)
for attempt in range(2):
existing_result = await db.execute(
select(CollectedData)
.where(
CollectedData.source == datasource_name,
CollectedData.entity_key.in_(list(prepared_by_key.keys())),
CollectedData.is_current.is_(True),
CollectedData.deleted_at.is_(None),
)
.order_by(CollectedData.id.desc())
)
existing_by_key: dict[str, CollectedData] = {}
for row in existing_result.scalars().all():
if row.entity_key not in existing_by_key:
existing_by_key[row.entity_key] = row
else:
row.is_current = False
if effective_mode == "history":
pending_inserts: list[tuple[str, dict[str, Any], CollectedData | None]] = []
for entity_key, item in prepared_by_key.items():
prev = existing_by_key.get(entity_key)
if prev is not None and prev.content_hash == item["content_hash"]:
continue
if prev is not None:
prev.is_current = False
pending_inserts.append((entity_key, item, prev))
if pending_inserts and hasattr(db, "flush"):
await db.flush()
for entity_key, item, prev in pending_inserts:
db.add(
CollectedData(
source=datasource_name,
source_id=item["source_id"],
entity_key=entity_key,
data_type=target_schema,
name=item["name"],
title=item["name"],
extra_data=item["metadata"],
collected_at=collected_at,
reference_date=item["reference_date"],
is_valid=1,
is_current=True,
previous_record_id=prev.id if prev is not None else None,
change_type="created" if prev is None else "updated",
change_summary={},
content_hash=item["content_hash"],
)
)
if attempt == 0:
latest_mode, _ = await acquire_storage_policy_publish_lock(db, datasource_name)
if latest_mode == "single":
await db.rollback()
effective_mode = "single"
continue
else:
for entity_key, item in prepared_by_key.items():
existing = existing_by_key.get(entity_key)
if existing is None:
db.add(
CollectedData(
source=datasource_name,
source_id=item["source_id"],
entity_key=entity_key,
data_type=target_schema,
name=item["name"],
title=item["name"],
extra_data=item["metadata"],
collected_at=collected_at,
reference_date=item["reference_date"],
is_valid=1,
is_current=True,
previous_record_id=None,
change_type="created",
change_summary={},
content_hash=item["content_hash"],
)
)
elif existing.content_hash != item["content_hash"]:
existing.source_id = item["source_id"]
existing.data_type = target_schema
existing.name = item["name"]
existing.title = item["name"]
existing.extra_data = item["metadata"]
existing.collected_at = collected_at
existing.reference_date = item["reference_date"]
existing.is_current = True
existing.previous_record_id = None
existing.change_type = "updated"
existing.content_hash = item["content_hash"]
await db.commit()
break
return len(prepared_by_key)
+1
View File
@@ -59,6 +59,7 @@ DOCS_METADATA: tuple[DocsMetadata, ...] = (
DocsMetadata("location-pipeline-development.md", "location-pipeline-development", "docs_developer", "Backend", 35, "通用位置估算管线开发说明", "Shared Location Resolution Pipeline Development Guide"),
DocsMetadata("earth-news-live-streams-collector-format.md", "earth-news-live-streams-collector-format", "docs_developer", "Backend", 36, "新闻直播采集格式", "News Live Streams Collector Format"),
DocsMetadata("docs-gatekeeper-development.md", "docs-gatekeeper-development", "docs_developer", "Backend", 37, "Docs Gatekeeper 开发说明", "Docs Gatekeeper Development Guide"),
DocsMetadata("api-integration-guide.md", "api-integration-guide", "docs_developer", "Backend", 38, "API 接入与鉴权指南", "API Integration and Authentication Guide"),
DocsMetadata("agents-aiprovider.md", "agents-aiprovider", "docs_developer", "Agents", 40, "AI Provider 指南", "AI Provider Guide"),
DocsMetadata("ops-runbook.md", "ops-runbook", "docs_admin", "Ops", 49, "智能星球运维手册", "Intelligent Planet Ops Runbook"),
DocsMetadata("ops-docker-compose-buildx-upgrade.md", "ops-docker-compose-buildx-upgrade", "docs_admin", "Ops", 50, "Docker + Compose + Buildx 升级", "Docker + Compose + Buildx Upgrade"),
+11 -2
View File
@@ -172,18 +172,27 @@ async def clear_derived_datasource_data(db: AsyncSession, source: str) -> dict[s
from app.models.bgp_anomaly import BGPAnomaly
from app.models.bgp_incident import BGPIncident
from app.models.bgp_observation import BGPObservation
from app.models.vessel import AISConflictRecord, AISRawObservation, AISSourceHealth
from app.models.vessel import (
AISConflictRecord,
AISRawObservation,
AISSourceHealth,
VesselCurrentState,
)
model_by_key: dict[str, Any] = {
"bgp_observations": BGPObservation,
"bgp_anomalies": BGPAnomaly,
"bgp_incidents": BGPIncident,
"ais_raw_observations": AISRawObservation,
"vessel_current_state": VesselCurrentState,
"ais_conflict_records": AISConflictRecord,
"ais_source_health": AISSourceHealth,
}
deleted_counts: dict[str, int] = {}
for key in adapter.derived_models:
keys_to_clear = list(adapter.derived_models)
if "ais_raw_observations" in keys_to_clear and "vessel_current_state" not in keys_to_clear:
keys_to_clear.append("vessel_current_state")
for key in keys_to_clear:
model = model_by_key.get(key)
if model is None:
continue
+182 -13
View File
@@ -1,16 +1,18 @@
from __future__ import annotations
import asyncio
from collections import OrderedDict
from collections.abc import Awaitable, Callable
from contextlib import suppress
from dataclasses import dataclass, replace
import gzip
import hashlib
import json
import time
from typing import Any
from uuid import uuid4
from fastapi import HTTPException, Response
from fastapi import HTTPException, Request, Response
from app.core.cache import _RedisClient
from app.core.config import settings
@@ -27,6 +29,8 @@ DEFAULT_MAX_FEATURES = 5000
DEFAULT_MAX_BYTES = 5 * 1024 * 1024
DEFAULT_BBOX_PRECISION_DEGREES = 0.1
DEV_CACHE_KEY_HEADER = {"development", "dev", "test", "testing", "local"}
ENCODED_ARTIFACT_CACHE_MAX_ENTRIES = 8
GZIP_COMPRESS_LEVEL = 5
@dataclass(frozen=True)
@@ -49,6 +53,25 @@ class EarthLayerCacheResult:
bytes: int
@dataclass(frozen=True)
class _EncodedLayerArtifact:
raw_bytes: bytes
gzip_bytes: bytes
etag: str
features: int
byte_length: int
@dataclass(frozen=True)
class EarthLayerEncodedResult:
artifact: _EncodedLayerArtifact
state: str
key: str
_ENCODED_ARTIFACT_CACHE: OrderedDict[tuple[str, str], _EncodedLayerArtifact] = OrderedDict()
class EarthLayerCache:
def __init__(self) -> None:
self._client = None
@@ -81,6 +104,16 @@ class EarthLayerCache:
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:32]
return f"{EARTH_LAYER_LOCK_PREFIX}:{digest}"
def get_raw(self, key: str) -> bytes | None:
raw = self.client.get(key)
if not raw:
return None
if isinstance(raw, bytes):
return raw
if isinstance(raw, str):
return raw.encode("utf-8")
return None
def get_json(self, key: str) -> dict[str, Any] | None:
raw = self.client.get(key)
if not raw:
@@ -191,15 +224,143 @@ def format_bbox_key(bbox: tuple[float, float, float, float]) -> str:
return ",".join(f"{value:.1f}" for value in bbox)
def apply_cache_headers(response: Response | None, result: EarthLayerCacheResult) -> None:
if response is None:
return
response.headers["X-Planet-Cache"] = result.state
response.headers["X-Planet-Cache-Features"] = str(result.features)
response.headers["X-Planet-Cache-Bytes"] = str(result.bytes)
def _cache_headers(
result: EarthLayerCacheResult | EarthLayerEncodedResult,
) -> dict[str, str]:
if isinstance(result, EarthLayerEncodedResult):
features, byte_length = result.artifact.features, result.artifact.byte_length
else:
features, byte_length = result.features, result.bytes
headers = {
"X-Planet-Cache": result.state,
"X-Planet-Cache-Features": str(features),
"X-Planet-Cache-Bytes": str(byte_length),
}
env_name = str(getattr(settings, "ENVIRONMENT", "") or "development").lower()
if env_name in DEV_CACHE_KEY_HEADER:
response.headers["X-Planet-Cache-Key"] = result.key
headers["X-Planet-Cache-Key"] = result.key
return headers
def apply_cache_headers(
response: Response | None,
result: EarthLayerCacheResult | EarthLayerEncodedResult,
) -> None:
if response is not None:
response.headers.update(_cache_headers(result))
def _etag_matches(if_none_match: str | None, etag: str) -> bool:
if not if_none_match:
return False
normalized_target = etag.strip()
if normalized_target.startswith("W/"):
normalized_target = normalized_target[2:].strip()
for candidate in if_none_match.split(","):
token = candidate.strip()
if token == "*":
return True
if token.startswith("W/"):
token = token[2:].strip()
if token == normalized_target:
return True
return False
def _encode_layer_bytes(
key: str,
raw_bytes: bytes,
*,
features: int | None = None,
) -> _EncodedLayerArtifact:
etag = f'"{hashlib.sha256(raw_bytes).hexdigest()[:24]}"'
cache_key = (key, etag)
cached = _ENCODED_ARTIFACT_CACHE.get(cache_key)
if cached is not None:
_ENCODED_ARTIFACT_CACHE.move_to_end(cache_key)
return cached
resolved_features = features
if resolved_features is None:
parsed = json.loads(raw_bytes)
if not isinstance(parsed, dict):
raise ValueError("Earth layer cache payload must be a JSON object")
resolved_features = _feature_count(parsed)
gzip_bytes = gzip.compress(raw_bytes, compresslevel=GZIP_COMPRESS_LEVEL)
artifact = _EncodedLayerArtifact(
raw_bytes=raw_bytes,
gzip_bytes=gzip_bytes,
etag=etag,
features=resolved_features,
byte_length=len(raw_bytes),
)
_ENCODED_ARTIFACT_CACHE[cache_key] = artifact
while len(_ENCODED_ARTIFACT_CACHE) > ENCODED_ARTIFACT_CACHE_MAX_ENTRIES:
_ENCODED_ARTIFACT_CACHE.popitem(last=False)
return artifact
async def resolve_layer_encoded_payload(
*,
key: str,
policy: EarthLayerCachePolicy,
builder: Callable[[], Awaitable[dict[str, Any]]],
) -> EarthLayerEncodedResult:
flight_key = (asyncio.get_running_loop(), key)
if flight_key not in earth_layer_cache._inflight:
cached_raw = None
with suppress(Exception):
cached_raw = earth_layer_cache.get_raw(key)
if cached_raw is not None:
try:
artifact = _encode_layer_bytes(key, cached_raw)
return EarthLayerEncodedResult(artifact=artifact, state="hit", key=key)
except Exception as exc:
logger.warning_event(
"Invalid raw earth layer cache payload; falling back to standard resolver",
event="earth_layer_cache.raw_decode_failed",
context={"key": key, "error": str(exc)},
)
result = await resolve_layer_payload(key=key, policy=policy, builder=builder)
raw_bytes = json.dumps(result.payload, ensure_ascii=False, default=str).encode("utf-8")
artifact = _encode_layer_bytes(key, raw_bytes, features=result.features)
return EarthLayerEncodedResult(artifact=artifact, state=result.state, key=result.key)
async def get_or_build_layer_response(
*,
key: str,
policy: EarthLayerCachePolicy,
builder: Callable[[], Awaitable[dict[str, Any]]],
request: Request,
response: Response | None = None,
) -> Response:
result = await resolve_layer_encoded_payload(key=key, policy=policy, builder=builder)
headers = _cache_headers(result)
if response is not None:
response.headers.update(headers)
headers.update({
"ETag": result.artifact.etag,
"Cache-Control": "private, no-cache",
"Vary": "Accept-Encoding",
})
if _etag_matches(request.headers.get("if-none-match"), result.artifact.etag):
return Response(status_code=304, headers=headers)
accept_encoding = (request.headers.get("accept-encoding") or "").lower()
if "gzip" in accept_encoding:
return Response(
content=result.artifact.gzip_bytes,
media_type="application/json",
headers={**headers, "Content-Encoding": "gzip"},
)
return Response(
content=result.artifact.raw_bytes,
media_type="application/json",
headers=headers,
)
async def get_or_build_layer_payload(
@@ -262,9 +423,11 @@ async def _resolve_layer_payload(
try:
async with asyncio.timeout(policy.build_wait_seconds):
while True:
cached = earth_layer_cache.get_json(key)
if cached is not None:
return _result(cached, state="hit", key=key)
cached_raw = earth_layer_cache.get_raw(key)
if cached_raw is not None:
cached = json.loads(cached_raw)
if isinstance(cached, dict):
return _result(cached, state="hit", key=key, byte_length=len(cached_raw))
token = earth_layer_cache.acquire_lock(key, policy.lock_ttl_seconds)
if token is not None:
break
@@ -454,13 +617,19 @@ def _with_budget_diagnostics(
return {**payload, "diagnostics": diagnostics}
def _result(payload: dict[str, Any], *, state: str, key: str) -> EarthLayerCacheResult:
def _result(
payload: dict[str, Any],
*,
state: str,
key: str,
byte_length: int | None = None,
) -> EarthLayerCacheResult:
return EarthLayerCacheResult(
payload=payload,
state=state,
key=key,
features=_feature_count(payload),
bytes=_payload_size(payload),
bytes=_payload_size(payload) if byte_length is None else byte_length,
)
+310 -21
View File
@@ -5,7 +5,9 @@ from __future__ import annotations
import asyncio
from dataclasses import dataclass
from datetime import datetime
import time
from urllib.parse import urlsplit, urlunsplit
from weakref import WeakKeyDictionary
import httpx
@@ -14,32 +16,117 @@ CATALOG_MAX_PAGES = 100
CATALOG_PAGE_SIZE = 100
CATALOG_REQUEST_ATTEMPTS = 2
CATALOG_RETRY_DELAY_SECONDS = 0.2
MODELS_DEV_CATALOG_URL = "https://models.dev/api.json"
OPENROUTER_CATALOG_URL = "https://openrouter.ai/api/v1/models"
AGGREGATOR_CACHE_TTL_SECONDS = 300
SUPPORTED_PROVIDER_APIS = {
"openai-completions",
"openai-responses",
"anthropic-messages",
"ollama-generate",
}
OFFICIAL_PUBLIC_CATALOG_HOSTS: dict[str, frozenset[str]] = {
"openrouter": frozenset({"openrouter.ai"}),
"opencode-go": frozenset({"opencode.ai"}),
}
OFFICIAL_PROVIDER_HOSTS: dict[str, frozenset[str]] = {
"minimax": frozenset({"api.minimaxi.com", "api.minimax.cn", "api.minimax.io"}),
"openai": frozenset({"api.openai.com"}),
"anthropic": frozenset({"api.anthropic.com"}),
"deepseek": frozenset({"api.deepseek.com"}),
"alibaba": frozenset({"dashscope.aliyuncs.com", "dashscope-intl.aliyuncs.com"}),
"moonshotai": frozenset({"api.moonshot.ai", "api.moonshot.cn"}),
"glm": frozenset({"open.bigmodel.cn", "api.z.ai"}),
"meta": frozenset({"api.meta.ai", "api.llama.com"}),
"gemini": frozenset({"generativelanguage.googleapis.com"}),
"grok": frozenset({"api.x.ai"}),
**OFFICIAL_PUBLIC_CATALOG_HOSTS,
}
AGGREGATOR_OPENROUTER_PREFIXES: dict[str, str] = {
"minimax": "minimax/",
"openai": "openai/",
"anthropic": "anthropic/",
"deepseek": "deepseek/",
"alibaba": "qwen/",
"moonshotai": "moonshotai/",
"glm": "z-ai/",
"meta": "meta-llama/",
"gemini": "google/",
"grok": "x-ai/",
}
_AGGREGATOR_CACHE: dict[str, tuple[float, object]] = {}
_AGGREGATOR_LOOP_LOCKS: WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Lock] = WeakKeyDictionary()
class LLMProviderCatalogError(RuntimeError):
"""A safe, user-facing catalog failure with no upstream response or credentials."""
class LLMProviderCatalogConfigError(LLMProviderCatalogError):
"""Invalid local catalog configuration or missing required credentials."""
@dataclass(frozen=True)
class ModelCatalog:
url: str
models: list[str]
def is_official_public_catalog(provider: str, base_url: str) -> bool:
provider_key = provider.strip().lower()
host = (urlsplit(base_url.strip()).hostname or "").lower()
return host in OFFICIAL_PUBLIC_CATALOG_HOSTS.get(provider_key, frozenset())
def is_official_provider_host(provider: str, base_url: str) -> bool:
provider_key = provider.strip().lower()
host = (urlsplit(base_url.strip()).hostname or "").lower()
if not host:
return False
if host in OFFICIAL_PROVIDER_HOSTS.get(provider_key, frozenset()):
return True
return provider_key == "alibaba" and (host == "aliyuncs.com" or host.endswith(".aliyuncs.com"))
def catalog_requires_api_key(provider: str, base_url: str, provider_api: str) -> bool:
provider_key = provider.strip().lower()
if provider_key == "ollama" or provider_api == "ollama-generate":
return False
return not is_official_public_catalog(provider_key, base_url)
def catalog_supports_aggregator_fallback(
provider: str, base_url: str, provider_api: str
) -> bool:
provider_key = provider.strip().lower()
return (
provider_key in AGGREGATOR_OPENROUTER_PREFIXES
and provider_api in SUPPORTED_PROVIDER_APIS
and provider_api != "ollama-generate"
and is_official_provider_host(provider_key, base_url)
)
def can_refresh_catalog_without_api_key(
provider: str, base_url: str, provider_api: str
) -> bool:
return not catalog_requires_api_key(
provider, base_url, provider_api
) or catalog_supports_aggregator_fallback(provider, base_url, provider_api)
def clear_aggregator_catalog_cache() -> None:
_AGGREGATOR_CACHE.clear()
def model_catalog_url(provider: str, base_url: str, provider_api: str) -> str:
parts = urlsplit(base_url.strip())
if parts.scheme not in {"http", "https"} or not parts.hostname:
raise LLMProviderCatalogError("请填写有效的 HTTP(S) 模型基础地址。")
raise LLMProviderCatalogConfigError("请填写有效的 HTTP(S) 模型基础地址。")
if parts.username or parts.password or parts.query or parts.fragment:
raise LLMProviderCatalogError("模型基础地址不能包含账号、密码、查询参数或片段。")
raise LLMProviderCatalogConfigError("模型基础地址不能包含账号、密码、查询参数或片段。")
if provider_api not in SUPPORTED_PROVIDER_APIS:
raise LLMProviderCatalogError("当前接口协议不支持模型目录查询。")
raise LLMProviderCatalogConfigError("当前接口协议不支持模型目录查询。")
path = parts.path.rstrip("/")
if provider_api == "ollama-generate":
path = path.removesuffix("/api").removesuffix("/v1") + "/api/tags"
@@ -85,11 +172,14 @@ def _model_rows(payload: object) -> tuple[list[dict[str, object]], dict[str, obj
return rows, envelope
def _model_id(row: dict[str, object]) -> str:
def _model_id(row: dict[str, object], provider: str = "") -> str:
value = row.get("id") or row.get("model") or row.get("name")
if not isinstance(value, str) or not value.strip():
raise LLMProviderCatalogError("供应商返回了缺少 ID 的模型条目。")
return value.strip()
normalized = value.strip()
if provider.strip().lower() == "gemini" and normalized.startswith("models/"):
normalized = normalized.removeprefix("models/")
return normalized
def _model_date(row: dict[str, object]) -> float:
@@ -132,21 +222,23 @@ async def fetch_model_catalog(
api_key: str = "",
anthropic_version: str = "2023-06-01",
timeout_seconds: int = CATALOG_TIMEOUT_SECONDS,
*,
include_auth: bool = True,
) -> ModelCatalog:
url = model_catalog_url(provider, base_url, provider_api)
public_catalog = provider in {"opencode-go", "openrouter"}
if not api_key and provider_api != "ollama-generate" and not public_catalog:
raise LLMProviderCatalogError("请先配置当前供应商的 API Key,再刷新模型列表。")
if not api_key and catalog_requires_api_key(provider, base_url, provider_api):
raise LLMProviderCatalogConfigError("请先配置当前供应商的 API Key,再刷新模型列表。")
headers = {"User-Agent": "Planet/1.0", "Accept": "application/json"}
if provider_api == "anthropic-messages" and provider not in {
"opencode-go",
"openrouter",
"alibaba",
"moonshotai",
}:
headers.update({"x-api-key": api_key, "anthropic-version": anthropic_version})
elif api_key:
headers["Authorization"] = f"Bearer {api_key}"
if include_auth and api_key:
if provider_api == "anthropic-messages" and provider not in {
"opencode-go",
"openrouter",
"alibaba",
"moonshotai",
}:
headers.update({"x-api-key": api_key, "anthropic-version": anthropic_version})
else:
headers["Authorization"] = f"Bearer {api_key}"
native_dashscope = provider == "alibaba" and urlsplit(url).hostname.endswith(".aliyuncs.com")
params: dict[str, str | int] = {}
if native_dashscope:
@@ -160,7 +252,7 @@ async def fetch_model_catalog(
rows, envelope = _model_rows(payload)
previous_count = len(rows_by_id)
for row in rows:
rows_by_id[_model_id(row)] = row
rows_by_id[_model_id(row, provider)] = row
has_more = envelope.get("has_more") is True
if native_dashscope:
total = envelope.get("total")
@@ -179,8 +271,205 @@ async def fetch_model_catalog(
)
# An empty Ollama catalog is valid: no models have been installed yet.
if not models and provider_api != "ollama-generate":
raise LLMProviderCatalogError("供应商返回了空模型目录,已保留上次模型列表。")
raise LLMProviderCatalogError("供应商返回了空模型目录。")
return ModelCatalog(url=url, models=models)
if len(rows_by_id) == previous_count:
raise LLMProviderCatalogError("供应商模型目录分页没有进展,已保留上次模型列表。")
raise LLMProviderCatalogError("供应商模型目录分页超过限制,已保留上次模型列表。")
raise LLMProviderCatalogError("供应商模型目录分页没有进展。")
raise LLMProviderCatalogError("供应商模型目录分页超过限制。")
def _aggregator_lock() -> asyncio.Lock:
loop = asyncio.get_running_loop()
lock = _AGGREGATOR_LOOP_LOCKS.get(loop)
if lock is None:
lock = asyncio.Lock()
_AGGREGATOR_LOOP_LOCKS[loop] = lock
return lock
async def _fetch_aggregator_json(url: str, timeout_seconds: int) -> object:
now = time.monotonic()
cached = _AGGREGATOR_CACHE.get(url)
if cached is not None and cached[0] > now:
return cached[1]
async with _aggregator_lock():
now = time.monotonic()
cached = _AGGREGATOR_CACHE.get(url)
if cached is not None and cached[0] > now:
return cached[1]
timeout = max(1, min(timeout_seconds, CATALOG_TIMEOUT_SECONDS))
headers = {
"User-Agent": "Planet/1.0",
"Accept": "application/json",
"Accept-Encoding": "gzip",
}
async with asyncio.timeout(timeout), httpx.AsyncClient(timeout=timeout) as client:
payload = await _get_catalog_page(client, url, headers, {})
_AGGREGATOR_CACHE[url] = (time.monotonic() + AGGREGATOR_CACHE_TTL_SECONDS, payload)
return payload
def _models_dev_candidate_keys(provider: str, base_url: str) -> tuple[str, ...]:
provider_key = provider.strip().lower()
host = (urlsplit(base_url.strip()).hostname or "").lower()
if provider_key == "minimax":
if host in {"api.minimaxi.com", "api.minimax.cn"}:
return ("minimax-cn", "minimax")
return ("minimax", "minimax-cn")
if provider_key == "alibaba":
if "intl" in host:
return ("alibaba", "alibaba-cn")
return ("alibaba-cn", "alibaba")
if provider_key == "moonshotai":
if host.endswith(".cn"):
return ("moonshotai-cn", "moonshotai")
return ("moonshotai", "moonshotai-cn")
fixed: dict[str, tuple[str, ...]] = {
"glm": ("zhipuai",),
"meta": ("meta",),
"gemini": ("google",),
"grok": ("xai",),
"openai": ("openai",),
"anthropic": ("anthropic",),
"deepseek": ("deepseek",),
}
return fixed.get(provider_key, (provider_key,))
def _is_aggregator_chat_model(model_id: str, output_modalities: object = None) -> bool:
"""Exclude embeddings, image/audio/video generators, and consumer chat aliases."""
lower = model_id.strip().lower()
if not lower:
return False
if isinstance(output_modalities, list) and output_modalities:
mods = {str(item).strip().lower() for item in output_modalities if str(item).strip()}
if "text" not in mods or (mods & {"image", "video", "audio"}):
return False
if "embedding" in lower:
return False
if lower.startswith(
(
"chatgpt-",
"dall-e",
"whisper",
"tts-",
"gpt-image",
"gpt-audio",
"gpt-realtime",
"grok-imagine",
"qwen-mt-",
)
):
return False
if lower == "gpt-chat-latest" or (lower.startswith("gpt-") and lower.endswith("-chat")):
return False
if any(token in lower for token in ("-image", "-tts", "-asr", "-live-", "-realtime", "-video")):
return False
return True
def _is_general_aggregator_model(model_id: str) -> bool:
"""Rank general-purpose flagship chat models ahead of vertical or experimental variants."""
lower = model_id.strip().lower()
if lower.startswith(("gpt-daybreak-", "deep-research-")):
return False
if lower.endswith(("-healthcare", "-legal", "-contributor", "-exp")):
return False
return True
def _extract_models_dev_models(
payload: object, provider: str, base_url: str
) -> ModelCatalog | None:
if not isinstance(payload, dict):
return None
for key in _models_dev_candidate_keys(provider, base_url):
entry = payload.get(key)
if not isinstance(entry, dict):
continue
raw_models = entry.get("models")
if not isinstance(raw_models, dict):
continue
candidates: list[tuple[bool, bool, str, str]] = []
for model_id, meta in raw_models.items():
if not isinstance(model_id, str) or not model_id.strip() or not isinstance(meta, dict):
continue
modalities = meta.get("modalities")
output_mods = modalities.get("output") if isinstance(modalities, dict) else None
if not _is_aggregator_chat_model(model_id, output_mods):
continue
active = str(meta.get("status") or "").strip().lower() != "deprecated"
release_date = str(meta.get("release_date") or "")
candidates.append(
(active, _is_general_aggregator_model(model_id), release_date, model_id.strip())
)
if candidates:
candidates.sort(key=lambda item: (item[0], item[1], item[2], item[3]), reverse=True)
return ModelCatalog(
url=f"{MODELS_DEV_CATALOG_URL}#{key}",
models=[item[3] for item in candidates],
)
return None
def _extract_openrouter_models(payload: object, provider: str) -> ModelCatalog | None:
provider_key = provider.strip().lower()
prefix = AGGREGATOR_OPENROUTER_PREFIXES.get(provider_key, "")
if not prefix:
return None
try:
rows, _ = _model_rows(payload)
except LLMProviderCatalogError:
return None
dated: list[tuple[bool, float, str]] = []
seen: set[str] = set()
for row in rows:
raw_id = row.get("id")
if not isinstance(raw_id, str) or not raw_id.startswith(prefix):
continue
model_id = raw_id[len(prefix) :].strip()
if not model_id or ":" in model_id or model_id in seen:
continue
arch = row.get("architecture")
output_mods = arch.get("output_modalities") if isinstance(arch, dict) else None
if not _is_aggregator_chat_model(model_id, output_mods):
continue
seen.add(model_id)
dated.append((_is_general_aggregator_model(model_id), _model_date(row), model_id))
if not dated:
return None
dated.sort(key=lambda item: (item[0], item[1], item[2]), reverse=True)
return ModelCatalog(
url=f"{OPENROUTER_CATALOG_URL}#{provider_key}",
models=[item[2] for item in dated],
)
async def fetch_aggregator_model_catalog(
provider: str,
base_url: str,
provider_api: str,
timeout_seconds: int = CATALOG_TIMEOUT_SECONDS,
) -> ModelCatalog:
"""Fetch public model catalog for a keyless official-host provider via aggregators."""
model_catalog_url(provider, base_url, provider_api)
if not catalog_supports_aggregator_fallback(provider, base_url, provider_api):
raise LLMProviderCatalogConfigError("请先配置当前供应商的 API Key,再刷新模型列表。")
try:
models_dev_payload = await _fetch_aggregator_json(MODELS_DEV_CATALOG_URL, timeout_seconds)
catalog = _extract_models_dev_models(models_dev_payload, provider, base_url)
if catalog is not None and catalog.models:
return catalog
except (httpx.HTTPError, TimeoutError, LLMProviderCatalogError, ValueError):
pass
try:
openrouter_payload = await _fetch_aggregator_json(OPENROUTER_CATALOG_URL, timeout_seconds)
catalog = _extract_openrouter_models(openrouter_payload, provider)
if catalog is not None and catalog.models:
return catalog
except (httpx.HTTPError, TimeoutError, LLMProviderCatalogError, ValueError):
pass
raise LLMProviderCatalogError("公共聚合模型目录暂不可用,请稍后重试或配置 API Key。")
+178 -35
View File
@@ -2,10 +2,21 @@
from __future__ import annotations
import logging
from typing import Any
from urllib.parse import urlsplit
from app.services.llm_model_catalog import fetch_model_catalog
import httpx
from app.services.llm_model_catalog import (
catalog_requires_api_key,
catalog_supports_aggregator_fallback,
fetch_aggregator_model_catalog,
fetch_model_catalog,
is_official_public_catalog,
)
logger = logging.getLogger(__name__)
OPENCODE_GO_MODEL_PROVIDER_APIS = {
"minimax-m3": "anthropic-messages",
@@ -22,30 +33,44 @@ OPENCODE_GO_MODEL_PROVIDER_APIS = {
"minimax-m2.5": "anthropic-messages",
}
OPENCODE_GO_FALLBACK_MODELS = [
"minimax-m3",
"kimi-k3",
"glm-5.3",
"qwen3.8-max",
"gpt-5.6-luna",
"minimax-m2.7",
"minimax-m2.5",
"kimi-k2.6",
"kimi-k2.5",
"glm-5.1",
"glm-5",
"glm-5.3-flash",
"deepseek-v4.1-flash",
"deepseek-v4-pro",
"deepseek-v4-flash",
"qwen3.6-plus",
"qwen3.5-plus",
"mimo-v2.5-pro",
"mimo-v2.5",
"kimi-k3.1-pro",
"kimi-k3",
"kimi-k2.7-code",
"minimax-m3",
"minimax-m3.1-flash",
"qwen4-max",
"qwen3.8-max",
"qwen3.8-flash",
"qwen3.7-plus",
"gpt-6-luna",
"gpt-5.6-luna",
"grok-4.7",
"claude-haiku-5-5",
"gemini-4-argon",
"mimo-v2.6-pro",
"mimo-v2.6-flash",
"hy4",
"hy4-flash-free",
"step-5-preview",
"muse-spark-1.3-contributor",
"muse-spark-1.2-contributor",
]
OPENAI_MODEL_PROVIDER_APIS = {
model: "openai-responses"
for model in [
"gpt-6.2-astra",
"gpt-6.2-sol",
"gpt-6.1-terra",
"gpt-6.1-sol",
"gpt-6-astra",
"gpt-6-sol",
"gpt-6-luna",
"gpt-5.6-sol",
"gpt-5.6-terra",
"gpt-5.6-luna",
@@ -80,8 +105,18 @@ FALLBACK_LLM_PROVIDER_PRESETS: dict[str, dict[str, Any]] = {
"label": "OpenAI",
"provider_api": "openai-responses",
"base_url": "https://api.openai.com/v1",
"model": "gpt-6-astra",
"models": ["gpt-6-astra", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-4.1"],
"model": "gpt-6.2-astra",
"models": [
"gpt-6.2-astra",
"gpt-6.2-sol",
"gpt-6.1-terra",
"gpt-6.1-sol",
"gpt-6-astra",
"gpt-6-sol",
"gpt-6-luna",
"gpt-5.6-sol",
"gpt-4.1",
],
"model_provider_apis": OPENAI_MODEL_PROVIDER_APIS,
"api_key_env": "OPENAI_API_KEY",
"source": "fallback",
@@ -126,13 +161,66 @@ FALLBACK_LLM_PROVIDER_PRESETS: dict[str, dict[str, Any]] = {
"api_key_env": "MOONSHOT_API_KEY",
"source": "fallback",
},
"glm": {
"provider": "glm",
"label": "Zhipu AI / GLM (CN)",
"provider_api": "openai-completions",
"base_url": "https://open.bigmodel.cn/api/paas/v4",
"model": "glm-5.3",
"models": ["glm-5.3", "glm-5.3-flash", "glm-5.3-flashx", "glm-5.2", "glm-5.1", "glm-5"],
"api_key_env": "ZHIPU_API_KEY",
"source": "fallback",
},
"meta": {
"provider": "meta",
"label": "Meta AI",
"provider_api": "openai-completions",
"base_url": "https://api.meta.ai/v1",
"model": "muse-ember-1.0",
"models": ["muse-ember-1.0", "muse-wonder-1.0", "muse-spark-1.3", "muse-spark-1.2", "muse-spark-1.1"],
"api_key_env": "META_MODEL_API_KEY",
"source": "fallback",
},
"gemini": {
"provider": "gemini",
"label": "Google Gemini",
"provider_api": "openai-completions",
"base_url": "https://generativelanguage.googleapis.com/v1beta/openai",
"model": "gemini-4-neon",
"models": [
"gemini-4-neon",
"gemini-4-hydrogen",
"gemini-4-carbon",
"gemini-4-argon",
"gemini-3.8-flash",
"gemini-2.5-flash",
],
"api_key_env": "GEMINI_API_KEY",
"source": "fallback",
},
"grok": {
"provider": "grok",
"label": "xAI Grok",
"provider_api": "openai-completions",
"base_url": "https://api.x.ai/v1",
"model": "grok-4.7",
"models": ["grok-4.7", "grok-4.6", "grok-4.5", "grok-4.3", "grok-4.20-0309-reasoning"],
"api_key_env": "XAI_API_KEY",
"source": "fallback",
},
"openrouter": {
"provider": "openrouter",
"label": "OpenRouter",
"provider_api": "openai-completions",
"base_url": "https://openrouter.ai/api/v1",
"model": "openai/gpt-5.1",
"models": ["openai/gpt-5.1", "anthropic/claude-sonnet-4.5", "qwen/qwen3-max"],
"model": "openai/gpt-6.2-astra",
"models": [
"openai/gpt-6.2-astra",
"openai/gpt-6.2-sol",
"google/gemini-4-neon",
"qwen/qwen4-max",
"anthropic/claude-sonnet-4.5",
],
"api_key_env": "OPENROUTER_API_KEY",
"source": "fallback",
},
@@ -141,7 +229,7 @@ FALLBACK_LLM_PROVIDER_PRESETS: dict[str, dict[str, Any]] = {
"label": "OpenCode Go",
"provider_api": "openai-completions",
"base_url": "https://opencode.ai/zen/go/v1",
"model": "glm-5.1",
"model": "glm-5.3",
"models": OPENCODE_GO_FALLBACK_MODELS,
"model_provider_apis": OPENCODE_GO_MODEL_PROVIDER_APIS,
"api_key_env": "OPENCODE_GO_API_KEY",
@@ -178,6 +266,15 @@ def _opencode_go_model_provider_apis(model_ids: list[str]) -> dict[str, str]:
}
def _openai_model_provider_apis(model_ids: list[str]) -> dict[str, str]:
mapping: dict[str, str] = {}
for model_id in model_ids:
lower = model_id.strip().lower()
if model_id in OPENAI_MODEL_PROVIDER_APIS or lower.startswith(("gpt-6", "gpt-5", "o3", "o4")):
mapping[model_id] = OPENAI_MODEL_PROVIDER_APIS.get(model_id, "openai-responses")
return mapping
async def refresh_llm_provider_preset(
provider: str,
api_key: str | None = None,
@@ -189,23 +286,69 @@ async def refresh_llm_provider_preset(
fallback = get_fallback_llm_provider_preset(provider)
resolved_base_url = base_url or fallback["base_url"]
resolved_api = provider_api or fallback["provider_api"]
catalog = await fetch_model_catalog(
fallback["provider"],
resolved_base_url,
resolved_api,
api_key or "",
anthropic_version,
)
model_provider_apis = (
_opencode_go_model_provider_apis(catalog.models)
if fallback["provider"] == "opencode-go"
else fallback.get("model_provider_apis", {})
resolved_api_key = (api_key or "").strip()
supports_aggregator = catalog_supports_aggregator_fallback(
fallback["provider"], resolved_base_url, resolved_api
)
if (
fallback["provider"] == "openai"
and urlsplit(resolved_base_url).hostname != "api.openai.com"
not resolved_api_key
and catalog_requires_api_key(fallback["provider"], resolved_base_url, resolved_api)
and supports_aggregator
):
model_provider_apis = {}
catalog = await fetch_aggregator_model_catalog(
fallback["provider"],
resolved_base_url,
resolved_api,
)
else:
try:
catalog = await fetch_model_catalog(
fallback["provider"],
resolved_base_url,
resolved_api,
resolved_api_key,
anthropic_version,
include_auth=not is_official_public_catalog(
fallback["provider"], resolved_base_url
),
)
except (httpx.HTTPError, TimeoutError) as official_exc:
if not resolved_api_key or not supports_aggregator:
raise
logger.warning(
"Official LLM catalog request failed; falling back to public aggregator",
extra={
"event": "settings.ai_provider.catalog.official_fallback",
"context": {
"provider": fallback["provider"],
"error_type": type(official_exc).__name__,
"status_code": (
official_exc.response.status_code
if isinstance(official_exc, httpx.HTTPStatusError)
else None
),
},
},
)
try:
catalog = await fetch_aggregator_model_catalog(
fallback["provider"],
resolved_base_url,
resolved_api,
)
except Exception:
# Preserve the original official error (e.g. 401 invalid API key) if public aggregators also fail.
raise official_exc from None
if fallback["provider"] == "opencode-go":
model_provider_apis = _opencode_go_model_provider_apis(catalog.models)
elif fallback["provider"] == "openai":
model_provider_apis = (
{}
if urlsplit(resolved_base_url).hostname != "api.openai.com"
else _openai_model_provider_apis(catalog.models)
)
else:
model_provider_apis = fallback.get("model_provider_apis", {})
return {
**fallback,
"base_url": resolved_base_url,
@@ -0,0 +1,664 @@
"""Controlled multi-step Tool-Calling agent & L1 resolvers for unknown facility locations."""
from __future__ import annotations
import asyncio
from datetime import UTC, datetime
import json
from typing import Any
from uuid import uuid4
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.models.compute_center_location import ComputeCenterLocationRecord
from app.models.situational_assessment import WorkflowRun
from app.schemas.ai import SituationalAnalysisRequest
from app.services.ai.tool_registry import isolate_untrusted_external_text, safe_web_fetch
from app.services.ai.workflow_registry import resolve_runtime_workflow_node
from app.services.location.llm_fallback import (
DEFAULT_MIN_CONFIDENCE,
LocationLLMFallbackResult,
collect_llm_location_fallback_candidate,
)
from app.services.location.models import LocationCandidate, LocationQuery
from app.services.location.resolvers.nominatim import build_default_nominatim_geocoder
from app.services.location.resolvers.peeringdb_facility import lookup_peeringdb_facility
from app.services.location.resolvers.wikidata import lookup_wikidata_facility
from app.services.location.text import coerce_str, normalize_country_text, normalize_text, parse_float
logger = get_logger(__name__, service="location_agent")
TERMINAL_UNLOCATABLE_STATUSES: frozenset[str] = frozenset({"undisclosed", "multi_site", "anonymous"})
_agent_geocoder = build_default_nominatim_geocoder()
LOCATION_AGENT_TOOLS: list[dict[str, Any]] = [
{
"name": "fetch_source_url",
"description": "Fetch and read a primary source webpage (especially Epoch Source 1..5 or TOP500 detail URL) cleanly with prompt-injection isolation.",
"parameters": {
"type": "object",
"properties": {"url": {"type": "string", "description": "Public http/https URL"}},
"required": ["url"],
},
},
{
"name": "web_search",
"description": "Search the web using concise English or local-language queries (do not chain long hardware suffixes).",
"parameters": {
"type": "object",
"properties": {"query": {"type": "string", "description": "Concise search query"}},
"required": ["query"],
},
},
{
"name": "geocode_verify",
"description": "Verify a physical facility address or city via geocoder and receive a verified geocode_candidate_id with coordinates and country.",
"parameters": {
"type": "object",
"properties": {
"place_query": {"type": "string", "description": "Address, campus, or city + country"},
"country": {"type": "string", "description": "Expected country name"},
},
"required": ["place_query"],
},
},
{
"name": "submit_location_result",
"description": "Finalize location verification using a geocode_candidate_id from geocode_verify, or report a terminal status (undisclosed/multi_site/anonymous/unresolved).",
"parameters": {
"type": "object",
"properties": {
"status": {
"type": "string",
"enum": ["located", "undisclosed", "multi_site", "anonymous", "unresolved"],
},
"facility_name": {"type": "string"},
"address": {"type": "string"},
"city": {"type": "string"},
"region": {"type": "string"},
"country": {"type": "string"},
"precision": {"type": "string", "enum": ["precise", "site", "city"]},
"geocode_candidate_id": {"type": "string"},
"citations": {
"type": "array",
"items": {"type": "string"},
"description": "URLs directly observed in fetch_source_url or web_search outputs",
},
"confidence": {"type": "number"},
"reasoning": {"type": "string"},
},
"required": ["status", "reasoning"],
},
},
]
async def run_l1_structured_facility_resolvers(
query: LocationQuery,
*,
db: AsyncSession | None = None,
) -> tuple[list[LocationCandidate], list[str], bool]:
"""Run async L1 Wikidata & PeeringDB lookups respecting `location.resolve_unknown` config."""
l1_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l1_knowledge")
params = (l1_node or {}).get("params") or {}
enabled_tools = set((l1_node or {}).get("tools") or [])
allow_low_short_circuit = bool(params.get("allow_low_confidence_short_circuit", False))
tasks = []
if params.get("wikidata_enabled", True) and (not enabled_tools or "wikidata_lookup" in enabled_tools):
tasks.append(lookup_wikidata_facility(query))
if params.get("peeringdb_enabled", True) and (not enabled_tools or "peeringdb_fac_lookup" in enabled_tools):
tasks.append(lookup_peeringdb_facility(query))
candidates: list[LocationCandidate] = []
attempted: list[str] = []
if tasks:
results = await asyncio.gather(*tasks, return_exceptions=True)
for out in results:
if isinstance(out, Exception):
continue
attempted.extend(out.attempted_queries)
candidates.extend(out.candidates)
return candidates, attempted, allow_low_short_circuit
async def _persist_terminal_location_status(
db: AsyncSession | None,
*,
query: LocationQuery,
terminal_status: str,
reasoning: str,
) -> None:
if db is None or not hasattr(db, "execute"):
return
extra = query.extra or {}
source = coerce_str(extra.get("source"))
source_id = coerce_str(extra.get("source_id"))
if not source or not source_id:
return
try:
from app.services.compute_center_locations import refresh_compute_center_location_cache
existing = await db.scalar(
select(ComputeCenterLocationRecord)
.where(ComputeCenterLocationRecord.source == source)
.where(ComputeCenterLocationRecord.source_id == source_id)
)
if existing is None:
existing = ComputeCenterLocationRecord(
source=source,
source_id=source_id,
name=query.name,
operator=coerce_str(extra.get("operator")) or None,
site=coerce_str(extra.get("site")) or None,
city=query.city,
country=query.country,
latitude=None,
longitude=None,
precision="unknown",
confidence=0.0,
location_source=f"agent_terminal_{terminal_status}",
source_note=reasoning[:500] or f"Marked {terminal_status} by location agent",
needs_confirmation=False,
verification_status=terminal_status,
verified_at=datetime.now(UTC),
)
db.add(existing)
else:
existing.precision = "unknown"
existing.latitude = None
existing.longitude = None
existing.verification_status = terminal_status
existing.location_source = f"agent_terminal_{terminal_status}"
existing.source_note = reasoning[:500] or existing.source_note
existing.verified_at = datetime.now(UTC)
await db.commit()
await refresh_compute_center_location_cache(db)
except Exception as exc:
logger.warning_event(
"Failed to persist terminal unlocatable status",
event="location.agent.persist_terminal_failed",
context={"source_id": source_id, "status": terminal_status, "error": str(exc)},
)
async def _record_location_workflow_run(
db: AsyncSession | None,
*,
question: str,
status_value: str,
tool_trace: list[str],
steps_used: int,
error_message: str = "",
) -> None:
if db is None or not hasattr(db, "add"):
return
try:
db.add(
WorkflowRun(
id=f"run_{uuid4().hex[:16]}",
workflow_id="location.resolve_unknown",
status=status_value,
access_tier="admin",
actor_key="admin:collect-location",
question=question[:500],
tool_trace=tool_trace,
budget_used={"steps": steps_used},
error_message=error_message[:500],
completed_at=datetime.now(UTC),
)
)
await db.commit()
except Exception:
try:
await db.rollback()
except Exception:
pass
async def run_controlled_location_agent(
*,
provider_client: Any,
web_search_client: Any | None,
query: LocationQuery,
entity_type: str = "compute_center",
db: AsyncSession | None = None,
attempted_queries: list[str] | None = None,
) -> tuple[LocationLLMFallbackResult, str | None]:
"""Run the 3-4 step Tool-Calling location agent and return `(result, terminal_status)`."""
extra = query.extra or {}
l2_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l2_agent_research")
l3_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l3_geo_guardrail")
if l2_node and not l2_node.get("enabled", True):
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=list(attempted_queries or []),
failure_reason="Location agent node is disabled by workflow configuration.",
),
None,
)
max_steps = max(1, min(int((l2_node or {}).get("max_steps") or 4), 6))
allowed_tool_names = set((l2_node or {}).get("tools") or [t["name"] for t in LOCATION_AGENT_TOOLS])
min_confidence = float(((l3_node or {}).get("guardrails") or {}).get("min_confidence") or DEFAULT_MIN_CONFIDENCE)
require_tool_urls = bool(((l3_node or {}).get("guardrails") or {}).get("require_tool_cited_urls", True))
active_tools = [t for t in LOCATION_AGENT_TOOLS if t["name"] in allowed_tool_names]
if not any(t["name"] == "submit_location_result" for t in active_tools):
active_tools.append(LOCATION_AGENT_TOOLS[-1])
observed_urls: set[str] = set()
geocode_candidates: dict[str, dict[str, Any]] = {}
tool_trace: list[str] = ["l0_normalize", "l1_knowledge"]
agent_attempts: list[str] = []
source_urls = [
str(u).strip()
for u in [*([extra.get("source_url")] if extra.get("source_url") else []), *(extra.get("sources") or [])]
if str(u or "").strip().startswith(("http://", "https://"))
]
system_prompt = (l2_node or {}).get("system_prompt") or (
"你是算力与网络基础设施物理位置查证 Agent。严禁编造经纬度!"
"1) 若存在 primary_source_urls,优先调用 fetch_source_url;"
"2) 否则调用 web_search 查询物理地址;"
"3) 将查到的物理地址/城市传入 geocode_verify 获取 candidate_id;"
"4) 最后调用 submit_location_result 提交结果。"
)
user_objective = (l2_node or {}).get("prompt") or (
f"请查证目标设施 {query.name or extra.get('source_id')} 的物理所在城市或园区。"
)
context_payload = {
"name": query.name,
"name_short": query.aliases[0] if query.aliases else query.name,
"operator": extra.get("operator") or None,
"site": extra.get("site") or None,
"city": query.city,
"country": query.country,
"raw_country": extra.get("source_raw_country"),
"primary_source_urls": source_urls[:5],
}
messages: list[dict[str, Any]] = [
{
"role": "user",
"content": (
f"{user_objective}\n\n目标上下文 JSON:\n"
f"{json.dumps(context_payload, ensure_ascii=False)}"
),
}
]
submitted_payload: dict[str, Any] | None = None
last_text_response = ""
steps_taken = 0
for step in range(1, max_steps + 1):
steps_taken = step
req = SituationalAnalysisRequest(
title=f"Location agent step {step}",
objective=user_objective,
system_prompt=system_prompt,
context=context_payload,
preferred_model=(l2_node or {}).get("model_override"),
messages=messages,
tools=active_tools,
tool_choice="auto" if step < max_steps else {"type": "function", "name": "submit_location_result"},
native_web_search=bool((l2_node or {}).get("native_web_search", False)),
)
try:
resp = await provider_client.analyze(req)
except Exception as exc:
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message=str(exc),
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=f"Location agent failed: {exc}",
),
None,
)
last_text_response = str(getattr(resp, "content", "") or "")
tool_calls = list(getattr(resp, "tool_calls", None) or [])
if not tool_calls:
# Provider returned plain text (no tool calling support); break cleanly into deterministic fallback.
break
messages.append(
{
"role": "assistant",
"content": last_text_response,
"tool_calls": [
{"id": tc.id, "name": tc.name, "arguments": tc.arguments}
for tc in tool_calls
],
}
)
for tc in tool_calls:
raw_args = tc.arguments
if isinstance(raw_args, str):
try:
raw_args = json.loads(raw_args)
except json.JSONDecodeError:
raw_args = {}
args = raw_args if isinstance(raw_args, dict) else {}
tool_trace.append(f"l2_agent_research:{tc.name}")
if tc.name == "fetch_source_url":
target_url = coerce_str(args.get("url"))
agent_attempts.append(f"fetch_url:{target_url}")
try:
fetched = await asyncio.wait_for(safe_web_fetch(target_url, timeout_seconds=8), timeout=10.0)
final_url = (
coerce_str(fetched.get("final_url") or fetched.get("url"))
if isinstance(fetched, dict)
else coerce_str(getattr(fetched, "final_url", None) or getattr(fetched, "url", None))
) or target_url
title = fetched.get("title", "") if isinstance(fetched, dict) else getattr(fetched, "title", "")
text = fetched.get("content", "") if isinstance(fetched, dict) else getattr(fetched, "text", "")
observed_urls.add(target_url)
observed_urls.add(final_url)
tool_output = isolate_untrusted_external_text(final_url, title, text, max_chars=2400)
except Exception as exc:
tool_output = {"error": f"fetch failed: {exc}", "url": target_url}
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"name": tc.name,
"content": json.dumps(tool_output, ensure_ascii=False),
}
)
elif tc.name == "web_search":
q_str = coerce_str(args.get("query"))
agent_attempts.append(f"web_search:{q_str}")
if web_search_client is None:
tool_output = {"error": "WebSearch is not enabled or missing API key"}
else:
try:
evidences = await web_search_client.search(q_str, max_results=5)
items = []
for ev in evidences:
u = coerce_str(getattr(ev, "url", ""))
if u:
observed_urls.add(u)
items.append(
{
"title": getattr(ev, "title", ""),
"url": u,
"snippet": getattr(ev, "snippet", "")[:400],
}
)
tool_output = {"results": items}
except Exception as exc:
tool_output = {"error": str(exc)}
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"name": tc.name,
"content": json.dumps(tool_output, ensure_ascii=False),
}
)
elif tc.name == "geocode_verify":
place_q = coerce_str(args.get("place_query"))
expected_c = normalize_country_text(args.get("country") or query.country)
agent_attempts.append(f"geocode_verify:{place_q}")
try:
geo_res = await asyncio.to_thread(_agent_geocoder, place_q)
except Exception as exc:
logger.warning_event(
"Location agent geocode_verify failed",
event="location_agent.geocode_verify.failed",
context={"place_query": place_q, "error": str(exc)},
)
geo_res = None
geocode_error = f"geocoder request failed: {exc}"
else:
geocode_error = ""
if geocode_error:
tool_output = {"found": False, "error": geocode_error, "retryable": True}
elif not isinstance(geo_res, dict):
tool_output = {"found": False, "reason": "No geocoder match"}
else:
lat = parse_float(geo_res.get("lat") if geo_res.get("lat") is not None else geo_res.get("latitude"))
lon = parse_float(geo_res.get("lon") if geo_res.get("lon") is not None else geo_res.get("longitude"))
addr = geo_res.get("address") if isinstance(geo_res.get("address"), dict) else {}
res_country = normalize_country_text(addr.get("country") or geo_res.get("country"))
if (
lat in (None, 0.0)
or lon in (None, 0.0)
or not (-90.0 <= lat <= 90.0)
or not (-180.0 <= lon <= 180.0)
):
tool_output = {"found": False, "reason": "Invalid geocoder coordinates"}
elif expected_c and res_country and normalize_text(res_country) != normalize_text(expected_c):
tool_output = {
"found": False,
"reason": f"Country mismatch: got {res_country}, expected {expected_c}",
}
else:
cid = f"geo_{len(geocode_candidates) + 1}"
geocode_candidates[cid] = {
"latitude": lat,
"longitude": lon,
"display_name": coerce_str(geo_res.get("display_name")) or place_q,
"city": coerce_str(
addr.get("city")
or addr.get("town")
or addr.get("village")
or addr.get("municipality")
or geo_res.get("city")
),
"region": coerce_str(addr.get("state") or addr.get("region") or geo_res.get("region")),
"country": res_country or expected_c or query.country,
}
tool_output = {"found": True, "geocode_candidate_id": cid, **geocode_candidates[cid]}
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"name": tc.name,
"content": json.dumps(tool_output, ensure_ascii=False),
}
)
elif tc.name == "submit_location_result":
submitted_payload = dict(args)
tool_trace.append("l3_geo_guardrail")
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"name": tc.name,
"content": json.dumps({"accepted": True}),
}
)
if submitted_payload is not None:
break
if submitted_payload is None:
# Fallback for providers/mocks without tool_calls support
evidence_list = []
if web_search_client is not None:
from app.services.location.llm_fallback import collect_location_search_evidence
search_res = await collect_location_search_evidence(
web_search_client=web_search_client,
query=query,
entity_type=entity_type,
)
agent_attempts.extend(search_res.attempted_queries)
evidence_list = search_res.evidence
if evidence_list or last_text_response:
fallback_res = await collect_llm_location_fallback_candidate(
provider_client=provider_client,
query=query,
entity_type=entity_type,
db=db,
attempted_queries=[*(attempted_queries or []), *agent_attempts],
search_evidence=evidence_list,
min_confidence=min_confidence,
)
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="completed" if fallback_res.candidates else "failed",
tool_trace=[*tool_trace, "llm_fallback"],
steps_used=steps_taken,
error_message=fallback_res.failure_reason or "",
)
return fallback_res, None
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message="Agent did not submit location result",
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason="Location agent reached step budget without submitting a verified location.",
),
None,
)
sub_status = str(submitted_payload.get("status") or "unresolved").strip().lower()
reasoning = coerce_str(submitted_payload.get("reasoning"))
if sub_status in TERMINAL_UNLOCATABLE_STATUSES:
await _persist_terminal_location_status(
db,
query=query,
terminal_status=sub_status,
reasoning=reasoning,
)
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="completed",
tool_trace=[*tool_trace, f"l4_persist_outcome:{sub_status}"],
steps_used=steps_taken,
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=reasoning or f"Facility confirmed as {sub_status}.",
),
sub_status,
)
geo_cid = coerce_str(submitted_payload.get("geocode_candidate_id"))
geo_entry = geocode_candidates.get(geo_cid)
if sub_status != "located" or geo_entry is None:
reason = reasoning or "Submitted result missing verified geocode_candidate_id"
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message=reason,
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=reason,
),
None,
)
citations = [
str(c).strip()
for c in (submitted_payload.get("citations") or [])
if str(c or "").strip()
]
verified_citations = [c for c in citations if c in observed_urls]
if require_tool_urls and not verified_citations:
reason = "No verified citation URLs observed in tool outputs"
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message=reason,
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=reason,
),
None,
)
expected_country = normalize_country_text(query.country)
resolved_country = normalize_country_text(submitted_payload.get("country") or geo_entry.get("country"))
if expected_country and resolved_country and normalize_text(resolved_country) != normalize_text(expected_country):
reason = f"Country mismatch ({resolved_country} != {expected_country})"
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message=reason,
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=reason,
),
None,
)
confidence = min(max(parse_float(submitted_payload.get("confidence")) or 0.78, 0.0), 1.0)
raw_precision = coerce_str(submitted_payload.get("precision")).lower()
precision = raw_precision if raw_precision in {"precise", "site", "city"} else "city"
facility_label = coerce_str(submitted_payload.get("facility_name")) or coerce_str(geo_entry.get("display_name")) or coerce_str(query.name)
candidate = LocationCandidate(
latitude=float(geo_entry["latitude"]),
longitude=float(geo_entry["longitude"]),
display_name=facility_label,
precision=precision,
confidence=max(confidence, min_confidence),
query=f"location_agent:{entity_type}:{query.name or extra.get('source_id') or 'unknown'}",
source="llm_location_factcheck",
source_note=reasoning or f"Verified via tool-calling agent ({len(verified_citations)} citations)",
matched_fields=("name", "tool_calling_agent"),
needs_confirmation=True,
city=coerce_str(submitted_payload.get("city")) or geo_entry.get("city") or query.city or None,
region=coerce_str(submitted_payload.get("region")) or geo_entry.get("region") or query.region or None,
country=resolved_country or expected_country or query.country,
matched_location_name=facility_label,
raw_payload={"citations": verified_citations or citations, "geocode_candidate_id": geo_cid},
)
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="completed",
tool_trace=[*tool_trace, "l4_persist_outcome:located"],
steps_used=steps_taken,
)
return (
LocationLLMFallbackResult(
candidates=[candidate],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=None,
),
None,
)
+74 -27
View File
@@ -266,7 +266,14 @@ def _detect_country_in_text(text: str) -> str:
variants = [canonical, *aliases]
for variant in variants:
normalized_variant = normalize_text(variant)
if normalized_variant and normalized_variant in normalized_text:
if not normalized_variant:
continue
if normalized_variant.isascii():
if len(normalized_variant) < 4:
continue
if re.search(rf"\b{re.escape(normalized_variant)}\b", normalized_text):
return canonical
elif normalized_variant in normalized_text:
return canonical
return ""
@@ -488,6 +495,7 @@ def _fill_city_coordinates_from_geocoder(
if not geocode_queries:
return payload, None
expected_country = normalize_text(normalize_country_text(country or query.country))
failures: list[str] = []
geocode_query = ""
result: dict[str, Any] | None = None
@@ -503,9 +511,19 @@ def _fill_city_coordinates_from_geocoder(
continue
latitude = parse_float(maybe_result.get("lat"))
longitude = parse_float(maybe_result.get("lon"))
if latitude in (None, 0.0) or longitude in (None, 0.0):
if (
latitude in (None, 0.0)
or longitude in (None, 0.0)
or not (-90.0 <= latitude <= 90.0)
or not (-180.0 <= longitude <= 180.0)
):
failures.append(f"{geocode_query}: invalid coordinates")
continue
cand_addr = maybe_result.get("address") if isinstance(maybe_result.get("address"), dict) else {}
cand_country = normalize_text(normalize_country_text(cand_addr.get("country")))
if expected_country and cand_country and cand_country != expected_country:
failures.append(f"{geocode_query}: country mismatch ({cand_country} != {expected_country})")
continue
result = maybe_result
break
if result is None:
@@ -514,7 +532,12 @@ def _fill_city_coordinates_from_geocoder(
latitude = parse_float(result.get("lat"))
longitude = parse_float(result.get("lon"))
if latitude in (None, 0.0) or longitude in (None, 0.0):
if (
latitude in (None, 0.0)
or longitude in (None, 0.0)
or not (-90.0 <= latitude <= 90.0)
or not (-180.0 <= longitude <= 180.0)
):
return payload, f"city geocode fallback returned invalid coordinates for '{geocode_query}'"
address = result.get("address") if isinstance(result.get("address"), dict) else {}
city = (
@@ -527,9 +550,11 @@ def _fill_city_coordinates_from_geocoder(
)
country = country or address.get("country")
try:
precision = _normalize_llm_precision(payload.get("precision")) or "city"
raw_precision = _normalize_llm_precision(payload.get("precision")) or "city"
except Exception:
precision = "city"
raw_precision = "city"
# City-level geocoder fallback must never keep inflated site/precise claims.
precision = "city" if raw_precision in {"precise", "site", "city"} else raw_precision
filled = {
**payload,
"latitude": latitude,
@@ -665,7 +690,15 @@ def _ambiguity_text(payload: dict[str, Any], evidence_items: list[dict[str, Any]
def _conflict_penalty(payload: dict[str, Any], evidence_items: list[dict[str, Any]]) -> float:
penalty = 0.0
ambiguity_text = _ambiguity_text(payload, evidence_items)
if any(token in ambiguity_text for token in ("conflict", "contradict", "inconsistent")):
cleaned_text = re.sub(
r"\b(?:no|without|not|zero)\s+(?:conflict|contradiction|ambiguity)s?\b|无冲突|未见矛盾",
" ",
ambiguity_text,
)
if any(
token in cleaned_text
for token in ("conflict", "contradict", "inconsistent", "冲突", "矛盾", "不一致")
):
penalty += 0.35
if any(
_truthy_evidence_field(item, "has_conflict", "conflicting")
@@ -685,8 +718,12 @@ def _weak_evidence_penalty(
conflict_penalty: float,
) -> float:
ambiguity_text = _ambiguity_text(payload, evidence_items)
cleaned_text = re.sub(r"\b(?:no|without|not)\s+ambiguity\b|无歧义", " ", ambiguity_text)
penalty = 0.0
if any(token in ambiguity_text for token in ("ambiguous", "unclear", "weak", "guess")):
if any(
token in cleaned_text
for token in ("ambiguous", "unclear", "weak", "guess", "存疑", "不确定", "猜测", "无法确认")
):
penalty += 0.20
if any(_truthy_evidence_field(item, "ambiguous") for item in evidence_items):
penalty += 0.15
@@ -762,7 +799,12 @@ def _candidate_from_payload(
min_confidence: float,
) -> tuple[LocationCandidate | None, str | None]:
latitude, longitude = _extract_llm_coordinates(payload)
if latitude in (None, 0.0) or longitude in (None, 0.0):
if (
latitude in (None, 0.0)
or longitude in (None, 0.0)
or not (-90.0 <= latitude <= 90.0)
or not (-180.0 <= longitude <= 180.0)
):
return None, "missing, invalid, or zero latitude/longitude"
precision = _normalize_llm_precision(payload.get("precision"))
@@ -770,11 +812,11 @@ def _candidate_from_payload(
return None, f"precision '{payload.get('precision')}' is not precise/site/city"
city = coerce_str(payload.get("city")) or query.city or None
country = (
normalize_country_text(payload.get("country"))
or normalize_country_text(query.country)
or query.country
)
payload_country = normalize_country_text(payload.get("country"))
expected_country = normalize_country_text(query.country)
if payload_country and expected_country and normalize_text(payload_country) != normalize_text(expected_country):
return None, f"country '{payload_country}' contradicts expected '{expected_country}'"
country = payload_country or expected_country or query.country
evidence_score = _score_llm_location_payload(payload, query=query, precision=precision)
if evidence_score.score < min_confidence:
return None, (
@@ -1230,20 +1272,25 @@ async def collect_llm_location_fallback_candidate(
if search_evidence:
payload["search_evidence"] = search_evidence
existing_evidence = _evidence_items(payload.get("evidence"))
payload["evidence"] = [
*existing_evidence,
*[
{
"source": item.get("title") or item.get("url"),
"url": item.get("url"),
"text": item.get("snippet") or item.get("content"),
"source_type": "web_search",
"entity_match": _search_evidence_entity_match(item, query),
}
for item in search_evidence
if isinstance(item, dict)
],
]
search_by_url = {
str(item.get("url")).strip(): item
for item in search_evidence
if isinstance(item, dict) and item.get("url")
}
enriched_evidence = []
for item in existing_evidence:
url = coerce_str(item.get("url"))
matched_search = search_by_url.get(url)
if matched_search is not None:
enriched_evidence.append(
{
**item,
"entity_match": item.get("entity_match") or _search_evidence_entity_match(matched_search, query),
}
)
else:
enriched_evidence.append(item)
payload["evidence"] = enriched_evidence
latitude, longitude = _extract_llm_coordinates(payload)
city_geocode_failure = None
if latitude in (None, 0.0) or longitude in (None, 0.0):
@@ -14,12 +14,15 @@ can swap the geocoder behavior without touching pipeline construction.
from __future__ import annotations
import ssl
import time
from functools import lru_cache
from typing import Any, Callable
import httpx
from app.core.logging import get_logger
from ..models import LocationCandidate, LocationQuery, ResolverOutput
from ..text import (
coerce_str,
@@ -28,6 +31,9 @@ from ..text import (
parse_float,
)
logger = get_logger(__name__, service="location_geocoder")
_RETRYABLE_STATUS_CODES: frozenset[int] = frozenset({429, 502, 503, 504})
NOMINATIM_SEARCH_URL = "https://nominatim.openstreetmap.org/search"
DEFAULT_USER_AGENT = "planet-earth-location-resolver/1.0"
DEFAULT_MIN_INTERVAL_SECONDS = 1.1
@@ -40,8 +46,10 @@ def build_default_nominatim_geocoder(
min_interval_seconds: float = DEFAULT_MIN_INTERVAL_SECONDS,
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
cache_size: int = 512,
max_retries: int = 2,
retry_backoff_seconds: float = 0.6,
) -> Callable[[str], dict[str, Any] | None]:
"""Return a cached, rate-limited Nominatim geocoder."""
"""Return a cached, rate-limited Nominatim geocoder with transient retry."""
last_request_at = [0.0]
@@ -49,29 +57,52 @@ def build_default_nominatim_geocoder(
def geocode(query: str) -> dict[str, Any] | None:
if not query:
return None
elapsed = time.monotonic() - last_request_at[0]
if elapsed < min_interval_seconds:
time.sleep(min_interval_seconds - elapsed)
last_request_at[0] = time.monotonic()
response = httpx.get(
NOMINATIM_SEARCH_URL,
params={
"q": query,
"format": "jsonv2",
"limit": 1,
"addressdetails": 1,
},
headers={"User-Agent": user_agent},
timeout=timeout_seconds,
)
response.raise_for_status()
payload = response.json()
if not isinstance(payload, list) or not payload:
return None
result = payload[0]
if not isinstance(result, dict):
return None
return result
attempts = max(0, int(max_retries)) + 1
for attempt in range(attempts):
elapsed = time.monotonic() - last_request_at[0]
if elapsed < min_interval_seconds:
time.sleep(min_interval_seconds - elapsed)
last_request_at[0] = time.monotonic()
try:
response = httpx.get(
NOMINATIM_SEARCH_URL,
params={
"q": query,
"format": "jsonv2",
"limit": 1,
"addressdetails": 1,
},
headers={"User-Agent": user_agent},
timeout=timeout_seconds,
)
response.raise_for_status()
payload = response.json()
if not isinstance(payload, list) or not payload:
return None
result = payload[0]
if not isinstance(result, dict):
return None
return result
except httpx.HTTPStatusError as exc:
status_code = exc.response.status_code if exc.response is not None else 0
if status_code not in _RETRYABLE_STATUS_CODES or attempt >= attempts - 1:
raise
logger.warning_event(
"Nominatim HTTP status transient failure, retrying",
event="location.nominatim.retry",
context={"attempt": attempt + 1, "max_attempts": attempts, "status_code": status_code, "error": str(exc)},
)
except (httpx.TransportError, ssl.SSLError, OSError) as exc:
if attempt >= attempts - 1:
raise
logger.warning_event(
"Nominatim transport/SSL transient failure, retrying",
event="location.nominatim.retry",
context={"attempt": attempt + 1, "max_attempts": attempts, "error": str(exc)},
)
if retry_backoff_seconds > 0:
time.sleep(retry_backoff_seconds * (attempt + 1))
return None
return geocode
@@ -0,0 +1,101 @@
"""PeeringDB Facility (/api/fac) resolver for commercial datacenter compute sites."""
from __future__ import annotations
import os
from typing import Any
import httpx
from ..models import LocationCandidate, LocationQuery, ResolverOutput
from ..text import coerce_str, normalize_country_text, normalize_text, parse_float
PEERINGDB_FAC_URL = "https://www.peeringdb.com/api/fac"
PEERINGDB_USER_AGENT = "Planet-Intelligence-System/1.0"
PEERINGDB_TIMEOUT_SECONDS = 6.0
async def lookup_peeringdb_facility(
query: LocationQuery,
*,
timeout_seconds: float = PEERINGDB_TIMEOUT_SECONDS,
) -> ResolverOutput:
"""Query PeeringDB facilities matching the target site/operator/name."""
extra = query.extra or {}
search_terms: list[str] = []
for raw in [
extra.get("site"),
extra.get("operator"),
*(query.aliases or ()),
query.name,
]:
cleaned = coerce_str(raw)
if cleaned and len(cleaned) >= 3 and cleaned not in search_terms:
search_terms.append(cleaned)
if not search_terms:
return ResolverOutput()
attempted: list[str] = []
candidates: list[LocationCandidate] = []
expected_country = normalize_text(normalize_country_text(query.country))
headers = {"User-Agent": PEERINGDB_USER_AGENT, "Accept": "application/json"}
api_key = os.environ.get("PEERINGDB_API_KEY", "").strip()
async with httpx.AsyncClient(timeout=timeout_seconds, headers=headers) as client:
for term in search_terms[:2]:
attempted.append(f"peeringdb_fac:{term}")
params: dict[str, Any] = {"name__icontains": term, "limit": 4}
if api_key:
params["key"] = api_key
try:
resp = await client.get(PEERINGDB_FAC_URL, params=params)
resp.raise_for_status()
rows = (resp.json() or {}).get("data") or []
except Exception:
continue
term_norm = normalize_text(term)
for item in rows:
if not isinstance(item, dict):
continue
lat = parse_float(item.get("latitude"))
lon = parse_float(item.get("longitude"))
if (
lat in (None, 0.0)
or lon in (None, 0.0)
or not (-90.0 <= lat <= 90.0)
or not (-180.0 <= lon <= 180.0)
):
continue
item_country = normalize_country_text(item.get("country"))
if expected_country and item_country and normalize_text(item_country) != expected_country:
continue
fac_name = coerce_str(item.get("name")) or term
if term_norm and term_norm not in normalize_text(fac_name):
# Require meaningful overlap when fuzzy matched
fac_tokens = set(normalize_text(fac_name).split())
if not (set(term_norm.split()) & fac_tokens):
continue
city = coerce_str(item.get("city")) or None
addr = coerce_str(item.get("address1"))
candidates.append(
LocationCandidate(
latitude=lat,
longitude=lon,
display_name=fac_name,
precision="precise" if addr else "site",
confidence=0.80,
query=f"peeringdb_fac:{term}",
source="peeringdb_facility",
source_note=f"PeeringDB facility #{item.get('id')}: {fac_name}" + (f" ({addr})" if addr else ""),
matched_fields=("site", "peeringdb"),
needs_confirmation=True,
city=city,
region=coerce_str(item.get("state")) or None,
country=item_country or query.country,
matched_location_name=fac_name,
raw_payload={"peeringdb_fac_id": item.get("id"), "address": addr},
)
)
return ResolverOutput(candidates=tuple(candidates), attempted_queries=tuple(attempted))
@@ -0,0 +1,139 @@
"""Wikidata structured entity lookup for compute-center / facility coordinates (P625 / P276)."""
from __future__ import annotations
from typing import Any
import httpx
from ..models import LocationCandidate, LocationQuery, ResolverOutput
from ..text import coerce_str, normalize_country_text, normalize_text, parse_float
WIKIDATA_API_URL = "https://www.wikidata.org/w/api.php"
WIKIDATA_USER_AGENT = "planet-earth-location-resolver/1.0"
WIKIDATA_TIMEOUT_SECONDS = 6.0
async def lookup_wikidata_facility(
query: LocationQuery,
*,
timeout_seconds: float = WIKIDATA_TIMEOUT_SECONDS,
) -> ResolverOutput:
"""Query Wikidata entities for facility-level P625 coordinate claims."""
extra = query.extra or {}
terms: list[str] = []
for raw in [
*(query.aliases or ()),
query.name,
extra.get("site"),
]:
cleaned = coerce_str(raw)
if cleaned and cleaned not in terms:
terms.append(cleaned)
if not terms:
return ResolverOutput()
attempted: list[str] = []
candidates: list[LocationCandidate] = []
seen_qids: set[str] = set()
headers = {"User-Agent": WIKIDATA_USER_AGENT, "Accept": "application/json"}
async with httpx.AsyncClient(timeout=timeout_seconds, headers=headers) as client:
for term in terms[:2]:
attempted.append(f"wikidata:{term}")
try:
search_resp = await client.get(
WIKIDATA_API_URL,
params={
"action": "wbsearchentities",
"search": term,
"language": "en",
"format": "json",
"limit": 4,
},
)
search_resp.raise_for_status()
search_items = (search_resp.json() or {}).get("search") or []
except Exception:
continue
qids = [
str(item.get("id"))
for item in search_items
if isinstance(item, dict) and item.get("id") and item.get("id") not in seen_qids
]
if not qids:
continue
seen_qids.update(qids)
try:
ent_resp = await client.get(
WIKIDATA_API_URL,
params={
"action": "wbgetentities",
"ids": "|".join(qids[:4]),
"props": "labels|descriptions|claims",
"languages": "en|zh",
"format": "json",
},
)
ent_resp.raise_for_status()
entities = (ent_resp.json() or {}).get("entities") or {}
except Exception:
continue
term_tokens = set(normalize_text(term).split())
for qid, entity in entities.items():
if not isinstance(entity, dict):
continue
labels = entity.get("labels") or {}
label = coerce_str((labels.get("en") or {}).get("value") or (labels.get("zh") or {}).get("value"))
desc = coerce_str(((entity.get("descriptions") or {}).get("en") or {}).get("value")).lower()
if label:
label_tokens = set(normalize_text(label).split())
if term_tokens and not (term_tokens & label_tokens):
continue
if desc and not any(
kw in desc
for kw in ("supercomputer", "data center", "datacenter", "computer", "cluster", "laboratory", "facility", "campus")
):
continue
claims = entity.get("claims") or {}
coord_claims = claims.get("P625") or []
for claim in coord_claims:
mainsnak = claim.get("mainsnak") if isinstance(claim, dict) else None
datavalue = (mainsnak or {}).get("datavalue") or {}
val = datavalue.get("value") if isinstance(datavalue, dict) else None
if not isinstance(val, dict):
continue
lat = parse_float(val.get("latitude"))
lon = parse_float(val.get("longitude"))
if (
lat in (None, 0.0)
or lon in (None, 0.0)
or not (-90.0 <= lat <= 90.0)
or not (-180.0 <= lon <= 180.0)
):
continue
country = normalize_country_text(query.country)
candidates.append(
LocationCandidate(
latitude=lat,
longitude=lon,
display_name=label or term,
precision="site",
confidence=0.84,
query=f"wikidata:{term}",
source="wikidata_facility",
source_note=f"Wikidata entity {qid} P625 coordinates ({desc or label})",
matched_fields=("name", "wikidata"),
needs_confirmation=True,
city=query.city or None,
country=country or query.country,
matched_location_name=label or term,
raw_payload={"wikidata_qid": qid, "description": desc},
)
)
break
return ResolverOutput(candidates=tuple(candidates), attempted_queries=tuple(attempted))
Loaded 100 of 354 files, more files were not shown because too many files have changed in this diff. Show more