add notification and valid returns
This commit is contained in:
@ -2,7 +2,7 @@ from tiramisu import Config
|
||||
from inspect import signature
|
||||
from traceback import print_exc
|
||||
from copy import copy
|
||||
from typing import Dict
|
||||
from typing import Dict, Callable
|
||||
|
||||
from .utils import undefined, _
|
||||
from .error import RegistrationError, CallError, NotAllowedError
|
||||
@ -18,7 +18,10 @@ def register(uri: str,
|
||||
"""
|
||||
version, uri = uri.split('.', 1)
|
||||
def decorator(function):
|
||||
dispatcher.set_function(version, uri, function)
|
||||
dispatcher.set_function(version,
|
||||
uri,
|
||||
notification,
|
||||
function)
|
||||
return decorator
|
||||
|
||||
|
||||
@ -100,7 +103,11 @@ class RegisterDispatcher:
|
||||
msg = _(f'extra arguments: {extra_function_args}')
|
||||
raise RegistrationError(_(f'error with {module_name}.{function_name} arguments: {msg}'))
|
||||
|
||||
def set_function(self, version, uri, function):
|
||||
def set_function(self,
|
||||
version: str,
|
||||
uri: str,
|
||||
notification: str,
|
||||
function: Callable):
|
||||
""" register a function to an URI
|
||||
URI is a message
|
||||
"""
|
||||
@ -145,11 +152,18 @@ class RegisterDispatcher:
|
||||
# valid function's arguments
|
||||
self._valid_rpc_params(version, uri, function, module_name)
|
||||
# register this function
|
||||
self.uris[version][uri] = {'module': module_name,
|
||||
'function': function,
|
||||
'risotto_context': inject_risotto_context}
|
||||
dico = {'module': module_name,
|
||||
'function': function,
|
||||
'risotto_context': inject_risotto_context}
|
||||
if notification is undefined:
|
||||
raise RegistrationError(_('notification is mandatory when registered {uri} with {module_name}.{function_name} even if you set None'))
|
||||
if notification:
|
||||
dico['notification'] = notification
|
||||
self.uris[version][uri] = dico
|
||||
else:
|
||||
# if event
|
||||
if notification and notification is not undefined:
|
||||
raise RegistrationError(_(f'notification not supported yet'))
|
||||
# valid function's arguments
|
||||
self._valid_event_params(version, uri, function, module_name)
|
||||
# register this function
|
||||
@ -164,7 +178,7 @@ class RegisterDispatcher:
|
||||
""" register and instanciate a new module
|
||||
"""
|
||||
try:
|
||||
self.modules[module_name] = module.Risotto()
|
||||
self.injected_self[module_name] = module.Risotto()
|
||||
except AttributeError as err:
|
||||
raise RegistrationError(_(f'unable to register the module {module_name}, this module must have Risotto class'))
|
||||
|
||||
@ -182,11 +196,13 @@ class Dispatcher(RegisterDispatcher):
|
||||
so launch a function when a message is called
|
||||
"""
|
||||
def __init__(self):
|
||||
self.modules = {}
|
||||
# reference to instanciate module (to inject self in method): {"module_name": instance_of_module}
|
||||
self.injected_self = {}
|
||||
# list of uris with informations: {"v1": {"module_name.xxxxx": yyyyyy}}
|
||||
self.uris = {}
|
||||
# all function for a module, to avoid conflict name {"v1": {"module_name": ["function_name"]}}
|
||||
self.function_names = {}
|
||||
self.messages, self.option = get_messages()
|
||||
config = Config(self.option)
|
||||
|
||||
def new_context(self,
|
||||
context: Context,
|
||||
@ -246,6 +262,51 @@ class Dispatcher(RegisterDispatcher):
|
||||
# return the config
|
||||
return config
|
||||
|
||||
def valid_call_returns(self,
|
||||
function: Callable,
|
||||
returns: Dict,
|
||||
version: str,
|
||||
uri:str,
|
||||
context: Context,
|
||||
kwargs: Dict):
|
||||
if not isinstance(returns, dict):
|
||||
module_name = function.__module__.split('.')[-2]
|
||||
function_name = function.__name__
|
||||
err = _(f'function {module_name}.{function_name} has to return a dict')
|
||||
log.error_msg(version, uri, context, kwargs, 'call', err)
|
||||
raise CallError(str(err))
|
||||
response = self.messages[uri]['response']
|
||||
if response is None:
|
||||
raise Exception('hu?')
|
||||
else:
|
||||
config = Config(response, display_name=lambda self, dyn_name: self.impl_getname())
|
||||
config.property.read_write()
|
||||
try:
|
||||
for key, value in returns.items():
|
||||
config.option(key).value.set(value)
|
||||
except AttributeError:
|
||||
module_name = function.__module__.split('.')[-2]
|
||||
function_name = function.__name__
|
||||
err = _(f'function {module_name}.{function_name} return the unknown parameter "{key}"')
|
||||
log.error_msg(version, uri, context, kwargs, 'call', err)
|
||||
raise CallError(str(err))
|
||||
except ValueError:
|
||||
module_name = function.__module__.split('.')[-2]
|
||||
function_name = function.__name__
|
||||
err = _(f'function {module_name}.{function_name} return the parameter "{key}" with an unvalid value "{value}"')
|
||||
log.error_msg(version, uri, context, kwargs, 'call', err)
|
||||
raise CallError(str(err))
|
||||
config.property.read_only()
|
||||
try:
|
||||
config.value.dict()
|
||||
except Exception as err:
|
||||
module_name = function.__module__.split('.')[-2]
|
||||
function_name = function.__name__
|
||||
err = _(f'function {module_name}.{function_name} return an invalid response {err}')
|
||||
log.error_msg(version, uri, context, kwargs, 'call', err)
|
||||
raise CallError(str(err))
|
||||
|
||||
|
||||
async def call(self, version, uri, risotto_context, public_only=False, **kwargs):
|
||||
""" execute the function associate with specified uri
|
||||
arguments are validate before
|
||||
@ -270,7 +331,7 @@ class Dispatcher(RegisterDispatcher):
|
||||
kw = config.option(uri).value.dict()
|
||||
if obj['risotto_context']:
|
||||
kw['risotto_context'] = new_context
|
||||
returns = await obj['function'](self.modules[obj['module']], **kw)
|
||||
returns = await obj['function'](self.injected_self[obj['module']], **kw)
|
||||
except CallError as err:
|
||||
raise err
|
||||
except Exception as err:
|
||||
@ -278,9 +339,22 @@ class Dispatcher(RegisterDispatcher):
|
||||
print_exc()
|
||||
log.error_msg(version, uri, new_context, kwargs, 'call', err)
|
||||
raise CallError(str(err))
|
||||
# FIXME notification
|
||||
# FIXME valider le retour!
|
||||
# valid returns
|
||||
self.valid_call_returns(obj['function'],
|
||||
returns,
|
||||
version,
|
||||
uri,
|
||||
new_context,
|
||||
kwargs)
|
||||
# log the success
|
||||
log.info_msg(version, uri, new_context, kwargs, 'call', _(f'returns {returns}'))
|
||||
# notification
|
||||
if obj.get('notification'):
|
||||
notif_version, notif_message = obj['notification'].split('.', 1)
|
||||
await self.publish(notif_version,
|
||||
notif_message,
|
||||
new_context,
|
||||
**returns)
|
||||
return returns
|
||||
|
||||
async def publish(self, version, uri, risotto_context, public_only=False, **kwargs):
|
||||
@ -320,7 +394,7 @@ class Dispatcher(RegisterDispatcher):
|
||||
if function_obj['risotto_context']:
|
||||
kw['risotto_context'] = new_context
|
||||
# send event
|
||||
await function(self.modules[function_obj['module']], **kw)
|
||||
await function(self.injected_self[function_obj['module']], **kw)
|
||||
except Exception as err:
|
||||
if DEBUG:
|
||||
print_exc()
|
||||
|
Reference in New Issue
Block a user