Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

flavors.py 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. # -*- test-case-name: twisted.spread.test.test_pb -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. This module represents flavors of remotely accessible objects.
  6. Currently this is only objects accessible through Perspective Broker, but will
  7. hopefully encompass all forms of remote access which can emulate subsets of PB
  8. (such as XMLRPC or SOAP).
  9. Future Plans: Optimization. Exploitation of new-style object model.
  10. Optimizations to this module should not affect external-use semantics at all,
  11. but may have a small impact on users who subclass and override methods.
  12. @author: Glyph Lefkowitz
  13. """
  14. # NOTE: this module should NOT import pb; it is supposed to be a module which
  15. # abstractly defines remotely accessible types. Many of these types expect to
  16. # be serialized by Jelly, but they ought to be accessible through other
  17. # mechanisms (like XMLRPC)
  18. import sys
  19. from zope.interface import Interface, implementer
  20. from twisted.python import log, reflect
  21. from twisted.python.compat import cmp, comparable
  22. from .jelly import (
  23. Jellyable,
  24. Unjellyable,
  25. _createBlank,
  26. getInstanceState,
  27. setInstanceState,
  28. setUnjellyableFactoryForClass,
  29. setUnjellyableForClass,
  30. setUnjellyableForClassTree,
  31. unjellyableRegistry,
  32. )
  33. # compatibility
  34. setCopierForClass = setUnjellyableForClass
  35. setCopierForClassTree = setUnjellyableForClassTree
  36. setFactoryForClass = setUnjellyableFactoryForClass
  37. copyTags = unjellyableRegistry
  38. copy_atom = b"copy"
  39. cache_atom = b"cache"
  40. cached_atom = b"cached"
  41. remote_atom = b"remote"
  42. class NoSuchMethod(AttributeError):
  43. """Raised if there is no such remote method"""
  44. class IPBRoot(Interface):
  45. """Factory for root Referenceable objects for PB servers."""
  46. def rootObject(broker):
  47. """Return root Referenceable for broker."""
  48. class Serializable(Jellyable):
  49. """An object that can be passed remotely.
  50. I am a style of object which can be serialized by Perspective
  51. Broker. Objects which wish to be referenceable or copied remotely
  52. have to subclass Serializable. However, clients of Perspective
  53. Broker will probably not want to directly subclass Serializable; the
  54. Flavors of transferable objects are listed below.
  55. What it means to be \"Serializable\" is that an object can be
  56. passed to or returned from a remote method. Certain basic types
  57. (dictionaries, lists, tuples, numbers, strings) are serializable by
  58. default; however, classes need to choose a specific serialization
  59. style: L{Referenceable}, L{Viewable}, L{Copyable} or L{Cacheable}.
  60. You may also pass C{[lists, dictionaries, tuples]} of L{Serializable}
  61. instances to or return them from remote methods, as many levels deep
  62. as you like.
  63. """
  64. def processUniqueID(self):
  65. """Return an ID which uniquely represents this object for this process.
  66. By default, this uses the 'id' builtin, but can be overridden to
  67. indicate that two values are identity-equivalent (such as proxies
  68. for the same object).
  69. """
  70. return id(self)
  71. class Referenceable(Serializable):
  72. perspective = None
  73. """I am an object sent remotely as a direct reference.
  74. When one of my subclasses is sent as an argument to or returned
  75. from a remote method call, I will be serialized by default as a
  76. direct reference.
  77. This means that the peer will be able to call methods on me;
  78. a method call xxx() from my peer will be resolved to methods
  79. of the name remote_xxx.
  80. """
  81. def remoteMessageReceived(self, broker, message, args, kw):
  82. """A remote message has been received. Dispatch it appropriately.
  83. The default implementation is to dispatch to a method called
  84. 'remote_messagename' and call it with the same arguments.
  85. """
  86. args = broker.unserialize(args)
  87. kw = broker.unserialize(kw)
  88. # Need this to interoperate with Python 2 clients
  89. # which may try to send use keywords where keys are of type
  90. # bytes.
  91. if [key for key in kw.keys() if isinstance(key, bytes)]:
  92. kw = {k.decode("utf8"): v for k, v in kw.items()}
  93. if not isinstance(message, str):
  94. message = message.decode("utf8")
  95. method = getattr(self, "remote_%s" % message, None)
  96. if method is None:
  97. raise NoSuchMethod(f"No such method: remote_{message}")
  98. try:
  99. state = method(*args, **kw)
  100. except TypeError:
  101. log.msg(f"{method} didn't accept {args} and {kw}")
  102. raise
  103. return broker.serialize(state, self.perspective)
  104. def jellyFor(self, jellier):
  105. """(internal)
  106. Return a tuple which will be used as the s-expression to
  107. serialize this to a peer.
  108. """
  109. return [b"remote", jellier.invoker.registerReference(self)]
  110. @implementer(IPBRoot)
  111. class Root(Referenceable):
  112. """I provide a root object to L{pb.Broker}s for a L{pb.PBClientFactory} or
  113. L{pb.PBServerFactory}.
  114. When a factory produces a L{pb.Broker}, it supplies that
  115. L{pb.Broker} with an object named \"root\". That object is obtained
  116. by calling my rootObject method.
  117. """
  118. def rootObject(self, broker):
  119. """A factory is requesting to publish me as a root object.
  120. When a factory is sending me as the root object, this
  121. method will be invoked to allow per-broker versions of an
  122. object. By default I return myself.
  123. """
  124. return self
  125. class ViewPoint(Referenceable):
  126. """
  127. I act as an indirect reference to an object accessed through a
  128. L{pb.IPerspective}.
  129. Simply put, I combine an object with a perspective so that when a
  130. peer calls methods on the object I refer to, the method will be
  131. invoked with that perspective as a first argument, so that it can
  132. know who is calling it.
  133. While L{Viewable} objects will be converted to ViewPoints by default
  134. when they are returned from or sent as arguments to a remote
  135. method, any object may be manually proxied as well. (XXX: Now that
  136. this class is no longer named C{Proxy}, this is the only occurrence
  137. of the term 'proxied' in this docstring, and may be unclear.)
  138. This can be useful when dealing with L{pb.IPerspective}s, L{Copyable}s,
  139. and L{Cacheable}s. It is legal to implement a method as such on
  140. a perspective::
  141. | def perspective_getViewPointForOther(self, name):
  142. | defr = self.service.getPerspectiveRequest(name)
  143. | defr.addCallbacks(lambda x, self=self: ViewPoint(self, x), log.msg)
  144. | return defr
  145. This will allow you to have references to Perspective objects in two
  146. different ways. One is through the initial 'attach' call -- each
  147. peer will have a L{pb.RemoteReference} to their perspective directly. The
  148. other is through this method; each peer can get a L{pb.RemoteReference} to
  149. all other perspectives in the service; but that L{pb.RemoteReference} will
  150. be to a L{ViewPoint}, not directly to the object.
  151. The practical offshoot of this is that you can implement 2 varieties
  152. of remotely callable methods on this Perspective; view_xxx and
  153. C{perspective_xxx}. C{view_xxx} methods will follow the rules for
  154. ViewPoint methods (see ViewPoint.L{remoteMessageReceived}), and
  155. C{perspective_xxx} methods will follow the rules for Perspective
  156. methods.
  157. """
  158. def __init__(self, perspective, object):
  159. """Initialize me with a Perspective and an Object."""
  160. self.perspective = perspective
  161. self.object = object
  162. def processUniqueID(self):
  163. """Return an ID unique to a proxy for this perspective+object combination."""
  164. return (id(self.perspective), id(self.object))
  165. def remoteMessageReceived(self, broker, message, args, kw):
  166. """A remote message has been received. Dispatch it appropriately.
  167. The default implementation is to dispatch to a method called
  168. 'C{view_messagename}' to my Object and call it on my object with
  169. the same arguments, modified by inserting my Perspective as
  170. the first argument.
  171. """
  172. args = broker.unserialize(args, self.perspective)
  173. kw = broker.unserialize(kw, self.perspective)
  174. if not isinstance(message, str):
  175. message = message.decode("utf8")
  176. method = getattr(self.object, "view_%s" % message)
  177. try:
  178. state = method(*(self.perspective,) + args, **kw)
  179. except TypeError:
  180. log.msg(f"{method} didn't accept {args} and {kw}")
  181. raise
  182. rv = broker.serialize(state, self.perspective, method, args, kw)
  183. return rv
  184. class Viewable(Serializable):
  185. """I will be converted to a L{ViewPoint} when passed to or returned from a remote method.
  186. The beginning of a peer's interaction with a PB Service is always
  187. through a perspective. However, if a C{perspective_xxx} method returns
  188. a Viewable, it will be serialized to the peer as a response to that
  189. method.
  190. """
  191. def jellyFor(self, jellier):
  192. """Serialize a L{ViewPoint} for me and the perspective of the given broker."""
  193. return ViewPoint(jellier.invoker.serializingPerspective, self).jellyFor(jellier)
  194. class Copyable(Serializable):
  195. """Subclass me to get copied each time you are returned from or passed to a remote method.
  196. When I am returned from or passed to a remote method call, I will be
  197. converted into data via a set of callbacks (see my methods for more
  198. info). That data will then be serialized using Jelly, and sent to
  199. the peer.
  200. The peer will then look up the type to represent this with; see
  201. L{RemoteCopy} for details.
  202. """
  203. def getStateToCopy(self):
  204. """Gather state to send when I am serialized for a peer.
  205. I will default to returning self.__dict__. Override this to
  206. customize this behavior.
  207. """
  208. return self.__dict__
  209. def getStateToCopyFor(self, perspective):
  210. """
  211. Gather state to send when I am serialized for a particular
  212. perspective.
  213. I will default to calling L{getStateToCopy}. Override this to
  214. customize this behavior.
  215. """
  216. return self.getStateToCopy()
  217. def getTypeToCopy(self):
  218. """Determine what type tag to send for me.
  219. By default, send the string representation of my class
  220. (package.module.Class); normally this is adequate, but
  221. you may override this to change it.
  222. """
  223. return reflect.qual(self.__class__).encode("utf-8")
  224. def getTypeToCopyFor(self, perspective):
  225. """Determine what type tag to send for me.
  226. By default, defer to self.L{getTypeToCopy}() normally this is
  227. adequate, but you may override this to change it.
  228. """
  229. return self.getTypeToCopy()
  230. def jellyFor(self, jellier):
  231. """Assemble type tag and state to copy for this broker.
  232. This will call L{getTypeToCopyFor} and L{getStateToCopy}, and
  233. return an appropriate s-expression to represent me.
  234. """
  235. if jellier.invoker is None:
  236. return getInstanceState(self, jellier)
  237. p = jellier.invoker.serializingPerspective
  238. t = self.getTypeToCopyFor(p)
  239. state = self.getStateToCopyFor(p)
  240. sxp = jellier.prepare(self)
  241. sxp.extend([t, jellier.jelly(state)])
  242. return jellier.preserve(self, sxp)
  243. class Cacheable(Copyable):
  244. """A cached instance.
  245. This means that it's copied; but there is some logic to make sure
  246. that it's only copied once. Additionally, when state is retrieved,
  247. it is passed a "proto-reference" to the state as it will exist on
  248. the client.
  249. XXX: The documentation for this class needs work, but it's the most
  250. complex part of PB and it is inherently difficult to explain.
  251. """
  252. def getStateToCacheAndObserveFor(self, perspective, observer):
  253. """
  254. Get state to cache on the client and client-cache reference
  255. to observe locally.
  256. This is similar to getStateToCopyFor, but it additionally
  257. passes in a reference to the client-side RemoteCache instance
  258. that will be created when it is unserialized. This allows
  259. Cacheable instances to keep their RemoteCaches up to date when
  260. they change, such that no changes can occur between the point
  261. at which the state is initially copied and the client receives
  262. it that are not propagated.
  263. """
  264. return self.getStateToCopyFor(perspective)
  265. def jellyFor(self, jellier):
  266. """Return an appropriate tuple to serialize me.
  267. Depending on whether this broker has cached me or not, this may
  268. return either a full state or a reference to an existing cache.
  269. """
  270. if jellier.invoker is None:
  271. return getInstanceState(self, jellier)
  272. luid = jellier.invoker.cachedRemotelyAs(self, 1)
  273. if luid is None:
  274. luid = jellier.invoker.cacheRemotely(self)
  275. p = jellier.invoker.serializingPerspective
  276. type_ = self.getTypeToCopyFor(p)
  277. observer = RemoteCacheObserver(jellier.invoker, self, p)
  278. state = self.getStateToCacheAndObserveFor(p, observer)
  279. l = jellier.prepare(self)
  280. jstate = jellier.jelly(state)
  281. l.extend([type_, luid, jstate])
  282. return jellier.preserve(self, l)
  283. else:
  284. return cached_atom, luid
  285. def stoppedObserving(self, perspective, observer):
  286. """This method is called when a client has stopped observing me.
  287. The 'observer' argument is the same as that passed in to
  288. getStateToCacheAndObserveFor.
  289. """
  290. class RemoteCopy(Unjellyable):
  291. """I am a remote copy of a Copyable object.
  292. When the state from a L{Copyable} object is received, an instance will
  293. be created based on the copy tags table (see setUnjellyableForClass) and
  294. sent the L{setCopyableState} message. I provide a reasonable default
  295. implementation of that message; subclass me if you wish to serve as
  296. a copier for remote data.
  297. NOTE: copiers are invoked with no arguments. Do not implement a
  298. constructor which requires args in a subclass of L{RemoteCopy}!
  299. """
  300. def setCopyableState(self, state):
  301. """I will be invoked with the state to copy locally.
  302. 'state' is the data returned from the remote object's
  303. 'getStateToCopyFor' method, which will often be the remote
  304. object's dictionary (or a filtered approximation of it depending
  305. on my peer's perspective).
  306. """
  307. state = {
  308. x.decode("utf8") if isinstance(x, bytes) else x: y for x, y in state.items()
  309. }
  310. self.__dict__ = state
  311. def unjellyFor(self, unjellier, jellyList):
  312. if unjellier.invoker is None:
  313. return setInstanceState(self, unjellier, jellyList)
  314. self.setCopyableState(unjellier.unjelly(jellyList[1]))
  315. return self
  316. class RemoteCache(RemoteCopy, Serializable):
  317. """A cache is a local representation of a remote L{Cacheable} object.
  318. This represents the last known state of this object. It may
  319. also have methods invoked on it -- in order to update caches,
  320. the cached class generates a L{pb.RemoteReference} to this object as
  321. it is originally sent.
  322. Much like copy, I will be invoked with no arguments. Do not
  323. implement a constructor that requires arguments in one of my
  324. subclasses.
  325. """
  326. def remoteMessageReceived(self, broker, message, args, kw):
  327. """A remote message has been received. Dispatch it appropriately.
  328. The default implementation is to dispatch to a method called
  329. 'C{observe_messagename}' and call it on my with the same arguments.
  330. """
  331. if not isinstance(message, str):
  332. message = message.decode("utf8")
  333. args = broker.unserialize(args)
  334. kw = broker.unserialize(kw)
  335. method = getattr(self, "observe_%s" % message)
  336. try:
  337. state = method(*args, **kw)
  338. except TypeError:
  339. log.msg(f"{method} didn't accept {args} and {kw}")
  340. raise
  341. return broker.serialize(state, None, method, args, kw)
  342. def jellyFor(self, jellier):
  343. """serialize me (only for the broker I'm for) as the original cached reference"""
  344. if jellier.invoker is None:
  345. return getInstanceState(self, jellier)
  346. assert (
  347. jellier.invoker is self.broker
  348. ), "You cannot exchange cached proxies between brokers."
  349. return b"lcache", self.luid
  350. def unjellyFor(self, unjellier, jellyList):
  351. if unjellier.invoker is None:
  352. return setInstanceState(self, unjellier, jellyList)
  353. self.broker = unjellier.invoker
  354. self.luid = jellyList[1]
  355. borgCopy = self._borgify()
  356. # XXX questionable whether this was a good design idea...
  357. init = getattr(borgCopy, "__init__", None)
  358. if init:
  359. init()
  360. unjellier.invoker.cacheLocally(jellyList[1], self)
  361. borgCopy.setCopyableState(unjellier.unjelly(jellyList[2]))
  362. # Might have changed due to setCopyableState method; we'll assume that
  363. # it's bad form to do so afterwards.
  364. self.__dict__ = borgCopy.__dict__
  365. # chomp, chomp -- some existing code uses "self.__dict__ =", some uses
  366. # "__dict__.update". This is here in order to handle both cases.
  367. self.broker = unjellier.invoker
  368. self.luid = jellyList[1]
  369. return borgCopy
  370. ## def __really_del__(self):
  371. ## """Final finalization call, made after all remote references have been lost.
  372. ## """
  373. def __cmp__(self, other):
  374. """Compare me [to another RemoteCache."""
  375. if isinstance(other, self.__class__):
  376. return cmp(id(self.__dict__), id(other.__dict__))
  377. else:
  378. return cmp(id(self.__dict__), other)
  379. def __hash__(self):
  380. """Hash me."""
  381. return int(id(self.__dict__) % sys.maxsize)
  382. broker = None
  383. luid = None
  384. def __del__(self):
  385. """Do distributed reference counting on finalize."""
  386. try:
  387. # log.msg( ' --- decache: %s %s' % (self, self.luid) )
  388. if self.broker:
  389. self.broker.decCacheRef(self.luid)
  390. except BaseException:
  391. log.deferr()
  392. def _borgify(self):
  393. """
  394. Create a new object that shares its state (i.e. its C{__dict__}) and
  395. type with this object, but does not share its identity.
  396. This is an instance of U{the Borg design pattern
  397. <https://code.activestate.com/recipes/66531/>} originally described by
  398. Alex Martelli, but unlike the example given there, this is not a
  399. replacement for a Singleton. Instead, it is for lifecycle tracking
  400. (and distributed garbage collection). The purpose of these separate
  401. objects is to have a separate object tracking each application-level
  402. reference to the root L{RemoteCache} object being tracked by the
  403. broker, and to have their C{__del__} methods be invoked.
  404. This may be achievable via a weak value dictionary to track the root
  405. L{RemoteCache} instances instead, but this implementation strategy
  406. predates the availability of weak references in Python.
  407. @return: The new instance.
  408. @rtype: C{self.__class__}
  409. """
  410. blank = _createBlank(self.__class__)
  411. blank.__dict__ = self.__dict__
  412. return blank
  413. def unjellyCached(unjellier, unjellyList):
  414. luid = unjellyList[1]
  415. return unjellier.invoker.cachedLocallyAs(luid)._borgify()
  416. setUnjellyableForClass("cached", unjellyCached)
  417. def unjellyLCache(unjellier, unjellyList):
  418. luid = unjellyList[1]
  419. obj = unjellier.invoker.remotelyCachedForLUID(luid)
  420. return obj
  421. setUnjellyableForClass("lcache", unjellyLCache)
  422. def unjellyLocal(unjellier, unjellyList):
  423. obj = unjellier.invoker.localObjectForID(unjellyList[1])
  424. return obj
  425. setUnjellyableForClass("local", unjellyLocal)
  426. @comparable
  427. class RemoteCacheMethod:
  428. """A method on a reference to a L{RemoteCache}."""
  429. def __init__(self, name, broker, cached, perspective):
  430. """(internal) initialize."""
  431. self.name = name
  432. self.broker = broker
  433. self.perspective = perspective
  434. self.cached = cached
  435. def __cmp__(self, other):
  436. return cmp((self.name, self.broker, self.perspective, self.cached), other)
  437. def __hash__(self):
  438. return hash((self.name, self.broker, self.perspective, self.cached))
  439. def __call__(self, *args, **kw):
  440. """(internal) action method."""
  441. cacheID = self.broker.cachedRemotelyAs(self.cached)
  442. if cacheID is None:
  443. from pb import ProtocolError # type: ignore[import]
  444. raise ProtocolError(
  445. "You can't call a cached method when the object hasn't been given to the peer yet."
  446. )
  447. return self.broker._sendMessage(
  448. b"cache", self.perspective, cacheID, self.name, args, kw
  449. )
  450. @comparable
  451. class RemoteCacheObserver:
  452. """I am a reverse-reference to the peer's L{RemoteCache}.
  453. I am generated automatically when a cache is serialized. I
  454. represent a reference to the client's L{RemoteCache} object that
  455. will represent a particular L{Cacheable}; I am the additional
  456. object passed to getStateToCacheAndObserveFor.
  457. """
  458. def __init__(self, broker, cached, perspective):
  459. """(internal) Initialize me.
  460. @param broker: a L{pb.Broker} instance.
  461. @param cached: a L{Cacheable} instance that this L{RemoteCacheObserver}
  462. corresponds to.
  463. @param perspective: a reference to the perspective who is observing this.
  464. """
  465. self.broker = broker
  466. self.cached = cached
  467. self.perspective = perspective
  468. def __repr__(self) -> str:
  469. return "<RemoteCacheObserver({}, {}, {}) at {}>".format(
  470. self.broker,
  471. self.cached,
  472. self.perspective,
  473. id(self),
  474. )
  475. def __hash__(self):
  476. """Generate a hash unique to all L{RemoteCacheObserver}s for this broker/perspective/cached triplet"""
  477. return (
  478. (hash(self.broker) % 2 ** 10)
  479. + (hash(self.perspective) % 2 ** 10)
  480. + (hash(self.cached) % 2 ** 10)
  481. )
  482. def __cmp__(self, other):
  483. """Compare me to another L{RemoteCacheObserver}."""
  484. return cmp((self.broker, self.perspective, self.cached), other)
  485. def callRemote(self, _name, *args, **kw):
  486. """(internal) action method."""
  487. cacheID = self.broker.cachedRemotelyAs(self.cached)
  488. if isinstance(_name, str):
  489. _name = _name.encode("utf-8")
  490. if cacheID is None:
  491. from pb import ProtocolError
  492. raise ProtocolError(
  493. "You can't call a cached method when the "
  494. "object hasn't been given to the peer yet."
  495. )
  496. return self.broker._sendMessage(
  497. b"cache", self.perspective, cacheID, _name, args, kw
  498. )
  499. def remoteMethod(self, key):
  500. """Get a L{pb.RemoteMethod} for this key."""
  501. return RemoteCacheMethod(key, self.broker, self.cached, self.perspective)