"""공개 공휴일 API의 정상 자료를 별도 DB에 보관한다. 회원 DB와 갱신 수명을 분리한다. 빈 응답과 일부 날짜만 담긴 응답은 저장하지 않는다. 통신 실패 때는 직전 정상 자료를 계속 제공한다. 서버는 하루마다 확인하지만 기기는 월별·수동·변경 확인 때만 전체 자료를 받는다. """ from contextlib import closing from datetime import date import hashlib import json from pathlib import Path import sqlite3 import threading import time from urllib.request import Request, urlopen SOURCE = 'https://holidays.hyunbin.page/basic.json' LIMIT = 1_048_576 def validate(raw, require_current=True): if len(raw) > LIMIT: raise ValueError('공휴일 응답 크기 초과') data = json.loads(raw) if not isinstance(data, dict) or not data: raise ValueError('공휴일 연도 누락') for year, days in data.items(): if not year.isdigit() or len(year) != 4 or not 2000 <= int(year) <= 2099 or not isinstance(days, dict) or not 15 <= len(days) <= 80: raise ValueError('공휴일 연도 범위 또는 날짜 누락') for key, names in days.items(): if str(date.fromisoformat(key).year) != year or not isinstance(names, list) or not 1 <= len(names) <= 8 or any(not isinstance(name, str) or not 1 <= len(name.strip()) <= 100 for name in names): raise ValueError('공휴일 날짜 또는 이름 오류') # 월력 자료가 중간에 잘려도 JSON 형식은 맞을 수 있다. 고정 공휴일과 두 명절을 함께 확인한다. if any(f'{year}-{day}' not in days for day in ('01-01', '03-01', '05-05', '06-06', '08-15', '10-03', '10-09', '12-25')): raise ValueError('고정 공휴일 누락') names = [name for values in days.values() for name in values] if sum('설날' in name for name in names) < 3 or sum('추석' in name for name in names) < 3: raise ValueError('명절 자료 누락') if require_current and str(date.today().year) not in data: raise ValueError('올해 공휴일 누락') return data class HolidayStore: def __init__(self, directory, bundled): self.path = Path(directory) / 'holiday-cache.sqlite3' self.gate = threading.Lock() with closing(sqlite3.connect(self.path, timeout=10)) as conn, conn: conn.execute('CREATE TABLE IF NOT EXISTS snapshot(id INTEGER PRIMARY KEY CHECK(id=1), body TEXT NOT NULL, revision TEXT NOT NULL, checked INTEGER NOT NULL, attempted INTEGER NOT NULL, saved INTEGER NOT NULL)') if not conn.execute('SELECT 1 FROM snapshot').fetchone(): legacy = Path(directory) / 'holidays.json' try: data = validate(legacy.read_bytes(), False) except Exception: data = validate(Path(bundled).read_bytes(), False) body = self.encode(data) conn.execute('INSERT INTO snapshot VALUES(1,?,?,0,0,1)', (body, self.revision(body))) self.path.chmod(0o600) @staticmethod def encode(data): return json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(',', ':')) @staticmethod def revision(body): return hashlib.sha256(body.encode()).hexdigest()[:24] def read(self): with closing(sqlite3.connect(self.path, timeout=10)) as conn: body, revision, checked, attempted, saved = conn.execute('SELECT body,revision,checked,attempted,saved FROM snapshot WHERE id=1').fetchone() return json.loads(body), {'revision': revision, 'checked': checked, 'attempted': attempted, 'saved': bool(saved)} def refresh(self, force=False, fetch=None): # 여러 수동 요청이 겹쳐도 외부 API는 한 번만 조회한다. 실패 시 재시도 간격은 1시간이다. if not self.gate.acquire(blocking=False): return False try: old, state = self.read() now = int(time.time()) if now - state['attempted'] < 3600 or (not force and now - state['checked'] < 86400): return not state['saved'] try: if fetch is None: with urlopen(Request(SOURCE, headers={'Accept': 'application/json', 'User-Agent': 'DutyCalendar/0.7 (+https://duty.itosm.co.kr/calendar/)'}), timeout=10) as response: raw = response.read(LIMIT + 1) else: raw = fetch() data = validate(raw) # 제공처가 과거 연도를 목록에서 빼더라도 이미 검증한 과거 기록은 남긴다. body = self.encode({**old, **data}) with closing(sqlite3.connect(self.path, timeout=10)) as conn, conn: conn.execute('UPDATE snapshot SET body=?,revision=?,checked=?,attempted=?,saved=0 WHERE id=1', (body, self.revision(body), now, now)) return True except Exception: with closing(sqlite3.connect(self.path, timeout=10)) as conn, conn: conn.execute('UPDATE snapshot SET attempted=?,saved=1 WHERE id=1', (now,)) return False finally: self.gate.release()