add notification and valid returns
This commit is contained in:
parent
1d1b51d37b
commit
332dc61fd4
|
@ -2,7 +2,7 @@ from tiramisu import Config
|
||||||
from inspect import signature
|
from inspect import signature
|
||||||
from traceback import print_exc
|
from traceback import print_exc
|
||||||
from copy import copy
|
from copy import copy
|
||||||
from typing import Dict
|
from typing import Dict, Callable
|
||||||
|
|
||||||
from .utils import undefined, _
|
from .utils import undefined, _
|
||||||
from .error import RegistrationError, CallError, NotAllowedError
|
from .error import RegistrationError, CallError, NotAllowedError
|
||||||
|
@ -18,7 +18,10 @@ def register(uri: str,
|
||||||
"""
|
"""
|
||||||
version, uri = uri.split('.', 1)
|
version, uri = uri.split('.', 1)
|
||||||
def decorator(function):
|
def decorator(function):
|
||||||
dispatcher.set_function(version, uri, function)
|
dispatcher.set_function(version,
|
||||||
|
uri,
|
||||||
|
notification,
|
||||||
|
function)
|
||||||
return decorator
|
return decorator
|
||||||
|
|
||||||
|
|
||||||
|
@ -100,7 +103,11 @@ class RegisterDispatcher:
|
||||||
msg = _(f'extra arguments: {extra_function_args}')
|
msg = _(f'extra arguments: {extra_function_args}')
|
||||||
raise RegistrationError(_(f'error with {module_name}.{function_name} arguments: {msg}'))
|
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
|
""" register a function to an URI
|
||||||
URI is a message
|
URI is a message
|
||||||
"""
|
"""
|
||||||
|
@ -145,11 +152,18 @@ class RegisterDispatcher:
|
||||||
# valid function's arguments
|
# valid function's arguments
|
||||||
self._valid_rpc_params(version, uri, function, module_name)
|
self._valid_rpc_params(version, uri, function, module_name)
|
||||||
# register this function
|
# register this function
|
||||||
self.uris[version][uri] = {'module': module_name,
|
dico = {'module': module_name,
|
||||||
'function': function,
|
'function': function,
|
||||||
'risotto_context': inject_risotto_context}
|
'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:
|
else:
|
||||||
# if event
|
# if event
|
||||||
|
if notification and notification is not undefined:
|
||||||
|
raise RegistrationError(_(f'notification not supported yet'))
|
||||||
# valid function's arguments
|
# valid function's arguments
|
||||||
self._valid_event_params(version, uri, function, module_name)
|
self._valid_event_params(version, uri, function, module_name)
|
||||||
# register this function
|
# register this function
|
||||||
|
@ -164,7 +178,7 @@ class RegisterDispatcher:
|
||||||
""" register and instanciate a new module
|
""" register and instanciate a new module
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
self.modules[module_name] = module.Risotto()
|
self.injected_self[module_name] = module.Risotto()
|
||||||
except AttributeError as err:
|
except AttributeError as err:
|
||||||
raise RegistrationError(_(f'unable to register the module {module_name}, this module must have Risotto class'))
|
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
|
so launch a function when a message is called
|
||||||
"""
|
"""
|
||||||
def __init__(self):
|
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 = {}
|
self.uris = {}
|
||||||
|
# all function for a module, to avoid conflict name {"v1": {"module_name": ["function_name"]}}
|
||||||
self.function_names = {}
|
self.function_names = {}
|
||||||
self.messages, self.option = get_messages()
|
self.messages, self.option = get_messages()
|
||||||
config = Config(self.option)
|
|
||||||
|
|
||||||
def new_context(self,
|
def new_context(self,
|
||||||
context: Context,
|
context: Context,
|
||||||
|
@ -246,6 +262,51 @@ class Dispatcher(RegisterDispatcher):
|
||||||
# return the config
|
# return the config
|
||||||
return 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):
|
async def call(self, version, uri, risotto_context, public_only=False, **kwargs):
|
||||||
""" execute the function associate with specified uri
|
""" execute the function associate with specified uri
|
||||||
arguments are validate before
|
arguments are validate before
|
||||||
|
@ -270,7 +331,7 @@ class Dispatcher(RegisterDispatcher):
|
||||||
kw = config.option(uri).value.dict()
|
kw = config.option(uri).value.dict()
|
||||||
if obj['risotto_context']:
|
if obj['risotto_context']:
|
||||||
kw['risotto_context'] = new_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:
|
except CallError as err:
|
||||||
raise err
|
raise err
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
|
@ -278,9 +339,22 @@ class Dispatcher(RegisterDispatcher):
|
||||||
print_exc()
|
print_exc()
|
||||||
log.error_msg(version, uri, new_context, kwargs, 'call', err)
|
log.error_msg(version, uri, new_context, kwargs, 'call', err)
|
||||||
raise CallError(str(err))
|
raise CallError(str(err))
|
||||||
# FIXME notification
|
# valid returns
|
||||||
# FIXME valider le retour!
|
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}'))
|
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
|
return returns
|
||||||
|
|
||||||
async def publish(self, version, uri, risotto_context, public_only=False, **kwargs):
|
async def publish(self, version, uri, risotto_context, public_only=False, **kwargs):
|
||||||
|
@ -320,7 +394,7 @@ class Dispatcher(RegisterDispatcher):
|
||||||
if function_obj['risotto_context']:
|
if function_obj['risotto_context']:
|
||||||
kw['risotto_context'] = new_context
|
kw['risotto_context'] = new_context
|
||||||
# send event
|
# send event
|
||||||
await function(self.modules[function_obj['module']], **kw)
|
await function(self.injected_self[function_obj['module']], **kw)
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
if DEBUG:
|
if DEBUG:
|
||||||
print_exc()
|
print_exc()
|
||||||
|
|
|
@ -7,6 +7,8 @@ from .context import Context
|
||||||
from .error import CallError, NotAllowedError
|
from .error import CallError, NotAllowedError
|
||||||
from .message import get_messages
|
from .message import get_messages
|
||||||
from .logger import log
|
from .logger import log
|
||||||
|
from .config import DEBUG
|
||||||
|
from traceback import print_exc
|
||||||
|
|
||||||
|
|
||||||
async def handle(request):
|
async def handle(request):
|
||||||
|
@ -25,6 +27,8 @@ async def handle(request):
|
||||||
except CallError as err:
|
except CallError as err:
|
||||||
raise HTTPBadRequest(reason=str(err))
|
raise HTTPBadRequest(reason=str(err))
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
|
if DEBUG:
|
||||||
|
print_exc()
|
||||||
raise HTTPInternalServerError(reason=str(err))
|
raise HTTPInternalServerError(reason=str(err))
|
||||||
return Response(text=dumps({'response': text}))
|
return Response(text=dumps({'response': text}))
|
||||||
|
|
||||||
|
|
|
@ -448,53 +448,39 @@ def _parse_responses(message_def,
|
||||||
file_path):
|
file_path):
|
||||||
"""build option with returns
|
"""build option with returns
|
||||||
"""
|
"""
|
||||||
responses = OrderedDict()
|
if message_def.response.parameters is None:
|
||||||
if message_def.response:
|
raise Exception('not implemented yet')
|
||||||
keys = {'': {'description': '',
|
#name = 'response'
|
||||||
'columns': {}}}
|
#keys['']['columns'][name] = {'description': message_def.response.description,
|
||||||
provides = {}
|
# 'type': message_def.response.type}
|
||||||
to_list = True
|
#responses = {}
|
||||||
param_type = message_def.response.type
|
#responses['keys'] = keys
|
||||||
|
#return responses
|
||||||
|
|
||||||
if param_type.startswith('[]'):
|
options = []
|
||||||
to_list = False
|
names = []
|
||||||
param_type = param_type[2:]
|
|
||||||
if param_type in ['Dict', 'File']:
|
|
||||||
pass
|
|
||||||
|
|
||||||
if message_def.response.parameters is not None:
|
|
||||||
for name, obj in message_def.response.parameters.items():
|
for name, obj in message_def.response.parameters.items():
|
||||||
if name in responses:
|
if name in names:
|
||||||
raise Exception('multi response with name {} in {}'.format(name, file_path))
|
raise Exception('multi response with name {} in {}'.format(name, file_path))
|
||||||
|
names.append(name)
|
||||||
|
|
||||||
descr = obj.description.strip().rstrip()
|
option = {'String': StrOption,
|
||||||
keys['']['columns'][name] = {'description': obj.description,
|
'Number': IntOption,
|
||||||
'type': obj.type}
|
'Boolean': BoolOption,
|
||||||
ref = obj.ref
|
# FIXME
|
||||||
if ref:
|
'File': StrOption}.get(obj.type)
|
||||||
provides[name] = ref
|
if not option:
|
||||||
|
raise Exception(f'unknown param type {obj.type}')
|
||||||
|
kwargs = {'name': name,
|
||||||
|
'doc': obj.description.strip().rstrip()}
|
||||||
|
if hasattr(obj, 'default'):
|
||||||
|
kwargs['default'] = obj.default
|
||||||
else:
|
else:
|
||||||
keys['']['columns'][name] = {'description': descr,
|
kwargs['properties'] = ('mandatory',)
|
||||||
'type': obj.type}
|
options.append(option(**kwargs))
|
||||||
ref = obj.ref
|
return OptionDescription(message_def.uri,
|
||||||
if ref:
|
message_def.response.description,
|
||||||
provides[name] = ref
|
options)
|
||||||
responses['keys'] = keys
|
|
||||||
responses['to_list'] = to_list
|
|
||||||
responses['to_dict'] = False
|
|
||||||
responses['provides'] = provides
|
|
||||||
else:
|
|
||||||
name = 'response'
|
|
||||||
keys['']['columns'][name] = {'description': message_def.response.description,
|
|
||||||
'type': message_def.response.type}
|
|
||||||
ref = message_def.response.ref
|
|
||||||
if ref:
|
|
||||||
provides[name] = ref
|
|
||||||
responses['keys'] = keys
|
|
||||||
responses['to_list'] = to_list
|
|
||||||
responses['to_dict'] = True
|
|
||||||
responses['provides'] = provides
|
|
||||||
return responses
|
|
||||||
|
|
||||||
|
|
||||||
def _getoptions_from_yml(message_def,
|
def _getoptions_from_yml(message_def,
|
||||||
|
@ -564,7 +550,6 @@ def get_messages(load_shortarg=False, only_public=False):
|
||||||
optiondescriptions = OrderedDict()
|
optiondescriptions = OrderedDict()
|
||||||
optiondescriptions_name = []
|
optiondescriptions_name = []
|
||||||
optiondescriptions_info = {}
|
optiondescriptions_info = {}
|
||||||
responses = OrderedDict()
|
|
||||||
needs = OrderedDict()
|
needs = OrderedDict()
|
||||||
messages = list(list_messages())
|
messages = list(list_messages())
|
||||||
messages.sort()
|
messages.sort()
|
||||||
|
@ -586,9 +571,12 @@ def get_messages(load_shortarg=False, only_public=False):
|
||||||
continue
|
continue
|
||||||
optiondescriptions_info[message_def.uri] = {'pattern': message_def.pattern,
|
optiondescriptions_info[message_def.uri] = {'pattern': message_def.pattern,
|
||||||
'public': message_def.public}
|
'public': message_def.public}
|
||||||
|
if message_def.pattern == 'rpc':
|
||||||
|
optiondescriptions_info[message_def.uri]['response'] = _parse_responses(message_def,
|
||||||
|
message_name)
|
||||||
|
elif message_def.response:
|
||||||
|
raise Exception(f'response not allowed for {message_def.uri}')
|
||||||
version = message_name.split('.')[0]
|
version = message_name.split('.')[0]
|
||||||
if message_def.uri in responses:
|
|
||||||
raise Exception('uri {} allready loader'.format(message_def.uri))
|
|
||||||
_getoptions_from_yml(message_def,
|
_getoptions_from_yml(message_def,
|
||||||
version,
|
version,
|
||||||
optiondescriptions,
|
optiondescriptions,
|
||||||
|
@ -596,8 +584,6 @@ def get_messages(load_shortarg=False, only_public=False):
|
||||||
needs,
|
needs,
|
||||||
select_option,
|
select_option,
|
||||||
load_shortarg)
|
load_shortarg)
|
||||||
responses[message_def.uri] = _parse_responses(message_def,
|
|
||||||
message_name)
|
|
||||||
|
|
||||||
root = _get_root_option(select_option, optiondescriptions)
|
root = _get_root_option(select_option, optiondescriptions)
|
||||||
try:
|
try:
|
||||||
|
|
|
@ -11,7 +11,13 @@ class Risotto(Controller):
|
||||||
async def get_configuration(self, risotto_context, id):
|
async def get_configuration(self, risotto_context, id):
|
||||||
#stop = await self.call('v1.config.session.server.stop', risotto_context, sessionid=str(id))
|
#stop = await self.call('v1.config.session.server.stop', risotto_context, sessionid=str(id))
|
||||||
#await self.publish('v1.config.configuration.server.updated', risotto_context, server_id=1, deploy=True)
|
#await self.publish('v1.config.configuration.server.updated', risotto_context, server_id=1, deploy=True)
|
||||||
return {'start': id}
|
return {'id': id,
|
||||||
|
'sessionid': 'sess',
|
||||||
|
'username': risotto_context.username,
|
||||||
|
'timestamp': 0,
|
||||||
|
'namespace': 'creole',
|
||||||
|
'mode': 'basic',
|
||||||
|
'debug': False}
|
||||||
|
|
||||||
@register('v1.config.session.server.stop', None)
|
@register('v1.config.session.server.stop', None)
|
||||||
async def get_configuration2(self, sessionid, save):
|
async def get_configuration2(self, sessionid, save):
|
||||||
|
@ -21,6 +27,6 @@ class Risotto(Controller):
|
||||||
async def get_configuration3(self, server_id, deploy):
|
async def get_configuration3(self, server_id, deploy):
|
||||||
return {'get': server_id}
|
return {'get': server_id}
|
||||||
|
|
||||||
@register('v1.config.configuration.server.deploy', None)
|
@register('v1.config.configuration.server.deploy')
|
||||||
async def get_configuration4(self, server_id):
|
async def get_configuration4(self, server_id):
|
||||||
return {'deploy': server_id}
|
return {'deploy': server_id}
|
||||||
|
|
Loading…
Reference in New Issue