Monteeq CI commited on
Commit
02c1fe3
·
1 Parent(s): cbf7ff4

🚀 Deploy from GitHub @ c7c11eb07b319cec1e9d85c4c05969ab77322faf

Browse files

Triggered by: Smasduq
Message: Merge pull request #17 from Monteeq/feat/async-upload-jobs-gunicorn

Feat/async upload jobs gunicorn

Dockerfile CHANGED
@@ -28,5 +28,5 @@ RUN chmod +x start.sh
28
  # Hugging Face Spaces requires port 7860
29
  EXPOSE 7860
30
 
31
- # Start Celery worker in background, then launch uvicorn on port 7860
32
  CMD ["./start.sh"]
 
28
  # Hugging Face Spaces requires port 7860
29
  EXPOSE 7860
30
 
31
+ # Celery (background) + gunicorn with 2–4 uvicorn workers (see start.sh)
32
  CMD ["./start.sh"]
alembic/versions/a8c3e1f2b4d6_add_upload_jobs_table.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """add upload_jobs table
2
+
3
+ Revision ID: a8c3e1f2b4d6
4
+ Revises: 1cb317046980
5
+ Create Date: 2026-07-20 21:05:00.000000
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+ from sqlalchemy.dialects import postgresql
13
+
14
+
15
+ # revision identifiers, used by Alembic.
16
+ revision: str = "a8c3e1f2b4d6"
17
+ down_revision: Union[str, Sequence[str], None] = "1cb317046980"
18
+ branch_labels: Union[str, Sequence[str], None] = None
19
+ depends_on: Union[str, Sequence[str], None] = None
20
+
21
+
22
+ def upgrade() -> None:
23
+ op.create_table(
24
+ "upload_jobs",
25
+ sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True, nullable=False),
26
+ sa.Column("user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
27
+ sa.Column("status", sa.String(), nullable=False, server_default="uploading"),
28
+ sa.Column("video_id", sa.Integer(), sa.ForeignKey("videos.id", ondelete="SET NULL"), nullable=True),
29
+ sa.Column("error_message", sa.Text(), nullable=True),
30
+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
31
+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
32
+ )
33
+ op.create_index("ix_upload_jobs_user_id", "upload_jobs", ["user_id"])
34
+ op.create_index("ix_upload_jobs_status", "upload_jobs", ["status"])
35
+ op.create_index("ix_upload_jobs_video_id", "upload_jobs", ["video_id"])
36
+ op.create_index("ix_upload_jobs_user_status", "upload_jobs", ["user_id", "status"])
37
+
38
+
39
+ def downgrade() -> None:
40
+ op.drop_index("ix_upload_jobs_user_status", table_name="upload_jobs")
41
+ op.drop_index("ix_upload_jobs_video_id", table_name="upload_jobs")
42
+ op.drop_index("ix_upload_jobs_status", table_name="upload_jobs")
43
+ op.drop_index("ix_upload_jobs_user_id", table_name="upload_jobs")
44
+ op.drop_table("upload_jobs")
alembic/versions/b4d7e9a1c2f3_add_cover_fields_to_upload_jobs.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """add cover_source and cover_s3_key to upload_jobs
2
+
3
+ Revision ID: b4d7e9a1c2f3
4
+ Revises: a8c3e1f2b4d6
5
+ Create Date: 2026-07-21 00:10:00.000000
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+
13
+
14
+ revision: str = "b4d7e9a1c2f3"
15
+ down_revision: Union[str, Sequence[str], None] = "a8c3e1f2b4d6"
16
+ branch_labels: Union[str, Sequence[str], None] = None
17
+ depends_on: Union[str, Sequence[str], None] = None
18
+
19
+
20
+ def upgrade() -> None:
21
+ op.add_column(
22
+ "upload_jobs",
23
+ sa.Column("cover_source", sa.String(), nullable=False, server_default="auto"),
24
+ )
25
+ op.add_column(
26
+ "upload_jobs",
27
+ sa.Column("cover_s3_key", sa.String(), nullable=True),
28
+ )
29
+
30
+
31
+ def downgrade() -> None:
32
+ op.drop_column("upload_jobs", "cover_s3_key")
33
+ op.drop_column("upload_jobs", "cover_source")
alembic/versions/c1d2e3f4a5b6_add_video_type_to_upload_jobs.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """add video_type to upload_jobs
2
+
3
+ Revision ID: c1d2e3f4a5b6
4
+ Revises: b4d7e9a1c2f3
5
+ Create Date: 2026-07-21 12:00:00.000000
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+
13
+
14
+ revision: str = "c1d2e3f4a5b6"
15
+ down_revision: Union[str, Sequence[str], None] = "b4d7e9a1c2f3"
16
+ branch_labels: Union[str, Sequence[str], None] = None
17
+ depends_on: Union[str, Sequence[str], None] = None
18
+
19
+
20
+ def upgrade() -> None:
21
+ op.add_column(
22
+ "upload_jobs",
23
+ sa.Column("video_type", sa.String(), nullable=True),
24
+ )
25
+
26
+
27
+ def downgrade() -> None:
28
+ op.drop_column("upload_jobs", "video_type")
alembic/versions/c5e8f0b2d4a1_add_cover_fields_to_videos.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """add cover_url and cover_source to videos
2
+
3
+ Revision ID: c5e8f0b2d4a1
4
+ Revises: b4d7e9a1c2f3
5
+ Create Date: 2026-07-21 00:20:00.000000
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+
13
+
14
+ revision: str = "c5e8f0b2d4a1"
15
+ down_revision: Union[str, Sequence[str], None] = "b4d7e9a1c2f3"
16
+ branch_labels: Union[str, Sequence[str], None] = None
17
+ depends_on: Union[str, Sequence[str], None] = None
18
+
19
+
20
+ def upgrade() -> None:
21
+ op.add_column("videos", sa.Column("cover_url", sa.String(), nullable=True))
22
+ op.add_column("videos", sa.Column("cover_source", sa.String(), nullable=True))
23
+
24
+
25
+ def downgrade() -> None:
26
+ op.drop_column("videos", "cover_source")
27
+ op.drop_column("videos", "cover_url")
app/api/v1/endpoints/videos.py CHANGED
@@ -2,6 +2,7 @@ from typing import List, Optional
2
  import os
3
  import shutil
4
  import tempfile
 
5
  import httpx
6
  from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, BackgroundTasks, Request
7
  from fastapi.responses import StreamingResponse
@@ -19,7 +20,9 @@ from app.core import config
19
  from app.utils.push import notify_user_push
20
  from app.core.storage import storage
21
  from app.core.config import FLASH_QUOTA_LIMIT, HOME_QUOTA_LIMIT
22
- from app.models.models import Video, User, View, WatchLater, Repost, VideoInteraction
 
 
23
  from app.models.library import WatchHistory, LibraryWatchLater, LikedVideo
24
  from app.services.email_service import send_challenge_exit_email
25
  from app.core.redis import redis_client
@@ -676,10 +679,17 @@ async def finalize_upload(
676
  upload_id: str = Form(...),
677
  total_chunks: int = Form(...),
678
  filename: str = Form(...),
 
 
679
  db: Session = Depends(get_db),
680
  current_user: User = Depends(get_current_user)
681
  ):
 
682
  logger.info(f"Finalizing chunked upload {upload_id} with {total_chunks} chunks")
 
 
 
 
683
 
684
  backend_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../"))
685
  temp_dir = os.path.join(backend_dir, "static", "temp_uploads", upload_id)
@@ -700,25 +710,29 @@ async def finalize_upload(
700
  detail=f"Missing chunks: {missing_chunks}. Please upload them first."
701
  )
702
 
703
- # Merge chunks
704
  merged_path = os.path.join(temp_dir, filename)
705
- try:
 
706
  with open(merged_path, "wb") as outfile:
707
  for i in range(total_chunks):
708
  chunk_file = os.path.join(temp_dir, f"chunk_{i}")
709
  with open(chunk_file, "rb") as infile:
710
  shutil.copyfileobj(infile, outfile)
 
 
 
 
711
  except Exception as e:
712
  logger.error(f"Failed to merge chunks for upload {upload_id}: {str(e)}")
713
  raise HTTPException(status_code=500, detail="Failed to merge chunks on server")
714
 
715
- # Upload to storage
716
  source_key = f"uploads/{upload_id}/{filename}"
717
  logger.info(f"Uploading merged video to storage: {source_key}")
718
 
719
  try:
720
- with open(merged_path, "rb") as f:
721
- storage.upload_file_obj(f, source_key)
722
  except Exception as e:
723
  logger.error(f"Failed to upload merged video to storage: {str(e)}")
724
  raise HTTPException(status_code=500, detail="Failed to upload video to storage")
@@ -733,132 +747,456 @@ async def finalize_upload(
733
  video = db.query(Video).filter(Video.processing_key == upload_id).first()
734
  if not video:
735
  raise HTTPException(status_code=404, detail="Video record not found")
 
 
736
 
737
  video.status = "pending"
 
 
 
 
 
 
 
 
 
 
 
738
  db.commit()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
739
 
740
- # Trigger Celery transcoding task
 
 
741
  try:
 
742
  from app.tasks.video_tasks import process_video_task
743
- process_video_task.delay(
744
  source_key,
745
  video.video_type,
746
  video.title,
747
  video.id,
748
- video.thumbnail_url != "https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?auto=format&fit=crop&w=800&q=60",
749
- video.processing_key
 
 
 
 
 
 
750
  )
751
- logger.info(f"Transcoding celery task enqueued for video_id={video.id}")
752
  except Exception as e:
753
  logger.error(f"Failed to enqueue Celery transcoding task: {str(e)}")
754
  video.status = "failed"
 
 
755
  db.commit()
 
756
 
757
- return {"status": "success", "video_id": video.public_id}
 
 
 
 
 
 
 
758
 
759
 
760
- @router.post("/upload", response_model=schemas.Video)
761
- async def upload_video(
762
- background_tasks: BackgroundTasks,
763
- title: str = Form(...),
764
- description: Optional[str] = Form(None),
765
- tags: Optional[str] = Form(None),
766
- video_type: str = Form(...),
767
- file: UploadFile = File(...),
768
- thumbnail: Optional[UploadFile] = File(None),
769
  db: Session = Depends(get_db),
770
- current_user: dict = Depends(get_current_user)
771
  ):
772
- logger.info(f"Upload initiated: title='{title}', type='{video_type}', user_id={current_user.id}")
773
-
774
- # current_user is now a User model instance, not dict
775
- if not current_user.is_premium:
776
- if video_type == "flash" and current_user.flash_uploads >= FLASH_QUOTA_LIMIT:
777
- raise HTTPException(status_code=403, detail=f"Flash quota exceeded ({FLASH_QUOTA_LIMIT} max)")
778
- if video_type == "home" and current_user.home_uploads >= HOME_QUOTA_LIMIT:
779
- raise HTTPException(status_code=403, detail=f"Home quota exceeded ({HOME_QUOTA_LIMIT} max)")
 
 
 
 
 
 
780
 
781
- import uuid
782
- import time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
783
  import re
784
  import unicodedata
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
785
  task_id = str(uuid.uuid4())
786
-
787
- # Aggressively slugify filename
788
- filename_base, filename_ext = os.path.splitext(file.filename)
789
- safe_name = unicodedata.normalize('NFKD', filename_base).encode('ascii', 'ignore').decode('ascii')
790
- safe_name = re.sub(r'[^\w\s-]', '', safe_name).strip().lower()
791
- safe_name = re.sub(r'[-\s]+', '_', safe_name)
792
  safe_filename = f"{safe_name}{filename_ext}"
793
-
794
  source_key = f"uploads/{task_id}/{safe_filename}"
795
-
796
- logger.info(f"Streaming uploaded file directly to storage: {source_key}")
797
  try:
798
- storage.upload_file_obj(file.file, source_key)
799
  except Exception as e:
800
- import traceback
801
  error_detail = f"Storage upload failed: {str(e)}"
802
  logger.error(f"{error_detail}\n{traceback.format_exc()}")
803
- raise HTTPException(status_code=500, detail=error_detail)
804
 
805
- # Initial DB record
806
  video_create_data = schemas.VideoCreate(
807
  title=title,
808
  description=description,
809
  tags=tags,
810
  video_type=video_type,
811
- video_url="",
812
  thumbnail_url="https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?auto=format&fit=crop&w=800&q=60",
813
- processing_key=task_id
814
  )
815
-
816
- if thumbnail:
817
- safe_thumb_name = thumbnail.filename.replace(" ", "_")
818
- timestamp = int(time.time())
819
- thumb_key = f"thumbs/custom_{timestamp}_{safe_thumb_name}"
820
-
821
- try:
822
- video_create_data.thumbnail_url = storage.upload_file_obj(thumbnail.file, thumb_key)
823
- except Exception as e:
824
- logger.error(f"Failed to upload thumbnail to storage: {str(e)}")
825
 
826
- # Update quota
827
  if video_type == "flash":
828
  current_user.flash_uploads = (current_user.flash_uploads or 0) + 1
829
  else:
830
  current_user.home_uploads = (current_user.home_uploads or 0) + 1
831
-
832
- db.commit() # Save user updates
833
-
834
  db_video = crud_video.create_video(db, video_create_data, user_id=current_user.id)
 
835
  logger.info(f"Video record created in DB: id={db_video.id}")
836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
837
  try:
 
838
  from app.tasks.video_tasks import process_video_task
 
839
  process_video_task.delay(
840
  source_key,
841
  video_type,
842
  title,
843
  db_video.id,
844
- thumbnail is not None,
845
- db_video.processing_key
 
 
 
 
 
846
  )
847
- logger.info(f"Celery task enqueued for video_id={db_video.id}")
848
  except Exception as e:
849
  logger.error(f"Failed to enqueue Celery task: {str(e)}")
850
- # We still return the video, but flag it as failed immediately or show a specific message
851
  db_video.status = "failed"
 
 
852
  db.commit()
853
- raise HTTPException(status_code=500, detail="Video enqueued for processing but local queue is unreachable.")
854
 
855
- return db_video
 
 
 
 
 
 
 
 
856
 
857
 
858
- @router.post("/{video_id}/reupload", response_model=schemas.Video)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
859
  async def reupload_video(
860
  video_id: str,
861
- background_tasks: BackgroundTasks,
862
  file: UploadFile = File(...),
863
  db: Session = Depends(get_db),
864
  current_user: User = Depends(get_current_user)
@@ -874,20 +1212,26 @@ async def reupload_video(
874
  raise HTTPException(status_code=400, detail="Only failed videos can be reuploaded")
875
 
876
 
877
- import uuid
878
  task_id = str(uuid.uuid4())
879
  safe_filename = file.filename.replace(" ", "_")
880
  source_key = f"uploads/{task_id}/{safe_filename}"
881
 
882
  try:
883
- storage.upload_file_obj(file.file, source_key)
884
  except Exception as e:
885
  raise HTTPException(status_code=500, detail="Failed to reupload video file to storage")
886
-
887
 
888
  video.processing_key = task_id
889
  video.status = "pending"
890
  video.failed_at = None
 
 
 
 
 
 
 
 
891
  db.commit()
892
 
893
  from app.tasks.video_tasks import process_video_task
@@ -897,10 +1241,15 @@ async def reupload_video(
897
  video.title,
898
  video.id,
899
  False, # thumbnail_provided = False
900
- video.processing_key
 
901
  )
902
 
903
- return video
 
 
 
 
904
 
905
  @router.get("/status/{key}")
906
  async def get_processing_status(key: str, db: Session = Depends(get_db)):
 
2
  import os
3
  import shutil
4
  import tempfile
5
+ import uuid
6
  import httpx
7
  from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, BackgroundTasks, Request
8
  from fastapi.responses import StreamingResponse
 
20
  from app.utils.push import notify_user_push
21
  from app.core.storage import storage
22
  from app.core.config import FLASH_QUOTA_LIMIT, HOME_QUOTA_LIMIT
23
+ from app.models.models import (
24
+ Video, User, View, WatchLater, Repost, VideoInteraction, UploadJob, UploadJobStatus,
25
+ )
26
  from app.models.library import WatchHistory, LibraryWatchLater, LikedVideo
27
  from app.services.email_service import send_challenge_exit_email
28
  from app.core.redis import redis_client
 
679
  upload_id: str = Form(...),
680
  total_chunks: int = Form(...),
681
  filename: str = Form(...),
682
+ cover_source: str = Form("auto"),
683
+ cover: Optional[UploadFile] = File(None),
684
  db: Session = Depends(get_db),
685
  current_user: User = Depends(get_current_user)
686
  ):
687
+ """Merge chunks → S3 (threadpool) → optional cover → queue Celery → return job id."""
688
  logger.info(f"Finalizing chunked upload {upload_id} with {total_chunks} chunks")
689
+
690
+ source = (cover_source or "auto").strip().lower()
691
+ if source not in ("auto", "custom"):
692
+ raise HTTPException(status_code=400, detail="cover_source must be 'auto' or 'custom'")
693
 
694
  backend_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../"))
695
  temp_dir = os.path.join(backend_dir, "static", "temp_uploads", upload_id)
 
710
  detail=f"Missing chunks: {missing_chunks}. Please upload them first."
711
  )
712
 
713
+ # Merge chunks (CPU/IO — keep off the event loop)
714
  merged_path = os.path.join(temp_dir, filename)
715
+
716
+ def _merge_chunks():
717
  with open(merged_path, "wb") as outfile:
718
  for i in range(total_chunks):
719
  chunk_file = os.path.join(temp_dir, f"chunk_{i}")
720
  with open(chunk_file, "rb") as infile:
721
  shutil.copyfileobj(infile, outfile)
722
+
723
+ try:
724
+ import asyncio
725
+ await asyncio.to_thread(_merge_chunks)
726
  except Exception as e:
727
  logger.error(f"Failed to merge chunks for upload {upload_id}: {str(e)}")
728
  raise HTTPException(status_code=500, detail="Failed to merge chunks on server")
729
 
730
+ # Upload to storage (sync boto3 via threadpool)
731
  source_key = f"uploads/{upload_id}/{filename}"
732
  logger.info(f"Uploading merged video to storage: {source_key}")
733
 
734
  try:
735
+ await storage.async_upload_file(merged_path, source_key)
 
736
  except Exception as e:
737
  logger.error(f"Failed to upload merged video to storage: {str(e)}")
738
  raise HTTPException(status_code=500, detail="Failed to upload video to storage")
 
747
  video = db.query(Video).filter(Video.processing_key == upload_id).first()
748
  if not video:
749
  raise HTTPException(status_code=404, detail="Video record not found")
750
+ if video.owner_id != current_user.id and current_user.role != "admin":
751
+ raise HTTPException(status_code=403, detail="Not authorized")
752
 
753
  video.status = "pending"
754
+
755
+ job = UploadJob(
756
+ id=uuid.uuid4(),
757
+ user_id=current_user.id,
758
+ status=UploadJobStatus.QUEUED,
759
+ video_id=video.id, # link immediately for progress lookups while processing
760
+ video_type=video.video_type,
761
+ cover_source=source,
762
+ cover_s3_key=None,
763
+ )
764
+ db.add(job)
765
  db.commit()
766
+ db.refresh(job)
767
+
768
+ cover_s3_key = None
769
+ if source == "custom":
770
+ if cover is None or not getattr(cover, "filename", None):
771
+ job.status = UploadJobStatus.FAILED
772
+ job.error_message = "cover_source is custom but no cover file was provided"
773
+ video.status = "failed"
774
+ db.commit()
775
+ raise HTTPException(status_code=400, detail="Cover file required when cover_source is custom")
776
+ cover_s3_key = f"covers/{job.id}.jpg"
777
+ try:
778
+ cover_url = await storage.async_upload_file_obj(cover.file, cover_s3_key)
779
+ job.cover_s3_key = cover_s3_key
780
+ video.thumbnail_url = cover_url
781
+ db.commit()
782
+ logger.info(f"Custom cover uploaded for job_id={job.id} key={cover_s3_key}")
783
+ except Exception as e:
784
+ logger.error(f"Failed to upload custom cover for job_id={job.id}: {e}")
785
+ job.status = UploadJobStatus.FAILED
786
+ job.error_message = f"Cover upload failed: {e}"
787
+ video.status = "failed"
788
+ db.commit()
789
+ raise HTTPException(status_code=500, detail="Failed to upload cover image to storage")
790
 
791
+ # Trigger Celery — do not wait for Rust/transcode
792
+ # thumbnail_provided / skip_thumbnail when custom cover already on S3
793
+ thumbnail_provided = source == "custom" and bool(cover_s3_key)
794
  try:
795
+ import app.worker # noqa: F401 — set Redis Celery app as default before delay()
796
  from app.tasks.video_tasks import process_video_task
797
+ async_result = process_video_task.delay(
798
  source_key,
799
  video.video_type,
800
  video.title,
801
  video.id,
802
+ thumbnail_provided,
803
+ video.processing_key,
804
+ str(job.id),
805
+ )
806
+ logger.info(
807
+ f"Transcoding celery task enqueued for video_id={video.id} "
808
+ f"job_id={job.id} cover_source={source} cover_s3_key={cover_s3_key} "
809
+ f"celery_id={async_result.id}"
810
  )
 
811
  except Exception as e:
812
  logger.error(f"Failed to enqueue Celery transcoding task: {str(e)}")
813
  video.status = "failed"
814
+ job.status = UploadJobStatus.FAILED
815
+ job.error_message = str(e)
816
  db.commit()
817
+ raise HTTPException(status_code=500, detail="Failed to enqueue transcoding job")
818
 
819
+ return {
820
+ "job_id": str(job.id),
821
+ "status": UploadJobStatus.QUEUED.value,
822
+ "video_id": video.public_id,
823
+ "processing_key": video.processing_key,
824
+ "cover_source": source,
825
+ "cover_s3_key": cover_s3_key,
826
+ }
827
 
828
 
829
+ @router.get("/upload/jobs/{job_id}")
830
+ async def get_upload_job(
831
+ job_id: str,
 
 
 
 
 
 
832
  db: Session = Depends(get_db),
833
+ current_user: User = Depends(get_current_user),
834
  ):
835
+ """
836
+ Poll async upload/transcode job status.
837
+ Returns status, video_id (when completed), live progress, and error_message (when failed).
838
+ """
839
+ try:
840
+ job_uuid = uuid.UUID(job_id)
841
+ except ValueError:
842
+ raise HTTPException(status_code=400, detail="Invalid job id")
843
+
844
+ job = db.query(UploadJob).filter(UploadJob.id == job_uuid).first()
845
+ if not job:
846
+ raise HTTPException(status_code=404, detail="Upload job not found")
847
+ if job.user_id != current_user.id and current_user.role != "admin":
848
+ raise HTTPException(status_code=403, detail="Not authorized")
849
 
850
+ status = job.status.value if hasattr(job.status, "value") else str(job.status)
851
+
852
+ video = None
853
+ if job.video_id:
854
+ video = db.query(Video).filter(Video.id == job.video_id).first()
855
+
856
+ # Only expose watchable public id once the job is done
857
+ video_public_id = None
858
+ if status == UploadJobStatus.COMPLETED.value or status == "completed":
859
+ video_public_id = video.public_id if video else None
860
+
861
+ progress = None
862
+ processing_key = video.processing_key if video else None
863
+ if processing_key:
864
+ try:
865
+ raw = redis_client.get(f"job:progress:{processing_key}")
866
+ if raw is not None:
867
+ progress = int(float(raw))
868
+ else:
869
+ status_raw = redis_client.get(f"task:status:{processing_key}")
870
+ if status_raw:
871
+ import json
872
+ payload = json.loads(status_raw)
873
+ if isinstance(payload.get("progress"), (int, float)):
874
+ progress = int(payload["progress"])
875
+ except Exception as e:
876
+ logger.debug(f"Progress lookup failed for job {job_id}: {e}")
877
+
878
+ if status == "completed":
879
+ progress = 100
880
+ elif status == "queued" and progress is None:
881
+ progress = 5
882
+ elif status == "processing" and progress is None:
883
+ progress = 15
884
+
885
+ return {
886
+ "job_id": str(job.id),
887
+ "status": status,
888
+ "video_id": video_public_id,
889
+ "processing_key": processing_key,
890
+ "progress": progress,
891
+ "error_message": job.error_message,
892
+ "created_at": job.created_at,
893
+ "updated_at": job.updated_at,
894
+ }
895
+
896
+
897
+ async def _direct_upload_one(
898
+ *,
899
+ db: Session,
900
+ current_user: User,
901
+ file: UploadFile,
902
+ title: str,
903
+ description: Optional[str],
904
+ tags: Optional[str],
905
+ video_type: str,
906
+ thumbnail: Optional[UploadFile] = None,
907
+ cover_source: str = "auto",
908
+ raise_http: bool = False,
909
+ ) -> dict:
910
+ """
911
+ Save one file to storage, create upload_jobs + Video, enqueue Celery.
912
+ When raise_http=False (batch), returns a per-file result dict and never raises
913
+ for storage/enqueue failures. When raise_http=True (single /upload), raises HTTPException.
914
+ """
915
  import re
916
  import unicodedata
917
+ import traceback
918
+
919
+ filename = file.filename or "video"
920
+ source = (cover_source or "auto").strip().lower()
921
+ if source not in ("auto", "custom"):
922
+ source = "auto"
923
+ # Legacy: a thumbnail file implies custom cover
924
+ if source == "auto" and thumbnail is not None and getattr(thumbnail, "filename", None):
925
+ source = "custom"
926
+
927
+ def _fail(error: str, status_code: int = 500) -> dict:
928
+ logger.error(f"Direct upload failed for '{filename}': {error}")
929
+ if raise_http:
930
+ raise HTTPException(status_code=status_code, detail=error)
931
+ return {
932
+ "filename": filename,
933
+ "job_id": None,
934
+ "status": "failed",
935
+ "video_id": None,
936
+ "error": error,
937
+ "cover_source": source,
938
+ "cover_s3_key": None,
939
+ }
940
+
941
+ if not current_user.is_premium:
942
+ if video_type == "flash" and (current_user.flash_uploads or 0) >= FLASH_QUOTA_LIMIT:
943
+ return _fail(f"Flash quota exceeded ({FLASH_QUOTA_LIMIT} max)", status_code=403)
944
+ if video_type == "home" and (current_user.home_uploads or 0) >= HOME_QUOTA_LIMIT:
945
+ return _fail(f"Home quota exceeded ({HOME_QUOTA_LIMIT} max)", status_code=403)
946
+
947
  task_id = str(uuid.uuid4())
948
+
949
+ filename_base, filename_ext = os.path.splitext(filename)
950
+ safe_name = unicodedata.normalize("NFKD", filename_base).encode("ascii", "ignore").decode("ascii")
951
+ safe_name = re.sub(r"[^\w\s-]", "", safe_name).strip().lower()
952
+ safe_name = re.sub(r"[-\s]+", "_", safe_name) or "video"
 
953
  safe_filename = f"{safe_name}{filename_ext}"
954
+
955
  source_key = f"uploads/{task_id}/{safe_filename}"
956
+
957
+ logger.info(f"Streaming uploaded file to storage (threadpool): {source_key}")
958
  try:
959
+ await storage.async_upload_file_obj(file.file, source_key)
960
  except Exception as e:
 
961
  error_detail = f"Storage upload failed: {str(e)}"
962
  logger.error(f"{error_detail}\n{traceback.format_exc()}")
963
+ return _fail(error_detail)
964
 
 
965
  video_create_data = schemas.VideoCreate(
966
  title=title,
967
  description=description,
968
  tags=tags,
969
  video_type=video_type,
970
+ video_url="",
971
  thumbnail_url="https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?auto=format&fit=crop&w=800&q=60",
972
+ processing_key=task_id,
973
  )
 
 
 
 
 
 
 
 
 
 
974
 
 
975
  if video_type == "flash":
976
  current_user.flash_uploads = (current_user.flash_uploads or 0) + 1
977
  else:
978
  current_user.home_uploads = (current_user.home_uploads or 0) + 1
979
+
980
+ db.commit()
981
+
982
  db_video = crud_video.create_video(db, video_create_data, user_id=current_user.id)
983
+ db_video.status = "pending"
984
  logger.info(f"Video record created in DB: id={db_video.id}")
985
 
986
+ job = UploadJob(
987
+ id=uuid.uuid4(),
988
+ user_id=current_user.id,
989
+ status=UploadJobStatus.QUEUED,
990
+ video_id=db_video.id,
991
+ video_type=video_type,
992
+ cover_source=source,
993
+ cover_s3_key=None,
994
+ )
995
+ db.add(job)
996
+ db.commit()
997
+ db.refresh(job)
998
+
999
+ cover_s3_key = None
1000
+ if source == "custom":
1001
+ if thumbnail is None or not getattr(thumbnail, "filename", None):
1002
+ db_video.status = "failed"
1003
+ job.status = UploadJobStatus.FAILED
1004
+ job.error_message = "cover_source is custom but no cover file was provided"
1005
+ db.commit()
1006
+ return _fail("Cover file required when cover_source is custom", status_code=400)
1007
+ cover_s3_key = f"covers/{job.id}.jpg"
1008
+ try:
1009
+ cover_url = await storage.async_upload_file_obj(thumbnail.file, cover_s3_key)
1010
+ job.cover_s3_key = cover_s3_key
1011
+ db_video.thumbnail_url = cover_url
1012
+ db.commit()
1013
+ except Exception as e:
1014
+ logger.error(f"Failed to upload cover to storage: {e}")
1015
+ db_video.status = "failed"
1016
+ job.status = UploadJobStatus.FAILED
1017
+ job.error_message = f"Cover upload failed: {e}"
1018
+ db.commit()
1019
+ return _fail(f"Cover upload failed: {e}")
1020
+
1021
+ thumbnail_provided = source == "custom" and bool(cover_s3_key)
1022
+
1023
  try:
1024
+ import app.worker # noqa: F401 — bind Redis Celery app before delay()
1025
  from app.tasks.video_tasks import process_video_task
1026
+
1027
  process_video_task.delay(
1028
  source_key,
1029
  video_type,
1030
  title,
1031
  db_video.id,
1032
+ thumbnail_provided,
1033
+ db_video.processing_key,
1034
+ str(job.id),
1035
+ )
1036
+ logger.info(
1037
+ f"Celery task enqueued for video_id={db_video.id} job_id={job.id} "
1038
+ f"cover_source={source} cover_s3_key={cover_s3_key}"
1039
  )
 
1040
  except Exception as e:
1041
  logger.error(f"Failed to enqueue Celery task: {str(e)}")
 
1042
  db_video.status = "failed"
1043
+ job.status = UploadJobStatus.FAILED
1044
+ job.error_message = str(e)
1045
  db.commit()
1046
+ return _fail("Failed to enqueue transcoding job")
1047
 
1048
+ return {
1049
+ "filename": filename,
1050
+ "job_id": str(job.id),
1051
+ "status": UploadJobStatus.QUEUED.value,
1052
+ "video_id": db_video.public_id,
1053
+ "error": None,
1054
+ "cover_source": source,
1055
+ "cover_s3_key": cover_s3_key,
1056
+ }
1057
 
1058
 
1059
+ @router.post("/upload")
1060
+ async def upload_video(
1061
+ title: str = Form(...),
1062
+ description: Optional[str] = Form(None),
1063
+ tags: Optional[str] = Form(None),
1064
+ video_type: str = Form(...),
1065
+ file: UploadFile = File(...),
1066
+ thumbnail: Optional[UploadFile] = File(None),
1067
+ cover_source: str = Form("auto"),
1068
+ db: Session = Depends(get_db),
1069
+ current_user: User = Depends(get_current_user)
1070
+ ):
1071
+ """
1072
+ Save file to storage, create an upload_jobs row, enqueue Celery, return immediately.
1073
+ Transcoding happens in the worker — this handler never waits on Rust.
1074
+ """
1075
+ logger.info(f"Upload initiated: title='{title}', type='{video_type}', user_id={current_user.id}")
1076
+ result = await _direct_upload_one(
1077
+ db=db,
1078
+ current_user=current_user,
1079
+ file=file,
1080
+ title=title,
1081
+ description=description,
1082
+ tags=tags,
1083
+ video_type=video_type,
1084
+ thumbnail=thumbnail,
1085
+ cover_source=cover_source,
1086
+ raise_http=True,
1087
+ )
1088
+ return {
1089
+ "job_id": result["job_id"],
1090
+ "status": result["status"],
1091
+ "video_id": result["video_id"],
1092
+ "cover_source": result.get("cover_source"),
1093
+ "cover_s3_key": result.get("cover_s3_key"),
1094
+ }
1095
+
1096
+
1097
+ @router.post("/upload/batch")
1098
+ async def upload_videos_batch(
1099
+ files: List[UploadFile] = File(..., description="One or more video files"),
1100
+ titles: List[str] = Form(..., description="Caption/title per file (same order as files)"),
1101
+ video_types: Optional[List[str]] = Form(None, description="Per-video 'home' or 'flash' (same order as files); falls back to video_type if omitted"),
1102
+ video_type: str = Form("home", description="Fallback video type when video_types is omitted"),
1103
+ descriptions: Optional[List[str]] = Form(None),
1104
+ tags: Optional[List[str]] = Form(None),
1105
+ cover_sources: Optional[List[str]] = Form(None),
1106
+ thumbnails: Optional[List[UploadFile]] = File(None),
1107
+ db: Session = Depends(get_db),
1108
+ current_user: User = Depends(get_current_user),
1109
+ ):
1110
+ """
1111
+ Multipart batch upload: each file gets its own S3 object, upload_jobs row, and Celery task.
1112
+
1113
+ ``video_types`` is a parallel list of ``"home"`` / ``"flash"`` values, one per file.
1114
+ If omitted, every file uses the scalar ``video_type`` fallback (default ``"home"``).
1115
+
1116
+ Returns HTTP 200 with a per-file results array. Individual storage/enqueue failures are
1117
+ reported in that array; remaining files are still processed.
1118
+ """
1119
+ if not files:
1120
+ raise HTTPException(status_code=400, detail="At least one file is required")
1121
+
1122
+ if len(titles) != len(files):
1123
+ raise HTTPException(
1124
+ status_code=400,
1125
+ detail=f"titles count ({len(titles)}) must match files count ({len(files)})",
1126
+ )
1127
+
1128
+ vt_list = list(video_types or [])
1129
+ if len(vt_list) > 0 and len(vt_list) != len(files):
1130
+ raise HTTPException(
1131
+ status_code=400,
1132
+ detail=f"video_types count ({len(vt_list)}) must match files count ({len(files)})",
1133
+ )
1134
+ # Normalise + fallback: pad with scalar video_type for any missing entries
1135
+ while len(vt_list) < len(files):
1136
+ vt_list.append(video_type if video_type in ("home", "flash") else "home")
1137
+ vt_list = [v if v in ("home", "flash") else "home" for v in vt_list]
1138
+
1139
+ desc_list = list(descriptions or [])
1140
+ tags_list = list(tags or [])
1141
+ thumb_list = list(thumbnails or [])
1142
+ cover_list = list(cover_sources or [])
1143
+
1144
+ # Pad optional parallel fields so zip never IndexErrors
1145
+ while len(desc_list) < len(files):
1146
+ desc_list.append(None)
1147
+ while len(tags_list) < len(files):
1148
+ tags_list.append(None)
1149
+ while len(thumb_list) < len(files):
1150
+ thumb_list.append(None)
1151
+ while len(cover_list) < len(files):
1152
+ cover_list.append("auto")
1153
+
1154
+ logger.info(
1155
+ f"Batch upload initiated: count={len(files)}, types={vt_list}, "
1156
+ f"user_id={current_user.id}"
1157
+ )
1158
+
1159
+ results = []
1160
+ for index, (file, title, description, file_tags, thumbnail, cov, vt) in enumerate(
1161
+ zip(files, titles, desc_list, tags_list, thumb_list, cover_list, vt_list)
1162
+ ):
1163
+ # Skip empty thumbnail slots (some clients send blank file parts)
1164
+ thumb = thumbnail
1165
+ if thumb is not None and not getattr(thumb, "filename", None):
1166
+ thumb = None
1167
+
1168
+ caption = (title or "").strip() or (file.filename or f"video-{index + 1}")
1169
+ result = await _direct_upload_one(
1170
+ db=db,
1171
+ current_user=current_user,
1172
+ file=file,
1173
+ title=caption,
1174
+ description=description,
1175
+ tags=file_tags,
1176
+ video_type=vt,
1177
+ thumbnail=thumb,
1178
+ cover_source=cov or "auto",
1179
+ raise_http=False,
1180
+ )
1181
+ result["index"] = index
1182
+ results.append(result)
1183
+
1184
+ # Keep quota counters accurate for subsequent files in this request
1185
+ db.refresh(current_user)
1186
+
1187
+ succeeded = sum(1 for r in results if r.get("status") != "failed")
1188
+ failed = len(results) - succeeded
1189
+
1190
+ return {
1191
+ "results": results,
1192
+ "succeeded": succeeded,
1193
+ "failed": failed,
1194
+ }
1195
+
1196
+
1197
+ @router.post("/{video_id}/reupload")
1198
  async def reupload_video(
1199
  video_id: str,
 
1200
  file: UploadFile = File(...),
1201
  db: Session = Depends(get_db),
1202
  current_user: User = Depends(get_current_user)
 
1212
  raise HTTPException(status_code=400, detail="Only failed videos can be reuploaded")
1213
 
1214
 
 
1215
  task_id = str(uuid.uuid4())
1216
  safe_filename = file.filename.replace(" ", "_")
1217
  source_key = f"uploads/{task_id}/{safe_filename}"
1218
 
1219
  try:
1220
+ await storage.async_upload_file_obj(file.file, source_key)
1221
  except Exception as e:
1222
  raise HTTPException(status_code=500, detail="Failed to reupload video file to storage")
 
1223
 
1224
  video.processing_key = task_id
1225
  video.status = "pending"
1226
  video.failed_at = None
1227
+
1228
+ job = UploadJob(
1229
+ id=uuid.uuid4(),
1230
+ user_id=current_user.id,
1231
+ status=UploadJobStatus.QUEUED,
1232
+ video_id=video.id,
1233
+ )
1234
+ db.add(job)
1235
  db.commit()
1236
 
1237
  from app.tasks.video_tasks import process_video_task
 
1241
  video.title,
1242
  video.id,
1243
  False, # thumbnail_provided = False
1244
+ video.processing_key,
1245
+ str(job.id),
1246
  )
1247
 
1248
+ return {
1249
+ "job_id": str(job.id),
1250
+ "status": UploadJobStatus.QUEUED.value,
1251
+ "video_id": video.public_id,
1252
+ }
1253
 
1254
  @router.get("/status/{key}")
1255
  async def get_processing_status(key: str, db: Session = Depends(get_db)):
app/core/storage.py CHANGED
@@ -1,6 +1,7 @@
1
  import os
2
  import logging
3
  import time
 
4
  from typing import Optional
5
  import shutil
6
  import boto3
@@ -168,6 +169,14 @@ class Storage:
168
  logger.error(f"S3 Object Upload failed for {s3_key}: {e}", exc_info=True)
169
  raise
170
 
 
 
 
 
 
 
 
 
171
  def get_url(self, s3_key: str, mode: Optional[str] = None) -> str:
172
  """
173
  Returns the public URL for a given key.
 
1
  import os
2
  import logging
3
  import time
4
+ import asyncio
5
  from typing import Optional
6
  import shutil
7
  import boto3
 
169
  logger.error(f"S3 Object Upload failed for {s3_key}: {e}", exc_info=True)
170
  raise
171
 
172
+ async def async_upload_file_obj(self, file_obj, s3_key: str) -> str:
173
+ """Non-blocking wrapper — runs sync boto3 upload off the event loop."""
174
+ return await asyncio.to_thread(self.upload_file_obj, file_obj, s3_key)
175
+
176
+ async def async_upload_file(self, local_path: str, s3_key: str) -> str:
177
+ """Non-blocking wrapper for path-based uploads."""
178
+ return await asyncio.to_thread(self.upload_file, local_path, s3_key)
179
+
180
  def get_url(self, s3_key: str, mode: Optional[str] = None) -> str:
181
  """
182
  Returns the public URL for a given key.
app/models/models.py CHANGED
@@ -1,6 +1,7 @@
1
  from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, Float, Text, DateTime, func, Numeric, Index
2
  import uuid
3
 
 
4
  from sqlalchemy.orm import relationship, backref
5
  from app.db.base import Base
6
  import enum
@@ -20,6 +21,13 @@ class ApprovalStatus(str, enum.Enum):
20
  REJECTED = "rejected"
21
  FAILED = "failed"
22
 
 
 
 
 
 
 
 
23
  from app.models.library import WatchHistory, LibraryWatchLater, LikedVideo
24
 
25
  class User(Base):
@@ -154,6 +162,9 @@ class Video(Base):
154
  url_2k = Column(String, nullable=True)
155
  url_4k = Column(String, nullable=True)
156
  thumbnail_url = Column(String)
 
 
 
157
  video_type = Column(String, index=True) # home or flash
158
  status = Column(String, default=ApprovalStatus.PENDING, index=True)
159
  owner_id = Column(Integer, ForeignKey("users.id"), index=True)
@@ -176,6 +187,7 @@ class Video(Base):
176
  comments = relationship("Comment", back_populates="video", cascade="all, delete-orphan")
177
  likes = relationship("Like", back_populates="video", cascade="all, delete-orphan")
178
  challenge_entries = relationship("ChallengeEntry", back_populates="video", cascade="all, delete-orphan")
 
179
 
180
  @property
181
  def owner_username(self):
@@ -208,6 +220,10 @@ class Video(Base):
208
  def dynamic_thumbnail_url(self):
209
  return self._resolve_url(self.thumbnail_url)
210
 
 
 
 
 
211
  @property
212
  def dynamic_url_720p(self):
213
  return self._resolve_url(self.url_720p)
@@ -216,6 +232,43 @@ class Video(Base):
216
  def dynamic_url_1080p(self):
217
  return self._resolve_url(self.url_1080p)
218
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  class View(Base):
220
  __tablename__ = "views"
221
 
 
1
  from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, Float, Text, DateTime, func, Numeric, Index
2
  import uuid
3
 
4
+ from sqlalchemy.dialects.postgresql import UUID
5
  from sqlalchemy.orm import relationship, backref
6
  from app.db.base import Base
7
  import enum
 
21
  REJECTED = "rejected"
22
  FAILED = "failed"
23
 
24
+ class UploadJobStatus(str, enum.Enum):
25
+ UPLOADING = "uploading"
26
+ QUEUED = "queued"
27
+ PROCESSING = "processing"
28
+ COMPLETED = "completed"
29
+ FAILED = "failed"
30
+
31
  from app.models.library import WatchHistory, LibraryWatchLater, LikedVideo
32
 
33
  class User(Base):
 
162
  url_2k = Column(String, nullable=True)
163
  url_4k = Column(String, nullable=True)
164
  thumbnail_url = Column(String)
165
+ # Final cover after transcode (custom upload or Rust-generated). Prefer over thumbnail_url for new clients.
166
+ cover_url = Column(String, nullable=True)
167
+ cover_source = Column(String, nullable=True) # "auto" | "custom"
168
  video_type = Column(String, index=True) # home or flash
169
  status = Column(String, default=ApprovalStatus.PENDING, index=True)
170
  owner_id = Column(Integer, ForeignKey("users.id"), index=True)
 
187
  comments = relationship("Comment", back_populates="video", cascade="all, delete-orphan")
188
  likes = relationship("Like", back_populates="video", cascade="all, delete-orphan")
189
  challenge_entries = relationship("ChallengeEntry", back_populates="video", cascade="all, delete-orphan")
190
+ upload_jobs = relationship("UploadJob", back_populates="video")
191
 
192
  @property
193
  def owner_username(self):
 
220
  def dynamic_thumbnail_url(self):
221
  return self._resolve_url(self.thumbnail_url)
222
 
223
+ @property
224
+ def dynamic_cover_url(self):
225
+ return self._resolve_url(self.cover_url or self.thumbnail_url)
226
+
227
  @property
228
  def dynamic_url_720p(self):
229
  return self._resolve_url(self.url_720p)
 
232
  def dynamic_url_1080p(self):
233
  return self._resolve_url(self.url_1080p)
234
 
235
+
236
+ class UploadJob(Base):
237
+ """Tracks async upload/transcode lifecycle so HTTP handlers can return early."""
238
+
239
+ __tablename__ = "upload_jobs"
240
+
241
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
242
+ user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
243
+ status = Column(
244
+ String,
245
+ nullable=False,
246
+ default=UploadJobStatus.UPLOADING,
247
+ index=True,
248
+ )
249
+ video_id = Column(Integer, ForeignKey("videos.id", ondelete="SET NULL"), nullable=True, index=True)
250
+ error_message = Column(Text, nullable=True)
251
+ # "home" or "flash" — mirrors video_type on the linked Video, used for quota refunds
252
+ video_type = Column(String, nullable=True)
253
+ # "auto" = Rust generates thumbnail; "custom" = cover_s3_key was uploaded by client
254
+ cover_source = Column(String, nullable=False, default="auto", server_default="auto")
255
+ cover_s3_key = Column(String, nullable=True)
256
+ created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
257
+ updated_at = Column(
258
+ DateTime(timezone=True),
259
+ server_default=func.now(),
260
+ onupdate=func.now(),
261
+ nullable=False,
262
+ )
263
+
264
+ user = relationship("User", backref=backref("upload_jobs", cascade="all, delete-orphan"))
265
+ video = relationship("Video", back_populates="upload_jobs")
266
+
267
+ __table_args__ = (
268
+ Index("ix_upload_jobs_user_status", "user_id", "status"),
269
+ )
270
+
271
+
272
  class View(Base):
273
  __tablename__ = "views"
274
 
app/schemas/schemas.py CHANGED
@@ -192,6 +192,8 @@ class Video(VideoBase):
192
  url_2k: Optional[str] = None
193
  url_4k: Optional[str] = None
194
  thumbnail_url: str
 
 
195
  status: str
196
  owner_id: int
197
  owner: Optional[UserPublic] = None
@@ -213,7 +215,11 @@ class Video(VideoBase):
213
  def ensure_int(cls, v):
214
  return v if v is not None else 0
215
 
216
- @field_validator('video_url', 'thumbnail_url', 'url_480p', 'url_720p', 'url_1080p', 'url_2k', 'url_4k', mode='before')
 
 
 
 
217
  @classmethod
218
  def resolve_cdn_url(cls, v):
219
  if not v or not isinstance(v, str):
 
192
  url_2k: Optional[str] = None
193
  url_4k: Optional[str] = None
194
  thumbnail_url: str
195
+ cover_url: Optional[str] = None
196
+ cover_source: Optional[str] = None
197
  status: str
198
  owner_id: int
199
  owner: Optional[UserPublic] = None
 
215
  def ensure_int(cls, v):
216
  return v if v is not None else 0
217
 
218
+ @field_validator(
219
+ 'video_url', 'thumbnail_url', 'cover_url',
220
+ 'url_480p', 'url_720p', 'url_1080p', 'url_2k', 'url_4k',
221
+ mode='before',
222
+ )
223
  @classmethod
224
  def resolve_cdn_url(cls, v):
225
  if not v or not isinstance(v, str):
app/tasks/video_tasks.py CHANGED
@@ -1,227 +1,588 @@
1
- import os
2
- import time
3
  import requests
 
4
  from celery import shared_task
5
  from sqlalchemy import func
6
 
 
 
 
 
7
  from app.db.session import SessionLocal
8
- from app.models.models import Video, User
9
  from app.core import config
10
  from app.core.storage import storage
11
  from app.utils.push import notify_user_push
12
  from app.core.redis import redis_client
13
  import logging
14
  import json
 
15
 
16
  logger = logging.getLogger(__name__)
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  @shared_task(bind=True, name="video_tasks.process_video", max_retries=3)
19
- def process_video_task(self, source_key: str, video_type: str, title: str, video_id: int, thumbnail_provided: bool, task_id: str):
20
- logger.info(f"Starting Celery task: video_id={video_id}, task_id={task_id}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  db = SessionLocal()
22
  try:
23
- # Phase 1: Communication with Rust Service
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  try:
25
- logger.info(f"Phase 1: POST to Rust service at {config.RUST_SERVICE_URL}/process with source {source_key}")
 
 
 
26
  try:
27
- rust_response = requests.post(
28
- f"{config.RUST_SERVICE_URL}/process",
29
- json={
30
- "video_id": source_key,
31
- "target_format": video_type,
32
- "skip_thumbnail": thumbnail_provided,
33
- "task_id": task_id
34
- },
35
- timeout=30.0 # Increased timeout to 30s to allow for Render cold starts
36
- )
37
- logger.info(f"Rust service responded with status {rust_response.status_code}")
38
- rust_response.raise_for_status()
39
- except requests.exceptions.RequestException as re:
40
- logger.error(f"Failed to communicate with Rust service: {str(re)}")
41
- if hasattr(re, 'response') and re.response is not None:
42
- logger.error(f"Rust error response: {re.response.text}")
43
- raise Exception(f"Rust service unreachable or returned error: {re}")
44
- logger.info(f"Rust service accepted task. Starting polling for task_id={task_id}")
45
- max_retries = 300 # 10 minutes with 2s sleep
46
- retries = 0
47
- while retries < max_retries:
48
- try:
49
- # Priority 1: Check Redis (Shared with Rust)
50
- status_data_raw = redis_client.get(f"task:status:{task_id}")
51
- status_data = None
52
-
53
- if status_data_raw:
54
- status_data = json.loads(status_data_raw)
55
- else:
56
- # Priority 2: Fallback to HTTP (If Redis is inconsistent or Rust is updating differently)
57
- status_resp = requests.get(f"{config.RUST_SERVICE_URL}/status/{task_id}", timeout=2.0)
58
- if status_resp.status_code == 200:
59
- status_data = status_resp.json()
60
-
61
- if status_data:
62
- current_status = status_data.get("status")
63
- progress = status_data.get("progress", 0)
64
- msg = status_data.get("message", "")
65
-
66
- logger.debug(f"Task {task_id} status: {current_status} ({progress}%)")
67
-
68
- # Provide progress update to DB
69
- db_video = db.query(Video).filter(Video.id == video_id).first()
70
- if db_video:
71
- db_video.processing_message = f"{msg} ({progress}%)"
72
- db.commit()
73
-
74
- if current_status and current_status.lower() in ["completed", "uploaded", "success"]:
75
- logger.info(f"Transcoding completed for task_id={task_id}")
76
- break
77
- if current_status == "error":
78
- logger.error(f"Rust processing error for task {task_id}: {msg}")
79
- raise Exception(f"Rust processing error: {msg}")
80
- else:
81
- logger.warning(f"Task {task_id} status not found in Redis or Rust API.")
82
-
83
- except Exception as e:
84
- if "Rust processing error" in str(e): raise e
85
- logger.warning(f"Polling error (try {retries}): {e}")
86
-
87
- time.sleep(3)
88
- retries += 1
89
-
90
- if retries >= max_retries:
91
- logger.error(f"Background processing timed out for task {task_id}")
92
- raise Exception(f"Background processing timed out for task {task_id}")
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  except Exception as e:
95
- print(f"Error in background processing phase: {e}")
96
-
97
- # Only fail permanently if we've exhausted retries
98
- if self.request.retries >= self.max_retries:
99
- video = db.query(Video).filter(Video.id == video_id).first()
100
- if video:
101
- video.status = "failed"
102
- video.failed_at = func.now()
103
- owner = db.query(User).filter(User.id == video.owner_id).first()
104
- if owner:
105
- if video.video_type == "flash":
106
- owner.flash_uploads = max(0, (owner.flash_uploads or 1) - 1)
107
- else:
108
- owner.home_uploads = max(0, (owner.home_uploads or 1) - 1)
109
- db.commit()
110
-
111
- # Cleanup cloud storage on final failure
112
- try:
113
- logger.info(f"Cleaning up storage after final failure for task {task_id}")
114
- storage.delete_prefix(f"uploads/{task_id}/")
115
- storage.delete_prefix(f"videos/{task_id}/")
116
- except Exception as cleanup_err:
117
- logger.warning(f"Storage cleanup failed: {cleanup_err}")
118
-
119
- raise e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  else:
121
- logger.warning(f"Task {task_id} failed, retrying... ({self.request.retries}/{self.max_retries})")
122
- raise self.retry(exc=e, countdown=60)
 
 
 
 
 
123
 
124
- # Phase 2: Post-processing (Updating DB URLs)
125
- # Note: Rust service now handles the upload of HLS files to GCS.
126
- logger.info(f"Phase 2: Updating DB with S3 URLs for video_id={video_id}")
127
-
128
- # Use storage abstraction to generate correct URLs (S3 or Local)
129
- video_url = storage.get_url(f"videos/{task_id}/master.m3u8")
130
-
131
- if video_type == "flash":
132
- url_480p = None
133
- url_720p = None
134
- url_1080p = None
135
- url_2k = None
136
- url_4k = None
137
- else:
138
- url_480p = storage.get_url(f"videos/{task_id}/480p.m3u8")
139
- url_720p = storage.get_url(f"videos/{task_id}/720p.m3u8")
140
- url_1080p = storage.get_url(f"videos/{task_id}/1080p.m3u8")
141
- url_2k = storage.get_url(f"videos/{task_id}/2k.m3u8")
142
- url_4k = storage.get_url(f"videos/{task_id}/4k.m3u8")
143
-
144
- thumbnail_url = storage.get_url(f"thumbnails/{task_id}.jpg")
145
-
146
- # Duration is not available from the Rust service response yet;
147
- # keep as 0 — can be backfilled later via a separate metadata job.
148
- duration = 0
149
-
150
- video = db.query(Video).filter(Video.id == video_id).first()
151
- if video:
152
- video.video_url = video_url
153
- video.url_480p = url_480p
154
- video.url_720p = url_720p
155
- video.url_1080p = url_1080p
156
- video.url_2k = url_2k
157
- video.url_4k = url_4k
158
- video.duration = duration
159
- video.failed_at = None
160
- # Auto-approve: no admin review needed
161
- video.status = "approved"
162
- video.processing_message = "Live"
163
-
164
- # Only set thumbnail if a custom one wasn't provided during upload
165
- if not thumbnail_provided and thumbnail_url:
166
- video.thumbnail_url = thumbnail_url
167
-
168
- db.commit()
169
-
170
- # Notify user of success
171
- try:
172
- notify_user_push(
173
  db,
174
- user_id=video.owner_id,
175
- title="Video Live! 🚀",
176
- body=f"Your video '{title}' has been processed and is now live!",
177
- link=f"/profile",
178
- n_type="status_change"
 
 
179
  )
180
- except: pass
181
-
182
 
183
-
184
- # Phase 3: Cleanup
185
- try:
186
- logger.info(f"Phase 3: Deleting raw source directory uploads/{task_id}/")
187
- storage.delete_prefix(f"uploads/{task_id}/")
188
- except Exception as e:
189
- logger.warning(f"Failed to delete source directory uploads/{task_id}/: {e}")
190
-
191
- return {"status": "success", "video_id": video_id}
192
 
193
- except Exception as e:
194
- # Notify user of failure and set status
195
- try:
196
- video = db.query(Video).filter(Video.id == video_id).first()
197
- if video:
198
- video.status = "failed"
199
- video.failed_at = func.now()
200
- owner = db.query(User).filter(User.id == video.owner_id).first()
201
- if owner:
202
- if video.video_type == "flash":
203
- owner.flash_uploads = max(0, (owner.flash_uploads or 1) - 1)
204
- else:
205
- owner.home_uploads = max(0, (owner.home_uploads or 1) - 1)
206
- db.commit()
207
-
208
- notify_user_push(
209
- db,
210
- user_id=video.owner_id,
211
- title="Video Processing Failed",
212
- body=f"Something went wrong while processing '{title}'. Please try uploading again.",
213
- link="/upload",
214
- n_type="status_change"
215
- )
216
-
217
- # Cleanup cloud storage on failure
218
- logger.info(f"Cleaning up storage after phase 2 failure for task {task_id}")
219
- storage.delete_prefix(f"uploads/{task_id}/")
220
- storage.delete_prefix(f"videos/{task_id}/")
221
- except: pass
222
-
223
- print(f"Error in post-processing: {e}")
224
- raise e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  finally:
226
  db.close()
227
 
 
 
 
1
  import requests
2
+ from datetime import datetime, timezone
3
  from celery import shared_task
4
  from sqlalchemy import func
5
 
6
+ from uuid import UUID
7
+
8
+ # Bind @shared_task to the Redis-backed worker app (not Celery's default AMQP).
9
+ import app.worker # noqa: F401
10
  from app.db.session import SessionLocal
11
+ from app.models.models import Video, User, UploadJob, UploadJobStatus
12
  from app.core import config
13
  from app.core.storage import storage
14
  from app.utils.push import notify_user_push
15
  from app.core.redis import redis_client
16
  import logging
17
  import json
18
+ import time
19
 
20
  logger = logging.getLogger(__name__)
21
 
22
+
23
+ def _resolve_user_tier(db, video_id: int) -> str:
24
+ """Map video owner premium status to Rust queue tier ('pro' | 'free')."""
25
+ video = db.query(Video).filter(Video.id == video_id).first()
26
+ if not video:
27
+ return "free"
28
+ owner = db.query(User).filter(User.id == video.owner_id).first()
29
+ if not owner or not owner.is_premium:
30
+ return "free"
31
+ if owner.premium_expires_at and owner.premium_expires_at < datetime.now(timezone.utc):
32
+ owner.is_premium = False
33
+ db.commit()
34
+ return "free"
35
+ return "pro"
36
+
37
+
38
+ def _update_upload_job(db, upload_job_id, status: str, *, video_id: int = None, error_message: str = None):
39
+ if not upload_job_id:
40
+ return
41
+ try:
42
+ job_uuid = UUID(str(upload_job_id))
43
+ except (TypeError, ValueError):
44
+ logger.warning(f"Invalid upload_job_id: {upload_job_id}")
45
+ return
46
+ job = db.query(UploadJob).filter(UploadJob.id == job_uuid).first()
47
+ if not job:
48
+ return
49
+ job.status = status
50
+ if video_id is not None:
51
+ job.video_id = video_id
52
+ if error_message is not None:
53
+ job.error_message = error_message
54
+ db.commit()
55
+
56
+
57
+ def _mark_video_failed(db, video_id: int, title: str, task_id: str, upload_job_id, error_message: str):
58
+ video = db.query(Video).filter(Video.id == video_id).first()
59
+ if video:
60
+ video.status = "failed"
61
+ video.failed_at = func.now()
62
+ video.processing_message = error_message[:500] if error_message else "Failed"
63
+ owner = db.query(User).filter(User.id == video.owner_id).first()
64
+ if owner:
65
+ if video.video_type == "flash":
66
+ owner.flash_uploads = max(0, (owner.flash_uploads or 1) - 1)
67
+ else:
68
+ owner.home_uploads = max(0, (owner.home_uploads or 1) - 1)
69
+ db.commit()
70
+ try:
71
+ notify_user_push(
72
+ db,
73
+ user_id=video.owner_id,
74
+ title="Video Processing Failed",
75
+ body=f"Something went wrong while processing '{title}'. Please try uploading again.",
76
+ link="/upload",
77
+ n_type="status_change",
78
+ )
79
+ except Exception:
80
+ pass
81
+ _update_upload_job(
82
+ db, upload_job_id, UploadJobStatus.FAILED, error_message=error_message
83
+ )
84
+ try:
85
+ storage.delete_prefix(f"uploads/{task_id}/")
86
+ storage.delete_prefix(f"videos/{task_id}/")
87
+ except Exception as cleanup_err:
88
+ logger.warning(f"Storage cleanup failed: {cleanup_err}")
89
+
90
+
91
+ def _resolve_cover_url(raw: str | None) -> str | None:
92
+ """Accept a full URL or storage key from Rust / job row."""
93
+ if not raw:
94
+ return None
95
+ if str(raw).startswith("http://") or str(raw).startswith("https://"):
96
+ return str(raw)
97
+ return storage.get_url(str(raw))
98
+
99
+
100
+ def _finalize_transcode_success(
101
+ db, *, video_id: int, video_type: str, title: str, task_id: str,
102
+ thumbnail_provided: bool, upload_job_id,
103
+ status_data: dict | None = None,
104
+ ):
105
+ """After Rust finishes: wire up CDN URLs, cover fields, mark upload_job completed, notify."""
106
+ logger.info(f"Finalizing transcode for video_id={video_id} task_id={task_id}")
107
+ video_url = storage.get_url(f"videos/{task_id}/master.m3u8")
108
+
109
+ if video_type == "flash":
110
+ url_480p = url_720p = url_1080p = url_2k = url_4k = None
111
+ else:
112
+ url_480p = storage.get_url(f"videos/{task_id}/480p.m3u8")
113
+ url_720p = storage.get_url(f"videos/{task_id}/720p.m3u8")
114
+ url_1080p = storage.get_url(f"videos/{task_id}/1080p.m3u8")
115
+ url_2k = storage.get_url(f"videos/{task_id}/2k.m3u8")
116
+ url_4k = storage.get_url(f"videos/{task_id}/4k.m3u8")
117
+
118
+ generated_thumb_url = storage.get_url(f"thumbnails/{task_id}.jpg")
119
+ video = db.query(Video).filter(Video.id == video_id).first()
120
+ if not video:
121
+ _update_upload_job(
122
+ db, upload_job_id, UploadJobStatus.FAILED,
123
+ error_message="Video record missing after transcode",
124
+ )
125
+ return {"status": "error", "message": "video missing"}
126
+
127
+ # Cover metadata: prefer Rust completion payload, then upload_jobs row
128
+ status_data = status_data or {}
129
+ rust_cover_url = status_data.get("cover_url") or status_data.get("coverUrl")
130
+ rust_cover_source = status_data.get("cover_source") or status_data.get("coverSource")
131
+
132
+ job_cover_source = None
133
+ job_cover_s3_key = None
134
+ if upload_job_id:
135
+ try:
136
+ from uuid import UUID as _UUID
137
+ job_row = db.query(UploadJob).filter(UploadJob.id == _UUID(str(upload_job_id))).first()
138
+ if job_row:
139
+ job_cover_source = getattr(job_row, "cover_source", None)
140
+ job_cover_s3_key = getattr(job_row, "cover_s3_key", None)
141
+ except Exception as e:
142
+ logger.debug(f"upload_job cover lookup in finalize skipped: {e}")
143
+
144
+ cover_source = (
145
+ rust_cover_source
146
+ or job_cover_source
147
+ or ("custom" if thumbnail_provided else "auto")
148
+ )
149
+ cover_source = str(cover_source).strip().lower()
150
+ if cover_source not in ("auto", "custom"):
151
+ cover_source = "custom" if thumbnail_provided else "auto"
152
+
153
+ cover_url = _resolve_cover_url(rust_cover_url)
154
+ if not cover_url and cover_source == "custom" and job_cover_s3_key:
155
+ cover_url = _resolve_cover_url(job_cover_s3_key)
156
+ if not cover_url:
157
+ cover_url = generated_thumb_url
158
+
159
+ video.video_url = video_url
160
+ video.url_480p = url_480p
161
+ video.url_720p = url_720p
162
+ video.url_1080p = url_1080p
163
+ video.url_2k = url_2k
164
+ video.url_4k = url_4k
165
+ video.duration = 0
166
+ video.failed_at = None
167
+ video.status = "approved"
168
+ video.processing_message = "Live"
169
+ video.cover_source = cover_source
170
+ video.cover_url = cover_url
171
+ # Keep thumbnail_url aligned for existing clients / feeds
172
+ if cover_url:
173
+ video.thumbnail_url = cover_url
174
+ elif not thumbnail_provided and generated_thumb_url:
175
+ video.thumbnail_url = generated_thumb_url
176
+ db.commit()
177
+
178
+ # 2) completed + fill video_id on the upload_jobs row
179
+ _update_upload_job(
180
+ db, upload_job_id, UploadJobStatus.COMPLETED, video_id=video_id
181
+ )
182
+
183
+ try:
184
+ notify_user_push(
185
+ db,
186
+ user_id=video.owner_id,
187
+ title="Video Live! 🚀",
188
+ body=f"Your video '{title}' has been processed and is now live!",
189
+ link="/profile",
190
+ n_type="status_change",
191
+ )
192
+ except Exception:
193
+ pass
194
+
195
+ try:
196
+ storage.delete_prefix(f"uploads/{task_id}/")
197
+ except Exception as e:
198
+ logger.warning(f"Failed to delete source directory uploads/{task_id}/: {e}")
199
+
200
+ return {"status": "success", "video_id": video_id}
201
+
202
+
203
+ _POLL_COUNTDOWN_SEC = 3
204
+ # Fail only if live progress has not increased for this long.
205
+ _POLL_STALL_SEC = 90
206
+ # Absolute safety net (~45 minutes) regardless of progress movement.
207
+ _POLL_ABSOLUTE_CEILING_SEC = 45 * 60
208
+ _POLL_META_TTL_SEC = 60 * 60
209
+
210
+
211
+ def _progress_meta_key(task_id: str) -> str:
212
+ return f"job:progress:last_change:{task_id}"
213
+
214
+
215
+ def _read_live_progress(task_id: str, status_data: dict | None = None):
216
+ """Prefer Rust job:progress:{task_id}; fall back to coarse task:status progress."""
217
+ try:
218
+ raw = redis_client.get(f"job:progress:{task_id}")
219
+ if raw is not None and str(raw).strip() != "":
220
+ return float(raw)
221
+ except Exception as e:
222
+ logger.debug(f"job:progress read failed for {task_id}: {e}")
223
+
224
+ if status_data and isinstance(status_data.get("progress"), (int, float)):
225
+ return float(status_data["progress"])
226
+ return None
227
+
228
+
229
+ def _touch_progress_meta(task_id: str, current_progress: float | None) -> dict:
230
+ """
231
+ Track last-seen progress + when it last increased in Redis.
232
+ Key: job:progress:last_change:{task_id}
233
+ Value: {"progress": N, "changed_at": unix, "started_at": unix}
234
+ """
235
+ now = time.time()
236
+ key = _progress_meta_key(task_id)
237
+ meta = None
238
+ try:
239
+ raw = redis_client.get(key)
240
+ if raw:
241
+ meta = json.loads(raw)
242
+ except Exception:
243
+ meta = None
244
+
245
+ if not meta:
246
+ meta = {
247
+ "progress": current_progress if current_progress is not None else -1.0,
248
+ "changed_at": now,
249
+ "started_at": now,
250
+ }
251
+ try:
252
+ redis_client.set(key, json.dumps(meta), ex=_POLL_META_TTL_SEC)
253
+ except Exception as e:
254
+ logger.warning(f"Failed to init progress meta for {task_id}: {e}")
255
+ return meta
256
+
257
+ last_progress = float(meta.get("progress", -1.0))
258
+ if current_progress is not None and current_progress > last_progress:
259
+ meta["progress"] = current_progress
260
+ meta["changed_at"] = now
261
+ try:
262
+ redis_client.set(key, json.dumps(meta), ex=_POLL_META_TTL_SEC)
263
+ except Exception as e:
264
+ logger.warning(f"Failed to update progress meta for {task_id}: {e}")
265
+
266
+ return meta
267
+
268
+
269
+ def _clear_progress_meta(task_id: str) -> None:
270
+ try:
271
+ redis_client.delete(_progress_meta_key(task_id))
272
+ except Exception:
273
+ pass
274
+
275
+
276
+ def _final_rust_status_check(
277
+ db, *, video_type, title, video_id, thumbnail_provided, task_id, upload_job_id, reason: str
278
+ ):
279
+ """
280
+ Before failing on stall/ceiling: one synchronous GET to Rust.
281
+ Finalize if completed; otherwise mark failed.
282
+ """
283
+ logger.warning(
284
+ f"{reason} for task_id={task_id}; "
285
+ f"final GET {config.RUST_SERVICE_URL}/status/{task_id}"
286
+ )
287
+ try:
288
+ final_resp = requests.get(
289
+ f"{config.RUST_SERVICE_URL}/status/{task_id}", timeout=10.0
290
+ )
291
+ if final_resp.status_code == 200:
292
+ final_data = final_resp.json() or {}
293
+ final_status = (final_data.get("status") or "").lower()
294
+ if final_status in ("completed", "uploaded", "success"):
295
+ logger.info(
296
+ f"Final status check: task_id={task_id} completed — finalizing"
297
+ )
298
+ _clear_progress_meta(task_id)
299
+ return _finalize_transcode_success(
300
+ db,
301
+ video_id=video_id,
302
+ video_type=video_type,
303
+ title=title,
304
+ task_id=task_id,
305
+ thumbnail_provided=thumbnail_provided,
306
+ upload_job_id=upload_job_id,
307
+ status_data=final_data,
308
+ )
309
+ if final_status == "error":
310
+ err = final_data.get("message") or "Rust processing error"
311
+ _clear_progress_meta(task_id)
312
+ _mark_video_failed(db, video_id, title, task_id, upload_job_id, err)
313
+ return {"status": "failed", "error": err}
314
+ err = (
315
+ f"Background processing timed out for task {task_id} "
316
+ f"({reason}; final status={final_status or 'unknown'})"
317
+ )
318
+ elif final_resp.status_code == 404:
319
+ err = (
320
+ f"Background processing timed out for task {task_id} "
321
+ f"({reason}; status endpoint returned 404)"
322
+ )
323
+ else:
324
+ err = (
325
+ f"Background processing timed out for task {task_id} "
326
+ f"({reason}; status endpoint returned {final_resp.status_code})"
327
+ )
328
+ except Exception as e:
329
+ err = (
330
+ f"Background processing timed out for task {task_id} "
331
+ f"({reason}; final status check unreachable: {e})"
332
+ )
333
+
334
+ _clear_progress_meta(task_id)
335
+ _mark_video_failed(db, video_id, title, task_id, upload_job_id, err)
336
+ return {"status": "failed", "error": err}
337
+
338
+
339
  @shared_task(bind=True, name="video_tasks.process_video", max_retries=3)
340
+ def process_video_task(
341
+ self,
342
+ source_key: str,
343
+ video_type: str,
344
+ title: str,
345
+ video_id: int,
346
+ thumbnail_provided: bool,
347
+ task_id: str,
348
+ upload_job_id: str = None,
349
+ ):
350
+ """
351
+ Dispatch to Rust only — does not wait for transcode.
352
+ Status polling runs in poll_video_transcode so multiple uploads can
353
+ sit on the Rust queue / worker pool at the same time.
354
+ """
355
+ logger.info(
356
+ f"Dispatching video_id={video_id} task_id={task_id} upload_job_id={upload_job_id}"
357
+ )
358
  db = SessionLocal()
359
  try:
360
+ # Prefer cover metadata from the upload_jobs row when present
361
+ cover_source = "custom" if thumbnail_provided else "auto"
362
+ cover_s3_key = None
363
+ if upload_job_id:
364
+ try:
365
+ from uuid import UUID as _UUID
366
+ job_row = db.query(UploadJob).filter(UploadJob.id == _UUID(str(upload_job_id))).first()
367
+ if job_row:
368
+ cover_source = getattr(job_row, "cover_source", None) or cover_source
369
+ cover_s3_key = getattr(job_row, "cover_s3_key", None)
370
+ if cover_source == "custom":
371
+ thumbnail_provided = True
372
+ except Exception as e:
373
+ logger.debug(f"upload_job cover lookup skipped: {e}")
374
+
375
+ # Resolve tier best-effort — never block the Rust handoff on a flaky DB
376
  try:
377
+ tier = _resolve_user_tier(db, video_id)
378
+ except Exception as e:
379
+ logger.warning(f"Tier lookup failed for video_id={video_id}, defaulting free: {e}")
380
+ tier = "free"
381
  try:
382
+ db.rollback()
383
+ except Exception:
384
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
385
 
386
+ # Call Rust FIRST so DB blips cannot prevent transcode from starting
387
+ skip_thumbnail = bool(thumbnail_provided) or cover_source == "custom"
388
+ rust_payload = {
389
+ "video_id": source_key,
390
+ "target_format": video_type,
391
+ "skip_thumbnail": skip_thumbnail,
392
+ "task_id": task_id,
393
+ "tier": tier,
394
+ "coverSource": cover_source,
395
+ }
396
+ if cover_source == "custom" and cover_s3_key:
397
+ rust_payload["coverS3Key"] = cover_s3_key
398
+ rust_payload["cover_s3_key"] = cover_s3_key # snake_case alias
399
+
400
+ logger.info(
401
+ f"POST {config.RUST_SERVICE_URL}/process source={source_key} tier={tier} "
402
+ f"coverSource={cover_source} coverS3Key={cover_s3_key}"
403
+ )
404
+ try:
405
+ rust_response = requests.post(
406
+ f"{config.RUST_SERVICE_URL}/process",
407
+ json=rust_payload,
408
+ timeout=30.0,
409
+ )
410
+ logger.info(f"Rust responded {rust_response.status_code}")
411
+ rust_response.raise_for_status()
412
+ except requests.exceptions.RequestException as re:
413
+ err = f"Rust service unreachable or returned error: {re}"
414
+ logger.error(err)
415
+ if self.request.retries < self.max_retries:
416
+ raise self.retry(exc=Exception(err), countdown=60)
417
+ try:
418
+ _mark_video_failed(db, video_id, title, task_id, upload_job_id, err)
419
+ except Exception:
420
+ logger.exception("Failed to mark video failed after Rust error")
421
+ raise Exception(err)
422
+
423
+ # Best-effort DB status updates after Rust has accepted the job
424
+ try:
425
+ _update_upload_job(db, upload_job_id, UploadJobStatus.PROCESSING)
426
+ video = db.query(Video).filter(Video.id == video_id).first()
427
+ if video:
428
+ video.status = "processing"
429
+ video.processing_message = "Queued for transcode"
430
+ db.commit()
431
  except Exception as e:
432
+ logger.warning(
433
+ f"Post-dispatch DB update failed for video_id={video_id} "
434
+ f"(Rust already accepted task_id={task_id}): {e}"
435
+ )
436
+ try:
437
+ db.rollback()
438
+ except Exception:
439
+ pass
440
+
441
+ # Seed stall-detection meta so the absolute ceiling starts now
442
+ _touch_progress_meta(task_id, 0.0)
443
+
444
+ # Hand off to non-blocking poller so this worker is free for the next upload
445
+ poll_video_transcode.delay(
446
+ video_type,
447
+ title,
448
+ video_id,
449
+ thumbnail_provided,
450
+ task_id,
451
+ upload_job_id,
452
+ 0,
453
+ )
454
+ return {"status": "dispatched", "task_id": task_id, "upload_job_id": upload_job_id}
455
+ finally:
456
+ db.close()
457
+
458
+
459
+ @shared_task(name="video_tasks.poll_video_transcode")
460
+ def poll_video_transcode(
461
+ video_type: str,
462
+ title: str,
463
+ video_id: int,
464
+ thumbnail_provided: bool,
465
+ task_id: str,
466
+ upload_job_id: str = None,
467
+ attempt: int = 0,
468
+ ):
469
+ """
470
+ Poll Rust/Redis once; reschedule until done.
471
+
472
+ Timeout model (stall detection):
473
+ - Read live percent from job:progress:{task_id} (fallback: task:status progress)
474
+ - Track last increase in job:progress:last_change:{task_id}
475
+ - Fail only after _POLL_STALL_SEC with no progress increase
476
+ - Absolute ceiling _POLL_ABSOLUTE_CEILING_SEC as a safety net
477
+ - Before failing, one final GET /status/{task_id} (finalize if completed)
478
+ """
479
+ db = SessionLocal()
480
+ try:
481
+ status_data = None
482
+ try:
483
+ status_data_raw = redis_client.get(f"task:status:{task_id}")
484
+ if status_data_raw:
485
+ status_data = json.loads(status_data_raw)
486
  else:
487
+ status_resp = requests.get(
488
+ f"{config.RUST_SERVICE_URL}/status/{task_id}", timeout=2.0
489
+ )
490
+ if status_resp.status_code == 200:
491
+ status_data = status_resp.json()
492
+ except Exception as e:
493
+ logger.warning(f"Poll error for {task_id} (attempt {attempt}): {e}")
494
 
495
+ live_progress = _read_live_progress(task_id, status_data)
496
+ meta = _touch_progress_meta(task_id, live_progress)
497
+ now = time.time()
498
+ started_at = float(meta.get("started_at") or now)
499
+ changed_at = float(meta.get("changed_at") or now)
500
+ stall_secs = now - changed_at
501
+ elapsed_secs = now - started_at
502
+
503
+ if status_data:
504
+ current_status = (status_data.get("status") or "").lower()
505
+ # Prefer live encode %, else coarse status progress for UI message
506
+ progress = (
507
+ int(live_progress)
508
+ if live_progress is not None
509
+ else int(status_data.get("progress") or 0)
510
+ )
511
+ msg = status_data.get("message", "")
512
+
513
+ video = db.query(Video).filter(Video.id == video_id).first()
514
+ if video:
515
+ video.processing_message = f"{msg} ({progress}%)"
516
+ db.commit()
517
+
518
+ if current_status in ("completed", "uploaded", "success"):
519
+ _clear_progress_meta(task_id)
520
+ return _finalize_transcode_success(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521
  db,
522
+ video_id=video_id,
523
+ video_type=video_type,
524
+ title=title,
525
+ task_id=task_id,
526
+ thumbnail_provided=thumbnail_provided,
527
+ upload_job_id=upload_job_id,
528
+ status_data=status_data,
529
  )
 
 
530
 
531
+ if current_status == "error":
532
+ err = msg or "Rust processing error"
533
+ _clear_progress_meta(task_id)
534
+ _mark_video_failed(db, video_id, title, task_id, upload_job_id, err)
535
+ return {"status": "failed", "error": err}
 
 
 
 
536
 
537
+ # Absolute ceiling (safety net for pathological cases)
538
+ if elapsed_secs >= _POLL_ABSOLUTE_CEILING_SEC:
539
+ return _final_rust_status_check(
540
+ db,
541
+ video_type=video_type,
542
+ title=title,
543
+ video_id=video_id,
544
+ thumbnail_provided=thumbnail_provided,
545
+ task_id=task_id,
546
+ upload_job_id=upload_job_id,
547
+ reason=f"absolute ceiling {_POLL_ABSOLUTE_CEILING_SEC}s exceeded",
548
+ )
549
+
550
+ # Stall: no progress increase for the stall window
551
+ if stall_secs >= _POLL_STALL_SEC:
552
+ return _final_rust_status_check(
553
+ db,
554
+ video_type=video_type,
555
+ title=title,
556
+ video_id=video_id,
557
+ thumbnail_provided=thumbnail_provided,
558
+ task_id=task_id,
559
+ upload_job_id=upload_job_id,
560
+ reason=(
561
+ f"progress stalled for {int(stall_secs)}s "
562
+ f"(last={meta.get('progress')}%)"
563
+ ),
564
+ )
565
+
566
+ # Still progressing (or within stall grace) — check again soon
567
+ poll_video_transcode.apply_async(
568
+ args=[
569
+ video_type,
570
+ title,
571
+ video_id,
572
+ thumbnail_provided,
573
+ task_id,
574
+ upload_job_id,
575
+ attempt + 1,
576
+ ],
577
+ countdown=_POLL_COUNTDOWN_SEC,
578
+ )
579
+ return {
580
+ "status": "polling",
581
+ "attempt": attempt,
582
+ "progress": live_progress,
583
+ "stall_secs": round(stall_secs, 1),
584
+ "elapsed_secs": round(elapsed_secs, 1),
585
+ }
586
  finally:
587
  db.close()
588
 
app/worker.py CHANGED
@@ -20,6 +20,11 @@ celery_app = Celery(
20
  ]
21
  )
22
 
 
 
 
 
 
23
  celery_app.conf.update(
24
  task_serializer="json",
25
  accept_content=["json"],
 
20
  ]
21
  )
22
 
23
+ # Ensure @shared_task.delay() from FastAPI/scripts always uses this Redis broker
24
+ # (otherwise Celery falls back to amqp://localhost and enqueue silently fails).
25
+ celery_app.set_default()
26
+ celery_app.set_current()
27
+
28
  celery_app.conf.update(
29
  task_serializer="json",
30
  accept_content=["json"],
requirements.txt CHANGED
@@ -1,5 +1,6 @@
1
  fastapi[all]
2
  uvicorn
 
3
  python-dotenv
4
  python-jose[cryptography]
5
  passlib[bcrypt]
 
1
  fastapi[all]
2
  uvicorn
3
+ gunicorn
4
  python-dotenv
5
  python-jose[cryptography]
6
  passlib[bcrypt]
start.sh CHANGED
@@ -1,6 +1,19 @@
1
  #!/bin/bash
2
  set -e
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  echo "Starting Celery worker in background..."
5
  celery -A app.worker.celery_app worker \
6
  --loglevel=info \
@@ -11,5 +24,14 @@ echo "Starting Celery beat scheduler in background..."
11
  celery -A app.worker.celery_app beat \
12
  --loglevel=info &
13
 
14
- echo "Starting FastAPI server on port 7860..."
15
- exec uvicorn main:app --host 0.0.0.0 --port 7860 --workers 1
 
 
 
 
 
 
 
 
 
 
1
  #!/bin/bash
2
  set -e
3
 
4
+ # Size HTTP workers for the Space CPU tier (clamp 2–4).
5
+ # Override with WEB_CONCURRENCY if needed.
6
+ CORES=$(nproc 2>/dev/null || echo 2)
7
+ if [ -n "${WEB_CONCURRENCY:-}" ]; then
8
+ WORKERS="$WEB_CONCURRENCY"
9
+ elif [ "$CORES" -le 1 ]; then
10
+ WORKERS=2
11
+ elif [ "$CORES" -ge 4 ]; then
12
+ WORKERS=4
13
+ else
14
+ WORKERS="$CORES"
15
+ fi
16
+
17
  echo "Starting Celery worker in background..."
18
  celery -A app.worker.celery_app worker \
19
  --loglevel=info \
 
24
  celery -A app.worker.celery_app beat \
25
  --loglevel=info &
26
 
27
+ echo "Starting FastAPI via gunicorn (${WORKERS} uvicorn workers, $(nproc 2>/dev/null || echo '?') CPU cores)..."
28
+ exec gunicorn main:app \
29
+ --worker-class uvicorn.workers.UvicornWorker \
30
+ --workers "$WORKERS" \
31
+ --bind "0.0.0.0:${PORT:-7860}" \
32
+ --timeout 120 \
33
+ --graceful-timeout 30 \
34
+ --keep-alive 5 \
35
+ --access-logfile - \
36
+ --error-logfile - \
37
+ --log-level info