request_handler.py 15 KB

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