Refactor scheduled task repository and schemas for improved type hints and consistency

- Updated type hints from List/Optional to list/None for better readability and consistency across the codebase.
- Refactored import statements for better organization and clarity.
- Enhanced the ScheduledTaskBase schema to use modern type hints.
- Cleaned up unnecessary comments and whitespace in various files.
- Improved error handling and logging in task execution handlers.
- Updated test cases to reflect changes in type hints and ensure compatibility with the new structure.
This commit is contained in:
JSC
2025-08-28 23:38:47 +02:00
parent 96801dc4d6
commit dc89e45675
19 changed files with 292 additions and 291 deletions

View File

@@ -1,6 +1,5 @@
"""Task execution handlers for different task types."""
from typing import Any, Dict, Optional
from collections.abc import Callable
from sqlmodel.ext.asyncio.session import AsyncSession
@@ -18,7 +17,6 @@ logger = get_logger(__name__)
class TaskExecutionError(Exception):
"""Exception raised when task execution fails."""
pass
class TaskHandlerRegistry:
@@ -58,8 +56,8 @@ class TaskHandlerRegistry:
await handler(task)
logger.info(f"Task {task.id} executed successfully")
except Exception as e:
logger.exception(f"Task {task.id} execution failed: {str(e)}")
raise TaskExecutionError(f"Task execution failed: {str(e)}") from e
logger.exception(f"Task {task.id} execution failed: {e!s}")
raise TaskExecutionError(f"Task execution failed: {e!s}") from e
async def _handle_credit_recharge(self, task: ScheduledTask) -> None:
"""Handle credit recharge task."""
@@ -72,7 +70,7 @@ class TaskHandlerRegistry:
user_id_int = int(user_id)
except (ValueError, TypeError) as e:
raise TaskExecutionError(f"Invalid user_id format: {user_id}") from e
stats = await self.credit_service.recharge_user_credits(user_id_int)
logger.info(f"Recharged credits for user {user_id}: {stats}")
else:
@@ -105,7 +103,7 @@ class TaskHandlerRegistry:
logger.info(f"Played sound {result.get('sound_name', sound_id)} via scheduled task for user {task.user_id} (credits deducted: {result.get('credits_deducted', 0)})")
except Exception as e:
# Convert HTTP exceptions or credit errors to task execution errors
raise TaskExecutionError(f"Failed to play sound with credits: {str(e)}") from e
raise TaskExecutionError(f"Failed to play sound with credits: {e!s}") from e
else:
# System task: play without credit deduction
sound = await self.sound_repository.get_by_id(sound_id_int)
@@ -116,10 +114,10 @@ class TaskHandlerRegistry:
vlc_service = VLCPlayerService(self.db_session_factory)
success = await vlc_service.play_sound(sound)
if not success:
raise TaskExecutionError(f"Failed to play sound {sound.filename}")
logger.info(f"Played sound {sound.filename} via scheduled system task")
async def _handle_play_playlist(self, task: ScheduledTask) -> None:
@@ -157,4 +155,4 @@ class TaskHandlerRegistry:
# Start playing
await self.player_service.play()
logger.info(f"Started playing playlist {playlist.name} via scheduled task")
logger.info(f"Started playing playlist {playlist.name} via scheduled task")