fix: 失败账号按间隔重试,请求并发不再占满整段学习
This commit is contained in:
@@ -433,6 +433,9 @@ def post_study_control(body: StudyControlBody, request: Request, db: Session = D
|
|||||||
|
|
||||||
halt_work(employee_id)
|
halt_work(employee_id)
|
||||||
else:
|
else:
|
||||||
|
from euniv.autostudy import clear_study_hold
|
||||||
|
|
||||||
|
clear_study_hold(employee_id)
|
||||||
start_now(account)
|
start_now(account)
|
||||||
db.commit()
|
db.commit()
|
||||||
sync_work(employee_id)
|
sync_work(employee_id)
|
||||||
|
|||||||
+88
-19
@@ -58,6 +58,10 @@ _user_halts: dict[str, asyncio.Event] = {}
|
|||||||
_wanted: dict[str, int] = {}
|
_wanted: dict[str, int] = {}
|
||||||
_wanted_seq = 0
|
_wanted_seq = 0
|
||||||
_running: set[str] = set()
|
_running: set[str] = set()
|
||||||
|
_retry_at: dict[str, float] = {}
|
||||||
|
_retry_count: dict[str, int] = {}
|
||||||
|
_done_month: dict[str, str] = {}
|
||||||
|
_RETRY_STEPS = (5 * 60, 15 * 60, 60 * 60)
|
||||||
_worker = None
|
_worker = None
|
||||||
|
|
||||||
|
|
||||||
@@ -314,6 +318,31 @@ def request_wake() -> None:
|
|||||||
worker.wake()
|
worker.wake()
|
||||||
|
|
||||||
|
|
||||||
|
def clear_study_hold(employee_id: str) -> None:
|
||||||
|
key = (employee_id or "").strip()
|
||||||
|
_retry_at.pop(key, None)
|
||||||
|
_retry_count.pop(key, None)
|
||||||
|
_done_month.pop(key, None)
|
||||||
|
|
||||||
|
|
||||||
|
def note_attempt_end(employee_id: str) -> None:
|
||||||
|
with _lock:
|
||||||
|
info = (_status.get("users") or {}).get(employee_id) or {}
|
||||||
|
state = str(info.get("state") or "")
|
||||||
|
if state in ("学习失败", "会话失效"):
|
||||||
|
count = _retry_count.get(employee_id, 0)
|
||||||
|
delay = _RETRY_STEPS[min(count, len(_RETRY_STEPS) - 1)]
|
||||||
|
_retry_count[employee_id] = count + 1
|
||||||
|
_retry_at[employee_id] = time.time() + delay
|
||||||
|
return
|
||||||
|
if state == "已学完":
|
||||||
|
from euniv.study_window import month_key
|
||||||
|
|
||||||
|
_done_month[employee_id] = month_key()
|
||||||
|
_retry_at.pop(employee_id, None)
|
||||||
|
_retry_count.pop(employee_id, None)
|
||||||
|
|
||||||
|
|
||||||
def want_work(employee_id: str) -> None:
|
def want_work(employee_id: str) -> None:
|
||||||
key = (employee_id or "").strip()
|
key = (employee_id or "").strip()
|
||||||
if not key:
|
if not key:
|
||||||
@@ -606,6 +635,9 @@ class StudySession:
|
|||||||
self._use_pool = use_pool
|
self._use_pool = use_pool
|
||||||
self._referer = EUNIV + "/"
|
self._referer = EUNIV + "/"
|
||||||
self._submit_logs = 0
|
self._submit_logs = 0
|
||||||
|
self._proxy_lock: asyncio.Lock | None = None
|
||||||
|
self._closing: list[httpx.AsyncClient] = []
|
||||||
|
self._switches = 0
|
||||||
self._client: httpx.AsyncClient | None = None
|
self._client: httpx.AsyncClient | None = None
|
||||||
|
|
||||||
async def __aenter__(self) -> "StudySession":
|
async def __aenter__(self) -> "StudySession":
|
||||||
@@ -618,49 +650,72 @@ class StudySession:
|
|||||||
headers={"User-Agent": USER_AGENT},
|
headers={"User-Agent": USER_AGENT},
|
||||||
)
|
)
|
||||||
_load_cookies(self._client, self._initial_cookies)
|
_load_cookies(self._client, self._initial_cookies)
|
||||||
|
self._proxy_lock = asyncio.Lock()
|
||||||
return self
|
return self
|
||||||
|
|
||||||
async def __aexit__(self, *args: object) -> None:
|
async def __aexit__(self, *args: object) -> None:
|
||||||
|
for client in self._closing:
|
||||||
|
await client.aclose()
|
||||||
|
self._closing.clear()
|
||||||
if self._client:
|
if self._client:
|
||||||
await self._client.aclose()
|
await self._client.aclose()
|
||||||
|
|
||||||
async def _rotate_proxy(self) -> bool:
|
async def _rotate_proxy(self, used: str | None = None) -> bool:
|
||||||
if not self._use_pool:
|
if not self._use_pool:
|
||||||
return False
|
return False
|
||||||
from euniv.proxy import parse_proxy
|
from euniv.proxy import async_httpx_client, parse_proxy
|
||||||
from euniv.proxy_pool import acquire, mark_failed
|
from euniv.proxy_pool import MAX_SWITCHES, acquire, mark_failed
|
||||||
|
|
||||||
old = self._proxy
|
if self._proxy_lock is None:
|
||||||
await asyncio.to_thread(mark_failed, self._employee_id, old)
|
self._proxy_lock = asyncio.Lock()
|
||||||
|
failed = self._proxy if used is None else used
|
||||||
|
async with self._proxy_lock:
|
||||||
|
if failed != self._proxy:
|
||||||
|
return True
|
||||||
|
if self._switches >= MAX_SWITCHES:
|
||||||
|
return False
|
||||||
|
self._switches += 1
|
||||||
|
await asyncio.to_thread(mark_failed, self._employee_id, failed)
|
||||||
nxt = await asyncio.to_thread(acquire, self._employee_id)
|
nxt = await asyncio.to_thread(acquire, self._employee_id)
|
||||||
parsed = parse_proxy(nxt)
|
parsed = parse_proxy(nxt)
|
||||||
if parsed == old:
|
if parsed == failed:
|
||||||
return False
|
return False
|
||||||
from euniv.proxy import async_httpx_client
|
|
||||||
|
|
||||||
client = async_httpx_client(
|
client = async_httpx_client(
|
||||||
parsed,
|
parsed,
|
||||||
timeout=30,
|
timeout=30,
|
||||||
follow_redirects=True,
|
follow_redirects=True,
|
||||||
headers={"User-Agent": USER_AGENT},
|
headers={"User-Agent": USER_AGENT},
|
||||||
)
|
)
|
||||||
_load_cookies(client, self._initial_cookies)
|
cookies = self._initial_cookies
|
||||||
prev = self._client
|
if self._client is not None:
|
||||||
|
cookies = [
|
||||||
|
(cookie.name, cookie.value or "", cookie.domain or "", cookie.path or "/")
|
||||||
|
for cookie in self._client.cookies.jar
|
||||||
|
] or self._initial_cookies
|
||||||
|
self._closing.append(self._client)
|
||||||
|
_load_cookies(client, cookies)
|
||||||
self._client = client
|
self._client = client
|
||||||
self._proxy = parsed
|
self._proxy = parsed
|
||||||
if prev is not None:
|
|
||||||
await prev.aclose()
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
async def _http(self, method: str, url: str, **kw: object) -> httpx.Response:
|
async def _http(self, method: str, url: str, **kw: object) -> httpx.Response:
|
||||||
assert self._client is not None
|
assert self._client is not None
|
||||||
try:
|
limit = getattr(self, "_request_limit", None)
|
||||||
return await self._client.request(method, url, **kw)
|
|
||||||
except Exception as exc:
|
async def once() -> httpx.Response:
|
||||||
if self._use_pool and self._proxy and is_proxy_failure(exc):
|
|
||||||
if await self._rotate_proxy():
|
|
||||||
assert self._client is not None
|
assert self._client is not None
|
||||||
|
if limit is None:
|
||||||
return await self._client.request(method, url, **kw)
|
return await self._client.request(method, url, **kw)
|
||||||
|
async with limit:
|
||||||
|
return await self._client.request(method, url, **kw)
|
||||||
|
|
||||||
|
used = self._proxy
|
||||||
|
try:
|
||||||
|
return await once()
|
||||||
|
except Exception as exc:
|
||||||
|
if self._use_pool and used and is_proxy_failure(exc):
|
||||||
|
if await self._rotate_proxy(used):
|
||||||
|
return await once()
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def _api_headers(self) -> dict[str, str]:
|
def _api_headers(self) -> dict[str, str]:
|
||||||
@@ -1317,6 +1372,7 @@ class AutoStudyWorker:
|
|||||||
|
|
||||||
def _tick(self) -> float:
|
def _tick(self) -> float:
|
||||||
from euniv.db import SessionLocal
|
from euniv.db import SessionLocal
|
||||||
|
from euniv.study_window import CN_TZ, month_key
|
||||||
|
|
||||||
now = as_cn()
|
now = as_cn()
|
||||||
soonest = next_month_start(now)
|
soonest = next_month_start(now)
|
||||||
@@ -1341,6 +1397,17 @@ class AutoStudyWorker:
|
|||||||
if is_studying(eid) or is_wanted(eid):
|
if is_studying(eid) or is_wanted(eid):
|
||||||
halt_work(eid)
|
halt_work(eid)
|
||||||
continue
|
continue
|
||||||
|
retry_hold = _retry_at.get(eid)
|
||||||
|
if retry_hold and time.time() < retry_hold and not is_wanted(eid):
|
||||||
|
retry_at = datetime.fromtimestamp(retry_hold, CN_TZ)
|
||||||
|
if retry_at < soonest:
|
||||||
|
soonest = retry_at
|
||||||
|
continue
|
||||||
|
if retry_hold and time.time() >= retry_hold:
|
||||||
|
want_work(eid)
|
||||||
|
_retry_at.pop(eid, None)
|
||||||
|
if _done_month.get(eid) == month_key(now) and not is_wanted(eid):
|
||||||
|
continue
|
||||||
if not (study_eligible(row) or is_wanted(eid)):
|
if not (study_eligible(row) or is_wanted(eid)):
|
||||||
continue
|
continue
|
||||||
if self._busy(eid):
|
if self._busy(eid):
|
||||||
@@ -1367,7 +1434,7 @@ class AutoStudyWorker:
|
|||||||
else:
|
else:
|
||||||
label = soonest.strftime("%m-%d %H:%M:%S")
|
label = soonest.strftime("%m-%d %H:%M:%S")
|
||||||
_set_status(running=False, message=f"下一次定时 {label}")
|
_set_status(running=False, message=f"下一次定时 {label}")
|
||||||
return wait
|
return min(wait, 3600.0)
|
||||||
|
|
||||||
def _launch(self, job: tuple, course_list: list[tuple[str, str, str]]) -> bool:
|
def _launch(self, job: tuple, course_list: list[tuple[str, str, str]]) -> bool:
|
||||||
eid = job[0]
|
eid = job[0]
|
||||||
@@ -1377,6 +1444,7 @@ class AutoStudyWorker:
|
|||||||
_set_user_status(eid, state="学习失败", message="没有可用的课程")
|
_set_user_status(eid, state="学习失败", message="没有可用的课程")
|
||||||
drop_work(eid)
|
drop_work(eid)
|
||||||
return False
|
return False
|
||||||
|
_set_user_status(eid, state="排队中", course="")
|
||||||
want_work(eid)
|
want_work(eid)
|
||||||
with _halt_lock:
|
with _halt_lock:
|
||||||
generation = _wanted.get(eid, 0)
|
generation = _wanted.get(eid, 0)
|
||||||
@@ -1412,6 +1480,7 @@ class AutoStudyWorker:
|
|||||||
drop_work(emp_id)
|
drop_work(emp_id)
|
||||||
elif current is not None and self._kick is not None:
|
elif current is not None and self._kick is not None:
|
||||||
self._kick.set()
|
self._kick.set()
|
||||||
|
note_attempt_end(emp_id)
|
||||||
self._tasks.pop(emp_id, None)
|
self._tasks.pop(emp_id, None)
|
||||||
|
|
||||||
async def _study_user(self, employee_id: str, target: int,
|
async def _study_user(self, employee_id: str, target: int,
|
||||||
@@ -1427,7 +1496,6 @@ class AutoStudyWorker:
|
|||||||
_user_halts[employee_id] = user_stop
|
_user_halts[employee_id] = user_stop
|
||||||
_running.add(employee_id)
|
_running.add(employee_id)
|
||||||
try:
|
try:
|
||||||
async with sem:
|
|
||||||
if user_stop.is_set():
|
if user_stop.is_set():
|
||||||
_set_user_status(employee_id, state="已停止")
|
_set_user_status(employee_id, state="已停止")
|
||||||
return
|
return
|
||||||
@@ -1443,6 +1511,7 @@ class AutoStudyWorker:
|
|||||||
token, cookies, proxy=proxy, employee_id=employee_id, use_pool=use_pool
|
token, cookies, proxy=proxy, employee_id=employee_id, use_pool=use_pool
|
||||||
) as session:
|
) as session:
|
||||||
session._employee_id = employee_id # type: ignore[attr-defined]
|
session._employee_id = employee_id # type: ignore[attr-defined]
|
||||||
|
session._request_limit = sem
|
||||||
_set_user_status(employee_id, state="学习中")
|
_set_user_status(employee_id, state="学习中")
|
||||||
hours = HoursWatcher(session, employee_id, target, user_stop, source=hours_source)
|
hours = HoursWatcher(session, employee_id, target, user_stop, source=hours_source)
|
||||||
if await hours.refresh():
|
if await hours.refresh():
|
||||||
|
|||||||
@@ -1354,8 +1354,15 @@ class EunivClient:
|
|||||||
response = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"")
|
response = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"")
|
||||||
except SessionExpired:
|
except SessionExpired:
|
||||||
return False
|
return False
|
||||||
|
if response.status_code >= 500 or response.status_code == 429:
|
||||||
|
raise RuntimeError("学习平台暂时不可用")
|
||||||
|
try:
|
||||||
payload = response.json()
|
payload = response.json()
|
||||||
return isinstance(payload, dict) and bool(payload.get("cnName"))
|
except ValueError as exc:
|
||||||
|
raise RuntimeError("学习平台暂时不可用") from exc
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
raise RuntimeError("学习平台暂时不可用")
|
||||||
|
return bool(payload.get("cnName"))
|
||||||
|
|
||||||
def _pages(self, url: str, headers: dict, html: str, parse, identity: str) -> list[dict]:
|
def _pages(self, url: str, headers: dict, html: str, parse, identity: str) -> list[dict]:
|
||||||
items = parse(html)
|
items = parse(html)
|
||||||
|
|||||||
@@ -211,6 +211,10 @@ def _fetch_and_store(trigger: str) -> bool:
|
|||||||
sync.next_allowed_at = sync.finished_at + next_gap()
|
sync.next_allowed_at = sync.finished_at + next_gap()
|
||||||
sync.course_count = len(courses)
|
sync.course_count = len(courses)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
from euniv.autostudy import clear_study_hold, request_wake
|
||||||
|
|
||||||
|
clear_study_hold(employee_id)
|
||||||
|
request_wake()
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -498,6 +498,10 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
|
|||||||
|
|
||||||
stamp_hours(account, hours)
|
stamp_hours(account, hours)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
if valid is True:
|
||||||
|
from euniv.autostudy import request_wake
|
||||||
|
|
||||||
|
request_wake()
|
||||||
if checked_alive:
|
if checked_alive:
|
||||||
_request_course_sync(employee_id)
|
_request_course_sync(employee_id)
|
||||||
|
|
||||||
|
|||||||
@@ -47,6 +47,9 @@ def fresh_database():
|
|||||||
|
|
||||||
autostudy_mod._wanted.clear()
|
autostudy_mod._wanted.clear()
|
||||||
autostudy_mod._running.clear()
|
autostudy_mod._running.clear()
|
||||||
|
autostudy_mod._retry_at.clear()
|
||||||
|
autostudy_mod._retry_count.clear()
|
||||||
|
autostudy_mod._done_month.clear()
|
||||||
autostudy_mod._user_halts.clear()
|
autostudy_mod._user_halts.clear()
|
||||||
users = autostudy_mod._status.get("users")
|
users = autostudy_mod._status.get("users")
|
||||||
if isinstance(users, dict):
|
if isinstance(users, dict):
|
||||||
|
|||||||
@@ -97,6 +97,7 @@ const studyLabel = computed(() => {
|
|||||||
if (state === "已停止" || studyControl.value.paused) return "任务已停止";
|
if (state === "已停止" || studyControl.value.paused) return "任务已停止";
|
||||||
if (state === "已学完") return "课程已学完";
|
if (state === "已学完") return "课程已学完";
|
||||||
if (studyFailed.value) return message || state;
|
if (studyFailed.value) return message || state;
|
||||||
|
if (state === "排队中") return "排队中";
|
||||||
if (state === "准备") return "正在连接学习平台";
|
if (state === "准备") return "正在连接学习平台";
|
||||||
if (studyingWorkers.value.length) return studyControl.value.course || "学习中";
|
if (studyingWorkers.value.length) return studyControl.value.course || "学习中";
|
||||||
if (state === "学习中") return "正在领取课程";
|
if (state === "学习中") return "正在领取课程";
|
||||||
|
|||||||
Reference in New Issue
Block a user