fiderail 2.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fiderail/ledger.py ADDED
@@ -0,0 +1,355 @@
1
+ """Concurrent-safe embedded SQLite WAL edge ledger (Python stdlib sqlite3)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import secrets
8
+ import sqlite3
9
+ import threading
10
+ import time
11
+ from datetime import datetime, timezone
12
+ from typing import Any, Dict, Optional, Set
13
+
14
+ from .spec import normalize_chain_address, normalize_chain_name
15
+
16
+
17
+ def _utc_day_key() -> str:
18
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d")
19
+
20
+
21
+ def _utc_now_iso() -> str:
22
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
23
+
24
+
25
+ def _trust_cache_key(chain: str, address: str) -> str:
26
+ norm_chain = normalize_chain_name(chain)
27
+ if norm_chain:
28
+ return f"{norm_chain}:{normalize_chain_address(norm_chain, address)}"
29
+ return f"{str(chain).strip().lower()}:{str(address).strip()}"
30
+
31
+
32
+ class SqliteSpendLedger:
33
+ """Thread-safe and multi-process-safe SQLite WAL budget, mandate, and trust-cache ledger."""
34
+
35
+ def __init__(self, db_path: str = ":memory:") -> None:
36
+ self.db_path = db_path
37
+ self._lock = threading.RLock()
38
+ if db_path != ":memory:":
39
+ parent = os.path.dirname(os.path.abspath(db_path))
40
+ if parent:
41
+ os.makedirs(parent, exist_ok=True)
42
+ # isolation_level=None gives explicit BEGIN IMMEDIATE transaction control
43
+ self._conn = sqlite3.connect(db_path, timeout=5.0, isolation_level=None, check_same_thread=False)
44
+ self._conn.row_factory = sqlite3.Row
45
+ self._init_schema()
46
+
47
+ def _init_schema(self) -> None:
48
+ with self._lock:
49
+ cur = self._conn.cursor()
50
+ cur.executescript(
51
+ """
52
+ PRAGMA journal_mode = WAL;
53
+ PRAGMA synchronous = NORMAL;
54
+ PRAGMA busy_timeout = 5000;
55
+
56
+ CREATE TABLE IF NOT EXISTS daily_spend (
57
+ day TEXT PRIMARY KEY,
58
+ spent_usdc REAL NOT NULL DEFAULT 0,
59
+ tx_count INTEGER NOT NULL DEFAULT 0,
60
+ updated_at TEXT NOT NULL
61
+ );
62
+ CREATE TABLE IF NOT EXISTS pending_reservations (
63
+ reservation_id TEXT PRIMARY KEY,
64
+ day TEXT NOT NULL,
65
+ amount_usdc REAL NOT NULL,
66
+ created_at_ms INTEGER NOT NULL
67
+ );
68
+ CREATE TABLE IF NOT EXISTS recent_payments (
69
+ fingerprint TEXT PRIMARY KEY,
70
+ last_paid_at_ms INTEGER NOT NULL,
71
+ count INTEGER NOT NULL DEFAULT 1
72
+ );
73
+ CREATE TABLE IF NOT EXISTS endpoint_health (
74
+ endpoint_key TEXT PRIMARY KEY,
75
+ consecutive_failures INTEGER NOT NULL DEFAULT 0,
76
+ last_failure_at_ms INTEGER,
77
+ last_status INTEGER,
78
+ circuit_open_until_ms INTEGER NOT NULL DEFAULT 0
79
+ );
80
+ CREATE TABLE IF NOT EXISTS mandate_spend (
81
+ mandate_id TEXT PRIMARY KEY,
82
+ spent_usd REAL NOT NULL DEFAULT 0,
83
+ tx_count INTEGER NOT NULL DEFAULT 0,
84
+ updated_at TEXT NOT NULL
85
+ );
86
+ CREATE TABLE IF NOT EXISTS revoked_mandates (
87
+ mandate_id TEXT PRIMARY KEY,
88
+ reason TEXT,
89
+ revoked_at TEXT NOT NULL
90
+ );
91
+ CREATE TABLE IF NOT EXISTS trust_cache (
92
+ cache_key TEXT PRIMARY KEY,
93
+ profile_json TEXT NOT NULL,
94
+ expires_at_ms INTEGER NOT NULL,
95
+ updated_at_ms INTEGER NOT NULL
96
+ );
97
+ """
98
+ )
99
+
100
+ def _run_immediate(self, fn):
101
+ with self._lock:
102
+ self._conn.execute("BEGIN IMMEDIATE")
103
+ try:
104
+ res = fn(self._conn)
105
+ self._conn.execute("COMMIT")
106
+ return res
107
+ except Exception:
108
+ try:
109
+ self._conn.execute("ROLLBACK")
110
+ except Exception:
111
+ pass
112
+ raise
113
+
114
+ def get_spent_today_usdc(self) -> float:
115
+ with self._lock:
116
+ row = self._conn.execute(
117
+ "SELECT spent_usdc FROM daily_spend WHERE day = ?", (_utc_day_key(),)
118
+ ).fetchone()
119
+ return round(float(row["spent_usdc"]) if row else 0.0, 6)
120
+
121
+ def get_effective_spent_today_usdc(self) -> float:
122
+ now_ms = int(time.time() * 1000)
123
+ day = _utc_day_key()
124
+ with self._lock:
125
+ self._conn.execute("DELETE FROM pending_reservations WHERE created_at_ms < ?", (now_ms - 120000,))
126
+ s = self._conn.execute("SELECT spent_usdc FROM daily_spend WHERE day = ?", (day,)).fetchone()
127
+ r = self._conn.execute(
128
+ "SELECT COALESCE(SUM(amount_usdc), 0) AS total FROM pending_reservations WHERE day = ?",
129
+ (day,),
130
+ ).fetchone()
131
+ return round((float(s["spent_usdc"]) if s else 0.0) + float(r["total"]), 6)
132
+
133
+ def reserve_budget(self, amount_usdc: float, max_daily_usdc: float) -> Dict[str, Any]:
134
+ amt = float(amount_usdc)
135
+ cap = float(max_daily_usdc)
136
+ if amt <= 0:
137
+ return {"ok": False, "reservationId": None, "effectiveSpentUsdc": self.get_effective_spent_today_usdc()}
138
+ day = _utc_day_key()
139
+ now_ms = int(time.time() * 1000)
140
+
141
+ def _tx(conn: sqlite3.Connection) -> Dict[str, Any]:
142
+ conn.execute("DELETE FROM pending_reservations WHERE created_at_ms < ?", (now_ms - 120000,))
143
+ s = conn.execute("SELECT spent_usdc FROM daily_spend WHERE day = ?", (day,)).fetchone()
144
+ r = conn.execute(
145
+ "SELECT COALESCE(SUM(amount_usdc), 0) AS total FROM pending_reservations WHERE day = ?",
146
+ (day,),
147
+ ).fetchone()
148
+ effective = round((float(s["spent_usdc"]) if s else 0.0) + float(r["total"]), 6)
149
+ if effective + amt > cap + 1e-9:
150
+ return {"ok": False, "reservationId": None, "effectiveSpentUsdc": effective}
151
+ res_id = f"pyres_{secrets.token_hex(6)}_{now_ms}"
152
+ conn.execute(
153
+ "INSERT INTO pending_reservations (reservation_id, day, amount_usdc, created_at_ms) VALUES (?, ?, ?, ?)",
154
+ (res_id, day, round(amt, 6), now_ms),
155
+ )
156
+ return {"ok": True, "reservationId": res_id, "effectiveSpentUsdc": round(effective + amt, 6)}
157
+
158
+ return self._run_immediate(_tx)
159
+
160
+ def commit_reservation(self, reservation_id: str) -> float:
161
+ now_iso = _utc_now_iso()
162
+ day = _utc_day_key()
163
+
164
+ def _tx(conn: sqlite3.Connection) -> float:
165
+ rec = conn.execute(
166
+ "SELECT day, amount_usdc FROM pending_reservations WHERE reservation_id = ?",
167
+ (reservation_id,),
168
+ ).fetchone()
169
+ if not rec:
170
+ s = conn.execute("SELECT spent_usdc FROM daily_spend WHERE day = ?", (day,)).fetchone()
171
+ return round(float(s["spent_usdc"]) if s else 0.0, 6)
172
+ conn.execute("DELETE FROM pending_reservations WHERE reservation_id = ?", (reservation_id,))
173
+ conn.execute(
174
+ """
175
+ INSERT INTO daily_spend (day, spent_usdc, tx_count, updated_at)
176
+ VALUES (?, ?, 1, ?)
177
+ ON CONFLICT (day) DO UPDATE SET
178
+ spent_usdc = ROUND(daily_spend.spent_usdc + excluded.spent_usdc, 6),
179
+ tx_count = daily_spend.tx_count + 1,
180
+ updated_at = excluded.updated_at
181
+ """,
182
+ (rec["day"], round(float(rec["amount_usdc"]), 6), now_iso),
183
+ )
184
+ s = conn.execute("SELECT spent_usdc FROM daily_spend WHERE day = ?", (rec["day"],)).fetchone()
185
+ return round(float(s["spent_usdc"]) if s else 0.0, 6)
186
+
187
+ return self._run_immediate(_tx)
188
+
189
+ def release_reservation(self, reservation_id: Optional[str]) -> bool:
190
+ if not reservation_id:
191
+ return False
192
+ with self._lock:
193
+ cur = self._conn.execute(
194
+ "DELETE FROM pending_reservations WHERE reservation_id = ?", (reservation_id,)
195
+ )
196
+ return cur.rowcount > 0
197
+
198
+ def check_idempotency(self, fingerprint: str, window_ms: int = 60000) -> Dict[str, Any]:
199
+ if not fingerprint or window_ms <= 0:
200
+ return {"isDuplicate": False, "secondsSinceLast": None}
201
+ now_ms = int(time.time() * 1000)
202
+ with self._lock:
203
+ self._conn.execute(
204
+ "DELETE FROM recent_payments WHERE last_paid_at_ms < ?",
205
+ (now_ms - max(window_ms * 2, 300000),),
206
+ )
207
+ row = self._conn.execute(
208
+ "SELECT last_paid_at_ms FROM recent_payments WHERE fingerprint = ?", (fingerprint,)
209
+ ).fetchone()
210
+ if not row:
211
+ return {"isDuplicate": False, "secondsSinceLast": None}
212
+ elapsed = now_ms - int(row["last_paid_at_ms"])
213
+ if 0 <= elapsed < window_ms:
214
+ return {"isDuplicate": True, "secondsSinceLast": round(elapsed / 1000.0, 2)}
215
+ return {"isDuplicate": False, "secondsSinceLast": None}
216
+
217
+ def record_payment_fingerprint(self, fingerprint: str) -> None:
218
+ if not fingerprint:
219
+ return
220
+ now_ms = int(time.time() * 1000)
221
+ with self._lock:
222
+ self._conn.execute(
223
+ """
224
+ INSERT INTO recent_payments (fingerprint, last_paid_at_ms, count)
225
+ VALUES (?, ?, 1)
226
+ ON CONFLICT (fingerprint) DO UPDATE SET
227
+ last_paid_at_ms = excluded.last_paid_at_ms,
228
+ count = recent_payments.count + 1
229
+ """,
230
+ (fingerprint, now_ms),
231
+ )
232
+
233
+ def check_circuit_breaker(self, endpoint_key: str) -> Dict[str, Any]:
234
+ now_ms = int(time.time() * 1000)
235
+ with self._lock:
236
+ row = self._conn.execute(
237
+ "SELECT * FROM endpoint_health WHERE endpoint_key = ?", (endpoint_key,)
238
+ ).fetchone()
239
+ if not row:
240
+ return {"open": False, "retryAfterSec": 0, "consecutiveFailures": 0, "lastStatus": None}
241
+ open_until = int(row["circuit_open_until_ms"] or 0)
242
+ if open_until > now_ms:
243
+ return {
244
+ "open": True,
245
+ "retryAfterSec": max(1, int((open_until - now_ms + 999) // 1000)),
246
+ "consecutiveFailures": int(row["consecutive_failures"]),
247
+ "lastStatus": row["last_status"],
248
+ }
249
+ return {"open": False, "retryAfterSec": 0, "consecutiveFailures": int(row["consecutive_failures"]), "lastStatus": row["last_status"]}
250
+
251
+ def record_endpoint_failure(
252
+ self, endpoint_key: str, status: Optional[int] = None, max_consecutive_failures: int = 3, cooldown_ms: int = 600000
253
+ ) -> Dict[str, Any]:
254
+ now_ms = int(time.time() * 1000)
255
+
256
+ def _tx(conn: sqlite3.Connection) -> Dict[str, Any]:
257
+ row = conn.execute(
258
+ "SELECT consecutive_failures FROM endpoint_health WHERE endpoint_key = ?", (endpoint_key,)
259
+ ).fetchone()
260
+ fails = (int(row["consecutive_failures"]) if row else 0) + 1
261
+ opened = fails >= max(1, int(max_consecutive_failures))
262
+ open_until = now_ms + max(1000, int(cooldown_ms)) if opened else 0
263
+ conn.execute(
264
+ """
265
+ INSERT OR REPLACE INTO endpoint_health (
266
+ endpoint_key, consecutive_failures, last_failure_at_ms, last_status, circuit_open_until_ms
267
+ ) VALUES (?, ?, ?, ?, ?)
268
+ """,
269
+ (endpoint_key, fails, now_ms, status, open_until),
270
+ )
271
+ return {
272
+ "opened": opened,
273
+ "consecutiveFailures": fails,
274
+ "retryAfterSec": int((open_until - now_ms + 999) // 1000) if opened else 0,
275
+ }
276
+
277
+ return self._run_immediate(_tx)
278
+
279
+ def record_endpoint_success(self, endpoint_key: str) -> None:
280
+ with self._lock:
281
+ self._conn.execute("DELETE FROM endpoint_health WHERE endpoint_key = ?", (endpoint_key,))
282
+
283
+ def get_mandate_spent_usd(self, mandate_id: str) -> float:
284
+ with self._lock:
285
+ row = self._conn.execute(
286
+ "SELECT spent_usd FROM mandate_spend WHERE mandate_id = ?", (mandate_id,)
287
+ ).fetchone()
288
+ return round(float(row["spent_usd"]) if row else 0.0, 6)
289
+
290
+ def record_mandate_spend(self, mandate_id: str, amount_usd: float) -> float:
291
+ if not mandate_id or float(amount_usd) <= 0:
292
+ return self.get_mandate_spent_usd(mandate_id)
293
+ now_iso = _utc_now_iso()
294
+
295
+ def _tx(conn: sqlite3.Connection) -> float:
296
+ conn.execute(
297
+ """
298
+ INSERT INTO mandate_spend (mandate_id, spent_usd, tx_count, updated_at)
299
+ VALUES (?, ?, 1, ?)
300
+ ON CONFLICT (mandate_id) DO UPDATE SET
301
+ spent_usd = ROUND(mandate_spend.spent_usd + excluded.spent_usd, 6),
302
+ tx_count = mandate_spend.tx_count + 1,
303
+ updated_at = excluded.updated_at
304
+ """,
305
+ (mandate_id, round(float(amount_usd), 6), now_iso),
306
+ )
307
+ row = conn.execute(
308
+ "SELECT spent_usd FROM mandate_spend WHERE mandate_id = ?", (mandate_id,)
309
+ ).fetchone()
310
+ return round(float(row["spent_usd"]) if row else 0.0, 6)
311
+
312
+ return self._run_immediate(_tx)
313
+
314
+ def revoke_mandate(self, mandate_id: str, reason: str = "REVOKED") -> None:
315
+ if not mandate_id:
316
+ return
317
+ with self._lock:
318
+ self._conn.execute(
319
+ "INSERT OR REPLACE INTO revoked_mandates (mandate_id, reason, revoked_at) VALUES (?, ?, ?)",
320
+ (mandate_id, reason, _utc_now_iso()),
321
+ )
322
+
323
+ def get_revoked_mandate_ids(self) -> Set[str]:
324
+ with self._lock:
325
+ rows = self._conn.execute("SELECT mandate_id FROM revoked_mandates").fetchall()
326
+ return {str(r["mandate_id"]) for r in rows}
327
+
328
+ def get_cached_trust(self, chain: str, address: str) -> Optional[Dict[str, Any]]:
329
+ key = _trust_cache_key(chain, address)
330
+ now_ms = int(time.time() * 1000)
331
+ with self._lock:
332
+ row = self._conn.execute(
333
+ "SELECT profile_json, expires_at_ms FROM trust_cache WHERE cache_key = ?", (key,)
334
+ ).fetchone()
335
+ if not row:
336
+ return None
337
+ if int(row["expires_at_ms"]) <= now_ms:
338
+ self._conn.execute("DELETE FROM trust_cache WHERE cache_key = ?", (key,))
339
+ return None
340
+ return json.loads(row["profile_json"])
341
+
342
+ def set_cached_trust(self, chain: str, address: str, profile: Dict[str, Any], ttl_ms: int = 30000) -> None:
343
+ if ttl_ms <= 0:
344
+ return
345
+ key = _trust_cache_key(chain, address)
346
+ now_ms = int(time.time() * 1000)
347
+ with self._lock:
348
+ self._conn.execute(
349
+ "INSERT OR REPLACE INTO trust_cache (cache_key, profile_json, expires_at_ms, updated_at_ms) VALUES (?, ?, ?, ?)",
350
+ (key, json.dumps(profile), now_ms + int(ttl_ms), now_ms),
351
+ )
352
+
353
+ def close(self) -> None:
354
+ with self._lock:
355
+ self._conn.close()