This commit is contained in:
2026-08-26 14:15:06 +08:00
parent 48dd28a796
commit e3280623de
10 changed files with 541 additions and 65 deletions
+18 -2
View File
@@ -117,13 +117,14 @@ class ServerAPI:
resp.raise_for_status()
return resp.json()
def heartbeat(self) -> bool:
"""发送心跳,刷新服务端 last_seen_at;失败返回 False(不抛异常)"""
def heartbeat(self, payload: dict | None = None) -> bool:
"""发送心跳并携带 RPA 全量状态;失败返回 False(不抛异常)"""
if not self.token:
return False
try:
resp = self._req("post",
f"{self.base_url}/api/auth/heartbeat",
json=payload or {},
headers=self._headers(), timeout=10,
)
return resp.status_code == 200
@@ -131,6 +132,21 @@ class ServerAPI:
logger.debug(f"心跳发送失败:{e}")
return False
def fetch_pending_task(self) -> dict | None:
"""轮询拉取待执行的远程控制任务(服务端已标记 running)"""
resp = self._req("get", f"{self.base_url}/api/rpa/tasks/pending",
headers=self._headers(), timeout=10)
resp.raise_for_status()
return resp.json().get("task")
def finish_task(self, task_id: int, status: str, result: str = "") -> None:
"""远程任务执行完回调:更新终态与结果"""
resp = self._req("post",
f"{self.base_url}/api/rpa/tasks/{task_id}/finish",
json={"status": status, "result": result[:500]},
headers=self._headers(), timeout=10)
resp.raise_for_status()
def update_login_status(self, status: str, boss_account: str | None = None) -> dict:
payload = {"login_status": status}
if boss_account:
+117 -41
View File
@@ -40,7 +40,8 @@ class AppState:
self.applicant: Applicant | None = None
self.connected = False # 是否已注册/登录云端
self.login_polling = False
self._heartbeat_started = False
self._control_started = False
self._boss_login = "unknown" # Boss 登录状态缓存(控制线程周期刷新)
def ensure_applicant(self) -> Applicant:
if self.applicant is None:
@@ -48,34 +49,129 @@ class AppState:
return self.applicant
# ------------------------------------------------------------------
# 心跳:登录成功后启动后台线程,周期性向服务端上报存活
# 控制线程:登录成功后启动,5s 一轮 = 心跳带全量状态 + outbox 补发 + 远程任务轮询
# ------------------------------------------------------------------
def ensure_heartbeat(self) -> None:
if self._heartbeat_started or not self.server_api.token:
def ensure_control(self) -> None:
if self._control_started or not self.server_api.token:
return
self._heartbeat_started = True
threading.Thread(target=self._heartbeat_loop, daemon=True).start()
logger.info(f"心跳线程已启动,间隔 {client_settings.HEARTBEAT_INTERVAL}s")
self._control_started = True
threading.Thread(target=self._control_loop, daemon=True).start()
logger.info("控制线程已启动(状态上报/outbox 补发/远程任务轮询,间隔 5s)")
def _heartbeat_loop(self) -> None:
def _control_loop(self) -> None:
rounds = 0
while True:
if not self.server_api.token:
# 已退出登录,停止心跳
self._heartbeat_started = False
logger.info("已退出登录,心跳停止")
# 已退出登录,停止控制线程
self._control_started = False
logger.info("已退出登录,控制线程停止")
break
self.server_api.heartbeat()
# 心跳每轮顺便补发 outbox(网络恢复后自动补齐丢失记录)
try:
self.server_api.heartbeat(self._collect_status(rounds))
except Exception as e:
logger.debug(f"状态上报失败:{e}")
try:
outbox.flush(self.server_api)
except Exception as e:
logger.debug(f"outbox 补发轮异常:{e}")
time.sleep(client_settings.HEARTBEAT_INTERVAL)
try:
self._poll_remote_task()
except Exception as e:
logger.debug(f"远程任务轮询异常:{e}")
rounds += 1
time.sleep(5)
def _collect_status(self, rounds: int) -> dict:
"""采集 RPA 全量状态,随心跳上报(每用户单设备,服务端一行快照)"""
# 每 6 轮(约 30s)活体刷新 Boss 登录状态,其余轮次用缓存
if rounds % 6 == 0:
try:
if self.browser.is_browser_running():
new = "logged_in" if self.browser.check_boss_login() else "not_login"
else:
new = "not_login"
if new != self._boss_login:
self._boss_login = new
# 与云端 User.login_status 保持一致
try:
if new == "logged_in":
self.server_api.update_login_status("logged_in",
self.browser.get_boss_account_name())
else:
self.server_api.update_login_status("not_login")
except Exception:
pass
except Exception as e:
logger.debug(f"Boss 登录状态刷新失败:{e}")
applying = bool(self.applicant and self.applicant.is_running)
stats = self.applicant.stats if self.applicant else {}
return {
"boss_login": self._boss_login,
"browser": "running" if self.browser.is_browser_running() else "stopped",
"apply_status": "running" if applying else "idle",
"current": (stats.get("current") or "") if applying else "",
"applied": stats.get("applied", 0),
"skipped": stats.get("skipped", 0),
}
def _poll_remote_task(self) -> None:
"""拉取并执行云端下发的远程控制任务,执行完回调终态"""
task = self.server_api.fetch_pending_task()
if not task:
return
tid, ttype = task["id"], task["task_type"]
logger.info(f"收到远程任务 #{tid}:{ttype}")
try:
if ttype == "start_apply":
res = start_apply_shared(task.get("params") or {})
status, result = ("done", res["msg"]) if res["ok"] else ("failed", res["msg"])
elif ttype == "stop_apply":
applicant = self.ensure_applicant()
if applicant.is_running:
applicant.stop()
status, result = "done", "停止指令已下达"
else:
status, result = "done", "当前没有运行中的投递任务"
else:
status, result = "failed", f"未知任务类型:{ttype}"
except Exception as e:
status, result = "failed", f"执行异常:{e}"
logger.info(f"远程任务 #{tid} 执行结果:{status} - {result}")
try:
self.server_api.finish_task(tid, status, result)
except Exception as e:
logger.warning(f"远程任务回调失败 #{tid}:{e}")
state = AppState()
def start_apply_shared(params: dict) -> dict:
"""面板 / 远程任务共用的启动入口(返回 ok+msg,不抛业务异常)"""
if not state.server_api.get_primary_resume():
return {"ok": False, "msg": "请先设置主简历"}
try:
# 浏览器可能被用户手动关闭,投递前确保已拉起(复用登录态 profile)
state.browser.ensure_browser_started()
except RuntimeError as e:
return {"ok": False, "msg": str(e)}
applicant = state.ensure_applicant()
if applicant.is_running:
return {"ok": False, "msg": "已有投递任务在运行"}
applicant.start(
keywords=list(params.get("keywords") or []),
city_code=str(params.get("city_code") or ""),
salary_min=params.get("salary_min"),
salary_max=params.get("salary_max"),
min_score=int(params.get("min_score") or 65),
delay_range=(int(params.get("delay_min") or 3), int(params.get("delay_max") or 8)),
boss_online_only=bool(params.get("boss_online_only")),
daily_limit=int(params.get("daily_limit") or 0),
allow_headhunter=bool(params.get("allow_headhunter")),
)
return {"ok": True, "msg": "投递任务已启动", "session_id": applicant.session_id}
# =======================================================
# 前置校验(收敛:所有需要已登录云端的路由统一走这里)
# =======================================================
@@ -148,7 +244,7 @@ def get_status():
try:
me = state.server_api.get_me()
state.connected = True
state.ensure_heartbeat() # token 有效时确保心跳线程在跑
state.ensure_control() # token 有效时确保控制线程在跑
except Exception:
state.connected = False
state.server_api.logout() # token 失效,清除本地缓存
@@ -200,7 +296,7 @@ def register(req: AuthReq):
try:
data = state.server_api.register(req.username, req.password, req.nickname)
state.connected = True
state.ensure_heartbeat()
state.ensure_control()
return {"ok": True, "user_id": data["user_id"], "username": data["username"]}
except requests.HTTPError as e:
raise HTTPException(status_code=e.response.status_code, detail=_extract_error(e))
@@ -214,7 +310,7 @@ def login(req: AuthReq):
try:
data = state.server_api.login(req.username, req.password)
state.connected = True
state.ensure_heartbeat()
state.ensure_control()
return {"ok": True, "user_id": data["user_id"], "username": data["username"]}
except requests.HTTPError as e:
raise HTTPException(status_code=e.response.status_code, detail=_extract_error(e))
@@ -377,30 +473,10 @@ def delete_resume(resume_id: int):
def start_apply(req: StartApplyReq):
_require_auth()
_require_rpa_online() # 在线预检:与服务端 require_online_user 前置校验呼应
if not state.server_api.get_primary_resume():
raise HTTPException(status_code=400, detail="请先设置主简历")
try:
# 浏览器可能被用户手动关闭,投递前确保已拉起(复用登录态 profile)
state.browser.ensure_browser_started()
except RuntimeError as e:
raise HTTPException(status_code=400, detail=str(e))
applicant = state.ensure_applicant()
if applicant.is_running:
raise HTTPException(status_code=400, detail="已有投递任务在运行")
applicant.start(
keywords=req.keywords,
city_code=req.city_code,
salary_min=req.salary_min,
salary_max=req.salary_max,
min_score=req.min_score,
delay_range=(req.delay_min, req.delay_max),
boss_online_only=req.boss_online_only,
daily_limit=req.daily_limit,
allow_headhunter=req.allow_headhunter,
)
return {"ok": True, "session_id": applicant.session_id}
res = start_apply_shared(req.model_dump())
if not res["ok"]:
raise HTTPException(status_code=400, detail=res["msg"])
return {"ok": True, "session_id": res.get("session_id")}
@app.post("/api/stop-apply")