Files
momentum devandClaude Fable 5 495a3fa5d6 feat: strategy knobs in the database — config_overrides table, admin-managed
Owner preference: the bulk of TRADING_*/TRIGGER_* logic switches should live
in the DB, not the compose file (keys + connection info stay in compose —
the DB address cannot live inside the DB, and secrets don't belong in a
table the stack can SELECT). Precedence at boot: compose env < overrides.env
< config_overrides table; every entrypoint already routes through
env_overrides.load(), which now applies the table last. Admin /api/config
and profile-apply write the table (secrets whitelist unchanged); the config
page shows source=database. DB down = silent fall-through to file/compose,
boot never blocks on config. One-shot migration:
  python -m runtime.env_overrides seed-from-env
run in any stack container to copy its current effective knobs into the
table, after which the compose lines are dead weight strippable at the next
redeploy.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 20:31:16 -05:00

141 lines
5.4 KiB
Python

"""Runtime env overrides: /app/data/overrides.env (shared volume) beats the
compose-baked environment. The admin panel writes this file and restarts the
service; every entrypoint calls load() first so changes take effect on boot
without touching the deployment YAML."""
from __future__ import annotations
import os
OVERRIDES_FILE = os.environ.get("ENV_OVERRIDES_FILE") or os.path.join(
os.path.dirname(__file__), "..", "data", "overrides.env")
def load() -> int:
"""Apply overrides (override=True). Returns count of applied keys.
Order: overrides.env file first, then the config_overrides DB table (DB
wins — it is the owner-facing store; the file keeps secrets + bootstrap)."""
n = 0
try:
from dotenv import load_dotenv
if os.path.exists(OVERRIDES_FILE):
before = dict(os.environ)
load_dotenv(OVERRIDES_FILE, override=True)
n = sum(1 for k, v in os.environ.items() if before.get(k) != v)
except Exception: # noqa: BLE001 — a broken overrides file must not stop boot
pass
try:
n += load_db()
except Exception: # noqa: BLE001
pass
return n
def read_overrides() -> dict[str, str]:
out: dict[str, str] = {}
if not os.path.exists(OVERRIDES_FILE):
return out
for line in open(OVERRIDES_FILE):
line = line.strip()
if line and not line.startswith("#") and "=" in line:
k, _, v = line.partition("=")
out[k.strip()] = v.strip()
return out
def write_overrides(updates: dict[str, str | None]) -> dict[str, str]:
"""Merge updates into the overrides file (None deletes a key)."""
cur = read_overrides()
for k, v in updates.items():
if v is None:
cur.pop(k, None)
else:
cur[k] = str(v)
os.makedirs(os.path.dirname(os.path.abspath(OVERRIDES_FILE)), exist_ok=True)
with open(OVERRIDES_FILE, "w") as f:
f.write("# Written by the momentum admin panel — beats compose env at boot.\n")
for k in sorted(cur):
f.write(f"{k}={cur[k]}\n")
return cur
# ---------- database-backed overrides (owner preference 2026-07-22) ----------
# Strategy knobs (TRADING_*/TRIGGER_*/... — no secrets, admin whitelist enforces)
# live in the config_overrides table and are applied at boot AFTER the file
# pass, so precedence is: compose env < overrides.env < database. Secrets and
# connection info stay in compose/overrides.env by design — the DB address
# cannot live inside the DB, and secret values don't belong in a table the
# whole stack can SELECT.
def _db_con():
from storage.db_pg import get_connection
return get_connection("momentum")
def read_db_overrides(con=None) -> dict[str, str]:
"""Best-effort: {} when the DB or table doesn't exist yet."""
try:
con = con or _db_con()
rows = con.execute(
"SELECT key, value FROM config_overrides ORDER BY key").fetchall()
return {str(k): str(v) for k, v in rows}
except Exception: # noqa: BLE001 — missing table / DB down = no overrides
return {}
def write_db_overrides(updates: dict[str, str | None], con=None) -> dict[str, str]:
"""Merge updates into config_overrides (None deletes). Creates the table on
first use. Raises on DB failure — a config write must not silently vanish."""
con = con or _db_con()
con.execute(
"CREATE TABLE IF NOT EXISTS config_overrides ("
" key TEXT PRIMARY KEY, value TEXT NOT NULL,"
" updated_at TIMESTAMPTZ NOT NULL DEFAULT now())")
for k, v in updates.items():
if v is None:
con.execute("DELETE FROM config_overrides WHERE key=?", [k])
else:
con.execute(
"INSERT INTO config_overrides (key, value) VALUES (?, ?) "
"ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, "
"updated_at=now()", [k, str(v)])
return read_db_overrides(con)
def load_db() -> int:
"""Apply DB overrides onto os.environ (they win over compose + file).
Silent no-op when the DB is unreachable — boot must never block on config."""
if os.environ.get("ENV_OVERRIDES_DB", "1") != "1":
return 0
n = 0
for k, v in read_db_overrides().items():
if os.environ.get(k) != v:
os.environ[k] = v
n += 1
return n
def _seed_from_env() -> dict[str, str]:
"""One-shot migration: copy the current process env's strategy knobs into
config_overrides so the compose lines become strippable. Same whitelist as
the admin panel; secret-marked keys never enter the table."""
prefixes = ("TRADING_", "TRIGGER_", "WATCHER_", "LIVE_BARS_", "NEWS_",
"OLLAMA_", "DISCOVER_", "SYMBOL_WEIGHTS")
secret = ("KEY", "SECRET", "TOKEN", "PASSWORD", "WEBHOOK", "URL")
knobs = {k: v for k, v in os.environ.items()
if (k.startswith(prefixes) or k == "ALPACA_DATA_FEED")
and not any(m in k.upper() for m in secret)}
return write_db_overrides(knobs)
if __name__ == "__main__":
import sys
if len(sys.argv) > 1 and sys.argv[1] == "seed-from-env":
from dotenv import load_dotenv
load_dotenv()
load() # file overrides first, so the seed captures the effective values
merged = _seed_from_env()
print(f"seeded {len(merged)} knobs into config_overrides")
else:
print("usage: python -m runtime.env_overrides seed-from-env")