release: bump version to 0.84.0
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s

This commit is contained in:
linkong committed 2026-12-04 07:07:19 +08:00
1 parent 3b1b9ef68c
commit e1cc27f13d
241 files changed
+42779 -6027

No files matched your search

+279 -157
View File
@@ -1,23 +1,32 @@
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status, Response
from fastapi.responses import StreamingResponse
from sqlalchemy import select, func, text
from sqlalchemy.ext.asyncio import AsyncSession
import json
import csv
import hashlib
import io
import json
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from fastapi.responses import StreamingResponse
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.cache import cache
from app.core.collected_data_fields import get_metadata_field
from app.core.countries import COUNTRY_OPTIONS, get_country_search_variants, normalize_country
from app.core.security import get_current_user
from app.core.time import to_iso8601_utc
from app.db.session import get_db
from app.models.user import User
from app.core.security import get_current_user
from app.models.collected_data import CollectedData
from app.models.datasource import DataSource
from app.models.user import User
router = APIRouter()
DEFAULT_EXCLUDED_DATA_TYPES: tuple[str, ...] = ("prefix_geography",)
DEFAULT_EXCLUDED_SOURCES: frozenset[str] = frozenset(
{"iptoasn_prefix_geo", "opengeofeed_prefix_geo", "nro_delegated_prefix_geo"}
)
COLLECTED_FACETS_CACHE_KEY = "collected:facets:v1"
COLLECTED_FACETS_TTL_SECONDS = 300
COLLECTED_SUMMARY_TTL_SECONDS = 60
COUNTRY_SQL = "metadata->>'country'"
SEARCHABLE_SQL = [
@@ -46,6 +55,50 @@ def build_in_condition(field_sql: str, values: list[str], param_prefix: str, par
return f"{field_sql} IN ({', '.join(placeholders)})"
def build_not_in_condition(field_sql: str, values: tuple[str, ...], param_prefix: str, params: dict) -> str:
placeholders = []
for index, value in enumerate(values):
key = f"{param_prefix}_{index}"
params[key] = value
placeholders.append(f":{key}")
return f"{field_sql} NOT IN ({', '.join(placeholders)})"
def _includes_default_excluded(source_values: list[str], data_type_values: list[str]) -> bool:
if any(dt in DEFAULT_EXCLUDED_DATA_TYPES for dt in data_type_values):
return True
if any(src in DEFAULT_EXCLUDED_SOURCES for src in source_values):
return True
return False
def _facets_cache_key(mode: str) -> str:
return COLLECTED_FACETS_CACHE_KEY if mode != "history" else f"{COLLECTED_FACETS_CACHE_KEY}:history"
def _summary_cache_key(
*,
mode: str,
source: Optional[str],
data_type: Optional[str],
country: Optional[str],
search: Optional[str],
) -> str:
payload = json.dumps(
{
"mode": "history" if mode == "history" else "current",
"source": source or "",
"data_type": data_type or "",
"country": country or "",
"search": (search or "").strip(),
},
sort_keys=True,
ensure_ascii=False,
)
digest = hashlib.sha256(payload.encode("utf-8")).hexdigest()[:24]
return f"collected:summary:v1:{digest}"
def build_search_condition(search: Optional[str], params: dict) -> Optional[str]:
if not search:
return None
@@ -108,7 +161,14 @@ def serialize_collected_row(
*,
include_metadata: bool = True,
) -> dict:
metadata = row[7]
raw_metadata = row[7]
if isinstance(raw_metadata, str):
try:
metadata = json.loads(raw_metadata)
except json.JSONDecodeError:
metadata = None
else:
metadata = raw_metadata
source = row[1]
return {
"id": row[0],
@@ -141,6 +201,43 @@ async def get_source_name_map(db: AsyncSession) -> dict[str, str]:
return {row[0]: row[1] for row in result.fetchall()}
async def _load_collected_facets(
db: AsyncSession,
*,
mode: str,
source_name_map: dict[str, str] | None = None,
) -> list[dict]:
cache_key = _facets_cache_key(mode)
cached_facets = cache.get(cache_key)
if isinstance(cached_facets, list):
return cached_facets
where_sql = "is_current IS TRUE" if mode != "history" else "1=1"
result = await db.execute(
text(
f"""
SELECT source, data_type, COUNT(*) AS count
FROM collected_data
WHERE {where_sql}
GROUP BY source, data_type
ORDER BY source, data_type
"""
)
)
names = source_name_map if source_name_map is not None else await get_source_name_map(db)
facets = [
{
"source": row[0],
"source_name": names.get(row[0], row[0]),
"data_type": row[1],
"count": int(row[2] or 0),
}
for row in result.fetchall()
]
cache.set(cache_key, facets, expire_seconds=COLLECTED_FACETS_TTL_SECONDS)
return facets
@router.get("")
async def list_collected_data(
mode: str = Query("current", description="查询模式: current/history"),
@@ -155,55 +252,64 @@ async def list_collected_data(
db: AsyncSession = Depends(get_db),
):
"""查询采集的数据列表"""
normalized_country = normalize_country(country) if country else None
source_values = parse_multi_values(source)
data_type_values = parse_multi_values(data_type)
# Build WHERE clause
conditions = []
params = {}
if mode != "history":
conditions.append("COALESCE(is_current, TRUE) = TRUE")
if source_values:
conditions.append(build_in_condition("source", source_values, "source", params))
if data_type_values:
conditions.append(build_in_condition("data_type", data_type_values, "data_type", params))
if normalized_country:
conditions.append(f"{COUNTRY_SQL} = :country")
params["country"] = normalized_country
search_condition = build_search_condition(search, params)
if search_condition:
conditions.append(search_condition)
where_sql = " AND ".join(conditions) if conditions else "1=1"
search_rank_sql = build_search_rank_sql(search)
where_sql, params, include_excluded = build_where_clause(
source,
data_type,
country,
search,
mode=mode,
)
has_search = bool(search and search.strip())
# Calculate offset
offset = (page - 1) * page_size
source_name_map = await get_source_name_map(db)
# Query total count
count_query = text(f"SELECT COUNT(*) FROM collected_data WHERE {where_sql}")
count_result = await db.execute(count_query, params)
total = count_result.scalar()
if not country and not has_search:
facets = await _load_collected_facets(db, mode=mode, source_name_map=source_name_map)
source_set = set(parse_multi_values(source))
type_set = set(parse_multi_values(data_type))
total = sum(
item["count"]
for item in facets
if (include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES)
and (not source_set or item["source"] in source_set)
and (not type_set or item["data_type"] in type_set)
)
else:
count_query = text(f"SELECT COUNT(*) FROM collected_data WHERE {where_sql}")
count_result = await db.execute(count_query, params)
total = int(count_result.scalar() or 0)
# Query data
query = text(f"""
SELECT id, source, source_id, data_type, name, title, description,
metadata, collected_at, reference_date, is_valid,
{search_rank_sql} AS search_rank
FROM collected_data
WHERE {where_sql}
ORDER BY search_rank DESC, collected_at DESC
LIMIT :limit OFFSET :offset
""")
params["limit"] = page_size
params["offset"] = offset
if has_search:
search_rank_sql = build_search_rank_sql(search)
query = text(
f"""
SELECT id, source, source_id, data_type, name, title, description,
metadata, collected_at, reference_date, is_valid,
{search_rank_sql} AS search_rank
FROM collected_data
WHERE {where_sql}
ORDER BY search_rank DESC, collected_at DESC
LIMIT :limit OFFSET :offset
"""
)
else:
query = text(
f"""
SELECT id, source, source_id, data_type, name, title, description,
metadata, collected_at, reference_date, is_valid
FROM collected_data
WHERE {where_sql}
ORDER BY collected_at DESC
LIMIT :limit OFFSET :offset
"""
)
result = await db.execute(query, params)
rows = result.fetchall()
source_name_map = await get_source_name_map(db)
data = []
for row in rows:
@@ -217,6 +323,40 @@ async def list_collected_data(
}
def _aggregate_summary_from_facets(facets: list[dict], *, overall_total: int) -> dict:
by_source: dict[str, dict[str, int]] = {}
source_acc: dict[str, dict] = {}
type_acc: dict[str, int] = {}
total = 0
for item in facets:
src = str(item["source"])
src_name = str(item.get("source_name") or src)
dt = str(item["data_type"])
cnt = int(item["count"] or 0)
if cnt <= 0:
continue
by_source.setdefault(src_name, {})[dt] = by_source.get(src_name, {}).get(dt, 0) + cnt
if src not in source_acc:
source_acc[src] = {"source": src, "source_name": src_name, "count": 0}
source_acc[src]["count"] += cnt
type_acc[dt] = type_acc.get(dt, 0) + cnt
total += cnt
source_totals = sorted(source_acc.values(), key=lambda x: (-x["count"], x["source"]))
type_totals = [
{"data_type": dt, "count": cnt}
for dt, cnt in sorted(type_acc.items(), key=lambda item: (-item[1], item[0]))
]
return {
"total_records": total,
"overall_total_records": overall_total,
"by_source": by_source,
"source_totals": source_totals,
"type_totals": type_totals,
}
@router.get("/summary")
async def get_data_summary(
mode: str = Query("current", description="查询模式: current/history"),
@@ -228,89 +368,76 @@ async def get_data_summary(
db: AsyncSession = Depends(get_db),
):
"""获取数据汇总统计"""
where_sql, params = build_where_clause(source, data_type, country, search)
if mode != "history":
where_sql = f"({where_sql}) AND COALESCE(is_current, TRUE) = TRUE"
overall_where_sql = "COALESCE(is_current, TRUE) = TRUE" if mode != "history" else "1=1"
overall_total_result = await db.execute(
text(f"SELECT COUNT(*) FROM collected_data WHERE {overall_where_sql}")
cache_key = _summary_cache_key(
mode=mode,
source=source,
data_type=data_type,
country=country,
search=search,
)
overall_total = overall_total_result.scalar() or 0
cached_summary = cache.get(cache_key)
if isinstance(cached_summary, dict):
return cached_summary
# By source and data_type
result = await db.execute(
text(f"""
SELECT source, data_type, COUNT(*) as count
FROM collected_data
WHERE {where_sql}
GROUP BY source, data_type
ORDER BY source, data_type
"""),
params,
)
rows = result.fetchall()
source_name_map = await get_source_name_map(db)
by_source = {}
total = 0
for row in rows:
source = row[0]
data_type = row[1]
count = row[2]
source_key = source_name_map.get(source, source)
if source_key not in by_source:
by_source[source_key] = {}
by_source[source_key][data_type] = count
total += count
# Total by source
source_totals = await db.execute(
text(f"""
SELECT source, COUNT(*) as count
FROM collected_data
WHERE {where_sql}
GROUP BY source
ORDER BY count DESC
"""),
params,
unfiltered_facets = await _load_collected_facets(
db, mode=mode, source_name_map=source_name_map
)
source_rows = source_totals.fetchall()
type_totals = await db.execute(
text(f"""
SELECT data_type, COUNT(*) as count
FROM collected_data
WHERE {where_sql}
GROUP BY data_type
ORDER BY count DESC, data_type
"""),
params,
source_values = parse_multi_values(source)
data_type_values = parse_multi_values(data_type)
include_excluded = _includes_default_excluded(source_values, data_type_values)
overall_total = sum(
int(item["count"] or 0)
for item in unfiltered_facets
if include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES
)
type_rows = type_totals.fetchall()
return {
"total_records": total,
"overall_total_records": overall_total,
"by_source": by_source,
"source_totals": [
normalized_country = normalize_country(country) if country else None
has_search = bool(search and search.strip())
if not normalized_country and not has_search:
source_set = set(source_values)
type_set = set(data_type_values)
filtered_facets = [
item
for item in unfiltered_facets
if (include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES)
and (not source_set or item["source"] in source_set)
and (not type_set or item["data_type"] in type_set)
]
else:
where_sql, params, _ = build_where_clause(
source,
data_type,
country,
search,
mode=mode,
)
result = await db.execute(
text(
f"""
SELECT source, data_type, COUNT(*) AS count
FROM collected_data
WHERE {where_sql}
GROUP BY source, data_type
ORDER BY source, data_type
"""
),
params,
)
filtered_facets = [
{
"source": row[0],
"source_name": source_name_map.get(row[0], row[0]),
"count": row[1],
"data_type": row[1],
"count": int(row[2] or 0),
}
for row in source_rows
],
"type_totals": [
{
"data_type": row[0],
"count": row[1],
}
for row in type_rows
],
}
for row in result.fetchall()
]
payload = _aggregate_summary_from_facets(filtered_facets, overall_total=overall_total)
cache.set(cache_key, payload, expire_seconds=COLLECTED_SUMMARY_TTL_SECONDS)
return payload
@router.get("/sources")
@@ -320,21 +447,17 @@ async def get_data_sources(
db: AsyncSession = Depends(get_db),
):
"""获取所有数据源列表"""
result = await db.execute(
text("""
SELECT DISTINCT source FROM collected_data
""" + ("WHERE COALESCE(is_current, TRUE) = TRUE " if mode != "history" else "") + """
ORDER BY source
""")
)
rows = result.fetchall()
source_name_map = await get_source_name_map(db)
facets = await _load_collected_facets(db, mode=mode)
seen: dict[str, str] = {}
for item in facets:
src = str(item["source"])
if src not in seen:
seen[src] = str(item.get("source_name") or src)
return {
"sources": [
{"source": row[0], "source_name": source_name_map.get(row[0], row[0])}
for row in rows
{"source": src, "source_name": seen[src]}
for src in sorted(seen.keys())
],
}
@@ -346,18 +469,10 @@ async def get_data_types(
db: AsyncSession = Depends(get_db),
):
"""获取所有数据类型列表"""
result = await db.execute(
text("""
SELECT DISTINCT data_type FROM collected_data
""" + ("WHERE COALESCE(is_current, TRUE) = TRUE " if mode != "history" else "") + """
ORDER BY data_type
""")
)
rows = result.fetchall()
facets = await _load_collected_facets(db, mode=mode)
types = sorted({str(item["data_type"]) for item in facets if item.get("data_type")})
return {
"data_types": [row[0] for row in rows],
"data_types": types,
}
@@ -403,20 +518,31 @@ async def get_collected_data(
def build_where_clause(
source: Optional[str], data_type: Optional[str], country: Optional[str], search: Optional[str]
):
"""Build WHERE clause and params for queries"""
source: Optional[str],
data_type: Optional[str],
country: Optional[str],
search: Optional[str],
*,
mode: str = "current",
) -> tuple[str, dict, bool]:
"""Build WHERE clause and params for queries."""
conditions = []
params = {}
params: dict = {}
if mode != "history":
conditions.append("is_current IS TRUE")
source_values = parse_multi_values(source)
data_type_values = parse_multi_values(data_type)
include_excluded = _includes_default_excluded(source_values, data_type_values)
if source_values:
conditions.append(build_in_condition("source", source_values, "source", params))
if data_type_values:
conditions.append(build_in_condition("data_type", data_type_values, "data_type", params))
normalized_country = normalize_country(country) if country else None
if not include_excluded and DEFAULT_EXCLUDED_DATA_TYPES:
conditions.append(build_not_in_condition("data_type", DEFAULT_EXCLUDED_DATA_TYPES, "excl_dt", params))
normalized_country = normalize_country(country) if country else None
if normalized_country:
conditions.append(f"{COUNTRY_SQL} = :country")
params["country"] = normalized_country
@@ -425,7 +551,7 @@ def build_where_clause(
conditions.append(search_condition)
where_sql = " AND ".join(conditions) if conditions else "1=1"
return where_sql, params
return where_sql, params, include_excluded
@router.get("/export/json")
@@ -441,9 +567,7 @@ async def export_json(
):
"""导出数据为 JSON 格式"""
where_sql, params = build_where_clause(source, data_type, country, search)
if mode != "history":
where_sql = f"({where_sql}) AND COALESCE(is_current, TRUE) = TRUE"
where_sql, params, _ = build_where_clause(source, data_type, country, search, mode=mode)
params["limit"] = limit
query = text(f"""
@@ -486,9 +610,7 @@ async def export_csv(
):
"""导出数据为 CSV 格式"""
where_sql, params = build_where_clause(source, data_type, country, search)
if mode != "history":
where_sql = f"({where_sql}) AND COALESCE(is_current, TRUE) = TRUE"
where_sql, params, _ = build_where_clause(source, data_type, country, search, mode=mode)
params["limit"] = limit
query = text(f"""