Spaces:
Sleeping
Sleeping
File size: 12,787 Bytes
3067a0c f617a51 3067a0c f617a51 3067a0c 90436a7 3067a0c 90436a7 3067a0c 90436a7 3067a0c f617a51 3067a0c 90436a7 3067a0c f617a51 5b71488 3067a0c a013512 | 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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | """Database persistence layer for FL-MCP with Hugging Face Persistent Volume and PostgreSQL support.
Ensures ACID compliance and persistence:
- If DATABASE_URL is set (e.g. Supabase, Neon, Render, Railway), connects via PostgreSQL.
- If running on a Hugging Face Space with Persistent Storage mounted at /data, defaults to /data/flmcp.db.
- Otherwise falls back to FLMCP_DB or local file with directory auto-creation.
"""
from __future__ import annotations
import contextlib
import os
import re
import sqlite3
import time
from collections.abc import Callable, Iterator
from pathlib import Path
from typing import Any
SQLITE_SCHEMA = """
CREATE TABLE IF NOT EXISTS accounts (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
auth_user_id TEXT UNIQUE,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS licenses (
id TEXT PRIMARY KEY,
account_id TEXT NOT NULL REFERENCES accounts(id),
key_hash TEXT NOT NULL UNIQUE,
plan TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('active','past_due','canceled','revoked')),
period_end INTEGER,
seats_allowed INTEGER NOT NULL DEFAULT 2,
provider TEXT NOT NULL DEFAULT '',
provider_ref TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL,
revoked_at INTEGER
);
CREATE UNIQUE INDEX IF NOT EXISTS licenses_ref ON licenses(provider, provider_ref)
WHERE provider_ref != '';
CREATE TABLE IF NOT EXISTS devices (
pk INTEGER PRIMARY KEY AUTOINCREMENT,
license_id TEXT NOT NULL REFERENCES licenses(id),
device_id TEXT NOT NULL,
name TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL,
last_seen INTEGER NOT NULL,
revoked INTEGER NOT NULL DEFAULT 0,
UNIQUE (license_id, device_id)
);
CREATE TABLE IF NOT EXISTS lots (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account_id TEXT NOT NULL REFERENCES accounts(id),
kind TEXT NOT NULL,
amount INTEGER NOT NULL CHECK (amount > 0),
remaining INTEGER NOT NULL CHECK (remaining >= 0 AND remaining <= amount),
expires_at INTEGER,
source TEXT UNIQUE,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS lots_account ON lots(account_id, expires_at);
CREATE TABLE IF NOT EXISTS reservations (
id TEXT PRIMARY KEY,
account_id TEXT NOT NULL REFERENCES accounts(id),
idem TEXT NOT NULL,
state TEXT NOT NULL CHECK (state IN ('held','settled','expired')),
ops TEXT NOT NULL,
cost INTEGER NOT NULL,
alloc TEXT NOT NULL,
done TEXT,
charged INTEGER,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
settled_at INTEGER,
UNIQUE (account_id, idem)
);
CREATE INDEX IF NOT EXISTS reservations_open ON reservations(state, expires_at);
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account_id TEXT NOT NULL REFERENCES accounts(id),
ts INTEGER NOT NULL,
kind TEXT NOT NULL CHECK (kind IN ('grant','hold','release','expire')),
amount INTEGER NOT NULL,
ref TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS entries_account ON entries(account_id, id);
CREATE TABLE IF NOT EXISTS webhook_events (
provider TEXT NOT NULL,
event_id TEXT NOT NULL,
received_at INTEGER NOT NULL,
PRIMARY KEY (provider, event_id)
);
CREATE TABLE IF NOT EXISTS outbox (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account_id TEXT NOT NULL REFERENCES accounts(id),
kind TEXT NOT NULL,
payload TEXT NOT NULL,
created_at INTEGER NOT NULL,
sent_at INTEGER
);
"""
PG_SCHEMA = """
CREATE TABLE IF NOT EXISTS accounts (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
auth_user_id TEXT UNIQUE,
created_at BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS licenses (
id TEXT PRIMARY KEY,
account_id TEXT NOT NULL REFERENCES accounts(id),
key_hash TEXT NOT NULL UNIQUE,
plan TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('active','past_due','canceled','revoked')),
period_end BIGINT,
seats_allowed INTEGER NOT NULL DEFAULT 2,
provider TEXT NOT NULL DEFAULT '',
provider_ref TEXT NOT NULL DEFAULT '',
created_at BIGINT NOT NULL,
revoked_at BIGINT
);
CREATE UNIQUE INDEX IF NOT EXISTS licenses_ref ON licenses(provider, provider_ref)
WHERE provider_ref != '';
CREATE TABLE IF NOT EXISTS devices (
pk SERIAL PRIMARY KEY,
license_id TEXT NOT NULL REFERENCES licenses(id),
device_id TEXT NOT NULL,
name TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
created_at BIGINT NOT NULL,
last_seen BIGINT NOT NULL,
revoked INTEGER NOT NULL DEFAULT 0,
UNIQUE (license_id, device_id)
);
CREATE TABLE IF NOT EXISTS lots (
id SERIAL PRIMARY KEY,
account_id TEXT NOT NULL REFERENCES accounts(id),
kind TEXT NOT NULL,
amount INTEGER NOT NULL CHECK (amount > 0),
remaining INTEGER NOT NULL CHECK (remaining >= 0 AND remaining <= amount),
expires_at BIGINT,
source TEXT UNIQUE,
created_at BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS lots_account ON lots(account_id, expires_at);
CREATE TABLE IF NOT EXISTS reservations (
id TEXT PRIMARY KEY,
account_id TEXT NOT NULL REFERENCES accounts(id),
idem TEXT NOT NULL,
state TEXT NOT NULL CHECK (state IN ('held','settled','expired')),
ops TEXT NOT NULL,
cost INTEGER NOT NULL,
alloc TEXT NOT NULL,
done TEXT,
charged INTEGER,
created_at BIGINT NOT NULL,
expires_at BIGINT NOT NULL,
settled_at BIGINT,
UNIQUE (account_id, idem)
);
CREATE INDEX IF NOT EXISTS reservations_open ON reservations(state, expires_at);
CREATE TABLE IF NOT EXISTS entries (
id SERIAL PRIMARY KEY,
account_id TEXT NOT NULL REFERENCES accounts(id),
ts BIGINT NOT NULL,
kind TEXT NOT NULL CHECK (kind IN ('grant','hold','release','expire')),
amount INTEGER NOT NULL,
ref TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS entries_account ON entries(account_id, id);
CREATE TABLE IF NOT EXISTS webhook_events (
provider TEXT NOT NULL,
event_id TEXT NOT NULL,
received_at BIGINT NOT NULL,
PRIMARY KEY (provider, event_id)
);
CREATE TABLE IF NOT EXISTS outbox (
id SERIAL PRIMARY KEY,
account_id TEXT NOT NULL REFERENCES accounts(id),
kind TEXT NOT NULL,
payload TEXT NOT NULL,
created_at BIGINT NOT NULL,
sent_at BIGINT
);
"""
def default_db_path() -> str:
"""Detect persistent volume or custom configuration."""
if os.environ.get("FLMCP_DB"):
return os.environ["FLMCP_DB"]
if os.path.isdir("/data") and os.access("/data", os.W_OK):
# Hugging Face Spaces persistent volume attached at /data
return "/data/flmcp.db"
# Local fallback
data_dir = Path("data")
data_dir.mkdir(parents=True, exist_ok=True)
return str(data_dir / "flmcp.db")
class PgCursorWrapper:
"""Wraps Postgres cursor to give dict-like and index-based row access and lastrowid."""
def __init__(self, raw_cursor: Any) -> None:
self._cur = raw_cursor
def execute(self, sql: str, params: tuple | list = ()) -> PgCursorWrapper:
# Convert SQLite ? parameters to Postgres %s
pg_sql = sql.replace("?", "%s")
# Handle 'INSERT OR IGNORE' for Postgres 'ON CONFLICT DO NOTHING'
if "INSERT OR IGNORE INTO lots" in pg_sql:
pg_sql = pg_sql.replace("INSERT OR IGNORE INTO lots", "INSERT INTO lots")
pg_sql += " ON CONFLICT (source) DO NOTHING"
if "RETURNING id" not in pg_sql:
pg_sql += " RETURNING id"
elif "INSERT OR IGNORE INTO webhook_events" in pg_sql:
pg_sql = pg_sql.replace("INSERT OR IGNORE INTO webhook_events", "INSERT INTO webhook_events")
pg_sql += " ON CONFLICT (provider, event_id) DO NOTHING"
self._cur.execute(pg_sql, params)
return self
def fetchone(self) -> dict[str, Any] | None:
row = self._cur.fetchone()
if row is None:
return None
return dict(row)
def fetchall(self) -> list[dict[str, Any]]:
rows = self._cur.fetchall()
return [dict(r) for r in rows]
@property
def rowcount(self) -> int:
return self._cur.rowcount
@property
def lastrowid(self) -> int | None:
try:
return self._cur.fetchone().get("id")
except Exception:
return None
class PgConnectionWrapper:
"""Wraps Postgres connection to present the same interface as sqlite3.Connection."""
def __init__(self, conn: Any) -> None:
self.conn = conn
def execute(self, sql: str, params: tuple | list = ()) -> PgCursorWrapper:
cur = self.conn.cursor()
wrapper = PgCursorWrapper(cur)
wrapper.execute(sql, params)
return wrapper
def executescript(self, sql: str) -> None:
with self.conn.cursor() as cur:
cur.execute(sql)
class DB:
"""Database interface supporting both SQLite (with HF persistent storage) and PostgreSQL."""
def __init__(
self,
db_target: str | None = None,
clock: Callable[[], float] = time.time,
) -> None:
self.clock = clock
raw_url = (os.environ.get("DATABASE_URL") or "").strip()
is_placeholder = any(
token in raw_url.upper()
for token in ("YOUR_", "CHANGE_ME", "PLACEHOLDER", "[PASSWORD]", "[YOUR-PASSWORD]")
)
self.database_url = "" if is_placeholder else raw_url
self.is_postgres = bool(
self.database_url
and (
self.database_url.startswith("postgres://")
or self.database_url.startswith("postgresql://")
)
)
self.path = db_target or default_db_path()
if self.is_postgres:
try:
import psycopg2
import psycopg2.extras
self._pg_module = psycopg2
self._init_postgres()
return
except Exception:
# Graceful fallback to SQLite so placeholder or temporarily unreachable
# DATABASE_URL values never crash the backend service.
self.is_postgres = False
Path(self.path).parent.mkdir(parents=True, exist_ok=True)
self._init_sqlite()
def _init_sqlite(self) -> None:
conn = sqlite3.connect(self.path, timeout=15)
try:
conn.execute("PRAGMA journal_mode=WAL")
conn.executescript(SQLITE_SCHEMA)
cols = [r[1] for r in conn.execute("PRAGMA table_info(accounts)")]
if "auth_user_id" not in cols: # database created before sign-in existed
conn.execute("ALTER TABLE accounts ADD COLUMN auth_user_id TEXT")
conn.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS accounts_auth ON accounts(auth_user_id)"
)
conn.commit()
finally:
conn.close()
def _init_postgres(self) -> None:
conn = self._pg_module.connect(self.database_url, connect_timeout=5)
try:
with conn.cursor() as cur:
cur.execute(PG_SCHEMA)
cur.execute("ALTER TABLE accounts ADD COLUMN IF NOT EXISTS auth_user_id TEXT")
cur.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS accounts_auth ON accounts(auth_user_id)"
)
# Supabase publishes the public schema through its REST API; with RLS on and no
# policies the publishable key sees nothing. This service connects as the
# postgres role, which bypasses RLS.
for table in (
"accounts", "licenses", "devices", "lots",
"reservations", "entries", "webhook_events", "outbox",
):
cur.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
conn.commit()
finally:
conn.close()
def now(self) -> int:
return int(self.clock())
@contextlib.contextmanager
def tx(self) -> Iterator[Any]:
if self.is_postgres:
import psycopg2.extras
conn = self._pg_module.connect(self.database_url, cursor_factory=psycopg2.extras.RealDictCursor)
try:
wrapper = PgConnectionWrapper(conn)
yield wrapper
conn.commit()
except BaseException:
conn.rollback()
raise
finally:
conn.close()
else:
conn = sqlite3.connect(self.path, timeout=15, isolation_level=None)
try:
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys=ON")
conn.execute("BEGIN IMMEDIATE")
try:
yield conn
except BaseException:
conn.execute("ROLLBACK")
raise
conn.execute("COMMIT")
finally:
conn.close()
|