from dataclasses import dataclass from datetime import date, timedelta from typing import Optional import httpx from fastapi import Depends from redis.exceptions import RedisError from common.cache.lock import redis_lock from common.cache.redis_client import REDIS from common.database.db_session_manager import DB_SESSION_MNG from common.database.model.models import Article, SeasonWeek, SolarTerm from common.enums import ArticleCategory, ErrorType from common.logger import LOG from common.utils.kma_time import now_kst from common.utils.text import day_range from crud.season_crud import SeasonCRUD from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed from services.external.kasi import fetch_solar_terms @dataclass class SeasonWeekView: year: int week: int start: date end: date headline: str poem: Optional[SeasonWeek] term_now: Optional[SolarTerm] term_next: Optional[SolarTerm] progress: Optional[float] news: list[Article] class SeasonService: def __init__(self, crud: SeasonCRUD = Depends(SeasonCRUD)) -> None: self.crud = crud async def this_week(self) -> tuple[ErrorType, Optional[SeasonWeekView]]: today = now_kst().date() await self._ensure_terms({today.year - 1, today.year, today.year + 1} if today.month in (1, 12) else {today.year}) year, week, _ = today.isocalendar() start = today - timedelta(days=today.weekday()) err, terms = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.terms(s, today - timedelta(days=40), today + timedelta(days=40))) _, poem = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.week(s, year, week)) _, news = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.articles(s, today, ArticleCategory.SEASON.value)) if err is not ErrorType.SUCCESS: return err, None past = [t for t in terms if t.term_date <= today] future = [t for t in terms if t.term_date > today] now_t, next_t = (past[-1] if past else None), (future[0] if future else None) progress = None if now_t and next_t: progress = round((today - now_t.term_date).days / (next_t.term_date - now_t.term_date).days, 2) if now_t is None: since_term = day_range(start, start + timedelta(days=6)) elif now_t.term_date == today: since_term = f"오늘은 {now_t.name}" else: since_term = f"{now_t.name} 지나 {(today - now_t.term_date).days}일째" headline = f"{since_term}, {poem.headline}" if poem is not None else since_term return ErrorType.SUCCESS, SeasonWeekView( year=year, week=week, start=start, end=start + timedelta(days=6), headline=headline, poem=poem, term_now=now_t, term_next=next_t, progress=progress, news=news or [], ) async def articles(self, category: Optional[ArticleCategory]) -> tuple[ErrorType, list[Article]]: today = now_kst().date() err, items = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.articles(s, today, category.value if category else None)) if category is None: items = [a for a in items or [] if a.category != ArticleCategory.QUOTE.value] return err, items async def article(self, article_id: int) -> tuple[ErrorType, Optional[Article]]: err, a = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.article(s, article_id)) return (ErrorType.NOT_FOUND if err is ErrorType.SUCCESS and a is None else err), a async def _ensure_terms(self, years: set[int]) -> None: for year in sorted(years): key = f"solar:{year}" try: if await REDIS.conn.exists(key): continue err, count = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.term_count(s, year)) if err is ErrorType.SUCCESS and count >= 24: await REDIS.conn.set(key, "1", ex=30 * 86400) continue async with redis_lock(f"lock:{key}", ttl_sec=60) as acquired: if not acquired: continue async with httpx.AsyncClient(timeout=20) as client: rows = [r for m in range(1, 13) for r in await fetch_solar_terms(client, year, m)] err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_terms(s, rows)]) if err is ErrorType.SUCCESS and len(rows) >= 24: await REDIS.conn.set(key, "1", ex=30 * 86400) except (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError) as e: LOG.error(f"[season] solar terms {year}: {e}")