o
    @Bi`N                    @   s`  d dl mZ d dlZd dlZd dlZd dlmZ d dlmZ d dl	m
Z
mZmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZmZmZmZ d dlmZmZmZ d dlmZmZmZ d dl m!Z! d dl"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. dd Z/G dd deZ0e
G dd de0Z1G dd de1Z2G dd de3Z4dS )    )absolute_importN)reduce)wamp)publicIdGeneratorObservableMixin)uri)message)types)role)	exception)ApplicationErrorProtocolErrorSessionNotReadySerializationError)ISessionIPayloadCodecIAuthenticator)SessionDetailsCloseDetailsEncodedPayload)PayloadExceededError)PublicationSubscriptionHandlerRegistrationEndpointPublishRequestSubscribeRequestUnsubscribeRequestCallRequestInvocationRequestRegisterRequestUnregisterRequestc                 C   s   t | p	t | S N)inspectismethod
isfunction)f r)   V/var/www/html/Trade-python/venv/lib/python3.10/site-packages/autobahn/wamp/protocol.pyis_method_or_function<   s   r+   c                   @   s   e Zd ZdZdZdd Zedd Zedd Zed	d
 Z	edd Z
edd Zedd ZdddZdddZdd ZdS )BaseSessionzi
    WAMP session base class.

    This class implements :class:`autobahn.wamp.interfaces.ISession`.
    Nc                 C   sn   t  | _| jg dd d| _i | _tjttj	t
i| _d| _d| _d| _d| _d| _d| _d| _t | _dS )z


        )joinleavereadyconnect
disconnect)valid_eventsFN)txaiomake_loggerlogset_valid_eventstraceback_app_ecls_to_uri_patr   INVALID_PAYLOADr   PAYLOAD_SIZE_EXCEEDEDr   _uri_to_ecls_realm_session_id_authid	_authrole_authmethod_authprovider_payload_codecr   _request_id_genselfr)   r)   r*   __init__H   s"   
zBaseSession.__init__c                 C      | j S r$   )r<   rD   r)   r)   r*   realmt      zBaseSession.realmc                 C   rG   r$   )r=   rD   r)   r)   r*   
session_idx   rI   zBaseSession.session_idc                 C   rG   r$   )r>   rD   r)   r)   r*   authid|   rI   zBaseSession.authidc                 C   rG   r$   )r?   rD   r)   r)   r*   authrole   rI   zBaseSession.authrolec                 C   rG   r$   )r@   rD   r)   r)   r*   
authmethod   rI   zBaseSession.authmethodc                 C   rG   r$   )rA   rD   r)   r)   r*   authprovider   rI   zBaseSession.authproviderc                 C   sz   |du rt |dsJ |j| j|< || j|jd  < dS t |dr$J tt|tjjg| j|< || jt|< dS )zM
        Implements :func:`autobahn.wamp.interfaces.ISession.define`
        N	_wampurisr   )	hasattrrO   r8   r;   r   PatternsixuURI_TARGET_HANDLER)rE   r   errorr)   r)   r*   define   s   zBaseSession.definec              	   C   s  d}t |drt|j}d}t |dr|j}|r$tjr$dd | D }|r1|r-||d< nd|i}t|tj	rIt
|jtjkrB|jnt|j}n|j| jv rY| j|j d j}nd}d}	| jri| jd	|||}	|	r}tj||||	j|	j|	j|	jd
}
|
S t|||||}
|
S )a  
        Create a WAMP error message from an exception.

        :param request_type: The request type this WAMP error message is for.
        :type request_type: int

        :param request: The request ID this WAMP error message is for.
        :type request: int

        :param exc: The exception.
        :type exc: Instance of :class:`Exception` or subclass thereof.

        :param tb: Optional traceback. If present, it'll be included with the WAMP error message.
        :type tb: list or None
        Nargskwargsc                 S      i | ]
\}}| d |qS utf8decode.0kvr)   r)   r*   
<dictcomp>       
z7BaseSession._message_from_exception.<locals>.<dictcomp>	tracebackr   zwamp.error.runtime_errorFpayloadenc_algoenc_keyenc_serializer)rP   listrW   rX   rR   PY2	iteritems
isinstancer   r   typerU   	text_typerS   	__class__r8   _urirB   encoder	   Errorrf   rg   rh   ri   )rE   request_typerequestexctbrg   rW   rX   rU   encoded_payloadmsgr)   r)   r*   _message_from_exception   sN   




$z#BaseSession._message_from_exceptionc           	   
   C   sr  d}d}|j r{| jsd}| j| ttj||j d}n_zt|j|j |j|j	}| j
d|j|\}|_|_W n& ty] } z| jjd|d ttjd||j d}W Y d}~n"d}~ww |j|kr{| jjd||jd	 ttjd
||j|j d}|r|S |j| jv r| j|j }z'|jr|jr||ji |j}n|di |j}n|jr||j }n| }W n ty   z
| t d W n   Y Y nw |s|jr|jrtj|jg|jR i |j}n!tj|jfi |j}n|jrtj|jg|jR  }nt|j}t|dr|j |_ t|dr|j|_t|dr#|j|_t|dr-|j|_t|dr7|j|_|S )z
        Create a user (or generic) exception from a WAMP error message.

        :param msg: A WAMP error message.
        :type msg: instance of :class:`autobahn.wamp.message.Error`
        N5received encoded payload, but no payload codec activerg   T.failed to decrypt application payload 1: {err}err+failed to decrypt application payload 1: {}zZURI within encrypted payload ('{decrypted_error}') does not match the envelope ('{error}'))decrypted_errorrU   FURI within encrypted payload ('{}') does not match the envelope ('{}')zWhile re-constructing exceptionrg   calleecallee_authidcallee_authroleforward_forr)   )rg   rB   r5   warnr   ENC_NO_PAYLOAD_CODECr   rf   ri   rh   r]   rU   rW   rX   	ExceptionENC_DECRYPT_ERRORformatENC_TRUSTED_URI_MISMATCHr;   onUserErrorr3   create_failurer   rP   r   r   r   r   )	rE   ry   rv   enc_errlog_msgrx   r   eeclsr)   r)   r*   _exception_from_message   s    
	 z#BaseSession._exception_from_messager$   NN)__name__
__module____qualname____doc__r5   rF   propertyrH   rJ   rK   rL   rM   rN   rV   rz   r   r)   r)   r)   r*   r,   @   s&    ,







Ar,   c                   @   sH  e Zd ZdZd7ddZedd Zedd Zed	d
 Zedd Z	e							d8ddZ
edd Zedd Zedd Zedd Zdd Zdd Zedd Zedd Zedd  Zed!d" Zd#d$ Zed%d& Zed9d'd(Zed)d* Zed+d, Zed9d-d.Zd/d0 Zed1d2 Zed:d3d4Zd5d6 ZdS );ApplicationSessionz 
    WAMP endpoint session.
    Nc                 C   s|   t |  |ptjdd| _tj| _d| _d| _	d| _
d| _d| _i | _i | _i | _i | _i | _i | _i | _i | _i | _dS )zF
        Implements :func:`autobahn.wamp.interfaces.ISession`
        realm1rH   NF)r,   rF   r
   ComponentConfigconfigr   DEFAULT_CLIENT_ROLES_session_roles
_transportr=   r<   _goodbye_sent_transport_is_closing_publish_reqs_subscribe_reqs_unsubscribe_reqs
_call_reqs_register_reqs_unregister_reqs_subscriptions_registrations_invocationsrE   r   r)   r)   r*   rF   E  s"   

zApplicationSession.__init__c                 C   s    |du st |tsJ || _dS )zX
        Implements :func:`autobahn.wamp.interfaces.ISession.set_payload_codec`
        N)rm   r   rB   )rE   payload_codecr)   r)   r*   set_payload_codecg  s   
z$ApplicationSession.set_payload_codecc                 C   rG   )zX
        Implements :func:`autobahn.wamp.interfaces.ISession.get_payload_codec`
        )rB   rD   r)   r)   r*   get_payload_codeco  s   z$ApplicationSession.get_payload_codecc                    sL   | _  d |}t|d fdd t| fdd fdd dS )zV
        Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onOpen`
        r0   Nc                         | dS )NzWhile notifying 'connect'_swallow_errorfailrD   r)   r*   <lambda>      z+ApplicationSession.onOpen.<locals>.<lambda>c                    s   t  jS r$   )r3   	as_future	onConnect_rD   r)   r*   r     r   c                    r   )NzWhile calling 'onConnect'r   r   rD   r)   r*   r     r   )r   firer3   add_callbacks)rE   	transportdr)   rD   r*   onOpenv  s   


zApplicationSession.onOpenc                 C   s   |  | jj dS )zP
        Implements :func:`autobahn.wamp.interfaces.ISession.onConnect`
        Nr-   r   rH   rD   r)   r)   r*   r     s   zApplicationSession.onConnectc	                 C   s   |du st |tjksJ |du st |tksJ t |tkr-|D ]}	t |	tjks,J q!|du s:t |tjks:J |du sGt |tjksGJ |du sSt |tksSJ | jrZtd|| _d| _t	j
|| j|||||||d	}
| j|
 dS )zK
        Implements :func:`autobahn.wamp.interfaces.ISession.join`
        Nzalready joinedF)	rH   rolesauthmethodsrK   rL   	authextra	resumableresume_sessionresume_token)rn   rR   ro   rj   dictr=   r   r<   r   r	   Hellor   r   send)rE   rH   r   rK   rL   r   r   r   r   rM   ry   r)   r)   r*   r-     s.   	zApplicationSession.joinc                 C   s   | j r
| j   dS dS )zQ
        Implements :func:`autobahn.wamp.interfaces.ISession.disconnect`
        N)r   closerD   r)   r)   r*   r1     s   zApplicationSession.disconnectc                 C   s
   | j duS )zS
        Implements :func:`autobahn.wamp.interfaces.ISession.is_connected`
        N)r   rD   r)   r)   r*   is_connected  s   
zApplicationSession.is_connectedc                 C   s   | j duo	| jduS )zR
        Implements :func:`autobahn.wamp.interfaces.ISession.is_attached`
        N)r   r=   rD   r)   r)   r*   is_attached  s   zApplicationSession.is_attachedc                 C   sP   t |jtjr| jjd| jj|j d dS | jj	d| jj|t
|d dS )zR
        Implements :func:`autobahn.wamp.interfaces.ISession.onUserError`
        z{klass}.onUserError(): "{msg}")klassry   z*{klass}.onUserError(): "{msg}"
{traceback})r   ry   rd   N)rm   valuer   r   r5   r   rp   r   error_messagerU   r3   failure_format_tracebackrE   r   ry   r)   r)   r*   r     s   

zApplicationSession.onUserErrorc              	   C   sB   z	|  || W dS  ty    | jjdtt d Y dS w )a  
        This is an internal generic error-handler for errors encountered
        when calling down to on*() handlers that can reasonably be
        expected to be overridden in user code.

        Note that it *cancels* the error, so use with care!

        Specifically, this should *never* be added to the errback
        chain for a Deferred/coroutine that will make it out to user
        code.
        zInternal error: {tb})rw   N)r   r   r5   rU   r3   r   r   r   r)   r)   r*   r     s   z!ApplicationSession._swallow_errorc           "         s&  j du rttjr(tj}fdd}fdd}t||| dS ttjrSt	
jj tj } fdd}fdd}t||| dS ttjr}t	jj}tj|}fd	d}fd
d}t||| dS tdjttjrjst }j| d_ t	
jj tj } fdd}fdd}t||| dS ttjrjjv rjj D ]}|jjp|j}	jr;jsjj djd  dS zt!j"jj#j$}
j%d|	|
\}_&_'W n t(y, } zjj d|jd W Y d}~ dS d}~ww |	|kr;j d  dS j)rCj)fnt* }j&rQ|t*j& }j'rXj'nt+ }j,rwt	j-|j.j/j0j1|	j2jj3d	|j,< fdd}fdd}tjj4g|R i |}t||| qdS tdjttj5rӈj6j7v rˈj78j6}t9j.|j:d}t;|j<| dS tdj6ttj=rj6j>v rj>8j6}jjvrg jj< t?j|j|j}jj @| t;|j<| dS tdj6ttjArXj6jBv rPjB8j6}|jCjv rGj|jC D ]}d|_Dq;j|jC= t;|j<d dS tdj6ttjErΈj6jFv rƈjFj6 }|jGd}jr߈jsd}j | tHtHjI|}nWzt!j"jj#j$}
j%d|
\}_&_'W n$ t(y } zjj d |d! tHtHjJd"|}W Y d}~nd}~ww |kr߈jj d#|d$ tHtHjKd%|}jLrC|jMjNrA|rO|d& dS j'pt+ }j&p t* }fd'd}|jMr*|jMjPr*t|jMjNt	jQj&jRjSjTj3d(j'}ntj|jMjNg|R i |}t|d| dS dS jFj6= |j<}|rVtU|| dS j'sc|jMr|jMjPrj'phi }j&rt	jQj&jRjSjTj3d(|}nt	jQdAjRjSjTj3d(|}t;|| dS j&rtVj&d)krt	jQj& }t;|| dS t;|j&d  dS t;|d dS td*j6ttjWrj6jXv rtd+j6jYjZvrtd,jYjZjY j[}jGpjGd}jrsjsd-}j | tHtHjI|}nWzt!j"jj#j$}
j%d|
\}_&_'W n$ t(yZ } zjj d.|d! tHtHjJd/|}W Y d}~nd}~ww |krsjj d0|d$ tHtHjKd1|}|r\tjWj]j6|}j| dS |j)dur|j)f}nt* }j&r|t*j& }j'rj'nt+ }|j,rшj^rfd2d3}nd}t	j_|j`jajbjd4||j,< tj|j4g|R i |}fd5d}fd6d}tcj6|jXj6< t||| dS ttjdr)j6jXvrjjed7j6d8 dS jXj6 } tf| j< dS ttjgroj6jhv rgjh8j6}jYjZvrVtijY|jG|j[jZjY< ntd9jYt;|j< dS td:j6ttjjrӈj6dkrzjZjY }!W n tky   td;jYw jjld<|!jGjYd= dS j6jmv rˈjm8j6}|jnjZv rdjZ|jn _DjZ|jn= t;|j< dS td>j6ttjord}jptjqj]krj6jFv rjF8j6j<}nwjptjrj]krj6j7v rj78j6j<}n_jptjsj]kr$j6j>v r$j>8j6j<}nGjptjtj]kr<j6jBv r<jB8j6j<}n/jptjuj]krTj6jhv rTjh8j6j<}njptjvj]krkj6jmv rkjm8j6j<}|rtw|stU|x dS dS td?jpj6td@j)BzY
        Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onMessage`
        Nc                    s.  | d urj d tdd| }j| d S jr"j_j	_
j_j_j_j_j_tjj
jjjjjjjjjjjd d }t|d fdd t| fddd  t|d fd	d t|fd
dd  t|d fdd d S )NzSession denied by onWelcomewamp.error.cannot_authenticate{0})rH   sessionrK   rL   rM   rN   r   
serializerresumedr   r   r-   c                    r   )NzWhile notifying 'join'r   r   rD   r)   r*   r   1  r   z?ApplicationSession.onMessage.<locals>.success.<locals>.<lambda>c                    s   t j S r$   )r3   r   onJoinr   detailsrE   r)   r*   r   6  s    c                    r   )NzWhile firing onJoinr   r   rD   r)   r*   r   <  r   c                    s     d S )Nr/   r   r   rD   r)   r*   r   A  r   c                    r   )NzWhile notifying 'ready'r   r   rD   r)   r*   r   G  r   )r5   infor	   Abortr   r   r   rH   r<   r   r=   rK   r>   rL   r?   rM   r@   rN   rA   r   _router_rolesr   r   _serializerSERIALIZER_IDr   r   r   r   r3   r   )resreplyr   ry   rE   r   r*   success  sf   




z-ApplicationSession.onMessage.<locals>.successc                    s$   t dd} j|  | dS )Nr   zError calling onWelcome handlerzWhile firing onWelcome)r	   r   r   r   r   )r   r   rD   r)   r*   rU   J  s
   z+ApplicationSession.onMessage.<locals>.errorc                    s8    d} fdd}fdd}t||| |S )Nr.   c                    s    S r$   r)   r   argr)   r*   
return_arg[     zAApplicationSession.onMessage.<locals>.success.<locals>.return_argc                    r   )NzWhile firing 'leave' eventr   r   rD   r)   r*   _error^     z=ApplicationSession.onMessage.<locals>.success.<locals>._error)r   r3   r   )r   r   r   r   r   r   r*   r   W  s
   c                    r   NzWhile firing onLeaver   r   rD   r)   r*   r   c  r   z,ApplicationSession.onMessage.<locals>._errorc                    sb   | d u rt dt| tjkr| d} t| tjkr$t dt| t| } j	
| d S )Nz4onChallenge user callback did not return a signaturer[   z"signature must be unicode (was {}))r   rn   rR   binary_typer]   ro   r   r	   Authenticater   r   )	signaturer   rD   r)   r*   r   l  s   

c                    sv    | d tdd| j}j| t|j	|j t
j } fdd}fdd}t
||| |S )NzAuthentication failedr   r   c                        d  | S Nr.   r   r   r   r)   r*   r   ~     z<ApplicationSession.onMessage.<locals>.error.<locals>.successc                    r   r   r   r   rD   r)   r*   r     r   z;ApplicationSession.onMessage.<locals>.error.<locals>._error)r   r	   r   r   r   r   r   r
   r   reasonr3   r   onLeaver   )r   r   r   r   r   rD   r   r*   rU   v  s   z8Received {0} message, and session is not yet establishedc                    r   r   r   r   r   r)   r*   r     r   c                    s   d  j j}| |S )Nz7While firing onLeave for reason "{0}" and message "{1}")r   r   r	   r   r   errmsgr   r)   r*   r     s   zjreceived encoded payload with enc_algo={enc_algo}, but no payload codec active - ignoring encoded payload!r|   FzNfailed to decode application payload encoded with enc_algo={enc_algo}: {error})rU   rg   z-envelope topic URI does not match encoded one)	publisherpublisher_authidpublisher_authroletopicretainedrg   r   c                    sL    j r"jd jr$jrt j}j| d S j	d d S d S d S )Nbrokerz}successfully processed event with acknowledged delivery, but could not send ACK, since the transport was lost in the meantime)
x_acknowledged_deliveryr   x_acknowledged_event_deliveryr   r	   EventReceivedpublicationr   r5   r   )r   responser   r)   r*   _success  s   z.ApplicationSession.onMessage.<locals>._successc                    s   d  jj}| |S )Nz&While firing {0} subscribed under {1}.)r   fnsubscriptionr   r   )handlerry   rE   r)   r*   r     s   z5EVENT received for non-subscribed subscription ID {0}was_encryptedz1PUBLISHED received for non-pending request ID {0}z2SUBSCRIBED received for non-pending request ID {0}r   z4UNSUBSCRIBED received for non-pending request ID {0}r{   Tr}   r~   r   zXURI within encrypted payload ('{decrypted_proc}') does not match the envelope ('{proc}'))decrypted_procprocr   zLcould not deliver progressive call result, because payload decryption failedc                    s     | d d S )NzWhile firing on_progress)r   r   rD   r)   r*   r   G     )r   r   r   r      z.RESULT received for non-pending request ID {0}z6INVOCATION received for request ID {0} already invokedz:INVOCATION received for non-registered registration ID {0}z<received encrypted INVOCATION payload, but no keyring activez+failed to decrypt INVOCATION payload: {err}z(failed to decrypt INVOCATION payload: {}zcURI within encrypted INVOCATION payload ('{decrypted_proc}') does not match the envelope ('{proc}')zQURI within encrypted INVOCATION payload ('{}') does not match the envelope ('{}')c                     s   | d u st | ttfv sJ |d u st |tksJ |r(tjr(dd | D }d } jr=js4t	dj
d| |}|rPtj j|jd|j|j|jd}n
tj j| |dd}j| d S )Nc                 S   rY   rZ   r\   r^   r)   r)   r*   rb     rc   zBApplicationSession.onMessage.<locals>.progress.<locals>.<dictcomp>7trying to send encrypted payload, but no keyring activeFT)rf   progressrg   rh   ri   )rW   rX   r  )rn   rj   tupler   rR   rk   rl   rg   rB   r   rr   r	   Yieldru   rf   rh   ri   r   r   )rW   rX   rx   progress_msg)ry   r
  rE   r)   r*   r    s2   
z.ApplicationSession.onMessage.<locals>.progress)r  callercaller_authidcaller_authrole	procedurerg   c                    s,  j  j= d } jrNjsd}j| n8zt| tjr)j	d| j
| j}n	j	d| g}W n tyM } zjjd|d W Y d }~nd }~ww |r~t| tjrntj j|j|j|j|j| j| j| j| jd	}n3tj j|j|j|j|jd}n#t| tjrtj j| j
| j| j| j| j| jd}n	tj j| gd}jd u rjd	j j d S z	j| W d S  ty } z tjtjj jtj d
j|gd}j| W Y d }~d S d }~w t!y } z tjtjj jtj"dj|gd}j| W Y d }~d S d }~ww )Nr  Fz,failed to encrypt application payload: {err}r~   )rf   rg   rh   ri   r   r   r   r   re   )rW   rX   r   r   r   r   rW   zCSkipping result of "{}", request {} because transport disconnected.zNsuccess return value from invoked procedure "{0}" could not be serialized: {1}Ssuccess return value from invoked procedure "{0}" exceeds transport size limit: {1})#r   ru   rg   rB   r5   r   rm   r
   
CallResultrr   results	kwresultsr   r	   r  rf   rh   ri   r   r   r   r   r   debugr   r  r   r   rs   
InvocationMESSAGE_TYPEr   r9   r   r:   )r   rx   r   r   r   )ry   r
  registrationrE   r)   r*   r     s   


c                    s   j  j= t| }z| | W n   Y d }jr!t| }tj	j
 j| j| j}z	j| W d S  tyd } z tjtj	j
 jtjdj|gd}j| W Y d }~d S d }~w ty } z tjtj	j
 jtjdj|gd}j| W Y d }~d S d }~ww )NzLerror return value from invoked procedure "{0}" could not be serialized: {1}r  r  )r   ru   r3   failure_messager   r7   r   rz   r	   r  r  r   rg   r   r   r   rs   r   r9   r   r  r   r:   )r   r   formatted_tbr   r   )ry   r  rE   r)   r*   rU   8  sD   


	z7INTERRUPT received for non-pending invocation {request}ru   z<REGISTERED received for already existing registration ID {0}z2REGISTERED received for non-pending request ID {0}z:UNREGISTERED received for non-existant registration ID {0}z3Router unregistered procedure '{proc}' with ID {id})r
  idz4UNREGISTERED received for non-pending request ID {0}z^WampAppSession.onMessage(): ERROR received for non-pending request_type {0} and request ID {1}zUnexpected message {0}r)   )yr=   rm   r	   Welcomer3   r   	onWelcomer   r   r
   r   r   r   	ChallengemethodextraonChallenger   r   rp   Goodbyer   r   r   Eventr  r   r  r   rg   rB   r5   r   r   rf   ri   rh   r]   rW   rX   r   objr  r   details_argEventDetailsr  r   r   r   r   r   r  	Publishedru   r   popr   r  resolveon_reply
Subscribedr   r   appendUnsubscribedr   subscription_idactiveResultr   r  r   r   r   r   r  optionson_progressr   r   r  r   r   r   rejectlenr  r   r  r   endpointrz   r  receive_progressCallDetailsr  r  r  r!   	Interruptr  cancel
Registeredr   r   UnregisteredKeyErrorr   r   registration_idrs   rt   CallPublish	SubscribeUnsubscribeRegister
Unregister	is_calledr   )"rE   ry   r   r   rU   r   	challenger   r  r   rx   decoded_topicr   invoke_argsinvoke_kwargsr  futurepublish_requestr  ru   call_requestr   r   r	  kwrW   prog_dr1  rX   r   r<  r  invokedregr)   )r   r  ry   r
  r  rE   r*   	onMessage  sL  
B

0
2












D'

zApplicationSession.onMessagec                    s   d_ jr1tjtjjdjd tj } fdd}fdd}t	||| d_tj
}fdd}fd	d}t	||| dS )
zW
        Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onClose`
        Nz=WAMP transport was lost without closing the session {} beforer   r	   c                    r   r   r   r   r   r)   r*   r     r   z+ApplicationSession.onClose.<locals>.successc                    r   r   r   r   rD   r)   r*   r     r   z*ApplicationSession.onClose.<locals>._errorc                    s    j d dS )Nr1   )	was_cleanr   r   )rE   wasCleanr)   r*   r     s   c                    r   )NzWhile firing onDisconnectr   r   rD   r)   r*   r     r   )r   r=   r
   r   REASON_TRANSPORT_LOSTr   r3   r   r   r   onDisconnect)rE   rZ  r   r   r   r)   )r   rE   rZ  r*   onClose  s   
zApplicationSession.onClosec                 C   s   t d)zR
        Implements :func:`autobahn.wamp.interfaces.ISession.onChallenge`
        zBreceived authentication challenge, but onChallenge not implemented)r   )rE   rL  r)   r)   r*   r(    s   zApplicationSession.onChallengec                 C      dS )zM
        Implements :func:`autobahn.wamp.interfaces.ISession.onJoin`
        Nr)   rE   r   r)   r)   r*   r         zApplicationSession.onJoinc                 C   r^  )zP
        Implements :func:`autobahn.wamp.interfaces.ISession.onWelcome`
        Nr)   )rE   ry   r)   r)   r*   r$    r`  zApplicationSession.onWelcomec                    s   t d}| j| j| j| j| j| jg}g }|D ]}||	  |
  q|r1| jjdt|d |D ], | jjd j j jjd t  jsPt  j| t | fdd fdd q3|S )zB
        Errback any still outstanding requests with exc.
        Nz'Cancelling {count} outstanding requests)countzncleaning up outstanding {request_type} request {request_id}, firing errback on user handler {request_on_reply})request_on_reply
request_idrt   c                    s    j S r$   )r1  r   r!  r)   r*   r   #  s    zBApplicationSession._errback_outstanding_requests.<locals>.<lambda>)r3   create_future_successr   r   r   r   r   r   extendvaluesclearr5   r   r;  r  r1  rc  rp   r   rK  r:  r   )rE   rv   r   all_requestsoutstandingrequestsr)   r!  r*   _errback_outstanding_requests   s8   

 z0ApplicationSession._errback_outstanding_requestsc                    sX   |j tjkr jjd|j |jd t|j |j} |} fdd}t	||| |S )zN
        Implements :func:`autobahn.wamp.interfaces.ISession.onLeave`
        z/session closed with reason {reason} [{message}]rX  c                    s    j r	   d S d S r$   )r   r1   r   rD   r)   r*   r1   2  s   z.ApplicationSession.onLeave.<locals>.disconnect)
r   r   REASON_DEFAULTr5   r   r	   r   rk  r3   r   )rE   r   rv   r   r1   r)   rD   r*   r   &  s   
zApplicationSession.onLeavec                 C   sb   | j std| js |sd}tjj||d}| j| d| _n| j	d | jdu p.| jj
}|S )zL
        Implements :func:`autobahn.wamp.interfaces.ISession.leave`
        zsession hasn't joined a realmzwamp.close.normalrX  TzBsession was already requested to leave - not sending GOODBYE againN)r=   r   r   r   r	   r)  r   r   r5   r   	is_closed)rE   r   r	   ry   rm  r)   r)   r*   r.   8  s   zApplicationSession.leavec                 C   s   t  }| | dS )zS
        Implements :func:`autobahn.wamp.interfaces.ISession.onDisconnect`
        N)r   TransportLostrk  )rE   rv   r)   r)   r*   r\  M  s   zApplicationSession.onDisconnectc           
   
   O   s$  t |tjks	J |du st |ttfv sJ |du s#t |tks#J tj|d| j	j
dddd |dd}|rDt|tjsDtd|rRtjrRdd | D }| jsYt | j }d}| jrl| jd	|||}|r|rtj||f|j|j|j|jd
| }n+tj|||j|j|j|jd
}n|rtj||f||d| }n	tj||||d}|r|jdur|j|_|j dur|j |_ |j!dur|j!|_!|j"dur|j"|_"|r|j#rt$% }t&|||dud| j'|< nd}z	| j(| W |S  ty }	 z|| j'v r| j'|= |	d}	~	ww )zP
        Implements :func:`autobahn.wamp.interfaces.IPublisher.publish`
        Nz{}.publish()Fr	   strictallow_empty_components
allow_noner8  z,options must be of type a.w.t.PublishOptionsc                 S   rY   rZ   r\   r^   r)   r)   r*   rb   l  rc   z.ApplicationSession.publish.<locals>.<dictcomp>Tre   rW   rX   r  ))rn   rR   ro   rj   r  r   r	   check_or_raise_urir   rp   r   r/  rm   r
   PublishOptionsr   rk   rl   r   r   rn  rC   nextrB   rr   rF  rf   rg   rh   ri   message_attrcorrelation_idcorrelation_uricorrelation_is_anchorcorrelation_is_lastacknowledger3   create_futurer   r   r   )
rE   r   rW   rX   r8  rc  rx   ry   r1  r   r)   r)   r*   publishX  s   






	zApplicationSession.publishc              	      s&  t |r|dust|dsJ |du st|tjksJ |du s(t|tjs(J  js/t	
  fdd}t |r@|d|||S g }t|jtD ]B}|d }d|jv r|jd D ]1}| r| }	|jpg|}
|
du r|jtjjkrztjdd}
ntjd	d}
|||||	|
 qYqItj|d
dS )zS
        Implements :func:`autobahn.wamp.interfaces.ISubscriber.subscribe`
        Nrp   c                    s   t j|d jjdddd  j }t }t	|| |r |j
nd }t|||| j|< |r<t j||fi | }nt ||}|rh|jd urM|j|_|jd urV|j|_|jd ur_|j|_|jd urh|j|_ j| |S )Nz{}.subscribe()FTro  )r	   rt  r   rp   r   rC   rv  r3   r}  r   r,  r   r   rG  rw  rx  ry  rz  r{  r   r   )r+  r  r   r8  rc  r1  handler_objry   rD   r)   r*   
_subscribe  s0   




z0ApplicationSession.subscribe.<locals>._subscriber  rO   wildcard)matchexactTconsume_exceptions)callablerP   rn   rR   ro   rm   r
   SubscribeOptionsr   r   rn  r%   
getmembersrp   r+   __dict__
is_handlerr   r8  uri_typerQ   URI_TYPE_WILDCARDr3  r3   gather)rE   r  r   r8  r  
on_repliesr`   r
  patrq   suboptsr)   rD   r*   	subscribe  s.   

zApplicationSession.subscribec                 C   s   t |tsJ |jsJ |j| jv sJ || j|j v sJ | js%t | j|j | d|_t	| j|j }|dkr_| j
 }t }t|||j| j|< t||j}| j| |S t|S )zU
        Called from :meth:`autobahn.wamp.protocol.Subscription.unsubscribe`
        Fr   )rm   r   r6  r"  r   r   r   rn  remover;  rC   rv  r3   r}  r   r   r	   rH  r   rd  )rE   r  scountrc  r1  ry   r)   r)   r*   _unsubscribe  s"   


zApplicationSession._unsubscribec           	         s$  t |tjks	J |du st |ttfv sJ |du s#t |tks#J tj|dj	j
dddd |dd}|rDt|tjsDtd|rRtjrRdd | D }jsYt j  d}jrxzjd	|||}W n	   j   |r|rtj |f|j|j|j|jd
|  }n+tj ||j|j|j|jd
}n|rtj |f||d|  }n	tj |||d}|r|j!dur|j!|_!|j"dur|j"|_"|j#dur|j#|_#|j$dur|j$|_$ fdd}t%j&|d}t' |||j( < z	j)| W |S     j(v rj( =  )zJ
        Implements :func:`autobahn.wamp.interfaces.ICaller.call`
        Nz	{}.call()Fro  r8  z)options must be of type a.w.t.CallOptionsc                 S   rY   rZ   r\   r^   r)   r)   r*   rb   2  rc   z+ApplicationSession.call.<locals>.<dictcomp>Tre   rs  c                    s   t  }j| d S r$   )r	   Cancelr   r   )r   
cancel_msgrc  rE   r)   r*   	cancellerk  s   
z*ApplicationSession.call.<locals>.canceller)r  )*rn   rR   ro   rj   r  r   r	   rt  r   rp   r   r/  rm   r
   CallOptionsr   rk   rl   r   r   rn  rC   rv  rB   rr   r5   failurerE  rf   rg   rh   ri   rw  rx  ry  rz  r{  r3   r}  r    r   r   )	rE   r  rW   rX   r8  rx   ry   r  r1  r)   r  r*   call  s   






	zApplicationSession.callc              	      s  t |r|dust|dsJ |du st|tjksJ |du s(t|tjs(J  du s4t tjs4J js;t	
  fdd}t |rM|d|||S g }t|jtD ]*}|d }d|jv r|jd D ]}	|	 r|	 }
|	jpt|}|||||
| qfqVtj|ddS )	zN
        Implements :func:`autobahn.wamp.interfaces.ICallee.register`
        Nrp   c                    s   t j|djjdddd j }t }t	|| |r |j
nd } d ur-d |}t||||j|< |rFt j||fi | }nt ||}|rr|jd urW|j|_|jd ur`|j|_|jd uri|j|_|jd urr|j|_j| |S )Nz{}.register()FTro  z{}{})r	   rt  r   rp   r   rC   rv  r3   r}  r   r,  r"   r   rI  rw  rx  ry  rz  r{  r   r   )r+  r  r  r8  rc  r1  endpoint_objry   prefixrE   r)   r*   	_register  s4   




z.ApplicationSession.register.<locals>._registerr  rO   Tr  )r  rP   rn   rR   ro   rm   r
   RegisterOptionsr   r   rn  r%   r  rp   r+   r  is_endpointr   r8  r3  r3   r  )rE   r<  r  r8  r  r  r  r`   r
  r  rq   regoptsr)   r  r*   register  s(    

zApplicationSession.registerc                 C   sz   t |tsJ |jsJ |j| jv sJ | jst | j	 }t
 }t|||j| j|< t||j}| j| |S )zT
        Called from :meth:`autobahn.wamp.protocol.Registration.unregister`
        )rm   r   r6  r"  r   r   r   rn  rC   rv  r3   r}  r#   r   r	   rJ  r   )rE   r  rc  r1  ry   r)   r)   r*   _unregister  s   

zApplicationSession._unregisterr$   )NNNNNNNr   )NNN)r   r   r   r   rF   r   r   r   r   r   r-   r1   r   r   r   r   rW  r]  r(  r   r$  rk  r   r.   r\  r~  r  r  r  r  r  r)   r)   r)   r*   r   ?  sx    
"



+



     X
#


&



`B"
gAr   c                   @   st   e Zd ZdZdZdd Zdd Zdd Zd	d
 Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd ZdS )_SessionShima  
    shim that lets us present pep8 API for user-classes to override,
    but also backwards-compatible for existing code using
    ApplicationSession "directly".

    **NOTE:** this is not public or intended for use; you should import
    either :class:`autobahn.asyncio.wamp.Session` or
    :class:`autobahn.twisted.wamp.Session` depending on which async
    framework you're using.
    Nc                 C   
   |  |S r$   )on_joinr_  r)   r)   r*   r        
z_SessionShim.onJoinc                 C   sx   | j r6dd | j  D d }dd | j  D d }|  }| j| jjt| j  |p-d|p0d|d d S |   d S )Nc                 S      g | ]	}|j d dqS )rK   N_argsgetr_   xr)   r)   r*   
<listcomp>      z*_SessionShim.onConnect.<locals>.<listcomp>c                 S   r  )rL   Nr  r  r)   r)   r*   r    r  r   default)r   rK   rL   r   )	_authenticatorsrf  _merged_authextrar-   r   rH   rj   keys
on_connect)rE   rK   rL   r   r)   r)   r*   r     s   
z_SessionShim.onConnectc                 C   s<   z| j |j }W n ty   td|jw || |S )Nz.Received challenge for unknown authmethod '{}')r  r&  rC  RuntimeErrorr   on_challenge)rE   rL  authenticatorr)   r)   r*   r(    s   z_SessionShim.onChallengec                 C   sV   |j d u s
| jd u rd S z| j|j  }W n ty#   td|j w || |jS )Nz.Received onWelcome for unknown authmethod '{}')rM   r  rC  r  r   
on_welcomer   )rE   ry   r  r)   r)   r*   r$    s   z_SessionShim.onWelcomec                 C   r  r$   )on_leaver_  r)   r)   r*   r     r  z_SessionShim.onLeavec                 C   s   |   S r$   )on_disconnectrD   r)   r)   r*   r\  !  s   z_SessionShim.onDisconnectc                    s   t  tsJ jd u ri _ fdd}|d |d  j} }| D ]\}}||v rB|| |krBtd|||| q) j j< d S )Nc                    sL   t  fddtj g D }t|dkr$td d|d S )Nc                    s    g | ]} |j v r|j   qS r)   )r  r_   anamer)   r*   r  1  s
    
zG_SessionShim.add_authenticator.<locals>.at_most_one.<locals>.<listcomp>r  zInconsistent {}s: {} )setrj   r  rf  r;  
ValueErrorr   r-   )r  unir  rE   r  r*   at_most_one0  s   z3_SessionShim.add_authenticator.<locals>.at_most_onerK   rL   z4Inconsistent authextra values for '{}': '{}' vs '{}')	rm   r   r  r   r  itemsr  r   r  )rE   r  r  r   mergedr`   ra   r)   r  r*   add_authenticator&  s"   

z_SessionShim.add_authenticatorc                    sH   dd | j  D  dd }t| t } fddfdd|D S )	a:  
        internal helper

        :returns: a single 'authextra' dict, consisting of all keys
            from any authenticator's authextra.

        Note that when the authenticator was added, we already checked
        that any keys it does contain has the same value as any
        existing authextra.
        c                 S   s   g | ]}|j qS r)   )r   r  r)   r)   r*   r  ^  s    z2_SessionShim._merged_authextra.<locals>.<listcomp>c                 S   s   | t | B S r$   )r  r  )r  yr)   r)   r*   extract_keys`  r  z4_SessionShim._merged_authextra.<locals>.extract_keysc                    s,    D ]}| |v r||    S qt d| )z
            for anything already in self._authenticators, we checked
            that it has the same value for any keys in its authextra --
            so here we just extract the first one
            zNo values for '{}')r  r   )r`   r   )
authextrasr)   r*   first_value_fore  s   z7_SessionShim._merged_authextra.<locals>.first_value_forc                    s   i | ]}| |qS r)   r)   )r_   r`   )r  r)   r*   rb   s  s    z2_SessionShim._merged_authextra.<locals>.<dictcomp>)r  rf  r   r  )rE   r  unique_keysr)   )r  r  r*   r  S  s   
z_SessionShim._merged_authextrac                 C      d S r$   r)   r_  r)   r)   r*   r  {  r   z_SessionShim.on_joinc                 C   s   |    d S r$   )r1   r_  r)   r)   r*   r  ~  r   z_SessionShim.on_leavec                 C   s   |  | jj d S r$   r   rD   r)   r)   r*   r    s   z_SessionShim.on_connectc                 C   r  r$   r)   rD   r)   r)   r*   r    r   z_SessionShim.on_disconnect)r   r   r   r   r  r   r   r(  r$  r   r\  r  r  r  r  r  r  r)   r)   r)   r*   r    s    -(r  c                   @   s(   e Zd ZdZeZ	 dddZdd ZdS )ApplicationSessionFactoryz(
    WAMP endpoint session factory.
    Nc                 C   s   |pt jdd| _dS )z

        :param config: The default component configuration.
        :type config: instance of :class:`autobahn.wamp.types.ComponentConfig`
        r   r   N)r
   r   r   r   r)   r)   r*   rF     s   z"ApplicationSessionFactory.__init__c                 C   s   |  | j}| |_|S )z
        Creates a new WAMP application session.

        :returns: -- An instance of the WAMP application session class as
                     given by `self.session`.
        )r   r   factory)rE   r   r)   r)   r*   __call__  s   z"ApplicationSessionFactory.__call__r$   )r   r   r   r   r   r   rF   r  r)   r)   r)   r*   r    s    
r  )5
__future__r   rR   r3   r%   	functoolsr   autobahnr   autobahn.utilr   r   r   autobahn.wampr   r	   r
   r   r   autobahn.wamp.exceptionr   r   r   r   autobahn.wamp.interfacesr   r   r   autobahn.wamp.typesr   r   r   autobahn.exceptionr   autobahn.wamp.requestr   r   r   r   r   r   r   r   r    r!   r"   r#   r+   r,   r   r  objectr  r)   r)   r)   r*   <module>   sJ   8             ) /