feat: 用安装页和编排完成部署,并整理登录页

This commit is contained in:
2026-10-30 09:49:20 +08:00
parent 7ed299bbf6
commit 3fa4f83180
30 changed files with 635 additions and 121 deletions
+9
View File
@@ -0,0 +1,9 @@
.git
.venv
**/__pycache__
**/.pytest_cache
web/node_modules
web/dist
backend/data
backend/.venv
.env
+3
View File
@@ -0,0 +1,3 @@
POSTGRES_USER=postgres
POSTGRES_PASSWORD=
POSTGRES_DB=decom
+20
View File
@@ -0,0 +1,20 @@
ARG NODE_IMAGE=node:22-bookworm-slim
ARG PYTHON_IMAGE=python:3.13-slim
FROM ${NODE_IMAGE} AS web
WORKDIR /src
COPY web/package.json web/package-lock.json ./
RUN npm ci
COPY web/ .
RUN npm run build
FROM ${PYTHON_IMAGE}
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
COPY backend/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY backend/ .
COPY --from=web /src/dist ./web/dist
EXPOSE 8000
CMD ["python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
+1 -2
View File
@@ -12,7 +12,7 @@ Vue 3、TypeScript、Naive UI。Node.js 只用于安装依赖、本地开发和
## Users ## Users
内网里使用网页的人,人数在 100 以内。管理员登录后看到管理导航,其他用户看到用户导航。 内网用户。管理员登录后看到管理导航,其他用户看到用户导航。
## Product Purpose ## Product Purpose
@@ -34,7 +34,6 @@ Vue 3、TypeScript、Naive UI。Node.js 只用于安装依赖、本地开发和
- 平台登录使用 JWT。账号池另行保存大数据平台凭证。退出只清除平台登录,不删除账号池中的账号。退出后再次登录需要重新发送手机验证码,成功后账号池改用新凭证。 - 平台登录使用 JWT。账号池另行保存大数据平台凭证。退出只清除平台登录,不删除账号池中的账号。退出后再次登录需要重新发送手机验证码,成功后账号池改用新凭证。
- 账号池凭证默认每 5 分钟刷新一次。采集从账号池选择凭证仍然有效的账号。 - 账号池凭证默认每 5 分钟刷新一次。采集从账号池选择凭证仍然有效的账号。
- 小区信息表名为 CellData。采集数据保留多个时间点,生成结果时再取用。 - 小区信息表名为 CellData。采集数据保留多个时间点,生成结果时再取用。
- 尚未实现的功能以后补进对应目录,不在这次把未定功能写成已有能力。
## Brand Commitments ## Brand Commitments
+21 -3
View File
@@ -2,12 +2,30 @@
拆站评估。数据先采集入库,用户提交任务后从库中导出 xlsx、xls 或 csv。 拆站评估。数据先采集入库,用户提交任务后从库中导出 xlsx、xls 或 csv。
首次打开网页进入安装页,填写数据库连接和管理员账号。这些配置保存在数据库中。
## 开发
数据库:
```text
docker compose -f compose.dev.yaml up -d
```
启动前在环境中设置 `POSTGRES_PASSWORD`。接口和排队进程在本机运行:
```text ```text
cd backend cd backend
.venv\Scripts\python -m uvicorn app.main:app --host 127.0.0.1 --port 8000 .venv\Scripts\python -m uvicorn app.main:app --host 127.0.0.1 --port 8000
.venv\Scripts\python -m worker.main .venv\Scripts\python -m worker.main
cd ..\web
npm run dev
``` ```
PostgreSQL 使用 `DECOM_DATABASE_URL=postgresql+psycopg://用户:密码@主机:5432/decom`。未设置时使用本机 SQLite。首次启动用 `DECOM_ADMIN_USERNAME` 和 `DECOM_ADMIN_PASSWORD` 创建管理员。生产环境同时运行接口和 `worker.main`,并设置 `DECOM_INLINE_WORKER=0`。 网页在构建后由接口直接提供。开发时也可以在 `web` 目录运行页面开发服务器。
## 生产
```text
docker compose up -d --build
```
启动前设置 `POSTGRES_PASSWORD`。首次打开网页完成安装,数据库主机使用 `postgres`,并保持独立排队进程开启。
+2 -2
View File
@@ -9,9 +9,9 @@ from app.config import database_url
from app.models import Base from app.models import Base
config = context.config config = context.config
if config.config_file_name is not None: if config.config_file_name is not None and config.attributes.get("configure_logger", True):
fileConfig(config.config_file_name) fileConfig(config.config_file_name)
config.set_main_option("sqlalchemy.url", database_url()) config.set_main_option("sqlalchemy.url", database_url().replace("%", "%%"))
target_metadata = Base.metadata target_metadata = Base.metadata
@@ -0,0 +1,29 @@
"""添加安装后保存在数据库里的连接和管理配置。"""
from alembic import op
import sqlalchemy as sa
revision = "0002_install_settings"
down_revision = "0001_initial"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("app_setting", sa.Column("db_host", sa.String(255), nullable=False, server_default=""))
op.add_column("app_setting", sa.Column("db_port", sa.Integer(), nullable=False, server_default="5432"))
op.add_column("app_setting", sa.Column("db_name", sa.String(128), nullable=False, server_default=""))
op.add_column("app_setting", sa.Column("db_user", sa.String(128), nullable=False, server_default=""))
op.add_column("app_setting", sa.Column("db_password", sa.Text(), nullable=False, server_default=""))
op.add_column("app_setting", sa.Column("jwt_secret", sa.String(128), nullable=False, server_default=""))
op.add_column("app_setting", sa.Column("inline_worker", sa.Boolean(), nullable=False, server_default=sa.false()))
def downgrade() -> None:
op.drop_column("app_setting", "inline_worker")
op.drop_column("app_setting", "jwt_secret")
op.drop_column("app_setting", "db_password")
op.drop_column("app_setting", "db_user")
op.drop_column("app_setting", "db_name")
op.drop_column("app_setting", "db_port")
op.drop_column("app_setting", "db_host")
+26 -2
View File
@@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
import base64 import base64
import os
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import Response from fastapi.responses import Response
@@ -8,7 +9,8 @@ from sqlalchemy import select
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.api.deps import Actor, current_actor, require_admin from app.api.deps import Actor, current_actor, require_admin
from app.config import RESULT_DIR from app.config import installed, result_dir
from app.install import InstallError, perform_install
from app.db import get_session, session_scope from app.db import get_session, session_scope
from app.models import AppSetting, CollectionSource, ExportTask, NqiAccount, User, utcnow from app.models import AppSetting, CollectionSource, ExportTask, NqiAccount, User, utcnow
from app.nqi.client import NqiAuthError, NqiClient, NqiError from app.nqi.client import NqiAuthError, NqiClient, NqiError
@@ -19,6 +21,28 @@ from app.tasks.runner import check_period, check_refresh, enqueue_export
router = APIRouter(prefix="/api") router = APIRouter(prefix="/api")
@router.get("/install/status")
def install_status() -> dict:
return {
"installed": installed(),
"defaults": {
"host": os.environ.get("DECOM_DB_HOST", "127.0.0.1"),
"port": int(os.environ.get("DECOM_DB_PORT", "5432")),
"database": os.environ.get("DECOM_DB_NAME", "decom"),
"username": os.environ.get("DECOM_DB_USER", "postgres"),
},
}
@router.post("/install")
def install(body: dict) -> dict:
try:
perform_install(body)
except InstallError as exc:
raise _bad(str(exc)) from exc
return {"ok": True}
def _bad(message: str, status: int = 400) -> HTTPException: def _bad(message: str, status: int = 400) -> HTTPException:
return HTTPException(status_code=status, detail=message) return HTTPException(status_code=status, detail=message)
@@ -246,7 +270,7 @@ def download_task(task_id: int, actor: Actor = Depends(current_actor), session:
task = session.get(ExportTask, task_id) task = session.get(ExportTask, task_id)
if task is None or task.owner_kind != actor.kind or task.owner_id != actor.id or task.status != "done": if task is None or task.owner_kind != actor.kind or task.owner_id != actor.id or task.status != "done":
raise _bad("结果还不能下载", 404) raise _bad("结果还不能下载", 404)
path = RESULT_DIR / task.result_name path = result_dir() / task.result_name
if not path.is_file(): if not path.is_file():
raise _bad("结果还不能下载", 404) raise _bad("结果还不能下载", 404)
return Response(content=path.read_bytes(), media_type="application/octet-stream", headers={"Content-Disposition": f'attachment; filename="{task.result_name}"'}) return Response(content=path.read_bytes(), media_type="application/octet-stream", headers={"Content-Disposition": f'attachment; filename="{task.result_name}"'})
+11 -22
View File
@@ -1,37 +1,26 @@
from __future__ import annotations from __future__ import annotations
import logging import logging
from pathlib import Path from pathlib import Path
from alembic import command from alembic import command
from alembic.config import Config from alembic.config import Config
from sqlalchemy import select
from app.config import BACKEND_ROOT, admin_password, admin_username from app.config import BACKEND_ROOT, data_dir, installed
from app.db import session_scope
from app.models import AppSetting, User
from app.security import hash_password
logger = logging.getLogger("decom") logger = logging.getLogger("decom")
def init_db() -> None: def migrate() -> None:
from app.config import DATA_DIR data_dir().mkdir(parents=True, exist_ok=True)
DATA_DIR.mkdir(parents=True, exist_ok=True)
config = Config(str(Path(BACKEND_ROOT) / "alembic.ini")) config = Config(str(Path(BACKEND_ROOT) / "alembic.ini"))
config.set_main_option("script_location", str(Path(BACKEND_ROOT) / "alembic")) config.set_main_option("script_location", str(Path(BACKEND_ROOT) / "alembic"))
config.attributes["configure_logger"] = False
command.upgrade(config, "head") command.upgrade(config, "head")
with session_scope() as session:
if session.get(AppSetting, 1) is None:
session.add(AppSetting(id=1, login_mode="local", credential_refresh_seconds=300)) def init_db() -> None:
if admin_username() and admin_password() and session.scalar(select(User).where(User.role == "admin")) is None: if not installed():
session.add( logger.info("尚未安装,等待安装页")
User( return
username=admin_username(), migrate()
password_hash=hash_password(admin_password()),
role="admin",
)
)
logger.info("已创建管理员 %s", admin_username())
+39 -26
View File
@@ -1,21 +1,41 @@
"""运行配置。秘密只从环境变量或 data 目录读取,不写进代码。""" """运行配置。连接信息在安装后写入 data/install.json,其余配置保存在数据库。"""
from __future__ import annotations from __future__ import annotations
import json
import os import os
import secrets
from pathlib import Path from pathlib import Path
BACKEND_ROOT = Path(__file__).resolve().parents[1] BACKEND_ROOT = Path(__file__).resolve().parents[1]
DATA_DIR = BACKEND_ROOT / "data"
RESULT_DIR = DATA_DIR / "results"
def data_dir() -> Path:
override = os.environ.get("DECOM_DATA_DIR", "").strip()
if override:
return Path(override)
return BACKEND_ROOT / "data"
def result_dir() -> Path:
return data_dir() / "results"
def install_file() -> Path:
return data_dir() / "install.json"
def installed() -> bool:
return install_file().is_file()
def database_url() -> str: def database_url() -> str:
return os.environ.get("DECOM_DATABASE_URL", f"sqlite+pysqlite:///{(DATA_DIR / 'decom.db').as_posix()}") payload = json.loads(install_file().read_text(encoding="utf-8"))
return str(payload["databaseUrl"])
def postgres_conninfo() -> str | None: def postgres_conninfo() -> str | None:
if not installed():
return None
url = database_url() url = database_url()
if url.startswith("postgresql+psycopg://"): if url.startswith("postgresql+psycopg://"):
return "postgresql://" + url.removeprefix("postgresql+psycopg://") return "postgresql://" + url.removeprefix("postgresql+psycopg://")
@@ -25,25 +45,18 @@ def postgres_conninfo() -> str | None:
def inline_worker() -> bool: def inline_worker() -> bool:
return os.environ.get("DECOM_INLINE_WORKER", "1") == "1" forced = os.environ.get("DECOM_INLINE_WORKER", "").strip()
if forced == "1":
return True
if forced == "0":
return False
if not installed():
return False
from app.db import session_scope
from app.models import AppSetting
with session_scope() as session:
def jwt_secret() -> str: setting = session.get(AppSetting, 1)
configured = os.environ.get("DECOM_JWT_SECRET", "").strip() if setting is None:
if configured: return False
return configured return bool(setting.inline_worker)
path = DATA_DIR / "jwt.secret"
if path.is_file():
return path.read_text(encoding="utf-8").strip()
path.parent.mkdir(parents=True, exist_ok=True)
value = secrets.token_hex(32)
path.write_text(value, encoding="utf-8")
return value
def admin_username() -> str:
return os.environ.get("DECOM_ADMIN_USERNAME", "").strip()
def admin_password() -> str:
return os.environ.get("DECOM_ADMIN_PASSWORD", "")
+111
View File
@@ -0,0 +1,111 @@
"""首次安装:连接数据库、建表、创建管理员,并把配置写入数据库。"""
from __future__ import annotations
import json
import os
import re
import secrets
from sqlalchemy import create_engine, text
from sqlalchemy.engine import URL
from app.config import data_dir, install_file, installed
from app.db import reset_engine, session_scope
from app.models import AppSetting, User
from app.security import hash_password
_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}$")
class InstallError(Exception):
pass
def _identifier(value: str, label: str) -> str:
if not _IDENT.match(value):
raise InstallError(f"{label}只能使用字母、数字和下划线")
return value
def build_postgres_url(host: str, port: int, database: str, username: str, password: str) -> str:
return URL.create(
"postgresql+psycopg",
username=username,
password=password,
host=host,
port=port,
database=database,
).render_as_string(hide_password=False)
def ensure_database(host: str, port: int, database: str, username: str, password: str) -> None:
maintenance = build_postgres_url(host, port, "postgres", username, password)
try:
checker = create_engine(maintenance, isolation_level="AUTOCOMMIT")
with checker.connect() as connection:
exists = connection.execute(
text("SELECT 1 FROM pg_database WHERE datname = :name"),
{"name": database},
).scalar()
if not exists:
connection.execute(text(f'CREATE DATABASE "{database}"'))
checker.dispose()
except Exception as exc:
raise InstallError("无法连接数据库,请检查主机、端口、账号和密码") from exc
def perform_install(body: dict) -> None:
if installed():
raise InstallError("已经安装")
admin_username = str(body.get("adminUsername") or "").strip()
admin_password = str(body.get("adminPassword") or "")
if not admin_username or not admin_password:
raise InstallError("请填写管理员账号和密码")
separate_worker = bool(body.get("separateWorker"))
use_sqlite = bool(body.get("sqlite"))
data_dir().mkdir(parents=True, exist_ok=True)
if use_sqlite:
if os.environ.get("DECOM_ALLOW_SQLITE") != "1":
raise InstallError("请使用 PostgreSQL")
url = f"sqlite+pysqlite:///{(data_dir() / 'decom.db').as_posix()}"
host, port, database, username, password = "", 0, "", "", ""
else:
host = str(body.get("host") or "").strip()
database = _identifier(str(body.get("database") or "").strip(), "数据库名")
username = _identifier(str(body.get("username") or "").strip(), "数据库用户")
password = str(body.get("password") or "")
try:
port = int(body.get("port") or 0)
except (TypeError, ValueError) as exc:
raise InstallError("端口不正确") from exc
if not host or port < 1 or port > 65535 or not password:
raise InstallError("请填写完整的数据库连接")
ensure_database(host, port, database, username, password)
url = build_postgres_url(host, port, database, username, password)
install_file().write_text(json.dumps({"databaseUrl": url}, ensure_ascii=False), encoding="utf-8")
reset_engine()
try:
from app.bootstrap import migrate
migrate()
with session_scope() as session:
session.add(
AppSetting(
id=1,
login_mode="local",
credential_refresh_seconds=300,
db_host=host,
db_port=port,
db_name=database,
db_user=username,
db_password=password,
jwt_secret=secrets.token_hex(32),
inline_worker=not separate_worker,
)
)
session.add(User(username=admin_username, password_hash=hash_password(admin_password), role="admin"))
except Exception:
install_file().unlink(missing_ok=True)
reset_engine()
raise
+20 -2
View File
@@ -6,15 +6,26 @@ from pathlib import Path
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.responses import FileResponse from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from app.api.http import router from app.api.http import router
from app.bootstrap import init_db from app.bootstrap import init_db
from app.config import installed
from app.runtime import start_background from app.runtime import start_background
logger = logging.getLogger("decom") logger = logging.getLogger("decom")
WEB_DIST = Path(__file__).resolve().parents[2] / "web" / "dist" WEB_DIST = next(
(
candidate
for candidate in (
Path(__file__).resolve().parents[2] / "web" / "dist",
Path(__file__).resolve().parents[1] / "web" / "dist",
)
if (candidate / "index.html").is_file()
),
Path(__file__).resolve().parents[2] / "web" / "dist",
)
@asynccontextmanager @asynccontextmanager
@@ -29,6 +40,13 @@ def create_app() -> FastAPI:
application = FastAPI(title="DecomEval", lifespan=lifespan) application = FastAPI(title="DecomEval", lifespan=lifespan)
application.include_router(router) application.include_router(router)
@application.middleware("http")
async def require_install(request, call_next):
path = request.url.path
if path.startswith("/api/") and not path.startswith("/api/install") and not installed():
return JSONResponse({"detail": "尚未安装"}, status_code=503)
return await call_next(request)
if (WEB_DIST / "index.html").is_file(): if (WEB_DIST / "index.html").is_file():
application.mount("/assets", StaticFiles(directory=WEB_DIST / "assets"), name="assets") application.mount("/assets", StaticFiles(directory=WEB_DIST / "assets"), name="assets")
+7
View File
@@ -20,6 +20,13 @@ class AppSetting(Base):
id: Mapped[int] = mapped_column(Integer, primary_key=True) id: Mapped[int] = mapped_column(Integer, primary_key=True)
login_mode: Mapped[str] = mapped_column(String(16), default="local") login_mode: Mapped[str] = mapped_column(String(16), default="local")
credential_refresh_seconds: Mapped[int] = mapped_column(Integer, default=300) credential_refresh_seconds: Mapped[int] = mapped_column(Integer, default=300)
db_host: Mapped[str] = mapped_column(String(255), default="")
db_port: Mapped[int] = mapped_column(Integer, default=5432)
db_name: Mapped[str] = mapped_column(String(128), default="")
db_user: Mapped[str] = mapped_column(String(128), default="")
db_password: Mapped[str] = mapped_column(Text, default="")
jwt_secret: Mapped[str] = mapped_column(String(128), default="")
inline_worker: Mapped[bool] = mapped_column(Boolean, default=False)
class User(Base): class User(Base):
+24 -8
View File
@@ -7,30 +7,43 @@ import logging
import threading import threading
import time import time
from sqlalchemy import select from app.config import installed
from app.db import session_scope from app.db import session_scope
from app.models import AppSetting
from app.tasks.runner import refresh_accounts, scan_sources from app.tasks.runner import refresh_accounts, scan_sources
logger = logging.getLogger("decom") logger = logging.getLogger("decom")
_started = False _started = False
def start_background() -> None: def start_background(owner: str = "api") -> None:
global _started global _started
if _started: if _started:
return return
_started = True _started = True
threading.Thread(target=_refresh_loop, name="decom-refresh", daemon=True).start() threading.Thread(target=_refresh_loop, args=(owner,), name="decom-refresh", daemon=True).start()
threading.Thread(target=_collect_loop, name="decom-collect", daemon=True).start() threading.Thread(target=_collect_loop, args=(owner,), name="decom-collect", daemon=True).start()
def _refresh_loop() -> None: def _owns_schedule(owner: str) -> bool:
from app.config import inline_worker
try:
inline = inline_worker()
except Exception:
return False
return inline if owner == "api" else not inline
def _refresh_loop(owner: str) -> None:
while True: while True:
if not installed() or not _owns_schedule(owner):
time.sleep(2)
continue
seconds = 300 seconds = 300
try: try:
with session_scope() as session: with session_scope() as session:
from app.models import AppSetting
setting = session.get(AppSetting, 1) setting = session.get(AppSetting, 1)
if setting is not None: if setting is not None:
seconds = setting.credential_refresh_seconds seconds = setting.credential_refresh_seconds
@@ -40,8 +53,11 @@ def _refresh_loop() -> None:
time.sleep(max(60, seconds)) time.sleep(max(60, seconds))
def _collect_loop() -> None: def _collect_loop(owner: str) -> None:
while True: while True:
if not installed() or not _owns_schedule(owner):
time.sleep(2)
continue
try: try:
scan_sources() scan_sources()
except Exception as exc: except Exception as exc:
+14 -1
View File
@@ -8,7 +8,7 @@ import os
import time import time
from typing import Any from typing import Any
from app.config import jwt_secret from app.config import installed
ITERATIONS = 200_000 ITERATIONS = 200_000
TOKEN_TTL = 12 * 60 * 60 TOKEN_TTL = 12 * 60 * 60
@@ -36,6 +36,19 @@ def _decode(raw: str) -> dict[str, Any]:
return json.loads(base64.urlsafe_b64decode(padded.encode("ascii"))) return json.loads(base64.urlsafe_b64decode(padded.encode("ascii")))
def jwt_secret() -> str:
if not installed():
raise RuntimeError("尚未安装")
from app.db import session_scope
from app.models import AppSetting
with session_scope() as session:
setting = session.get(AppSetting, 1)
if setting is None or not setting.jwt_secret:
raise RuntimeError("尚未安装")
return setting.jwt_secret
def issue_token(payload: dict[str, Any]) -> str: def issue_token(payload: dict[str, Any]) -> str:
body = {**payload, "exp": int(time.time()) + TOKEN_TTL} body = {**payload, "exp": int(time.time()) + TOKEN_TTL}
raw = _encode(body) raw = _encode(body)
+6
View File
@@ -27,6 +27,12 @@ def defer(name: str, **kwargs) -> None:
def serve() -> None: def serve() -> None:
import logging
logger = logging.getLogger("decom")
with queue.open(): with queue.open():
try:
queue.schema_manager.apply_schema() queue.schema_manager.apply_schema()
except Exception as exc:
logger.info("队列结构已存在: %s", exc)
queue.run_worker(queues=["decom"], concurrency=4) queue.run_worker(queues=["decom"], concurrency=4)
+3 -3
View File
@@ -10,7 +10,7 @@ from sqlalchemy import select
from app.collect.io import parse_upload, write_table from app.collect.io import parse_upload, write_table
from app.collect.remote import fetch_ftp, fetch_nqi from app.collect.remote import fetch_ftp, fetch_nqi
from app.config import RESULT_DIR, inline_worker, postgres_conninfo from app.config import inline_worker, postgres_conninfo, result_dir
from app.db import session_scope from app.db import session_scope
from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcnow from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcnow
from app.nqi.client import NqiAuthError, NqiClient, NqiError from app.nqi.client import NqiAuthError, NqiClient, NqiError
@@ -99,8 +99,8 @@ def execute_export(task_id: int) -> None:
with session_scope() as session: with session_scope() as session:
rows = query_cells(session, params) rows = query_cells(session, params)
name, content = write_table(file_format, rows) name, content = write_table(file_format, rows)
RESULT_DIR.mkdir(parents=True, exist_ok=True) result_dir().mkdir(parents=True, exist_ok=True)
path = RESULT_DIR / f"{task_id}-{name}" path = result_dir() / f"{task_id}-{name}"
path.write_bytes(content) path.write_bytes(content)
with session_scope() as session: with session_scope() as session:
task = session.get(ExportTask, task_id) task = session.get(ExportTask, task_id)
+13 -9
View File
@@ -1,17 +1,17 @@
from __future__ import annotations from __future__ import annotations
import os import os
import shutil
import time import time
from pathlib import Path from pathlib import Path
import pytest import pytest
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
os.environ["DECOM_DATABASE_URL"] = "sqlite+pysqlite:///" + (Path(__file__).resolve().parents[1] / "data" / "test.db").as_posix() TEST_DATA = Path(__file__).resolve().parents[1] / "data" / "pytest"
os.environ["DECOM_DATA_DIR"] = str(TEST_DATA)
os.environ["DECOM_ALLOW_SQLITE"] = "1"
os.environ["DECOM_INLINE_WORKER"] = "1" os.environ["DECOM_INLINE_WORKER"] = "1"
os.environ["DECOM_ADMIN_USERNAME"] = "admin"
os.environ["DECOM_ADMIN_PASSWORD"] = "admin-pass"
os.environ["DECOM_JWT_SECRET"] = "test-secret"
from app.collect.io import parse_csv, write_csv # noqa: E402 from app.collect.io import parse_csv, write_csv # noqa: E402
from app.db import reset_engine # noqa: E402 from app.db import reset_engine # noqa: E402
@@ -27,16 +27,20 @@ PUBLIC_KEY = (
@pytest.fixture() @pytest.fixture()
def client(): def client():
database = Path(os.environ["DECOM_DATABASE_URL"].removeprefix("sqlite+pysqlite:///")) if TEST_DATA.exists():
if database.exists(): shutil.rmtree(TEST_DATA)
database.unlink()
reset_engine() reset_engine()
application = create_app() application = create_app()
with TestClient(application) as test_client: with TestClient(application) as test_client:
created = test_client.post(
"/api/install",
json={"sqlite": True, "adminUsername": "admin", "adminPassword": "admin-pass", "separateWorker": False},
)
assert created.status_code == 200
yield test_client yield test_client
reset_engine() reset_engine()
if database.exists(): if TEST_DATA.exists():
database.unlink() shutil.rmtree(TEST_DATA)
def test_period_bounds(): def test_period_bounds():
+6 -1
View File
@@ -8,8 +8,13 @@ from app.runtime import start_background
def main() -> None: def main() -> None:
import asyncio
import sys
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
init_db() init_db()
start_background() start_background("worker")
if postgres_conninfo(): if postgres_conninfo():
from app.tasks.queue import serve from app.tasks.queue import serve
+21
View File
@@ -0,0 +1,21 @@
name: decom-dev
services:
postgres:
image: postgres:16
ports:
- "5432:5432"
environment:
POSTGRES_USER: ${POSTGRES_USER:-postgres}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?请设置 POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB:-decom}
volumes:
- decom-pg:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-decom}"]
interval: 5s
timeout: 5s
retries: 20
volumes:
decom-pg:
+51
View File
@@ -0,0 +1,51 @@
name: decom
services:
postgres:
image: postgres:16
environment:
POSTGRES_USER: ${POSTGRES_USER:-postgres}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?请设置 POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB:-decom}
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-decom}"]
interval: 5s
timeout: 5s
retries: 20
api:
build: .
ports:
- "8000:8000"
environment:
DECOM_DATA_DIR: /var/lib/decom
DECOM_DB_HOST: postgres
DECOM_DB_PORT: "5432"
DECOM_DB_NAME: ${POSTGRES_DB:-decom}
DECOM_DB_USER: ${POSTGRES_USER:-postgres}
volumes:
- decom-data:/var/lib/decom
depends_on:
postgres:
condition: service_healthy
worker:
build: .
command: ["python", "-m", "worker.main"]
environment:
DECOM_DATA_DIR: /var/lib/decom
DECOM_DB_HOST: postgres
DECOM_DB_PORT: "5432"
DECOM_DB_NAME: ${POSTGRES_DB:-decom}
DECOM_DB_USER: ${POSTGRES_USER:-postgres}
volumes:
- decom-data:/var/lib/decom
depends_on:
postgres:
condition: service_healthy
volumes:
pgdata:
decom-data:
+3 -1
View File
@@ -39,7 +39,9 @@ const overrides = computed<GlobalThemeOverrides>(() => ({
</script> </script>
<template> <template>
<n-config-provider :locale="zhCN" :date-locale="dateZhCN" :theme="isDark ? darkTheme : null" :theme-overrides="overrides"> <n-config-provider class="app-root" :locale="zhCN" :date-locale="dateZhCN" :theme="isDark ? darkTheme : null" :theme-overrides="overrides">
<div class="app-root">
<router-view /> <router-view />
</div>
</n-config-provider> </n-config-provider>
</template> </template>
+8 -20
View File
@@ -3,7 +3,7 @@ import { onMounted, ref } from "vue";
import { useRouter } from "vue-router"; import { useRouter } from "vue-router";
import { NAlert, NButton, NInput } from "naive-ui"; import { NAlert, NButton, NInput } from "naive-ui";
import { api, saveSession } from "../../shared/http"; import { api, saveSession } from "../../shared/http";
import { setThemeChoice, themeChoice, type ThemeChoice } from "../../shared/theme"; import ThemeButton from "../../shell/ThemeButton.vue";
const props = defineProps<{ purpose?: "login" | "pool" }>(); const props = defineProps<{ purpose?: "login" | "pool" }>();
const emit = defineEmits<{ done: [] }>(); const emit = defineEmits<{ done: [] }>();
@@ -18,11 +18,6 @@ const smsCode = ref("");
const smsRequired = ref(false); const smsRequired = ref(false);
const errorText = ref(""); const errorText = ref("");
const busy = ref(false); const busy = ref(false);
const themes = [
{ label: "跟随系统", value: "system" },
{ label: "深色", value: "dark" },
{ label: "浅色", value: "light" },
];
onMounted(async () => { onMounted(async () => {
if (props.purpose === "pool") { if (props.purpose === "pool") {
@@ -132,23 +127,16 @@ async function finishNqi() {
busy.value = false; busy.value = false;
} }
} }
function chooseTheme(value: ThemeChoice) {
setThemeChoice(value);
}
</script> </script>
<template> <template>
<div :class="purpose === 'pool' ? '' : 'gate'"> <div :class="purpose === 'pool' ? '' : 'gate'">
<div class="gate-card"> <ThemeButton v-if="purpose !== 'pool'" />
<h1 style="margin: 0 0 16px; font-size: 20px; display: flex; justify-content: space-between; align-items: center;"> <section class="gate-card">
<span>{{ purpose === "pool" ? "添加账号" : "DecomEval" }}</span> <div class="gate-brand">
<select v-if="purpose !== 'pool'" :value="themeChoice" @change="chooseTheme(($event.target as HTMLSelectElement).value as ThemeChoice)"> <div class="brand-mark" aria-hidden="true">D</div>
<option value="system">跟随系统</option> <h1>{{ purpose === "pool" ? "添加账号" : "DecomEval" }}</h1>
<option value="dark">深色</option> </div>
<option value="light">浅色</option>
</select>
</h1>
<n-alert v-if="errorText" type="error" style="margin-bottom: 12px">{{ errorText }}</n-alert> <n-alert v-if="errorText" type="error" style="margin-bottom: 12px">{{ errorText }}</n-alert>
<div class="form-grid"> <div class="form-grid">
<label>账号</label> <label>账号</label>
@@ -175,6 +163,6 @@ function chooseTheme(value: ThemeChoice) {
<n-button v-if="captchaUrl" type="primary" :loading="busy" @click="finishNqi">登录</n-button> <n-button v-if="captchaUrl" type="primary" :loading="busy" @click="finishNqi">登录</n-button>
</template> </template>
</div> </div>
</div> </section>
</div> </div>
</template> </template>
+90
View File
@@ -0,0 +1,90 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { NAlert, NButton, NInput, NInputNumber, NSwitch } from "naive-ui";
import { api } from "../../shared/http";
import { markInstalled } from "../../shared/installState";
import ThemeButton from "../../shell/ThemeButton.vue";
const router = useRouter();
const host = ref("127.0.0.1");
const port = ref(5432);
const database = ref("decom");
const username = ref("postgres");
const password = ref("nixevol@242520");
const adminUsername = ref("admin");
const adminPassword = ref("nixevol@242520");
const separateWorker = ref(true);
const errorText = ref("");
const busy = ref(false);
onMounted(async () => {
const status = await api<{ defaults?: { host?: string; port?: number; database?: string; username?: string } }>("/api/install/status");
const defaults = status.defaults;
if (!defaults) return;
if (defaults.host) host.value = defaults.host;
if (defaults.port) port.value = defaults.port;
if (defaults.database) database.value = defaults.database;
if (defaults.username) username.value = defaults.username;
});
async function submit() {
busy.value = true;
errorText.value = "";
try {
await api("/api/install", {
method: "POST",
body: JSON.stringify({
host: host.value,
port: port.value,
database: database.value,
username: username.value,
password: password.value,
adminUsername: adminUsername.value,
adminPassword: adminPassword.value,
separateWorker: separateWorker.value,
}),
});
markInstalled();
router.push("/login");
} catch (error) {
errorText.value = error instanceof Error ? error.message : "安装失败";
} finally {
busy.value = false;
}
}
</script>
<template>
<div class="gate">
<ThemeButton />
<section class="gate-card wide">
<div class="gate-brand">
<div class="brand-mark" aria-hidden="true">D</div>
<h1>安装 DecomEval</h1>
</div>
<n-alert v-if="errorText" type="error" style="margin-bottom: 12px">{{ errorText }}</n-alert>
<div class="form-grid">
<label>数据库主机</label>
<n-input v-model:value="host" />
<label>端口</label>
<n-input-number v-model:value="port" :min="1" :max="65535" />
<label>数据库名</label>
<n-input v-model:value="database" />
<label>数据库用户</label>
<n-input v-model:value="username" />
<label>数据库密码</label>
<n-input v-model:value="password" type="password" />
<label>管理员账号</label>
<n-input v-model:value="adminUsername" />
<label>管理员密码</label>
<n-input v-model:value="adminPassword" type="password" />
<label>独立排队进程</label>
<n-switch v-model:value="separateWorker" />
</div>
<div style="margin-top: 16px; display: flex; justify-content: flex-end;">
<n-button type="primary" :loading="busy" @click="submit">完成安装</n-button>
</div>
</section>
</div>
</template>
+8 -1
View File
@@ -1,6 +1,7 @@
import { createApp } from "vue"; import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router"; import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue"; import App from "./App.vue";
import InstallView from "./features/install/InstallView.vue";
import LoginView from "./features/auth/LoginView.vue"; import LoginView from "./features/auth/LoginView.vue";
import TasksView from "./features/user/TasksView.vue"; import TasksView from "./features/user/TasksView.vue";
import SettingsView from "./features/admin/SettingsView.vue"; import SettingsView from "./features/admin/SettingsView.vue";
@@ -8,11 +9,13 @@ import UsersView from "./features/admin/UsersView.vue";
import PoolView from "./features/admin/PoolView.vue"; import PoolView from "./features/admin/PoolView.vue";
import SourcesView from "./features/admin/SourcesView.vue"; import SourcesView from "./features/admin/SourcesView.vue";
import { token } from "./shared/http"; import { token } from "./shared/http";
import { installed, refreshInstalled } from "./shared/installState";
import "./styles.css"; import "./styles.css";
const router = createRouter({ const router = createRouter({
history: createWebHistory(), history: createWebHistory(),
routes: [ routes: [
{ path: "/install", component: InstallView },
{ path: "/login", component: LoginView }, { path: "/login", component: LoginView },
{ path: "/", redirect: "/tasks" }, { path: "/", redirect: "/tasks" },
{ path: "/tasks", component: TasksView, meta: { role: "user" } }, { path: "/tasks", component: TasksView, meta: { role: "user" } },
@@ -23,7 +26,11 @@ const router = createRouter({
], ],
}); });
router.beforeEach((to) => { router.beforeEach(async (to) => {
if (installed === null) await refreshInstalled();
if (!installed && to.path !== "/install") return "/install";
if (installed && to.path === "/install") return "/login";
if (to.path === "/install") return true;
if (to.path === "/login") return token() ? "/" : true; if (to.path === "/login") return token() ? "/" : true;
if (!token()) return "/login"; if (!token()) return "/login";
const role = sessionStorage.getItem("decom-role"); const role = sessionStorage.getItem("decom-role");
+11
View File
@@ -0,0 +1,11 @@
export let installed: boolean | null = null;
export async function refreshInstalled() {
const response = await fetch("/api/install/status");
installed = Boolean((await response.json()).installed);
return installed;
}
export function markInstalled() {
installed = true;
}
+6
View File
@@ -22,3 +22,9 @@ export function setThemeChoice(choice: ThemeChoice) {
themeChoice.value = choice; themeChoice.value = choice;
localStorage.setItem(STORAGE_KEY, choice); localStorage.setItem(STORAGE_KEY, choice);
} }
export function cycleTheme() {
const order: ThemeChoice[] = ["system", "dark", "light"];
const index = order.indexOf(themeChoice.value);
setThemeChoice(order[(index + 1) % order.length]);
}
+2 -12
View File
@@ -1,8 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { useRoute, useRouter } from "vue-router"; import { useRoute, useRouter } from "vue-router";
import { NSelect } from "naive-ui";
import { api, clearSession, token } from "../shared/http"; import { api, clearSession, token } from "../shared/http";
import { setThemeChoice, themeChoice, type ThemeChoice } from "../shared/theme"; import ThemeButton from "./ThemeButton.vue";
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
@@ -16,15 +15,6 @@ const items = role === "admin"
{ label: "采集", path: "/admin/sources" }, { label: "采集", path: "/admin/sources" },
] ]
: [{ label: "任务", path: "/tasks" }]; : [{ label: "任务", path: "/tasks" }];
const themes = [
{ label: "跟随系统", value: "system" },
{ label: "深色", value: "dark" },
{ label: "浅色", value: "light" },
];
function chooseTheme(value: ThemeChoice) {
setThemeChoice(value);
}
async function logout() { async function logout() {
if (token()) { if (token()) {
@@ -48,7 +38,7 @@ async function logout() {
</nav> </nav>
<div class="sider-foot"> <div class="sider-foot">
<div class="who">{{ name }}</div> <div class="who">{{ name }}</div>
<n-select :value="themeChoice" :options="themes" size="small" @update:value="chooseTheme" /> <ThemeButton />
<button class="text-button" @click="logout">退出</button> <button class="text-button" @click="logout">退出</button>
</div> </div>
</aside> </aside>
+31
View File
@@ -0,0 +1,31 @@
<script setup lang="ts">
import { NButton, NIcon, NTooltip } from "naive-ui";
import { cycleTheme, themeChoice } from "../shared/theme";
const label = { system: "跟随系统", dark: "深色", light: "浅色" } as const;
</script>
<template>
<n-tooltip>
<template #trigger>
<n-button class="theme-switch" quaternary circle :aria-label="label[themeChoice]" @click="cycleTheme">
<template #icon>
<n-icon>
<svg v-if="themeChoice === 'system'" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8">
<rect x="3" y="4" width="18" height="12" rx="1.5" />
<path d="M8 20h8M12 16v4" />
</svg>
<svg v-else-if="themeChoice === 'dark'" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8">
<path d="M16 3.2A8.5 8.5 0 1 0 20.8 14 7 7 0 0 1 16 3.2z" />
</svg>
<svg v-else viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8">
<circle cx="12" cy="12" r="4" />
<path d="M12 2.5v2.2M12 19.3v2.2M2.5 12h2.2M19.3 12h2.2M5 5l1.6 1.6M17.4 17.4 19 19M19 5l-1.6 1.6M6.6 17.4 5 19" />
</svg>
</n-icon>
</template>
</n-button>
</template>
{{ label[themeChoice] }}
</n-tooltip>
</template>
+37 -4
View File
@@ -5,7 +5,7 @@
font-size: 14px; font-size: 14px;
} }
* { box-sizing: border-box; } * { box-sizing: border-box; }
html, body, #app { margin: 0; height: 100%; } html, body, #app, .n-config-provider, .app-root { margin: 0; height: 100%; }
body { background: var(--bg); } body { background: var(--bg); }
button, input, select { font: inherit; } button, input, select { font: inherit; }
::selection { background: var(--accent-soft); } ::selection { background: var(--accent-soft); }
@@ -64,7 +64,8 @@ button, input, select { font: inherit; }
.topbar h1 { margin: 0; font-size: 18px; display: flex; align-items: center; gap: 6px; } .topbar h1 { margin: 0; font-size: 18px; display: flex; align-items: center; gap: 6px; }
.content { padding: 16px; overflow: auto; } .content { padding: 16px; overflow: auto; }
.panel { background: var(--panel); border: 1px solid var(--line); } .panel { background: var(--panel); border: 1px solid var(--line); }
.filters, .form-grid { display: grid; grid-template-columns: 96px minmax(0, 280px); gap: 8px 12px; align-items: center; } .filters, .form-grid { display: grid; grid-template-columns: 112px minmax(0, 280px); gap: 8px 12px; align-items: center; }
.gate-card.wide .form-grid { grid-template-columns: 112px minmax(0, 1fr); }
.hint { .hint {
width: 16px; width: 16px;
height: 16px; height: 16px;
@@ -76,13 +77,45 @@ button, input, select { font: inherit; }
text-align: center; text-align: center;
cursor: default; cursor: default;
} }
.app-root { height: 100%; }
.gate { .gate {
min-height: 100%; position: relative;
height: 100%;
min-height: 0;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
padding: 32px 16px; padding: 32px 16px;
overflow: auto;
background: var(--bg);
}
.gate .theme-switch { position: absolute; top: 16px; right: 16px; }
.sider-foot .theme-switch { position: static; align-self: flex-start; }
.gate-card {
width: min(440px, 100%);
background: var(--panel);
border: 1px solid var(--line);
border-radius: 4px;
padding: 28px 28px 22px;
}
.gate-card.wide { width: min(560px, 100%); }
.gate-brand {
display: flex;
gap: 14px;
align-items: center;
justify-content: center;
margin-bottom: 22px;
}
.gate-brand h1 { margin: 0; font-size: 20px; }
.brand-mark {
width: 36px;
height: 36px;
border-radius: 4px;
border: 1px solid var(--accent);
color: var(--accent);
display: grid;
place-items: center;
font-weight: 650;
} }
.gate-card { width: min(440px, 100%); background: var(--panel); border: 1px solid var(--line); padding: 28px; }
.captcha { height: 40px; cursor: pointer; } .captcha { height: 40px; cursor: pointer; }
.row-actions { display: flex; gap: 8px; } .row-actions { display: flex; gap: 8px; }