|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import contextlib |
| 4 | +import hashlib |
| 5 | +import json |
| 6 | +from collections import defaultdict |
| 7 | +from dataclasses import dataclass |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | +from mocket.compat import decode_from_bytes, encode_to_bytes |
| 11 | +from mocket.types import Address |
| 12 | +from mocket.utils import hexdump, hexload |
| 13 | + |
| 14 | +hash_function = hashlib.md5 |
| 15 | + |
| 16 | +with contextlib.suppress(ImportError): |
| 17 | + from xxhash_cffi import xxh32 as xxhash_cffi_xxh32 |
| 18 | + |
| 19 | + hash_function = xxhash_cffi_xxh32 |
| 20 | + |
| 21 | +with contextlib.suppress(ImportError): |
| 22 | + from xxhash import xxh32 as xxhash_xxh32 |
| 23 | + |
| 24 | + hash_function = xxhash_xxh32 |
| 25 | + |
| 26 | + |
| 27 | +def _hash_prepare_request(data: bytes) -> bytes: |
| 28 | + _data = decode_from_bytes(data) |
| 29 | + return encode_to_bytes("".join(sorted(_data.split("\r\n")))) |
| 30 | + |
| 31 | + |
| 32 | +def _hash_request(data: bytes) -> str: |
| 33 | + _data = _hash_prepare_request(data) |
| 34 | + return hash_function(_data).hexdigest() |
| 35 | + |
| 36 | + |
| 37 | +def _hash_request_fallback(data: bytes) -> str: |
| 38 | + _data = _hash_prepare_request(data) |
| 39 | + return hashlib.md5(_data).hexdigest() |
| 40 | + |
| 41 | + |
| 42 | +@dataclass |
| 43 | +class MocketRecord: |
| 44 | + host: str |
| 45 | + port: int |
| 46 | + request: bytes |
| 47 | + response: bytes |
| 48 | + |
| 49 | + |
| 50 | +class MocketRecordStorage: |
| 51 | + def __init__(self, directory: Path, namespace: str) -> None: |
| 52 | + self._directory = directory |
| 53 | + self._namespace = namespace |
| 54 | + self._records: defaultdict[Address, defaultdict[str, MocketRecord]] = ( |
| 55 | + defaultdict(defaultdict) |
| 56 | + ) |
| 57 | + |
| 58 | + self._load() |
| 59 | + |
| 60 | + @property |
| 61 | + def directory(self) -> Path: |
| 62 | + return self._directory |
| 63 | + |
| 64 | + @property |
| 65 | + def namespace(self) -> str: |
| 66 | + return self._namespace |
| 67 | + |
| 68 | + @property |
| 69 | + def file(self) -> Path: |
| 70 | + return self._directory / f"{self._namespace}.json" |
| 71 | + |
| 72 | + def _load(self) -> None: |
| 73 | + if not self.file.exists(): |
| 74 | + return |
| 75 | + |
| 76 | + json_data = self.file.read_text() |
| 77 | + records = json.loads(json_data) |
| 78 | + for host, port_signature_record in records.items(): |
| 79 | + for port, signature_record in port_signature_record.items(): |
| 80 | + for signature, record in signature_record.items(): |
| 81 | + # NOTE backward-compat |
| 82 | + try: |
| 83 | + request_data = hexload(record["request"]) |
| 84 | + except ValueError: |
| 85 | + request_data = record["request"] |
| 86 | + |
| 87 | + self._records[(host, int(port))][signature] = MocketRecord( |
| 88 | + host=host, |
| 89 | + port=port, |
| 90 | + request=request_data, |
| 91 | + response=hexload(record["response"]), |
| 92 | + ) |
| 93 | + |
| 94 | + def _save(self) -> None: |
| 95 | + data: dict[str, dict[str, dict[str, dict[str, str]]]] = defaultdict( |
| 96 | + lambda: defaultdict(defaultdict) |
| 97 | + ) |
| 98 | + for address, signature_record in self._records.items(): |
| 99 | + host, port = address |
| 100 | + for signature, record in signature_record.items(): |
| 101 | + data[host][str(port)][signature] = dict( |
| 102 | + request=decode_from_bytes(record.request), |
| 103 | + response=hexdump(record.response), |
| 104 | + ) |
| 105 | + |
| 106 | + json_data = json.dumps(data, indent=4, sort_keys=True) |
| 107 | + self.file.parent.mkdir(exist_ok=True) |
| 108 | + self.file.write_text(json_data) |
| 109 | + |
| 110 | + def get_records(self, address: Address) -> list[MocketRecord]: |
| 111 | + return list(self._records[address].values()) |
| 112 | + |
| 113 | + def get_record(self, address: Address, request: bytes) -> MocketRecord | None: |
| 114 | + # NOTE for backward-compat |
| 115 | + request_signature_fallback = _hash_request_fallback(request) |
| 116 | + if request_signature_fallback in self._records[address]: |
| 117 | + return self._records[address].get(request_signature_fallback) |
| 118 | + |
| 119 | + request_signature = _hash_request(request) |
| 120 | + if request_signature in self._records[address]: |
| 121 | + return self._records[address][request_signature] |
| 122 | + |
| 123 | + return None |
| 124 | + |
| 125 | + def put_record( |
| 126 | + self, |
| 127 | + address: Address, |
| 128 | + request: bytes, |
| 129 | + response: bytes, |
| 130 | + ) -> None: |
| 131 | + host, port = address |
| 132 | + record = MocketRecord( |
| 133 | + host=host, |
| 134 | + port=port, |
| 135 | + request=request, |
| 136 | + response=response, |
| 137 | + ) |
| 138 | + |
| 139 | + # NOTE for backward-compat |
| 140 | + request_signature_fallback = _hash_request_fallback(request) |
| 141 | + if request_signature_fallback in self._records[address]: |
| 142 | + self._records[address][request_signature_fallback] = record |
| 143 | + return |
| 144 | + |
| 145 | + request_signature = _hash_request(request) |
| 146 | + self._records[address][request_signature] = record |
| 147 | + self._save() |
0 commit comments