Agent 서버 구축: 멀티테넌트 협상 PoC (UCB Q-Table 학습 + /chat + 14 API + 학습검증 하네스), config 단일화(local.toml) + 빌드 경량화
This commit is contained in:
1 parent
212725e5f9
commit
951d6eab84
140 files changed
+6689
-214
No files matched your search
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,188 @@
|
||||
from asyncio import current_task
|
||||
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_scoped_session
|
||||
from sqlalchemy.util._collections import immutabledict
|
||||
|
||||
from common.database.model.models import MAIN_BASE
|
||||
from common.enums import DBType, DBWRType, ErrorType
|
||||
from common.logger import LOG
|
||||
from common.singleton import Singleton
|
||||
from config.server_configs import main_db_config
|
||||
|
||||
|
||||
class DBSessionManager(Singleton):
|
||||
"""DB 세션/엔진 관리자 (싱글톤). backend/common/database/db_session_manager.py 와 동일 패턴.
|
||||
|
||||
- DBType(논리 DB) x DBWRType(Read/Write) 조합마다 별도 async 엔진.
|
||||
- 비즈니스 로직(service)은 세션을 직접 열지 않고 "람다"를 넘긴다.
|
||||
execute_lambda : 단일 쿼리 (주로 조회)
|
||||
execute_lambda_run : 동일 DB 의 여러 변경 쿼리를 한 트랜잭션으로 commit
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
if DBSessionManager.is_init():
|
||||
LOG.e_no_callstack("already init DBSessionManager")
|
||||
return
|
||||
DBSessionManager.set_init()
|
||||
|
||||
self.__DB_URL_MAP = {"postgresql": "postgresql+asyncpg"}
|
||||
self.__engines = []
|
||||
self.__db_type_map = {
|
||||
DBType.MAIN.value: main_db_config,
|
||||
}
|
||||
|
||||
self.__write_session = {
|
||||
DBType.MAIN.value: self.create_engine(DBType.MAIN.value, DBWRType.DB_WRITE.value),
|
||||
}
|
||||
self.__read_session = {
|
||||
DBType.MAIN.value: self.create_engine(DBType.MAIN.value, DBWRType.DB_READ.value),
|
||||
}
|
||||
|
||||
def create_engine(self, db_type: int, db_wr_type: int):
|
||||
db_config = self.__db_type_map.get(db_type)
|
||||
if not db_config:
|
||||
raise ValueError("Invalid database type")
|
||||
|
||||
if db_wr_type == DBWRType.DB_READ.value:
|
||||
pw = (":" + db_config.read_pw) if len(db_config.read_pw) > 0 else ""
|
||||
db_url = f"{self.__DB_URL_MAP[db_config.db_type]}://{db_config.read_id}{pw}@{db_config.read_host}:{db_config.read_port}/{db_config.name}"
|
||||
LOG.i(f"Read DB create engine url : {db_url}")
|
||||
else:
|
||||
pw = (":" + db_config.write_pw) if len(db_config.write_pw) > 0 else ""
|
||||
db_url = f"{self.__DB_URL_MAP[db_config.db_type]}://{db_config.write_id}{pw}@{db_config.write_host}:{db_config.write_port}/{db_config.name}"
|
||||
LOG.i(f"Write DB create engine url : {db_url}")
|
||||
|
||||
engine = create_async_engine(
|
||||
db_url,
|
||||
echo=db_config.show_log,
|
||||
pool_size=db_config.pool_size,
|
||||
max_overflow=db_config.max_overflow,
|
||||
pool_pre_ping=True,
|
||||
pool_recycle=600,
|
||||
)
|
||||
self.__engines.append(engine)
|
||||
scoped_session = async_scoped_session(
|
||||
sessionmaker(engine, class_=AsyncSession, expire_on_commit=False, autocommit=False, autoflush=False),
|
||||
scopefunc=current_task,
|
||||
)
|
||||
return scoped_session
|
||||
|
||||
async def dispose_all(self):
|
||||
for engine in self.__engines:
|
||||
await engine.dispose()
|
||||
|
||||
# ---- 세션 lifecycle -------------------------------------------------
|
||||
async def start_session(self, db_type: int, db_wr_type: int) -> AsyncSession:
|
||||
if db_wr_type == DBWRType.DB_WRITE.value:
|
||||
return self.__write_session[db_type]()
|
||||
return self.__read_session[db_type]()
|
||||
|
||||
async def end_session(self, db_type: int, db_wr_type: int):
|
||||
if db_wr_type == DBWRType.DB_WRITE.value:
|
||||
await self.__write_session[db_type].remove()
|
||||
else:
|
||||
await self.__read_session[db_type].remove()
|
||||
|
||||
# ---- 저수준 DB 연산 (crud 에서 호출) --------------------------------
|
||||
async def run(self, db: AsyncSession, err_msg="DB Run Failed", raise_error=True) -> ErrorType:
|
||||
try:
|
||||
await db.commit()
|
||||
return ErrorType.SUCCESS
|
||||
except IntegrityError as ex:
|
||||
await db.rollback()
|
||||
LOG.e_no_callstack(f"duplicated. {ex}")
|
||||
return ErrorType.DB_ALREADY_SAME_KEY
|
||||
except Exception as ex:
|
||||
await db.rollback()
|
||||
err_type = ErrorType.DB_RUN_FAILED
|
||||
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
|
||||
if raise_error:
|
||||
raise RuntimeError(err_type.name, err_msg)
|
||||
return err_type
|
||||
|
||||
async def insert(self, db: AsyncSession, obj, err_msg="DB Failed", raise_error=True) -> ErrorType:
|
||||
try:
|
||||
if isinstance(obj, MAIN_BASE):
|
||||
db.add(obj)
|
||||
elif isinstance(obj, list):
|
||||
db.add_all(obj)
|
||||
else:
|
||||
raise RuntimeError("DO NOT USE QUERY IN DBJOB")
|
||||
return ErrorType.SUCCESS
|
||||
except Exception as ex:
|
||||
await db.rollback()
|
||||
err_type = ErrorType.DB_RUN_FAILED
|
||||
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
|
||||
if raise_error:
|
||||
raise RuntimeError(err_type.name, err_msg)
|
||||
return err_type
|
||||
|
||||
async def add(self, db: AsyncSession, query, err_msg="DB Operation Failed", raise_error=True) -> ErrorType:
|
||||
"""update/delete 등 비-select 쿼리 실행."""
|
||||
try:
|
||||
if hasattr(query, "column_descriptions"):
|
||||
raise RuntimeError("DO NOT USE SELECT QUERY IN DBJOB")
|
||||
await db.execute(query, execution_options=immutabledict({"synchronize_session": "fetch"}))
|
||||
return ErrorType.SUCCESS
|
||||
except IntegrityError as ex:
|
||||
await db.rollback()
|
||||
err_type = ErrorType.DB_ALREADY_SAME_KEY
|
||||
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
|
||||
return err_type
|
||||
except Exception as ex:
|
||||
await db.rollback()
|
||||
err_type = ErrorType.DB_RUN_FAILED
|
||||
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
|
||||
if raise_error:
|
||||
raise RuntimeError(err_type.name, err_msg)
|
||||
return err_type
|
||||
|
||||
async def execute(self, db: AsyncSession, query, err_msg="DB Query Execution Failed", raise_error=True) -> tuple[ErrorType, list]:
|
||||
"""select 쿼리 실행 후 결과 리스트 반환."""
|
||||
try:
|
||||
if not hasattr(query, "column_descriptions"):
|
||||
raise RuntimeError("DO NOT USE NON-SELECT QUERY IN DBJOB")
|
||||
res = await db.execute(query, execution_options=immutabledict({"synchronize_session": "fetch"}))
|
||||
return ErrorType.SUCCESS, res.scalars().fetchall() if 1 == len(query.column_descriptions) else res.all()
|
||||
except Exception as ex:
|
||||
err_type = ErrorType.DB_RUN_FAILED
|
||||
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
|
||||
if raise_error:
|
||||
raise RuntimeError(err_type.name, err_msg)
|
||||
return err_type, []
|
||||
|
||||
# ---- 람다 실행 진입점 (service 에서 호출) ---------------------------
|
||||
async def execute_lambda(self, db_type: int, db_wr_type: int, func):
|
||||
"""단일 쿼리 호출. func(session) 한 개를 실행하고 결과를 그대로 반환."""
|
||||
s = await self.start_session(db_type, db_wr_type)
|
||||
try:
|
||||
return await func(s)
|
||||
finally:
|
||||
await self.end_session(db_type, db_wr_type)
|
||||
|
||||
async def execute_lambda_run(self, db_type_list: list[int], func_list: list):
|
||||
"""동일 DB 의 변경 쿼리 여러 개를 한 트랜잭션으로 실행 후 commit.
|
||||
하나라도 SUCCESS 가 아니면 즉시 중단(rollback)된다.
|
||||
"""
|
||||
temp_list = list(set(db_type_list))
|
||||
if len(temp_list) != 1:
|
||||
return ErrorType.DB_INVALID_TYPE
|
||||
|
||||
db_type = temp_list[0]
|
||||
s = await self.start_session(db_type, DBWRType.DB_WRITE.value)
|
||||
try:
|
||||
for func in func_list:
|
||||
err_type = await func(s)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type
|
||||
return await self.run(s)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
finally:
|
||||
await self.end_session(db_type, DBWRType.DB_WRITE.value)
|
||||
|
||||
|
||||
DB_SESSION_MNG = DBSessionManager()
|
||||
Whitespace-only changes.
@@ -0,0 +1,144 @@
|
||||
from sqlalchemy.orm import declarative_base
|
||||
from sqlalchemy import (
|
||||
BigInteger,
|
||||
Boolean,
|
||||
Column,
|
||||
DateTime,
|
||||
Integer,
|
||||
Numeric,
|
||||
SmallInteger,
|
||||
String,
|
||||
Float,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
||||
from sqlalchemy.sql import text
|
||||
|
||||
from common.enums import DBType
|
||||
|
||||
# 모든 ORM 모델의 베이스. insert 시 isinstance 체크에도 사용된다. (backend 와 동일 패턴)
|
||||
#
|
||||
# agent 는 negosium_db 를 backend 와 공유한다.
|
||||
# - 기존 스키마(company/card/negotiation 등)는 postgres-init/01-schema.sql 이 소유 → 읽기/쓰기만.
|
||||
# - RL 학습 자산은 신설 `learning` 스키마(postgres-init/02-learning-schema.sql)에 둔다.
|
||||
MAIN_BASE = declarative_base()
|
||||
|
||||
LEARNING_SCHEMA = "learning"
|
||||
|
||||
# 공유 베이스 정책의 예약 테넌트 키 (company_id 컬럼에 저장). company uuid 와 혼용되므로 VARCHAR.
|
||||
BASE_COMPANY_ID = "_base"
|
||||
|
||||
|
||||
class _DBTypeMixin:
|
||||
"""모델이 자신이 속한 논리 DB 를 알려준다 (람다 실행 시 DBType 으로 세션 선택)."""
|
||||
|
||||
@staticmethod
|
||||
def DBType():
|
||||
return DBType.MAIN.value
|
||||
|
||||
|
||||
# ============================================================
|
||||
# learning 스키마 ORM (02-learning-schema.sql 과 1:1)
|
||||
# 모든 테이블에 company_id(테넌트 키) — 논리 격리.
|
||||
# ============================================================
|
||||
class QTableVersion(_DBTypeMixin, MAIN_BASE):
|
||||
__tablename__ = "q_table_versions"
|
||||
__table_args__ = {"schema": LEARNING_SCHEMA}
|
||||
|
||||
version_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
|
||||
company_id = Column(String(64), nullable=False)
|
||||
version_name = Column(String(50), nullable=False)
|
||||
scope = Column(SmallInteger, nullable=False, default=2) # 1=base, 2=tenant
|
||||
base_version_id = Column(UUID(as_uuid=True), nullable=True)
|
||||
state_space_size = Column(Integer, nullable=False)
|
||||
action_space_size = Column(Integer, nullable=False)
|
||||
learning_rate = Column(Numeric(6, 4), nullable=False, default=0.1)
|
||||
discount_factor = Column(Numeric(6, 4), nullable=False, default=0.95)
|
||||
epochs = Column(Integer, nullable=False, default=0)
|
||||
is_active = Column(Boolean, nullable=False, default=False)
|
||||
created_at = Column(DateTime(timezone=True), server_default=text("now()"))
|
||||
deleted = Column(Boolean, nullable=False, default=False)
|
||||
|
||||
|
||||
class QValue(_DBTypeMixin, MAIN_BASE):
|
||||
__tablename__ = "q_values"
|
||||
__table_args__ = {"schema": LEARNING_SCHEMA}
|
||||
|
||||
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
||||
company_id = Column(String(64), nullable=False)
|
||||
version_id = Column(UUID(as_uuid=True), nullable=False)
|
||||
state_index = Column(Integer, nullable=False)
|
||||
action_id = Column(Integer, nullable=False)
|
||||
q_value = Column(Float, nullable=False, default=0.0)
|
||||
|
||||
|
||||
class VisitCount(_DBTypeMixin, MAIN_BASE):
|
||||
__tablename__ = "visit_counts"
|
||||
__table_args__ = {"schema": LEARNING_SCHEMA}
|
||||
|
||||
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
||||
company_id = Column(String(64), nullable=False)
|
||||
version_id = Column(UUID(as_uuid=True), nullable=False)
|
||||
state_index = Column(Integer, nullable=False)
|
||||
action_id = Column(Integer, nullable=False)
|
||||
count = Column(BigInteger, nullable=False, default=0)
|
||||
|
||||
|
||||
class ExperienceLog(_DBTypeMixin, MAIN_BASE):
|
||||
__tablename__ = "experience_logs"
|
||||
__table_args__ = {"schema": LEARNING_SCHEMA}
|
||||
|
||||
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
||||
company_id = Column(String(64), nullable=False)
|
||||
transition_id = Column(UUID(as_uuid=True), nullable=False, server_default=text("gen_random_uuid()"))
|
||||
session_id = Column(UUID(as_uuid=True), nullable=True)
|
||||
state_index = Column(Integer, nullable=False)
|
||||
action_id = Column(Integer, nullable=False)
|
||||
card_id = Column(String(40), nullable=True)
|
||||
q_value_at_selection = Column(Float, nullable=True)
|
||||
reward = Column(Float, nullable=True)
|
||||
next_state_index = Column(Integer, nullable=True)
|
||||
done = Column(Boolean, nullable=False, default=False)
|
||||
snapshot = Column(JSONB, nullable=True)
|
||||
propensity = Column(Float, nullable=True) # OPE 필수
|
||||
turn = Column(Integer, nullable=True)
|
||||
available_actions = Column(JSONB, nullable=True)
|
||||
settled_price = Column(BigInteger, nullable=True)
|
||||
visit_count_at_selection = Column(BigInteger, nullable=True)
|
||||
total_visits_at_selection = Column(BigInteger, nullable=True)
|
||||
ucb_score_at_selection = Column(Float, nullable=True)
|
||||
is_new_quote = Column(Boolean, nullable=False, default=False)
|
||||
is_invalidated = Column(Boolean, nullable=False, default=False)
|
||||
invalidated_reason = Column(String(255), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=text("now()"))
|
||||
|
||||
|
||||
class TenantActionCard(_DBTypeMixin, MAIN_BASE):
|
||||
__tablename__ = "tenant_action_cards"
|
||||
__table_args__ = {"schema": LEARNING_SCHEMA}
|
||||
|
||||
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
||||
company_id = Column(String(64), nullable=False)
|
||||
action_id = Column(Integer, nullable=False)
|
||||
card_id = Column(String(40), nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), server_default=text("now()"))
|
||||
updated_at = Column(DateTime(timezone=True), server_default=text("now()"))
|
||||
deleted = Column(Boolean, nullable=False, default=False)
|
||||
|
||||
|
||||
class ChatSessionRow(_DBTypeMixin, MAIN_BASE):
|
||||
"""/chat 진행 상태 영속화 (P8-A). 채팅 메시지 로그가 아니라 step 머신 상태."""
|
||||
|
||||
__tablename__ = "chat_sessions"
|
||||
__table_args__ = {"schema": LEARNING_SCHEMA}
|
||||
|
||||
session_id = Column(UUID(as_uuid=True), primary_key=True)
|
||||
company_id = Column(String(64), nullable=False)
|
||||
tenant_id = Column(String(64), nullable=False)
|
||||
rq_type = Column(String(10), nullable=False, default="재협상")
|
||||
step = Column(String(40), nullable=False, default="시작")
|
||||
context = Column(JSONB, nullable=False, default=dict)
|
||||
used_action_ids = Column(JSONB, nullable=False, default=list)
|
||||
action_space_size = Column(Integer, nullable=False, default=0)
|
||||
ended = Column(Boolean, nullable=False, default=False)
|
||||
created_at = Column(DateTime(timezone=True), server_default=text("now()"))
|
||||
updated_at = Column(DateTime(timezone=True), server_default=text("now()"))
|
||||
@@ -0,0 +1,70 @@
|
||||
from enum import Enum, auto
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
|
||||
class ErrorType(Enum):
|
||||
"""서버 전역 결과 코드. backend/common/enums.py 와 구간을 공유하되,
|
||||
협상 에이전트 전용 코드를 2000 구간에 추가한다.
|
||||
"""
|
||||
|
||||
SUCCESS = 0
|
||||
FAIL = 1
|
||||
|
||||
# DB / Redis 에러
|
||||
DB_RUN_FAILED = 10
|
||||
DB_ALREADY_SAME_KEY = auto()
|
||||
DB_INVALID_KEY = auto()
|
||||
DB_EMPTY_DATA = auto()
|
||||
DB_INVALID_TYPE = auto()
|
||||
|
||||
# 요청/직렬화 에러
|
||||
JSON_PARSE_ERROR = 100
|
||||
INVALID_REQUEST_DATA = auto()
|
||||
INTERNAL_EXCEPTION = auto()
|
||||
|
||||
# http 에러 코드와 겹치지 않게 설정 - router 전용 예외 발생 옵션
|
||||
HTTP_INVALID_CLIENT_REQUEST = 419
|
||||
HTTP_TO_MANY_REQUEST = 429
|
||||
HTTP_INVALID_CLIENT_ACCESS = 433
|
||||
HTTP_ACCESS_TOKEN_EXPIRED = 434
|
||||
HTTP_REFRESH_TOKEN_EXPIRED = 435
|
||||
HTTP_INVALID_TOKEN_ACCESS = 436
|
||||
|
||||
# 테넌트 라우팅 에러 (P4 tenant_middleware)
|
||||
TENANT_HEADER_MISSING = 1400 # X-Tenant-ID 부재 -> 400
|
||||
TENANT_NOT_REGISTERED = auto() # 미등록 테넌트 -> 404
|
||||
|
||||
# 협상 에이전트 에러
|
||||
NEGO_INVALID_STEP = 2000
|
||||
NEGO_SESSION_NOT_FOUND = auto()
|
||||
NEGO_QTABLE_NOT_LOADED = auto()
|
||||
NEGO_DIM_MISMATCH = auto() # state/action 차원 불일치 (warm-start 폴백 트리거)
|
||||
|
||||
|
||||
# ErrorType 의 HTTP_* 값과 status_code 를 맞춰 router 단에서 raise 한다.
|
||||
EXCEPTION_INVALID_CLIENT_REQUEST = HTTPException(status_code=ErrorType.HTTP_INVALID_CLIENT_REQUEST.value, detail=ErrorType.HTTP_INVALID_CLIENT_REQUEST.name)
|
||||
EXCEPTION_TO_MANY_REQUEST = HTTPException(status_code=ErrorType.HTTP_TO_MANY_REQUEST.value, detail=ErrorType.HTTP_TO_MANY_REQUEST.name)
|
||||
EXCEPTION_INVALID_CLIENT_ACCESS = HTTPException(status_code=ErrorType.HTTP_INVALID_CLIENT_ACCESS.value, detail=ErrorType.HTTP_INVALID_CLIENT_ACCESS.name)
|
||||
EXCEPTION_ACCESS_TOKEN_EXPIRED = HTTPException(status_code=ErrorType.HTTP_ACCESS_TOKEN_EXPIRED.value, detail=ErrorType.HTTP_ACCESS_TOKEN_EXPIRED.name)
|
||||
EXCEPTION_REFRESH_TOKEN_EXPIRED = HTTPException(status_code=ErrorType.HTTP_REFRESH_TOKEN_EXPIRED.value, detail=ErrorType.HTTP_REFRESH_TOKEN_EXPIRED.name)
|
||||
EXCEPTION_HTTP_INVALID_TOKEN_ACCESS = HTTPException(status_code=ErrorType.HTTP_INVALID_TOKEN_ACCESS.value, detail=ErrorType.HTTP_INVALID_TOKEN_ACCESS.name)
|
||||
|
||||
# 테넌트 라우팅 전용 예외 (P4 에서 미들웨어가 raise)
|
||||
EXCEPTION_TENANT_HEADER_MISSING = HTTPException(status_code=400, detail=ErrorType.TENANT_HEADER_MISSING.name)
|
||||
EXCEPTION_TENANT_NOT_REGISTERED = HTTPException(status_code=404, detail=ErrorType.TENANT_NOT_REGISTERED.name)
|
||||
|
||||
|
||||
class DBType(Enum):
|
||||
"""논리 DB 구분. backend 와 동일하게 단일 negosium_db(MAIN)를 공유한다.
|
||||
agent 전용 RL 학습 자산은 negosium_db 안의 `learning` 스키마에 둔다(별도 DB 아님).
|
||||
"""
|
||||
|
||||
MAIN = 1
|
||||
|
||||
|
||||
class DBWRType(Enum):
|
||||
"""Read / Write 접속 구분. 조회는 DB_READ, 변경은 DB_WRITE 엔진을 사용한다."""
|
||||
|
||||
DB_READ = 1
|
||||
DB_WRITE = 2
|
||||
@@ -0,0 +1,43 @@
|
||||
import sys
|
||||
import traceback
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
class _Logger:
|
||||
"""backend/common/logger.py 와 동일 인터페이스 (서버군 컨벤션 정합).
|
||||
LOG.i / LOG.d / LOG.w / LOG.e / LOG.e_no_callstack / LOG.SetPrefix 제공.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._prefix = ""
|
||||
|
||||
def SetPrefix(self, prefix: str):
|
||||
self._prefix = prefix
|
||||
|
||||
def _now(self) -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
def _write(self, level: str, msg):
|
||||
head = f"{self._now()} [{level}]"
|
||||
if self._prefix:
|
||||
head += f"[{self._prefix}]"
|
||||
print(f"{head} {msg}", file=sys.stderr if level in ("WARN", "ERROR") else sys.stdout)
|
||||
|
||||
def d(self, msg):
|
||||
self._write("DEBUG", msg)
|
||||
|
||||
def i(self, msg):
|
||||
self._write("INFO", msg)
|
||||
|
||||
def w(self, msg):
|
||||
self._write("WARN", msg)
|
||||
|
||||
def e(self, msg):
|
||||
self._write("ERROR", msg)
|
||||
traceback.print_stack()
|
||||
|
||||
def e_no_callstack(self, msg):
|
||||
self._write("ERROR", msg)
|
||||
|
||||
|
||||
LOG = _Logger()
|
||||
Whitespace-only changes.
@@ -0,0 +1,42 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from common.enums import ErrorType
|
||||
|
||||
|
||||
class StructModel:
|
||||
"""프로토콜/구조체 식별용 마커 클래스. (backend 와 동일 규약)"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class ErrorInfo(BaseModel, StructModel):
|
||||
"""모든 응답에 공통으로 실리는 결과 정보. result.success / code / desc 로 내려간다."""
|
||||
|
||||
success: Optional[bool] = True
|
||||
code: Optional[int] = ErrorType.SUCCESS.value
|
||||
desc: Optional[str] = ErrorType.SUCCESS.name
|
||||
|
||||
def SetResult(self, enum: ErrorType):
|
||||
if enum is not None:
|
||||
self.success = ErrorType.SUCCESS.value == enum.value
|
||||
self.code = enum.value
|
||||
self.desc = enum.name
|
||||
|
||||
|
||||
# ---- Protocol 규약 (backend/common/models/gmodel.py 와 동일) ----------------
|
||||
# 모든 통신 패킷은 WebPacketProtocol 을 상속한다.
|
||||
# 요청 : Req_xxx (WebPacketProtocol) / 응답 : Res_xxx (Res_WebPacketProtocol, 항상 result)
|
||||
class WebPacketProtocol(BaseModel, StructModel):
|
||||
pass
|
||||
|
||||
|
||||
class Req_WebPacketProtocol(WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
class Res_WebPacketProtocol(WebPacketProtocol):
|
||||
# default_factory 로 인스턴스마다 새 ErrorInfo 를 생성한다 (mutable default 공유 방지).
|
||||
result: ErrorInfo = Field(default_factory=ErrorInfo)
|
||||
msg: Optional[str] = None
|
||||
@@ -0,0 +1,16 @@
|
||||
class Singleton:
|
||||
_init = False
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
if not hasattr(cls, "instance"):
|
||||
cls.instance = super(Singleton, cls).__new__(cls)
|
||||
|
||||
return cls.instance
|
||||
|
||||
@classmethod
|
||||
def is_init(cls):
|
||||
return cls._init
|
||||
|
||||
@classmethod
|
||||
def set_init(cls):
|
||||
cls._init = True
|
||||
Whitespace-only changes.
@@ -0,0 +1,21 @@
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
|
||||
class GTime:
|
||||
"""서버 전역에서 UTC 기준 시간을 사용하기 위한 유틸. (backend 와 동일)"""
|
||||
|
||||
@staticmethod
|
||||
def UTC() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
@staticmethod
|
||||
def UTCStr(fmt: str = "%Y-%m-%d %H:%M:%S") -> str:
|
||||
return GTime.UTC().strftime(fmt)
|
||||
|
||||
@staticmethod
|
||||
def AddMinutes(minutes: int) -> datetime:
|
||||
return GTime.UTC() + timedelta(minutes=minutes)
|
||||
|
||||
@staticmethod
|
||||
def AddDays(days: int) -> datetime:
|
||||
return GTime.UTC() + timedelta(days=days)
|
||||
Reference in new issue
Block a user