AsyncRequest.py 11 KB

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