AsyncRequest.py 11 KB

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