client.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # Copyright 2020 The 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. from concurrent.futures import ThreadPoolExecutor
  15. import logging
  16. import threading
  17. from typing import Iterator
  18. import grpc
  19. import phone_pb2
  20. import phone_pb2_grpc
  21. class CallMaker:
  22. def __init__(self, executor: ThreadPoolExecutor, channel: grpc.Channel,
  23. phone_number: str) -> None:
  24. self._executor = executor
  25. self._channel = channel
  26. self._stub = phone_pb2_grpc.PhoneStub(self._channel)
  27. self._phone_number = phone_number
  28. self._session_id = None
  29. self._audio_session_link = None
  30. self._call_state = None
  31. self._peer_responded = threading.Event()
  32. self._call_finished = threading.Event()
  33. self._consumer_future = None
  34. def _response_watcher(
  35. self,
  36. response_iterator: Iterator[phone_pb2.StreamCallResponse]) -> None:
  37. try:
  38. for response in response_iterator:
  39. # NOTE: All fields in Proto3 are optional. This is the recommended way
  40. # to check if a field is present or not, or to exam which one-of field is
  41. # fulfilled by this message.
  42. if response.HasField("call_info"):
  43. self._on_call_info(response.call_info)
  44. elif response.HasField("call_state"):
  45. self._on_call_state(response.call_state.state)
  46. else:
  47. raise RuntimeError(
  48. "Received StreamCallResponse without call_info and call_state"
  49. )
  50. except Exception as e:
  51. self._peer_responded.set()
  52. raise
  53. def _on_call_info(self, call_info: phone_pb2.CallInfo) -> None:
  54. self._session_id = call_info.session_id
  55. self._audio_session_link = call_info.media
  56. def _on_call_state(self, call_state: phone_pb2.CallState.State) -> None:
  57. logging.info("Call toward [%s] enters [%s] state", self._phone_number,
  58. phone_pb2.CallState.State.Name(call_state))
  59. self._call_state = call_state
  60. if call_state == phone_pb2.CallState.State.ACTIVE:
  61. self._peer_responded.set()
  62. if call_state == phone_pb2.CallState.State.ENDED:
  63. self._peer_responded.set()
  64. self._call_finished.set()
  65. def call(self) -> None:
  66. request = phone_pb2.StreamCallRequest()
  67. request.phone_number = self._phone_number
  68. response_iterator = self._stub.StreamCall(iter((request,)))
  69. # Instead of consuming the response on current thread, spawn a consumption thread.
  70. self._consumer_future = self._executor.submit(self._response_watcher,
  71. response_iterator)
  72. def wait_peer(self) -> bool:
  73. logging.info("Waiting for peer to connect [%s]...", self._phone_number)
  74. self._peer_responded.wait(timeout=None)
  75. if self._consumer_future.done():
  76. # If the future raises, forwards the exception here
  77. self._consumer_future.result()
  78. return self._call_state == phone_pb2.CallState.State.ACTIVE
  79. def audio_session(self) -> None:
  80. assert self._audio_session_link is not None
  81. logging.info("Consuming audio resource [%s]", self._audio_session_link)
  82. self._call_finished.wait(timeout=None)
  83. logging.info("Audio session finished [%s]", self._audio_session_link)
  84. def process_call(executor: ThreadPoolExecutor, channel: grpc.Channel,
  85. phone_number: str) -> None:
  86. call_maker = CallMaker(executor, channel, phone_number)
  87. call_maker.call()
  88. if call_maker.wait_peer():
  89. call_maker.audio_session()
  90. logging.info("Call finished!")
  91. else:
  92. logging.info("Call failed: peer didn't answer")
  93. def run():
  94. executor = ThreadPoolExecutor()
  95. with grpc.insecure_channel("localhost:50051") as channel:
  96. future = executor.submit(process_call, executor, channel,
  97. "555-0100-XXXX")
  98. future.result()
  99. if __name__ == '__main__':
  100. logging.basicConfig(level=logging.INFO)
  101. run()