_http.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. # coding=utf-8
  2. # Copyright 2022-present, the HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Contains utilities to handle HTTP requests in Huggingface Hub."""
  16. import io
  17. import os
  18. import re
  19. import threading
  20. import time
  21. import uuid
  22. from functools import lru_cache
  23. from shlex import quote
  24. from typing import Any, Callable, List, Optional, Tuple, Type, Union
  25. import requests
  26. from requests import HTTPError, Response
  27. from requests.adapters import HTTPAdapter
  28. from requests.models import PreparedRequest
  29. from huggingface_hub.errors import OfflineModeIsEnabled
  30. from .. import constants
  31. from ..errors import (
  32. BadRequestError,
  33. DisabledRepoError,
  34. EntryNotFoundError,
  35. GatedRepoError,
  36. HfHubHTTPError,
  37. RepositoryNotFoundError,
  38. RevisionNotFoundError,
  39. )
  40. from . import logging
  41. from ._fixes import JSONDecodeError
  42. from ._lfs import SliceFileObj
  43. from ._typing import HTTP_METHOD_T
  44. logger = logging.get_logger(__name__)
  45. # Both headers are used by the Hub to debug failed requests.
  46. # `X_AMZN_TRACE_ID` is better as it also works to debug on Cloudfront and ALB.
  47. # If `X_AMZN_TRACE_ID` is set, the Hub will use it as well.
  48. X_AMZN_TRACE_ID = "X-Amzn-Trace-Id"
  49. X_REQUEST_ID = "x-request-id"
  50. REPO_API_REGEX = re.compile(
  51. r"""
  52. # staging or production endpoint
  53. ^https://[^/]+
  54. (
  55. # on /api/repo_type/repo_id
  56. /api/(models|datasets|spaces)/(.+)
  57. |
  58. # or /repo_id/resolve/revision/...
  59. /(.+)/resolve/(.+)
  60. )
  61. """,
  62. flags=re.VERBOSE,
  63. )
  64. class UniqueRequestIdAdapter(HTTPAdapter):
  65. X_AMZN_TRACE_ID = "X-Amzn-Trace-Id"
  66. def add_headers(self, request, **kwargs):
  67. super().add_headers(request, **kwargs)
  68. # Add random request ID => easier for server-side debug
  69. if X_AMZN_TRACE_ID not in request.headers:
  70. request.headers[X_AMZN_TRACE_ID] = request.headers.get(X_REQUEST_ID) or str(uuid.uuid4())
  71. # Add debug log
  72. has_token = len(str(request.headers.get("authorization", ""))) > 0
  73. logger.debug(
  74. f"Request {request.headers[X_AMZN_TRACE_ID]}: {request.method} {request.url} (authenticated: {has_token})"
  75. )
  76. def send(self, request: PreparedRequest, *args, **kwargs) -> Response:
  77. """Catch any RequestException to append request id to the error message for debugging."""
  78. if constants.HF_DEBUG:
  79. logger.debug(f"Send: {_curlify(request)}")
  80. try:
  81. return super().send(request, *args, **kwargs)
  82. except requests.RequestException as e:
  83. request_id = request.headers.get(X_AMZN_TRACE_ID)
  84. if request_id is not None:
  85. # Taken from https://stackoverflow.com/a/58270258
  86. e.args = (*e.args, f"(Request ID: {request_id})")
  87. raise
  88. class OfflineAdapter(HTTPAdapter):
  89. def send(self, request: PreparedRequest, *args, **kwargs) -> Response:
  90. raise OfflineModeIsEnabled(
  91. f"Cannot reach {request.url}: offline mode is enabled. To disable it, please unset the `HF_HUB_OFFLINE` environment variable."
  92. )
  93. def _default_backend_factory() -> requests.Session:
  94. session = requests.Session()
  95. if constants.HF_HUB_OFFLINE:
  96. session.mount("http://", OfflineAdapter())
  97. session.mount("https://", OfflineAdapter())
  98. else:
  99. session.mount("http://", UniqueRequestIdAdapter())
  100. session.mount("https://", UniqueRequestIdAdapter())
  101. return session
  102. BACKEND_FACTORY_T = Callable[[], requests.Session]
  103. _GLOBAL_BACKEND_FACTORY: BACKEND_FACTORY_T = _default_backend_factory
  104. def configure_http_backend(backend_factory: BACKEND_FACTORY_T = _default_backend_factory) -> None:
  105. """
  106. Configure the HTTP backend by providing a `backend_factory`. Any HTTP calls made by `huggingface_hub` will use a
  107. Session object instantiated by this factory. This can be useful if you are running your scripts in a specific
  108. environment requiring custom configuration (e.g. custom proxy or certifications).
  109. Use [`get_session`] to get a configured Session. Since `requests.Session` is not guaranteed to be thread-safe,
  110. `huggingface_hub` creates 1 Session instance per thread. They are all instantiated using the same `backend_factory`
  111. set in [`configure_http_backend`]. A LRU cache is used to cache the created sessions (and connections) between
  112. calls. Max size is 128 to avoid memory leaks if thousands of threads are spawned.
  113. See [this issue](https://github.com/psf/requests/issues/2766) to know more about thread-safety in `requests`.
  114. Example:
  115. ```py
  116. import requests
  117. from huggingface_hub import configure_http_backend, get_session
  118. # Create a factory function that returns a Session with configured proxies
  119. def backend_factory() -> requests.Session:
  120. session = requests.Session()
  121. session.proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"}
  122. return session
  123. # Set it as the default session factory
  124. configure_http_backend(backend_factory=backend_factory)
  125. # In practice, this is mostly done internally in `huggingface_hub`
  126. session = get_session()
  127. ```
  128. """
  129. global _GLOBAL_BACKEND_FACTORY
  130. _GLOBAL_BACKEND_FACTORY = backend_factory
  131. reset_sessions()
  132. def get_session() -> requests.Session:
  133. """
  134. Get a `requests.Session` object, using the session factory from the user.
  135. Use [`get_session`] to get a configured Session. Since `requests.Session` is not guaranteed to be thread-safe,
  136. `huggingface_hub` creates 1 Session instance per thread. They are all instantiated using the same `backend_factory`
  137. set in [`configure_http_backend`]. A LRU cache is used to cache the created sessions (and connections) between
  138. calls. Max size is 128 to avoid memory leaks if thousands of threads are spawned.
  139. See [this issue](https://github.com/psf/requests/issues/2766) to know more about thread-safety in `requests`.
  140. Example:
  141. ```py
  142. import requests
  143. from huggingface_hub import configure_http_backend, get_session
  144. # Create a factory function that returns a Session with configured proxies
  145. def backend_factory() -> requests.Session:
  146. session = requests.Session()
  147. session.proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"}
  148. return session
  149. # Set it as the default session factory
  150. configure_http_backend(backend_factory=backend_factory)
  151. # In practice, this is mostly done internally in `huggingface_hub`
  152. session = get_session()
  153. ```
  154. """
  155. return _get_session_from_cache(process_id=os.getpid(), thread_id=threading.get_ident())
  156. def reset_sessions() -> None:
  157. """Reset the cache of sessions.
  158. Mostly used internally when sessions are reconfigured or an SSLError is raised.
  159. See [`configure_http_backend`] for more details.
  160. """
  161. _get_session_from_cache.cache_clear()
  162. @lru_cache
  163. def _get_session_from_cache(process_id: int, thread_id: int) -> requests.Session:
  164. """
  165. Create a new session per thread using global factory. Using LRU cache (maxsize 128) to avoid memory leaks when
  166. using thousands of threads. Cache is cleared when `configure_http_backend` is called.
  167. """
  168. return _GLOBAL_BACKEND_FACTORY()
  169. def http_backoff(
  170. method: HTTP_METHOD_T,
  171. url: str,
  172. *,
  173. max_retries: int = 5,
  174. base_wait_time: float = 1,
  175. max_wait_time: float = 8,
  176. retry_on_exceptions: Union[Type[Exception], Tuple[Type[Exception], ...]] = (
  177. requests.Timeout,
  178. requests.ConnectionError,
  179. requests.exceptions.ChunkedEncodingError,
  180. ),
  181. retry_on_status_codes: Union[int, Tuple[int, ...]] = (500, 502, 503, 504),
  182. **kwargs,
  183. ) -> Response:
  184. """Wrapper around requests to retry calls on an endpoint, with exponential backoff.
  185. Endpoint call is retried on exceptions (ex: connection timeout, proxy error,...)
  186. and/or on specific status codes (ex: service unavailable). If the call failed more
  187. than `max_retries`, the exception is thrown or `raise_for_status` is called on the
  188. response object.
  189. Re-implement mechanisms from the `backoff` library to avoid adding an external
  190. dependencies to `hugging_face_hub`. See https://github.com/litl/backoff.
  191. Args:
  192. method (`Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"]`):
  193. HTTP method to perform.
  194. url (`str`):
  195. The URL of the resource to fetch.
  196. max_retries (`int`, *optional*, defaults to `5`):
  197. Maximum number of retries, defaults to 5 (no retries).
  198. base_wait_time (`float`, *optional*, defaults to `1`):
  199. Duration (in seconds) to wait before retrying the first time.
  200. Wait time between retries then grows exponentially, capped by
  201. `max_wait_time`.
  202. max_wait_time (`float`, *optional*, defaults to `8`):
  203. Maximum duration (in seconds) to wait before retrying.
  204. retry_on_exceptions (`Type[Exception]` or `Tuple[Type[Exception]]`, *optional*):
  205. Define which exceptions must be caught to retry the request. Can be a single type or a tuple of types.
  206. By default, retry on `requests.Timeout`, `requests.ConnectionError` and `requests.exceptions.ChunkedEncodingError`.
  207. retry_on_status_codes (`int` or `Tuple[int]`, *optional*, defaults to `(500, 502, 503, 504)`):
  208. Define on which status codes the request must be retried. By default, 5xx errors are retried.
  209. **kwargs (`dict`, *optional*):
  210. kwargs to pass to `requests.request`.
  211. Example:
  212. ```
  213. >>> from huggingface_hub.utils import http_backoff
  214. # Same usage as "requests.request".
  215. >>> response = http_backoff("GET", "https://www.google.com")
  216. >>> response.raise_for_status()
  217. # If you expect a Gateway Timeout from time to time
  218. >>> http_backoff("PUT", upload_url, data=data, retry_on_status_codes=504)
  219. >>> response.raise_for_status()
  220. ```
  221. > [!WARNING]
  222. > When using `requests` it is possible to stream data by passing an iterator to the
  223. > `data` argument. On http backoff this is a problem as the iterator is not reset
  224. > after a failed call. This issue is mitigated for file objects or any IO streams
  225. > by saving the initial position of the cursor (with `data.tell()`) and resetting the
  226. > cursor between each call (with `data.seek()`). For arbitrary iterators, http backoff
  227. > will fail. If this is a hard constraint for you, please let us know by opening an
  228. > issue on [Github](https://github.com/huggingface/huggingface_hub).
  229. """
  230. if isinstance(retry_on_exceptions, type): # Tuple from single exception type
  231. retry_on_exceptions = (retry_on_exceptions,)
  232. if isinstance(retry_on_status_codes, int): # Tuple from single status code
  233. retry_on_status_codes = (retry_on_status_codes,)
  234. nb_tries = 0
  235. sleep_time = base_wait_time
  236. # If `data` is used and is a file object (or any IO), it will be consumed on the
  237. # first HTTP request. We need to save the initial position so that the full content
  238. # of the file is re-sent on http backoff. See warning tip in docstring.
  239. io_obj_initial_pos = None
  240. if "data" in kwargs and isinstance(kwargs["data"], (io.IOBase, SliceFileObj)):
  241. io_obj_initial_pos = kwargs["data"].tell()
  242. session = get_session()
  243. while True:
  244. nb_tries += 1
  245. try:
  246. # If `data` is used and is a file object (or any IO), set back cursor to
  247. # initial position.
  248. if io_obj_initial_pos is not None:
  249. kwargs["data"].seek(io_obj_initial_pos)
  250. # Perform request and return if status_code is not in the retry list.
  251. response = session.request(method=method, url=url, **kwargs)
  252. if response.status_code not in retry_on_status_codes:
  253. return response
  254. # Wrong status code returned (HTTP 503 for instance)
  255. logger.warning(f"HTTP Error {response.status_code} thrown while requesting {method} {url}")
  256. if nb_tries > max_retries:
  257. response.raise_for_status() # Will raise uncaught exception
  258. # We return response to avoid infinite loop in the corner case where the
  259. # user ask for retry on a status code that doesn't raise_for_status.
  260. return response
  261. except retry_on_exceptions as err:
  262. logger.warning(f"'{err}' thrown while requesting {method} {url}")
  263. if isinstance(err, requests.ConnectionError):
  264. reset_sessions() # In case of SSLError it's best to reset the shared requests.Session objects
  265. if nb_tries > max_retries:
  266. raise err
  267. # Sleep for X seconds
  268. logger.warning(f"Retrying in {sleep_time}s [Retry {nb_tries}/{max_retries}].")
  269. time.sleep(sleep_time)
  270. # Update sleep time for next retry
  271. sleep_time = min(max_wait_time, sleep_time * 2) # Exponential backoff
  272. def fix_hf_endpoint_in_url(url: str, endpoint: Optional[str]) -> str:
  273. """Replace the default endpoint in a URL by a custom one.
  274. This is useful when using a proxy and the Hugging Face Hub returns a URL with the default endpoint.
  275. """
  276. endpoint = endpoint.rstrip("/") if endpoint else constants.ENDPOINT
  277. # check if a proxy has been set => if yes, update the returned URL to use the proxy
  278. if endpoint not in (constants._HF_DEFAULT_ENDPOINT, constants._HF_DEFAULT_STAGING_ENDPOINT):
  279. url = url.replace(constants._HF_DEFAULT_ENDPOINT, endpoint)
  280. url = url.replace(constants._HF_DEFAULT_STAGING_ENDPOINT, endpoint)
  281. return url
  282. def hf_raise_for_status(response: Response, endpoint_name: Optional[str] = None) -> None:
  283. """
  284. Internal version of `response.raise_for_status()` that will refine a
  285. potential HTTPError. Raised exception will be an instance of `HfHubHTTPError`.
  286. This helper is meant to be the unique method to raise_for_status when making a call
  287. to the Hugging Face Hub.
  288. Example:
  289. ```py
  290. import requests
  291. from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError
  292. response = get_session().post(...)
  293. try:
  294. hf_raise_for_status(response)
  295. except HfHubHTTPError as e:
  296. print(str(e)) # formatted message
  297. e.request_id, e.server_message # details returned by server
  298. # Complete the error message with additional information once it's raised
  299. e.append_to_message("\n`create_commit` expects the repository to exist.")
  300. raise
  301. ```
  302. Args:
  303. response (`Response`):
  304. Response from the server.
  305. endpoint_name (`str`, *optional*):
  306. Name of the endpoint that has been called. If provided, the error message
  307. will be more complete.
  308. > [!WARNING]
  309. > Raises when the request has failed:
  310. >
  311. > - [`~utils.RepositoryNotFoundError`]
  312. > If the repository to download from cannot be found. This may be because it
  313. > doesn't exist, because `repo_type` is not set correctly, or because the repo
  314. > is `private` and you do not have access.
  315. > - [`~utils.GatedRepoError`]
  316. > If the repository exists but is gated and the user is not on the authorized
  317. > list.
  318. > - [`~utils.RevisionNotFoundError`]
  319. > If the repository exists but the revision couldn't be find.
  320. > - [`~utils.EntryNotFoundError`]
  321. > If the repository exists but the entry (e.g. the requested file) couldn't be
  322. > find.
  323. > - [`~utils.BadRequestError`]
  324. > If request failed with a HTTP 400 BadRequest error.
  325. > - [`~utils.HfHubHTTPError`]
  326. > If request failed for a reason not listed above.
  327. """
  328. try:
  329. response.raise_for_status()
  330. except HTTPError as e:
  331. error_code = response.headers.get("X-Error-Code")
  332. error_message = response.headers.get("X-Error-Message")
  333. if error_code == "RevisionNotFound":
  334. message = f"{response.status_code} Client Error." + "\n\n" + f"Revision Not Found for url: {response.url}."
  335. raise _format(RevisionNotFoundError, message, response) from e
  336. elif error_code == "EntryNotFound":
  337. message = f"{response.status_code} Client Error." + "\n\n" + f"Entry Not Found for url: {response.url}."
  338. raise _format(EntryNotFoundError, message, response) from e
  339. elif error_code == "GatedRepo":
  340. message = (
  341. f"{response.status_code} Client Error." + "\n\n" + f"Cannot access gated repo for url {response.url}."
  342. )
  343. raise _format(GatedRepoError, message, response) from e
  344. elif error_message == "Access to this resource is disabled.":
  345. message = (
  346. f"{response.status_code} Client Error."
  347. + "\n\n"
  348. + f"Cannot access repository for url {response.url}."
  349. + "\n"
  350. + "Access to this resource is disabled."
  351. )
  352. raise _format(DisabledRepoError, message, response) from e
  353. elif error_code == "RepoNotFound" or (
  354. response.status_code == 401
  355. and error_message != "Invalid credentials in Authorization header"
  356. and response.request is not None
  357. and response.request.url is not None
  358. and REPO_API_REGEX.search(response.request.url) is not None
  359. ):
  360. # 401 is misleading as it is returned for:
  361. # - private and gated repos if user is not authenticated
  362. # - missing repos
  363. # => for now, we process them as `RepoNotFound` anyway.
  364. # See https://gist.github.com/Wauplin/46c27ad266b15998ce56a6603796f0b9
  365. message = (
  366. f"{response.status_code} Client Error."
  367. + "\n\n"
  368. + f"Repository Not Found for url: {response.url}."
  369. + "\nPlease make sure you specified the correct `repo_id` and"
  370. " `repo_type`.\nIf you are trying to access a private or gated repo,"
  371. " make sure you are authenticated. For more details, see"
  372. " https://huggingface.co/docs/huggingface_hub/authentication"
  373. )
  374. raise _format(RepositoryNotFoundError, message, response) from e
  375. elif response.status_code == 400:
  376. message = (
  377. f"\n\nBad request for {endpoint_name} endpoint:" if endpoint_name is not None else "\n\nBad request:"
  378. )
  379. raise _format(BadRequestError, message, response) from e
  380. elif response.status_code == 403:
  381. message = (
  382. f"\n\n{response.status_code} Forbidden: {error_message}."
  383. + f"\nCannot access content at: {response.url}."
  384. + "\nMake sure your token has the correct permissions."
  385. )
  386. raise _format(HfHubHTTPError, message, response) from e
  387. elif response.status_code == 416:
  388. range_header = response.request.headers.get("Range")
  389. message = f"{e}. Requested range: {range_header}. Content-Range: {response.headers.get('Content-Range')}."
  390. raise _format(HfHubHTTPError, message, response) from e
  391. # Convert `HTTPError` into a `HfHubHTTPError` to display request information
  392. # as well (request id and/or server error message)
  393. raise _format(HfHubHTTPError, str(e), response) from e
  394. def _format(error_type: Type[HfHubHTTPError], custom_message: str, response: Response) -> HfHubHTTPError:
  395. server_errors = []
  396. # Retrieve server error from header
  397. from_headers = response.headers.get("X-Error-Message")
  398. if from_headers is not None:
  399. server_errors.append(from_headers)
  400. # Retrieve server error from body
  401. try:
  402. # Case errors are returned in a JSON format
  403. data = response.json()
  404. error = data.get("error")
  405. if error is not None:
  406. if isinstance(error, list):
  407. # Case {'error': ['my error 1', 'my error 2']}
  408. server_errors.extend(error)
  409. else:
  410. # Case {'error': 'my error'}
  411. server_errors.append(error)
  412. errors = data.get("errors")
  413. if errors is not None:
  414. # Case {'errors': [{'message': 'my error 1'}, {'message': 'my error 2'}]}
  415. for error in errors:
  416. if "message" in error:
  417. server_errors.append(error["message"])
  418. except JSONDecodeError:
  419. # If content is not JSON and not HTML, append the text
  420. content_type = response.headers.get("Content-Type", "")
  421. if response.text and "html" not in content_type.lower():
  422. server_errors.append(response.text)
  423. # Strip all server messages
  424. server_errors = [str(line).strip() for line in server_errors if str(line).strip()]
  425. # Deduplicate server messages (keep order)
  426. # taken from https://stackoverflow.com/a/17016257
  427. server_errors = list(dict.fromkeys(server_errors))
  428. # Format server error
  429. server_message = "\n".join(server_errors)
  430. # Add server error to custom message
  431. final_error_message = custom_message
  432. if server_message and server_message.lower() not in custom_message.lower():
  433. if "\n\n" in custom_message:
  434. final_error_message += "\n" + server_message
  435. else:
  436. final_error_message += "\n\n" + server_message
  437. # Add Request ID
  438. request_id = str(response.headers.get(X_REQUEST_ID, ""))
  439. if request_id:
  440. request_id_message = f" (Request ID: {request_id})"
  441. else:
  442. # Fallback to X-Amzn-Trace-Id
  443. request_id = str(response.headers.get(X_AMZN_TRACE_ID, ""))
  444. if request_id:
  445. request_id_message = f" (Amzn Trace ID: {request_id})"
  446. if request_id and request_id.lower() not in final_error_message.lower():
  447. if "\n" in final_error_message:
  448. newline_index = final_error_message.index("\n")
  449. final_error_message = (
  450. final_error_message[:newline_index] + request_id_message + final_error_message[newline_index:]
  451. )
  452. else:
  453. final_error_message += request_id_message
  454. # Return
  455. return error_type(final_error_message.strip(), response=response, server_message=server_message or None)
  456. def _curlify(request: requests.PreparedRequest) -> str:
  457. """Convert a `requests.PreparedRequest` into a curl command (str).
  458. Used for debug purposes only.
  459. Implementation vendored from https://github.com/ofw/curlify/blob/master/curlify.py.
  460. MIT License Copyright (c) 2016 Egor.
  461. """
  462. parts: List[Tuple[Any, Any]] = [
  463. ("curl", None),
  464. ("-X", request.method),
  465. ]
  466. for k, v in sorted(request.headers.items()):
  467. if k.lower() == "authorization":
  468. v = "<TOKEN>" # Hide authorization header, no matter its value (can be Bearer, Key, etc.)
  469. parts += [("-H", "{0}: {1}".format(k, v))]
  470. if request.body:
  471. body = request.body
  472. if isinstance(body, bytes):
  473. body = body.decode("utf-8", errors="ignore")
  474. elif hasattr(body, "read"):
  475. body = "<file-like object>" # Don't try to read it to avoid consuming the stream
  476. if len(body) > 1000:
  477. body = body[:1000] + " ... [truncated]"
  478. parts += [("-d", body.replace("\n", ""))]
  479. parts += [(None, request.url)]
  480. flat_parts = []
  481. for k, v in parts:
  482. if k:
  483. flat_parts.append(quote(k))
  484. if v:
  485. flat_parts.append(quote(v))
  486. return " ".join(flat_parts)
  487. # Regex to parse HTTP Range header
  488. RANGE_REGEX = re.compile(r"^\s*bytes\s*=\s*(\d*)\s*-\s*(\d*)\s*$", re.IGNORECASE)
  489. def _adjust_range_header(original_range: Optional[str], resume_size: int) -> Optional[str]:
  490. """
  491. Adjust HTTP Range header to account for resume position.
  492. """
  493. if not original_range:
  494. return f"bytes={resume_size}-"
  495. if "," in original_range:
  496. raise ValueError(f"Multiple ranges detected - {original_range!r}, not supported yet.")
  497. match = RANGE_REGEX.match(original_range)
  498. if not match:
  499. raise RuntimeError(f"Invalid range format - {original_range!r}.")
  500. start, end = match.groups()
  501. if not start:
  502. if not end:
  503. raise RuntimeError(f"Invalid range format - {original_range!r}.")
  504. new_suffix = int(end) - resume_size
  505. new_range = f"bytes=-{new_suffix}"
  506. if new_suffix <= 0:
  507. raise RuntimeError(f"Empty new range - {new_range!r}.")
  508. return new_range
  509. start = int(start)
  510. new_start = start + resume_size
  511. if end:
  512. end = int(end)
  513. new_range = f"bytes={new_start}-{end}"
  514. if new_start > end:
  515. raise RuntimeError(f"Empty new range - {new_range!r}.")
  516. return new_range
  517. return f"bytes={new_start}-"