AsyncRequest.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. #from otp.ai.AIBaseGlobal import *
  2. from direct.directnotify import DirectNotifyGlobal
  3. from direct.showbase.DirectObject import DirectObject
  4. from .ConnectionRepository import *
  5. from panda3d.core import ConfigVariableDouble, ConfigVariableInt, ConfigVariableBool
  6. ASYNC_REQUEST_DEFAULT_TIMEOUT_IN_SECONDS = 8.0
  7. ASYNC_REQUEST_INFINITE_RETRIES = -1
  8. ASYNC_REQUEST_DEFAULT_NUM_RETRIES = 0
  9. if __debug__:
  10. _overrideTimeoutTimeForAllAsyncRequests = ConfigVariableDouble("async-request-timeout", -1.0)
  11. _overrideNumRetriesForAllAsyncRequests = ConfigVariableInt("async-request-num-retries", -1)
  12. _breakOnTimeout = ConfigVariableBool("async-request-break-on-timeout", False)
  13. class AsyncRequest(DirectObject):
  14. """
  15. This class is used to make asynchronous reads and creates to a database.
  16. You can create a list of self.neededObjects and then ask for each to be
  17. read or created, or if you only have one object that you need you can
  18. skip the self.neededObjects because calling askForObject or createObject
  19. will set the self.neededObjects value for you.
  20. Once all the objects have been read or created, the self.finish() method
  21. will be called. You may override this function to run your code in a
  22. derived class.
  23. If you wish to queue up several items that you all need before the finish
  24. method is called, you can put items in self.neededObjects and then call
  25. askForObject or createObject afterwards. That way the _checkCompletion
  26. will not call finish until after all the requests have been done.
  27. If you need to chain serveral object reads or creates, just add more
  28. entries to the self.neededObjects dictionary in the self.finish function
  29. and return without calling AsyncRequest.finish(). Your finish method
  30. will be called again when the new self.neededObjects is complete. You
  31. may repeat this as necessary.
  32. """
  33. _asyncRequests = {}
  34. notify = DirectNotifyGlobal.directNotify.newCategory('AsyncRequest')
  35. def __init__(self, air, replyToChannelId = None,
  36. timeoutTime = ASYNC_REQUEST_DEFAULT_TIMEOUT_IN_SECONDS,
  37. numRetries = ASYNC_REQUEST_DEFAULT_NUM_RETRIES):
  38. """
  39. air is the AI Respository.
  40. replyToChannelId may be an avatarId, an accountId, or a channelId.
  41. timeoutTime is how many seconds to wait before aborting the request.
  42. numRetries is the number of times to retry the request before giving up.
  43. """
  44. assert AsyncRequest.notify.debugCall()
  45. if __debug__:
  46. if _overrideTimeoutTimeForAllAsyncRequests.getValue() >= 0.0:
  47. timeoutTime = _overrideTimeoutTimeForAllAsyncRequests.getValue()
  48. if _overrideNumRetriesForAllAsyncRequests.getValue() >= 0:
  49. numRetries = _overrideNumRetriesForAllAsyncRequests.getValue()
  50. AsyncRequest._asyncRequests[id(self)] = self
  51. self.deletingMessage = "AsyncRequest-deleting-%s"%(id(self,))
  52. self.air = air
  53. self.replyToChannelId = replyToChannelId
  54. self.timeoutTask = None
  55. self.neededObjects = {}
  56. self._timeoutTime = timeoutTime
  57. self._initialNumRetries = numRetries
  58. def delete(self):
  59. assert AsyncRequest.notify.debugCall()
  60. del AsyncRequest._asyncRequests[id(self)]
  61. self.ignoreAll()
  62. self._resetTimeoutTask(False)
  63. messenger.send(self.deletingMessage, [])
  64. del self.neededObjects
  65. del self.air
  66. del self.replyToChannelId
  67. def askForObjectField(
  68. self, dclassName, fieldName, doId, key = None, context = None):
  69. """
  70. Request an already created object, i.e. read from database.
  71. """
  72. assert AsyncRequest.notify.debugCall()
  73. if key is None:
  74. # default the dictionary key to the fieldName
  75. key = fieldName
  76. assert doId
  77. if context is None:
  78. context = self.air.allocateContext()
  79. self.air.contextToClassName[context] = dclassName
  80. self.acceptOnce(
  81. "doFieldResponse-%s"%(context,),
  82. self._checkCompletion, [key])
  83. self.neededObjects[key] = None
  84. self.air.queryObjectField(dclassName, fieldName, doId, context)
  85. self._resetTimeoutTask()
  86. def askForObjectFields(
  87. self, dclassName, fieldNames, doId, key = None, context = None):
  88. """
  89. Request an already created object, i.e. read from database.
  90. """
  91. assert AsyncRequest.notify.debugCall()
  92. if key is None:
  93. # default the dictionary key to the fieldName
  94. key = fieldNames[0]
  95. assert doId
  96. if context is None:
  97. context = self.air.allocateContext()
  98. self.air.contextToClassName[context] = dclassName
  99. self.acceptOnce(
  100. "doFieldResponse-%s"%(context,),
  101. self._checkCompletion, [key])
  102. self.air.queryObjectFields(dclassName, fieldNames, doId, context)
  103. self._resetTimeoutTask()
  104. def askForObjectFieldsByString(self, dbId, dclassName, objString, fieldNames, key=None, context=None):
  105. assert AsyncRequest.notify.debugCall()
  106. assert dbId
  107. if key is None:
  108. # default the dictionary key to the fieldNames
  109. key = fieldNames
  110. if context is None:
  111. context=self.air.allocateContext()
  112. self.air.contextToClassName[context]=dclassName
  113. self.acceptOnce(
  114. "doFieldResponse-%s"%(context,),
  115. self._checkCompletion, [key])
  116. self.air.queryObjectStringFields(dbId,dclassName,objString,fieldNames,context)
  117. self._resetTimeoutTask()
  118. def askForObject(self, doId, context = None):
  119. """
  120. Request an already created object, i.e. read from database.
  121. """
  122. assert AsyncRequest.notify.debugCall()
  123. assert doId
  124. if context is None:
  125. context = self.air.allocateContext()
  126. self.acceptOnce(
  127. "doRequestResponse-%s"%(context,),
  128. self._checkCompletion, [None])
  129. self.air.queryObjectAll(doId, context)
  130. self._resetTimeoutTask()
  131. def createObject(self, name, className,
  132. databaseId = None, values = None, context = None):
  133. """
  134. Create a new database object. You can get the doId from within
  135. your self.finish() function.
  136. This functions is different from createObjectId in that it does
  137. generate the object when the response comes back. The object is
  138. added to the doId2do and so forth and treated as a full regular
  139. object (which it is). This is useful on the AI where we really
  140. do want the object on the AI.
  141. """
  142. assert AsyncRequest.notify.debugCall()
  143. assert name
  144. assert className
  145. self.neededObjects[name] = None
  146. if context is None:
  147. context = self.air.allocateContext()
  148. self.accept(
  149. self.air.getDatabaseGenerateResponseEvent(context),
  150. self._doCreateObject, [name, className, values])
  151. self.air.requestDatabaseGenerate(
  152. className, context, databaseId = databaseId, values = values)
  153. self._resetTimeoutTask()
  154. def createObjectId(self, name, className, values = None, context = None):
  155. """
  156. Create a new database object. You can get the doId from within
  157. your self.finish() function.
  158. This functions is different from createObject in that it does not
  159. generate the object when the response comes back. It only tells you
  160. the doId. This is useful on the UD where we don't really want the
  161. object on the UD, we just want the object created and the UD wants
  162. to send messages to it using the ID.
  163. """
  164. assert AsyncRequest.notify.debugCall()
  165. assert name
  166. assert className
  167. self.neededObjects[name] = None
  168. if context is None:
  169. context = self.air.allocateContext()
  170. self.accept(
  171. self.air.getDatabaseGenerateResponseEvent(context),
  172. self._checkCompletion, [name, None])
  173. self.air.requestDatabaseGenerate(className, context, values = values)
  174. self._resetTimeoutTask()
  175. def finish(self):
  176. """
  177. This is the function that gets called when all of the needed objects
  178. are in (i.e. all the askForObject and createObject requests have
  179. been satisfied).
  180. If the other requests timeout, finish will not be called.
  181. """
  182. assert self.notify.debugCall()
  183. self.delete()
  184. def _doCreateObject(self, name, className, values, doId):
  185. isInDoId2do = doId in self.air.doId2do
  186. distObj = self.air.generateGlobalObject(doId, className, values)
  187. if not isInDoId2do and game.name == 'uberDog':
  188. # only remove doId if this is the uberdog?, in pirates this was
  189. # causing traded inventory objects to be generated twice, once
  190. # here and again later when it was noticed the doId was not in
  191. # the doId2do list yet.
  192. self.air.doId2do.pop(doId, None)
  193. self._checkCompletion(name, None, distObj)
  194. def _checkCompletion(self, name, context, distObj):
  195. """
  196. This checks whether we have all the needed objects and calls
  197. finish() if we do.
  198. """
  199. if name is not None:
  200. self.neededObjects[name] = distObj
  201. else:
  202. self.neededObjects[distObj.doId] = distObj
  203. for i in self.neededObjects.values():
  204. if i is None:
  205. return
  206. self.finish()
  207. def _resetTimeoutTask(self, createAnew = True):
  208. if self.timeoutTask:
  209. taskMgr.remove(self.timeoutTask)
  210. self.timeoutTask = None
  211. if createAnew:
  212. self.numRetries = self._initialNumRetries
  213. self.timeoutTask = taskMgr.doMethodLater(
  214. self._timeoutTime, self.timeout,
  215. "AsyncRequestTimer-%s"%(id(self,)))
  216. def timeout(self, task):
  217. assert AsyncRequest.notify.debugCall(
  218. "neededObjects: %s"%(self.neededObjects,))
  219. if self.numRetries > 0:
  220. assert AsyncRequest.notify.debug(
  221. 'Timed out. Trying %d more time(s) : %s' %
  222. (self.numRetries + 1, repr(self.neededObjects)))
  223. self.numRetries -= 1
  224. return Task.again
  225. else:
  226. if __debug__:
  227. if _breakOnTimeout:
  228. if hasattr(self, "avatarId"):
  229. print("\n\nself.avatarId =", self.avatarId)
  230. print("\nself.neededObjects =", self.neededObjects)
  231. print("\ntimed out after %s seconds.\n\n"%(task.delayTime,))
  232. import pdb; pdb.set_trace()
  233. self.delete()
  234. return Task.done
  235. def cleanupAsyncRequests():
  236. """
  237. Only call this when the application is shuting down.
  238. """
  239. for asyncRequest in AsyncRequest._asyncRequests:
  240. asyncRequest.delete()
  241. assert AsyncRequest._asyncRequests == {}