- 
                Notifications
    You must be signed in to change notification settings 
- Fork 0
6️⃣ CHAPTER_06 unit of work #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
  
     Merged
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            3 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      
    File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
              Empty file.
          
    
              Empty file.
          
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
              Empty file.
          
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -1,8 +1,8 @@ | ||
| from __future__ import annotations | ||
|  | ||
| from dataclasses import dataclass | ||
| from dataclasses import dataclass, field | ||
| from datetime import date | ||
| from uuid import UUID | ||
| from uuid import UUID, uuid4 | ||
|  | ||
|  | ||
| class OutOfStock(Exception): | ||
|  | @@ -18,21 +18,20 @@ def allocate(line: OrderLine, batches: list[Batch]) -> UUID: | |
| raise OutOfStock(f"Out of stock for sku {line.sku}") | ||
|  | ||
|  | ||
| @dataclass(unsafe_hash=True, kw_only=True) # TODO: kw_only를 언제 써야 할까? | ||
| @dataclass(unsafe_hash=True, kw_only=True) | ||
| class OrderLine: | ||
| id: UUID | ||
| id: UUID = field(default_factory=uuid4) | ||
| sku: str | ||
| qty: int | ||
|  | ||
|  | ||
| @dataclass(kw_only=True) | ||
| class Batch: | ||
| def __init__(self, id: UUID, sku: str, qty: int, eta: date | None) -> None: | ||
| # TODO: id 값 업으면 기본 값 채우기 | ||
| self.id = id | ||
| self.sku = sku | ||
| self.eta = eta | ||
| self.purchased_quantity = qty | ||
| self.allocations: set[OrderLine] = set() | ||
| id: UUID = field(default_factory=uuid4) | ||
| There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. default_factory를 사용하기 위해서 dataclass로 변경했습니다. 모델은 kw_only를 사용하도록 했습니다. | ||
| sku: str | ||
| eta: date = None | ||
| qty: int | ||
| allocations: set[OrderLine] = field(default_factory=lambda: set()) | ||
|  | ||
| def __repr__(self) -> str: | ||
| return f"<Batch {self.id}>" | ||
|  | @@ -66,7 +65,7 @@ def allocated_quantity(self) -> int: | |
|  | ||
| @property | ||
| def available_quantity(self) -> int: | ||
| return self.purchased_quantity - self.allocated_quantity | ||
| return self.qty - self.allocated_quantity | ||
|  | ||
| def can_allocate(self, line: OrderLine) -> bool: | ||
| return ( | ||
|  | ||
              Empty file.
          
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| from datetime import date | ||
| from uuid import UUID | ||
|  | ||
| from fastapi import Body, Depends, FastAPI, HTTPException | ||
|  | ||
| from app.allocation.adapters.repository import AbstractBatchRepository | ||
| from app.allocation.domain import models | ||
| from app.allocation.routers.dependencies import batch_uow | ||
| from app.allocation.service_layer import services | ||
| from app.allocation.service_layer.unit_of_work import AbstractUnitOfWork | ||
|  | ||
| app = FastAPI() | ||
| # start_mappers() # TODO: 운영환경에서는 실행되어야 함 | ||
|  | ||
|  | ||
| @app.get("/") | ||
| async def root() -> dict[str, str]: | ||
| return {"message": "Hello World"} | ||
|  | ||
|  | ||
| @app.post("/batches", status_code=201) | ||
| async def add_batch( | ||
| batch_id: UUID = Body(), | ||
| sku: str = Body(), | ||
| quantity: int = Body(), | ||
| eta: date = Body(default=None), | ||
| uow: AbstractUnitOfWork[AbstractBatchRepository] = Depends(batch_uow), | ||
| ) -> dict[str, str]: | ||
| await services.add_batch(batch_id, sku, quantity, eta, uow) | ||
| return {"message": "success"} | ||
|  | ||
|  | ||
| @app.post("/allocate", response_model=dict[str, str], status_code=201) | ||
| async def allocate( | ||
| line_id: UUID = Body(), | ||
| sku: str = Body(), | ||
| quantity: int = Body(), | ||
| uow: AbstractUnitOfWork[AbstractBatchRepository] = Depends(batch_uow), | ||
| ) -> dict[str, str]: | ||
| try: | ||
| batch_id = await services.allocate(line_id, sku, quantity, uow) | ||
| except (models.OutOfStock, services.InvalidSku) as e: | ||
| raise HTTPException(status_code=400, detail=str(e)) | ||
| return {"batch_id": str(batch_id)} | 
              Empty file.
          
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| from datetime import date | ||
| from uuid import UUID | ||
|  | ||
| from app.allocation.adapters.repository import AbstractBatchRepository | ||
| from app.allocation.domain import models | ||
| from app.allocation.service_layer import unit_of_work | ||
|  | ||
|  | ||
| class InvalidSku(Exception): | ||
| pass | ||
|  | ||
|  | ||
| async def add_batch( | ||
| batch_id: UUID, | ||
| sku: str, | ||
| qty: int, | ||
| eta: date | None, | ||
| uow: unit_of_work.AbstractUnitOfWork[AbstractBatchRepository], | ||
| ) -> None: | ||
| async with uow: | ||
| await uow.repo.add(models.Batch(id=batch_id, sku=sku, qty=qty, eta=eta)) | ||
| await uow.commit() | ||
|  | ||
|  | ||
| async def allocate( | ||
| line_id: UUID, sku: str, qty: int, uow: unit_of_work.AbstractUnitOfWork[AbstractBatchRepository] | ||
| ) -> UUID: | ||
| line = models.OrderLine(id=line_id, sku=sku, qty=qty) | ||
| async with uow: | ||
| batches = await uow.repo.list() | ||
| if not _is_valid_sku(line.sku, batches): | ||
| raise InvalidSku(f"Invalid sku {line.sku}") | ||
| batch_id = models.allocate(line, batches) | ||
| await uow.commit() | ||
| return batch_id | ||
|  | ||
|  | ||
| def _is_valid_sku(sku: str, batches: list[models.Batch]) -> bool: | ||
| return sku in {b.sku for b in batches} | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| from __future__ import annotations | ||
|  | ||
| import abc | ||
| from asyncio import current_task | ||
| from typing import Any, Generic, TypeVar | ||
|  | ||
| from sqlalchemy.ext.asyncio import AsyncSession, async_scoped_session, create_async_engine | ||
| from sqlalchemy.orm import sessionmaker | ||
|  | ||
| from app.allocation.adapters.repository import AbstractBatchRepository, PGBatchRepository | ||
| from app.config import get_config | ||
|  | ||
| config = get_config() | ||
|  | ||
| Repo = TypeVar("Repo") | ||
|  | ||
|  | ||
| class AbstractUnitOfWork(abc.ABC, Generic[Repo]): | ||
| async def __aenter__(self) -> AbstractUnitOfWork[Repo]: | ||
| return self | ||
|  | ||
| async def __aexit__(self, *args: Any) -> None: | ||
| await self.rollback() | ||
|  | ||
| @abc.abstractproperty | ||
| def repo(self) -> Repo: | ||
| raise NotImplementedError | ||
|  | ||
| @abc.abstractmethod | ||
| async def commit(self) -> None: | ||
| raise NotImplementedError | ||
|  | ||
| @abc.abstractmethod | ||
| async def rollback(self) -> None: | ||
| raise NotImplementedError | ||
|  | ||
|  | ||
| class BatchUnitOfWork(AbstractUnitOfWork[AbstractBatchRepository]): | ||
| def __init__(self) -> None: | ||
| self._engine = create_async_engine(config.PG_DSN, echo=False) | ||
| self._session_factory = async_scoped_session( | ||
| sessionmaker( | ||
| autocommit=False, | ||
| autoflush=False, | ||
| class_=AsyncSession, | ||
| bind=self._engine, | ||
| ), | ||
| scopefunc=current_task, | ||
| ) | ||
|  | ||
| @property | ||
| def repo(self) -> AbstractBatchRepository: | ||
| return self._batches | ||
|  | ||
| async def __aenter__(self) -> AbstractUnitOfWork[AbstractBatchRepository]: | ||
| self._session: AsyncSession = self._session_factory() | ||
| self._batches = PGBatchRepository(self._session) | ||
| return await super().__aenter__() | ||
|  | ||
| async def __aexit__(self, *args: Any) -> None: | ||
| await super().__aexit__(*args) | ||
| await self._session.close() | ||
|  | ||
| async def commit(self) -> None: | ||
| await self._session.commit() | ||
|  | ||
| async def rollback(self) -> None: | ||
| await self._session.rollback() | 
This file was deleted.
      
      Oops, something went wrong.
      
    
  This file was deleted.
      
      Oops, something went wrong.
      
    
  
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
async sqlalchemy에서 mapping한 객체의 relationship fetch을 지원하지 않아서 execute로 수정했습니다.