Spaces:
Paused

File size: 2,554 Bytes
6d2d8b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""章节数据持久化缓存(SQLite),防止频繁抓取同一章节。"""

from __future__ import annotations

import json
import sqlite3
import threading
import time
import os
from pathlib import Path

DEFAULT_DB_PATH = Path(
    os.getenv(
        "CHAPTER_CACHE_DB_PATH",
        str(Path(__file__).resolve().parent.parent / "data" / "chapter_cache.db"),
    )
)
DEFAULT_TTL = 7 * 24 * 3600  # 默认 7 天


class ChapterCache:
    def __init__(self, path: str | Path = DEFAULT_DB_PATH, ttl: int = DEFAULT_TTL) -> None:
        path = Path(path)
        path.parent.mkdir(parents=True, exist_ok=True)
        self.ttl = ttl
        self._conn = sqlite3.connect(str(path), check_same_thread=False)
        self._lock = threading.Lock()
        with self._lock:
            self._conn.execute(
                """
                CREATE TABLE IF NOT EXISTS chapter_cache (
                    key TEXT PRIMARY KEY,
                    value TEXT NOT NULL,
                    expires_at REAL NOT NULL
                )
                """
            )
            self._conn.execute(
                "CREATE INDEX IF NOT EXISTS idx_chapter_cache_expires "
                "ON chapter_cache(expires_at)"
            )
            self._conn.commit()

    def get(self, key: str) -> dict | None:
        with self._lock:
            row = self._conn.execute(
                "SELECT value, expires_at FROM chapter_cache WHERE key = ?", (key,)
            ).fetchone()
            if row is None:
                return None
            value, expires_at = row
            if expires_at <= time.time():
                self._conn.execute("DELETE FROM chapter_cache WHERE key = ?", (key,))
                self._conn.commit()
                return None
            return json.loads(value)

    def set(self, key: str, value: dict, ttl: int | None = None) -> None:
        expires = time.time() + (ttl if ttl is not None else self.ttl)
        with self._lock:
            self._conn.execute(
                """
                INSERT INTO chapter_cache (key, value, expires_at) VALUES (?, ?, ?)
                ON CONFLICT(key) DO UPDATE SET
                    value = excluded.value,
                    expires_at = excluded.expires_at
                """,
                (key, json.dumps(value, ensure_ascii=False), expires),
            )
            # 顺带清理过期数据
            self._conn.execute(
                "DELETE FROM chapter_cache WHERE expires_at <= ?", (time.time(),)
            )
            self._conn.commit()