"""A fake Supabase (http.server): PostgREST upserts and reads of the checkpoint, Storage list and upload, kept in memory.""" import json import threading import urllib.parse from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer KEYS = {"checkpoints": "name"} # the primary key of each table; uuid by default class FakeSupabase: def __init__(self): self.tables: dict[str, dict[str, dict]] = {"conversations": {}, "messages": {}, "checkpoints": {}} self.objects: dict[str, bytes] = {} self.requests: list[tuple[str, str, dict]] = [] # (method, path with query, headers with lower-case names) self.fail: dict[str, int | tuple[int, dict]] = {} # path prefix → error code, or (code, body) as Storage does fake = self class Handler(BaseHTTPRequestHandler): def _answer(self, code: int, body=None): text = json.dumps(body if body is not None else {}).encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(text))) self.end_headers() self.wfile.write(text) def _handle(self): n = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(n) if n else b"" fake.requests.append((self.command, self.path, {k.lower(): v for k, v in self.headers.items()})) url = urllib.parse.urlsplit(self.path) for prefix, failure in fake.fail.items(): if url.path.startswith(prefix): code, body = failure if isinstance(failure, tuple) else (failure, {"message": "failure"}) return self._answer(code, body) if url.path.startswith("/rest/v1/"): table = url.path.removeprefix("/rest/v1/") key = KEYS.get(table, "uuid") if self.command == "GET": q = urllib.parse.parse_qs(url.query) rows = list(fake.tables[table].values()) for col, vals in q.items(): if vals[0].startswith("eq."): rows = [r for r in rows if str(r.get(col)) == vals[0][3:]] return self._answer(200, rows) rows = json.loads(raw) if len({r[key] for r in rows}) < len(rows): # PostgREST: "cannot affect row a second time" return self._answer(500, {"code": "21000"}) for row in rows: fake.tables[table][row[key]] = fake.tables[table].get(row[key], {}) | row return self._answer(201) if url.path == "/storage/v1/object/list/attachments": prefix = json.loads(raw)["prefix"] return self._answer(200, [{"name": k[len(prefix):]} for k in fake.objects if k.startswith(prefix)]) if url.path.startswith("/storage/v1/object/attachments/"): fake.objects[urllib.parse.unquote(url.path.removeprefix("/storage/v1/object/attachments/"))] = raw return self._answer(200, {"Key": url.path}) return self._answer(404, {"message": "not found"}) do_GET = do_POST = do_PUT = do_DELETE = _handle def log_message(self, *_): pass self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) self.url = f"http://127.0.0.1:{self._server.server_address[1]}" threading.Thread(target=self._server.serve_forever, daemon=True).start() def stop(self): self._server.shutdown() self._server.server_close()