33"""
44
55import sys
6- from concurrent .futures import ThreadPoolExecutor
76from awslambdaric import __version__
7+ from .lambda_runtime_exception import FaultException
88
99
1010def _user_agent ():
@@ -49,8 +49,9 @@ class LambdaRuntimeClient(object):
4949 and response. It allows for function authors to override the the default implementation, LambdaMarshaller which
5050 unmarshals and marshals JSON, to an instance of a class that implements the same interface."""
5151
52- def __init__ (self , lambda_runtime_address ):
52+ def __init__ (self , lambda_runtime_address , use_thread_for_polling_next = False ):
5353 self .lambda_runtime_address = lambda_runtime_address
54+ self .use_thread_for_polling_next = use_thread_for_polling_next
5455
5556 def post_init_error (self , error_response_data ):
5657 # These imports are heavy-weight. They implicitly trigger `import ssl, hashlib`.
@@ -69,9 +70,23 @@ def post_init_error(self, error_response_data):
6970 raise LambdaRuntimeClientError (endpoint , response .code , response_body )
7071
7172 def wait_next_invocation (self ):
72- with ThreadPoolExecutor () as e :
73- fut = e .submit (runtime_client .next )
74- response_body , headers = fut .result ()
73+ # Calling runtime_client.next() from a separate thread unblocks the main thread,
74+ # which can then process signals.
75+ if self .use_thread_for_polling_next :
76+ try :
77+ from concurrent .futures import ThreadPoolExecutor
78+
79+ with ThreadPoolExecutor (max_workers = 1 ) as executor :
80+ future = executor .submit (runtime_client .next )
81+ response_body , headers = future .result ()
82+ except Exception as e :
83+ raise FaultException (
84+ FaultException .LAMBDA_RUNTIME_CLIENT_ERROR ,
85+ "LAMBDA_RUNTIME Failed to get next invocation: {}" .format (str (e )),
86+ None ,
87+ )
88+ else :
89+ response_body , headers = runtime_client .next ()
7590 return InvocationRequest (
7691 invoke_id = headers .get ("Lambda-Runtime-Aws-Request-Id" ),
7792 x_amzn_trace_id = headers .get ("Lambda-Runtime-Trace-Id" ),
0 commit comments