request_handler.py 15 KB

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