diff --git a/kis-api/main.py b/kis-api/main.py index 251f521..1827553 100644 --- a/kis-api/main.py +++ b/kis-api/main.py @@ -44,10 +44,19 @@ scheduler = AsyncIOScheduler(timezone="Asia/Seoul") class KiwoomToken: token: str = "" expires_at: datetime = datetime.min + _lock = asyncio.Lock() async def get(self, client: httpx.AsyncClient) -> str: if self.token and datetime.now() < self.expires_at: return self.token + # 동시 갱신 방지: 락 안에서 재확인(double-check) — 키움은 앱키당 토큰 1개만 + # 유효(재발급 시 이전 토큰 무효화)하므로 thundering-herd 시 무효 토큰을 붙들게 됨 + async with self._lock: + if self.token and datetime.now() < self.expires_at: + return self.token + return await self._refresh(client) + + async def _refresh(self, client: httpx.AsyncClient) -> str: resp = await client.post( f"{KIWOOM_BASE_URL}/oauth2/token", json={"grant_type": "client_credentials",