Skip to content
Snippets Groups Projects
AppClient.py 2.02 KiB
Newer Older
import grpc, logging
from common.Constants import ServiceNameEnum
from common.Settings import get_service_host, get_service_port_grpc
from common.proto.context_pb2 import Empty, ContextId
from common.proto.app_pb2 import App, AppId, AppList
from common.proto.app_pb2_grpc import AppServiceStub
from common.tools.client.RetryDecorator import retry, delay_exponential
from common.tools.grpc.Tools import grpc_message_to_json_string

LOGGER = logging.getLogger(__name__)
MAX_RETRIES = 15
DELAY_FUNCTION = delay_exponential(initial=0.01, increment=2.0, maximum=5.0)
RETRY_DECORATOR = retry(max_retries=MAX_RETRIES, delay_function=DELAY_FUNCTION, prepare_method_name='connect')

class AppClient:
    def __init__(self, host=None, port=None):
        if not host: host = get_service_host(ServiceNameEnum.APP)
        if not port: port = get_service_port_grpc(ServiceNameEnum.APP)
        self.endpoint = '{:s}:{:s}'.format(str(host), str(port))
        LOGGER.debug('Creating channel to {:s}...'.format(self.endpoint))
        self.channel = None
        self.stub = None
        self.connect()
        LOGGER.debug('Channel created')

    def connect(self):
        self.channel = grpc.insecure_channel(self.endpoint)
        self.stub = AppServiceStub(self.channel)

    def close(self):
        if self.channel is not None: self.channel.close()
        self.channel = None
        self.stub = None



    @RETRY_DECORATOR
    def RegisterApp(self, request : App) -> Empty:
        LOGGER.debug('RegisterApp request: {:s}'.format(grpc_message_to_json_string(request)))
        response = self.stub.RegisterApp(request)
        LOGGER.debug('RegisterApp result: {:s}'.format(grpc_message_to_json_string(response)))
        return response

    
    @RETRY_DECORATOR
    def ListApps(self, request: ContextId) -> AppList:
        LOGGER.debug('ListApps request: {:s}'.format(grpc_message_to_json_string(request)))
        response = self.stub.ListApps(request)
        LOGGER.debug('ListApps result: {:s}'.format(grpc_message_to_json_string(response)))
        return response