metadata.pyx.pxi 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # Copyright 2017 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. import collections
  15. class InitialMetadataFlags:
  16. used_mask = GRPC_INITIAL_METADATA_USED_MASK
  17. wait_for_ready = GRPC_INITIAL_METADATA_WAIT_FOR_READY
  18. wait_for_ready_explicitly_set = GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET
  19. _Metadatum = collections.namedtuple('_Metadatum', ('key', 'value',))
  20. cdef void _store_c_metadata(
  21. metadata, grpc_metadata **c_metadata, size_t *c_count) except *:
  22. if metadata is None:
  23. c_count[0] = 0
  24. c_metadata[0] = NULL
  25. else:
  26. metadatum_count = len(metadata)
  27. if metadatum_count == 0:
  28. c_count[0] = 0
  29. c_metadata[0] = NULL
  30. else:
  31. c_count[0] = metadatum_count
  32. c_metadata[0] = <grpc_metadata *>gpr_malloc(
  33. metadatum_count * sizeof(grpc_metadata))
  34. for index, (key, value) in enumerate(metadata):
  35. encoded_key = _encode(key)
  36. encoded_value = value if encoded_key[-4:] == b'-bin' else _encode(value)
  37. if not isinstance(encoded_value, bytes):
  38. raise TypeError('Binary metadata key="%s" expected bytes, got %s' % (
  39. key,
  40. type(encoded_value)
  41. ))
  42. c_metadata[0][index].key = _slice_from_bytes(encoded_key)
  43. c_metadata[0][index].value = _slice_from_bytes(encoded_value)
  44. cdef void _release_c_metadata(grpc_metadata *c_metadata, int count) except *:
  45. if 0 < count:
  46. for index in range(count):
  47. grpc_slice_unref(c_metadata[index].key)
  48. grpc_slice_unref(c_metadata[index].value)
  49. gpr_free(c_metadata)
  50. cdef tuple _metadatum(grpc_slice key_slice, grpc_slice value_slice):
  51. cdef bytes key = _slice_bytes(key_slice)
  52. cdef bytes value = _slice_bytes(value_slice)
  53. return <tuple>_Metadatum(
  54. _decode(key), value if key[-4:] == b'-bin' else _decode(value))
  55. cdef tuple _metadata(grpc_metadata_array *c_metadata_array):
  56. return tuple(
  57. _metadatum(
  58. c_metadata_array.metadata[index].key,
  59. c_metadata_array.metadata[index].value)
  60. for index in range(c_metadata_array.count))