File size: 2,460 Bytes
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33f7333
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98f87d0
1b4b6d2
6e77399
 
 
 
1b4b6d2
 
 
 
 
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
76
77
"""
Production settings loader.

Secrets must come from environment variables (or .env file via python-dotenv).
This module keeps the rest of the codebase away from hard-coded credentials.
"""
from __future__ import annotations

import os
from dotenv import load_dotenv
load_dotenv()
from dataclasses import dataclass
from typing import Any


def _st_secret(name: str, default: str | None = None) -> str | None:
    """Legacy fallback — now all secrets come from environment variables / .env file."""
    return os.environ.get(name, default)


def get_setting(name: str, default: str | None = None, required: bool = False) -> str:
    value = os.environ.get(name, default)
    if required and not value:
        raise RuntimeError(f"Missing required setting: {name}")
    return str(value).strip().strip("'").strip('"') if value is not None else ""


def get_int_setting(name: str, default: int) -> int:
    raw = get_setting(name, str(default))
    try:
        return int(raw)
    except (TypeError, ValueError):
        return default


@dataclass(frozen=True)
class DbSettings:
    host: str
    port: int
    user: str
    password: str
    database: str

    @classmethod
    def from_env(cls) -> "DbSettings":
        host = get_setting("TIDB_HOST", get_setting("DB_HOST", ""), required=False)
        if not host:
            return cls(host="", port=4000, user="", password="", database="local")
        return cls(
            host=host,
            port=get_int_setting("TIDB_PORT", get_int_setting("DB_PORT", 4000)),
            user=get_setting("TIDB_USER", get_setting("DB_USER", ""), required=True),
            password=get_setting("TIDB_PASSWORD", get_setting("DB_PASSWORD", ""), required=True),
            database=get_setting("TIDB_DATABASE", get_setting("DB_NAME", "test"), required=True),
        )

    def pymysql_kwargs(self) -> dict[str, Any]:
        import pymysql

        return {
            "host": self.host,
            "port": self.port,
            "user": self.user,
            "password": self.password,
            "database": self.database,
            "ssl": {"ssl_mode": "REQUIRED"},
            "cursorclass": pymysql.cursors.DictCursor,
            "connect_timeout": 30,
            "read_timeout": 30,
            "write_timeout": 30,
            "max_allowed_packet": 64 * 1024 * 1024,  # 64 MB
        }


def app_base_url() -> str:
    return get_setting("APP_BASE_URL", "http://localhost:8501").rstrip("/")