class RestClient(IOpenable, IConfigurable, IReferenceable): """ Abstract client that calls remove endpoints using HTTP/REST protocol. ### Configuration parameters ### - base_route: base route for remote URI - connection(s): - discovery_key: (optional) a key to retrieve the connection from IDiscovery - protocol: connection protocol: http or https - host: host name or IP address - port: port number - uri: resource URI or connection string with all parameters in it - options: - retries: number of retries (default: 3) - connect_timeout: connection timeout in milliseconds (default: 10 sec) - timeout: invocation timeout in milliseconds (default: 10 sec) ### References ### - *:logger:*:*:1.0 (optional) ILogger components to pass log messages - *:counters:*:*:1.0 (optional) ICounters components to pass collected measurements - *:discovery:*:*:1.0 (optional) IDiscovery services to resolve connection Example: class MyRestClient(RestClient, IMyClient): def get_data(self, correlation_id, id): timing = self.instrument(correlationId, 'myclient.get_data') result = self._controller.get_data(correlationId, id) timing.end_timing() return result ... client = MyRestClient() client.configure(ConfigParams.fromTuples("connection.protocol", "http", "connection.host", "localhost", "connection.port", 8080)) data = client.getData("123", "1") ... """ _default_config = None _client = None _uri = None _timeout = 1000 _connection_resolver = None _logger = None _counters = None _options = None _base_route = None _retries = 1 _headers = None _connect_timeout = 1000 def __init__(self): """ Creates a new instance of the client. """ self._connection_resolver = HttpConnectionResolver() self._default_config = ConfigParams.from_tuples( "connection.protocol", "http", "connection.host", "0.0.0.0", "connection.port", 3000, "options.timeout", 10000, "options.request_max_size", 1024 * 1024, "options.connect_timeout", 10000, "options.retries", 3, "options.debug", True) self._logger = CompositeLogger() self._counters = CompositeCounters() self._options = ConfigParams() self._headers = {} def set_references(self, references): """ Sets references to dependent components. :param references: references to locate the component dependencies. """ self._logger.set_references(references) self._counters.set_references(references) self._connection_resolver.set_references(references) def configure(self, config): """ Configures component by passing configuration parameters. :param config: configuration parameters to be set. """ config = config.set_defaults(self._default_config) self._connection_resolver.configure(config) self._options.override(config.get_section("options")) self._retries = config.get_as_integer_with_default( "options.retries", self._retries) self._connect_timeout = config.get_as_integer_with_default( "options.connect_timeout", self._connect_timeout) self._timeout = config.get_as_integer_with_default( "options.timeout", self._timeout) self._base_route = config.get_as_string_with_default( "base_route", self._base_route) def _instrument(self, correlation_id, name): """ Adds instrumentation to log calls and measure call time. It returns a Timing object that is used to end the time measurement. :param correlation_id: (optional) transaction id to trace execution through call chain. :param name: a method name. :return: Timing object to end the time measurement. """ TYPE_NAME = self.__class__.__name__ or 'unknown-target' self._logger.trace(correlation_id, f"Calling {name} method {TYPE_NAME}") self._counters.increment_one(f"{TYPE_NAME}.{name}.call_count") return self._counters.begin_timing(f"{TYPE_NAME}.{name}.call_count") def _instrument_error(self, correlation_id, name, err, result=None, callback=None): """ Adds instrumentation to error handling. :param correlation_id: (optional) transaction id to trace execution through call chain. :param name: a method name. :param err: an occured error :param result: (optional) an execution result :param callback: (optional) an execution callback """ if err is not None: TYPE_NAME = self.__class__.__name__ or 'unknown-target' self._logger.error(correlation_id, err, f"Failed to call {name} method of {TYPE_NAME}") self._counters.increment_one(f"{name}.call_errors") if callback: callback(err, result) def is_opened(self): """ Checks if the component is opened. :return: true if the component has been opened and false otherwise. """ return self._client is not None def open(self, correlation_id): """ Opens the component. :param correlation_id: (optional) transaction id to trace execution through call chain. """ if self.is_opened(): return connection = self._connection_resolver.resolve(correlation_id) self._uri = connection.get_uri() self._client = requests self._logger.debug(correlation_id, "Connected via REST to " + self._uri) def close(self, correlation_id): """ Closes component and frees used resources. :param correlation_id: (optional) transaction id to trace execution through call chain. """ if self._client is not None: self._logger.debug(correlation_id, "Disconnected from " + self._uri) self._client = None self._uri = None def _to_json(self, obj): if obj is None: return None if isinstance(obj, set): obj = list(obj) if isinstance(obj, list): result = [] for item in obj: item = self._to_json(item) result.append(item) return result if isinstance(obj, dict): result = {} for (k, v) in obj.items(): v = self._to_json(v) result[k] = v return result if hasattr(obj, 'to_json'): return obj.to_json() if hasattr(obj, '__dict__'): return self._to_json(obj.__dict__) return obj def fix_route(self, route) -> str: if route is not None and len(route) > 0: if route[0] != '/': route = f'/{route}' return route return '' def createRequestRoute(self, route): builder = '' if self._uri is not None and len(self._uri) > 0: builder = self._uri builder += self.fix_route(self._base_route) if route[0] != '/': builder += '/' builder += route return builder def add_correlation_id(self, correlation_id=None, params=None): params = params or {} if not (correlation_id is None): params['correlation_id'] = correlation_id return params def add_filter_params(self, params=None, filters=None): params = params or {} if not (filters is None): params.update(filters) return params def add_paging_params(self, params=None, paging=None): params = params or {} if not (paging is None): if not (paging['total'] is None): params['total'] = paging['total'] if not (paging['skip'] is None): params['skip'] = paging['skip'] if not (paging['take'] is None): params['take'] = paging['take'] # params.update(paging) return params def call(self, method, route, correlation_id=None, params=None, data=None): """ Calls a remote method via HTTP/REST protocol. :param method: HTTP method: "get", "head", "post", "put", "delete" :param route: a command route. Base route will be added to this route :param correlation_id: (optional) transaction id to trace execution through call chain. :param params: (optional) query parameters. :param data: (optional) body object. :return: result object """ method = method.upper() route = self.createRequestRoute(route) params = self.add_correlation_id(correlation_id=correlation_id, params=params) response = None result = None try: # Call the service data = self._to_json(data) response = requests.request(method, route, params=params, json=data, timeout=self._timeout) except Exception as ex: error = InvocationException(correlation_id, 'REST_ERROR', 'REST operation failed: ' + str(ex)).wrap(ex) raise error if response.status_code == 404 or response.status_code == 204: return None try: # Retrieve JSON data result = response.json() except: # Data is not in JSON if response.status_code < 400: raise UnknownException(correlation_id, 'FORMAT_ERROR', 'Failed to deserialize JSON data: ' + response.text) \ .with_details('response', response.text) else: raise UnknownException(correlation_id, 'UNKNOWN', 'Unknown error occured: ' + response.text) \ .with_details('response', response.text) # Return result if response.status_code < 400: return result # Raise error # Todo: We need to implement proper from_value method error = ErrorDescription.from_json(result) error.status = response.status_code raise ApplicationExceptionFactory.create(error)
class RestService(IOpenable, IConfigurable, IReferenceable, IUnreferenceable, IRegisterable): """ Abstract service that receives remove calls via HTTP/REST protocol. ### Configuration parameters ### - base_route: base route for remote URI - dependencies: - endpoint: override for HTTP Endpoint dependency - controller: override for Controller dependency - connection(s): - discovery_key: (optional) a key to retrieve the connection from IDiscovery - protocol: connection protocol: http or https - host: host name or IP address - port: port number - uri: resource URI or connection string with all parameters in it ### References ### - *:logger:*:*:1.0 (optional) ILogger components to pass log messages - *:counters:*:*:1.0 (optional) ICounters components to pass collected measurements - *:discovery:*:*:1.0 (optional) IDiscovery services to resolve connection - *:endpoint:http:*:1.0 (optional) HttpEndpoint reference Example: class MyRestService(RestService): _controller = None ... def __init__(self): super(MyRestService, self).__init__() self._dependencyResolver.put("controller", Descriptor("mygroup","controller","*","*","1.0")) def set_references(self, references): super(MyRestService, self).set_references(references) self._controller = self._dependencyResolver.get_required("controller") def register(): ... service = MyRestService() service.configure(ConfigParams.from_tuples("connection.protocol", "http", "connection.host", "localhost", "connection.port", 8080)) service.set_references(References.from_tuples(Descriptor("mygroup","controller","default","default","1.0"), controller)) service.open("123") """ _default_config = None _debug = False _dependency_resolver = None _logger = None _counters = None # _registered = None _local_endpoint = None _config = None _references = None _base_route = None _endpoint = None _opened = None def __init__(self): self._default_config = ConfigParams.from_tuples( "base_route", None, "dependencies.endpoint", "*:endpoint:http:*:1.0") # self._registered = False self._dependency_resolver = DependencyResolver() self._logger = CompositeLogger() self._counters = CompositeCounters() def _instrument(self, correlation_id, name): """ Adds instrumentation to log calls and measure call time. It returns a Timing object that is used to end the time measurement. :param correlation_id: (optional) transaction id to trace execution through call chain. :param name: a method name. """ self._logger.trace(correlation_id, "Executing " + name + " method") return self._counters.begin_timing(name + ".exec_time") def set_references(self, references): """ Sets references to dependent components. :param references: references to locate the component dependencies. """ self._references = references self._logger.set_references(references) self._counters.set_references(references) self._dependency_resolver.set_references(references) self._endpoint = self._dependency_resolver.get_one_optional('endpoint') if self._endpoint is None: self._endpoint = self.create_endpoint() self._local_endpoint = True else: self._local_endpoint = False self._endpoint.register(self) def configure(self, config): """ Configures component by passing configuration parameters. :param config: configuration parameters to be set. """ config = config.set_defaults(self._default_config) self._config = config self._dependency_resolver.configure(config) self._base_route = config.get_as_string_with_default( "base_route", self._base_route) def unset_references(self): """ Unsets (clears) previously set references to dependent components. """ if not (self._endpoint is None): self._endpoint.unregister(self) self._endpoint = None def create_endpoint(self): endpoint = HttpEndpoint() if not (self._config is None): endpoint.configure(self._config) if not (self._references is None): endpoint.set_references(self._references) return endpoint def _instrument(self, correlation_id, name): self._logger.trace(correlation_id, f"Executing {name} method") self._counters.increment_one(f"{name}.exec_count") return self._counters.begin_timing(f"{name}.exec_time") def _instrument_error(self, correlation_id, name, error, result, callback): if not (error is None): self._logger.error(correlation_id, error, f"Failed to execute {name} method") self._counters.increment_one(f"{name}.exec_error") if not (callback is None): callback(error, result) def is_opened(self): """ Checks if the component is opened. :return: true if the component has been opened and false otherwise. """ return self._opened def open(self, correlation_id): """ Opens the component. :param correlation_id: (optional) transaction id to trace execution through call chain. """ if self.is_opened(): return if self._endpoint is None: self._endpoint = self.create_endpoint() self._endpoint.register(self) self._local_endpoint = True if self._local_endpoint: self._endpoint.open(correlation_id) self._opened = True # # register route # if self._registered != True: # self.add_route() # self._registered = True def close(self, correlation_id): """ Closes component and frees used resources. :param correlation_id: (optional) transaction id to trace execution through call chain. """ if not self._opened: return if self._endpoint is None: raise InvalidStateException(correlation_id, "NO_ENDPOINT", "HTTP endpoint is missing") if self._local_endpoint: self._endpoint.close(correlation_id) self._opened = False def send_result(self, result): """ Creates a callback function that sends result as JSON object. That callack function call be called directly or passed as a parameter to business logic components. If object is not null it returns 200 status code. For null results it returns 204 status code. If error occur it sends ErrorDescription with approproate status code. :param result: a body object to result. :return: execution result. """ return HttpResponseSender.send_result(result) def send_created_result(self, result): """ Creates a callback function that sends newly created object as JSON. That callack function call be called directly or passed as a parameter to business logic components. If object is not null it returns 201 status code. For null results it returns 204 status code. If error occur it sends ErrorDescription with approproate status code. :param result: a body object to result. :return: execution result. """ return HttpResponseSender.send_created_result(result) def send_deleted_result(self): """ Creates a callback function that sends newly created object as JSON. That callack function call be called directly or passed as a parameter to business logic components. If object is not null it returns 200 status code. For null results it returns 204 status code. If error occur it sends ErrorDescription with approproate status code. :return: execution result. """ return HttpResponseSender.send_deleted_result() def send_error(self, error): """ Sends error serialized as ErrorDescription object and appropriate HTTP status code. If status code is not defined, it uses 500 status code. :param error: an error object to be sent. """ return HttpResponseSender.send_error(error) def fix_route(self, route) -> str: if (route is not None and len(route) > 0): if (route[0] != '/'): route = f'/{route}' return route return '' def register_route(self, method, route, schema, handler): """ Registers an action in this objects REST server (service) by the given method and route. :param method: the HTTP method of the route. :param route: the route to register in this object's REST server (service). :param schema: the schema to use for parameter validation. :param handler: the action to perform at the given route. """ if self._endpoint is None: return route = f"{self.fix_route(self._base_route)}{self.fix_route(route)}" # if not (self._base_route is None) and len(self._base_route) > 0: # base_route = self._base_route # if base_route[0] != '/': # base_route = '/' + base_route # if route[0] != '/': # base_route = base_route + '/' # route = base_route + route self._endpoint.register_route(method, route, schema, handler) def register(self): pass def get_data(self): data = bottle.request.json if isinstance(data, str): return json.loads(bottle.request.json) elif bottle.request.json: return bottle.request.json else: return None def get_request_param(self): if (not (bottle is None)) and (not (bottle.request is None)) and ( not (bottle.request.params is None)): return bottle.request.params else: return {} def _append_base_route(self, route): route = route or '' if self._base_route is not None and len(self._base_route) > 0: base_route = self._base_route if base_route[0] != '/': base_route = '/' + base_route route = base_route + route return route def register_route_with_auth(self, method, route, schema, authorize, action): """ Registers a route with authorization in HTTP endpoint. :param method: HTTP method: "get", "head", "post", "put", "delete" :param route: a command route. Base route will be added to this route :param schema: a validation schema to validate received parameters. :param authorize: an authorization interceptor :param action: an action function that is called when operation is invoked. """ if self._endpoint is None: return route = self._append_base_route(self.fix_route(route)) self._endpoint.register_route_with_auth(method, route, schema, authorize, method) def register_interceptor(self, route, action): """ Registers a middleware for a given route in HTTP endpoint. :param route: a command route. Base route will be added to this route :param action: an action function that is called when middleware is invoked. """ if self._endpoint is None: return route = self._append_base_route(self.fix_route(route)) self._endpoint.register_interceptor(route, action)
class DirectClient(IConfigurable, IReferenceable, IOpenable): """ Abstract client that calls controller directly in the same memory space. It is used when multiple microservices are deployed in a single container (monolyth) and communication between them can be done by direct calls rather then through the network. ### Configuration parameters ### - dependencies: - controller: override controller descriptor ### References ### - *:logger:*:*:1.0 (optional) ILogger components to pass log messages - *:counters:*:*:1.0 (optional) ICounters components to pass collected measurements - *:controller:*:*:1.0 controller to call business methods Example: class MyDirectClient(DirectClient, IMyClient): def __init__(self): super(MyDirectClient, self).__init__() self._dependencyResolver.put('controller', Descriptor("mygroup", "controller", "*", "*", "*")) ... def get_data(self, correlation_id, id): timing = self.instrument(correlationId, 'myclient.get_data') result = self._controller.get_data(correlationId, id) timing.end_timing() return result client = MyDirectClient() client.set_references(References.from_tuples(Descriptor("mygroup","controller","default","default","1.0"), controller)) data = client.get_data("123", "1") ... """ _controller = None _opened = True _logger = None _counters = None _dependency_resolver = None def __init__(self): """ Creates a new instance of the client. """ self._logger = CompositeLogger() self._counters = CompositeCounters() self._dependency_resolver = DependencyResolver() self._dependency_resolver.put('controller', 'none') def configure(self, config): """ Configures component by passing configuration parameters. :param config: configuration parameters to be set. """ self._dependency_resolver.configure(config) def set_references(self, references): """ Sets references to dependent components. :param references: references to locate the component dependencies. """ self._logger.set_references(references) self._counters.set_references(references) self._dependency_resolver.set_references(references) self._controller = self._dependency_resolver.get_one_required('controller') def _instrument(self, correlation_id, name): """ Adds instrumentation to log calls and measure call time. It returns a Timing object that is used to end the time measurement. :param correlation_id: (optional) transaction id to trace execution through call chain. :param name: a method name. :return: Timing object to end the time measurement. """ self._logger.trace(correlation_id, f"Executing {name} method") return self._counters.begin_timing(f"{name} .call_time") def _instrument_error(self, correlation_id, name, err, result, callback): """ Adds instrumentation to error handling. :param correlation_id: (optional) transaction id to trace execution through call chain. :param name: a method name. :param err: an occured error :param result: (optional) an execution result :param callback: (optional) an execution callback """ if err is not None: self._logger.error(correlation_id, err, f'Failed to call {name} method') self._counters.increment_one(f"{name}.call_errors") if callback: callback(err, result) def is_opened(self): """ Checks if the component is opened. :return: true if the component has been opened and false otherwise. """ return self._opened def open(self, correlation_id): """ Opens the component. :param correlation_id: (optional) transaction id to trace execution through call chain. """ if self._opened: return if self._controller is None: raise ConnectionException(correlation_id, 'NO_CONTROLLER', 'Controller references is missing') self._opened = True self._logger.info(correlation_id, 'Opened direct client') def close(self, correlation_id): """ Closes component and frees used resources. :param correlation_id: (optional) transaction id to trace execution through call chain. """ if self._opened: self._logger.info(correlation_id, 'Closed direct client') self._opened = False