paper-dynasty-discord/play_lock.py
Cal Corum ee80cd72ae fix: apply Black formatting and resolve ruff lint violations
Run Black formatter across 83 files and fix 1514 ruff violations:
- E722: bare except → typed exceptions (17 fixes)
- E711/E712/E721: comparison style fixes with noqa for SQLAlchemy (44 fixes)
- F841: unused variable assignments (70 fixes)
- F541/F401: f-string and import cleanup (1383 auto-fixes)

Remaining 925 errors are all F403/F405 (star imports) — structural,
requires converting to explicit imports in a separate effort.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 11:37:46 -05:00

76 lines
2.4 KiB
Python

"""
Play locking utilities to prevent concurrent play modifications.
This module is separate to avoid circular imports between logic_gameplay and utilities.
"""
import logging
from contextlib import contextmanager
from sqlmodel import Session
logger = logging.getLogger("discord_app")
def release_play_lock(session: Session, play: "Play") -> None:
"""
Release a play lock and commit the change.
This is a safety mechanism to ensure locks are always released,
even when exceptions occur during command processing.
"""
if play.locked:
logger.info(f"Releasing lock on play {play.id}")
play.locked = False
session.add(play)
session.commit()
@contextmanager
def safe_play_lock(session: Session, play: "Play"):
"""
Context manager for safely handling play locks.
Ensures the lock is ALWAYS released even if an exception occurs during
command processing. This prevents permanent user lockouts.
Usage:
with safe_play_lock(session, this_play):
# Do command processing
# Lock will be released automatically on exception or normal exit
pass
Note: This only releases the lock on exception. On successful completion,
complete_play() should handle releasing the lock and marking the play complete.
"""
lock_released = False
try:
yield play
except Exception as e:
# Release lock on any exception
if play.locked and not play.complete:
logger.error(
f"Exception during play {play.id} processing, releasing lock. Error: {e}"
)
play.locked = False
session.add(play)
try:
session.commit()
lock_released = True
except Exception as commit_error:
logger.error(
f"Failed to release lock on play {play.id}: {commit_error}"
)
raise # Re-raise the original exception
finally:
# Final safety check
if not lock_released and play.locked and not play.complete:
logger.warning(
f"Play {play.id} still locked after processing, forcing unlock"
)
play.locked = False
session.add(play)
try:
session.commit()
except Exception as commit_error:
logger.error(f"Failed to force unlock play {play.id}: {commit_error}")