174 lines
8.4 KiB
Python
174 lines
8.4 KiB
Python
"""Whole-graph export/import so the platform stays as portable as the original page."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import sqlite3
|
||
from typing import Annotated
|
||
|
||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||
|
||
from ..db import all_, get_db, json_dump, log_audit, set_setting, transaction, utcnow
|
||
from ..deps import actor_from, ensure_editable
|
||
from ..schemas import BackupIn
|
||
|
||
router = APIRouter(prefix="/api", tags=["backup"])
|
||
|
||
DB = Annotated[sqlite3.Connection, Depends(get_db)]
|
||
|
||
TABLES = ("layers", "systems", "flow_types", "data_flows")
|
||
|
||
|
||
@router.get("/backup")
|
||
def export_backup(db: DB) -> dict:
|
||
payload: dict = {"schema_version": 1, "exported_at": utcnow()}
|
||
for table in TABLES:
|
||
rows = all_(db, f"SELECT * FROM {table}") # noqa: S608 - table names come from a fixed tuple
|
||
if table == "data_flows":
|
||
for row in rows:
|
||
row["peak_hours"] = _loads(row.get("peak_hours"))
|
||
payload[table] = rows
|
||
payload["settings"] = {
|
||
row["key"]: _maybe_json(row["value"]) for row in all_(db, "SELECT key, value FROM settings")
|
||
if row["key"] != "last_live_tick"
|
||
}
|
||
return payload
|
||
|
||
|
||
@router.post("/backup")
|
||
def import_backup(payload: BackupIn, db: DB, request: Request) -> dict:
|
||
ensure_editable(db, "导入配置")
|
||
if not any(getattr(payload, table) for table in TABLES):
|
||
raise HTTPException(400, "备份文件中没有可导入的数据")
|
||
errors: list[str] = []
|
||
imported = {table: 0 for table in TABLES}
|
||
actor = actor_from(request)
|
||
|
||
with transaction(db):
|
||
if payload.mode == "replace":
|
||
# Metrics depend on flow ids, so a full replace resets history too.
|
||
for table in reversed(TABLES):
|
||
db.execute(f"DELETE FROM {table}")
|
||
db.execute("DELETE FROM settings")
|
||
|
||
for layer in payload.layers:
|
||
if not _has(layer, "id", "name"):
|
||
errors.append("层级缺少 id 或 name,已跳过")
|
||
continue
|
||
db.execute(
|
||
"""INSERT INTO layers (id, name, short_name, color, description, sort_order)
|
||
VALUES (?,?,?,?,?,?)
|
||
ON CONFLICT(id) DO UPDATE SET name=excluded.name, short_name=excluded.short_name,
|
||
color=excluded.color, description=excluded.description, sort_order=excluded.sort_order""",
|
||
(layer["id"], layer["name"], layer.get("short_name", ""), layer.get("color", "#0d9488"),
|
||
layer.get("description", ""), int(layer.get("sort_order", 0))),
|
||
)
|
||
imported["layers"] += 1
|
||
|
||
for system in payload.systems:
|
||
if not _has(system, "key", "name"):
|
||
errors.append("系统缺少 key 或 name,已跳过")
|
||
continue
|
||
now = utcnow()
|
||
db.execute(
|
||
"""INSERT INTO systems (key, name, layer_id, dept, status, tech, url, domain, owner,
|
||
impl_time, entry_enabled, description, tier, flow_x, flow_y,
|
||
sort_order, created_at, updated_at)
|
||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||
ON CONFLICT(key) DO UPDATE SET name=excluded.name, layer_id=excluded.layer_id,
|
||
dept=excluded.dept, status=excluded.status, tech=excluded.tech, url=excluded.url,
|
||
domain=excluded.domain, owner=excluded.owner, impl_time=excluded.impl_time,
|
||
entry_enabled=excluded.entry_enabled, description=excluded.description,
|
||
tier=excluded.tier, flow_x=excluded.flow_x, flow_y=excluded.flow_y, sort_order=excluded.sort_order, updated_at=excluded.updated_at""",
|
||
(system["key"], system["name"], system.get("layer_id"), system.get("dept", ""),
|
||
system.get("status", "unknown"), system.get("tech", ""), system.get("url", ""),
|
||
system.get("domain", ""), system.get("owner", ""), system.get("impl_time", ""),
|
||
1 if system.get("entry_enabled", 1) else 0, system.get("description", ""),
|
||
int(system.get("tier", 2)), system.get("flow_x"), system.get("flow_y"),
|
||
int(system.get("sort_order", 0)), now, now),
|
||
)
|
||
imported["systems"] += 1
|
||
|
||
for flow_type in payload.flow_types:
|
||
if not _has(flow_type, "id", "name"):
|
||
errors.append("数据类型缺少 id 或 name,已跳过")
|
||
continue
|
||
db.execute(
|
||
"""INSERT INTO flow_types (id, name, color, line_style, default_interval, description, sort_order)
|
||
VALUES (?,?,?,?,?,?,?)
|
||
ON CONFLICT(id) DO UPDATE SET name=excluded.name, color=excluded.color,
|
||
line_style=excluded.line_style, default_interval=excluded.default_interval,
|
||
description=excluded.description, sort_order=excluded.sort_order""",
|
||
(flow_type["id"], flow_type["name"], flow_type.get("color", "#64748b"),
|
||
flow_type.get("line_style", "dashed"), int(flow_type.get("default_interval", 3600)),
|
||
flow_type.get("description", ""), int(flow_type.get("sort_order", 0))),
|
||
)
|
||
imported["flow_types"] += 1
|
||
|
||
known_systems = {row["key"] for row in all_(db, "SELECT key FROM systems")}
|
||
known_types = {row["id"] for row in all_(db, "SELECT id FROM flow_types")}
|
||
now = utcnow()
|
||
for flow in payload.data_flows:
|
||
source, target = flow.get("source_key"), flow.get("target_key")
|
||
type_id = flow.get("flow_type_id")
|
||
if source not in known_systems or target not in known_systems:
|
||
errors.append(f"数据流 {source} → {target} 的端点系统不存在,已跳过")
|
||
continue
|
||
if type_id not in known_types:
|
||
errors.append(f"数据流 {flow.get('label', '')} 的数据类型 {type_id} 不存在,已跳过")
|
||
continue
|
||
columns = ["source_key", "target_key", "flow_type_id", "label", "payload", "direction",
|
||
"interval_sec", "records_per_batch", "avg_payload_kb", "latency_ms",
|
||
"reliability", "peak_hours", "enabled", "note", "sort_order", "created_at", "updated_at"]
|
||
values: list = [source, target, type_id, flow.get("label", ""), flow.get("payload", ""),
|
||
flow.get("direction", "forward"), int(flow.get("interval_sec", 3600)),
|
||
int(flow.get("records_per_batch", 1)), float(flow.get("avg_payload_kb", 1.0)),
|
||
int(flow.get("latency_ms", 120)), flow.get("reliability", "async"),
|
||
json_dump(flow.get("peak_hours") or []), 1 if flow.get("enabled", True) else 0,
|
||
flow.get("note", ""), int(flow.get("sort_order", 0)), now, now]
|
||
# Keep the original id when the backup carries one, so re-importing updates in place
|
||
# and existing metrics stay attached to the same flow.
|
||
flow_id = flow.get("id")
|
||
if isinstance(flow_id, int):
|
||
columns.insert(0, "id")
|
||
values.insert(0, flow_id)
|
||
placeholders = ", ".join("?" for _ in values)
|
||
column_list = ", ".join(columns)
|
||
upsert = ", ".join(f"{column}=excluded.{column}" for column in columns if column != "id")
|
||
sql = (
|
||
f"INSERT INTO data_flows ({column_list}) VALUES ({placeholders}) "
|
||
f"ON CONFLICT(id) DO UPDATE SET {upsert}"
|
||
)
|
||
db.execute(sql, values)
|
||
imported["data_flows"] += 1
|
||
|
||
for key, value in (payload.settings or {}).items():
|
||
set_setting(db, key, value)
|
||
|
||
log_audit(db, actor=actor, entity="backup", action="import",
|
||
summary=f"{payload.mode} 导入:{imported['systems']} 系统 / {imported['data_flows']} 数据流")
|
||
|
||
return {"imported": imported, "errors": errors, "mode": payload.mode}
|
||
|
||
|
||
def _has(row: dict, *keys: str) -> bool:
|
||
return all(row.get(key) not in (None, "") for key in keys)
|
||
|
||
|
||
def _loads(raw) -> list[int]:
|
||
import json
|
||
|
||
try:
|
||
value = json.loads(raw or "[]")
|
||
except (TypeError, json.JSONDecodeError):
|
||
return []
|
||
return [int(v) for v in value] if isinstance(value, list) else []
|
||
|
||
|
||
def _maybe_json(raw: str):
|
||
import json
|
||
|
||
try:
|
||
return json.loads(raw)
|
||
except json.JSONDecodeError:
|
||
return raw
|