feat: 采集和导出固定由排队进程执行
This commit is contained in:
@@ -28,4 +28,4 @@ cd backend
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
启动前设置 `POSTGRES_PASSWORD`。首次打开网页完成安装,数据库主机使用 `postgres`,并保持独立排队进程开启。
|
||||
启动前设置 `POSTGRES_PASSWORD`。首次打开网页完成安装,数据库主机使用 `postgres`。排队进程负责采集和导出,不能关掉。
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
"""去掉本进程执行任务的开关。采集和导出始终由排队进程执行。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "0003_drop_inline_worker"
|
||||
down_revision = "0002_install_settings"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.drop_column("app_setting", "inline_worker")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.add_column("app_setting", sa.Column("inline_worker", sa.Boolean(), nullable=False, server_default=sa.false()))
|
||||
@@ -44,19 +44,3 @@ def postgres_conninfo() -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def inline_worker() -> bool:
|
||||
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:
|
||||
setting = session.get(AppSetting, 1)
|
||||
if setting is None:
|
||||
return False
|
||||
return bool(setting.inline_worker)
|
||||
|
||||
@@ -62,7 +62,6 @@ def perform_install(body: dict) -> None:
|
||||
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:
|
||||
@@ -101,7 +100,6 @@ def perform_install(body: dict) -> None:
|
||||
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"))
|
||||
|
||||
@@ -12,7 +12,6 @@ from fastapi.staticfiles import StaticFiles
|
||||
from app.api.http import router
|
||||
from app.bootstrap import init_db
|
||||
from app.config import installed
|
||||
from app.runtime import start_background
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
WEB_DIST = next(
|
||||
@@ -31,7 +30,6 @@ WEB_DIST = next(
|
||||
@asynccontextmanager
|
||||
async def lifespan(_application: FastAPI):
|
||||
init_db()
|
||||
start_background()
|
||||
yield
|
||||
|
||||
|
||||
|
||||
@@ -26,7 +26,6 @@ class AppSetting(Base):
|
||||
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):
|
||||
|
||||
+8
-18
@@ -1,4 +1,4 @@
|
||||
"""凭证刷新和采集周期。用户任务由队列或本进程线程执行。"""
|
||||
"""凭证刷新和采集周期。只在排队进程中运行。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -15,28 +15,18 @@ logger = logging.getLogger("decom")
|
||||
_started = False
|
||||
|
||||
|
||||
def start_background(owner: str = "api") -> None:
|
||||
def start_background() -> None:
|
||||
global _started
|
||||
if _started:
|
||||
return
|
||||
_started = True
|
||||
threading.Thread(target=_refresh_loop, args=(owner,), name="decom-refresh", daemon=True).start()
|
||||
threading.Thread(target=_collect_loop, args=(owner,), name="decom-collect", daemon=True).start()
|
||||
threading.Thread(target=_refresh_loop, name="decom-refresh", daemon=True).start()
|
||||
threading.Thread(target=_collect_loop, name="decom-collect", daemon=True).start()
|
||||
|
||||
|
||||
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:
|
||||
def _refresh_loop() -> None:
|
||||
while True:
|
||||
if not installed() or not _owns_schedule(owner):
|
||||
if not installed():
|
||||
time.sleep(2)
|
||||
continue
|
||||
seconds = 300
|
||||
@@ -53,9 +43,9 @@ def _refresh_loop(owner: str) -> None:
|
||||
time.sleep(max(60, seconds))
|
||||
|
||||
|
||||
def _collect_loop(owner: str) -> None:
|
||||
def _collect_loop() -> None:
|
||||
while True:
|
||||
if not installed() or not _owns_schedule(owner):
|
||||
if not installed():
|
||||
time.sleep(2)
|
||||
continue
|
||||
try:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""PostgreSQL 上的 Procrastinate 队列。SQLite 或本进程模式不走这里。"""
|
||||
"""PostgreSQL 上的 Procrastinate 队列。采集和导出都由排队进程执行。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ from sqlalchemy import select
|
||||
|
||||
from app.collect.io import parse_upload, write_table
|
||||
from app.collect.remote import fetch_ftp, fetch_nqi
|
||||
from app.config import inline_worker, postgres_conninfo, result_dir
|
||||
from app.config import postgres_conninfo, result_dir
|
||||
from app.db import session_scope
|
||||
from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcnow
|
||||
from app.nqi.client import NqiAuthError, NqiClient, NqiError
|
||||
@@ -190,16 +190,12 @@ def enqueue_collection(source_id: int) -> None:
|
||||
|
||||
|
||||
def _defer(name: str, **kwargs) -> bool:
|
||||
if inline_worker() or not postgres_conninfo():
|
||||
if not postgres_conninfo():
|
||||
return False
|
||||
try:
|
||||
from app.tasks.queue import defer
|
||||
from app.tasks.queue import defer
|
||||
|
||||
defer(name, **kwargs)
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.info("排队未投递,改为本进程执行: %s", exc)
|
||||
return False
|
||||
defer(name, **kwargs)
|
||||
return True
|
||||
|
||||
|
||||
def scan_sources() -> None:
|
||||
|
||||
@@ -11,7 +11,6 @@ from fastapi.testclient import TestClient
|
||||
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"
|
||||
|
||||
from app.collect.io import parse_csv, write_csv # noqa: E402
|
||||
from app.db import reset_engine # noqa: E402
|
||||
@@ -34,7 +33,7 @@ def client():
|
||||
with TestClient(application) as test_client:
|
||||
created = test_client.post(
|
||||
"/api/install",
|
||||
json={"sqlite": True, "adminUsername": "admin", "adminPassword": "admin-pass", "separateWorker": False},
|
||||
json={"sqlite": True, "adminUsername": "admin", "adminPassword": "admin-pass"},
|
||||
)
|
||||
assert created.status_code == 200
|
||||
yield test_client
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""执行排队的导出和采集。"""
|
||||
"""排队进程:从 NQI、FTP/SFTP 采集入库,并导出结果文件。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -14,7 +14,7 @@ def main() -> None:
|
||||
if sys.platform == "win32":
|
||||
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
||||
init_db()
|
||||
start_background("worker")
|
||||
start_background()
|
||||
if postgres_conninfo():
|
||||
from app.tasks.queue import serve
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import { NAlert, NButton, NInput, NInputNumber, NSwitch } from "naive-ui";
|
||||
import { NAlert, NButton, NInput, NInputNumber } from "naive-ui";
|
||||
import { api } from "../../shared/http";
|
||||
import { markInstalled } from "../../shared/installState";
|
||||
import ThemeButton from "../../shell/ThemeButton.vue";
|
||||
@@ -14,7 +14,6 @@ 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);
|
||||
|
||||
@@ -42,7 +41,6 @@ async function submit() {
|
||||
password: password.value,
|
||||
adminUsername: adminUsername.value,
|
||||
adminPassword: adminPassword.value,
|
||||
separateWorker: separateWorker.value,
|
||||
}),
|
||||
});
|
||||
markInstalled();
|
||||
@@ -79,8 +77,6 @@ async function submit() {
|
||||
<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>
|
||||
|
||||
Reference in New Issue
Block a user