|
| 1 | +"""Helpers to record curl_cffi transfer metrics in Scrapy stats.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from curl_cffi import requests as curl_requests |
| 6 | +from curl_cffi.const import CurlInfo |
| 7 | + |
| 8 | + |
| 9 | +class TrackedCurlSession: |
| 10 | + """Wrapper around curl_cffi Session that auto-records transfer bytes.""" |
| 11 | + |
| 12 | + def __init__( |
| 13 | + self, |
| 14 | + *, |
| 15 | + stats, |
| 16 | + session=None, |
| 17 | + add_to_downloader_response_bytes=True, |
| 18 | + dedupe_on_response=True, |
| 19 | + ): |
| 20 | + self.stats = stats |
| 21 | + self.add_to_downloader_response_bytes = add_to_downloader_response_bytes |
| 22 | + self.dedupe_on_response = dedupe_on_response |
| 23 | + self._session = session if session is not None else self._build_default_session() |
| 24 | + |
| 25 | + @staticmethod |
| 26 | + def _build_default_session(): |
| 27 | + return curl_requests.Session() |
| 28 | + |
| 29 | + def _track(self, response): |
| 30 | + record_curl_transfer_bytes( |
| 31 | + self.stats, |
| 32 | + response, |
| 33 | + add_to_downloader_response_bytes=self.add_to_downloader_response_bytes, |
| 34 | + dedupe_on_response=self.dedupe_on_response, |
| 35 | + ) |
| 36 | + return response |
| 37 | + |
| 38 | + def request(self, method, url, *args, **kwargs): |
| 39 | + response = self._session.request(method, url, *args, **kwargs) |
| 40 | + return self._track(response) |
| 41 | + |
| 42 | + def get(self, url, *args, **kwargs): |
| 43 | + return self.request("GET", url, *args, **kwargs) |
| 44 | + |
| 45 | + def post(self, url, *args, **kwargs): |
| 46 | + return self.request("POST", url, *args, **kwargs) |
| 47 | + |
| 48 | + def put(self, url, *args, **kwargs): |
| 49 | + return self.request("PUT", url, *args, **kwargs) |
| 50 | + |
| 51 | + def patch(self, url, *args, **kwargs): |
| 52 | + return self.request("PATCH", url, *args, **kwargs) |
| 53 | + |
| 54 | + def delete(self, url, *args, **kwargs): |
| 55 | + return self.request("DELETE", url, *args, **kwargs) |
| 56 | + |
| 57 | + def head(self, url, *args, **kwargs): |
| 58 | + return self.request("HEAD", url, *args, **kwargs) |
| 59 | + |
| 60 | + def options(self, url, *args, **kwargs): |
| 61 | + return self.request("OPTIONS", url, *args, **kwargs) |
| 62 | + |
| 63 | + def close(self): |
| 64 | + close_fn = getattr(self._session, "close", None) |
| 65 | + if callable(close_fn): |
| 66 | + close_fn() |
| 67 | + |
| 68 | + def __enter__(self): |
| 69 | + return self |
| 70 | + |
| 71 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 72 | + self.close() |
| 73 | + return False |
| 74 | + |
| 75 | + def __getattr__(self, item): |
| 76 | + return getattr(self._session, item) |
| 77 | + |
| 78 | + |
| 79 | +def _safe_int(value): |
| 80 | + try: |
| 81 | + return int(value or 0) |
| 82 | + except Exception: |
| 83 | + return 0 |
| 84 | + |
| 85 | + |
| 86 | +def _extract_transfer_sizes(curl_response): |
| 87 | + """Return tuple: (down_bytes, up_bytes).""" |
| 88 | + download_size = 0 |
| 89 | + upload_size = 0 |
| 90 | + header_size = 0 |
| 91 | + request_size = 0 |
| 92 | + |
| 93 | + curl_handle = getattr(curl_response, "curl", None) |
| 94 | + if curl_handle is not None: |
| 95 | + try: |
| 96 | + download_size = _safe_int(curl_handle.getinfo(CurlInfo.SIZE_DOWNLOAD_T)) |
| 97 | + upload_size = _safe_int(curl_handle.getinfo(CurlInfo.SIZE_UPLOAD_T)) |
| 98 | + header_size = _safe_int(curl_handle.getinfo(CurlInfo.HEADER_SIZE)) |
| 99 | + request_size = _safe_int(curl_handle.getinfo(CurlInfo.REQUEST_SIZE)) |
| 100 | + except Exception: |
| 101 | + download_size = 0 |
| 102 | + upload_size = 0 |
| 103 | + header_size = 0 |
| 104 | + request_size = 0 |
| 105 | + |
| 106 | + if (download_size + header_size) == 0: |
| 107 | + download_size = len(getattr(curl_response, "content", b"") or b"") |
| 108 | + |
| 109 | + down_bytes = download_size + header_size |
| 110 | + up_bytes = request_size + upload_size |
| 111 | + return down_bytes, up_bytes |
| 112 | + |
| 113 | + |
| 114 | +def record_curl_transfer_bytes( |
| 115 | + stats, |
| 116 | + curl_response, |
| 117 | + *, |
| 118 | + add_to_downloader_response_bytes=True, |
| 119 | + dedupe_on_response=True, |
| 120 | +): |
| 121 | + """Record curl_cffi transfer metrics in Scrapy stats. |
| 122 | +
|
| 123 | + Args: |
| 124 | + stats: Scrapy stats collector. |
| 125 | + curl_response: response object returned by curl_cffi. |
| 126 | + add_to_downloader_response_bytes: if True, increment |
| 127 | + ``downloader/response_bytes`` with downloaded bytes. |
| 128 | + dedupe_on_response: if True, skip if metrics were already recorded for |
| 129 | + this response instance. |
| 130 | + """ |
| 131 | + if stats is None or curl_response is None: |
| 132 | + return {"down_bytes": 0, "up_bytes": 0, "total_bytes": 0} |
| 133 | + |
| 134 | + if dedupe_on_response and getattr(curl_response, "_ps_helper_curl_metrics_recorded", False): |
| 135 | + return {"down_bytes": 0, "up_bytes": 0, "total_bytes": 0} |
| 136 | + |
| 137 | + down_bytes, up_bytes = _extract_transfer_sizes(curl_response) |
| 138 | + total_bytes = down_bytes + up_bytes |
| 139 | + |
| 140 | + stats.inc_value("curl_cffi/bytes_down", down_bytes) |
| 141 | + stats.inc_value("curl_cffi/bytes_up", up_bytes) |
| 142 | + stats.inc_value("curl_cffi/bytes_total", total_bytes) |
| 143 | + stats.inc_value("curl_cffi/response_count", 1) |
| 144 | + |
| 145 | + if add_to_downloader_response_bytes: |
| 146 | + stats.inc_value("downloader/response_bytes", down_bytes) |
| 147 | + |
| 148 | + if dedupe_on_response: |
| 149 | + try: |
| 150 | + setattr(curl_response, "_ps_helper_curl_metrics_recorded", True) |
| 151 | + except Exception: |
| 152 | + pass |
| 153 | + |
| 154 | + return { |
| 155 | + "down_bytes": down_bytes, |
| 156 | + "up_bytes": up_bytes, |
| 157 | + "total_bytes": total_bytes, |
| 158 | + } |
0 commit comments