pip_services3_rpc.services package

Submodules

Module contents

pip_services3_rpc.services.__init__

Rpc module implementation

copyright

Conceptual Vision Consulting LLC 2018-2019, see AUTHORS for more details.

license

MIT, see LICENSE for more details.

class pip_services3_rpc.services.AboutOperations

Bases: pip_services3_rpc.services.RestOperations.RestOperations

get_about() str
get_about_operation() Callable
set_references(references: pip_services3_commons.refer.IReferences.IReferences)

Sets references to dependent components.

Parameters

references – references to locate the component dependencies.

class pip_services3_rpc.services.CommandableHttpService(base_route: str)

Bases: pip_services3_rpc.services.RestService.RestService

Abstract service that receives remove calls via HTTP/REST protocol to operations automatically generated for commands defined in ICommandable components. Each command is exposed as POST operation that receives all parameters in body object. Commandable services require only 3 lines of code to implement a robust external HTTP-based remote interface.

### 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 <pip_services3_rpc.services.HttpEndpoint reference

Example:

class MyCommandableHttpService(CommandableHttpService):
    def __init__(self):
        super(MyCommandableHttpService, self).__init__()
        self._dependencyResolver.put("controller", Descriptor("mygroup","controller","*","*","1.0"))

    # ...

service = MyCommandableHttpService()
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")
# ...
configure(config: pip_services3_commons.config.ConfigParams.ConfigParams)

Configures component by passing configuration parameters.

Parameters

config – configuration parameters to be set.

register()

Registers all service routes in HTTP endpoint.

class pip_services3_rpc.services.CommandableSwaggerDocument(base_route, config: pip_services3_commons.config.ConfigParams.ConfigParams, commands: List[pip_services3_commons.commands.ICommand.ICommand])

Bases: object

to_string() str
class pip_services3_rpc.services.HeartBeatOperations

Bases: pip_services3_rpc.services.RestOperations.RestOperations

get_heart_beat_operation() Callable
heartbeat() str
class pip_services3_rpc.services.HeartbeatRestService

Bases: pip_services3_rpc.services.RestService.RestService

Service returns heartbeat via HTTP/REST protocol.The service responds on /heartbeat route (can be changed) with a string with the current time in UTC. This service route can be used to health checks by loadbalancers and container orchestrators.

### Configuration parameters ###
  • base_route: base route for remote URI (default: “”)

  • route: route to heartbeat operation (default: “heartbeat”)

  • dependencies:
    • endpoint: override for HTTP Endpoint 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:

service = HeartbeatService()
service.configure(ConfigParams.from_tuples("route", "ping",
                                           "connection.protocol", "http",
                                           "connection.host", "localhost",
                                           "connection.port", 8080))

service.open("123")
# ...
configure(config: pip_services3_commons.config.ConfigParams.ConfigParams)

Configures component by passing configuration parameters.

Parameters

config – configuration parameters to be set.

heartbeat() str

Handles heartbeat requests

Returns

http response to the request.

register()

Registers all service routes in HTTP endpoint.

class pip_services3_rpc.services.HttpEndpoint

Bases: pip_services3_commons.run.IOpenable.IOpenable, pip_services3_commons.config.IConfigurable.IConfigurable, pip_services3_commons.refer.IReferenceable.IReferenceable

Used for creating HTTP endpoints. An endpoint is a URL, at which a given service can be accessed by a client.

### Configuration parameters ###

Parameters to pass to the configure() method for component configuration:

  • cors_headers - a comma-separated list of allowed CORS headers

  • cors_origins - a comma-separated list of allowed CORS origins

  • connection(s) - the connection resolver’s connections;
    • “connection.discovery_key” - the key to use for connection resolving in a discovery service;

    • “connection.protocol” - the connection’s protocol;

    • “connection.host” - the target host;

    • “connection.port” - the target port;

    • “connection.uri” - the target URI.

  • credential - the HTTPS credentials:
    • “credential.ssl_key_file” - the SSL private key in PEM

    • “credential.ssl_crt_file” - the SSL certificate in PEM

    • “credential.ssl_ca_file” - the certificate authorities (root cerfiticates) in PEM

### References ###
A logger, counters, and a connection resolver can be referenced by passing the following references to the object’s set_references() method:
  • *: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:

def my_method(_config, _references):
    endpoint = HttpEndpoint()
    if (_config)
        endpoint.configure(_config)
    if (_references)
        endpoint.setReferences(_references)
    # ...

    endpoint.open(correlationId)
    # ...
close(correlation_id: Optional[str])

Closes this endpoint and the REST server (service) that was opened earlier.

Parameters

correlation_id – (optional) transaction id to trace execution through call chain.

configure(config: pip_services3_commons.config.ConfigParams.ConfigParams)

Configures this HttpEndpoint using the given configuration parameters. - connection(s) - the connection resolver’s connections;

  • “connection.discovery_key” - the key to use for connection resolving in a discovery service;

  • “connection.protocol” - the connection’s protocol;

  • “connection.host” - the target host;

  • “connection.port” - the target port;

  • “connection.uri” - the target URI.

Parameters

config – configuration parameters, containing a “connection(s)” section.

get_correlation_id() Optional[str]

Returns correlationId from request

Returns

Returns correlationId from request

get_param(param, default=None)
is_open() bool

Checks if the component is opened.

Returns

whether or not this endpoint is open with an actively listening REST server.

open(correlation_id: Optional[str])

Opens a connection using the parameters resolved by the referenced connection resolver and creates a REST server (service) using the set options and parameters.

Parameters

correlation_id – (optional) transaction id to trace execution through call chain.

register(registration: <module 'pip_services3_rpc.services.IRegisterable' from '/pip_services3_rpc/services/IRegisterable.py'>)

Registers a registerable object for dynamic endpoint discovery.

Parameters

registration – the registration to add.

register_interceptor(route: str, action: Callable)

Registers a middleware action for the given route.

Parameters
  • route – the route to register in this object’s REST server (service).

  • action – the middleware action to perform at the given route.

register_route(method: str, route: str, schema: pip_services3_commons.validate.Schema.Schema, handler: Callable)

Registers an action in this objects REST server (service) by the given method and route.

Parameters
  • method – the HTTP method of the route.

  • route – the route to register in this object’s REST server (service).

  • schema – the schema to use for parameter validation.

  • handler – the action to perform at the given route.

register_route_with_auth(method: str, route: str, schema: pip_services3_commons.validate.Schema.Schema, authorize: Callable, action: Callable)

Registers an action with authorization in this objects REST server (service) by the given method and route.

Parameters
  • method – the HTTP method of the route.

  • route – the route to register in this object’s REST server (service).

  • schema – the schema to use for parameter validation.

  • authorize – the authorization interceptor

  • action – the action to perform at the given route.

set_references(references: pip_services3_commons.refer.IReferences.IReferences)

Sets references to this endpoint’s logger, counters, and connection resolver.

  • :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

Parameters

references – an IReferences object, containing references to a logger, counters, and a connection resolver.

unregister(registration: <module 'pip_services3_rpc.services.IRegisterable' from '/pip_services3_rpc/services/IRegisterable.py'>)

Unregisters a registerable object, so that it is no longer used in dynamic endpoint discovery.

Parameters

registration – the registration to remove.

class pip_services3_rpc.services.HttpRequestDetector

Bases: object

Helper class that retrieves parameters from HTTP requests.

static detect_address(req: bottle.BaseRequest) str

Detects the IP address from which the given HTTP request was received.

Parameters

req – an HTTP request to process.

Returns

the detected IP address (without a port). If no IP is detected -

None will be returned.

static detect_browser(req: bottle.BaseRequest) str

Detects the browser (using “user-agent”) from which the given HTTP request was made.

Parameters

req – an HTTP request to process.

Returns

the detected browser. Detectable browsers: “chrome”, “msie”, “firefox”,

“safari”. Otherwise - “unknown” will be returned.

static detect_platform(req: bottle.BaseRequest) str

Detects the platform (using “user-agent”) from which the given HTTP request was made.

Parameters

req – an HTTP request to process.

Returns

the detected platform and version. Detectable platforms: “mobile”, “iphone”,

“ipad”, “macosx”, “android”, “webos”, “mac”, “windows”. Otherwise - “unknown” will be returned.

static detect_server_host(req: bottle.BaseRequest) str

Detects the host name of the request’s destination server.

Parameters

req – an HTTP request to process.

Returns

the destination server’s host name.

static detect_server_port(req: bottle.BaseRequest) str

Detects the request’s destination port number.

Parameters

req – an HTTP request to process.

Returns

the detected port number or 80 (if none are detected).

class pip_services3_rpc.services.HttpResponseSender

Bases: object

Helper class that handles HTTP-based responses.

static send_created_result(result: Any) Optional[str]

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.

Parameters

result – an execution result or a promise with execution result

Returns

JSON text response

static send_deleted_result(result: Optional[Any] = None) Optional[str]

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.

Parameters

result – an execution result or a promise with execution result

Returns

JSON text response

static send_empty_result(result: Optional[Any] = None) Optional[str]

Creates a callback function that sends an empty result with 204 status code. If error occur it sends ErrorDescription with approproate status code.

Parameters

result

Returns

JSON text response

static send_error(error: Any) str

Sends error serialized as ErrorDescription object and appropriate HTTP status code. If status code is not defined, it uses 500 status code.

Parameters

error – an error object to be sent.

Returns

HTTP response status

static send_result(result: Any) Optional[str]

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.

Parameters

result – an execution result

Returns

JSON text response

class pip_services3_rpc.services.IRegisterable

Bases: abc.ABC

Interface to perform on-demand registrations.

register()

Perform required registration steps.

class pip_services3_rpc.services.ISwaggerService

Bases: abc.ABC

Interface to perform Swagger registrations.

register_open_api_spec(base_route: str, swagger_route: str)

Perform required Swagger registration steps.

class pip_services3_rpc.services.InstrumentTiming(correlation_id: Optional[str], name: str, verb: str, logger: pip_services3_components.log.ILogger.ILogger, counters: pip_services3_components.count.ICounters.ICounters, counter_timing: Optional[pip_services3_components.count.CounterTiming.CounterTiming], trace_timing: Optional[pip_services3_components.trace.TraceTiming.TraceTiming])

Bases: object

end_failure(err: Exception)
end_success()
end_timing(err: Optional[Exception] = None)
class pip_services3_rpc.services.RestOperations

Bases: pip_services3_commons.config.IConfigurable.IConfigurable, pip_services3_commons.refer.IReferenceable.IReferenceable, abc.ABC

configure(config: pip_services3_commons.config.ConfigParams.ConfigParams)

Configures object by passing configuration parameters.

Parameters

config – configuration parameters to be set.

get_param(param, default=None)
invoke(operation: str) Callable
set_references(references: pip_services3_commons.refer.IReferences.IReferences)

Sets references to dependent components.

Parameters

references – references to locate the component dependencies.

class pip_services3_rpc.services.RestQueryParams(correlation_id: Optional[str] = None, filte: Optional[pip_services3_commons.data.FilterParams.FilterParams] = None, paging: Optional[pip_services3_commons.data.PagingParams.PagingParams] = None)

Bases: dict

add_correlation_id(correlation_id: Optional[str] = None)
add_filter_params(filter)
add_paging_params(paging: pip_services3_commons.data.PagingParams.PagingParams)
class pip_services3_rpc.services.RestService

Bases: pip_services3_commons.run.IOpenable.IOpenable, pip_services3_commons.config.IConfigurable.IConfigurable, pip_services3_commons.refer.IReferenceable.IReferenceable, pip_services3_commons.refer.IUnreferenceable.IUnreferenceable, pip_services3_rpc.services.IRegisterable.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

  • credential - the HTTPS credentials:
    • ssl_key_file: the SSL private key in PEM

    • ssl_crt_file: the SSL certificate in PEM

    • ssl_ca_file: the certificate authorities (root cerfiticates) in PEM

### 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

  • *:tracer:*:*:1.0 (optional) ITracer components to record traces

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")
close(correlation_id: Optional[str])

Closes component and frees used resources.

Parameters

correlation_id – (optional) transaction id to trace execution through call chain.

configure(config: pip_services3_commons.config.ConfigParams.ConfigParams)

Configures component by passing configuration parameters.

Parameters

config – configuration parameters to be set.

create_endpoint()
fix_route(route) str
is_open() bool

Checks if the component is opened.

Returns

true if the component has been opened and false otherwise.

open(correlation_id: Optional[str])

Opens the component.

Parameters

correlation_id – (optional) transaction id to trace execution through call chain.

abstract register()

Registers all service routes in HTTP endpoint.

This method is called by the service and must be overriden in child classes.

register_interceptor(route: str, action: Callable)

Registers a middleware for a given route in HTTP endpoint.

Parameters
  • route – a command route. Base route will be added to this route

  • action – an action function that is called when middleware is invoked.

register_route(method: str, route: str, schema: Optional[pip_services3_commons.validate.Schema.Schema], handler: Callable)

Registers an action in this objects REST server (service) by the given method and route.

Parameters
  • method – the HTTP method of the route.

  • route – the route to register in this object’s REST server (service).

  • schema – the schema to use for parameter validation.

  • handler – the action to perform at the given route.

register_route_with_auth(method: str, route: str, schema: pip_services3_commons.validate.Schema.Schema, authorize: Callable, action: Callable)

Registers a route with authorization in HTTP endpoint.

Parameters
  • method – HTTP method: “get”, “head”, “post”, “put”, “delete”

  • route – a command route. Base route will be added to this route

  • schema – a validation schema to validate received parameters.

  • authorize – an authorization interceptor

  • action – an action function that is called when operation is invoked.

send_created_result(result: Any) Optional[str]

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.

Parameters

result – a body object to result.

Returns

execution result.

send_deleted_result(result: Optional[Any] = None) Optional[str]

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.

Parameters

result – a body object to result.

Returns

execution result.

send_error(error: Any) str

Sends error serialized as ErrorDescription object and appropriate HTTP status code. If status code is not defined, it uses 500 status code.

Parameters

error – an error object to be sent.

send_result(result: Any) Optional[str]

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.

Parameters

result – a body object to result.

Returns

execution result.

set_references(references: pip_services3_commons.refer.IReferences.IReferences)

Sets references to dependent components.

Parameters

references – references to locate the component dependencies.

unset_references()

Unsets (clears) previously set references to dependent components.

class pip_services3_rpc.services.SSLCherryPyServer(host='127.0.0.1', port=8080, **options)

Bases: bottle.ServerAdapter

run(handler)
server = None
shutdown()
class pip_services3_rpc.services.StatusOperations

Bases: pip_services3_rpc.services.RestOperations.RestOperations

get_status_operation() Callable
set_references(references: pip_services3_commons.refer.IReferences.IReferences)

Sets references to dependent components.

Parameters

references – references to locate the component dependencies.

class pip_services3_rpc.services.StatusRestService

Bases: pip_services3_rpc.services.RestService.RestService

Service that returns microservice status information via HTTP/REST protocol. The service responds on /status route (can be changed) with a JSON object:

{
    - "id":            unique container id (usually hostname)
    - "name":          container name (from ContextInfo)
    - "description":   container description (from ContextInfo)
    - "start_time":    time when container was started
    - "current_time":  current time in UTC
    - "uptime":        duration since container start time in milliseconds
    - "properties":    additional container properties (from ContextInfo)
    - "components":    descriptors of components registered in the container
}
### 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:

service = StatusService()
service.configure(ConfigParams.from_tuples("connection.protocol", "http",
                                           "connection.host", "localhost",
                                           "connection.port", 8080))
service.open("123")
# ...
configure(config: pip_services3_commons.config.ConfigParams.ConfigParams)

Configures component by passing configuration parameters.

Parameters

config – configuration parameters to be set.

register()

Registers all service routes in HTTP endpoint.

set_references(references: pip_services3_commons.refer.IReferences.IReferences)

Sets references to dependent components.

Parameters

references – references to locate the component dependencies.

status() str