File size: 9,563 Bytes
851e5ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
"""
Worker tasks - background jobs processed by arq workers.
"""

import logging
from typing import Dict, Any, Optional
import json
from arq import Retry, cron
from arq.worker import func
from .media_cleanup import cleanup_media, sweep_orphaned_media
from .media_replication import check_media_storage, replicate_pending_media
from ..repositories.task_run_guard import TaskRunBusy

from ..observability import configure_logging, set_trace_id, set_user_id

configure_logging()

logger = logging.getLogger(__name__)


async def process_video_task(
    ctx: Dict[str, Any],
    task_id: str,
    url: str,
    source_type: str,
    user_id: str,
    font_family: Optional[str] = None,
    font_size: Optional[int] = None,
    font_color: Optional[str] = None,
    caption_template: str = "default",
    processing_mode: str = "fast",
    output_format: str = "vertical",
    add_subtitles: bool = True,
    cleanup_settings: Dict[str, Any] | None = None,
    clip_length: str = "auto",
) -> Dict[str, Any]:
    """
    Background worker task to process a video.

    Args:
        ctx: arq context (provides Redis connection and other utilities)
        task_id: Task ID to update
        url: Video URL or file path
        source_type: "youtube" or "upload"
        user_id: User ID who created the task
        font_family: Font family for subtitles
        font_size: Font size for subtitles
        font_color: Font color for subtitles

    Returns:
        Dict with processing results
    """
    from ..database import AsyncSessionLocal
    from ..runtime_settings import load_runtime_settings_cache
    from ..services.task_service import TaskService
    from ..workers.progress import ProgressTracker

    set_trace_id(f"task-{task_id}")
    set_user_id(user_id)
    logger.info(f"Worker processing task {task_id}")

    # Create progress tracker
    progress = ProgressTracker(ctx["redis"], task_id)

    async with AsyncSessionLocal() as db:
        await load_runtime_settings_cache(db)
        task_service = TaskService(db)

        try:
            # Progress callback
            async def update_progress(
                percent: int, message: str, status: str = "processing"
            ):
                await progress.update(percent, message, status)
                logger.info(f"Task {task_id}: {percent}% - {message}")

            async def should_cancel() -> bool:
                cancelled = await ctx["redis"].get(f"task_cancel:{task_id}")
                return bool(cancelled)

            async def clip_ready_callback(
                clip_index: int, total_clips: int, clip_data: dict
            ):
                await progress.clip_ready(clip_index, total_clips, clip_data)

            # Process the video
            result = await task_service.process_task(
                task_id=task_id,
                url=url,
                source_type=source_type,
                user_id=user_id,
                font_family=font_family,
                font_size=font_size,
                font_color=font_color,
                caption_template=caption_template,
                processing_mode=processing_mode,
                output_format=output_format,
                add_subtitles=add_subtitles,
                progress_callback=update_progress,
                should_cancel=should_cancel,
                clip_ready_callback=clip_ready_callback,
                cleanup_settings=cleanup_settings,
                clip_length=clip_length,
            )

            logger.info(f"Task {task_id} completed successfully")
            return result

        except TaskRunBusy:
            # A resume request may still own the guard while publishing this job.
            # Retry without rewriting task state or creating a dead-letter entry.
            raise Retry(defer=2)
        except Exception as e:
            logger.error(f"Task {task_id} failed: {e}", exc_info=True)
            try:
                job_try = int(ctx.get("job_try", 1))
                max_tries = int(getattr(WorkerSettings, "max_tries", 3))
                if job_try >= max_tries:
                    payload = {
                        "task_id": task_id,
                        "error": str(e),
                        "tries": job_try,
                    }
                    await ctx["redis"].set(
                        f"dead_letter:{task_id}", json.dumps(payload)
                    )
                    await ctx["redis"].sadd("tasks:dead_letter", task_id)
                    await progress.error("Task failed permanently after retries")
            except Exception:
                logger.exception("Failed to persist dead-letter payload")
            # Error will be caught by arq and task status will be updated
            raise


async def _social_service(db):
    from ..runtime_settings import load_runtime_settings_cache
    from ..services.social_service import SocialService

    await load_runtime_settings_cache(db)
    return SocialService(db)


async def publish_social_post(ctx: Dict[str, Any], post_id: str) -> Dict[str, Any]:
    """Upload one queued social post to its platform."""
    from ..database import AsyncSessionLocal

    set_trace_id(f"social-{post_id}")
    logger.info("Worker publishing social post %s", post_id)
    async with AsyncSessionLocal() as db:
        service = await _social_service(db)
        try:
            post = await service.publish_post(post_id)
        except Exception as exc:
            # Failures are recorded on the post row; never let arq retry blindly.
            # Cancellation (job timeout, shutdown) propagates; the stale
            # publishing sweep fails that post. Logged without a traceback
            # because provider errors can carry request URLs.
            from ..social.base import redact

            logger.error(
                "Publishing social post %s crashed (%s): %s",
                post_id,
                type(exc).__name__,
                redact(exc),
            )
            return {"post_id": post_id, "status": "error"}
    return {"post_id": post_id, "status": post.get("status")}


async def dispatch_scheduled_social_posts(ctx: Dict[str, Any]) -> Dict[str, Any]:
    """Cron: move due scheduled posts onto the publish queue."""
    from ..database import AsyncSessionLocal

    async with AsyncSessionLocal() as db:
        service = await _social_service(db)
        dispatched = await service.dispatch_scheduled_posts()
        resolved = await service.resolve_pending_posts()
        # Covers workers that crashed or were cancelled mid-upload.
        swept = await service.sweep_stale_publishing()
    return {
        "dispatched": len(dispatched),
        "pending_checked": resolved,
        "stale_failed": len(swept),
    }


async def refresh_social_metrics(ctx: Dict[str, Any]) -> Dict[str, Any]:
    """Cron: pull fresh audience metrics for recently published posts."""
    from ..database import AsyncSessionLocal
    from ..repositories.social_repository import SocialRepository

    async with AsyncSessionLocal() as db:
        service = await _social_service(db)
        refreshed = await service.refresh_due_metrics()
        purged = await SocialRepository.purge_expired_oauth_states(db)
    return {"refreshed": refreshed, "purged_oauth_states": purged}


from ..services.editor_service import prepare_editor, export_editor, combine_editor
from ..services.clip_export_service import (
    CLIP_EXPORT_JOB_TIMEOUT_SECONDS,
    export_clip_preset,
)
from ..services.social_service import PUBLISH_JOB_TIMEOUT_SECONDS

# Worker configuration for arq
class WorkerSettings:
    """Configuration for arq worker."""

    from ..config import Config
    from arq.connections import RedisSettings

    config = Config()

    # Functions to run
    functions = [
        process_video_task,
        prepare_editor,
        export_editor,
        combine_editor,
        # One try: a lost running export is failed by the heartbeat sweep, and a
        # retry would start a second encode for the same row.
        func(
            export_clip_preset,
            timeout=CLIP_EXPORT_JOB_TIMEOUT_SECONDS,
            max_tries=1,
        ),
        # Results are not kept so a finished job's id ("social:{post}:{attempt}")
        # frees up; a dead job's post is failed by the stale-publishing sweep.
        func(publish_social_post, timeout=PUBLISH_JOB_TIMEOUT_SECONDS, keep_result=0),
    ]
    queue_name = "supoclip_tasks"
    health_check_interval = 30

    # Redis settings from environment
    redis_settings = RedisSettings(
        host=config.redis_host, port=config.redis_port, password=config.redis_password, database=0
    )

    # Retry settings
    max_tries = 3  # Retry failed jobs up to 3 times
    job_timeout = 10800  # 3 hour timeout for video processing

    # Worker pool settings
    max_jobs = 4  # Process up to 4 jobs simultaneously
    cron_jobs = [
        cron(check_media_storage, second=20, run_at_startup=True, timeout=120),
        cron(replicate_pending_media, second=40, run_at_startup=True, timeout=1800),
        cron(cleanup_media, minute={0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55}, run_at_startup=True),
        cron(sweep_orphaned_media, hour={0, 6, 12, 18}, minute=15),
        # Every minute: promote due scheduled posts and poll async publishes.
        cron(dispatch_scheduled_social_posts, second=0, timeout=300),
        # Hourly: pull audience metrics back for the performance loop.
        cron(refresh_social_metrics, minute=7, second=0, timeout=1800),
    ]