fix: TikTok 立即上传允许卡住的 uploading 任务强制重试

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-14 10:48:35 -05:00
parent d0bbcb484a
commit 9b9fb57491
6 changed files with 46 additions and 21 deletions

View File

@ -424,14 +424,24 @@ def claim_tiktok_job_manual_upload(job_id: str) -> dict[str, Any] | None:
if not row: if not row:
return None return None
st = str(row["status"] or "") st = str(row["status"] or "")
if st not in {"scheduled", "recorded"} or not str(row["clip_path"] or "").strip(): if st not in {"scheduled", "recorded", "uploading", "failed"}:
return None
if not str(row["clip_path"] or "").strip():
return None return None
if str(row["tiktok_video_id"] or "").strip(): if str(row["tiktok_video_id"] or "").strip():
return None return None
conn.execute( conn.execute(
"UPDATE tiktok_jobs SET status = 'uploading', upload_at = ?, updated_at = ? WHERE id = ?", """
UPDATE tiktok_jobs
SET status = 'uploading', upload_at = ?, attempts = attempts + 1,
error = '', finished_at = 0, updated_at = ?
WHERE id = ? AND tiktok_video_id = ''
""",
(now, now, job_id), (now, now, job_id),
) )
if conn.total_changes == 0:
conn.rollback()
return None
conn.commit() conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (job_id,)).fetchone()) return _row_to_dict(conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (job_id,)).fetchone())
finally: finally:

View File

@ -169,7 +169,7 @@ class TikTokPipeline:
async def upload_job_now(self, job_id: str) -> dict[str, Any]: async def upload_job_now(self, job_id: str) -> dict[str, Any]:
job = tiktok_db.claim_tiktok_job_manual_upload(job_id) job = tiktok_db.claim_tiktok_job_manual_upload(job_id)
if not job: if not job:
raise ValueError("任务不可立即上传(需 scheduled/recorded 且有成片)") raise ValueError("任务不可立即上传(需要成片且未发布;上传中卡住的可强制重试)")
await self._do_upload(job) await self._do_upload(job)
fresh = tiktok_db.get_tiktok_job(job_id) fresh = tiktok_db.get_tiktok_job(job_id)
if not fresh: if not fresh:
@ -207,7 +207,7 @@ class TikTokPipeline:
error="", error="",
) )
try: try:
tiktok_db.reclaim_stale_tiktok_uploads(max_age_sec=900) tiktok_db.reclaim_stale_tiktok_uploads(max_age_sec=180)
except Exception: except Exception:
pass pass
max_up = max(1, int(cfg.get("tiktok_max_concurrent") or 1)) max_up = max(1, int(cfg.get("tiktok_max_concurrent") or 1))

View File

@ -113,7 +113,10 @@ def schedule_board(limit: int = 24) -> dict[str, Any]:
"channel_name": ch.get("name") or "", "channel_name": ch.get("name") or "",
"status": j.get("status"), "status": j.get("status"),
"clip_ready": bool(clip) and Path(clip).is_file(), "clip_ready": bool(clip) and Path(clip).is_file(),
"can_upload_now": str(j.get("status") or "") in {"scheduled", "recorded"}, "can_upload_now": (
str(j.get("status") or "") in {"scheduled", "recorded", "uploading", "failed"}
and bool(str(j.get("clip_path") or "").strip())
),
} }
) )
channel_rows = [] channel_rows = []

View File

@ -98,7 +98,9 @@ async def upload_tiktok_mp4(
caption = (title or "").strip() caption = (title or "").strip()
if description.strip() and description.strip() not in caption: if description.strip() and description.strip() not in caption:
caption = f"{caption}\n{description.strip()}"[:2200] caption = f"{caption}\n{description.strip()}"[:2200]
return await asyncio.to_thread( try:
return await asyncio.wait_for(
asyncio.to_thread(
_upload_sync, _upload_sync,
channel_pk=channel_pk, channel_pk=channel_pk,
file_path=file_path, file_path=file_path,
@ -108,4 +110,8 @@ async def upload_tiktok_mp4(
allow_duet=0 if disable_duet else 1, allow_duet=0 if disable_duet else 1,
allow_stitch=0 if disable_stitch else 1, allow_stitch=0 if disable_stitch else 1,
proxy=proxy, proxy=proxy,
),
timeout=180,
) )
except TimeoutError as exc:
raise ValueError("TikTok 上传超时(180s),Cookie 可能失效或签名服务卡住,请重试") from exc

View File

@ -14,7 +14,13 @@ def test_save_and_load_session_cookies(temp_db, tmp_path, monkeypatch):
assert "tt-target-idc" in names assert "tt-target-idc" in names
def test_channel_has_session_false_when_missing(temp_db, tmp_path, monkeypatch): def test_manual_upload_allows_stuck_uploading(temp_db, tmp_path):
monkeypatch.setattr(tiktok_session, "cookies_dir", lambda: tmp_path) ch = tiktok_db.create_tiktok_channel(name="tt3")
ch = tiktok_db.create_tiktok_channel(name="tt2") job = tiktok_db.create_tiktok_job(session_id="", room_id="r1", channel_pk=ch["id"])
assert not tiktok_session.channel_has_session(ch) clip = tmp_path / "a.mp4"
clip.write_bytes(b"x")
tiktok_db.update_tiktok_job(job["id"], status="uploading", clip_path=str(clip))
claimed = tiktok_db.claim_tiktok_job_manual_upload(job["id"])
assert claimed is not None
assert claimed["status"] == "uploading"
assert claimed["clip_path"] == str(clip)

View File

@ -801,7 +801,7 @@ export default function TikTokPage() {
onClick={() => void uploadNow(j.id)} onClick={() => void uploadNow(j.id)}
className="rounded bg-teal-500/15 px-2 py-0.5 text-[10px] text-teal-200" className="rounded bg-teal-500/15 px-2 py-0.5 text-[10px] text-teal-200"
> >
上传 {j.status === "uploading" ? "重试上传" : "上传"}
</button> </button>
)} )}
{j.status === "failed" && ( {j.status === "failed" && (