request_handler.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. import sys
  2. import modelverse_kernel.primitives as primitive_functions
  3. import modelverse_jit.runtime as jit_runtime
  4. from collections import defaultdict
  5. class KnownRequestHandled(Exception):
  6. """An exception that signifies that a known request was handled."""
  7. pass
  8. def format_stack_trace(stack_trace):
  9. """Formats a list of (function name, debug info, origin) triples."""
  10. return '\n'.join([jit_runtime.format_stack_frame(*triple) for triple in stack_trace])
  11. class UnhandledRequestHandlerException(Exception):
  12. """The type of exception that is thrown when the request handler encounters an
  13. unhandled exception."""
  14. def __init__(self, inner_exception, stack_trace):
  15. import traceback
  16. Exception.__init__(
  17. self,
  18. """The request handler encountered an unknown exception.\n
  19. Inner exception: %s\n
  20. Stack trace:\n%s\n""" % (traceback.format_exc(), format_stack_trace(stack_trace)))
  21. self.inner_exception = inner_exception
  22. self.stack_trace = stack_trace
  23. class RequestHandler(object):
  24. """A type of object that intercepts logic-related Modelverse requests, and
  25. forwards Modelverse state requests."""
  26. def __init__(self):
  27. # generator_stack is a stack of GeneratorStackEntry values.
  28. self.generator_stack = []
  29. # exception_handlers is a stack of
  30. # (generator_stack index, [(exception type, handler function)])
  31. # tuples.
  32. self.exception_handlers = []
  33. self.produce_stack_trace = True
  34. self.handlers = {
  35. 'CALL' : self.execute_call,
  36. 'CALL_ARGS' : self.execute_call_args,
  37. 'CALL_KWARGS' : self.execute_call_kwargs,
  38. 'TAIL_CALL' : self.execute_tail_call,
  39. 'TAIL_CALL_ARGS' : self.execute_tail_call_args,
  40. 'TAIL_CALL_KWARGS' : self.execute_tail_call_kwargs,
  41. 'TRY' : self.execute_try,
  42. 'CATCH' : self.execute_catch,
  43. 'END_TRY' : self.execute_end_try,
  44. 'DEBUG_INFO' : self.execute_debug_info
  45. }
  46. def is_active(self):
  47. """Tests if this request handler has a top-of-stack generator."""
  48. return len(self.generator_stack) > 0
  49. def handle_request(self, reply):
  50. """Replies to a request from the top-of-stack generator, and returns a new request."""
  51. if not self.is_active():
  52. raise ValueError('handle_request cannot be called with an empty generator stack.')
  53. # Append the server's replies to the list of replies.
  54. if reply is not None:
  55. if self.generator_stack[-1]["replies"] is None:
  56. self.generator_stack[-1]["replies"] = reply
  57. else:
  58. self.generator_stack[-1]["replies"].extend(reply)
  59. while 1:
  60. # Silence pylint's warning about catching Exception.
  61. # pylint: disable=I0011,W0703
  62. try:
  63. while self.generator_stack[-1]["finished_requests"]:
  64. gen = self.generator_stack[-1]
  65. gen["pending_requests"] = gen["generator"].send(gen["replies"])
  66. gen["finished_requests"] = False
  67. gen["replies"] = None
  68. else:
  69. return self.pop_requests()
  70. except KnownRequestHandled:
  71. pass
  72. except StopIteration:
  73. # Done, so remove the generator
  74. self.pop_generator()
  75. if self.is_active():
  76. # This generator was called from another generator.
  77. # Append 'None' to the caller's list of replies.
  78. self.append_reply(None)
  79. else:
  80. # Looks like we're done here.
  81. return None
  82. except primitive_functions.PrimitiveFinished as ex:
  83. # Done, so remove the generator
  84. self.pop_generator()
  85. if self.is_active():
  86. # This generator was called from another generator.
  87. # Append the callee's result to the caller's list of replies.
  88. self.append_reply(ex.result)
  89. else:
  90. # Looks like we're done here.
  91. return None
  92. except Exception as ex:
  93. # Maybe get an exception handler to do this.
  94. stack_trace = self.handle_exception(ex)
  95. if stack_trace is not None:
  96. if self.produce_stack_trace:
  97. raise UnhandledRequestHandlerException(ex, stack_trace)
  98. else:
  99. raise
  100. def set_finished_requests_flag(self):
  101. """Sets the finished_requests flag in the top-of-stack tuple."""
  102. self.generator_stack[-1]["finished_requests"] = True
  103. def has_pending_requests(self):
  104. """Tests if the top-of-stack generator has pending requests."""
  105. return not self.generator_stack[-1]["finished_requests"]
  106. def push_generator(self, gen):
  107. """Pushes a new generator onto the stack."""
  108. dd = defaultdict(lambda : None)
  109. dd["generator"] = gen
  110. dd["finished_requests"] = True
  111. self.generator_stack.append(dd)
  112. # print('Pushed generator %s. Generator count: %d' % (gen, len(self.generator_stack)))
  113. def pop_generator(self):
  114. """Removes the top-of-stack generator from the generator stack."""
  115. # Pop the generator itself.
  116. self.generator_stack.pop()
  117. # print('Popped generator %s. Generator count: %d' % (gen, len(self.generator_stack)))
  118. # Pop any exception handlers defined by the generator.
  119. top_of_stack_index = len(self.generator_stack)
  120. while len(self.exception_handlers) > 0:
  121. stack_index, _ = self.exception_handlers[-1]
  122. if stack_index == top_of_stack_index:
  123. # Pop exception handlers until exception_handlers is empty or until
  124. # we find an exception handler that is not associated with the popped
  125. # generator.
  126. self.exception_handlers.pop()
  127. else:
  128. # We're done here.
  129. break
  130. def append_reply(self, new_reply):
  131. """Appends a reply to the top-of-stack generator's list of pending replies."""
  132. if self.generator_stack[-1]["replies"] is None:
  133. self.generator_stack[-1]["replies"] = [new_reply]
  134. else:
  135. self.generator_stack[-1]["replies"].append(new_reply)
  136. def handle_exception(self, exception):
  137. """Handles the given exception. A Boolean is returned that tells if
  138. the exception was handled."""
  139. # print('Exception thrown from %s: %s' % (str(self.generator_stack[-1]), str(exception)))
  140. while len(self.exception_handlers) > 0:
  141. # Pop the top-of-stack exception handler.
  142. stack_index, handlers = self.exception_handlers.pop()
  143. # Try to find an applicable handler.
  144. applicable_handler = None
  145. for handled_type, handler in handlers:
  146. if isinstance(exception, handled_type):
  147. applicable_handler = handler
  148. if applicable_handler is not None:
  149. # We handle exceptions by first clearing the current stack frame and
  150. # all of its children. Then, we place a dummy frame on the stack with
  151. # a single 'TAIL_CALL_ARGS' request. The next iteration will replace
  152. # the dummy frame by an actual frame.
  153. del self.generator_stack[stack_index:]
  154. stack_entry = defaultdict(lambda : None)
  155. stack_entry["pending_requests"] = [('TAIL_CALL_ARGS', [applicable_handler, (exception,)])]
  156. stack_entry["finished_requests"] = False
  157. self.generator_stack.append(stack_entry)
  158. return None
  159. # We couldn't find an applicable exception handler, even after exhausting the
  160. # entire exception handler stack. All is lost.
  161. # Also, clean up after ourselves by unwinding the stack.
  162. return self.unwind_stack()
  163. def unwind_stack(self):
  164. """Unwinds the entirety of the stack. All generators and exception handlers are
  165. discarded. A list of (function name, debug information, source) statements is
  166. returned."""
  167. class UnwindStackException(Exception):
  168. """A hard-to-catch exception that is used to make generators crash.
  169. The exceptions they produce can then be analyzed for line numbers."""
  170. pass
  171. # First throw away all exception handlers. We won't be needing them any more.
  172. self.exception_handlers = []
  173. # Then pop every generator from the stack and make it crash.
  174. stack_trace = []
  175. while len(self.generator_stack) > 0:
  176. top_entry = self.generator_stack.pop()
  177. if top_entry["function_origin"] is None:
  178. # Skip this function.
  179. continue
  180. try:
  181. # Crash the generator.
  182. top_entry["generator"].throw(UnwindStackException())
  183. except UnwindStackException:
  184. # Find out where the exception was thrown.
  185. _, _, exc_traceback = sys.exc_info()
  186. line_number = exc_traceback.tb_lineno
  187. source_map = top_entry["source_map"]
  188. if source_map is not None:
  189. debug_info = source_map.get_debug_info(line_number)
  190. else:
  191. debug_info = None
  192. function_name = top_entry["function_name"]
  193. stack_trace.append((function_name, debug_info, top_entry["function_origin"]))
  194. return stack_trace[::-1]
  195. def pop_requests(self):
  196. """Tries to pop a batch of Modelverse _state_ requests from the
  197. current list of requests. Known requests are executed immediately.
  198. A list of requests and a Boolean are returned. The latter is True
  199. if there are no more requests to process, and false otherwise."""
  200. requests = self.generator_stack[-1]["pending_requests"]
  201. if requests is None or len(requests) == 0:
  202. # Couldn't find a request for the state to handle.
  203. self.set_finished_requests_flag()
  204. return requests
  205. for i, elem in enumerate(requests):
  206. if elem[0] in self.handlers:
  207. # The kernel should handle known requests.
  208. if i > 0:
  209. # Handle any requests that precede the known request first.
  210. pre_requests = requests[:i]
  211. del requests[:i]
  212. return pre_requests
  213. # The known request must be the first element in the list. Pop it.
  214. requests.pop(0)
  215. # The list of requests might be empty now. If so, then flag this
  216. # batch of requests as finished.
  217. if len(requests) == 0:
  218. self.set_finished_requests_flag()
  219. # Handle the request.
  220. _, request_args = elem
  221. self.handlers[elem[0]](request_args)
  222. raise KnownRequestHandled()
  223. # We couldn't find a known request in the batch of requests, so we might as well
  224. # handle them all at once then.
  225. self.set_finished_requests_flag()
  226. return requests
  227. def execute_call(self, request_args):
  228. """Executes a CALL-request with the given argument list."""
  229. # Format: ("CALL", [gen])
  230. gen, = request_args
  231. self.push_generator(gen)
  232. def execute_call_kwargs(self, request_args):
  233. """Executes a CALL_KWARGS-request with the given argument list."""
  234. # Format: ("CALL_KWARGS", [func, kwargs])
  235. # This format is useful because it also works for functions that
  236. # throw an exception but never yield.
  237. func, kwargs = request_args
  238. # We need to be extra careful here, because func(**kwargs) might
  239. # not be a generator at all: it might simply be a method that
  240. # raises an exception. To cope with this we need to push a dummy
  241. # entry onto the stack if a StopIteration or PrimtiveFinished
  242. # exception is thrown. The logic in execute_yields will then pop
  243. # that dummy entry.
  244. try:
  245. self.push_generator(func(**kwargs))
  246. except StopIteration:
  247. self.push_generator(None)
  248. raise
  249. except primitive_functions.PrimitiveFinished:
  250. self.push_generator(None)
  251. raise
  252. def execute_call_args(self, request_args):
  253. """Executes a CALL_ARGS-request with the given argument list."""
  254. # Format: ("CALL_ARGS", [gen, args])
  255. func, args = request_args
  256. # We need to be extra careful here, because func(*args) might
  257. # not be a generator at all: it might simply be a method that
  258. # raises an exception. To cope with this we need to push a dummy
  259. # entry onto the stack if a StopIteration or PrimtiveFinished
  260. # exception is thrown. The logic in execute_yields will then pop
  261. # that dummy entry.
  262. try:
  263. self.push_generator(func(*args))
  264. except StopIteration:
  265. self.push_generator(None)
  266. raise
  267. except primitive_functions.PrimitiveFinished:
  268. self.push_generator(None)
  269. raise
  270. def execute_tail_call(self, request_args):
  271. """Executes a TAIL_CALL-request with the given argument list."""
  272. # Format: ("TAIL_CALL", [gen])
  273. self.pop_generator()
  274. self.execute_call(request_args)
  275. def execute_tail_call_args(self, request_args):
  276. """Executes a TAIL_CALL_ARGS-request with the given argument list."""
  277. # Format: ("TAIL_CALL_ARGS", [gen, args])
  278. self.pop_generator()
  279. self.execute_call_args(request_args)
  280. def execute_tail_call_kwargs(self, request_args):
  281. """Executes a TAIL_CALL_KWARGS-request with the given argument list."""
  282. # Format: ("TAIL_CALL_KWARGS", [gen, kwargs])
  283. self.pop_generator()
  284. self.execute_call_kwargs(request_args)
  285. def execute_try(self, request_args):
  286. """Executes a TRY-request with the given argument list."""
  287. # TRY pushes an exception handler onto the exception handler stack.
  288. # Format: ("TRY", [])
  289. if len(request_args) != 0:
  290. raise ValueError(
  291. ("TRY was given argument list '%s', " +
  292. "expected exactly zero arguments.") % repr(request_args))
  293. self.exception_handlers.append((len(self.generator_stack) - 1, []))
  294. self.append_reply(None)
  295. def execute_catch(self, request_args):
  296. """Executes a CATCH-request with the given argument list."""
  297. if len(request_args) != 2:
  298. raise ValueError(
  299. ("CATCH was given argument list '%s', "
  300. "expected exactly two arguments: an exception "
  301. "type and an exception handler.") % repr(request_args))
  302. exception_type, handler = request_args
  303. stack_index, handlers = self.exception_handlers[-1]
  304. if stack_index != len(self.generator_stack) - 1:
  305. raise ValueError(
  306. 'Cannot comply with CATCH because there is no exception handler for the '
  307. 'current generator.')
  308. handlers.append((exception_type, handler))
  309. self.append_reply(None)
  310. def execute_end_try(self, request_args):
  311. """Executes an END_TRY-request with the given argument list."""
  312. # END_TRY pops a value from the exception handler stack. The
  313. # popped value must reference the top-of-stack element in the
  314. # generator stack. END_TRY takes no arguments.
  315. # Format: ("END_TRY", [])
  316. if len(request_args) != 0:
  317. raise ValueError(
  318. "END_TRY was given argument list '%s', expected '%s'." % (
  319. repr(request_args), repr([])))
  320. if len(self.exception_handlers) == 0:
  321. raise ValueError(
  322. 'Cannot comply with END_TRY because the exception handler stack is empty.')
  323. stack_index, _ = self.exception_handlers[-1]
  324. if stack_index != len(self.generator_stack) - 1:
  325. raise ValueError(
  326. 'Cannot comply with END_TRY because there is no exception handler for the '
  327. 'current generator.')
  328. # Everything seems to be in order. Pop the exception handler.
  329. self.exception_handlers.pop()
  330. self.append_reply(None)
  331. def execute_debug_info(self, request_args):
  332. """Executes a DEBUG_INFO-request with the given argument list."""
  333. # DEBUG_INFO updates the function name and source map for the top-of-stack generator.
  334. # These two things allow us to unwind the stack neatly if an unhandled exception is
  335. # encountered.
  336. # Format: ("DEBUG_INFO", [function_name, source_map])
  337. top_entry = self.generator_stack[-1]
  338. top_entry["function_name"], top_entry["source_map"], top_entry["function_origin"] = request_args
  339. self.append_reply(None)