Skip to content

Refactor: Extract transcoding job state machine into explicit code #438

@filthyrake

Description

@filthyrake

Problem

The transcoding_jobs table in api/database.py (lines 153-202) has a 109-line comment block describing the state machine transitions. While the documentation is thorough, its length suggests the code itself doesn't make the state transitions clear.

Current State

States are implicitly derived from combinations of nullable fields:

  • claimed_at IS NULL AND completed_at IS NULL → unclaimed
  • claimed_at IS NOT NULL AND claim_expires_at > now() → actively claimed
  • etc.

This requires reading extensive comments to understand the business logic.

Suggested Approach

Extract into an explicit state machine class:

class TranscodingJobStateMachine:
    """Manages state transitions for transcoding jobs."""
    
    def is_unclaimed(self, job: JobRow) -> bool:
        """Job is available for workers to claim."""
        return job.claimed_at is None and job.completed_at is None
    
    def is_actively_claimed(self, job: JobRow) -> bool:
        """Worker has valid claim on this job."""
        if job.claimed_at is None or job.completed_at is not None:
            return False
        return job.claim_expires_at > datetime.now(timezone.utc)
    
    def is_claim_expired(self, job: JobRow) -> bool:
        """Worker's claim has expired, job can be reclaimed."""
        if job.claimed_at is None or job.completed_at is not None:
            return False
        return job.claim_expires_at <= datetime.now(timezone.utc)
    
    def can_transition_to(self, job: JobRow, target_state: str) -> bool:
        """Check if a state transition is valid."""
        # Explicit transition rules

Benefits

  • States are self-documenting
  • Code reads like requirements
  • Easier to test state transitions
  • Comments become unnecessary

Files Affected

  • api/database.py
  • Possibly extract to new api/job_state.py

From code clarity review by Conway

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions