feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
"""Background scheduler: free RSS detection, enrichment of new videos, and quota-aware
|
|
|
|
|
recent-first / deep backfill. Runs inside the API process (single worker)."""
|
2026-06-18 04:01:10 +02:00
|
|
|
import contextvars
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
import logging
|
2026-06-16 14:38:51 +02:00
|
|
|
import threading
|
|
|
|
|
from datetime import datetime, timezone
|
2026-06-18 04:01:10 +02:00
|
|
|
from typing import Callable
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
|
|
|
|
|
from apscheduler.schedulers.background import BackgroundScheduler
|
2026-06-16 15:58:23 +02:00
|
|
|
from sqlalchemy import select
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
|
2026-06-18 04:01:10 +02:00
|
|
|
from app import progress, quota
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
from app.config import settings
|
|
|
|
|
from app.db import SessionLocal
|
2026-06-16 15:58:23 +02:00
|
|
|
from app.models import SchedulerSetting
|
2026-06-18 04:01:10 +02:00
|
|
|
from app.notifications import create_notification
|
2026-06-11 04:15:25 +02:00
|
|
|
from app.state import is_sync_paused
|
2026-06-11 01:57:19 +02:00
|
|
|
from app.sync.autotag import run_autotag_all
|
2026-06-18 03:20:28 +02:00
|
|
|
from app.sync.maintenance import run_maintenance
|
2026-06-15 19:37:03 +02:00
|
|
|
from app.sync.playlists import sync_all_playlists
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
from app.sync.runner import (
|
|
|
|
|
run_deep_backfill,
|
|
|
|
|
run_enrich,
|
|
|
|
|
run_recent_backfill,
|
|
|
|
|
run_rss_poll,
|
fix: address reader-UI feedback (shorts, search, tags, login, UX)
- Shorts: confirm via youtube.com/shorts/<id> probe (SOCS cookie bypasses the
consent redirect) instead of a 60s heuristic; concurrent probing, shorts_probed
flag, scheduled refinement (migration 0005)
- Search: match title + channel name only (descriptions caused noisy results)
- Faceted tag filtering: AND across categories (language AND topic narrows),
OR within a category; any/all toggle applies to topics
- Language detection: majority vote over individual titles (fixes misdetections
like multipoleguy -> English; drops bogus Polish/Romanian)
- Login: drop forced consent so returning sign-in is quick (select_account)
- Feed cards: clickable channel name (opens channel), persistent saved badge,
undo toast on hide, Hidden view to restore; tag chips show counts in tooltip
2026-06-11 03:07:49 +02:00
|
|
|
run_shorts,
|
2026-06-11 03:28:45 +02:00
|
|
|
run_subscription_resync,
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger("subfeed.scheduler")
|
|
|
|
|
|
|
|
|
|
_scheduler: BackgroundScheduler | None = None
|
|
|
|
|
|
2026-06-16 14:38:51 +02:00
|
|
|
# Per-job run activity, kept in-memory for the admin Scheduler dashboard to read (the
|
|
|
|
|
# scheduler lives in the same single-worker process as the API, so a request can read it
|
|
|
|
|
# directly). Ephemeral by design — it reflects "what the scheduler is doing right now and
|
|
|
|
|
# how the last runs went" since this process started; durable history isn't the goal here.
|
|
|
|
|
_activity: dict[str, dict] = {}
|
|
|
|
|
_activity_lock = threading.Lock()
|
|
|
|
|
|
2026-06-18 04:01:10 +02:00
|
|
|
# Set (per-thread) by a manual "run now" trigger to the id of the admin who clicked, so that
|
|
|
|
|
# run — and only that run, not the recurring scheduled ones — posts a completion notification
|
|
|
|
|
# to their inbox. Unset (None) for scheduled runs.
|
|
|
|
|
_manual_actor: contextvars.ContextVar[int | None] = contextvars.ContextVar(
|
|
|
|
|
"manual_actor", default=None
|
|
|
|
|
)
|
|
|
|
|
|
2026-06-16 15:58:23 +02:00
|
|
|
# Each interval job's env/config default period (minutes). The admin can override any of
|
|
|
|
|
# these at runtime (stored in scheduler_settings, applied live); see load_intervals.
|
2026-06-16 14:38:51 +02:00
|
|
|
JOB_INTERVALS: dict[str, int] = {
|
|
|
|
|
"rss_poll": settings.rss_poll_minutes,
|
|
|
|
|
"enrich": settings.enrich_interval_minutes,
|
|
|
|
|
"backfill": settings.backfill_interval_minutes,
|
|
|
|
|
"autotag": settings.autotag_interval_minutes,
|
|
|
|
|
"shorts": settings.shorts_probe_interval_minutes,
|
|
|
|
|
"subscriptions": settings.subscriptions_resync_minutes,
|
|
|
|
|
"playlist_sync": settings.playlist_sync_minutes,
|
2026-06-18 03:20:28 +02:00
|
|
|
"maintenance": settings.maintenance_interval_minutes,
|
2026-06-19 15:25:13 +02:00
|
|
|
"demo_reset": settings.demo_reset_minutes,
|
2026-06-16 14:38:51 +02:00
|
|
|
}
|
|
|
|
|
|
2026-06-16 15:58:23 +02:00
|
|
|
# Sane bounds for an admin-set interval (minutes).
|
|
|
|
|
MIN_INTERVAL = 1
|
|
|
|
|
MAX_INTERVAL = 1440 # one day
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def load_intervals(db) -> dict[str, int]:
|
|
|
|
|
"""Effective per-job intervals: the env/config defaults overlaid with any admin overrides
|
|
|
|
|
saved in scheduler_settings."""
|
|
|
|
|
iv = dict(JOB_INTERVALS)
|
|
|
|
|
for row in db.execute(select(SchedulerSetting)).scalars():
|
|
|
|
|
if row.job_id in iv and row.interval_minutes:
|
|
|
|
|
iv[row.job_id] = row.interval_minutes
|
|
|
|
|
return iv
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def apply_interval(db, job_id: str, minutes: int) -> int:
|
|
|
|
|
"""Persist a job's interval override and reschedule the live job immediately (if the
|
|
|
|
|
scheduler runs in this process). Returns the applied value."""
|
|
|
|
|
if job_id not in JOB_INTERVALS:
|
|
|
|
|
raise KeyError(job_id)
|
|
|
|
|
minutes = max(MIN_INTERVAL, min(MAX_INTERVAL, int(minutes)))
|
|
|
|
|
row = db.get(SchedulerSetting, job_id)
|
|
|
|
|
if row is None:
|
|
|
|
|
db.add(SchedulerSetting(job_id=job_id, interval_minutes=minutes))
|
|
|
|
|
else:
|
|
|
|
|
row.interval_minutes = minutes
|
|
|
|
|
db.commit()
|
|
|
|
|
if _scheduler is not None and _scheduler.get_job(job_id) is not None:
|
|
|
|
|
_scheduler.reschedule_job(job_id, trigger="interval", minutes=minutes)
|
|
|
|
|
logger.info("rescheduled job %s to every %s min", job_id, minutes)
|
|
|
|
|
return minutes
|
|
|
|
|
|
2026-06-16 14:38:51 +02:00
|
|
|
|
|
|
|
|
def _now_iso() -> str:
|
|
|
|
|
return datetime.now(timezone.utc).isoformat()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _record(name: str, **fields) -> None:
|
|
|
|
|
with _activity_lock:
|
|
|
|
|
_activity.setdefault(name, {}).update(fields)
|
|
|
|
|
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
|
2026-06-18 04:01:10 +02:00
|
|
|
def _notify_done(db, actor_id: int, job_id: str, status: str, summary: str | None) -> None:
|
|
|
|
|
"""Post a completion notice to the triggering admin's inbox (manual runs only). Best
|
|
|
|
|
effort — a notification failure must never mask the job's own outcome."""
|
|
|
|
|
try:
|
|
|
|
|
create_notification(
|
|
|
|
|
db,
|
|
|
|
|
user_id=actor_id,
|
|
|
|
|
type="scheduler",
|
|
|
|
|
title=f"{job_id}: {status}", # English fallback; UI renders translated from data
|
|
|
|
|
body=summary,
|
|
|
|
|
data={"job_id": job_id, "status": status, "summary": summary},
|
|
|
|
|
)
|
|
|
|
|
except Exception:
|
|
|
|
|
db.rollback()
|
|
|
|
|
logger.exception("failed to write completion notification for job %s", job_id)
|
|
|
|
|
|
|
|
|
|
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
def _job(name: str, fn) -> None:
|
|
|
|
|
db = SessionLocal()
|
2026-06-18 04:01:10 +02:00
|
|
|
actor_id = _manual_actor.get() # set only for a manual "run now" trigger
|
|
|
|
|
_record(name, running=True, last_started=_now_iso(), last_error=None, progress=None)
|
|
|
|
|
|
|
|
|
|
def sink(current, total, phase):
|
|
|
|
|
_record(name, progress={"current": current, "total": total, "phase": phase})
|
|
|
|
|
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
try:
|
2026-06-11 04:15:25 +02:00
|
|
|
if is_sync_paused(db):
|
|
|
|
|
logger.info("job %s skipped (sync paused)", name)
|
2026-06-16 14:38:51 +02:00
|
|
|
_record(name, running=False, status="skipped", last_finished=_now_iso(),
|
2026-06-18 04:01:10 +02:00
|
|
|
last_result="paused", progress=None)
|
|
|
|
|
if actor_id is not None:
|
|
|
|
|
_notify_done(db, actor_id, name, "skipped", "sync paused")
|
2026-06-11 04:15:25 +02:00
|
|
|
return
|
2026-06-18 04:01:10 +02:00
|
|
|
with progress.bind(sink):
|
|
|
|
|
result = fn(db)
|
|
|
|
|
summary = _summarize(result)
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
logger.info("job %s -> %s", name, result)
|
2026-06-16 14:38:51 +02:00
|
|
|
_record(name, running=False, status="ok", last_finished=_now_iso(),
|
2026-06-18 04:01:10 +02:00
|
|
|
last_result=summary, progress=None)
|
|
|
|
|
if actor_id is not None:
|
|
|
|
|
_notify_done(db, actor_id, name, "ok", summary)
|
2026-06-16 14:38:51 +02:00
|
|
|
except Exception as exc:
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
db.rollback()
|
|
|
|
|
logger.exception("job %s failed", name)
|
2026-06-18 04:01:10 +02:00
|
|
|
err = str(exc) or exc.__class__.__name__
|
2026-06-16 14:38:51 +02:00
|
|
|
_record(name, running=False, status="error", last_finished=_now_iso(),
|
2026-06-18 04:01:10 +02:00
|
|
|
last_error=err, progress=None)
|
|
|
|
|
if actor_id is not None:
|
|
|
|
|
_notify_done(db, actor_id, name, "error", err)
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
finally:
|
|
|
|
|
db.close()
|
|
|
|
|
|
|
|
|
|
|
2026-06-16 14:38:51 +02:00
|
|
|
def _summarize(result) -> str | None:
|
|
|
|
|
"""Compact one-line rendering of a job's return value for the dashboard."""
|
|
|
|
|
if result is None:
|
|
|
|
|
return None
|
|
|
|
|
if isinstance(result, dict):
|
|
|
|
|
return ", ".join(f"{k}={v}" for k, v in result.items()) or None
|
|
|
|
|
return str(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def scheduler_snapshot() -> dict:
|
|
|
|
|
"""What the scheduler is doing, for the admin dashboard. `running_here` is False in
|
|
|
|
|
environments where the scheduler is disabled (e.g. local dev shares the prod-ish DB but
|
|
|
|
|
runs no scheduler), so the UI can say so while still showing DB-derived queue/quota."""
|
|
|
|
|
running_here = _scheduler is not None
|
|
|
|
|
next_runs: dict[str, str | None] = {}
|
2026-06-16 15:58:23 +02:00
|
|
|
live_intervals: dict[str, int] = {}
|
2026-06-16 14:38:51 +02:00
|
|
|
if _scheduler is not None:
|
|
|
|
|
for job in _scheduler.get_jobs():
|
|
|
|
|
nr = getattr(job, "next_run_time", None)
|
|
|
|
|
next_runs[job.id] = nr.astimezone(timezone.utc).isoformat() if nr else None
|
2026-06-16 15:58:23 +02:00
|
|
|
iv = getattr(job.trigger, "interval", None)
|
|
|
|
|
if iv is not None:
|
|
|
|
|
live_intervals[job.id] = round(iv.total_seconds() / 60)
|
2026-06-16 14:38:51 +02:00
|
|
|
with _activity_lock:
|
|
|
|
|
acts = {k: dict(v) for k, v in _activity.items()}
|
|
|
|
|
jobs = []
|
2026-06-16 15:58:23 +02:00
|
|
|
for job_id, default_interval in JOB_INTERVALS.items():
|
2026-06-16 14:38:51 +02:00
|
|
|
a = acts.get(job_id, {})
|
|
|
|
|
jobs.append(
|
|
|
|
|
{
|
|
|
|
|
"id": job_id,
|
2026-06-16 15:58:23 +02:00
|
|
|
"interval_minutes": live_intervals.get(job_id, default_interval),
|
2026-06-16 14:38:51 +02:00
|
|
|
"next_run": next_runs.get(job_id),
|
|
|
|
|
"running": a.get("running", False),
|
|
|
|
|
"status": a.get("status"),
|
|
|
|
|
"last_started": a.get("last_started"),
|
|
|
|
|
"last_finished": a.get("last_finished"),
|
|
|
|
|
"last_result": a.get("last_result"),
|
|
|
|
|
"last_error": a.get("last_error"),
|
2026-06-18 04:01:10 +02:00
|
|
|
"progress": a.get("progress"),
|
2026-06-16 14:38:51 +02:00
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
return {"running_here": running_here, "enabled": settings.scheduler_enabled, "jobs": jobs}
|
|
|
|
|
|
|
|
|
|
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
def _rss_job() -> None:
|
|
|
|
|
_job("rss_poll", lambda db: run_rss_poll(db))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _enrich_job() -> None:
|
2026-06-12 02:47:55 +02:00
|
|
|
def work(db):
|
2026-06-19 11:48:11 +02:00
|
|
|
with quota.attribute(None, quota.QuotaAction.VIDEOS_ENRICH):
|
2026-06-12 02:47:55 +02:00
|
|
|
return run_enrich(db)
|
|
|
|
|
|
|
|
|
|
_job("enrich", work)
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def _backfill_job() -> None:
|
2026-06-12 02:47:55 +02:00
|
|
|
# Recent-first for not-yet-synced channels, then deep backfill for the rest. All
|
|
|
|
|
# background spend is attributed to the system (no actor), split by action.
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
def work(db):
|
2026-06-19 11:48:11 +02:00
|
|
|
with quota.attribute(None, quota.QuotaAction.VIDEOS_BACKFILL_RECENT):
|
2026-06-12 02:47:55 +02:00
|
|
|
recent = run_recent_backfill(db, max_channels=25)
|
2026-06-19 11:48:11 +02:00
|
|
|
with quota.attribute(None, quota.QuotaAction.VIDEOS_BACKFILL_FULL):
|
2026-06-12 02:47:55 +02:00
|
|
|
deep = run_deep_backfill(db, max_channels=10)
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
return {"recent": recent, "deep": deep}
|
|
|
|
|
|
|
|
|
|
_job("backfill", work)
|
|
|
|
|
|
|
|
|
|
|
2026-06-11 01:57:19 +02:00
|
|
|
def _autotag_job() -> None:
|
|
|
|
|
_job("autotag", lambda db: run_autotag_all(db, only_missing=True))
|
|
|
|
|
|
|
|
|
|
|
fix: address reader-UI feedback (shorts, search, tags, login, UX)
- Shorts: confirm via youtube.com/shorts/<id> probe (SOCS cookie bypasses the
consent redirect) instead of a 60s heuristic; concurrent probing, shorts_probed
flag, scheduled refinement (migration 0005)
- Search: match title + channel name only (descriptions caused noisy results)
- Faceted tag filtering: AND across categories (language AND topic narrows),
OR within a category; any/all toggle applies to topics
- Language detection: majority vote over individual titles (fixes misdetections
like multipoleguy -> English; drops bogus Polish/Romanian)
- Login: drop forced consent so returning sign-in is quick (select_account)
- Feed cards: clickable channel name (opens channel), persistent saved badge,
undo toast on hide, Hidden view to restore; tag chips show counts in tooltip
2026-06-11 03:07:49 +02:00
|
|
|
def _shorts_job() -> None:
|
|
|
|
|
_job("shorts", run_shorts)
|
|
|
|
|
|
|
|
|
|
|
2026-06-11 03:28:45 +02:00
|
|
|
def _subscriptions_job() -> None:
|
2026-06-12 02:47:55 +02:00
|
|
|
def work(db):
|
2026-06-19 11:48:11 +02:00
|
|
|
with quota.attribute(None, quota.QuotaAction.SUBSCRIPTIONS_RESYNC):
|
2026-06-12 02:47:55 +02:00
|
|
|
return run_subscription_resync(db)
|
|
|
|
|
|
|
|
|
|
_job("subscriptions", work)
|
2026-06-11 03:28:45 +02:00
|
|
|
|
|
|
|
|
|
2026-06-15 19:37:03 +02:00
|
|
|
def _playlist_sync_job() -> None:
|
|
|
|
|
# Mirror each read-scope user's YouTube playlists; per-user quota attribution is
|
|
|
|
|
# handled inside sync_all_playlists.
|
|
|
|
|
_job("playlist_sync", sync_all_playlists)
|
|
|
|
|
|
|
|
|
|
|
2026-06-18 03:20:28 +02:00
|
|
|
def _maintenance_job() -> None:
|
|
|
|
|
def work(db):
|
2026-06-19 11:48:11 +02:00
|
|
|
with quota.attribute(None, quota.QuotaAction.MAINTENANCE_REVALIDATE):
|
2026-06-18 03:20:28 +02:00
|
|
|
return run_maintenance(db)
|
|
|
|
|
|
|
|
|
|
_job("maintenance", work)
|
|
|
|
|
|
|
|
|
|
|
2026-06-19 15:25:13 +02:00
|
|
|
def _demo_reset_job() -> None:
|
|
|
|
|
# Auto-clean the shared demo sandbox. No-op (and never creates one) if there's no demo
|
|
|
|
|
# account. Lazy import avoids a routes<->scheduler import cycle.
|
|
|
|
|
def work(db):
|
|
|
|
|
from app.models import User
|
|
|
|
|
demo = db.query(User).filter(User.is_demo.is_(True)).one_or_none()
|
|
|
|
|
if demo is None:
|
|
|
|
|
return {"skipped": "no demo account"}
|
|
|
|
|
from app.routes.admin import reset_demo_state
|
|
|
|
|
return {"playlists_seeded": reset_demo_state(db, demo)}
|
|
|
|
|
|
|
|
|
|
_job("demo_reset", work)
|
|
|
|
|
|
|
|
|
|
|
2026-06-18 04:01:10 +02:00
|
|
|
# job_id -> wrapper. The single source of truth for which jobs exist and how to run one,
|
|
|
|
|
# shared by start_scheduler (recurring registration) and trigger_job (manual "run now").
|
|
|
|
|
JOB_FUNCS: dict[str, Callable[[], None]] = {
|
|
|
|
|
"rss_poll": _rss_job,
|
|
|
|
|
"enrich": _enrich_job,
|
|
|
|
|
"backfill": _backfill_job,
|
|
|
|
|
"autotag": _autotag_job,
|
|
|
|
|
"shorts": _shorts_job,
|
|
|
|
|
"subscriptions": _subscriptions_job,
|
|
|
|
|
"playlist_sync": _playlist_sync_job,
|
|
|
|
|
"maintenance": _maintenance_job,
|
2026-06-19 15:25:13 +02:00
|
|
|
"demo_reset": _demo_reset_job,
|
2026-06-18 04:01:10 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _is_running(job_id: str) -> bool:
|
|
|
|
|
with _activity_lock:
|
|
|
|
|
return bool(_activity.get(job_id, {}).get("running"))
|
|
|
|
|
|
|
|
|
|
|
2026-06-19 02:57:45 +02:00
|
|
|
def running_job_ids() -> set[str]:
|
|
|
|
|
"""Ids of jobs executing right now (any trigger). Lets non-admin surfaces — e.g. the
|
|
|
|
|
header's sync indicator — reflect real activity instead of just pending-work counts."""
|
|
|
|
|
with _activity_lock:
|
|
|
|
|
return {jid for jid, a in _activity.items() if a.get("running")}
|
|
|
|
|
|
|
|
|
|
|
2026-06-18 04:01:10 +02:00
|
|
|
def trigger_job(job_id: str, actor_id: int | None = None) -> str:
|
|
|
|
|
"""Run a job immediately in a background thread, independent of its interval schedule.
|
|
|
|
|
The wrapper handles its own DB session, activity tracking and pause-skip, so the live
|
|
|
|
|
dashboard reflects the run. Returns "started", "already_running", or raises KeyError for
|
|
|
|
|
an unknown job. Refusing a concurrent run keeps a manual trigger from overlapping a
|
|
|
|
|
scheduled run (APScheduler enforces max_instances=1 for the scheduled side).
|
|
|
|
|
|
|
|
|
|
`actor_id` (the admin who clicked "run now") is stashed in a contextvar inside the new
|
|
|
|
|
thread so the run posts a completion notification to that admin's inbox."""
|
|
|
|
|
fn = JOB_FUNCS.get(job_id)
|
|
|
|
|
if fn is None:
|
|
|
|
|
raise KeyError(job_id)
|
|
|
|
|
if _is_running(job_id):
|
|
|
|
|
return "already_running"
|
|
|
|
|
|
|
|
|
|
def run() -> None:
|
|
|
|
|
if actor_id is not None:
|
|
|
|
|
_manual_actor.set(actor_id)
|
|
|
|
|
fn()
|
|
|
|
|
|
|
|
|
|
threading.Thread(target=run, name=f"trigger-{job_id}", daemon=True).start()
|
|
|
|
|
return "started"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def trigger_all(actor_id: int | None = None) -> list[str]:
|
|
|
|
|
"""Trigger every job that isn't already running; returns the ids actually started."""
|
|
|
|
|
started = []
|
|
|
|
|
for job_id in JOB_FUNCS:
|
|
|
|
|
if trigger_job(job_id, actor_id) == "started":
|
|
|
|
|
started.append(job_id)
|
|
|
|
|
return started
|
|
|
|
|
|
|
|
|
|
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
def start_scheduler() -> None:
|
|
|
|
|
global _scheduler
|
|
|
|
|
if not settings.scheduler_enabled or _scheduler is not None:
|
|
|
|
|
return
|
2026-06-16 15:58:23 +02:00
|
|
|
# Effective intervals = env defaults overlaid with any admin overrides from the DB.
|
|
|
|
|
db = SessionLocal()
|
|
|
|
|
try:
|
|
|
|
|
iv = load_intervals(db)
|
|
|
|
|
finally:
|
|
|
|
|
db.close()
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
scheduler = BackgroundScheduler(timezone="UTC")
|
2026-06-18 04:01:10 +02:00
|
|
|
for job_id, fn in JOB_FUNCS.items():
|
2026-06-16 15:58:23 +02:00
|
|
|
scheduler.add_job(fn, "interval", minutes=iv[job_id], id=job_id)
|
feat: M2 (part 2) — RSS poller, backfill, enrichment, scheduler
- Free per-channel RSS reader for quota-less fresh-video detection
- Recent-first backfill (configurable: 100 videos / 1 year) plus resumable deep
backfill from the uploads playlist
- Enrichment via videos.list: duration, view/like counts, category, topics,
language, Shorts heuristic and livestream/premiere classification
- Reusable sync runners + APScheduler jobs (rss / enrich / backfill), all
quota-aware with a reserve so backfill never starves fresh enrichment
- Manual triggers: POST /api/sync/{rss,backfill,enrich}
- Exact insert counting via RETURNING with in-batch de-duplication
2026-06-11 01:36:41 +02:00
|
|
|
scheduler.start()
|
|
|
|
|
_scheduler = scheduler
|
|
|
|
|
logger.info("scheduler started")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def shutdown_scheduler() -> None:
|
|
|
|
|
global _scheduler
|
|
|
|
|
if _scheduler is not None:
|
|
|
|
|
_scheduler.shutdown(wait=False)
|
|
|
|
|
_scheduler = None
|