Exemplo n.º 1
0
    def _dispatch_message(self, message, args, target, type_: str):
        if isinstance(message, str):
            message = getattr(self._message_factory, type_)(message, ffd.build_argument_list(args.__dict__, target))
        else:
            message = message(ffd.build_argument_list(args.__dict__, target))

        if type_ == 'command':
            return self._bus.invoke(message)
        if type_ == 'event':
            return self._bus.dispatch(message)
        return self._bus.query(message)
Exemplo n.º 2
0
    def __call__(self, message: ffd.Message, next_: Callable) -> ffd.Message:
        if not self._initialized:
            self._initialize()

        not_for_this_context = message.get_context() != 'firefly' and \
                               self._context_map.get_context(message.get_context()) is None
        is_async = hasattr(message, '_async') and getattr(message, '_async') is True

        if not_for_this_context or is_async:
            return self._transfer_message(message)

        args = message.to_dict()
        args['_message'] = message

        if str(message) not in self._command_handlers:
            raise ffd.ConfigurationError(f'No command handler registered for {message}')

        service = self._command_handlers[str(message)]

        if self._service_is_batch_capable(service) and self._batch_service.is_registered(service.__class__):
            self.debug('Deferring to batch service')
            return self._batch_service.handle(service, args)
        else:
            parsed_args = ffd.build_argument_list(args, service)
            self.debug('Calling service %s with arguments: %s', service, parsed_args)
            return service(**parsed_args)
Exemplo n.º 3
0
    def __call__(self, **kwargs):
        try:
            aggregate = self._registry(self._type()).find(
                kwargs[self._aggregate_name_snake()])
        except KeyError:
            raise ffd.MissingArgument(self._aggregate_name_snake())

        method = getattr(aggregate, self._method)
        return self._buffer_events(
            method(**ffd.build_argument_list(kwargs, method)))
Exemplo n.º 4
0
    def __call__(self, **kwargs) -> ffd.Entity:
        type_ = self._type()
        method = self._find_factory_method(type_)
        if method is not None:
            entity = method(type_, **kwargs)
        else:
            entity = type_(**ffd.build_argument_list(kwargs, type_))
        self._registry(type_).append(entity)
        self.dispatch(
            self._build_event(type_, 'create', asdict(entity),
                              kwargs['_context']))

        return entity
Exemplo n.º 5
0
    def __call__(self, message: ffd.Message, next_: Callable) -> ffd.Message:
        if not self._initialized:
            self._initialize()

        # TODO Fix the local dev server to work with multiple contexts
        if self._context is not None and message.get_context() != 'firefly' and message.get_context() != self._context:
            return self._transfer_message(message)

        args = message.to_dict()
        args['_message'] = message
        for service, query_type in self._query_handlers.items():
            if message.is_this(query_type):
                return service(**ffd.build_argument_list(args, service))
        raise ffd.ConfigurationError(f'No query handler registered for {message}')
Exemplo n.º 6
0
    def __call__(self, message: ffd.Message, next_: Callable) -> ffd.Message:
        if not self._initialized:
            self._initialize()

        if message.get_context() != 'firefly' and self._context_map.get_context(message.get_context()) is None:
            return self._transfer_message(message)

        args = message.to_dict()
        args['_message'] = message
        for service, query_type in self._query_handlers.items():
            if message.is_this(query_type):
                parsed_args = ffd.build_argument_list(args, service)
                self.debug('Calling service with arguments: %s', parsed_args)
                return service(**parsed_args)
        raise ffd.ConfigurationError(f'No query handler registered for {message}')
Exemplo n.º 7
0
    def __call__(self, message: ffd.Message, next_: Callable) -> ffd.Message:
        if not self._initialized:
            self._initialize()

        # TODO Fix the local dev server to work with multiple contexts
        if self._context is not None and message.get_context(
        ) != 'firefly' and message.get_context() != self._context:
            return self._transfer_message(message)

        args = message.to_dict()
        args['_message'] = message

        if str(message) not in self._command_handlers:
            raise ffd.ConfigurationError(
                f'No command handler registered for {message}')

        service = self._command_handlers[str(message)]

        return service(**ffd.build_argument_list(args, service))
Exemplo n.º 8
0
    def __call__(self, message: ffd.Message, next_: Callable) -> ffd.Message:
        if not self._initialized:
            self._initialize()

        self.debug('Message context: %s', message.get_context())
        self.debug('This context: %s', self._context)
        self.debug('Environment: %s', self._ff_environment)
        if message.get_context() != 'firefly' and \
                message.get_context() == self._context and \
                not message.headers.get('external', False) and \
                self._ff_environment != 'test':
            self.debug(
                'EventResolvingMiddleware - event originated from this context. Dispatching.'
            )
            self._publish_message(message)
            return next_(message)

        args = message.to_dict(recursive=False)
        args['_message'] = message

        if str(message) in self._event_listeners:
            services = self._event_listeners[str(message)]
            for service in services:
                try:
                    if self._service_is_batch_capable(
                            service) and self._batch_service.is_registered(
                                service.__class__):
                        self.debug('Deferring to batch service')
                        return self._batch_service.handle(service, args)
                    else:
                        parsed_args = ffd.build_argument_list(args, service)
                        self.debug('Calling service %s with arguments: %s',
                                   service.__class__.__name__, parsed_args)
                        service(**parsed_args)
                except TypeError as e:
                    self.exception(e)
                    raise ffd.FrameworkError(
                        f'Error calling {service.__class__.__name__}:\n\n{str(e)}'
                    )
        else:
            self.info('No event listener found for message %s', message)

        return next_(message)
Exemplo n.º 9
0
    def deserialize(self, data):
        try:
            if isinstance(data, (str, bytes, bytearray)):
                ret = json.loads(data)
            else:
                ret = data
        except json.JSONDecodeError:
            raise ffd.InvalidArgument('Could not deserialize data')

        if isinstance(ret, dict) and '_name' in ret:
            fqn = f'{ret["_context"]}.{ret["_name"]}'
            t = ffd.load_class(fqn)
            if t is None:
                args = [fqn]
                if ret['_type'] == 'query':
                    args.append(None)
                args.append(ret)
                return getattr(self._message_factory, ret['_type'])(*args)
            return t(**ffd.build_argument_list(ret, t))

        return ret
    def __call__(self, **kwargs) -> ffd.Entity:
        type_ = self._type()

        hints = get_type_hints(type_)
        for field_ in fields(type_):
            if ffd.is_aggregate_reference(hints[field_.name]):
                value = ffd.apply_aggregate(kwargs[field_.name],
                                            hints[field_.name],
                                            self._load_aggregate_reference)
                if value is not None:
                    kwargs[field_.name] = value

        method = self._find_factory_method(type_)
        if method is not None:
            entity = method(type_, **kwargs)
        else:
            entity = type_(**ffd.build_argument_list(kwargs, type_))

        self._registry(type_).append(entity)
        self.dispatch(
            self._build_event(type_, 'create', entity.to_dict(force_all=True),
                              entity.get_class_context()))

        return entity
Exemplo n.º 11
0
    def __call__(self, message: ffd.Message, next_: Callable) -> ffd.Message:
        if not self._initialized:
            self._initialize()

        if message.get_context() != 'firefly' and \
                message.get_context() == self._context and \
                not message.headers.get('external', False):
            self._publish_message(message)
            return next_(message)

        args = message.to_dict(recursive=False)
        args['_message'] = message

        if str(message) in self._event_listeners:
            services = self._event_listeners[str(message)]
            for service in services:
                try:
                    service(**ffd.build_argument_list(args, service))
                except TypeError as e:
                    raise ffd.FrameworkError(
                        f'Error calling {service.__class__.__name__}:\n\n{str(e)}'
                    )

        return next_(message)
 def __call__(self, message: ffd.Message, next_: Callable) -> ffd.Message:
     args = asdict(message)
     args['_message'] = message
     return next_(
         self._service(**ffd.build_argument_list(args, self._service)))