Initial commit
This commit is contained in:
@@ -0,0 +1,311 @@
|
||||
"""
|
||||
Service for Resource Allocation operations.
|
||||
|
||||
Handles allocation of resources from project pool to Systems/Guardians.
|
||||
Implements all business rules from 003-business-rules-design-v1.md.
|
||||
"""
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from app.models import (
|
||||
Resource,
|
||||
ResourceAllocation,
|
||||
SystemModule,
|
||||
System,
|
||||
Guardian,
|
||||
Module,
|
||||
Project
|
||||
)
|
||||
from app.services.exceptions import ResourceNotFoundError, SystemNotFoundError, AllocationError, ValidationError, GuardianNotFoundError
|
||||
|
||||
|
||||
class ResourceAllocationError(Exception):
|
||||
"""Base exception for resource allocation errors"""
|
||||
pass
|
||||
|
||||
|
||||
class InsufficientBalanceError(ResourceAllocationError):
|
||||
"""Not enough remaining balance in resource"""
|
||||
pass
|
||||
|
||||
|
||||
class CoreInCommonError(ResourceAllocationError):
|
||||
"""Cannot allocate Core to Common part"""
|
||||
pass
|
||||
|
||||
|
||||
class InvalidGuardianError(ResourceAllocationError):
|
||||
"""Guardian doesn't belong to specified System"""
|
||||
pass
|
||||
|
||||
|
||||
class ProjectMismatchError(ResourceAllocationError):
|
||||
"""Resource and System belong to different Projects"""
|
||||
pass
|
||||
|
||||
|
||||
class CoreAlreadyExistsError(ResourceAllocationError):
|
||||
"""Cannot create second Core for same Guardian"""
|
||||
pass
|
||||
|
||||
|
||||
class ResourceAllocationService:
|
||||
"""Service for resource allocation operations"""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def allocate_resource(
|
||||
self,
|
||||
resource_id: int,
|
||||
system_id: int,
|
||||
quantity: int,
|
||||
guardian_id: int | None = None,
|
||||
module_name: str | None = None,
|
||||
description: str | None = None
|
||||
) -> ResourceAllocation:
|
||||
"""
|
||||
Allocate resource to System/Guardian.
|
||||
|
||||
Atomic operation that:
|
||||
1. Validates all conditions
|
||||
2. Creates ResourceAllocation
|
||||
3. Updates/creates SystemModule
|
||||
4. Commits all changes
|
||||
|
||||
Args:
|
||||
resource_id: ID of Resource to allocate from
|
||||
system_id: ID of System to allocate to
|
||||
quantity: Amount to allocate
|
||||
guardian_id: Optional Guardian ID (NULL for Common part)
|
||||
module_name: Optional module name (used for Core validation)
|
||||
description: Optional description
|
||||
|
||||
Returns:
|
||||
Created ResourceAllocation
|
||||
|
||||
Raises:
|
||||
ResourceNotFoundError: If Resource doesn't exist
|
||||
SystemNotFoundError: If System doesn't exist
|
||||
InsufficientBalanceError: Not enough remaining balance
|
||||
CoreInCommonError: Cannot allocate Core to Common
|
||||
InvalidGuardianError: Guardian doesn't belong to System
|
||||
ProjectMismatchError: Resource and System different Projects
|
||||
ValidationError: If quantity <= 0
|
||||
IntegrityError: If Core already exists for Guardian
|
||||
"""
|
||||
|
||||
# Validate quantity > 0
|
||||
if quantity <= 0:
|
||||
raise ValidationError("Quantity must be greater than 0")
|
||||
|
||||
# Retry loop for concurrent allocation protection
|
||||
max_retries = 3
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
return self._allocate_atomic(
|
||||
resource_id=resource_id,
|
||||
system_id=system_id,
|
||||
quantity=quantity,
|
||||
guardian_id=guardian_id,
|
||||
module_name=module_name,
|
||||
description=description
|
||||
)
|
||||
except IntegrityError as e:
|
||||
# Core already exists for Guardian
|
||||
if "Core already exists" in str(e):
|
||||
raise CoreAlreadyExistsError("Cannot create second Core for same Guardian")
|
||||
# Retry on potential race condition
|
||||
if attempt < max_retries - 1:
|
||||
self.db.rollback()
|
||||
continue
|
||||
raise
|
||||
except IntegrityError:
|
||||
# Other integrity errors - don't retry
|
||||
raise
|
||||
|
||||
# Should never reach here, but just in case
|
||||
self.db.rollback()
|
||||
raise ResourceAllocationError("Failed to allocate after multiple attempts")
|
||||
|
||||
def _allocate_atomic(
|
||||
self,
|
||||
resource_id: int,
|
||||
system_id: int,
|
||||
quantity: int,
|
||||
guardian_id: int | None,
|
||||
module_name: str | None,
|
||||
description: str | None
|
||||
) -> ResourceAllocation:
|
||||
"""
|
||||
Core allocation logic within transaction boundary.
|
||||
All checks and updates happen in one transaction.
|
||||
"""
|
||||
|
||||
# 1. Validate Resource exists
|
||||
resource = self.db.query(Resource).filter(
|
||||
Resource.id == resource_id
|
||||
).first()
|
||||
|
||||
if not resource:
|
||||
raise ResourceNotFoundError(f"Resource {resource_id} not found")
|
||||
|
||||
# 2. Validate System exists
|
||||
system = self.db.query(System).filter(
|
||||
System.id == system_id
|
||||
).first()
|
||||
|
||||
if not system:
|
||||
raise SystemNotFoundError(f"System {system_id} not found")
|
||||
|
||||
# 3. Check Project match
|
||||
if resource.project_id != system.project_id:
|
||||
raise ProjectMismatchError(
|
||||
f"Resource belongs to Project {resource.project_id}, "
|
||||
f"System belongs to Project {system.project_id}"
|
||||
)
|
||||
|
||||
# 4. Check Guardian if specified
|
||||
if guardian_id is not None:
|
||||
guardian = self.db.query(Guardian).filter(
|
||||
Guardian.id == guardian_id
|
||||
).first()
|
||||
|
||||
if not guardian:
|
||||
raise GuardianNotFoundError(f"Guardian {guardian_id} not found")
|
||||
|
||||
if guardian.system_id != system_id:
|
||||
raise InvalidGuardianError(
|
||||
f"Guardian {guardian_id} belongs to System {guardian.system_id}, "
|
||||
f"not to System {system_id}"
|
||||
)
|
||||
|
||||
# 5. Check Core in Common restriction
|
||||
# If guardian is specified and module is Core, ensure we're not creating duplicate Core
|
||||
if module_name and module_name.lower() == 'core':
|
||||
existing_core = self.db.query(SystemModule).filter(
|
||||
SystemModule.guardian_id == guardian_id,
|
||||
SystemModule.module_id == self._get_core_module_id(),
|
||||
).first()
|
||||
|
||||
if existing_core:
|
||||
raise CoreAlreadyExistsError(
|
||||
f"Guardian {guardian_id} already has Core Module"
|
||||
)
|
||||
|
||||
# 6. Check remaining balance
|
||||
remaining = self._calculate_remaining(resource_id)
|
||||
|
||||
if quantity > remaining:
|
||||
raise InsufficientBalanceError(
|
||||
f"Cannot allocate {quantity}, only {remaining} remaining in Resource {resource_id}"
|
||||
)
|
||||
|
||||
# 7. Check Core in Common (if guardian_id is None and module is Core)
|
||||
if guardian_id is None and module_name and module_name.lower() == 'core':
|
||||
raise CoreInCommonError("Cannot allocate Core to Common part")
|
||||
|
||||
# 8. Create ResourceAllocation
|
||||
allocation = ResourceAllocation(
|
||||
resource_id=resource_id,
|
||||
system_id=system_id,
|
||||
guardian_id=guardian_id,
|
||||
quantity=quantity,
|
||||
description=description
|
||||
)
|
||||
self.db.add(allocation)
|
||||
|
||||
# 9. Update/Create SystemModule
|
||||
self._update_system_module(
|
||||
system_id=system_id,
|
||||
guardian_id=guardian_id,
|
||||
module_name=module_name,
|
||||
quantity=quantity
|
||||
)
|
||||
|
||||
# 10. Commit transaction
|
||||
self.db.commit()
|
||||
self.db.refresh(allocation)
|
||||
|
||||
return allocation
|
||||
|
||||
def _calculate_remaining(self, resource_id: int) -> int:
|
||||
"""Calculate remaining balance for Resource"""
|
||||
# Sum all existing allocations
|
||||
allocated = self.db.query(func.sum(ResourceAllocation.quantity)).filter(
|
||||
ResourceAllocation.resource_id == resource_id
|
||||
).scalar() or 0
|
||||
|
||||
# Get resource quantity
|
||||
resource = self.db.query(Resource).filter(
|
||||
Resource.id == resource_id
|
||||
).first()
|
||||
|
||||
return resource.quantity - allocated
|
||||
|
||||
def _get_core_module_id(self) -> int:
|
||||
"""Get ID of Core module"""
|
||||
core = self.db.query(Module).filter(
|
||||
Module.name.ilike('core')
|
||||
).first()
|
||||
|
||||
if core:
|
||||
return core.id
|
||||
|
||||
# If Core doesn't exist, create it (shouldn't happen in normal operation)
|
||||
core = Module(name="Core", description="Core module - required for Guardian")
|
||||
self.db.add(core)
|
||||
self.db.commit()
|
||||
self.db.refresh(core)
|
||||
|
||||
return core.id
|
||||
|
||||
def _update_system_module(
|
||||
self,
|
||||
system_id: int,
|
||||
guardian_id: int | None,
|
||||
module_name: str | None,
|
||||
quantity: int
|
||||
) -> SystemModule:
|
||||
"""
|
||||
Update or create SystemModule for the allocation.
|
||||
|
||||
Handles both Common part (guardian_id=None) and Guardian-specific allocations.
|
||||
"""
|
||||
# Find existing SystemModule
|
||||
existing = self.db.query(SystemModule).filter(
|
||||
SystemModule.system_id == system_id,
|
||||
SystemModule.guardian_id == guardian_id
|
||||
).first()
|
||||
|
||||
if existing:
|
||||
# Update existing
|
||||
existing.quantity += quantity
|
||||
else:
|
||||
# Create new - need module_id
|
||||
module_id = self._get_module_id_by_name(module_name)
|
||||
|
||||
if module_id is None:
|
||||
# If module_name not provided, we can't create SystemModule
|
||||
raise ValidationError(f"Module {module_name} not found or not provided")
|
||||
|
||||
existing = SystemModule(
|
||||
system_id=system_id,
|
||||
guardian_id=guardian_id,
|
||||
module_id=module_id,
|
||||
quantity=quantity
|
||||
)
|
||||
self.db.add(existing)
|
||||
|
||||
return existing
|
||||
|
||||
def _get_module_id_by_name(self, name: str | None) -> int | None:
|
||||
"""Get module ID by name"""
|
||||
if not name:
|
||||
return None
|
||||
|
||||
module = self.db.query(Module).filter(
|
||||
Module.name.ilike(name)
|
||||
).first()
|
||||
|
||||
return module.id if module else None
|
||||
Reference in New Issue
Block a user