def GetMessages(self, request, context): key = self.CH.hash(request.username) print(f'GetMessages - Server {SERVER_ID} / Username {request.username} / Username key: {key}') node = self.CH.find_successor(key) if node.server_id != SERVER_ID: print(f'GetMessages - Redirected to server {node.server_id}') try: with grpc.insecure_channel(f'{node.host}:{node.port}') as channel: stub = API_pb2_grpc.APIStub(channel) for message in stub.GetMessages(request): yield message except Exception as e: print(e) yield API_pb2.Message() else: print(f'GetMessages - Server {SERVER_ID} executing the action') error, data = messages.get_messages(self.LSMT, request, context) for message in data['messages']: pb_message = API_pb2.Message() pb_message.id = message['id'] pb_message.message = message['message'] pb_message.user.username = message['username'] pb_message.user.user_type = message['user_type'] yield pb_message
def SendMessage(self, request, context): """The messages need to be replicated across the chord""" print(f'SendMessage - Server {SERVER_ID} / Username {request.user.username}') replicated_message = API_pb2.ReplicatedMessage() replicated_message.message.user.username = request.user.username replicated_message.message.user.user_type = request.user.user_type replicated_message.message.user.token = request.user.token replicated_message.message.message = request.message nodes = self.CH.get_reachable_nodes() for node in nodes: pb_node = replicated_message.nodes.add() pb_node.id = str(node.id) pb_node.server_id = node.server_id pb_node = replicated_message.nodes.add() pb_node.id = str(self.CH.node.id) pb_node.server_id = self.CH.node.server_id for node in nodes: if node.server_id == SERVER_ID: continue try: with grpc.insecure_channel(f'{node.host}:{node.port}') as channel: stub = API_pb2_grpc.APIStub(channel) stub.ReplicateMessage(replicated_message) except Exception as e: print(e) continue error, data = messages.send_message(self.LSMT, request, context) if error: context.set_code(grpc.StatusCode.INVALID_ARGUMENT) context.set_details(data['msg']) return API_pb2.Message() else: pb_message = API_pb2.Message() pb_message.id = data['message']['id'] pb_message.user.username = data['message']['username'] pb_message.user.user_type = data['message']['user_type'] pb_message.message = data['message']['message'] return pb_message