m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

494 lines
18 KiB

6 months ago
  1. # SPDX-FileCopyrightText: 2015 Eric Larson
  2. #
  3. # SPDX-License-Identifier: Apache-2.0
  4. """
  5. The httplib2 algorithms ported for use with requests.
  6. """
  7. from __future__ import annotations
  8. import calendar
  9. import logging
  10. import re
  11. import time
  12. from email.utils import parsedate_tz
  13. from typing import TYPE_CHECKING, Collection, Mapping
  14. from pip._vendor.requests.structures import CaseInsensitiveDict
  15. from pip._vendor.cachecontrol.cache import DictCache, SeparateBodyBaseCache
  16. from pip._vendor.cachecontrol.serialize import Serializer
  17. if TYPE_CHECKING:
  18. from typing import Literal
  19. from pip._vendor.requests import PreparedRequest
  20. from pip._vendor.urllib3 import HTTPResponse
  21. from pip._vendor.cachecontrol.cache import BaseCache
  22. logger = logging.getLogger(__name__)
  23. URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
  24. PERMANENT_REDIRECT_STATUSES = (301, 308)
  25. def parse_uri(uri: str) -> tuple[str, str, str, str, str]:
  26. """Parses a URI using the regex given in Appendix B of RFC 3986.
  27. (scheme, authority, path, query, fragment) = parse_uri(uri)
  28. """
  29. match = URI.match(uri)
  30. assert match is not None
  31. groups = match.groups()
  32. return (groups[1], groups[3], groups[4], groups[6], groups[8])
  33. class CacheController:
  34. """An interface to see if request should cached or not."""
  35. def __init__(
  36. self,
  37. cache: BaseCache | None = None,
  38. cache_etags: bool = True,
  39. serializer: Serializer | None = None,
  40. status_codes: Collection[int] | None = None,
  41. ):
  42. self.cache = DictCache() if cache is None else cache
  43. self.cache_etags = cache_etags
  44. self.serializer = serializer or Serializer()
  45. self.cacheable_status_codes = status_codes or (200, 203, 300, 301, 308)
  46. @classmethod
  47. def _urlnorm(cls, uri: str) -> str:
  48. """Normalize the URL to create a safe key for the cache"""
  49. (scheme, authority, path, query, fragment) = parse_uri(uri)
  50. if not scheme or not authority:
  51. raise Exception("Only absolute URIs are allowed. uri = %s" % uri)
  52. scheme = scheme.lower()
  53. authority = authority.lower()
  54. if not path:
  55. path = "/"
  56. # Could do syntax based normalization of the URI before
  57. # computing the digest. See Section 6.2.2 of Std 66.
  58. request_uri = query and "?".join([path, query]) or path
  59. defrag_uri = scheme + "://" + authority + request_uri
  60. return defrag_uri
  61. @classmethod
  62. def cache_url(cls, uri: str) -> str:
  63. return cls._urlnorm(uri)
  64. def parse_cache_control(self, headers: Mapping[str, str]) -> dict[str, int | None]:
  65. known_directives = {
  66. # https://tools.ietf.org/html/rfc7234#section-5.2
  67. "max-age": (int, True),
  68. "max-stale": (int, False),
  69. "min-fresh": (int, True),
  70. "no-cache": (None, False),
  71. "no-store": (None, False),
  72. "no-transform": (None, False),
  73. "only-if-cached": (None, False),
  74. "must-revalidate": (None, False),
  75. "public": (None, False),
  76. "private": (None, False),
  77. "proxy-revalidate": (None, False),
  78. "s-maxage": (int, True),
  79. }
  80. cc_headers = headers.get("cache-control", headers.get("Cache-Control", ""))
  81. retval: dict[str, int | None] = {}
  82. for cc_directive in cc_headers.split(","):
  83. if not cc_directive.strip():
  84. continue
  85. parts = cc_directive.split("=", 1)
  86. directive = parts[0].strip()
  87. try:
  88. typ, required = known_directives[directive]
  89. except KeyError:
  90. logger.debug("Ignoring unknown cache-control directive: %s", directive)
  91. continue
  92. if not typ or not required:
  93. retval[directive] = None
  94. if typ:
  95. try:
  96. retval[directive] = typ(parts[1].strip())
  97. except IndexError:
  98. if required:
  99. logger.debug(
  100. "Missing value for cache-control " "directive: %s",
  101. directive,
  102. )
  103. except ValueError:
  104. logger.debug(
  105. "Invalid value for cache-control directive " "%s, must be %s",
  106. directive,
  107. typ.__name__,
  108. )
  109. return retval
  110. def _load_from_cache(self, request: PreparedRequest) -> HTTPResponse | None:
  111. """
  112. Load a cached response, or return None if it's not available.
  113. """
  114. cache_url = request.url
  115. assert cache_url is not None
  116. cache_data = self.cache.get(cache_url)
  117. if cache_data is None:
  118. logger.debug("No cache entry available")
  119. return None
  120. if isinstance(self.cache, SeparateBodyBaseCache):
  121. body_file = self.cache.get_body(cache_url)
  122. else:
  123. body_file = None
  124. result = self.serializer.loads(request, cache_data, body_file)
  125. if result is None:
  126. logger.warning("Cache entry deserialization failed, entry ignored")
  127. return result
  128. def cached_request(self, request: PreparedRequest) -> HTTPResponse | Literal[False]:
  129. """
  130. Return a cached response if it exists in the cache, otherwise
  131. return False.
  132. """
  133. assert request.url is not None
  134. cache_url = self.cache_url(request.url)
  135. logger.debug('Looking up "%s" in the cache', cache_url)
  136. cc = self.parse_cache_control(request.headers)
  137. # Bail out if the request insists on fresh data
  138. if "no-cache" in cc:
  139. logger.debug('Request header has "no-cache", cache bypassed')
  140. return False
  141. if "max-age" in cc and cc["max-age"] == 0:
  142. logger.debug('Request header has "max_age" as 0, cache bypassed')
  143. return False
  144. # Check whether we can load the response from the cache:
  145. resp = self._load_from_cache(request)
  146. if not resp:
  147. return False
  148. # If we have a cached permanent redirect, return it immediately. We
  149. # don't need to test our response for other headers b/c it is
  150. # intrinsically "cacheable" as it is Permanent.
  151. #
  152. # See:
  153. # https://tools.ietf.org/html/rfc7231#section-6.4.2
  154. #
  155. # Client can try to refresh the value by repeating the request
  156. # with cache busting headers as usual (ie no-cache).
  157. if int(resp.status) in PERMANENT_REDIRECT_STATUSES:
  158. msg = (
  159. "Returning cached permanent redirect response "
  160. "(ignoring date and etag information)"
  161. )
  162. logger.debug(msg)
  163. return resp
  164. headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(resp.headers)
  165. if not headers or "date" not in headers:
  166. if "etag" not in headers:
  167. # Without date or etag, the cached response can never be used
  168. # and should be deleted.
  169. logger.debug("Purging cached response: no date or etag")
  170. self.cache.delete(cache_url)
  171. logger.debug("Ignoring cached response: no date")
  172. return False
  173. now = time.time()
  174. time_tuple = parsedate_tz(headers["date"])
  175. assert time_tuple is not None
  176. date = calendar.timegm(time_tuple[:6])
  177. current_age = max(0, now - date)
  178. logger.debug("Current age based on date: %i", current_age)
  179. # TODO: There is an assumption that the result will be a
  180. # urllib3 response object. This may not be best since we
  181. # could probably avoid instantiating or constructing the
  182. # response until we know we need it.
  183. resp_cc = self.parse_cache_control(headers)
  184. # determine freshness
  185. freshness_lifetime = 0
  186. # Check the max-age pragma in the cache control header
  187. max_age = resp_cc.get("max-age")
  188. if max_age is not None:
  189. freshness_lifetime = max_age
  190. logger.debug("Freshness lifetime from max-age: %i", freshness_lifetime)
  191. # If there isn't a max-age, check for an expires header
  192. elif "expires" in headers:
  193. expires = parsedate_tz(headers["expires"])
  194. if expires is not None:
  195. expire_time = calendar.timegm(expires[:6]) - date
  196. freshness_lifetime = max(0, expire_time)
  197. logger.debug("Freshness lifetime from expires: %i", freshness_lifetime)
  198. # Determine if we are setting freshness limit in the
  199. # request. Note, this overrides what was in the response.
  200. max_age = cc.get("max-age")
  201. if max_age is not None:
  202. freshness_lifetime = max_age
  203. logger.debug(
  204. "Freshness lifetime from request max-age: %i", freshness_lifetime
  205. )
  206. min_fresh = cc.get("min-fresh")
  207. if min_fresh is not None:
  208. # adjust our current age by our min fresh
  209. current_age += min_fresh
  210. logger.debug("Adjusted current age from min-fresh: %i", current_age)
  211. # Return entry if it is fresh enough
  212. if freshness_lifetime > current_age:
  213. logger.debug('The response is "fresh", returning cached response')
  214. logger.debug("%i > %i", freshness_lifetime, current_age)
  215. return resp
  216. # we're not fresh. If we don't have an Etag, clear it out
  217. if "etag" not in headers:
  218. logger.debug('The cached response is "stale" with no etag, purging')
  219. self.cache.delete(cache_url)
  220. # return the original handler
  221. return False
  222. def conditional_headers(self, request: PreparedRequest) -> dict[str, str]:
  223. resp = self._load_from_cache(request)
  224. new_headers = {}
  225. if resp:
  226. headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(resp.headers)
  227. if "etag" in headers:
  228. new_headers["If-None-Match"] = headers["ETag"]
  229. if "last-modified" in headers:
  230. new_headers["If-Modified-Since"] = headers["Last-Modified"]
  231. return new_headers
  232. def _cache_set(
  233. self,
  234. cache_url: str,
  235. request: PreparedRequest,
  236. response: HTTPResponse,
  237. body: bytes | None = None,
  238. expires_time: int | None = None,
  239. ) -> None:
  240. """
  241. Store the data in the cache.
  242. """
  243. if isinstance(self.cache, SeparateBodyBaseCache):
  244. # We pass in the body separately; just put a placeholder empty
  245. # string in the metadata.
  246. self.cache.set(
  247. cache_url,
  248. self.serializer.dumps(request, response, b""),
  249. expires=expires_time,
  250. )
  251. # body is None can happen when, for example, we're only updating
  252. # headers, as is the case in update_cached_response().
  253. if body is not None:
  254. self.cache.set_body(cache_url, body)
  255. else:
  256. self.cache.set(
  257. cache_url,
  258. self.serializer.dumps(request, response, body),
  259. expires=expires_time,
  260. )
  261. def cache_response(
  262. self,
  263. request: PreparedRequest,
  264. response: HTTPResponse,
  265. body: bytes | None = None,
  266. status_codes: Collection[int] | None = None,
  267. ) -> None:
  268. """
  269. Algorithm for caching requests.
  270. This assumes a requests Response object.
  271. """
  272. # From httplib2: Don't cache 206's since we aren't going to
  273. # handle byte range requests
  274. cacheable_status_codes = status_codes or self.cacheable_status_codes
  275. if response.status not in cacheable_status_codes:
  276. logger.debug(
  277. "Status code %s not in %s", response.status, cacheable_status_codes
  278. )
  279. return
  280. response_headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(
  281. response.headers
  282. )
  283. if "date" in response_headers:
  284. time_tuple = parsedate_tz(response_headers["date"])
  285. assert time_tuple is not None
  286. date = calendar.timegm(time_tuple[:6])
  287. else:
  288. date = 0
  289. # If we've been given a body, our response has a Content-Length, that
  290. # Content-Length is valid then we can check to see if the body we've
  291. # been given matches the expected size, and if it doesn't we'll just
  292. # skip trying to cache it.
  293. if (
  294. body is not None
  295. and "content-length" in response_headers
  296. and response_headers["content-length"].isdigit()
  297. and int(response_headers["content-length"]) != len(body)
  298. ):
  299. return
  300. cc_req = self.parse_cache_control(request.headers)
  301. cc = self.parse_cache_control(response_headers)
  302. assert request.url is not None
  303. cache_url = self.cache_url(request.url)
  304. logger.debug('Updating cache with response from "%s"', cache_url)
  305. # Delete it from the cache if we happen to have it stored there
  306. no_store = False
  307. if "no-store" in cc:
  308. no_store = True
  309. logger.debug('Response header has "no-store"')
  310. if "no-store" in cc_req:
  311. no_store = True
  312. logger.debug('Request header has "no-store"')
  313. if no_store and self.cache.get(cache_url):
  314. logger.debug('Purging existing cache entry to honor "no-store"')
  315. self.cache.delete(cache_url)
  316. if no_store:
  317. return
  318. # https://tools.ietf.org/html/rfc7234#section-4.1:
  319. # A Vary header field-value of "*" always fails to match.
  320. # Storing such a response leads to a deserialization warning
  321. # during cache lookup and is not allowed to ever be served,
  322. # so storing it can be avoided.
  323. if "*" in response_headers.get("vary", ""):
  324. logger.debug('Response header has "Vary: *"')
  325. return
  326. # If we've been given an etag, then keep the response
  327. if self.cache_etags and "etag" in response_headers:
  328. expires_time = 0
  329. if response_headers.get("expires"):
  330. expires = parsedate_tz(response_headers["expires"])
  331. if expires is not None:
  332. expires_time = calendar.timegm(expires[:6]) - date
  333. expires_time = max(expires_time, 14 * 86400)
  334. logger.debug(f"etag object cached for {expires_time} seconds")
  335. logger.debug("Caching due to etag")
  336. self._cache_set(cache_url, request, response, body, expires_time)
  337. # Add to the cache any permanent redirects. We do this before looking
  338. # that the Date headers.
  339. elif int(response.status) in PERMANENT_REDIRECT_STATUSES:
  340. logger.debug("Caching permanent redirect")
  341. self._cache_set(cache_url, request, response, b"")
  342. # Add to the cache if the response headers demand it. If there
  343. # is no date header then we can't do anything about expiring
  344. # the cache.
  345. elif "date" in response_headers:
  346. time_tuple = parsedate_tz(response_headers["date"])
  347. assert time_tuple is not None
  348. date = calendar.timegm(time_tuple[:6])
  349. # cache when there is a max-age > 0
  350. max_age = cc.get("max-age")
  351. if max_age is not None and max_age > 0:
  352. logger.debug("Caching b/c date exists and max-age > 0")
  353. expires_time = max_age
  354. self._cache_set(
  355. cache_url,
  356. request,
  357. response,
  358. body,
  359. expires_time,
  360. )
  361. # If the request can expire, it means we should cache it
  362. # in the meantime.
  363. elif "expires" in response_headers:
  364. if response_headers["expires"]:
  365. expires = parsedate_tz(response_headers["expires"])
  366. if expires is not None:
  367. expires_time = calendar.timegm(expires[:6]) - date
  368. else:
  369. expires_time = None
  370. logger.debug(
  371. "Caching b/c of expires header. expires in {} seconds".format(
  372. expires_time
  373. )
  374. )
  375. self._cache_set(
  376. cache_url,
  377. request,
  378. response,
  379. body,
  380. expires_time,
  381. )
  382. def update_cached_response(
  383. self, request: PreparedRequest, response: HTTPResponse
  384. ) -> HTTPResponse:
  385. """On a 304 we will get a new set of headers that we want to
  386. update our cached value with, assuming we have one.
  387. This should only ever be called when we've sent an ETag and
  388. gotten a 304 as the response.
  389. """
  390. assert request.url is not None
  391. cache_url = self.cache_url(request.url)
  392. cached_response = self._load_from_cache(request)
  393. if not cached_response:
  394. # we didn't have a cached response
  395. return response
  396. # Lets update our headers with the headers from the new request:
  397. # http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-26#section-4.1
  398. #
  399. # The server isn't supposed to send headers that would make
  400. # the cached body invalid. But... just in case, we'll be sure
  401. # to strip out ones we know that might be problmatic due to
  402. # typical assumptions.
  403. excluded_headers = ["content-length"]
  404. cached_response.headers.update(
  405. {
  406. k: v
  407. for k, v in response.headers.items() # type: ignore[no-untyped-call]
  408. if k.lower() not in excluded_headers
  409. }
  410. )
  411. # we want a 200 b/c we have content via the cache
  412. cached_response.status = 200
  413. # update our cache
  414. self._cache_set(cache_url, request, cached_response)
  415. return cached_response