Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
responses = list(client.get_all_responses(SERVICE_NAME))
self.assertEqual(len(responses), 0)
request_id = client.send_request(
SERVICE_NAME,
action_request,
switches={1},
)
self.assertTrue(request_id >= 0)
responses = list(client.get_all_responses(SERVICE_NAME))
self.assertEqual(len(responses), 1)
response_id, response = responses[0]
# ensure that the response is structured as expected
self.assertEqual(response_id, request_id)
self.assertTrue(isinstance(response, JobResponse))
self.assertTrue(all([isinstance(a, ActionResponse) for a in response.actions]))
self.assertEqual(response.actions[0].action, 'action_1')
self.assertEqual(response.actions[0].body['foo'], 'bar')
self.assertEqual(response.actions[1].action, 'action_2')
self.assertEqual(response.actions[1].body['baz'], 3)
def _base_get_response(self, receive_timeout_in_seconds=None):
# type: (int) -> Tuple[Optional[int], Optional[JobResponse]]
with self.metrics.timer('client.receive.excluding_middleware', resolution=TimerResolution.MICROSECONDS):
request_id, meta, message = self.transport.receive_response_message(receive_timeout_in_seconds)
if message is None:
return None, None
else:
return request_id, JobResponse(**message)
request_id, response = self._middleware_get_response_wrapper(receive_timeout_in_seconds)
if request_id is None or response is None:
break
yield request_id, response
finally:
self.metrics.publish_all()
_FR = TypeVar(
'_FR',
ActionResponse,
JobResponse,
List[ActionResponse],
List[JobResponse],
Generator[ActionResponse, None, None],
Generator[JobResponse, None, None],
)
ActionRequestArgument = Union[
ActionRequest,
Dict[six.text_type, Any],
]
ActionRequestArgumentList = Union[
List[ActionRequest],
List[Dict[six.text_type, Any]],
]
ActionRequestArgumentIterable = Union[
Iterable[ActionRequest],
Iterable[Dict[six.text_type, Any]],
]
JobRequestArgument = Dict[six.text_type, Any]
:param request_for_logging: The censor-wrapped request dictionary.
:param response_for_logging: The censor-wrapped response dictionary.
:param extra: Any extra items to add to the logged error.
:return: A `JobResponse` object.
"""
log_extra = {'data': {'request': request_for_logging, 'response': response_for_logging}}
if extra:
log_extra['data'].update(extra)
self.logger.error(
message,
exc_info=True,
extra=log_extra,
)
return JobResponse(errors=[Error(code=code, message=message, is_caller_error=False)])
from pysoa.common.types import (
JobRequest,
JobResponse,
)
__all__ = (
'ClientMiddleware',
'ClientRequestMiddlewareTask',
'ClientResponseMiddlewareTask',
)
ClientRequestMiddlewareTask = Callable[[int, Dict[six.text_type, Any], JobRequest, Optional[int]], None]
ClientResponseMiddlewareTask = Callable[[Optional[int]], Tuple[Optional[int], Optional[JobResponse]]]
@fields.ClassConfigurationSchema.provider(fields.Dictionary(
{},
description='Most client middleware has no constructor arguments, but subclasses can override this schema',
))
class ClientMiddleware(object):
"""
Base middleware class for client middleware. Not required, but provides some helpful stubbed methods and
documentation that you should follow for creating your middleware classes. If you extend this class, you may
override either one or both of the methods.
Middleware must have two callable attributes, `request` and `response`, that, when called with the next level
down, return a callable that takes the appropriate arguments and returns the appropriate value.
"""
job_response = self._middleware_job_wrapper(EnrichedJobRequest(**job_request))
if 'correlation_id' in job_request['context']:
job_response.context['correlation_id'] = job_request['context']['correlation_id']
except HarakiriInterrupt:
self.metrics.counter('server.error.harakiri', harakiri_level='job')
job_response = JobResponse(
errors=[Error(
code=ERROR_CODE_JOB_TIMEOUT,
message='The service job ran for too long and had to be interrupted (probably a middleware issue).',
is_caller_error=False,
)],
)
except JobError as e:
self.metrics.counter('server.error.job_error').increment()
job_response = JobResponse(errors=e.errors)
except Exception as e:
# Send a job error response if no middleware caught this.
self.metrics.counter('server.error.unhandled_error').increment()
return self.handle_unhandled_exception(e, JobResponse)
return job_response
"""
try:
while True:
with self.metrics.timer('client.receive.including_middleware', resolution=TimerResolution.MICROSECONDS):
request_id, response = self._middleware_get_response_wrapper(receive_timeout_in_seconds)
if request_id is None or response is None:
break
yield request_id, response
finally:
self.metrics.publish_all()
_FR = TypeVar(
'_FR',
ActionResponse,
JobResponse,
List[ActionResponse],
List[JobResponse],
Generator[ActionResponse, None, None],
Generator[JobResponse, None, None],
)
ActionRequestArgument = Union[
ActionRequest,
Dict[six.text_type, Any],
]
ActionRequestArgumentList = Union[
List[ActionRequest],
List[Dict[six.text_type, Any]],
]
ActionRequestArgumentIterable = Union[
Iterable[ActionRequest],
Iterable[Dict[six.text_type, Any]],
class DatabaseError(Exception): # type: ignore
pass
__all__ = (
'HarakiriInterrupt',
'Server',
'ServerMiddlewareActionTask',
'ServerMiddlewareJobTask',
)
# A hack to make documentation generation work properly, otherwise there are errors (see `if TYPE_CHECKING`)
middleware.EnrichedActionRequest = EnrichedActionRequest # type: ignore
middleware.EnrichedJobRequest = EnrichedJobRequest # type: ignore
ServerMiddlewareJobTask = Callable[[EnrichedJobRequest], JobResponse]
ServerMiddlewareActionTask = Callable[[EnrichedActionRequest], ActionResponse]
_MT = TypeVar('_MT', ServerMiddlewareActionTask, ServerMiddlewareJobTask)
_RT = TypeVar('_RT', JobResponse, ActionResponse)
def _replace_fid(d, fid): # type: (Dict[Any, Any], six.text_type) -> None
for k, v in six.iteritems(d):
if isinstance(v, six.text_type):
d[k] = v.replace('{{fid}}', fid).replace('[[fid]]', fid).replace('%%fid%%', fid)
elif isinstance(v, dict):
_replace_fid(v, fid)
class HarakiriInterrupt(BaseException):
"""
Raised internally to notify the server code about interrupts due to harakiri. You should never, ever, ever, ever
def execute_job(self, job_request): # type: (EnrichedJobRequest) -> JobResponse
"""
Processes and runs the action requests contained in the job and returns a `JobResponse`.
:param job_request: The job request
:return: A `JobResponse` object
"""
# Run the Job's Actions
harakiri = False
job_response = JobResponse()
job_switches = RequestSwitchSet(job_request.context['switches'])
for i, simple_action_request in enumerate(job_request.actions):
# noinspection PyArgumentList
action_request = self.request_class(
action=simple_action_request.action,
body=simple_action_request.body,
switches=job_switches,
context=job_request.context,
control=job_request.control,
client=job_request.client,
run_coroutine=job_request.run_coroutine,
)
action_request._server = self
action_in_class_map = action_request.action in self.action_class_map
if action_in_class_map or action_request.action in ('status', 'introspect'):