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
20 MetadataValue = Union[str, bytes]
24 """Metadata abstraction for the asynchronous calls and interceptors.
26 The metadata is a mapping from str -> List[str]
29 * Multiple entries are allowed for the same key
30 * The order of the values by key is preserved
31 * Getting by an element by key, retrieves the first mapped value
32 * Supports an immutable view of the data
33 * Allows partial mutation on the data without recreating the new object from scratch.
36 def __init__(self, *args: Tuple[MetadataKey, MetadataValue]) ->
None:
38 for md_key, md_value
in args:
39 self.
add(md_key, md_value)
44 return cls(*raw_metadata)
47 def add(self, key: MetadataKey, value: MetadataValue) ->
None:
52 """Return the total number of elements that there are in the metadata,
53 including multiple values for the same key.
58 """When calling <metadata>[<key>], the first element of all those
59 mapped for <key> is returned.
63 except (ValueError, IndexError)
as e:
64 raise KeyError(
"{0!r}".
format(key))
from e
66 def __setitem__(self, key: MetadataKey, value: MetadataValue) ->
None:
67 """Calling metadata[<key>] = <value>
68 Maps <value> to the first instance of <key>.
73 current_values = self.
get_all(key)
74 self.
_metadata[key] = [value, *current_values[1:]]
77 """``del metadata[<key>]`` deletes the first mapping for <key>."""
78 current_values = self.
get_all(key)
79 if not current_values:
80 raise KeyError(repr(key))
84 """Delete all mappings for <key>."""
87 def __iter__(self) -> Iterator[Tuple[MetadataKey, MetadataValue]]:
92 def get_all(self, key: MetadataKey) -> List[MetadataValue]:
93 """For compatibility with other Metadata abstraction objects (like in Java),
94 this would return all items under the desired <key>.
98 def set_all(self, key: MetadataKey, values: List[MetadataValue]) ->
None:
105 if isinstance(other, self.__class__):
107 if isinstance(other, tuple):
108 return tuple(self) == other
109 return NotImplemented
112 if isinstance(other, self.__class__):
113 return Metadata(*(tuple(self) + tuple(other)))
114 if isinstance(other, tuple):
115 return Metadata(*(tuple(self) + other))
116 return NotImplemented
120 return "{0}({1!r})".
format(self.__class__.__name__, view)