request_handler.py 17 KB

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