Rthur2003 commited on
Commit
3067a0c
·
1 Parent(s): a427438

feat: add FL-MCP database persistence layer supporting SQLite and PostgreSQL

Browse files
app/services/flmcp/db.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Database persistence layer for FL-MCP with Hugging Face Persistent Volume and PostgreSQL support.
2
+
3
+ Ensures ACID compliance and persistence:
4
+ - If DATABASE_URL is set (e.g. Supabase, Neon, Render, Railway), connects via PostgreSQL.
5
+ - If running on a Hugging Face Space with Persistent Storage mounted at /data, defaults to /data/flmcp.db.
6
+ - Otherwise falls back to FLMCP_DB or local file with directory auto-creation.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import contextlib
12
+ import os
13
+ import re
14
+ import sqlite3
15
+ import time
16
+ from collections.abc import Callable, Iterator
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ SQLITE_SCHEMA = """
21
+ CREATE TABLE IF NOT EXISTS accounts (
22
+ id TEXT PRIMARY KEY,
23
+ email TEXT NOT NULL UNIQUE,
24
+ created_at INTEGER NOT NULL
25
+ );
26
+
27
+ CREATE TABLE IF NOT EXISTS licenses (
28
+ id TEXT PRIMARY KEY,
29
+ account_id TEXT NOT NULL REFERENCES accounts(id),
30
+ key_hash TEXT NOT NULL UNIQUE,
31
+ plan TEXT NOT NULL,
32
+ status TEXT NOT NULL CHECK (status IN ('active','past_due','canceled','revoked')),
33
+ period_end INTEGER,
34
+ seats_allowed INTEGER NOT NULL DEFAULT 2,
35
+ provider TEXT NOT NULL DEFAULT '',
36
+ provider_ref TEXT NOT NULL DEFAULT '',
37
+ created_at INTEGER NOT NULL,
38
+ revoked_at INTEGER
39
+ );
40
+
41
+ CREATE UNIQUE INDEX IF NOT EXISTS licenses_ref ON licenses(provider, provider_ref)
42
+ WHERE provider_ref != '';
43
+
44
+ CREATE TABLE IF NOT EXISTS devices (
45
+ pk INTEGER PRIMARY KEY AUTOINCREMENT,
46
+ license_id TEXT NOT NULL REFERENCES licenses(id),
47
+ device_id TEXT NOT NULL,
48
+ name TEXT NOT NULL,
49
+ token_hash TEXT NOT NULL UNIQUE,
50
+ created_at INTEGER NOT NULL,
51
+ last_seen INTEGER NOT NULL,
52
+ revoked INTEGER NOT NULL DEFAULT 0,
53
+ UNIQUE (license_id, device_id)
54
+ );
55
+
56
+ CREATE TABLE IF NOT EXISTS lots (
57
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
58
+ account_id TEXT NOT NULL REFERENCES accounts(id),
59
+ kind TEXT NOT NULL,
60
+ amount INTEGER NOT NULL CHECK (amount > 0),
61
+ remaining INTEGER NOT NULL CHECK (remaining >= 0 AND remaining <= amount),
62
+ expires_at INTEGER,
63
+ source TEXT UNIQUE,
64
+ created_at INTEGER NOT NULL
65
+ );
66
+
67
+ CREATE INDEX IF NOT EXISTS lots_account ON lots(account_id, expires_at);
68
+
69
+ CREATE TABLE IF NOT EXISTS reservations (
70
+ id TEXT PRIMARY KEY,
71
+ account_id TEXT NOT NULL REFERENCES accounts(id),
72
+ idem TEXT NOT NULL,
73
+ state TEXT NOT NULL CHECK (state IN ('held','settled','expired')),
74
+ ops TEXT NOT NULL,
75
+ cost INTEGER NOT NULL,
76
+ alloc TEXT NOT NULL,
77
+ done TEXT,
78
+ charged INTEGER,
79
+ created_at INTEGER NOT NULL,
80
+ expires_at INTEGER NOT NULL,
81
+ settled_at INTEGER,
82
+ UNIQUE (account_id, idem)
83
+ );
84
+
85
+ CREATE INDEX IF NOT EXISTS reservations_open ON reservations(state, expires_at);
86
+
87
+ CREATE TABLE IF NOT EXISTS entries (
88
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
89
+ account_id TEXT NOT NULL REFERENCES accounts(id),
90
+ ts INTEGER NOT NULL,
91
+ kind TEXT NOT NULL CHECK (kind IN ('grant','hold','release','expire')),
92
+ amount INTEGER NOT NULL,
93
+ ref TEXT NOT NULL DEFAULT ''
94
+ );
95
+
96
+ CREATE INDEX IF NOT EXISTS entries_account ON entries(account_id, id);
97
+
98
+ CREATE TABLE IF NOT EXISTS webhook_events (
99
+ provider TEXT NOT NULL,
100
+ event_id TEXT NOT NULL,
101
+ received_at INTEGER NOT NULL,
102
+ PRIMARY KEY (provider, event_id)
103
+ );
104
+
105
+ CREATE TABLE IF NOT EXISTS outbox (
106
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
107
+ account_id TEXT NOT NULL REFERENCES accounts(id),
108
+ kind TEXT NOT NULL,
109
+ payload TEXT NOT NULL,
110
+ created_at INTEGER NOT NULL,
111
+ sent_at INTEGER
112
+ );
113
+ """
114
+
115
+ PG_SCHEMA = """
116
+ CREATE TABLE IF NOT EXISTS accounts (
117
+ id TEXT PRIMARY KEY,
118
+ email TEXT NOT NULL UNIQUE,
119
+ created_at BIGINT NOT NULL
120
+ );
121
+
122
+ CREATE TABLE IF NOT EXISTS licenses (
123
+ id TEXT PRIMARY KEY,
124
+ account_id TEXT NOT NULL REFERENCES accounts(id),
125
+ key_hash TEXT NOT NULL UNIQUE,
126
+ plan TEXT NOT NULL,
127
+ status TEXT NOT NULL CHECK (status IN ('active','past_due','canceled','revoked')),
128
+ period_end BIGINT,
129
+ seats_allowed INTEGER NOT NULL DEFAULT 2,
130
+ provider TEXT NOT NULL DEFAULT '',
131
+ provider_ref TEXT NOT NULL DEFAULT '',
132
+ created_at BIGINT NOT NULL,
133
+ revoked_at BIGINT
134
+ );
135
+
136
+ CREATE UNIQUE INDEX IF NOT EXISTS licenses_ref ON licenses(provider, provider_ref)
137
+ WHERE provider_ref != '';
138
+
139
+ CREATE TABLE IF NOT EXISTS devices (
140
+ pk SERIAL PRIMARY KEY,
141
+ license_id TEXT NOT NULL REFERENCES licenses(id),
142
+ device_id TEXT NOT NULL,
143
+ name TEXT NOT NULL,
144
+ token_hash TEXT NOT NULL UNIQUE,
145
+ created_at BIGINT NOT NULL,
146
+ last_seen BIGINT NOT NULL,
147
+ revoked INTEGER NOT NULL DEFAULT 0,
148
+ UNIQUE (license_id, device_id)
149
+ );
150
+
151
+ CREATE TABLE IF NOT EXISTS lots (
152
+ id SERIAL PRIMARY KEY,
153
+ account_id TEXT NOT NULL REFERENCES accounts(id),
154
+ kind TEXT NOT NULL,
155
+ amount INTEGER NOT NULL CHECK (amount > 0),
156
+ remaining INTEGER NOT NULL CHECK (remaining >= 0 AND remaining <= amount),
157
+ expires_at BIGINT,
158
+ source TEXT UNIQUE,
159
+ created_at BIGINT NOT NULL
160
+ );
161
+
162
+ CREATE INDEX IF NOT EXISTS lots_account ON lots(account_id, expires_at);
163
+
164
+ CREATE TABLE IF NOT EXISTS reservations (
165
+ id TEXT PRIMARY KEY,
166
+ account_id TEXT NOT NULL REFERENCES accounts(id),
167
+ idem TEXT NOT NULL,
168
+ state TEXT NOT NULL CHECK (state IN ('held','settled','expired')),
169
+ ops TEXT NOT NULL,
170
+ cost INTEGER NOT NULL,
171
+ alloc TEXT NOT NULL,
172
+ done TEXT,
173
+ charged INTEGER,
174
+ created_at BIGINT NOT NULL,
175
+ expires_at BIGINT NOT NULL,
176
+ settled_at BIGINT,
177
+ UNIQUE (account_id, idem)
178
+ );
179
+
180
+ CREATE INDEX IF NOT EXISTS reservations_open ON reservations(state, expires_at);
181
+
182
+ CREATE TABLE IF NOT EXISTS entries (
183
+ id SERIAL PRIMARY KEY,
184
+ account_id TEXT NOT NULL REFERENCES accounts(id),
185
+ ts BIGINT NOT NULL,
186
+ kind TEXT NOT NULL CHECK (kind IN ('grant','hold','release','expire')),
187
+ amount INTEGER NOT NULL,
188
+ ref TEXT NOT NULL DEFAULT ''
189
+ );
190
+
191
+ CREATE INDEX IF NOT EXISTS entries_account ON entries(account_id, id);
192
+
193
+ CREATE TABLE IF NOT EXISTS webhook_events (
194
+ provider TEXT NOT NULL,
195
+ event_id TEXT NOT NULL,
196
+ received_at BIGINT NOT NULL,
197
+ PRIMARY KEY (provider, event_id)
198
+ );
199
+
200
+ CREATE TABLE IF NOT EXISTS outbox (
201
+ id SERIAL PRIMARY KEY,
202
+ account_id TEXT NOT NULL REFERENCES accounts(id),
203
+ kind TEXT NOT NULL,
204
+ payload TEXT NOT NULL,
205
+ created_at BIGINT NOT NULL,
206
+ sent_at BIGINT
207
+ );
208
+ """
209
+
210
+
211
+ def default_db_path() -> str:
212
+ """Detect persistent volume or custom configuration."""
213
+ if os.environ.get("FLMCP_DB"):
214
+ return os.environ["FLMCP_DB"]
215
+ if os.path.isdir("/data") and os.access("/data", os.W_OK):
216
+ # Hugging Face Spaces persistent volume attached at /data
217
+ return "/data/flmcp.db"
218
+ # Local fallback
219
+ data_dir = Path("data")
220
+ data_dir.mkdir(parents=True, exist_ok=True)
221
+ return str(data_dir / "flmcp.db")
222
+
223
+
224
+ class PgCursorWrapper:
225
+ """Wraps Postgres cursor to give dict-like and index-based row access and lastrowid."""
226
+
227
+ def __init__(self, raw_cursor: Any) -> None:
228
+ self._cur = raw_cursor
229
+
230
+ def execute(self, sql: str, params: tuple | list = ()) -> PgCursorWrapper:
231
+ # Convert SQLite ? parameters to Postgres %s
232
+ pg_sql = sql.replace("?", "%s")
233
+ # Handle 'INSERT OR IGNORE' for Postgres 'ON CONFLICT DO NOTHING'
234
+ if "INSERT OR IGNORE INTO lots" in pg_sql:
235
+ pg_sql = pg_sql.replace("INSERT OR IGNORE INTO lots", "INSERT INTO lots")
236
+ pg_sql += " ON CONFLICT (source) DO NOTHING"
237
+ if "RETURNING id" not in pg_sql:
238
+ pg_sql += " RETURNING id"
239
+ elif "INSERT OR IGNORE INTO webhook_events" in pg_sql:
240
+ pg_sql = pg_sql.replace("INSERT OR IGNORE INTO webhook_events", "INSERT INTO webhook_events")
241
+ pg_sql += " ON CONFLICT (provider, event_id) DO NOTHING"
242
+
243
+ self._cur.execute(pg_sql, params)
244
+ return self
245
+
246
+ def fetchone(self) -> dict[str, Any] | None:
247
+ row = self._cur.fetchone()
248
+ if row is None:
249
+ return None
250
+ return dict(row)
251
+
252
+ def fetchall(self) -> list[dict[str, Any]]:
253
+ rows = self._cur.fetchall()
254
+ return [dict(r) for r in rows]
255
+
256
+ @property
257
+ def rowcount(self) -> int:
258
+ return self._cur.rowcount
259
+
260
+ @property
261
+ def lastrowid(self) -> int | None:
262
+ try:
263
+ return self._cur.fetchone().get("id")
264
+ except Exception:
265
+ return None
266
+
267
+
268
+ class PgConnectionWrapper:
269
+ """Wraps Postgres connection to present the same interface as sqlite3.Connection."""
270
+
271
+ def __init__(self, conn: Any) -> None:
272
+ self.conn = conn
273
+
274
+ def execute(self, sql: str, params: tuple | list = ()) -> PgCursorWrapper:
275
+ cur = self.conn.cursor()
276
+ wrapper = PgCursorWrapper(cur)
277
+ wrapper.execute(sql, params)
278
+ return wrapper
279
+
280
+ def executescript(self, sql: str) -> None:
281
+ with self.conn.cursor() as cur:
282
+ cur.execute(sql)
283
+
284
+
285
+ class DB:
286
+ """Database interface supporting both SQLite (with HF persistent storage) and PostgreSQL."""
287
+
288
+ def __init__(
289
+ self,
290
+ db_target: str | None = None,
291
+ clock: Callable[[], float] = time.time,
292
+ ) -> None:
293
+ self.clock = clock
294
+ self.database_url = os.environ.get("DATABASE_URL")
295
+ self.is_postgres = bool(self.database_url and (
296
+ self.database_url.startswith("postgres://") or self.database_url.startswith("postgresql://")
297
+ ))
298
+
299
+ if self.is_postgres:
300
+ try:
301
+ import psycopg2
302
+ import psycopg2.extras
303
+ self._pg_module = psycopg2
304
+ except ImportError:
305
+ try:
306
+ import psycopg
307
+ self._pg_module = psycopg
308
+ except ImportError:
309
+ raise RuntimeError("PostgreSQL driver (psycopg2 or psycopg) not found. Install psycopg2-binary.")
310
+ self._init_postgres()
311
+ else:
312
+ self.path = db_target or default_db_path()
313
+ Path(self.path).parent.mkdir(parents=True, exist_ok=True)
314
+ self._init_sqlite()
315
+
316
+ def _init_sqlite(self) -> None:
317
+ conn = sqlite3.connect(self.path, timeout=15)
318
+ try:
319
+ conn.execute("PRAGMA journal_mode=WAL")
320
+ conn.executescript(SQLITE_SCHEMA)
321
+ finally:
322
+ conn.close()
323
+
324
+ def _init_postgres(self) -> None:
325
+ import psycopg2.extras
326
+ conn = self._pg_module.connect(self.database_url)
327
+ try:
328
+ with conn.cursor() as cur:
329
+ cur.execute(PG_SCHEMA)
330
+ conn.commit()
331
+ finally:
332
+ conn.close()
333
+
334
+ def now(self) -> int:
335
+ return int(self.clock())
336
+
337
+ @contextlib.contextmanager
338
+ def tx(self) -> Iterator[Any]:
339
+ if self.is_postgres:
340
+ import psycopg2.extras
341
+ conn = self._pg_module.connect(self.database_url, cursor_factory=psycopg2.extras.RealDictCursor)
342
+ try:
343
+ wrapper = PgConnectionWrapper(conn)
344
+ yield wrapper
345
+ conn.commit()
346
+ except BaseException:
347
+ conn.rollback()
348
+ raise
349
+ finally:
350
+ conn.close()
351
+ else:
352
+ conn = sqlite3.connect(self.path, timeout=15, isolation_level=None)
353
+ try:
354
+ conn.row_factory = sqlite3.Row
355
+ conn.execute("PRAGMA foreign_keys=ON")
356
+ conn.execute("BEGIN IMMEDIATE")
357
+ try:
358
+ yield conn
359
+ except BaseException:
360
+ conn.execute("ROLLBACK")
361
+ raise
362
+ conn.execute("COMMIT")
363
+ finally:
364
+ conn.close()
app/services/flmcp/errors.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """API Errors matching RFC 9457 application/problem+json."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class ApiError(Exception):
7
+ """A failure the API reports as application/problem+json (RFC 9457)."""
8
+
9
+ def __init__(self, status: int, code: str, detail: str, **extra: object) -> None:
10
+ super().__init__(detail)
11
+ self.status = status
12
+ self.code = code
13
+ self.detail = detail
14
+ self.extra = extra
app/services/flmcp/keys.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """License key format shared by the client and the license service.
2
+
3
+ FLMCP-XXXXX-XXXXX-XXXXX-XXXXX: 19 random Crockford base32 characters (95 bits) plus one check
4
+ character. Any single mistyped character is caught on the user's machine before a request is made.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import secrets
11
+
12
+ ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
13
+ PREFIX = "FLMCP"
14
+ _FIX = str.maketrans({"O": "0", "I": "1", "L": "1"})
15
+
16
+
17
+ def _check(body: str) -> str:
18
+ """Odd position weights make every single wrong character change the sum."""
19
+ return ALPHABET[sum((2 * i + 1) * ALPHABET.index(ch) for i, ch in enumerate(body)) % 32]
20
+
21
+
22
+ def _format(chars: str) -> str:
23
+ return "-".join([PREFIX, *(chars[i : i + 5] for i in range(0, 20, 5))])
24
+
25
+
26
+ def new_key() -> str:
27
+ body = "".join(secrets.choice(ALPHABET) for _ in range(19))
28
+ return _format(body + _check(body))
29
+
30
+
31
+ def normalize(text: str) -> str | None:
32
+ """Canonical 20-character form of a typed key, or None when it cannot be a key."""
33
+ s = "".join(ch for ch in text.upper() if ch.isalnum())
34
+ if len(s) == len(PREFIX) + 20 and s.startswith(PREFIX):
35
+ s = s[len(PREFIX) :]
36
+ s = s.translate(_FIX)
37
+ if len(s) != 20 or any(ch not in ALPHABET for ch in s):
38
+ return None
39
+ return s if _check(s[:19]) == s[19] else None
40
+
41
+
42
+ def hash_key(text: str) -> str | None:
43
+ s = normalize(text)
44
+ return hashlib.sha256(s.encode()).hexdigest() if s else None
45
+
46
+
47
+ def display(text: str) -> str | None:
48
+ s = normalize(text)
49
+ return _format(s) if s else None
app/services/flmcp/plans.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plans, credit costs and policy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ from .errors import ApiError
10
+
11
+ GRACE_SECONDS = 3 * 86400 # a late renewal webhook must not lock a paying customer out
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class Plan:
16
+ credits: int # granted each period
17
+ devices: int # activations allowed at once
18
+ days: int | None = None # one-off plans (trial): length of the licence and of its credits
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Config:
23
+ costs: dict[str, int]
24
+ plans: dict[str, Plan]
25
+ packs: dict[str, int]
26
+ topup_days: int | None = None # purchased credits do not expire unless set
27
+ refund_days: int = 30 # life of the credits returned for a lot that expired meanwhile
28
+ hold_seconds: int = 600
29
+
30
+
31
+ DEFAULT = {
32
+ "costs": {"produce.compose": 5, "produce.flp": 3, "mix.balance": 2},
33
+ "plans": {
34
+ "trial": {"credits": 15, "devices": 1, "days": 30},
35
+ "pro": {"credits": 300, "devices": 2},
36
+ "studio": {"credits": 1200, "devices": 5},
37
+ },
38
+ "packs": {"pack_100": 100, "pack_500": 500},
39
+ }
40
+
41
+
42
+ def load(path: str | Path | None = None) -> Config:
43
+ raw = {**DEFAULT, **(json.loads(Path(path).read_text("utf-8")) if path else {})}
44
+ costs, packs = dict(raw["costs"]), dict(raw["packs"])
45
+ plans = {name: Plan(**p) for name, p in raw["plans"].items()}
46
+ if not costs or any(not isinstance(v, int) or v < 1 for v in costs.values()):
47
+ raise ValueError("every cost must be a whole number of credits, at least 1")
48
+ if any(not isinstance(v, int) or v < 1 for v in packs.values()):
49
+ raise ValueError("every pack must be a whole number of credits, at least 1")
50
+ if any(p.credits < 0 or p.devices < 1 for p in plans.values()):
51
+ raise ValueError("plans need credits >= 0 and devices >= 1")
52
+ return Config(
53
+ costs,
54
+ plans,
55
+ packs,
56
+ raw.get("topup_days"),
57
+ int(raw.get("refund_days", 30)),
58
+ int(raw.get("hold_seconds", 600)),
59
+ )
60
+
61
+
62
+ def usable(status: str, period_end: int | None, now: int) -> bool:
63
+ """active licences run a grace period past period_end; canceled ones stop at period_end."""
64
+ if status not in ("active", "canceled"):
65
+ return False
66
+ if period_end is None:
67
+ return True
68
+ return now < period_end + (GRACE_SECONDS if status == "active" else 0)
69
+
70
+
71
+ def require_usable(status: str, period_end: int | None, now: int) -> None:
72
+ if not usable(status, period_end, now):
73
+ state = "expired" if status == "active" else status
74
+ raise ApiError(
75
+ 403,
76
+ "license_inactive",
77
+ f"the subscription is {state}; renew it to continue",
78
+ subscription=state,
79
+ )