|
| 1 | +"""Job repository with worker-safe operations. |
| 2 | +
|
| 3 | +Provides CRUD operations for jobs with atomic claim, progress updates, |
| 4 | +and status transitions. Uses optimistic locking for concurrency control. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +from datetime import UTC, datetime |
| 10 | +from uuid import UUID |
| 11 | + |
| 12 | +from sqlalchemy import func, select, update |
| 13 | + |
| 14 | +from bookbytes.models.job import Job, JobStatus, JobType |
| 15 | +from bookbytes.repositories.base import BaseRepository |
| 16 | + |
| 17 | + |
| 18 | +class JobRepository(BaseRepository[Job]): |
| 19 | + """Repository for Job model with worker-safe operations. |
| 20 | +
|
| 21 | + Provides atomic operations for job claiming and status updates |
| 22 | + to ensure safe concurrent access from multiple workers. |
| 23 | + """ |
| 24 | + |
| 25 | + async def claim_next( |
| 26 | + self, |
| 27 | + worker_id: str, |
| 28 | + job_type: str | None = None, |
| 29 | + ) -> Job | None: |
| 30 | + """Atomically claim the next pending job. |
| 31 | +
|
| 32 | + Uses optimistic locking via version column to prevent |
| 33 | + race conditions when multiple workers try to claim jobs. |
| 34 | +
|
| 35 | + Args: |
| 36 | + worker_id: Identifier of the claiming worker |
| 37 | + job_type: Optional filter by job type |
| 38 | +
|
| 39 | + Returns: |
| 40 | + The claimed job, or None if no jobs available |
| 41 | + """ |
| 42 | + # Find oldest pending job |
| 43 | + query = ( |
| 44 | + select(Job) |
| 45 | + .where(Job.status == JobStatus.PENDING.value) |
| 46 | + .order_by(Job.created_at) |
| 47 | + .limit(1) |
| 48 | + ) |
| 49 | + |
| 50 | + if job_type: |
| 51 | + query = query.where(Job.job_type == job_type) |
| 52 | + |
| 53 | + result = await self.session.execute(query) |
| 54 | + job = result.scalar_one_or_none() |
| 55 | + |
| 56 | + if not job: |
| 57 | + return None |
| 58 | + |
| 59 | + # Atomically claim with optimistic lock |
| 60 | + stmt = ( |
| 61 | + update(Job) |
| 62 | + .where(Job.id == job.id) |
| 63 | + .where(Job.version == job.version) # Optimistic lock |
| 64 | + .values( |
| 65 | + status=JobStatus.PROCESSING.value, |
| 66 | + worker_id=worker_id, |
| 67 | + started_at=datetime.now(UTC), |
| 68 | + version=job.version + 1, |
| 69 | + ) |
| 70 | + .returning(Job) |
| 71 | + ) |
| 72 | + |
| 73 | + result = await self.session.execute(stmt) |
| 74 | + claimed = result.scalar_one_or_none() |
| 75 | + |
| 76 | + if claimed: |
| 77 | + await self.session.commit() |
| 78 | + |
| 79 | + return claimed |
| 80 | + |
| 81 | + async def update_progress( |
| 82 | + self, |
| 83 | + job_id: UUID, |
| 84 | + progress: int, |
| 85 | + current_step: str | None = None, |
| 86 | + ) -> bool: |
| 87 | + """Update job progress. |
| 88 | +
|
| 89 | + Args: |
| 90 | + job_id: The job's UUID |
| 91 | + progress: Progress percentage (0-100) |
| 92 | + current_step: Optional human-readable step description |
| 93 | +
|
| 94 | + Returns: |
| 95 | + True if update succeeded, False if job not found |
| 96 | + """ |
| 97 | + values: dict[str, int | str | None] = {"progress": min(100, max(0, progress))} |
| 98 | + if current_step is not None: |
| 99 | + values["current_step"] = current_step |
| 100 | + |
| 101 | + stmt = update(Job).where(Job.id == job_id).values(**values) |
| 102 | + result = await self.session.execute(stmt) |
| 103 | + await self.session.commit() |
| 104 | + |
| 105 | + return result.rowcount > 0 |
| 106 | + |
| 107 | + async def mark_completed(self, job_id: UUID) -> bool: |
| 108 | + """Mark job as completed. |
| 109 | +
|
| 110 | + Args: |
| 111 | + job_id: The job's UUID |
| 112 | +
|
| 113 | + Returns: |
| 114 | + True if update succeeded |
| 115 | + """ |
| 116 | + stmt = ( |
| 117 | + update(Job) |
| 118 | + .where(Job.id == job_id) |
| 119 | + .values( |
| 120 | + status=JobStatus.COMPLETED.value, |
| 121 | + progress=100, |
| 122 | + completed_at=datetime.now(UTC), |
| 123 | + ) |
| 124 | + ) |
| 125 | + result = await self.session.execute(stmt) |
| 126 | + await self.session.commit() |
| 127 | + |
| 128 | + return result.rowcount > 0 |
| 129 | + |
| 130 | + async def mark_failed( |
| 131 | + self, |
| 132 | + job_id: UUID, |
| 133 | + error_message: str, |
| 134 | + error_code: str | None = None, |
| 135 | + ) -> bool: |
| 136 | + """Mark job as failed with error details. |
| 137 | +
|
| 138 | + Args: |
| 139 | + job_id: The job's UUID |
| 140 | + error_message: Human-readable error message |
| 141 | + error_code: Optional machine-readable error code |
| 142 | +
|
| 143 | + Returns: |
| 144 | + True if update succeeded |
| 145 | + """ |
| 146 | + stmt = ( |
| 147 | + update(Job) |
| 148 | + .where(Job.id == job_id) |
| 149 | + .values( |
| 150 | + status=JobStatus.FAILED.value, |
| 151 | + error_message=error_message[:2000], # Truncate to fit |
| 152 | + error_code=error_code[:50] if error_code else None, |
| 153 | + completed_at=datetime.now(UTC), |
| 154 | + ) |
| 155 | + ) |
| 156 | + result = await self.session.execute(stmt) |
| 157 | + await self.session.commit() |
| 158 | + |
| 159 | + return result.rowcount > 0 |
| 160 | + |
| 161 | + async def schedule_retry(self, job_id: UUID) -> bool: |
| 162 | + """Schedule a failed job for retry. |
| 163 | +
|
| 164 | + Increments retry_count and sets status back to pending. |
| 165 | +
|
| 166 | + Args: |
| 167 | + job_id: The job's UUID |
| 168 | +
|
| 169 | + Returns: |
| 170 | + True if retry scheduled, False if max retries exceeded |
| 171 | + """ |
| 172 | + # Get current job state |
| 173 | + job = await self.get_by_id(job_id) |
| 174 | + if not job or not job.can_retry: |
| 175 | + return False |
| 176 | + |
| 177 | + stmt = ( |
| 178 | + update(Job) |
| 179 | + .where(Job.id == job_id) |
| 180 | + .values( |
| 181 | + status=JobStatus.PENDING.value, |
| 182 | + retry_count=job.retry_count + 1, |
| 183 | + worker_id=None, |
| 184 | + started_at=None, |
| 185 | + completed_at=None, |
| 186 | + error_message=None, |
| 187 | + error_code=None, |
| 188 | + ) |
| 189 | + ) |
| 190 | + await self.session.execute(stmt) |
| 191 | + await self.session.commit() |
| 192 | + |
| 193 | + return True |
| 194 | + |
| 195 | + async def get_by_status( |
| 196 | + self, |
| 197 | + status: JobStatus, |
| 198 | + limit: int = 100, |
| 199 | + ) -> list[Job]: |
| 200 | + """Get jobs by status. |
| 201 | +
|
| 202 | + Args: |
| 203 | + status: The status to filter by |
| 204 | + limit: Maximum number of results |
| 205 | +
|
| 206 | + Returns: |
| 207 | + List of jobs with the given status |
| 208 | + """ |
| 209 | + query = ( |
| 210 | + select(Job) |
| 211 | + .where(Job.status == status.value) |
| 212 | + .order_by(Job.created_at) |
| 213 | + .limit(limit) |
| 214 | + ) |
| 215 | + result = await self.session.execute(query) |
| 216 | + return list(result.scalars().all()) |
| 217 | + |
| 218 | + async def get_pending_count(self) -> int: |
| 219 | + """Get count of pending jobs (for monitoring). |
| 220 | +
|
| 221 | + Returns: |
| 222 | + Number of pending jobs |
| 223 | + """ |
| 224 | + query = ( |
| 225 | + select(func.count()) |
| 226 | + .select_from(Job) |
| 227 | + .where(Job.status == JobStatus.PENDING.value) |
| 228 | + ) |
| 229 | + result = await self.session.execute(query) |
| 230 | + return result.scalar() or 0 |
| 231 | + |
| 232 | + async def get_by_job_type( |
| 233 | + self, |
| 234 | + job_type: JobType, |
| 235 | + limit: int = 100, |
| 236 | + ) -> list[Job]: |
| 237 | + """Get jobs by type. |
| 238 | +
|
| 239 | + Args: |
| 240 | + job_type: The job type to filter by |
| 241 | + limit: Maximum number of results |
| 242 | +
|
| 243 | + Returns: |
| 244 | + List of jobs of the given type |
| 245 | + """ |
| 246 | + query = ( |
| 247 | + select(Job) |
| 248 | + .where(Job.job_type == job_type.value) |
| 249 | + .order_by(Job.created_at.desc()) |
| 250 | + .limit(limit) |
| 251 | + ) |
| 252 | + result = await self.session.execute(query) |
| 253 | + return list(result.scalars().all()) |
0 commit comments