fix: harden yt-long reclaim/quota/sync, monitor overdue backoff, X day-pause, TikTok cookie delay
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
0dcfdb263a
commit
a6ede5619c
@ -490,6 +490,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
||||
"x_clips_dedupe_room_day": True,
|
||||
"x_clips_max_concurrent": 1,
|
||||
"x_clips_auto_post": True,
|
||||
"x_clips_auto_post_paused_date": "",
|
||||
"x_clips_live_sample": True,
|
||||
"x_clips_live_sample_interval_sec": 180,
|
||||
"x_clips_live_sample_batch": 1,
|
||||
@ -515,8 +516,8 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
||||
"yt_long_max_concurrent": 1,
|
||||
"yt_long_upload_min_gap_sec": 900,
|
||||
"yt_long_delete_clip_after_upload": True,
|
||||
"yt_long_title_template": "{anchor} street food live",
|
||||
"yt_long_description_template": "{anchor}\n{url}\n#StreetFood #Live",
|
||||
"yt_long_title_template": "",
|
||||
"yt_long_description_template": "",
|
||||
"tiktok_auto_retry_failed": False,
|
||||
"tiktok_auto_retry_max_attempts": 3,
|
||||
"tiktok_auto_retry_interval_sec": 300,
|
||||
|
||||
@ -121,30 +121,27 @@ async def lifespan(_: FastAPI):
|
||||
async def _start_workers() -> None:
|
||||
if _desktop_light:
|
||||
return
|
||||
try:
|
||||
await monitor.start()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
await yt_monitor.start()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
await shorts_pipeline.start()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
await tiktok_pipeline.start()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
await x_clips_pipeline.start()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
await yt_long_pipeline.start()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def _boot(name: str, starter) -> None:
|
||||
try:
|
||||
await starter()
|
||||
except Exception as exc:
|
||||
try:
|
||||
db.add_event(
|
||||
kind="ops",
|
||||
level="error",
|
||||
message=f"worker 启动失败:{name} — {str(exc)[:160]}",
|
||||
meta={"worker": name, "error": str(exc)[:240]},
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
await _boot("monitor", monitor.start)
|
||||
await _boot("yt_monitor", yt_monitor.start)
|
||||
await _boot("shorts", shorts_pipeline.start)
|
||||
await _boot("tiktok", tiktok_pipeline.start)
|
||||
await _boot("x_clips", x_clips_pipeline.start)
|
||||
await _boot("yt_long", yt_long_pipeline.start)
|
||||
|
||||
asyncio.create_task(_start_workers())
|
||||
yield
|
||||
@ -1201,6 +1198,10 @@ async def yt_long_start() -> dict[str, Any]:
|
||||
@app.post("/api/yt-long/stop")
|
||||
async def yt_long_stop() -> dict[str, Any]:
|
||||
db.update_settings_map({"yt_long_enabled": False})
|
||||
try:
|
||||
await yt_long_pipeline.stop()
|
||||
except Exception:
|
||||
pass
|
||||
return yt_long_pipeline.status()
|
||||
|
||||
|
||||
|
||||
@ -421,7 +421,22 @@ class MonitorService:
|
||||
try:
|
||||
await self.check_one(room)
|
||||
except Exception as exc:
|
||||
self.last_error = str(exc)
|
||||
self.last_error = str(exc)[:240]
|
||||
try:
|
||||
rid = str(room.get("id") or "")
|
||||
errs = int(room.get("error_count") or 0) + 1
|
||||
nxt = time.time() + self._next_interval(
|
||||
cfg, live=False, errors=errs, priority=self._is_priority(room)
|
||||
)
|
||||
db.touch_room(
|
||||
rid,
|
||||
last_status=str(room.get("last_status") or "unknown"),
|
||||
last_error=str(exc)[:240],
|
||||
error_count=errs,
|
||||
next_check_at=nxt,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
await asyncio.gather(*[_wrapped(r) for r in rooms[:concurrency]])
|
||||
await asyncio.sleep(0.2)
|
||||
|
||||
@ -649,7 +649,12 @@ class TikTokPipeline:
|
||||
)
|
||||
return
|
||||
if not tiktok_session.channel_has_session(channel):
|
||||
tiktok_db.update_tiktok_job(jid, status="scheduled", error="账号未配置 Cookie")
|
||||
tiktok_db.update_tiktok_job(
|
||||
jid,
|
||||
status="scheduled",
|
||||
upload_at=time.time() + 1800,
|
||||
error="账号未配置 Cookie(已延后 30 分钟再试)",
|
||||
)
|
||||
return
|
||||
# 文案 = 账号自定义模板(+1) + DB 中 100 条英文 street food 随机其一
|
||||
from . import caption_pool
|
||||
|
||||
@ -11,7 +11,7 @@ from .db import _connect, _lock, _row_to_dict
|
||||
from .timeutil import push_date_from_ts
|
||||
|
||||
# Quota-consuming statuses (posting pipeline has claimed a daily slot)
|
||||
_QUOTA_STATUSES = ("scheduled", "posting", "posted")
|
||||
_QUOTA_STATUSES = ("pending", "recording", "scheduled", "posting", "posted")
|
||||
|
||||
X_CLIPS_DAILY_DEFAULT = 20
|
||||
|
||||
|
||||
@ -397,6 +397,22 @@ class XClipsPipeline:
|
||||
self._active_records += 1
|
||||
asyncio.create_task(self._run_record(job))
|
||||
|
||||
# Auto-resume posting after Beijing day rolls past pause date
|
||||
try:
|
||||
paused_day = str(cfg.get("x_clips_auto_post_paused_date") or "").strip()
|
||||
if paused_day and not cfg.get("x_clips_auto_post", True):
|
||||
from .timeutil import push_date_from_ts
|
||||
|
||||
today = push_date_from_ts(time.time())
|
||||
if today > paused_day:
|
||||
db.update_settings_map(
|
||||
{"x_clips_auto_post": True, "x_clips_auto_post_paused_date": ""}
|
||||
)
|
||||
cfg["x_clips_auto_post"] = True
|
||||
cfg["x_clips_auto_post_paused_date"] = ""
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if cfg.get("x_clips_auto_post", True):
|
||||
max_post = max(1, int(cfg.get("x_clips_max_concurrent") or 1))
|
||||
while self._active_posts < max_post:
|
||||
@ -647,11 +663,23 @@ class XClipsPipeline:
|
||||
self._on_x_daily_post_limit(err)
|
||||
|
||||
def _on_x_daily_post_limit(self, err: str) -> None:
|
||||
"""Pause auto-post, skip remaining clips today, cancel queued engage.post."""
|
||||
"""Pause auto-post until next Beijing day; skip remaining clips today; cancel queued posts."""
|
||||
try:
|
||||
db.update_settings_map({"x_clips_auto_post": False})
|
||||
from .timeutil import push_date_from_ts
|
||||
|
||||
day = push_date_from_ts(time.time())
|
||||
# Pause for today only — next Beijing day auto-resume via status/loop check
|
||||
db.update_settings_map(
|
||||
{
|
||||
"x_clips_auto_post": False,
|
||||
"x_clips_auto_post_paused_date": day,
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
db.update_settings_map({"x_clips_auto_post": False})
|
||||
except Exception:
|
||||
pass
|
||||
skipped = 0
|
||||
cancelled = 0
|
||||
try:
|
||||
@ -662,12 +690,12 @@ class XClipsPipeline:
|
||||
cancelled = x2_db.cancel_queued_engage_posts(reason="x_daily_post_limit")
|
||||
except Exception:
|
||||
pass
|
||||
self.last_error = "X 每日发帖上限,已暂停自动发帖"
|
||||
self.last_error = "X 每日发帖上限,已暂停自动发帖(今日)"
|
||||
try:
|
||||
db.add_event(
|
||||
kind="x_clips",
|
||||
level="error",
|
||||
message=f"X 触发每日发帖上限,已暂停自动发帖(跳过 {skipped},取消队列 {cancelled})",
|
||||
message=f"X 触发每日发帖上限,已暂停今日自动发帖(跳过 {skipped},取消队列 {cancelled})",
|
||||
meta={"error": str(err)[:240], "skipped": skipped, "cancelled": cancelled},
|
||||
)
|
||||
except Exception:
|
||||
|
||||
@ -205,6 +205,21 @@ def create_yt_long_job(
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
rid = str(room_id or "").strip()
|
||||
if rid:
|
||||
exists = conn.execute(
|
||||
"""
|
||||
SELECT id FROM yt_long_jobs
|
||||
WHERE room_id = ? AND push_date = ?
|
||||
AND status NOT IN ('failed', 'skipped')
|
||||
LIMIT 1
|
||||
""",
|
||||
(rid, day),
|
||||
).fetchone()
|
||||
if exists:
|
||||
return _row_to_dict(
|
||||
conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (exists["id"],)).fetchone()
|
||||
) # type: ignore
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO yt_long_jobs(
|
||||
@ -216,7 +231,7 @@ def create_yt_long_job(
|
||||
(
|
||||
jid,
|
||||
room_pk,
|
||||
room_id,
|
||||
rid,
|
||||
source_url,
|
||||
anchor_name,
|
||||
stream_url,
|
||||
@ -423,9 +438,9 @@ def count_yt_long_jobs_by_status(status: str, *, push_date: str = "") -> int:
|
||||
conn.close()
|
||||
|
||||
|
||||
def reclaim_stale_yt_long_recordings(*, max_age_sec: float = 600) -> int:
|
||||
"""Reclaim orphan recording rows (no worker). Use started_at when present."""
|
||||
age = max(180.0, float(max_age_sec))
|
||||
def reclaim_stale_yt_long_recordings(*, max_age_sec: float = 720) -> int:
|
||||
"""Reclaim orphan recording rows. Never reclaim before ~12 min (3–8 min clip + encode slack)."""
|
||||
age = max(720.0, float(max_age_sec))
|
||||
cutoff = time.time() - age
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
@ -711,7 +726,7 @@ def sync_channels_from_shorts() -> dict[str, Any]:
|
||||
"source_shorts_channel_pk": src,
|
||||
}
|
||||
if existing_id:
|
||||
# Always refresh OAuth + identity from Shorts; keep local daily_max / templates
|
||||
# Refresh OAuth + identity only — never overwrite local enabled/daily_max/templates
|
||||
update_yt_long_channel(
|
||||
existing_id,
|
||||
name=payload["name"],
|
||||
@ -720,7 +735,6 @@ def sync_channels_from_shorts() -> dict[str, Any]:
|
||||
client_id=payload["client_id"],
|
||||
client_secret=payload["client_secret"],
|
||||
refresh_token=payload["refresh_token"],
|
||||
enabled=payload["enabled"],
|
||||
privacy=payload["privacy"],
|
||||
note=payload["note"],
|
||||
)
|
||||
@ -735,8 +749,8 @@ def sync_channels_from_shorts() -> dict[str, Any]:
|
||||
refresh_token=payload["refresh_token"],
|
||||
enabled=payload["enabled"],
|
||||
daily_max=payload["daily_max"],
|
||||
title_template="{anchor} street food live",
|
||||
description_template="{anchor}\n{url}\n#StreetFood #Live",
|
||||
title_template="",
|
||||
description_template="",
|
||||
privacy=payload["privacy"],
|
||||
note=payload["note"],
|
||||
source_shorts_channel_pk=src,
|
||||
|
||||
@ -41,8 +41,14 @@ def build_yt_long_copy(job: dict[str, Any], channel: dict[str, Any], cfg: dict[s
|
||||
"""Random SEO title + description (independent rolls; +1 channel custom each)."""
|
||||
from .yt_long_seo import pick_yt_long_seo
|
||||
|
||||
title_tpl = str(cfg.get("yt_long_title_template") or channel.get("title_template") or "")
|
||||
desc_tpl = str(cfg.get("yt_long_description_template") or channel.get("description_template") or "")
|
||||
# Channel template wins; global settings only as fallback when channel is empty
|
||||
title_tpl = str(channel.get("title_template") or cfg.get("yt_long_title_template") or "").strip()
|
||||
desc_tpl = str(channel.get("description_template") or cfg.get("yt_long_description_template") or "").strip()
|
||||
# Ignore legacy global placeholders so the 100 SEO pool is used by default
|
||||
if title_tpl in {"{anchor} street food live", "{anchor}"}:
|
||||
title_tpl = ""
|
||||
if desc_tpl in {"{anchor}\n{url}", "{anchor}\n{url}\n#StreetFood #Live"}:
|
||||
desc_tpl = ""
|
||||
anchor = str(job.get("anchor_name") or job.get("room_id") or "live").strip()
|
||||
url = str(job.get("source_url") or "").strip()
|
||||
room = str(job.get("room_id") or "").strip()
|
||||
@ -78,7 +84,8 @@ def pick_yt_long_channel(cfg: dict[str, Any], push_date: str = "") -> dict[str,
|
||||
except Exception:
|
||||
dmax = 0
|
||||
used = yt_long_db.channel_quota_used(cid, day)
|
||||
if dmax > 0 and used >= dmax:
|
||||
# daily_max <= 0 means closed for new assigns (not unlimited)
|
||||
if dmax <= 0 or used >= dmax:
|
||||
continue
|
||||
scored.append((float(ch.get("last_assigned_at") or 0), ch))
|
||||
if not scored:
|
||||
@ -394,10 +401,7 @@ class YtLongPipeline:
|
||||
async def kick_pending_records(self, ids: list[str] | None = None) -> int:
|
||||
cfg = db.get_settings_map()
|
||||
max_rec = max(1, int(cfg.get("yt_long_max_concurrent") or 1))
|
||||
try:
|
||||
yt_long_db.reclaim_stale_yt_long_recordings(max_age_sec=180)
|
||||
except Exception:
|
||||
pass
|
||||
# Never reclaim active long recordings here (3–8 min + encode); loop handles orphans safely
|
||||
db_recording = yt_long_db.count_yt_long_jobs_by_status("recording")
|
||||
slots = max(0, max_rec - max(self._active_records, db_recording))
|
||||
if slots <= 0:
|
||||
@ -432,9 +436,9 @@ class YtLongPipeline:
|
||||
if n:
|
||||
self.sampled += n
|
||||
try:
|
||||
# Long clips are 3–8 min; reclaim orphans after ~10 min wall clock
|
||||
# Long clips are 3–8 min (+ ffmpeg slack); reclaim only true orphans
|
||||
max_clip = int(cfg.get("yt_long_max_sec") or YT_LONG_MAX_SEC)
|
||||
yt_long_db.reclaim_stale_yt_long_recordings(max_age_sec=max(600, max_clip + 120))
|
||||
yt_long_db.reclaim_stale_yt_long_recordings(max_age_sec=max(720, max_clip + 240))
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
@ -444,13 +448,25 @@ class YtLongPipeline:
|
||||
|
||||
max_rec = max(1, int(cfg.get("yt_long_max_concurrent") or 1))
|
||||
db_recording = yt_long_db.count_yt_long_jobs_by_status("recording")
|
||||
# If DB has more recording rows than live tasks, they are orphans — force reclaim
|
||||
if db_recording > self._active_records:
|
||||
try:
|
||||
yt_long_db.reclaim_stale_yt_long_recordings(max_age_sec=90)
|
||||
db_recording = yt_long_db.count_yt_long_jobs_by_status("recording")
|
||||
except Exception:
|
||||
pass
|
||||
# If in-flight + done already fills daily_max, soft-skip leftover pending
|
||||
try:
|
||||
from .timeutil import push_date_from_ts as _pday
|
||||
|
||||
dmax = yt_long_db.yt_long_daily_max(cfg)
|
||||
day = _pday(time.time())
|
||||
inflight = 0
|
||||
for st_name in ("recording", "recorded", "scheduled", "uploading", "uploaded"):
|
||||
inflight += yt_long_db.count_yt_long_jobs_by_status(st_name, push_date=day)
|
||||
if dmax > 0 and inflight >= dmax:
|
||||
for pj in yt_long_db.list_pending_yt_long_jobs(limit=30):
|
||||
yt_long_db.update_yt_long_job(
|
||||
str(pj.get("id") or ""),
|
||||
status="skipped",
|
||||
error="daily_quota_full",
|
||||
finished_at=time.time(),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
while self._active_records < max_rec and db_recording < max_rec:
|
||||
pending = yt_long_db.list_pending_yt_long_jobs(limit=1)
|
||||
if not pending:
|
||||
@ -596,7 +612,8 @@ class YtLongPipeline:
|
||||
yt_long_db.update_yt_long_job(
|
||||
jid,
|
||||
status="scheduled",
|
||||
error="频道未授权 Google",
|
||||
upload_at=time.time() + 1800,
|
||||
error="频道未授权 Google(已延后 30 分钟再试)",
|
||||
)
|
||||
return
|
||||
copy = build_yt_long_copy(fresh, channel, cfg)
|
||||
|
||||
@ -406,12 +406,8 @@ export default function YtLongPage() {
|
||||
|
||||
<div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
|
||||
{[
|
||||
[
|
||||
"北京日配额",
|
||||
`${totals.used} / ${totals.cap || status?.daily_max || "—"}`,
|
||||
beijingWindow ? `${beijingWindow}(北京时间)` : "按各频道日上限合计",
|
||||
],
|
||||
["当日缺口", String(quotaGap), `全局上限 ${status?.daily_max ?? "—"} · 频道合计缺口 ${totals.gap}`],
|
||||
["北京日配额", `${status?.quota_used ?? 0} / ${status?.daily_max ?? "—"}`, beijingWindow ? `${beijingWindow}(北京时间 · 全局)` : "全局日上限"],
|
||||
["当日缺口", String(quotaGap), `频道合计缺口 ${totals.gap}`],
|
||||
["已上传", String(totals.uploaded), `排队 ${totals.scheduled}`],
|
||||
[
|
||||
"抖音在播源",
|
||||
|
||||
Loading…
Reference in New Issue
Block a user