registry.py 1.9 KB
"""按数据源取连接器,并缓存 engine。

每建一次 engine 就等于开一个新连接池,内省和问答是高频操作,不能每次都新建。
缓存键带上凭据哈希:用户改了口令/主机,旧连接器会自动作废。
"""
from __future__ import annotations
import hashlib
import threading

from .base import Connector
from .mysql import MySQLConnector

_REGISTRY: dict[str, type[Connector]] = {
    "mysql": MySQLConnector,
}

_lock = threading.RLock()
_cache: dict[int, tuple[str, Connector]] = {}


def supported_types() -> list[str]:
    return sorted(_REGISTRY)


def _fingerprint(ds: dict, password: str) -> str:
    raw = f"{ds.get('ds_type')}|{ds.get('host')}|{ds.get('port')}|{ds.get('db_name')}|" \
          f"{ds.get('username')}|{password}"
    return hashlib.sha256(raw.encode("utf-8")).hexdigest()


def build(ds: dict, password: str) -> Connector:
    """不走缓存地新建一个(测试连接时用,避免把坏配置塞进缓存)。"""
    cls = _REGISTRY.get(str(ds.get("ds_type") or "").lower())
    if cls is None:
        raise ValueError(f"暂不支持的数据源类型:{ds.get('ds_type')}(当前支持 {'、'.join(supported_types())})")
    return cls(ds, password)


def get(ds: dict, password: str) -> Connector:
    """取缓存的连接器;凭据变了就换掉旧的。"""
    ds_id = int(ds["id"])
    fp = _fingerprint(ds, password)
    with _lock:
        hit = _cache.get(ds_id)
        if hit and hit[0] == fp:
            return hit[1]
        if hit:
            try:
                hit[1].dispose()
            except Exception:  # noqa: BLE001
                pass
        conn = build(ds, password)
        _cache[ds_id] = (fp, conn)
        return conn


def evict(ds_id: int) -> None:
    with _lock:
        hit = _cache.pop(int(ds_id), None)
    if hit:
        try:
            hit[1].dispose()
        except Exception:  # noqa: BLE001
            pass