_metadata.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. # Copyright 2020 gRPC authors.
  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. """Implementation of the metadata abstraction for gRPC Asyncio Python."""
  15. from collections import OrderedDict
  16. from collections import abc
  17. from typing import Any, Iterator, List, Tuple, Union
  18. MetadataKey = str
  19. MetadataValue = Union[str, bytes]
  20. class Metadata(abc.Mapping):
  21. """Metadata abstraction for the asynchronous calls and interceptors.
  22. The metadata is a mapping from str -> List[str]
  23. Traits
  24. * Multiple entries are allowed for the same key
  25. * The order of the values by key is preserved
  26. * Getting by an element by key, retrieves the first mapped value
  27. * Supports an immutable view of the data
  28. * Allows partial mutation on the data without recreating the new object from scratch.
  29. """
  30. def __init__(self, *args: Tuple[MetadataKey, MetadataValue]) -> None:
  31. self._metadata = OrderedDict()
  32. for md_key, md_value in args:
  33. self.add(md_key, md_value)
  34. @classmethod
  35. def from_tuple(cls, raw_metadata: tuple):
  36. if raw_metadata:
  37. return cls(*raw_metadata)
  38. return cls()
  39. def add(self, key: MetadataKey, value: MetadataValue) -> None:
  40. self._metadata.setdefault(key, [])
  41. self._metadata[key].append(value)
  42. def __len__(self) -> int:
  43. """Return the total number of elements that there are in the metadata,
  44. including multiple values for the same key.
  45. """
  46. return sum(map(len, self._metadata.values()))
  47. def __getitem__(self, key: MetadataKey) -> MetadataValue:
  48. """When calling <metadata>[<key>], the first element of all those
  49. mapped for <key> is returned.
  50. """
  51. try:
  52. return self._metadata[key][0]
  53. except (ValueError, IndexError) as e:
  54. raise KeyError("{0!r}".format(key)) from e
  55. def __setitem__(self, key: MetadataKey, value: MetadataValue) -> None:
  56. """Calling metadata[<key>] = <value>
  57. Maps <value> to the first instance of <key>.
  58. """
  59. if key not in self:
  60. self._metadata[key] = [value]
  61. else:
  62. current_values = self.get_all(key)
  63. self._metadata[key] = [value, *current_values[1:]]
  64. def __delitem__(self, key: MetadataKey) -> None:
  65. """``del metadata[<key>]`` deletes the first mapping for <key>."""
  66. current_values = self.get_all(key)
  67. if not current_values:
  68. raise KeyError(repr(key))
  69. self._metadata[key] = current_values[1:]
  70. def delete_all(self, key: MetadataKey) -> None:
  71. """Delete all mappings for <key>."""
  72. del self._metadata[key]
  73. def __iter__(self) -> Iterator[Tuple[MetadataKey, MetadataValue]]:
  74. for key, values in self._metadata.items():
  75. for value in values:
  76. yield (key, value)
  77. def get_all(self, key: MetadataKey) -> List[MetadataValue]:
  78. """For compatibility with other Metadata abstraction objects (like in Java),
  79. this would return all items under the desired <key>.
  80. """
  81. return self._metadata.get(key, [])
  82. def set_all(self, key: MetadataKey, values: List[MetadataValue]) -> None:
  83. self._metadata[key] = values
  84. def __contains__(self, key: MetadataKey) -> bool:
  85. return key in self._metadata
  86. def __eq__(self, other: Any) -> bool:
  87. if isinstance(other, self.__class__):
  88. return self._metadata == other._metadata
  89. if isinstance(other, tuple):
  90. return tuple(self) == other
  91. return NotImplemented # pytype: disable=bad-return-type
  92. def __add__(self, other: Any) -> 'Metadata':
  93. if isinstance(other, self.__class__):
  94. return Metadata(*(tuple(self) + tuple(other)))
  95. if isinstance(other, tuple):
  96. return Metadata(*(tuple(self) + other))
  97. return NotImplemented # pytype: disable=bad-return-type
  98. def __repr__(self) -> str:
  99. view = tuple(self)
  100. return "{0}({1!r})".format(self.__class__.__name__, view)