_http.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  1. # Copyright 2022-present, the HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Contains utilities to handle HTTP requests in huggingface_hub."""
  15. import atexit
  16. import io
  17. import json
  18. import os
  19. import re
  20. import threading
  21. import time
  22. import uuid
  23. from collections.abc import Callable, Generator, Mapping
  24. from contextlib import contextmanager
  25. from dataclasses import dataclass
  26. from shlex import quote
  27. from typing import Any, TypeVar
  28. from urllib.parse import urlparse
  29. import httpx
  30. from huggingface_hub.errors import OfflineModeIsEnabled
  31. from .. import constants
  32. from ..errors import (
  33. BadRequestError,
  34. BucketNotFoundError,
  35. DisabledRepoError,
  36. GatedRepoError,
  37. HfHubHTTPError,
  38. RemoteEntryNotFoundError,
  39. RepositoryNotFoundError,
  40. RevisionNotFoundError,
  41. )
  42. from . import logging
  43. from ._lfs import SliceFileObj
  44. from ._typing import HTTP_METHOD_T
  45. logger = logging.get_logger(__name__)
  46. @dataclass(frozen=True)
  47. class RateLimitInfo:
  48. """
  49. Parsed rate limit information from HTTP response headers.
  50. Attributes:
  51. resource_type (`str`): The type of resource being rate limited.
  52. remaining (`int`): The number of requests remaining in the current window.
  53. reset_in_seconds (`int`): The number of seconds until the rate limit resets.
  54. limit (`int`, *optional*): The maximum number of requests allowed in the current window.
  55. window_seconds (`int`, *optional*): The number of seconds in the current window.
  56. """
  57. resource_type: str
  58. remaining: int
  59. reset_in_seconds: int
  60. limit: int | None = None
  61. window_seconds: int | None = None
  62. # Regex patterns for parsing rate limit headers
  63. # e.g.: "api";r=0;t=55 --> resource_type="api", r=0, t=55
  64. _RATELIMIT_REGEX = re.compile(r"\"(?P<resource_type>\w+)\"\s*;\s*r\s*=\s*(?P<r>\d+)\s*;\s*t\s*=\s*(?P<t>\d+)")
  65. # e.g.: "fixed window";"api";q=500;w=300 --> q=500, w=300
  66. _RATELIMIT_POLICY_REGEX = re.compile(r"q\s*=\s*(?P<q>\d+).*?w\s*=\s*(?P<w>\d+)")
  67. def parse_ratelimit_headers(headers: Mapping[str, str]) -> RateLimitInfo | None:
  68. """Parse rate limit information from HTTP response headers.
  69. Follows IETF draft: https://www.ietf.org/archive/id/draft-ietf-httpapi-ratelimit-headers-09.html
  70. Only a subset is implemented.
  71. Example:
  72. ```python
  73. >>> from huggingface_hub.utils import parse_ratelimit_headers
  74. >>> headers = {
  75. ... "ratelimit": '"api";r=0;t=55',
  76. ... "ratelimit-policy": '"fixed window";"api";q=500;w=300',
  77. ... }
  78. >>> info = parse_ratelimit_headers(headers)
  79. >>> info.remaining
  80. 0
  81. >>> info.reset_in_seconds
  82. 55
  83. ```
  84. """
  85. ratelimit: str | None = None
  86. policy: str | None = None
  87. for key in headers:
  88. lower_key = key.lower()
  89. if lower_key == "ratelimit":
  90. ratelimit = headers[key]
  91. elif lower_key == "ratelimit-policy":
  92. policy = headers[key]
  93. if not ratelimit:
  94. return None
  95. match = _RATELIMIT_REGEX.search(ratelimit)
  96. if not match:
  97. return None
  98. resource_type = match.group("resource_type")
  99. remaining = int(match.group("r"))
  100. reset_in_seconds = int(match.group("t"))
  101. limit: int | None = None
  102. window_seconds: int | None = None
  103. if policy:
  104. policy_match = _RATELIMIT_POLICY_REGEX.search(policy)
  105. if policy_match:
  106. limit = int(policy_match.group("q"))
  107. window_seconds = int(policy_match.group("w"))
  108. return RateLimitInfo(
  109. resource_type=resource_type,
  110. remaining=remaining,
  111. reset_in_seconds=reset_in_seconds,
  112. limit=limit,
  113. window_seconds=window_seconds,
  114. )
  115. # When raising an error, we include the request id in the error message for easier debugging.
  116. # Request ID is sourced from headers in order of precedence: "X-Request-Id", "X-Amzn-Trace-Id", "X-Amz-Cf-Id".
  117. X_REQUEST_ID = "x-request-id"
  118. X_AMZN_TRACE_ID = "X-Amzn-Trace-Id"
  119. X_AMZ_CF_ID = "x-amz-cf-id"
  120. REPO_API_REGEX = re.compile(
  121. r"""
  122. # staging or production endpoint
  123. ^https://[^/]+
  124. (
  125. # on /api/repo_type/repo_id
  126. /api/(models|datasets|spaces)/(.+)
  127. |
  128. # or /repo_id/resolve/revision/...
  129. /(.+)/resolve/(.+)
  130. )
  131. """,
  132. flags=re.VERBOSE,
  133. )
  134. BUCKET_API_REGEX = re.compile(
  135. r"""
  136. # staging or production endpoint
  137. ^https?://[^/]+
  138. # on /api/buckets/...
  139. /api/buckets/
  140. """,
  141. flags=re.VERBOSE,
  142. )
  143. # Regex to extract repo_type and repo_id from API URLs.
  144. # Captures: group(1) = repo_type plural (models/datasets/spaces), group(2) = first path segment, group(3) = optional second segment.
  145. _REPO_ID_FROM_URL_REGEX = re.compile(r"^https?://[^/]+/api/(models|datasets|spaces)/([^/]+)(?:/([^/]+))?")
  146. # Regex to extract bucket_id (namespace/name) from bucket API URLs.
  147. _BUCKET_ID_FROM_URL_REGEX = re.compile(r"^https?://[^/]+/api/buckets/([^/]+/[^/]+)")
  148. # Sub-paths that follow a repo_id in API URLs (not part of the repo name).
  149. _REPO_URL_SUBPATHS = {"resolve", "tree", "blob", "raw", "refs", "commit", "discussions", "settings", "revision"}
  150. def _parse_repo_info_from_url(url: str) -> tuple[str | None, str | None]:
  151. """Extract (repo_type, repo_id) from an API URL.
  152. Returns canonical repo_type values: "model", "dataset", "space" (or None).
  153. Examples:
  154. >>> _parse_repo_info_from_url("https://huggingface.co/api/models/user/repo")
  155. ("model", "user/repo")
  156. >>> _parse_repo_info_from_url("https://huggingface.co/api/datasets/user/repo/resolve/main/data.csv")
  157. ("dataset", "user/repo")
  158. >>> _parse_repo_info_from_url("https://huggingface.co/api/models/bert-base-cased/resolve/main/config.json")
  159. ("model", "bert-base-cased")
  160. """
  161. match = _REPO_ID_FROM_URL_REGEX.search(url)
  162. if not match:
  163. return None, None
  164. repo_type = constants.REPO_TYPES_MAPPING.get(match.group(1))
  165. first, second = match.group(2), match.group(3)
  166. if second and second not in _REPO_URL_SUBPATHS:
  167. repo_id = f"{first}/{second}"
  168. else:
  169. repo_id = first
  170. return repo_type, repo_id
  171. def _parse_bucket_id_from_url(url: str) -> str | None:
  172. """Extract bucket_id (namespace/name) from a bucket API URL."""
  173. match = _BUCKET_ID_FROM_URL_REGEX.search(url)
  174. return match.group(1) if match else None
  175. def hf_request_event_hook(request: httpx.Request) -> None:
  176. """
  177. Event hook that will be used to make HTTP requests to the Hugging Face Hub.
  178. What it does:
  179. - Block requests if offline mode is enabled
  180. - Add a request ID to the request headers
  181. - Log the request if debug mode is enabled
  182. """
  183. if constants.is_offline_mode():
  184. raise OfflineModeIsEnabled(
  185. f"Cannot reach {request.url}: offline mode is enabled. To disable it, please unset the `HF_HUB_OFFLINE` environment variable."
  186. )
  187. # Add random request ID => easier for server-side debugging
  188. if X_AMZN_TRACE_ID not in request.headers:
  189. request.headers[X_AMZN_TRACE_ID] = request.headers.get(X_REQUEST_ID) or str(uuid.uuid4())
  190. request_id = request.headers.get(X_AMZN_TRACE_ID)
  191. # Debug log
  192. logger.debug(
  193. "Request %s: %s %s (authenticated: %s)",
  194. request_id,
  195. request.method,
  196. request.url,
  197. request.headers.get("authorization") is not None,
  198. )
  199. if constants.HF_DEBUG:
  200. logger.debug("Send: %s", _curlify(request))
  201. return request_id
  202. async def async_hf_request_event_hook(request: httpx.Request) -> None:
  203. """
  204. Async version of `hf_request_event_hook`.
  205. """
  206. return hf_request_event_hook(request)
  207. async def async_hf_response_event_hook(response: httpx.Response) -> None:
  208. if response.status_code >= 400:
  209. # If response will raise, read content from stream to have it available when raising the exception
  210. # If content-length is not set or is too large, skip reading the content to avoid OOM
  211. if "Content-length" in response.headers:
  212. try:
  213. length = int(response.headers["Content-length"])
  214. except ValueError:
  215. return
  216. if length < 1_000_000:
  217. await response.aread()
  218. def default_client_factory() -> httpx.Client:
  219. """
  220. Factory function to create a `httpx.Client` with the default transport.
  221. """
  222. return httpx.Client(
  223. event_hooks={"request": [hf_request_event_hook]},
  224. follow_redirects=True,
  225. timeout=None,
  226. )
  227. def default_async_client_factory() -> httpx.AsyncClient:
  228. """
  229. Factory function to create a `httpx.AsyncClient` with the default transport.
  230. """
  231. return httpx.AsyncClient(
  232. event_hooks={"request": [async_hf_request_event_hook], "response": [async_hf_response_event_hook]},
  233. follow_redirects=True,
  234. timeout=None,
  235. )
  236. CLIENT_FACTORY_T = Callable[[], httpx.Client]
  237. ASYNC_CLIENT_FACTORY_T = Callable[[], httpx.AsyncClient]
  238. _CLIENT_LOCK = threading.Lock()
  239. _GLOBAL_CLIENT_FACTORY: CLIENT_FACTORY_T = default_client_factory
  240. _GLOBAL_ASYNC_CLIENT_FACTORY: ASYNC_CLIENT_FACTORY_T = default_async_client_factory
  241. _GLOBAL_CLIENT: httpx.Client | None = None
  242. def set_client_factory(client_factory: CLIENT_FACTORY_T) -> None:
  243. """
  244. Set the HTTP client factory to be used by `huggingface_hub`.
  245. The client factory is a method that returns a `httpx.Client` object. On the first call to [`get_session`] the client factory
  246. will be used to create a new `httpx.Client` object that will be shared between all calls made by `huggingface_hub`.
  247. This can be useful if you are running your scripts in a specific environment requiring custom configuration (e.g. custom proxy or certifications).
  248. Use [`get_session`] to get a correctly configured `httpx.Client`.
  249. """
  250. global _GLOBAL_CLIENT_FACTORY
  251. with _CLIENT_LOCK:
  252. close_session()
  253. _GLOBAL_CLIENT_FACTORY = client_factory
  254. def set_async_client_factory(async_client_factory: ASYNC_CLIENT_FACTORY_T) -> None:
  255. """
  256. Set the HTTP async client factory to be used by `huggingface_hub`.
  257. The async client factory is a method that returns a `httpx.AsyncClient` object.
  258. This can be useful if you are running your scripts in a specific environment requiring custom configuration (e.g. custom proxy or certifications).
  259. Use [`get_async_client`] to get a correctly configured `httpx.AsyncClient`.
  260. <Tip warning={true}>
  261. Contrary to the `httpx.Client` that is shared between all calls made by `huggingface_hub`, the `httpx.AsyncClient` is not shared.
  262. It is recommended to use an async context manager to ensure the client is properly closed when the context is exited.
  263. </Tip>
  264. """
  265. global _GLOBAL_ASYNC_CLIENT_FACTORY
  266. _GLOBAL_ASYNC_CLIENT_FACTORY = async_client_factory
  267. def get_session() -> httpx.Client:
  268. """
  269. Get a `httpx.Client` object, using the transport factory from the user.
  270. This client is shared between all calls made by `huggingface_hub`. Therefore you should not close it manually.
  271. Use [`set_client_factory`] to customize the `httpx.Client`.
  272. """
  273. global _GLOBAL_CLIENT
  274. if _GLOBAL_CLIENT is None:
  275. with _CLIENT_LOCK:
  276. _GLOBAL_CLIENT = _GLOBAL_CLIENT_FACTORY()
  277. return _GLOBAL_CLIENT
  278. def get_async_session() -> httpx.AsyncClient:
  279. """
  280. Return a `httpx.AsyncClient` object, using the transport factory from the user.
  281. Use [`set_async_client_factory`] to customize the `httpx.AsyncClient`.
  282. <Tip warning={true}>
  283. Contrary to the `httpx.Client` that is shared between all calls made by `huggingface_hub`, the `httpx.AsyncClient` is not shared.
  284. It is recommended to use an async context manager to ensure the client is properly closed when the context is exited.
  285. </Tip>
  286. """
  287. return _GLOBAL_ASYNC_CLIENT_FACTORY()
  288. def close_session() -> None:
  289. """
  290. Close the global `httpx.Client` used by `huggingface_hub`.
  291. If a Client is closed, it will be recreated on the next call to [`get_session`].
  292. Can be useful if e.g. an SSL certificate has been updated.
  293. """
  294. global _GLOBAL_CLIENT
  295. client = _GLOBAL_CLIENT
  296. # First, set global client to None
  297. _GLOBAL_CLIENT = None
  298. # Then, close the clients
  299. if client is not None:
  300. try:
  301. client.close()
  302. except Exception as e:
  303. logger.warning(f"Error closing client: {e}")
  304. atexit.register(close_session)
  305. if hasattr(os, "register_at_fork"):
  306. os.register_at_fork(after_in_child=close_session)
  307. _DEFAULT_RETRY_ON_EXCEPTIONS: tuple[type[Exception], ...] = (httpx.TimeoutException, httpx.NetworkError)
  308. _DEFAULT_RETRY_ON_STATUS_CODES: tuple[int, ...] = (429, 500, 502, 503, 504)
  309. def _http_backoff_base(
  310. method: HTTP_METHOD_T,
  311. url: str,
  312. *,
  313. max_retries: int = 5,
  314. base_wait_time: float = 1,
  315. max_wait_time: float = 8,
  316. retry_on_exceptions: type[Exception] | tuple[type[Exception], ...] = _DEFAULT_RETRY_ON_EXCEPTIONS,
  317. retry_on_status_codes: int | tuple[int, ...] = _DEFAULT_RETRY_ON_STATUS_CODES,
  318. stream: bool = False,
  319. **kwargs,
  320. ) -> Generator[httpx.Response, None, None]:
  321. """Internal implementation of HTTP backoff logic shared between `http_backoff` and `http_stream_backoff`."""
  322. if isinstance(retry_on_exceptions, type): # Tuple from single exception type
  323. retry_on_exceptions = (retry_on_exceptions,)
  324. if isinstance(retry_on_status_codes, int): # Tuple from single status code
  325. retry_on_status_codes = (retry_on_status_codes,)
  326. nb_tries = 0
  327. sleep_time = base_wait_time
  328. ratelimit_reset: int | None = None # seconds to wait for rate limit reset if 429 response
  329. # If `data` is used and is a file object (or any IO), it will be consumed on the
  330. # first HTTP request. We need to save the initial position so that the full content
  331. # of the file is re-sent on http backoff. See warning tip in docstring.
  332. io_obj_initial_pos = None
  333. if "data" in kwargs and isinstance(kwargs["data"], (io.IOBase, SliceFileObj)):
  334. io_obj_initial_pos = kwargs["data"].tell()
  335. client = get_session()
  336. while True:
  337. nb_tries += 1
  338. ratelimit_reset = None
  339. try:
  340. # If `data` is used and is a file object (or any IO), set back cursor to
  341. # initial position.
  342. if io_obj_initial_pos is not None:
  343. kwargs["data"].seek(io_obj_initial_pos)
  344. # Perform request and handle response
  345. def _should_retry(response: httpx.Response) -> bool:
  346. """Handle response and return True if should retry, False if should return/yield."""
  347. nonlocal ratelimit_reset
  348. if response.status_code not in retry_on_status_codes:
  349. return False # Success, don't retry
  350. # Wrong status code returned (HTTP 503 for instance)
  351. logger.warning(f"HTTP Error {response.status_code} thrown while requesting {method} {url}")
  352. if nb_tries > max_retries:
  353. hf_raise_for_status(response) # Will raise uncaught exception
  354. # Return/yield response to avoid infinite loop in the corner case where the
  355. # user ask for retry on a status code that doesn't raise_for_status.
  356. return False # Don't retry, return/yield response
  357. # get rate limit reset time from headers if 429 response
  358. if response.status_code == 429:
  359. ratelimit_info = parse_ratelimit_headers(response.headers)
  360. if ratelimit_info is not None:
  361. ratelimit_reset = ratelimit_info.reset_in_seconds
  362. return True # Should retry
  363. if stream:
  364. with client.stream(method=method, url=url, **kwargs) as response:
  365. if not _should_retry(response):
  366. yield response
  367. return
  368. else:
  369. response = client.request(method=method, url=url, **kwargs)
  370. if not _should_retry(response):
  371. yield response
  372. return
  373. except retry_on_exceptions as err:
  374. logger.warning(f"'{err}' thrown while requesting {method} {url}")
  375. if isinstance(err, httpx.ConnectError):
  376. close_session() # In case of SSLError it's best to close the shared httpx.Client objects
  377. if nb_tries > max_retries:
  378. raise err
  379. if ratelimit_reset is not None:
  380. actual_sleep = float(ratelimit_reset) + 1 # +1s to avoid rounding issues
  381. logger.warning(f"Rate limited. Waiting {actual_sleep}s before retry [Retry {nb_tries}/{max_retries}].")
  382. else:
  383. actual_sleep = sleep_time
  384. logger.warning(f"Retrying in {actual_sleep}s [Retry {nb_tries}/{max_retries}].")
  385. time.sleep(actual_sleep)
  386. # Update sleep time for next retry
  387. sleep_time = min(max_wait_time, sleep_time * 2) # Exponential backoff
  388. def http_backoff(
  389. method: HTTP_METHOD_T,
  390. url: str,
  391. *,
  392. max_retries: int = 5,
  393. base_wait_time: float = 1,
  394. max_wait_time: float = 8,
  395. retry_on_exceptions: type[Exception] | tuple[type[Exception], ...] = _DEFAULT_RETRY_ON_EXCEPTIONS,
  396. retry_on_status_codes: int | tuple[int, ...] = _DEFAULT_RETRY_ON_STATUS_CODES,
  397. **kwargs,
  398. ) -> httpx.Response:
  399. """Wrapper around httpx to retry calls on an endpoint, with exponential backoff.
  400. Endpoint call is retried on exceptions (ex: connection timeout, proxy error,...)
  401. and/or on specific status codes (ex: service unavailable). If the call failed more
  402. than `max_retries`, the exception is thrown or `raise_for_status` is called on the
  403. response object.
  404. Re-implement mechanisms from the `backoff` library to avoid adding an external
  405. dependencies to `hugging_face_hub`. See https://github.com/litl/backoff.
  406. Args:
  407. method (`Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"]`):
  408. HTTP method to perform.
  409. url (`str`):
  410. The URL of the resource to fetch.
  411. max_retries (`int`, *optional*, defaults to `5`):
  412. Maximum number of retries, defaults to 5 (no retries).
  413. base_wait_time (`float`, *optional*, defaults to `1`):
  414. Duration (in seconds) to wait before retrying the first time.
  415. Wait time between retries then grows exponentially, capped by
  416. `max_wait_time`.
  417. max_wait_time (`float`, *optional*, defaults to `8`):
  418. Maximum duration (in seconds) to wait before retrying.
  419. retry_on_exceptions (`type[Exception]` or `tuple[type[Exception]]`, *optional*):
  420. Define which exceptions must be caught to retry the request. Can be a single type or a tuple of types.
  421. By default, retry on `httpx.TimeoutException` and `httpx.NetworkError`.
  422. retry_on_status_codes (`int` or `tuple[int]`, *optional*, defaults to `(429, 500, 502, 503, 504)`):
  423. Define on which status codes the request must be retried. By default, retries
  424. on rate limit (429) and server errors (5xx).
  425. **kwargs (`dict`, *optional*):
  426. kwargs to pass to `httpx.request`.
  427. Example:
  428. ```
  429. >>> from huggingface_hub.utils import http_backoff
  430. # Same usage as "httpx.request".
  431. >>> response = http_backoff("GET", "https://www.google.com")
  432. >>> response.raise_for_status()
  433. # If you expect a Gateway Timeout from time to time
  434. >>> http_backoff("PUT", upload_url, data=data, retry_on_status_codes=504)
  435. >>> response.raise_for_status()
  436. ```
  437. > [!WARNING]
  438. > When using `requests` it is possible to stream data by passing an iterator to the
  439. > `data` argument. On http backoff this is a problem as the iterator is not reset
  440. > after a failed call. This issue is mitigated for file objects or any IO streams
  441. > by saving the initial position of the cursor (with `data.tell()`) and resetting the
  442. > cursor between each call (with `data.seek()`). For arbitrary iterators, http backoff
  443. > will fail. If this is a hard constraint for you, please let us know by opening an
  444. > issue on [Github](https://github.com/huggingface/huggingface_hub).
  445. """
  446. return next(
  447. _http_backoff_base(
  448. method=method,
  449. url=url,
  450. max_retries=max_retries,
  451. base_wait_time=base_wait_time,
  452. max_wait_time=max_wait_time,
  453. retry_on_exceptions=retry_on_exceptions,
  454. retry_on_status_codes=retry_on_status_codes,
  455. stream=False,
  456. **kwargs,
  457. )
  458. )
  459. @contextmanager
  460. def http_stream_backoff(
  461. method: HTTP_METHOD_T,
  462. url: str,
  463. *,
  464. max_retries: int = 5,
  465. base_wait_time: float = 1,
  466. max_wait_time: float = 8,
  467. retry_on_exceptions: type[Exception] | tuple[type[Exception], ...] = _DEFAULT_RETRY_ON_EXCEPTIONS,
  468. retry_on_status_codes: int | tuple[int, ...] = _DEFAULT_RETRY_ON_STATUS_CODES,
  469. **kwargs,
  470. ) -> Generator[httpx.Response, None, None]:
  471. """Wrapper around httpx to retry calls on an endpoint, with exponential backoff.
  472. Endpoint call is retried on exceptions (ex: connection timeout, proxy error,...)
  473. and/or on specific status codes (ex: service unavailable). If the call failed more
  474. than `max_retries`, the exception is thrown or `raise_for_status` is called on the
  475. response object.
  476. Re-implement mechanisms from the `backoff` library to avoid adding an external
  477. dependencies to `hugging_face_hub`. See https://github.com/litl/backoff.
  478. Args:
  479. method (`Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"]`):
  480. HTTP method to perform.
  481. url (`str`):
  482. The URL of the resource to fetch.
  483. max_retries (`int`, *optional*, defaults to `5`):
  484. Maximum number of retries, defaults to 5 (no retries).
  485. base_wait_time (`float`, *optional*, defaults to `1`):
  486. Duration (in seconds) to wait before retrying the first time.
  487. Wait time between retries then grows exponentially, capped by
  488. `max_wait_time`.
  489. max_wait_time (`float`, *optional*, defaults to `8`):
  490. Maximum duration (in seconds) to wait before retrying.
  491. retry_on_exceptions (`type[Exception]` or `tuple[type[Exception]]`, *optional*):
  492. Define which exceptions must be caught to retry the request. Can be a single type or a tuple of types.
  493. By default, retry on `httpx.TimeoutException` and `httpx.NetworkError`.
  494. retry_on_status_codes (`int` or `tuple[int]`, *optional*, defaults to `(429, 500, 502, 503, 504)`):
  495. Define on which status codes the request must be retried. By default, retries
  496. on rate limit (429) and server errors (5xx).
  497. **kwargs (`dict`, *optional*):
  498. kwargs to pass to `httpx.request`.
  499. Example:
  500. ```
  501. >>> from huggingface_hub.utils import http_stream_backoff
  502. # Same usage as "httpx.stream".
  503. >>> with http_stream_backoff("GET", "https://www.google.com") as response:
  504. ... for chunk in response.iter_bytes():
  505. ... print(chunk)
  506. # If you expect a Gateway Timeout from time to time
  507. >>> with http_stream_backoff("PUT", upload_url, data=data, retry_on_status_codes=504) as response:
  508. ... response.raise_for_status()
  509. ```
  510. <Tip warning={true}>
  511. When using `httpx` it is possible to stream data by passing an iterator to the
  512. `data` argument. On http backoff this is a problem as the iterator is not reset
  513. after a failed call. This issue is mitigated for file objects or any IO streams
  514. by saving the initial position of the cursor (with `data.tell()`) and resetting the
  515. cursor between each call (with `data.seek()`). For arbitrary iterators, http backoff
  516. will fail. If this is a hard constraint for you, please let us know by opening an
  517. issue on [Github](https://github.com/huggingface/huggingface_hub).
  518. </Tip>
  519. """
  520. yield from _http_backoff_base(
  521. method=method,
  522. url=url,
  523. max_retries=max_retries,
  524. base_wait_time=base_wait_time,
  525. max_wait_time=max_wait_time,
  526. retry_on_exceptions=retry_on_exceptions,
  527. retry_on_status_codes=retry_on_status_codes,
  528. stream=True,
  529. **kwargs,
  530. )
  531. def _httpx_follow_relative_redirects_with_backoff(
  532. method: HTTP_METHOD_T, url: str, *, retry_on_errors: bool = False, **httpx_kwargs
  533. ) -> httpx.Response:
  534. """Perform an HTTP request with backoff and follow relative redirects only.
  535. Used to fetch HEAD /resolve on repo or bucket files.
  536. This is useful to follow a redirection to a renamed repository without following redirection to a CDN.
  537. A backoff mechanism retries the HTTP call on errors (429, 5xx, timeout, network errors).
  538. Args:
  539. method (`str`):
  540. HTTP method, such as 'GET' or 'HEAD'.
  541. url (`str`):
  542. The URL of the resource to fetch.
  543. retry_on_errors (`bool`, *optional*, defaults to `False`):
  544. Whether to retry on errors. If False, no retry is performed (fast fallback to local cache).
  545. If True, uses default retry behavior (429, 5xx, timeout, network errors).
  546. **httpx_kwargs (`dict`, *optional*):
  547. Params to pass to `httpx.request`.
  548. """
  549. # if `retry_on_errors=False`, disable all retries for fast fallback to cache
  550. no_retry_kwargs: dict[str, Any] = (
  551. {} if retry_on_errors else {"retry_on_exceptions": (), "retry_on_status_codes": ()}
  552. )
  553. while True:
  554. response = http_backoff(
  555. method=method,
  556. url=url,
  557. **httpx_kwargs,
  558. follow_redirects=False,
  559. **no_retry_kwargs,
  560. )
  561. hf_raise_for_status(response)
  562. # Check if response is a relative redirect
  563. if 300 <= response.status_code <= 399:
  564. parsed_target = urlparse(response.headers["Location"])
  565. if parsed_target.netloc == "":
  566. # Relative redirect -> update URL and retry
  567. url = urlparse(url)._replace(path=parsed_target.path).geturl()
  568. continue
  569. # Break if no relative redirect
  570. break
  571. return response
  572. def fix_hf_endpoint_in_url(url: str, endpoint: str | None) -> str:
  573. """Replace the default endpoint in a URL by a custom one.
  574. This is useful when using a proxy and the Hugging Face Hub returns a URL with the default endpoint.
  575. """
  576. endpoint = endpoint.rstrip("/") if endpoint else constants.ENDPOINT
  577. # check if a proxy has been set => if yes, update the returned URL to use the proxy
  578. if endpoint not in (constants._HF_DEFAULT_ENDPOINT, constants._HF_DEFAULT_STAGING_ENDPOINT):
  579. url = url.replace(constants._HF_DEFAULT_ENDPOINT, endpoint)
  580. url = url.replace(constants._HF_DEFAULT_STAGING_ENDPOINT, endpoint)
  581. return url
  582. def hf_raise_for_status(response: httpx.Response, endpoint_name: str | None = None) -> None:
  583. """
  584. Internal version of `response.raise_for_status()` that will refine a potential HTTPError.
  585. Raised exception will be an instance of [`~errors.HfHubHTTPError`].
  586. This helper is meant to be the unique method to raise_for_status when making a call to the Hugging Face Hub.
  587. Args:
  588. response (`Response`):
  589. Response from the server.
  590. endpoint_name (`str`, *optional*):
  591. Name of the endpoint that has been called. If provided, the error message will be more complete.
  592. > [!WARNING]
  593. > Raises when the request has failed:
  594. >
  595. > - [`~utils.RepositoryNotFoundError`]
  596. > If the repository to download from cannot be found. This may be because it
  597. > doesn't exist, because `repo_type` is not set correctly, or because the repo
  598. > is `private` and you do not have access.
  599. > - [`~utils.GatedRepoError`]
  600. > If the repository exists but is gated and the user is not on the authorized
  601. > list.
  602. > - [`~utils.RevisionNotFoundError`]
  603. > If the repository exists but the revision couldn't be found.
  604. > - [`~utils.EntryNotFoundError`]
  605. > If the repository exists but the entry (e.g. the requested file) couldn't be
  606. > find.
  607. > - [`~utils.BadRequestError`]
  608. > If request failed with a HTTP 400 BadRequest error.
  609. > - [`~utils.HfHubHTTPError`]
  610. > If request failed for a reason not listed above.
  611. """
  612. try:
  613. _warn_on_warning_headers(response)
  614. except Exception:
  615. # Never raise on warning parsing
  616. logger.debug("Failed to parse warning headers", exc_info=True)
  617. try:
  618. response.raise_for_status()
  619. except httpx.HTTPStatusError as e:
  620. if response.status_code // 100 == 3:
  621. return # Do not raise on redirects to stay consistent with `requests`
  622. error_code = response.headers.get("X-Error-Code")
  623. error_message = response.headers.get("X-Error-Message")
  624. # Parse repo info from request URL (used to enrich errors below)
  625. request_url = (
  626. str(response.request.url) if response.request is not None and response.request.url is not None else None
  627. )
  628. repo_type, repo_id = _parse_repo_info_from_url(request_url) if request_url else (None, None)
  629. if error_code == "RevisionNotFound":
  630. message = f"{response.status_code} Client Error." + "\n\n" + f"Revision Not Found for url: {response.url}."
  631. raise _format(RevisionNotFoundError, message, response, repo_type=repo_type, repo_id=repo_id) from e
  632. elif error_code == "EntryNotFound":
  633. message = f"{response.status_code} Client Error." + "\n\n" + f"Entry Not Found for url: {response.url}."
  634. raise _format(RemoteEntryNotFoundError, message, response, repo_type=repo_type, repo_id=repo_id) from e
  635. elif error_code == "GatedRepo":
  636. message = (
  637. f"{response.status_code} Client Error." + "\n\n" + f"Cannot access gated repo for url {response.url}."
  638. )
  639. raise _format(GatedRepoError, message, response, repo_type=repo_type, repo_id=repo_id) from e
  640. elif error_message == "Access to this resource is disabled.":
  641. message = (
  642. f"{response.status_code} Client Error."
  643. + "\n\n"
  644. + f"Cannot access repository for url {response.url}."
  645. + "\n"
  646. + "Access to this resource is disabled."
  647. )
  648. raise _format(DisabledRepoError, message, response) from e
  649. elif (
  650. error_code == "RepoNotFound"
  651. and request_url is not None
  652. and BUCKET_API_REGEX.search(request_url) is not None
  653. ):
  654. message = (
  655. f"{response.status_code} Client Error."
  656. + "\n\n"
  657. + f"Bucket Not Found for url: {response.url}."
  658. + "\nPlease make sure you specified the correct bucket id (namespace/name)."
  659. + "\nIf the bucket is private, make sure you are authenticated and your token has the required permissions."
  660. )
  661. raise _format(
  662. BucketNotFoundError, message, response, bucket_id=_parse_bucket_id_from_url(request_url)
  663. ) from e
  664. elif error_code == "RepoNotFound" or (
  665. response.status_code == 401
  666. and error_message != "Invalid credentials in Authorization header"
  667. and request_url is not None
  668. and REPO_API_REGEX.search(request_url) is not None
  669. ):
  670. # 401 is misleading as it is returned for:
  671. # - private and gated repos if user is not authenticated
  672. # - missing repos
  673. # => for now, we process them as `RepoNotFound` anyway.
  674. # See https://gist.github.com/Wauplin/46c27ad266b15998ce56a6603796f0b9
  675. message = (
  676. f"{response.status_code} Client Error."
  677. + "\n\n"
  678. + f"Repository Not Found for url: {response.url}."
  679. + "\nPlease make sure you specified the correct `repo_id` and"
  680. " `repo_type`.\nIf you are trying to access a private or gated repo,"
  681. " make sure you are authenticated and your token has the required permissions."
  682. + "\nFor more details, see https://huggingface.co/docs/huggingface_hub/authentication"
  683. )
  684. raise _format(RepositoryNotFoundError, message, response, repo_type=repo_type, repo_id=repo_id) from e
  685. elif response.status_code == 400:
  686. message = (
  687. f"\n\nBad request for {endpoint_name} endpoint:" if endpoint_name is not None else "\n\nBad request:"
  688. )
  689. raise _format(BadRequestError, message, response) from e
  690. elif response.status_code == 403:
  691. message = (
  692. f"\n\n{response.status_code} Forbidden: {error_message}."
  693. + f"\nCannot access content at: {response.url}."
  694. + "\nMake sure your token has the correct permissions."
  695. )
  696. raise _format(HfHubHTTPError, message, response) from e
  697. elif response.status_code == 429:
  698. ratelimit_info = parse_ratelimit_headers(response.headers)
  699. if ratelimit_info is not None:
  700. message = (
  701. f"\n\n429 Too Many Requests: you have reached your '{ratelimit_info.resource_type}' rate limit."
  702. )
  703. message += f"\nRetry after {ratelimit_info.reset_in_seconds} seconds"
  704. if ratelimit_info.limit is not None and ratelimit_info.window_seconds is not None:
  705. message += (
  706. f" ({ratelimit_info.remaining}/{ratelimit_info.limit} requests remaining"
  707. f" in current {ratelimit_info.window_seconds}s window)."
  708. )
  709. else:
  710. message += "."
  711. message += f"\nUrl: {response.url}."
  712. else:
  713. message = f"\n\n429 Too Many Requests for url: {response.url}."
  714. raise _format(HfHubHTTPError, message, response) from e
  715. elif response.status_code == 416:
  716. range_header = response.request.headers.get("Range")
  717. message = f"{e}. Requested range: {range_header}. Content-Range: {response.headers.get('Content-Range')}."
  718. raise _format(HfHubHTTPError, message, response) from e
  719. # Convert `HTTPError` into a `HfHubHTTPError` to display request information
  720. # as well (request id and/or server error message)
  721. raise _format(HfHubHTTPError, str(e), response) from e
  722. _WARNED_TOPICS = set()
  723. def _warn_on_warning_headers(response: httpx.Response) -> None:
  724. """
  725. Emit warnings if warning headers are present in the HTTP response.
  726. Expected header format: 'X-HF-Warning: topic; message'
  727. Only the first warning for each topic will be shown. Topic is optional and can be empty. Note that several warning
  728. headers can be present in a single response.
  729. Args:
  730. response (`httpx.Response`):
  731. The HTTP response to check for warning headers.
  732. """
  733. server_warnings = response.headers.get_list("X-HF-Warning")
  734. for server_warning in server_warnings:
  735. topic, message = server_warning.split(";", 1) if ";" in server_warning else ("", server_warning)
  736. topic = topic.strip()
  737. if topic not in _WARNED_TOPICS:
  738. message = message.strip()
  739. if message:
  740. _WARNED_TOPICS.add(topic)
  741. logger.warning(message)
  742. _HfHubHTTPErrorT = TypeVar("_HfHubHTTPErrorT", bound=HfHubHTTPError)
  743. def _format(
  744. error_type: type[_HfHubHTTPErrorT], custom_message: str, response: httpx.Response, **attrs: Any
  745. ) -> _HfHubHTTPErrorT:
  746. server_errors = []
  747. # Retrieve server error from header
  748. from_headers = response.headers.get("X-Error-Message")
  749. if from_headers is not None:
  750. server_errors.append(from_headers)
  751. # Retrieve server error from body
  752. try:
  753. # Case errors are returned in a JSON format
  754. try:
  755. data = response.json()
  756. except httpx.ResponseNotRead:
  757. try:
  758. response.read() # In case of streaming response, we need to read the response first
  759. data = response.json()
  760. except RuntimeError:
  761. # In case of async streaming response, we can't read the stream here.
  762. # In practice if user is using the default async client from `get_async_client`, the stream will have
  763. # already been read in the async event hook `async_hf_response_event_hook`.
  764. #
  765. # Here, we are skipping reading the response to avoid RuntimeError but it happens only if async + stream + used httpx.AsyncClient directly.
  766. data = {}
  767. error = data.get("error")
  768. if error is not None:
  769. if isinstance(error, list):
  770. # Case {'error': ['my error 1', 'my error 2']}
  771. server_errors.extend(error)
  772. else:
  773. # Case {'error': 'my error'}
  774. server_errors.append(error)
  775. errors = data.get("errors")
  776. if errors is not None:
  777. # Case {'errors': [{'message': 'my error 1'}, {'message': 'my error 2'}]}
  778. for error in errors:
  779. if "message" in error:
  780. server_errors.append(error["message"])
  781. except json.JSONDecodeError:
  782. # If content is not JSON and not HTML, append the text
  783. content_type = response.headers.get("Content-Type", "")
  784. if response.text and "html" not in content_type.lower():
  785. server_errors.append(response.text)
  786. # Strip all server messages
  787. server_errors = [str(line).strip() for line in server_errors if str(line).strip()]
  788. # Deduplicate server messages (keep order)
  789. # taken from https://stackoverflow.com/a/17016257
  790. server_errors = list(dict.fromkeys(server_errors))
  791. # Format server error
  792. server_message = "\n".join(server_errors)
  793. # Add server error to custom message
  794. final_error_message = custom_message
  795. if server_message and server_message.lower() not in custom_message.lower():
  796. if "\n\n" in custom_message:
  797. final_error_message += "\n" + server_message
  798. else:
  799. final_error_message += "\n\n" + server_message
  800. # Prepare Request ID message
  801. request_id = ""
  802. request_id_message = ""
  803. for header, label in (
  804. (X_REQUEST_ID, "Request ID"),
  805. (X_AMZN_TRACE_ID, "Amzn Trace ID"),
  806. (X_AMZ_CF_ID, "Amz CF ID"),
  807. ):
  808. value = response.headers.get(header)
  809. if value:
  810. request_id = str(value)
  811. request_id_message = f" ({label}: {value})"
  812. break
  813. # Add Request ID
  814. if request_id and request_id.lower() not in final_error_message.lower():
  815. if "\n" in final_error_message:
  816. newline_index = final_error_message.index("\n")
  817. final_error_message = (
  818. final_error_message[:newline_index] + request_id_message + final_error_message[newline_index:]
  819. )
  820. else:
  821. final_error_message += request_id_message
  822. # Return
  823. err = error_type(final_error_message.strip(), response=response, server_message=server_message or None)
  824. for k, v in attrs.items():
  825. setattr(err, k, v)
  826. return err
  827. def _curlify(request: httpx.Request) -> str:
  828. """Convert a `httpx.Request` into a curl command (str).
  829. Used for debug purposes only.
  830. Implementation vendored from https://github.com/ofw/curlify/blob/master/curlify.py.
  831. MIT License Copyright (c) 2016 Egor.
  832. """
  833. parts: list[tuple[Any, Any]] = [
  834. ("curl", None),
  835. ("-X", request.method),
  836. ]
  837. for k, v in sorted(request.headers.items()):
  838. if k.lower() == "authorization":
  839. v = "<TOKEN>" # Hide authorization header, no matter its value (can be Bearer, Key, etc.)
  840. parts += [("-H", f"{k}: {v}")]
  841. body: str | None = None
  842. try:
  843. if request.content is not None:
  844. body = request.content.decode("utf-8", errors="ignore")
  845. if len(body) > 1000:
  846. body = f"{body[:1000]} ... [truncated]"
  847. except httpx.RequestNotRead:
  848. body = "<streaming body>"
  849. if body is not None:
  850. parts += [("-d", body.replace("\n", ""))]
  851. parts += [(None, request.url)]
  852. flat_parts = []
  853. for k, v in parts:
  854. if k:
  855. flat_parts.append(quote(str(k)))
  856. if v:
  857. flat_parts.append(quote(str(v)))
  858. return " ".join(flat_parts)
  859. # Regex to parse HTTP Range header
  860. RANGE_REGEX = re.compile(r"^\s*bytes\s*=\s*(\d*)\s*-\s*(\d*)\s*$", re.IGNORECASE)
  861. def _adjust_range_header(original_range: str | None, resume_size: int) -> str | None:
  862. """
  863. Adjust HTTP Range header to account for resume position.
  864. """
  865. if not original_range:
  866. return f"bytes={resume_size}-"
  867. if "," in original_range:
  868. raise ValueError(f"Multiple ranges detected - {original_range!r}, not supported yet.")
  869. match = RANGE_REGEX.match(original_range)
  870. if not match:
  871. raise RuntimeError(f"Invalid range format - {original_range!r}.")
  872. start, end = match.groups()
  873. if not start:
  874. if not end:
  875. raise RuntimeError(f"Invalid range format - {original_range!r}.")
  876. new_suffix = int(end) - resume_size
  877. new_range = f"bytes=-{new_suffix}"
  878. if new_suffix <= 0:
  879. raise RuntimeError(f"Empty new range - {new_range!r}.")
  880. return new_range
  881. start = int(start)
  882. new_start = start + resume_size
  883. if end:
  884. end = int(end)
  885. new_range = f"bytes={new_start}-{end}"
  886. if new_start > end:
  887. raise RuntimeError(f"Empty new range - {new_range!r}.")
  888. return new_range
  889. return f"bytes={new_start}-"