_collections.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. from __future__ import annotations
  2. import typing
  3. from collections import OrderedDict
  4. from enum import Enum, auto
  5. from threading import RLock
  6. if typing.TYPE_CHECKING:
  7. # We can only import Protocol if TYPE_CHECKING because it's a development
  8. # dependency, and is not available at runtime.
  9. from typing import Protocol
  10. from typing_extensions import Self
  11. class HasGettableStringKeys(Protocol):
  12. def keys(self) -> typing.Iterator[str]:
  13. ...
  14. def __getitem__(self, key: str) -> str:
  15. ...
  16. __all__ = ["RecentlyUsedContainer", "HTTPHeaderDict"]
  17. # Key type
  18. _KT = typing.TypeVar("_KT")
  19. # Value type
  20. _VT = typing.TypeVar("_VT")
  21. # Default type
  22. _DT = typing.TypeVar("_DT")
  23. ValidHTTPHeaderSource = typing.Union[
  24. "HTTPHeaderDict",
  25. typing.Mapping[str, str],
  26. typing.Iterable[typing.Tuple[str, str]],
  27. "HasGettableStringKeys",
  28. ]
  29. class _Sentinel(Enum):
  30. not_passed = auto()
  31. def ensure_can_construct_http_header_dict(
  32. potential: object,
  33. ) -> ValidHTTPHeaderSource | None:
  34. if isinstance(potential, HTTPHeaderDict):
  35. return potential
  36. elif isinstance(potential, typing.Mapping):
  37. # Full runtime checking of the contents of a Mapping is expensive, so for the
  38. # purposes of typechecking, we assume that any Mapping is the right shape.
  39. return typing.cast(typing.Mapping[str, str], potential)
  40. elif isinstance(potential, typing.Iterable):
  41. # Similarly to Mapping, full runtime checking of the contents of an Iterable is
  42. # expensive, so for the purposes of typechecking, we assume that any Iterable
  43. # is the right shape.
  44. return typing.cast(typing.Iterable[typing.Tuple[str, str]], potential)
  45. elif hasattr(potential, "keys") and hasattr(potential, "__getitem__"):
  46. return typing.cast("HasGettableStringKeys", potential)
  47. else:
  48. return None
  49. class RecentlyUsedContainer(typing.Generic[_KT, _VT], typing.MutableMapping[_KT, _VT]):
  50. """
  51. Provides a thread-safe dict-like container which maintains up to
  52. ``maxsize`` keys while throwing away the least-recently-used keys beyond
  53. ``maxsize``.
  54. :param maxsize:
  55. Maximum number of recent elements to retain.
  56. :param dispose_func:
  57. Every time an item is evicted from the container,
  58. ``dispose_func(value)`` is called. Callback which will get called
  59. """
  60. _container: typing.OrderedDict[_KT, _VT]
  61. _maxsize: int
  62. dispose_func: typing.Callable[[_VT], None] | None
  63. lock: RLock
  64. def __init__(
  65. self,
  66. maxsize: int = 10,
  67. dispose_func: typing.Callable[[_VT], None] | None = None,
  68. ) -> None:
  69. super().__init__()
  70. self._maxsize = maxsize
  71. self.dispose_func = dispose_func
  72. self._container = OrderedDict()
  73. self.lock = RLock()
  74. def __getitem__(self, key: _KT) -> _VT:
  75. # Re-insert the item, moving it to the end of the eviction line.
  76. with self.lock:
  77. item = self._container.pop(key)
  78. self._container[key] = item
  79. return item
  80. def __setitem__(self, key: _KT, value: _VT) -> None:
  81. evicted_item = None
  82. with self.lock:
  83. # Possibly evict the existing value of 'key'
  84. try:
  85. # If the key exists, we'll overwrite it, which won't change the
  86. # size of the pool. Because accessing a key should move it to
  87. # the end of the eviction line, we pop it out first.
  88. evicted_item = key, self._container.pop(key)
  89. self._container[key] = value
  90. except KeyError:
  91. # When the key does not exist, we insert the value first so that
  92. # evicting works in all cases, including when self._maxsize is 0
  93. self._container[key] = value
  94. if len(self._container) > self._maxsize:
  95. # If we didn't evict an existing value, and we've hit our maximum
  96. # size, then we have to evict the least recently used item from
  97. # the beginning of the container.
  98. evicted_item = self._container.popitem(last=False)
  99. # After releasing the lock on the pool, dispose of any evicted value.
  100. if evicted_item is not None and self.dispose_func:
  101. _, evicted_value = evicted_item
  102. self.dispose_func(evicted_value)
  103. def __delitem__(self, key: _KT) -> None:
  104. with self.lock:
  105. value = self._container.pop(key)
  106. if self.dispose_func:
  107. self.dispose_func(value)
  108. def __len__(self) -> int:
  109. with self.lock:
  110. return len(self._container)
  111. def __iter__(self) -> typing.NoReturn:
  112. raise NotImplementedError(
  113. "Iteration over this class is unlikely to be threadsafe."
  114. )
  115. def clear(self) -> None:
  116. with self.lock:
  117. # Copy pointers to all values, then wipe the mapping
  118. values = list(self._container.values())
  119. self._container.clear()
  120. if self.dispose_func:
  121. for value in values:
  122. self.dispose_func(value)
  123. def keys(self) -> set[_KT]: # type: ignore[override]
  124. with self.lock:
  125. return set(self._container.keys())
  126. class HTTPHeaderDictItemView(typing.Set[typing.Tuple[str, str]]):
  127. """
  128. HTTPHeaderDict is unusual for a Mapping[str, str] in that it has two modes of
  129. address.
  130. If we directly try to get an item with a particular name, we will get a string
  131. back that is the concatenated version of all the values:
  132. >>> d['X-Header-Name']
  133. 'Value1, Value2, Value3'
  134. However, if we iterate over an HTTPHeaderDict's items, we will optionally combine
  135. these values based on whether combine=True was called when building up the dictionary
  136. >>> d = HTTPHeaderDict({"A": "1", "B": "foo"})
  137. >>> d.add("A", "2", combine=True)
  138. >>> d.add("B", "bar")
  139. >>> list(d.items())
  140. [
  141. ('A', '1, 2'),
  142. ('B', 'foo'),
  143. ('B', 'bar'),
  144. ]
  145. This class conforms to the interface required by the MutableMapping ABC while
  146. also giving us the nonstandard iteration behavior we want; items with duplicate
  147. keys, ordered by time of first insertion.
  148. """
  149. _headers: HTTPHeaderDict
  150. def __init__(self, headers: HTTPHeaderDict) -> None:
  151. self._headers = headers
  152. def __len__(self) -> int:
  153. return len(list(self._headers.iteritems()))
  154. def __iter__(self) -> typing.Iterator[tuple[str, str]]:
  155. return self._headers.iteritems()
  156. def __contains__(self, item: object) -> bool:
  157. if isinstance(item, tuple) and len(item) == 2:
  158. passed_key, passed_val = item
  159. if isinstance(passed_key, str) and isinstance(passed_val, str):
  160. return self._headers._has_value_for_header(passed_key, passed_val)
  161. return False
  162. class HTTPHeaderDict(typing.MutableMapping[str, str]):
  163. """
  164. :param headers:
  165. An iterable of field-value pairs. Must not contain multiple field names
  166. when compared case-insensitively.
  167. :param kwargs:
  168. Additional field-value pairs to pass in to ``dict.update``.
  169. A ``dict`` like container for storing HTTP Headers.
  170. Field names are stored and compared case-insensitively in compliance with
  171. RFC 7230. Iteration provides the first case-sensitive key seen for each
  172. case-insensitive pair.
  173. Using ``__setitem__`` syntax overwrites fields that compare equal
  174. case-insensitively in order to maintain ``dict``'s api. For fields that
  175. compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``
  176. in a loop.
  177. If multiple fields that are equal case-insensitively are passed to the
  178. constructor or ``.update``, the behavior is undefined and some will be
  179. lost.
  180. >>> headers = HTTPHeaderDict()
  181. >>> headers.add('Set-Cookie', 'foo=bar')
  182. >>> headers.add('set-cookie', 'baz=quxx')
  183. >>> headers['content-length'] = '7'
  184. >>> headers['SET-cookie']
  185. 'foo=bar, baz=quxx'
  186. >>> headers['Content-Length']
  187. '7'
  188. """
  189. _container: typing.MutableMapping[str, list[str]]
  190. def __init__(self, headers: ValidHTTPHeaderSource | None = None, **kwargs: str):
  191. super().__init__()
  192. self._container = {} # 'dict' is insert-ordered
  193. if headers is not None:
  194. if isinstance(headers, HTTPHeaderDict):
  195. self._copy_from(headers)
  196. else:
  197. self.extend(headers)
  198. if kwargs:
  199. self.extend(kwargs)
  200. def __setitem__(self, key: str, val: str) -> None:
  201. # avoid a bytes/str comparison by decoding before httplib
  202. if isinstance(key, bytes):
  203. key = key.decode("latin-1")
  204. self._container[key.lower()] = [key, val]
  205. def __getitem__(self, key: str) -> str:
  206. val = self._container[key.lower()]
  207. return ", ".join(val[1:])
  208. def __delitem__(self, key: str) -> None:
  209. del self._container[key.lower()]
  210. def __contains__(self, key: object) -> bool:
  211. if isinstance(key, str):
  212. return key.lower() in self._container
  213. return False
  214. def setdefault(self, key: str, default: str = "") -> str:
  215. return super().setdefault(key, default)
  216. def __eq__(self, other: object) -> bool:
  217. maybe_constructable = ensure_can_construct_http_header_dict(other)
  218. if maybe_constructable is None:
  219. return False
  220. else:
  221. other_as_http_header_dict = type(self)(maybe_constructable)
  222. return {k.lower(): v for k, v in self.itermerged()} == {
  223. k.lower(): v for k, v in other_as_http_header_dict.itermerged()
  224. }
  225. def __ne__(self, other: object) -> bool:
  226. return not self.__eq__(other)
  227. def __len__(self) -> int:
  228. return len(self._container)
  229. def __iter__(self) -> typing.Iterator[str]:
  230. # Only provide the originally cased names
  231. for vals in self._container.values():
  232. yield vals[0]
  233. def discard(self, key: str) -> None:
  234. try:
  235. del self[key]
  236. except KeyError:
  237. pass
  238. def add(self, key: str, val: str, *, combine: bool = False) -> None:
  239. """Adds a (name, value) pair, doesn't overwrite the value if it already
  240. exists.
  241. If this is called with combine=True, instead of adding a new header value
  242. as a distinct item during iteration, this will instead append the value to
  243. any existing header value with a comma. If no existing header value exists
  244. for the key, then the value will simply be added, ignoring the combine parameter.
  245. >>> headers = HTTPHeaderDict(foo='bar')
  246. >>> headers.add('Foo', 'baz')
  247. >>> headers['foo']
  248. 'bar, baz'
  249. >>> list(headers.items())
  250. [('foo', 'bar'), ('foo', 'baz')]
  251. >>> headers.add('foo', 'quz', combine=True)
  252. >>> list(headers.items())
  253. [('foo', 'bar, baz, quz')]
  254. """
  255. # avoid a bytes/str comparison by decoding before httplib
  256. if isinstance(key, bytes):
  257. key = key.decode("latin-1")
  258. key_lower = key.lower()
  259. new_vals = [key, val]
  260. # Keep the common case aka no item present as fast as possible
  261. vals = self._container.setdefault(key_lower, new_vals)
  262. if new_vals is not vals:
  263. # if there are values here, then there is at least the initial
  264. # key/value pair
  265. assert len(vals) >= 2
  266. if combine:
  267. vals[-1] = vals[-1] + ", " + val
  268. else:
  269. vals.append(val)
  270. def extend(self, *args: ValidHTTPHeaderSource, **kwargs: str) -> None:
  271. """Generic import function for any type of header-like object.
  272. Adapted version of MutableMapping.update in order to insert items
  273. with self.add instead of self.__setitem__
  274. """
  275. if len(args) > 1:
  276. raise TypeError(
  277. f"extend() takes at most 1 positional arguments ({len(args)} given)"
  278. )
  279. other = args[0] if len(args) >= 1 else ()
  280. if isinstance(other, HTTPHeaderDict):
  281. for key, val in other.iteritems():
  282. self.add(key, val)
  283. elif isinstance(other, typing.Mapping):
  284. for key, val in other.items():
  285. self.add(key, val)
  286. elif isinstance(other, typing.Iterable):
  287. other = typing.cast(typing.Iterable[typing.Tuple[str, str]], other)
  288. for key, value in other:
  289. self.add(key, value)
  290. elif hasattr(other, "keys") and hasattr(other, "__getitem__"):
  291. # THIS IS NOT A TYPESAFE BRANCH
  292. # In this branch, the object has a `keys` attr but is not a Mapping or any of
  293. # the other types indicated in the method signature. We do some stuff with
  294. # it as though it partially implements the Mapping interface, but we're not
  295. # doing that stuff safely AT ALL.
  296. for key in other.keys():
  297. self.add(key, other[key])
  298. for key, value in kwargs.items():
  299. self.add(key, value)
  300. @typing.overload
  301. def getlist(self, key: str) -> list[str]:
  302. ...
  303. @typing.overload
  304. def getlist(self, key: str, default: _DT) -> list[str] | _DT:
  305. ...
  306. def getlist(
  307. self, key: str, default: _Sentinel | _DT = _Sentinel.not_passed
  308. ) -> list[str] | _DT:
  309. """Returns a list of all the values for the named field. Returns an
  310. empty list if the key doesn't exist."""
  311. try:
  312. vals = self._container[key.lower()]
  313. except KeyError:
  314. if default is _Sentinel.not_passed:
  315. # _DT is unbound; empty list is instance of List[str]
  316. return []
  317. # _DT is bound; default is instance of _DT
  318. return default
  319. else:
  320. # _DT may or may not be bound; vals[1:] is instance of List[str], which
  321. # meets our external interface requirement of `Union[List[str], _DT]`.
  322. return vals[1:]
  323. def _prepare_for_method_change(self) -> Self:
  324. """
  325. Remove content-specific header fields before changing the request
  326. method to GET or HEAD according to RFC 9110, Section 15.4.
  327. """
  328. content_specific_headers = [
  329. "Content-Encoding",
  330. "Content-Language",
  331. "Content-Location",
  332. "Content-Type",
  333. "Content-Length",
  334. "Digest",
  335. "Last-Modified",
  336. ]
  337. for header in content_specific_headers:
  338. self.discard(header)
  339. return self
  340. # Backwards compatibility for httplib
  341. getheaders = getlist
  342. getallmatchingheaders = getlist
  343. iget = getlist
  344. # Backwards compatibility for http.cookiejar
  345. get_all = getlist
  346. def __repr__(self) -> str:
  347. return f"{type(self).__name__}({dict(self.itermerged())})"
  348. def _copy_from(self, other: HTTPHeaderDict) -> None:
  349. for key in other:
  350. val = other.getlist(key)
  351. self._container[key.lower()] = [key, *val]
  352. def copy(self) -> HTTPHeaderDict:
  353. clone = type(self)()
  354. clone._copy_from(self)
  355. return clone
  356. def iteritems(self) -> typing.Iterator[tuple[str, str]]:
  357. """Iterate over all header lines, including duplicate ones."""
  358. for key in self:
  359. vals = self._container[key.lower()]
  360. for val in vals[1:]:
  361. yield vals[0], val
  362. def itermerged(self) -> typing.Iterator[tuple[str, str]]:
  363. """Iterate over all headers, merging duplicate ones together."""
  364. for key in self:
  365. val = self._container[key.lower()]
  366. yield val[0], ", ".join(val[1:])
  367. def items(self) -> HTTPHeaderDictItemView: # type: ignore[override]
  368. return HTTPHeaderDictItemView(self)
  369. def _has_value_for_header(self, header_name: str, potential_value: str) -> bool:
  370. if header_name in self:
  371. return potential_value in self._container[header_name.lower()][1:]
  372. return False
  373. def __ior__(self, other: object) -> HTTPHeaderDict:
  374. # Supports extending a header dict in-place using operator |=
  375. # combining items with add instead of __setitem__
  376. maybe_constructable = ensure_can_construct_http_header_dict(other)
  377. if maybe_constructable is None:
  378. return NotImplemented
  379. self.extend(maybe_constructable)
  380. return self
  381. def __or__(self, other: object) -> HTTPHeaderDict:
  382. # Supports merging header dicts using operator |
  383. # combining items with add instead of __setitem__
  384. maybe_constructable = ensure_can_construct_http_header_dict(other)
  385. if maybe_constructable is None:
  386. return NotImplemented
  387. result = self.copy()
  388. result.extend(maybe_constructable)
  389. return result
  390. def __ror__(self, other: object) -> HTTPHeaderDict:
  391. # Supports merging header dicts using operator | when other is on left side
  392. # combining items with add instead of __setitem__
  393. maybe_constructable = ensure_can_construct_http_header_dict(other)
  394. if maybe_constructable is None:
  395. return NotImplemented
  396. result = type(self)(maybe_constructable)
  397. result.extend(self)
  398. return result