server.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. import time
  18. from typing import Iterable
  19. from google.protobuf.json_format import MessageToJson
  20. import grpc
  21. import phone_pb2
  22. import phone_pb2_grpc
  23. def create_state_response(
  24. call_state: phone_pb2.CallState.State) -> phone_pb2.StreamCallResponse:
  25. response = phone_pb2.StreamCallResponse()
  26. response.call_state.state = call_state
  27. return response
  28. class Phone(phone_pb2_grpc.PhoneServicer):
  29. def __init__(self):
  30. self._id_counter = 0
  31. self._lock = threading.RLock()
  32. def _create_call_session(self) -> phone_pb2.CallInfo:
  33. call_info = phone_pb2.CallInfo()
  34. with self._lock:
  35. call_info.session_id = str(self._id_counter)
  36. self._id_counter += 1
  37. call_info.media = "https://link.to.audio.resources"
  38. logging.info("Created a call session [%s]", MessageToJson(call_info))
  39. return call_info
  40. def _clean_call_session(self, call_info: phone_pb2.CallInfo) -> None:
  41. logging.info("Call session cleaned [%s]", MessageToJson(call_info))
  42. def StreamCall(
  43. self, request_iterator: Iterable[phone_pb2.StreamCallRequest],
  44. context: grpc.ServicerContext
  45. ) -> Iterable[phone_pb2.StreamCallResponse]:
  46. try:
  47. request = next(request_iterator)
  48. logging.info("Received a phone call request for number [%s]",
  49. request.phone_number)
  50. except StopIteration:
  51. raise RuntimeError("Failed to receive call request")
  52. # Simulate the acceptance of call request
  53. time.sleep(1)
  54. yield create_state_response(phone_pb2.CallState.NEW)
  55. # Simulate the start of the call session
  56. time.sleep(1)
  57. call_info = self._create_call_session()
  58. context.add_callback(lambda: self._clean_call_session(call_info))
  59. response = phone_pb2.StreamCallResponse()
  60. response.call_info.session_id = call_info.session_id
  61. response.call_info.media = call_info.media
  62. yield response
  63. yield create_state_response(phone_pb2.CallState.ACTIVE)
  64. # Simulate the end of the call
  65. time.sleep(2)
  66. yield create_state_response(phone_pb2.CallState.ENDED)
  67. logging.info("Call finished [%s]", request.phone_number)
  68. def serve(address: str) -> None:
  69. server = grpc.server(ThreadPoolExecutor())
  70. phone_pb2_grpc.add_PhoneServicer_to_server(Phone(), server)
  71. server.add_insecure_port(address)
  72. server.start()
  73. logging.info("Server serving at %s", address)
  74. server.wait_for_termination()
  75. if __name__ == "__main__":
  76. logging.basicConfig(level=logging.INFO)
  77. serve("[::]:50051")