Download api/db.py from Qempireautomation/qrypto-engine: direct link, hf CLI and curl.
- Browser
- Download file 8.45 kB
-
https://huggingface.co/Qempireautomation/qrypto-engine/resolve/main/api/db.py
- Command line
-
hf download hf://Qempireautomation/qrypto-engine/api/db.py
-
curl -L -o db.py https://huggingface.co/Qempireautomation/qrypto-engine/resolve/main/api/db.py
8.45 kB
| """SQLite persistence (stdlib). One file, WAL mode, safe for a single-process API.""" | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import sqlite3 | |
| import threading | |
| import time | |
| import uuid | |
| from contextlib import contextmanager | |
| from typing import Any, Iterator, Optional | |
| def _pick_data_dir() -> str: | |
| """Prefer the configured data dir; fall back to /tmp if it isn't writable (hosts without storage).""" | |
| for candidate in (os.environ.get("QRYPTO_DATA_DIR"), "/data", "/tmp", "."): | |
| if not candidate: | |
| continue | |
| try: | |
| os.makedirs(candidate, exist_ok=True) | |
| probe = os.path.join(candidate, ".write-probe") | |
| with open(probe, "w") as fh: | |
| fh.write("1") | |
| os.remove(probe) | |
| return candidate | |
| except OSError: | |
| continue | |
| return "." | |
| DB_PATH = os.environ.get("QRYPTO_DB") or os.path.join(_pick_data_dir(), "qrypto.db") | |
| SCHEMA = """ | |
| CREATE TABLE IF NOT EXISTS users ( | |
| id TEXT PRIMARY KEY, email TEXT UNIQUE NOT NULL, pw_hash TEXT NOT NULL, | |
| tier TEXT NOT NULL DEFAULT 'free', created_at REAL NOT NULL, | |
| accepted_risk_at REAL, is_admin INTEGER NOT NULL DEFAULT 0 | |
| ); | |
| CREATE TABLE IF NOT EXISTS exchange_keys ( | |
| user_id TEXT NOT NULL, exchange TEXT NOT NULL, label TEXT, | |
| enc_key TEXT NOT NULL, enc_secret TEXT NOT NULL, created_at REAL NOT NULL, | |
| PRIMARY KEY (user_id, exchange) | |
| ); | |
| CREATE TABLE IF NOT EXISTS bots ( | |
| id TEXT PRIMARY KEY, user_id TEXT NOT NULL, name TEXT NOT NULL, strategy TEXT NOT NULL, | |
| params TEXT NOT NULL, symbol TEXT NOT NULL, timeframe TEXT NOT NULL, mode TEXT NOT NULL, | |
| exchange TEXT, status TEXT NOT NULL DEFAULT 'stopped', state TEXT, created_at REAL NOT NULL, | |
| updated_at REAL NOT NULL | |
| ); | |
| CREATE TABLE IF NOT EXISTS bot_events ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, bot_id TEXT NOT NULL, at REAL NOT NULL, payload TEXT NOT NULL | |
| ); | |
| CREATE INDEX IF NOT EXISTS ix_events_bot ON bot_events(bot_id, at); | |
| CREATE TABLE IF NOT EXISTS api_tokens ( | |
| token TEXT PRIMARY KEY, user_id TEXT NOT NULL, label TEXT, created_at REAL NOT NULL | |
| ); | |
| """ | |
| _lock = threading.RLock() | |
| def _connect() -> sqlite3.Connection: | |
| os.makedirs(os.path.dirname(os.path.abspath(DB_PATH)), exist_ok=True) | |
| c = sqlite3.connect(DB_PATH, check_same_thread=False) | |
| c.row_factory = sqlite3.Row | |
| c.execute("PRAGMA journal_mode=WAL") | |
| return c | |
| _conn: Optional[sqlite3.Connection] = None | |
| def conn() -> sqlite3.Connection: | |
| global _conn | |
| if _conn is None: | |
| _conn = _connect() | |
| _conn.executescript(SCHEMA) | |
| return _conn | |
| def tx() -> Iterator[sqlite3.Connection]: | |
| with _lock: | |
| c = conn() | |
| try: | |
| yield c | |
| c.commit() | |
| except Exception: | |
| c.rollback() | |
| raise | |
| def row_to_dict(r: sqlite3.Row | None) -> Optional[dict[str, Any]]: | |
| return dict(r) if r is not None else None | |
| def new_id() -> str: | |
| return uuid.uuid4().hex | |
| def now() -> float: | |
| return time.time() | |
| # --- users --------------------------------------------------------------- | |
| def create_user(email: str, pw_hash: str, accepted_risk: bool, is_admin: bool = False) -> dict: | |
| uid = new_id() | |
| with tx() as c: | |
| c.execute("INSERT INTO users(id,email,pw_hash,tier,created_at,accepted_risk_at,is_admin) VALUES(?,?,?,?,?,?,?)", | |
| (uid, email.lower(), pw_hash, "free", now(), now() if accepted_risk else None, int(is_admin))) | |
| return get_user(uid) | |
| def get_user(uid: str) -> Optional[dict]: | |
| return row_to_dict(conn().execute("SELECT * FROM users WHERE id=?", (uid,)).fetchone()) | |
| def get_user_by_email(email: str) -> Optional[dict]: | |
| return row_to_dict(conn().execute("SELECT * FROM users WHERE email=?", (email.lower(),)).fetchone()) | |
| def set_tier(uid: str, tier: str) -> None: | |
| with tx() as c: | |
| c.execute("UPDATE users SET tier=? WHERE id=?", (tier, uid)) | |
| def count_users() -> int: | |
| return conn().execute("SELECT COUNT(*) FROM users").fetchone()[0] | |
| # --- exchange keys --------------------------------------------------------- | |
| def put_exchange_key(uid: str, exchange: str, enc_key: str, enc_secret: str, label: str = "") -> None: | |
| with tx() as c: | |
| c.execute("INSERT OR REPLACE INTO exchange_keys(user_id,exchange,label,enc_key,enc_secret,created_at) VALUES(?,?,?,?,?,?)", | |
| (uid, exchange, label, enc_key, enc_secret, now())) | |
| def get_exchange_key(uid: str, exchange: str) -> Optional[dict]: | |
| return row_to_dict(conn().execute("SELECT * FROM exchange_keys WHERE user_id=? AND exchange=?", (uid, exchange)).fetchone()) | |
| def list_exchange_keys(uid: str) -> list[dict]: | |
| rows = conn().execute("SELECT exchange,label,created_at FROM exchange_keys WHERE user_id=?", (uid,)).fetchall() | |
| return [dict(r) for r in rows] | |
| def delete_exchange_key(uid: str, exchange: str) -> None: | |
| with tx() as c: | |
| c.execute("DELETE FROM exchange_keys WHERE user_id=? AND exchange=?", (uid, exchange)) | |
| # --- bots ---------------------------------------------------------------- | |
| def create_bot(uid: str, name: str, strategy: str, params: dict, symbol: str, timeframe: str, mode: str, | |
| exchange: Optional[str], state: Optional[dict] = None) -> dict: | |
| bid = new_id() | |
| with tx() as c: | |
| c.execute("""INSERT INTO bots(id,user_id,name,strategy,params,symbol,timeframe,mode,exchange,status,state,created_at,updated_at) | |
| VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""", | |
| (bid, uid, name, strategy, json.dumps(params), symbol, timeframe, mode, exchange, "stopped", | |
| json.dumps(state or {}), now(), now())) | |
| return get_bot(bid) | |
| def get_bot(bid: str) -> Optional[dict]: | |
| b = row_to_dict(conn().execute("SELECT * FROM bots WHERE id=?", (bid,)).fetchone()) | |
| if b: | |
| b["params"] = json.loads(b["params"] or "{}") | |
| b["state"] = json.loads(b["state"] or "{}") | |
| return b | |
| def list_bots(uid: str) -> list[dict]: | |
| rows = conn().execute("SELECT id FROM bots WHERE user_id=? ORDER BY created_at", (uid,)).fetchall() | |
| return [get_bot(r["id"]) for r in rows] | |
| def list_running_bots() -> list[dict]: | |
| rows = conn().execute("SELECT id FROM bots WHERE status='running'").fetchall() | |
| return [get_bot(r["id"]) for r in rows] | |
| # Columns update_bot may write. The UPDATE statement is built by joining these names, so an | |
| # allowlist is what keeps that from ever becoming an injection point, whatever a caller passes. | |
| _BOT_COLUMNS = {"name", "strategy", "params", "symbol", "timeframe", "mode", "exchange", "status", "state"} | |
| def update_bot(bid: str, **fields: Any) -> None: | |
| unknown = set(fields) - _BOT_COLUMNS | |
| if unknown: | |
| raise ValueError(f"not updatable bot columns: {sorted(unknown)}") | |
| if "params" in fields: | |
| fields["params"] = json.dumps(fields["params"]) | |
| if "state" in fields: | |
| fields["state"] = json.dumps(fields["state"]) | |
| fields["updated_at"] = now() | |
| cols = ", ".join(f"{k}=?" for k in fields) | |
| with tx() as c: | |
| c.execute(f"UPDATE bots SET {cols} WHERE id=?", (*fields.values(), bid)) | |
| def delete_bot(bid: str) -> None: | |
| with tx() as c: | |
| c.execute("DELETE FROM bots WHERE id=?", (bid,)) | |
| c.execute("DELETE FROM bot_events WHERE bot_id=?", (bid,)) | |
| def add_event(bid: str, payload: dict) -> None: | |
| with tx() as c: | |
| c.execute("INSERT INTO bot_events(bot_id,at,payload) VALUES(?,?,?)", (bid, now(), json.dumps(payload))) | |
| c.execute("DELETE FROM bot_events WHERE bot_id=? AND id NOT IN (SELECT id FROM bot_events WHERE bot_id=? ORDER BY id DESC LIMIT 500)", (bid, bid)) | |
| def list_events(bid: str, limit: int = 100) -> list[dict]: | |
| rows = conn().execute("SELECT at,payload FROM bot_events WHERE bot_id=? ORDER BY id DESC LIMIT ?", (bid, limit)).fetchall() | |
| return [{"at": r["at"], **json.loads(r["payload"])} for r in rows] | |
| # --- api tokens (enterprise) ------------------------------------------------- | |
| def create_api_token(uid: str, label: str) -> str: | |
| token = "tb_" + uuid.uuid4().hex + uuid.uuid4().hex[:16] | |
| with tx() as c: | |
| c.execute("INSERT INTO api_tokens(token,user_id,label,created_at) VALUES(?,?,?,?)", (token, uid, label, now())) | |
| return token | |
| def user_for_api_token(token: str) -> Optional[dict]: | |
| r = conn().execute("SELECT user_id FROM api_tokens WHERE token=?", (token,)).fetchone() | |
| return get_user(r["user_id"]) if r else None | |