o bf[@sdZddlZddlmZmZddlmZmZddlm Z m Z ddl m Z m Z mZmZmZmZmZmZmZeZeZeZeZdZd Zd Zd ZGd d d eZGdddeZGddde Z Gddde Z!eeGddde!Z"Gddde!Z#Gddde Z$Gddde Z%Gddde%Z&Gddde Z'Gd d!d!e'e Z(d"d#Z)ed$e)d%d&Z*ed'e*d(d)Z+ed*e+e Gd+d,d,Z,e Gd-d.d.Z-dS)/a This module represents flavors of remotely accessible objects. Currently this is only objects accessible through Perspective Broker, but will hopefully encompass all forms of remote access which can emulate subsets of PB (such as XMLRPC or SOAP). Future Plans: Optimization. Exploitation of new-style object model. Optimizations to this module should not affect external-use semantics at all, but may have a small impact on users who subclass and override methods. @author: Glyph Lefkowitz N) Interface implementer)logreflect)cmp comparable) Jellyable Unjellyable _createBlankgetInstanceStatesetInstanceStatesetUnjellyableFactoryForClasssetUnjellyableForClasssetUnjellyableForClassTreeunjellyableRegistryscopycachescachedremotec@seZdZdZdS) NoSuchMethodz(Raised if there is no such remote methodN)__name__ __module__ __qualname____doc__rr8/usr/lib/python3/dist-packages/twisted/spread/flavors.pyr7src@eZdZdZddZdS)IPBRootz6Factory for root Referenceable objects for PB servers.cCdS)z%Return root Referenceable for broker.Nr)brokerrrr rootObject>zIPBRoot.rootObjectNrrrrrrrrrr;s rc@r) SerializableaxAn object that can be passed remotely. I am a style of object which can be serialized by Perspective Broker. Objects which wish to be referenceable or copied remotely have to subclass Serializable. However, clients of Perspective Broker will probably not want to directly subclass Serializable; the Flavors of transferable objects are listed below. What it means to be "Serializable" is that an object can be passed to or returned from a remote method. Certain basic types (dictionaries, lists, tuples, numbers, strings) are serializable by default; however, classes need to choose a specific serialization style: L{Referenceable}, L{Viewable}, L{Copyable} or L{Cacheable}. You may also pass C{[lists, dictionaries, tuples]} of L{Serializable} instances to or return them from remote methods, as many levels deep as you like. cCst|S)zReturn an ID which uniquely represents this object for this process. By default, this uses the 'id' builtin, but can be overridden to indicate that two values are identity-equivalent (such as proxies for the same object). )idselfrrrprocessUniqueIDVszSerializable.processUniqueIDN)rrrrr&rrrrr"Bs r"c@s"eZdZdZ ddZddZdS) ReferenceableNc Cs||}||}dd|Drdd|D}t|ts&|d}t|d|d}|dur9td|z ||i|}WntyWt |d |d |w| ||j S) zA remote message has been received. Dispatch it appropriately. The default implementation is to dispatch to a method called 'remote_messagename' and call it with the same arguments. cSsg|] }t|tr|qSr) isinstancebytes).0keyrrr ysz7Referenceable.remoteMessageReceived..cSsi|] \}}|d|qSutf8)decode)r*kvrrr zsz7Referenceable.remoteMessageReceived..r.z remote_%sNzNo such method: remote_ didn't accept  and ) unserializekeysitemsr(strr/getattrr TypeErrorrmsg serialize perspectiver%rmessageargskwmethodstaterrrremoteMessageReceivedns     z#Referenceable.remoteMessageReceivedcCsd|j|gS)zw(internal) Return a tuple which will be used as the s-expression to serialize this to a peer. r)invokerregisterReferencer%jellierrrrjellyForszReferenceable.jellyFor)rrrr=rDrIrrrrr'as  r'c@r)RootaI provide a root object to L{pb.Broker}s for a L{pb.PBClientFactory} or L{pb.PBServerFactory}. When a factory produces a L{pb.Broker}, it supplies that L{pb.Broker} with an object named "root". That object is obtained by calling my rootObject method. cCs|S)zA factory is requesting to publish me as a root object. When a factory is sending me as the root object, this method will be invoked to allow per-broker versions of an object. By default I return myself. r)r%rrrrrszRoot.rootObjectNr!rrrrrJs rJc@(eZdZdZddZddZddZdS) ViewPointaF I act as an indirect reference to an object accessed through a L{pb.IPerspective}. Simply put, I combine an object with a perspective so that when a peer calls methods on the object I refer to, the method will be invoked with that perspective as a first argument, so that it can know who is calling it. While L{Viewable} objects will be converted to ViewPoints by default when they are returned from or sent as arguments to a remote method, any object may be manually proxied as well. (XXX: Now that this class is no longer named C{Proxy}, this is the only occurrence of the term 'proxied' in this docstring, and may be unclear.) This can be useful when dealing with L{pb.IPerspective}s, L{Copyable}s, and L{Cacheable}s. It is legal to implement a method as such on a perspective:: | def perspective_getViewPointForOther(self, name): | defr = self.service.getPerspectiveRequest(name) | defr.addCallbacks(lambda x, self=self: ViewPoint(self, x), log.msg) | return defr This will allow you to have references to Perspective objects in two different ways. One is through the initial 'attach' call -- each peer will have a L{pb.RemoteReference} to their perspective directly. The other is through this method; each peer can get a L{pb.RemoteReference} to all other perspectives in the service; but that L{pb.RemoteReference} will be to a L{ViewPoint}, not directly to the object. The practical offshoot of this is that you can implement 2 varieties of remotely callable methods on this Perspective; view_xxx and C{perspective_xxx}. C{view_xxx} methods will follow the rules for ViewPoint methods (see ViewPoint.L{remoteMessageReceived}), and C{perspective_xxx} methods will follow the rules for Perspective methods. cCs||_||_dS)z/Initialize me with a Perspective and an Object.N)r=object)r%r=rMrrr__init__s zViewPoint.__init__cCst|jt|jfS)zGReturn an ID unique to a proxy for this perspective+object combination.)r#r=rMr$rrrr&zViewPoint.processUniqueIDc Cs|||j}|||j}t|ts|d}t|jd|}z ||jf|i|}WntyBt |d|d|w| ||j|||}|S)a7A remote message has been received. Dispatch it appropriately. The default implementation is to dispatch to a method called 'C{view_messagename}' to my Object and call it on my object with the same arguments, modified by inserting my Perspective as the first argument. r.zview_%sr3r4) r5r=r(r8r/r9rMr:rr;r<)r%rr?r@rArBrCrvrrrrDs   zViewPoint.remoteMessageReceivedN)rrrrrNr&rDrrrrrLs ' rLc@r)ViewableaBI will be converted to a L{ViewPoint} when passed to or returned from a remote method. The beginning of a peer's interaction with a PB Service is always through a perspective. However, if a C{perspective_xxx} method returns a Viewable, it will be serialized to the peer as a response to that method. cCst|jj||S)zHSerialize a L{ViewPoint} for me and the perspective of the given broker.)rLrEserializingPerspectiverIrGrrrrIrOzViewable.jellyForN)rrrrrIrrrrrQs rQc@s8eZdZdZddZddZddZdd Zd d Zd S) CopyableaSubclass me to get copied each time you are returned from or passed to a remote method. When I am returned from or passed to a remote method call, I will be converted into data via a set of callbacks (see my methods for more info). That data will then be serialized using Jelly, and sent to the peer. The peer will then look up the type to represent this with; see L{RemoteCopy} for details. cCs|jS)zGather state to send when I am serialized for a peer. I will default to returning self.__dict__. Override this to customize this behavior. )__dict__r$rrrgetStateToCopy szCopyable.getStateToCopycC|S)z Gather state to send when I am serialized for a particular perspective. I will default to calling L{getStateToCopy}. Override this to customize this behavior. )rUr%r=rrrgetStateToCopyFors zCopyable.getStateToCopyForcCst|jdS)zDetermine what type tag to send for me. By default, send the string representation of my class (package.module.Class); normally this is adequate, but you may override this to change it. utf-8)rqual __class__encoder$rrr getTypeToCopyszCopyable.getTypeToCopycCrV)zDetermine what type tag to send for me. By default, defer to self.L{getTypeToCopy}() normally this is adequate, but you may override this to change it. )r]rWrrrgetTypeToCopyFor(szCopyable.getTypeToCopyForcCsZ|jdur t||S|jj}||}||}||}||||g|||S)zAssemble type tag and state to copy for this broker. This will call L{getTypeToCopyFor} and L{getStateToCopy}, and return an appropriate s-expression to represent me. N) rEr rRr^rXprepareextendjellypreserve)r%rHptrCsxprrrrI1s      zCopyable.jellyForN) rrrrrUrXr]r^rIrrrrrSs    rSc@rK) CacheableaA cached instance. This means that it's copied; but there is some logic to make sure that it's only copied once. Additionally, when state is retrieved, it is passed a "proto-reference" to the state as it will exist on the client. XXX: The documentation for this class needs work, but it's the most complex part of PB and it is inherently difficult to explain. cCs ||S)a- Get state to cache on the client and client-cache reference to observe locally. This is similar to getStateToCopyFor, but it additionally passes in a reference to the client-side RemoteCache instance that will be created when it is unserialized. This allows Cacheable instances to keep their RemoteCaches up to date when they change, such that no changes can occur between the point at which the state is initially copied and the client receives it that are not propagated. )rXr%r=observerrrrgetStateToCacheAndObserveForNs z&Cacheable.getStateToCacheAndObserveForc Cs|jdur t||S|j|d}|durI|j|}|jj}||}t|j||}|||}||}| |}| |||g| ||St |fS)zReturn an appropriate tuple to serialize me. Depending on whether this broker has cached me or not, this may return either a full state or a reference to an existing cache. Nr) rEr cachedRemotelyAs cacheRemotelyrRr^RemoteCacheObserverrir_rar`rb cached_atom) r%rHluidrctype_rhrCljstaterrrrI^s        zCacheable.jellyForcCr)zThis method is called when a client has stopped observing me. The 'observer' argument is the same as that passed in to getStateToCacheAndObserveFor. NrrgrrrstoppedObservingtr zCacheable.stoppedObservingN)rrrrrirIrrrrrrrfBs   rfc@s eZdZdZddZddZdS) RemoteCopyaI am a remote copy of a Copyable object. When the state from a L{Copyable} object is received, an instance will be created based on the copy tags table (see setUnjellyableForClass) and sent the L{setCopyableState} message. I provide a reasonable default implementation of that message; subclass me if you wish to serve as a copier for remote data. NOTE: copiers are invoked with no arguments. Do not implement a constructor which requires args in a subclass of L{RemoteCopy}! cCsdd|D}||_dS)a(I will be invoked with the state to copy locally. 'state' is the data returned from the remote object's 'getStateToCopyFor' method, which will often be the remote object's dictionary (or a filtered approximation of it depending on my peer's perspective). cSs*i|]\}}t|tr|dn||qSr-)r(r)r/)r*xyrrrr2sz/RemoteCopy.setCopyableState..N)r7rT)r%rCrrrsetCopyableStates zRemoteCopy.setCopyableStatecCs.|jdur t|||S|||d|SNr)rEr rvunjelly)r% unjellier jellyListrrr unjellyFors  zRemoteCopy.unjellyForN)rrrrrvr{rrrrrs|s rsc@sPeZdZdZddZddZddZdd Zd d Zd Z d Z d dZ ddZ d S) RemoteCacheaA cache is a local representation of a remote L{Cacheable} object. This represents the last known state of this object. It may also have methods invoked on it -- in order to update caches, the cached class generates a L{pb.RemoteReference} to this object as it is originally sent. Much like copy, I will be invoked with no arguments. Do not implement a constructor that requires arguments in one of my subclasses. c Cst|ts |d}||}||}t|d|}z ||i|}Wnty9t|d|d|w||d|||S)zA remote message has been received. Dispatch it appropriately. The default implementation is to dispatch to a method called 'C{observe_messagename}' and call it on my with the same arguments. r.z observe_%sr3r4N) r(r8r/r5r9r:rr;r<r>rrrrDs     z!RemoteCache.remoteMessageReceivedcCs2|jdur t||S|j|jusJdd|jfS)zKserialize me (only for the broker I'm for) as the original cached referenceNz3You cannot exchange cached proxies between brokers.slcache)rEr rrnrGrrrrIs   zRemoteCache.jellyForcCs|jdur t|||S|j|_|d|_|}t|dd}|r#||j|d||||d|j |_ |j|_|d|_|S)NrrN) rEr rrn_borgifyr9 cacheLocallyrvrxrT)r%ryrzborgCopyinitrrrr{s     zRemoteCache.unjellyForcCs2t||jrtt|jt|jStt|j|S)z#Compare me [to another RemoteCache.)r(r[rr#rTr%otherrrr__cmp__s zRemoteCache.__cmp__cCstt|jtjS)zHash me.)intr#rTsysmaxsizer$rrr__hash__rOzRemoteCache.__hash__NcCs>z|jr|j|jWdSWdStytYdSw)z.Do distributed reference counting on finalize.N)r decCacheRefrn BaseExceptionrdeferrr$rrr__del__s zRemoteCache.__del__cCst|j}|j|_|S)a Create a new object that shares its state (i.e. its C{__dict__}) and type with this object, but does not share its identity. This is an instance of U{the Borg design pattern } originally described by Alex Martelli, but unlike the example given there, this is not a replacement for a Singleton. Instead, it is for lifecycle tracking (and distributed garbage collection). The purpose of these separate objects is to have a separate object tracking each application-level reference to the root L{RemoteCache} object being tracked by the broker, and to have their C{__del__} methods be invoked. This may be achievable via a weak value dictionary to track the root L{RemoteCache} instances instead, but this implementation strategy predates the availability of weak references in Python. @return: The new instance. @rtype: C{self.__class__} )r r[rT)r%blankrrrr~s zRemoteCache._borgify) rrrrrDrIr{rrrrnrr~rrrrr|s   r|cCs|d}|j|Srw)rEcachedLocallyAsr~)ry unjellyListrnrrr unjellyCachedsrcachedcCs|d}|j|}|Srw)rEremotelyCachedForLUID)ryrrnobjrrr unjellyLCaches rlcachecCs|j|d}|Srw)rElocalObjectForID)ryrrrrr unjellyLocal!srlocalc@s0eZdZdZddZddZddZdd Zd S) RemoteCacheMethodz,A method on a reference to a L{RemoteCache}.cCs||_||_||_||_dS)z(internal) initialize.N)namerr=r)r%rrrr=rrrrN-s zRemoteCacheMethod.__init__cCst|j|j|j|jf|SN)rrrr=rrrrrr4szRemoteCacheMethod.__cmp__cCst|j|j|j|jfSr)hashrrr=rr$rrrr7szRemoteCacheMethod.__hash__cOsD|j|j}|durddlm}|d|jd|j||j||S)(internal) action method.Nr ProtocolErrorQYou can't call a cached method when the object hasn't been given to the peer yet.r)rrjrpbr _sendMessager=r)r%r@rAcacheIDrrrr__call__:s zRemoteCacheMethod.__call__N)rrrrrNrrrrrrrr)s  rc@sFeZdZdZddZdefddZddZd d Zd d Z d dZ dS)rla6I am a reverse-reference to the peer's L{RemoteCache}. I am generated automatically when a cache is serialized. I represent a reference to the client's L{RemoteCache} object that will represent a particular L{Cacheable}; I am the additional object passed to getStateToCacheAndObserveFor. cCs||_||_||_dS)a(internal) Initialize me. @param broker: a L{pb.Broker} instance. @param cached: a L{Cacheable} instance that this L{RemoteCacheObserver} corresponds to. @param perspective: a reference to the perspective who is observing this. N)rrr=)r%rrr=rrrrNRs  zRemoteCacheObserver.__init__returncCsd|j|j|jt|S)Nz')formatrrr=r#r$rrr__repr__as zRemoteCacheObserver.__repr__cCs*t|jdt|jdt|jdS)z`Generate a hash unique to all L{RemoteCacheObserver}s for this broker/perspective/cached tripleti)rrr=rr$rrrris   zRemoteCacheObserver.__hash__cCst|j|j|jf|S)z-Compare me to another L{RemoteCacheObserver}.)rrr=rrrrrrrszRemoteCacheObserver.__cmp__cOsV|j|j}t|tr|d}|durddlm}|d|jd|j ||||S)rrYNrrrr) rrjrr(r8r\rrrr=)r%_namer@rArrrrr callRemotews   zRemoteCacheObserver.callRemotecCst||j|j|jS)z&Get a L{pb.RemoteMethod} for this key.)rrrr=)r%r+rrr remoteMethodrOz RemoteCacheObserver.remoteMethodN) rrrrrNr8rrrrrrrrrrlHs  rl).rrzope.interfacerrtwisted.pythonrrtwisted.python.compatrrrar r r r r rrrrsetCopierForClasssetCopierForClassTreesetFactoryForClasscopyTags copy_atom cache_atomrm remote_atomAttributeErrorrrr"r'rJrLrQrSrfrsr|rrrrrlrrrrsH, 2ID:!s