|
| 1 | +# Copyright 2025, 2026 Query Farm LLC - https://query.farm |
| 2 | + |
| 3 | +"""In-memory stand-in for the Cloudflare DO storage service, as an httpx2 transport. |
| 4 | +
|
| 5 | +Implements the endpoints `FunctionStorageCfDo` calls with the service's |
| 6 | +wire shapes (base64 keys and values, ``{rows, next_after}`` pages), its |
| 7 | +1 MiB per-value cap (413 ``payload_too_large``) and its ``attempt_id`` |
| 8 | +replay for writes. One instance is one tenant; state is keyed by |
| 9 | +``shard_key`` so sharding bugs show up. Not a model of the DO's |
| 10 | +transactional details -- the live suite in |
| 11 | +``test_function_storage_cf_do_integration.py`` covers those. |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import base64 |
| 17 | +import json |
| 18 | +import threading |
| 19 | +from collections.abc import Callable |
| 20 | +from typing import Any |
| 21 | + |
| 22 | +import httpx2 |
| 23 | + |
| 24 | +MAX_VALUE_BYTES = 1024 * 1024 |
| 25 | + |
| 26 | + |
| 27 | +def _d(s: str) -> bytes: |
| 28 | + return base64.b64decode(s) |
| 29 | + |
| 30 | + |
| 31 | +def _e(b: bytes) -> str: |
| 32 | + return base64.b64encode(b).decode() |
| 33 | + |
| 34 | + |
| 35 | +class FakeCfDo: |
| 36 | + """The fake service: in-memory tables plus request log and fault hooks.""" |
| 37 | + |
| 38 | + def __init__(self, *, page_rows: int = 2) -> None: |
| 39 | + """Create an empty service whose scan/drain pages hold ``page_rows`` rows.""" |
| 40 | + self.page_rows = page_rows |
| 41 | + self.queues: dict[tuple[str, bytes], list[bytes]] = {} |
| 42 | + self.state: dict[tuple[str, bytes, bytes, bytes], bytes] = {} |
| 43 | + self.logs: dict[tuple[str, bytes, bytes, bytes], list[tuple[int, bytes]]] = {} |
| 44 | + self.requests: list[tuple[str, dict[str, Any]]] = [] |
| 45 | + self._replay: dict[str, dict[str, Any]] = {} |
| 46 | + self._drains: dict[str, list[tuple[bytes, bytes]]] = {} |
| 47 | + self._next_ordinal = 0 |
| 48 | + self._lock = threading.Lock() |
| 49 | + #: Called with ``(endpoint, body)`` before handling; may return a status to fail with. |
| 50 | + self.fault: Callable[[str, dict[str, Any]], int | None] | None = None |
| 51 | + |
| 52 | + def transport(self) -> httpx2.MockTransport: |
| 53 | + """Return an httpx2 transport serving this fake.""" |
| 54 | + return httpx2.MockTransport(self._handle) |
| 55 | + |
| 56 | + def endpoint_counts(self) -> dict[str, int]: |
| 57 | + """Return how many requests each endpoint received.""" |
| 58 | + counts: dict[str, int] = {} |
| 59 | + for endpoint, _ in self.requests: |
| 60 | + counts[endpoint] = counts.get(endpoint, 0) + 1 |
| 61 | + return counts |
| 62 | + |
| 63 | + def stored_values(self) -> list[bytes]: |
| 64 | + """Return every stored value as the DO holds it (envelopes).""" |
| 65 | + with self._lock: |
| 66 | + out = [v for q in self.queues.values() for v in q] |
| 67 | + out += list(self.state.values()) |
| 68 | + out += [v for log in self.logs.values() for _, v in log] |
| 69 | + return out |
| 70 | + |
| 71 | + def _handle(self, request: httpx2.Request) -> httpx2.Response: |
| 72 | + endpoint = request.url.path.lstrip("/") |
| 73 | + body: dict[str, Any] = json.loads(request.content) |
| 74 | + self.requests.append((endpoint, body)) |
| 75 | + if self.fault is not None: |
| 76 | + status = self.fault(endpoint, body) |
| 77 | + if status is not None: |
| 78 | + return httpx2.Response(status, json={"error": "injected"}) |
| 79 | + with self._lock: |
| 80 | + try: |
| 81 | + return httpx2.Response(200, json=self._dispatch(endpoint, body)) |
| 82 | + except _TooLarge as exc: |
| 83 | + return httpx2.Response(413, json={"error": "payload_too_large", "message": str(exc)}) |
| 84 | + |
| 85 | + def _dispatch(self, endpoint: str, body: dict[str, Any]) -> dict[str, Any]: |
| 86 | + attempt = body.get("attempt_id") |
| 87 | + replay_key = f"{endpoint}:{attempt}" if attempt and endpoint not in ("state_drain",) else None |
| 88 | + if replay_key is not None and replay_key in self._replay: |
| 89 | + return self._replay[replay_key] |
| 90 | + result: dict[str, Any] = getattr(self, f"_op_{endpoint}")(body["shard_key"], body) |
| 91 | + if replay_key is not None: |
| 92 | + self._replay[replay_key] = result |
| 93 | + return result |
| 94 | + |
| 95 | + @staticmethod |
| 96 | + def _check(value: bytes, what: str) -> bytes: |
| 97 | + if len(value) > MAX_VALUE_BYTES: |
| 98 | + raise _TooLarge(f"{what} exceeds {MAX_VALUE_BYTES} bytes (got {len(value)})") |
| 99 | + return value |
| 100 | + |
| 101 | + # --- queue --- |
| 102 | + |
| 103 | + def _op_queue_push(self, shard: str, body: dict[str, Any]) -> dict[str, Any]: |
| 104 | + items = [self._check(_d(i), "work item") for i in body["items"]] |
| 105 | + self.queues.setdefault((shard, _d(body["execution_id"])), []).extend(items) |
| 106 | + return {"count": len(items)} |
| 107 | + |
| 108 | + def _op_queue_pop(self, shard: str, body: dict[str, Any]) -> dict[str, Any]: |
| 109 | + q = self.queues.get((shard, _d(body["execution_id"])), []) |
| 110 | + return {"item": _e(q.pop(0)) if q else None} |
| 111 | + |
| 112 | + def _op_queue_clear(self, shard: str, body: dict[str, Any]) -> dict[str, Any]: |
| 113 | + q = self.queues.pop((shard, _d(body["execution_id"])), []) |
| 114 | + return {"cleared": len(q)} |
| 115 | + |
| 116 | + # --- state --- |
| 117 | + |
| 118 | + def _ns_rows(self, shard: str, scope: bytes, ns: bytes) -> list[tuple[bytes, bytes]]: |
| 119 | + return sorted((k[3], v) for k, v in self.state.items() if k[:3] == (shard, scope, ns)) |
| 120 | + |
| 121 | + def _op_state_get_many(self, shard: str, body: dict[str, Any]) -> dict[str, Any]: |
| 122 | + scope, ns = _d(body["scope_id"]), _d(body["ns"]) |
| 123 | + rows = [] |
| 124 | + for k in body["keys"]: |
| 125 | + v = self.state.get((shard, scope, ns, _d(k))) |
| 126 | + rows.append(None if v is None else {"value": _e(v)}) |
| 127 | + return {"rows": rows} |
| 128 | + |
| 129 | + def _op_state_put_many(self, shard: str, body: dict[str, Any]) -> dict[str, Any]: |
| 130 | + scope, ns = _d(body["scope_id"]), _d(body["ns"]) |
| 131 | + for item in body["items"]: |
| 132 | + self.state[(shard, scope, ns, _d(item["key"]))] = self._check(_d(item["value"]), "value") |
| 133 | + return {} |
| 134 | + |
| 135 | + def _page(self, rows: list[tuple[bytes, bytes]], after: str | None) -> dict[str, Any]: |
| 136 | + start = 0 |
| 137 | + if after is not None: |
| 138 | + start = next((i + 1 for i, (k, _) in enumerate(rows) if _e(k) == after), len(rows)) |
| 139 | + page = rows[start : start + self.page_rows] |
| 140 | + more = start + self.page_rows < len(rows) |
| 141 | + return { |
| 142 | + "rows": [{"key": _e(k), "value": _e(v)} for k, v in page], |
| 143 | + "next_after": _e(page[-1][0]) if more and page else None, |
| 144 | + } |
| 145 | + |
| 146 | + def _op_state_scan(self, shard: str, body: dict[str, Any]) -> dict[str, Any]: |
| 147 | + rows = self._ns_rows(shard, _d(body["scope_id"]), _d(body["ns"])) |
| 148 | + return self._page(rows, body.get("after_key")) |
| 149 | + |
| 150 | + def _op_state_drain(self, shard: str, body: dict[str, Any]) -> dict[str, Any]: |
| 151 | + scope, ns = _d(body["scope_id"]), _d(body["ns"]) |
| 152 | + attempt = body["attempt_id"] |
| 153 | + if body.get("after_key") is None and attempt not in self._drains: |
| 154 | + self._drains[attempt] = self._ns_rows(shard, scope, ns) |
| 155 | + for k in [k for k in self.state if k[:3] == (shard, scope, ns)]: |
| 156 | + del self.state[k] |
| 157 | + return self._page(self._drains[attempt], body.get("after_key")) |
| 158 | + |
| 159 | + def _op_state_delete(self, shard: str, body: dict[str, Any]) -> dict[str, Any]: |
| 160 | + scope, ns = _d(body["scope_id"]), _d(body["ns"]) |
| 161 | + keys = [k for k in self.state if k[:3] == (shard, scope, ns)] |
| 162 | + if "keys" in body: |
| 163 | + wanted = {_d(k) for k in body["keys"]} |
| 164 | + keys = [k for k in keys if k[3] in wanted] |
| 165 | + for k in keys: |
| 166 | + del self.state[k] |
| 167 | + return {"deleted": len(keys)} |
| 168 | + |
| 169 | + def _op_execution_clear(self, shard: str, body: dict[str, Any]) -> dict[str, Any]: |
| 170 | + scope = _d(body["scope_id"]) |
| 171 | + keys = [k for k in self.state if k[:2] == (shard, scope)] |
| 172 | + logs = [k for k in self.logs if k[:2] == (shard, scope)] |
| 173 | + for k in keys: |
| 174 | + del self.state[k] |
| 175 | + for k in logs: |
| 176 | + del self.logs[k] |
| 177 | + return {"deleted": len(keys) + len(logs)} |
| 178 | + |
| 179 | + def _op_state_append(self, shard: str, body: dict[str, Any]) -> dict[str, Any]: |
| 180 | + key = (shard, _d(body["scope_id"]), _d(body["ns"]), _d(body["key"])) |
| 181 | + item = self._check(_d(body["item"]), "log item") |
| 182 | + self._next_ordinal += 1 |
| 183 | + self.logs.setdefault(key, []).append((self._next_ordinal, item)) |
| 184 | + return {"ordinal": self._next_ordinal} |
| 185 | + |
| 186 | + def _op_state_log_scan(self, shard: str, body: dict[str, Any]) -> dict[str, Any]: |
| 187 | + key = (shard, _d(body["scope_id"]), _d(body["ns"]), _d(body["key"])) |
| 188 | + rows = [(i, v) for i, v in self.logs.get(key, []) if i > body["after_id"]] |
| 189 | + if body.get("limit") is not None: |
| 190 | + rows = rows[: body["limit"]] |
| 191 | + return {"rows": [{"id": i, "value": _e(v)} for i, v in rows]} |
| 192 | + |
| 193 | + |
| 194 | +class _TooLarge(Exception): |
| 195 | + pass |
0 commit comments