o
    >hh                    @   s  d dl mZmZmZmZmZmZm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 m!Z!m"Z" d dl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* d dl+m,Z, d dl-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 dd Z:G dd deZ;eG dd de;Z<G dd de<Z=e>e< G dd de?Z@dS )    )UnionOptionalDictAnyClassVarListCallableN)reduce)wamp)publicIdGeneratorObservableMixin)uri)message)types)role)	exception)ApplicationErrorProtocolErrorSerializationErrorTypeCheckError)ISessionIPayloadCodecIAuthenticator
ITransportIMessage)	ChallengeSessionDetailsCloseDetailsEncodedPayloadSubscribeOptions
CallResultRegisterOptions)PayloadExceededError)PublicationSubscriptionHandlerRegistrationEndpointPublishRequestSubscribeRequestUnsubscribeRequestCallRequestInvocationRequestRegisterRequestUnregisterRequestc                 C   s   t | p	t | S N)inspectismethod
isfunction)f r5   v/var/www/vedio/testing/chatpythonscript.ninositsolution.com/env/lib/python3.10/site-packages/autobahn/wamp/protocol.pyis_method_or_function;   s   r7   c                   @   s8  e Zd ZdZdZdd Zedee fddZ	e
defdd	Ze
defd
dZedee fddZedee fddZedee fddZedee fddZedee fddZedee fddZedee fddZedeeeef  fddZd$dedee f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   s   t  | _| jg dd d| _i | _tjttj	t
i| _d | _d | _d | _d | _d | _d | _d | _d | _tj| _d | _d | _t | _d S )N)joinleavereadyconnect
disconnect)valid_eventsF)txaiomake_loggerlogset_valid_eventstraceback_app_ecls_to_uri_patr   INVALID_PAYLOADr   PAYLOAD_SIZE_EXCEEDEDr#   _uri_to_ecls
_transport_realm_session_id_authid	_authrole_authmethod_authprovider
_authextrar   DEFAULT_CLIENT_ROLES_session_roles_session_details_payload_codecr   _request_id_genselfr5   r5   r6   __init__G   s*   
zBaseSession.__init__returnc                 C      | j S )zY
        Implements :func:`autobahn.wamp.interfaces.ITransportHandler.transport`
        )rH   rU   r5   r5   r6   	transportz   s   zBaseSession.transportc                 C   s   | j duo	| j  S )zS
        Implements :func:`autobahn.wamp.interfaces.ISession.is_connected`
        N)rH   isOpenrU   r5   r5   r6   is_connected   s   zBaseSession.is_connectedc                 C   s   | j duo|  S )zR
        Implements :func:`autobahn.wamp.interfaces.ISession.is_attached`
        N)rJ   r\   rU   r5   r5   r6   is_attached   s   zBaseSession.is_attachedc                 C   rY   )zV
        Implements :func:`autobahn.wamp.interfaces.ISession.session_details`
        )rR   rU   r5   r5   r6   session_details      zBaseSession.session_detailsc                 C   rY   r0   )rI   rU   r5   r5   r6   realm      zBaseSession.realmc                 C   rY   r0   )rJ   rU   r5   r5   r6   
session_id   ra   zBaseSession.session_idc                 C   rY   r0   )rK   rU   r5   r5   r6   authid   ra   zBaseSession.authidc                 C   rY   r0   )rL   rU   r5   r5   r6   authrole   ra   zBaseSession.authrolec                 C   rY   r0   )rM   rU   r5   r5   r6   
authmethod   ra   zBaseSession.authmethodc                 C   rY   r0   )rN   rU   r5   r5   r6   authprovider   ra   zBaseSession.authproviderc                 C   rY   r0   )rO   rU   r5   r5   r6   	authextra   ra   zBaseSession.authextrar   errorc                 C   sv   |du rt |dr|j| j|< || j|jd  < dS tdt |ds7t|tjjg| j|< || j|< dS td)zM
        Implements :func:`autobahn.wamp.interfaces.ISession.define`
        N	_wampurisr   zNcannot define WAMP exception from class with no decoration ("_wampuris" unset)z\cannot define WAMP exception: error URI is explicit, but class is decorated ("_wampuris" set)hasattrri   rD   rG   r   RuntimeErrorPatternURI_TARGET_HANDLER)rV   r   rh   r5   r5   r6   define   s   

zBaseSession.definec              	   C   s   d}t |drt|j}d}t |dr|j}|r#|r||d< nd|i}t|tjr7t|jt	kr3|jn|j}n|j
| jv rG| j|j
 d j}nd}d}	| jrW| jd|||}	|	rkt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kwargs	tracebackr   zwamp.error.runtime_errorFpayloadenc_algoenc_keyenc_serializer)rj   listro   rp   
isinstancer   r   typerh   str	__class__rD   _urirS   encoder   Errorrs   rt   ru   rv   )rV   request_typerequestexctbrt   ro   rp   rh   encoded_payloadmsgr5   r5   r6   _message_from_exception   sF   



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rt   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_errorrh   FURI within encrypted payload ('{}') does not match the envelope ('{}')zWhile re-constructing exceptionrt   calleecallee_authidcallee_authroleforward_forr5   )rt   rS   rA   warnr   ENC_NO_PAYLOAD_CODECr   rs   rv   ru   decoderh   ro   rp   	ExceptionENC_DECRYPT_ERRORformatENC_TRUSTED_URI_MISMATCHrG   onUserErrorr?   create_failurer   rj   r   r   r   r   )	rV   r   r   enc_errlog_msgr   r   eeclsr5   r5   r6   _exception_from_message   s    
	 z#BaseSession._exception_from_messager0   NN)__name__
__module____qualname____doc__rA   rW   propertyr   r   rZ   r   boolr\   r]   r   r^   rz   r`   intrb   rc   rd   re   rf   r   r   rg   r   rn   r   r   r5   r5   r5   r6   r8   ?   s:    3
;r8   c                   @   s  e Zd ZdZdPdeej fddZedejfddZ	e
d	ee fd
dZe
dee fddZe
defddZe
dd Ze
							dQdedeee  dee dee deeeef  dee dee dee fddZe
dd Ze
dd  Zd!d" Zd#d$ Zd%efd&d'Ze
d(d) Ze
d*edefd+d,Z e
d-e!fd.d/Z"e
d0e#j$dee fd1d2Z%d3d4 Z&e
d-e'fd5d6Z(e
dRd7ee d8ee fd9d:Z)e
d;d< Z*e
d=edee+ fd>d?Z,e
		dSd@e-e.ef d=ee dAee/ dBee de-e0ee0 f f
dCdDZ1dEdF Z2e
dGede-ee3f fdHdIZ4e
			dTdJe-e.ef dGee dAee5 dKee dBee de-e6ee6 f fdLdMZ7dNdO Z8dS )UApplicationSessionz
    WAMP application session for applications (networking framework agnostic parts).

    Implements (partially):

        * :class:`autobahn.wamp.interfaces.ITransportHandler`
        * :class:`autobahn.wamp.interfaces.ISession`
    Nconfigc                 C   sh   t |  |p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r`   FN)r8   rW   r   ComponentConfig_config_goodbye_sent_transport_is_closingrS   _publish_reqs_subscribe_reqs_unsubscribe_reqs
_call_reqs_register_reqs_unregister_reqs_subscriptions_registrations_invocationsrV   r   r5   r5   r6   rW   p  s   

zApplicationSession.__init__rX   c                 C   rY   r0   )r   rU   r5   r5   r6   r     ra   zApplicationSession.configpayload_codecc                 C   s
   || _ dS )zX
        Implements :func:`autobahn.wamp.interfaces.ISession.set_payload_codec`
        NrS   )rV   r   r5   r5   r6   set_payload_codec  s   
z$ApplicationSession.set_payload_codecc                 C   rY   )zX
        Implements :func:`autobahn.wamp.interfaces.ISession.get_payload_codec`
        r   rU   r5   r5   r6   get_payload_codec  r_   z$ApplicationSession.get_payload_codecrZ   c                    s`    j jd j|d | _ d |}t|d fdd t| fdd fdd dS )	zV
        Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onOpen`
        z{func}(transport={transport}))funcrZ   r<   Nc                         | dS )NzWhile notifying 'connect'_swallow_errorfailrU   r5   r6   <lambda>      z+ApplicationSession.onOpen.<locals>.<lambda>c                    s   t  jS r0   )r?   	as_future	onConnect_rU   r5   r6   r     r   c                    r   )NzWhile calling 'onConnect'r   r   rU   r5   r6   r     r   )rA   debugonOpenrH   firer?   add_callbacks)rV   rZ   dr5   rU   r6   r     s   


zApplicationSession.onOpenc                 C   s$   | j jd| jd | | jj dS )zP
        Implements :func:`autobahn.wamp.interfaces.ISession.onConnect`
        z{func}()r   N)rA   r   r   r9   r   r`   rU   r5   r5   r6   r     s   zApplicationSession.onConnectr`   authmethodsrc   rd   rg   	resumableresume_sessionresume_tokenc	           
      C   sV   | j rtd| jstd|| _d| _tj|| j|||||||d	}	| j|	 dS )zK
        Implements :func:`autobahn.wamp.interfaces.ISession.join`
        zsession already joinedzno transport set for sessionF)	r`   rolesr   rc   rd   rg   r   r   r   N)	rJ   r   rH   rI   r   r   HellorQ   send)
rV   r`   r   rc   rd   rg   r   r   r   r   r5   r5   r6   r9     s"   	zApplicationSession.joinc                 C   s   | j r
| j   dS dS )zQ
        Implements :func:`autobahn.wamp.interfaces.ISession.disconnect`
        N)rH   closerU   r5   r5   r6   r=     s   zApplicationSession.disconnectc                 C   sZ   t |dr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`
        valuez{klass}.onUserError(): "{msg}")klassr   z*{klass}.onUserError(): "{msg}"
{traceback})r   r   rq   N)rj   rx   r   r   r   rA   r   r{   r   error_messagerh   r?   failure_format_tracebackrV   r   r   r5   r5   r6   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})r   N)r   r   rA   rh   r?   r   r   r   r5   r5   r6   r     s   z!ApplicationSession._swallow_errorc                    s    fdd}|S )z
        Does parameter type checking and validation against type hints
        and appropriately tells the user code and the caller (through router).
        c               
      s   t j g| R i |}g } j D ]G\}}||v r[t|dd tkrDdd |jD }t|| |jsC|d	||t
|| j qt|| |s[|d	||jt
|| j q|retd|tj g| R i |I d H S )N
__origin__c                 S      g | ]}|j qS r5   )r   ).0argr5   r5   r6   
<listcomp>!      zFApplicationSession.type_check.<locals>._type_check.<locals>.<listcomp>z'{}' expected types={} got={}z'{}' expected type={} got={}z, )r1   getcallargs__annotations__itemsgetattrr   __args__rx   appendr   ry   r   r   r9   r?   r   )ro   rp   	argumentsresponsenamekindexpected_typesr   r5   r6   _type_check  s,   z2ApplicationSession.type_check.<locals>._type_checkr5   )rV   r   r   r5   r   r6   
type_check  s   zApplicationSession.type_checkr   c           "         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,ryt	j-|j.j/j0j1|	j2j3jj4d
|j,< fdd}fdd}tjj5g|R i |}t||| qdS tdjttj6rj7j8v r݈j89j7}t:|j;rt<|j;rdS t=j.|j>d}t?|j;| dS tdj7ttj@r;j7jAv r3jA9j7}t:|j;r
t<|j;r
dS jjvrg jj< tBj|j|j}jj C| t?|j;| dS tdj7ttjDrj7jEv rjE9j7}t:|j;r`t<|j;r`dS |jFjv ryj|jF D ]}d|_Gqmj|jF= t?|j;d dS tdj7ttjHrj7jIv rjIj7 }|jJd}jrjsd}j | tKtKjL|}nWzt!j"jj#j$}
j%d|
\}_&_'W n$ t(y } zjj d |d! tKtKjMd"|}W Y d}~nd}~ww |krjj d#|d$ tKtKjNd%|}jOru|jPjQrs|r%R|d& dS j'p+t+ }j&p2t* }fd'd}|jPr\|jPjSr\t|jPjQt	jTj&jUjVjWj4d(j'}ntj|jPjQg|R i |}t|d| dS dS jIj7= |j;}t:|rt<|rdS |rtX|| dS j's|jPr|jPjSrوj'pi }j&rt	jTj&jUjVjWj4d(|}nt	jTdAjUjVjWj4d(|}t?|| dS j&rtYj&d)krt	jTj& }t?|| dS t?|j&d  dS t?|d dS td*j7ttjZrDj7j[v r$td+j7j\j]vr3td,j\j]j\ j^}jJpBjJd}jrjs\d-}j | tKtKjL|}nWzt!j"jj#j$}
j%d|
\}_&_'W n$ t(y } zjj d.|d! tKtKjMd/|}W Y d}~nd}~ww |krjj d0|d$ tKtKjNd1|}|rȈ_tjZj`j7|}j| dS |j)dur|j)f}nt* }j&r|t*j& }j'rj'nt+ }|j,rjarfd2d3}nd}t	jb|jcjdjej2jd4||j,< tj|j5g|R i |}fd5d}fd6d}tfj7|j[j7< t||| dS ttjgrkj7j[vr]jjhd7j7d8 dS j[j7 } ti| j; dS ttjjrj7jkv rjk9j7}t:|j;rt<|j;rdS j\j]vrtlj\|jJ|j^j]j\< ntd9j\t?|j; dS td:j7ttjmr5j7dkrzj]j\ }!W n tny   td;j\w jjhd<|!jJj\d= dS j7jov r-jo9j7}t:|j;rt<|j;rdS |jpj]v r%dj]|jp _Gj]|jp= t?|j; dS td>j7ttjqrd}jrtjsj`krVj7jIv rVjI9j7j;}nwjrtjtj`krnj7j8v rnj89j7j;}n_jrtjuj`krj7jAv rjA9j7j;}nGjrtjvj`krj7jEv rjE9j7j;}n/jrtjwj`krj7jkv rjk9j7j;}njrtjxj`kr͈j7jov r͈jo9j7j;}|rt<|stX|y dS dS td?jrj7td@j)BzY
        Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onMessage`
        Nc                    s<  | d urj jd| d tdd| }j| d S  jr$ j_ j	_
 j_ j_ j_ j_ j_ j_tjj
jjjj jjjjjjddd d_dj}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: {res})reswamp.error.cannot_authenticate{0}F)r`   sessionrc   rd   re   rf   rg   
serializerrZ   resumedr   r   r9   c                    r   )NzWhile notifying 'join'r   r   rU   r5   r6   r   n  r   z?ApplicationSession.onMessage.<locals>.success.<locals>.<lambda>c                    s   t  j jS r0   )r?   r   onJoinrR   r   rU   r5   r6   r   s  s    c                    r   )NzWhile firing onJoinr   r   rU   r5   r6   r   y  r   c                    s     d S )Nr;   r   r   rU   r5   r6   r   ~  r   c                    r   )NzWhile notifying 'ready'r   r   rU   r5   r6   r     r   )rA   r   r   Abortr   rH   r   r`   rI   r   rJ   rc   rK   rd   rL   re   rM   rf   rN   rg   rO   r   _router_rolesr   _serializerSERIALIZER_IDtransport_detailsrR   r   r?   r   )r   replyr   r   rV   r5   r6   successA  sj   





z-ApplicationSession.onMessage.<locals>.successc                    s$   t dd} j|  | dS )Nr   zError calling onWelcome handlerzWhile firing onWelcome)r   r   rH   r   r   )r   r   rU   r5   r6   rh     s
   z+ApplicationSession.onMessage.<locals>.errorc                    s8    d} fdd}fdd}t||| |S )Nr:   c                    s    S r0   r5   r   r   r5   r6   
return_arg     zAApplicationSession.onMessage.<locals>.success.<locals>.return_argc                    r   )NzWhile firing 'leave' eventr   r   rU   r5   r6   _error     z=ApplicationSession.onMessage.<locals>.success.<locals>._error)r   r?   r   )r   r   r  r  detailsrV   r  r6   r     s
   c                    r   NzWhile firing onLeaver   r   rU   r5   r6   r    r  z,ApplicationSession.onMessage.<locals>._errorc                    s^   | d u rt dt| tkr| d} t| tkr"t dt| t| } j	| d S )Nz4onChallenge user callback did not return a signatureutf8z"signature must be unicode (was {}))
r   ry   bytesr   rz   r   r   AuthenticaterH   r   )	signaturer   rU   r5   r6   r     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  r5   r6   r        z<ApplicationSession.onMessage.<locals>.error.<locals>.successc                    r   r  r   r   rU   r5   r6   r    r  z;ApplicationSession.onMessage.<locals>.error.<locals>._error)r   r   r   r   r   rH   r   r   r   reasonr?   r   onLeaver   )r   r   r   r   r  rU   )r  r6   rh     s   z8Received {0} message, and session is not yet establishedc                    r  r  r   r  r  r5   r6   r     r  c                    s   d  j j}| |S )Nz7While firing onLeave for reason "{0}" and message "{1}")r   r  r   r   r   errmsgr   r5   r6   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})rh   rt   z-envelope topic URI does not match encoded one)	publisherpublisher_authidpublisher_authroletopictransaction_hashretainedrt   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_deliveryrH   r   EventReceivedpublicationr   rA   r   )r   r   r   r5   r6   _success  s   z.ApplicationSession.onMessage.<locals>._successc                    s   d  jj}| |S )Nz&While firing {0} subscribed under {1}.)r   fnsubscriptionr   r  )handlerr   rV   r5   r6   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   rU   r5   r6   r       )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 d } jr/js&tdjd| |}|rBtj	 j
|jd|j|j|jd}n
tj	 j
| |dd}j| d S )N7trying to send encrypted payload, but no keyring activeFT)rs   progressrt   ru   rv   )ro   rp   r*  )ry   rw   tupledictrt   rS   r   r}   r   Yieldr   rs   ru   rv   rH   r   )ro   rp   r   progress_msg)r   r&  rV   r5   r6   r*    s*   z.ApplicationSession.onMessage.<locals>.progress)r*  callercaller_authidcaller_authrole	procedurer  rt   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!|j"j|gd}j| W Y d }~d S d }~w t#y } z$tjtjj jtj$d|j!|j"j|gd}j| W Y d }~d S d }~ww )Nr)  Fz,failed to encrypt application payload: {err}r   )rs   rt   ru   rv   r   r   r   r   rr   )ro   rp   r   r   r   r   ro   zCSkipping result of "{}", request {} because transport disconnected.zasuccess return value (args={}, kwargs={}) from invoked procedure "{}" could not be serialized: {}zfsuccess return value (args={}, kwargs={}) from invoked procedure "{}" exceeds transport size limit: {})%r   r   rt   rS   rA   r   rx   r   r!   r}   results	kwresultsr   r   r-  rs   ru   rv   r   r   r   r   rH   r   r   r2  r   r   r~   
InvocationMESSAGE_TYPEr   rE   ro   rp   r#   rF   )r   r   r   r   r   error_reply)r   r&  registrationrV   r5   r6   r   8  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}r3  zSsuccess return value from invoked procedure "{0}" exceeds transport size limit: {1})r   r   r?   failure_messager   rC   r   r   r   r6  r7  r   rt   rH   r   r   r~   r   rE   r   r2  r#   rF   )r   r  formatted_tbr   r   )r   r9  rV   r5   r6   rh     sD   


	z7INTERRUPT received for non-pending invocation {request}r   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}r5   )zrJ   rx   r   Welcomer?   r   	onWelcomer   r   r   r   r  r  r   methodextraonChallenger   r   r{   Goodbyer   rH   r   Eventr!  r   r"  r  rt   rS   rA   r   r   rs   rv   ru   r   ro   rp   r   objr+  r,  details_argEventDetailsr  r  r  r  r  r  r   r   	Publishedr   r   pop	is_futureon_reply	is_calledr$   r$  resolve
Subscribedr   r%   r   Unsubscribedr   subscription_idactiveResultr   r2  r   r   r   r   r*  optionson_progressr   r  r!   r   r   r   rejectlenr6  r   r9  r   endpointr   r7  receive_progressCallDetailsr/  r0  r1  r-   	Interruptr   cancel
Registeredr   r'   UnregisteredKeyErrorr   registration_idr~   r   CallPublish	SubscribeUnsubscribeRegister
Unregisterr   )"rV   r   r   r   rh   r  	challenger   r!  r  r   decoded_topicr   invoke_argsinvoke_kwargsr  futurepublish_requestr  r   call_requestr   r   r%  kwro   prog_drK  rp   r   rW  r*  invokedregr5   )r  r"  r   r&  r9  rV   r6   	onMessage/  sf  
F

4
2



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



	J'

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  r5   r6   r   (  r  z+ApplicationSession.onClose.<locals>.successc                    r   r  r   r   rU   r5   r6   r  -  r  z*ApplicationSession.onClose.<locals>._errorc                    s    j d dS )Nr=   )	was_cleanr   r  )rV   wasCleanr5   r6   r   5  s   c                    r   )NzWhile firing onDisconnectr   r   rU   r5   r6   r  9  r  )rH   rJ   r   r   REASON_TRANSPORT_LOSTr   r?   r   r  r   onDisconnect)rV   rt  r   r   r  r5   )r  rV   rt  r6   onClose  s   
zApplicationSession.onCloserf  c                 C   s   t d)zR
        Implements :func:`autobahn.wamp.interfaces.ISession.onChallenge`
        zBreceived authentication challenge, but onChallenge not implemented)rk   )rV   rf  r5   r5   r6   rB  =  s   	zApplicationSession.onChallenger  c                 C      dS )zM
        Implements :meth:`autobahn.wamp.interfaces.ISession.onJoin`
        Nr5   rV   r  r5   r5   r6   r   H      zApplicationSession.onJoinwelcomec                 C   rx  )zP
        Implements :meth:`autobahn.wamp.interfaces.ISession.onWelcome`
        Nr5   )rV   r{  r5   r5   r6   r?  N  rz  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_idr   c                    s    j S r0   )rK  r   r<  r5   r6   r   w  s    zBApplicationSession._errback_outstanding_requests.<locals>.<lambda>)r?   create_future_successr   r   r   r   r   r   extendvaluesclearrA   inforV  r   rK  r~  r{   r   rL  rU  r   )rV   r   r   all_requestsoutstandingrequestsr5   r<  r6   _errback_outstanding_requestsT  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 :meth:`autobahn.wamp.interfaces.ISession.onLeave`
        z/session closed with reason {reason} [{message}]rr  c                    s    j r	   d S d S r0   )rH   r=   r   rU   r5   r6   r=     s   z.ApplicationSession.onLeave.<locals>.disconnect)
r  r   REASON_DEFAULTrA   r   r   r   r  r?   r   )rV   r  r   r   r=   r5   rU   r6   r  z  s   
zApplicationSession.onLeaver  r   c                 C   sj   | j s| jd dS | js$|sd}tjj||d}| j| d| _n| jd | jdu p2| jj	}|S )zL
        Implements :meth:`autobahn.wamp.interfaces.ISession.leave`
        z6session is not joined on a realm - no session to leaveNzwamp.close.normalrr  TzBsession was already requested to leave - not sending GOODBYE again)
rJ   rA   r   r   r
   r   rC  rH   r   	is_closed)rV   r  r   r   r  r5   r5   r6   r:     s   zApplicationSession.leavec                 C   s   t  }| | dS )zS
        Implements :meth:`autobahn.wamp.interfaces.ISession.onDisconnect`
        N)r   TransportLostr  )rV   r   r5   r5   r6   rv    s   zApplicationSession.onDisconnectr  c           
   
   O   s  t |t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}|rCt|tjsCtd| jsJt | j }d}| jr]| jd|||}|r|rwt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 :meth:`autobahn.wamp.interfaces.IPublisher.publish`
        Nz{}.publish()Fr   strictallow_empty_components
allow_nonerS  z,options must be of type a.w.t.PublishOptionsTrr   ro   rp   r#  )&ry   rz   rw   r+  r,  r   check_or_raise_urir   r{   r   rI  rx   r   PublishOptionsr   rH   r   r  rT   nextrS   r}   ra  rs   rt   ru   rv   message_attrcorrelation_idcorrelation_uricorrelation_is_anchorcorrelation_is_lastacknowledger?   create_futurer)   r   r   )
rV   r  ro   rp   rS  r~  r   r   rK  r   r5   r5   r6   publish  s   





	
zApplicationSession.publishr"  rS  check_typesc              
      s.  t |r|dust|dr|rJ |du st|tksJ |du s)t|tjs)J  js0t	  fdd}t |rB|d||||S g }t
|jtD ]D}|d }d|jv r|jd D ]3}	|	 r|	 }
|	jpi|}|du r|	jtjjkr|tjdd}ntjd	d}|||||
||	j q[qKtj|d
dS )zS
        Implements :meth:`autobahn.wamp.interfaces.ISubscriber.subscribe`
        Nr{   c           	         s   t j|d jjdddd  j }t }|r 	|}t
|| |r'|jnd }t|||| j|< |rCt j||fi | }nt ||}|ro|jd urT|j|_|jd ur]|j|_|jd urf|j|_|jd uro|j|_ j| |S )Nz{}.subscribe()FTr  )r   r  r   r{   r   rT   r  r?   r  r   r&   rF  r*   r   rb  r  r  r  r  r  rH   r   )	rE  r   r  rS  r  r~  rK  handler_objr   rU   r5   r6   
_subscribe  s4   





z0ApplicationSession.subscribe.<locals>._subscriber(  ri   wildcard)matchexactTconsume_exceptions)callablerj   ry   rz   rx   r   r    rH   r   r  r1   
getmembersr{   r7   __dict__
is_handlerr   rS  uri_typerl   URI_TYPE_WILDCARDr   _check_typesr?   gather)rV   r"  r  rS  r  r  
on_replieskr&  patr|   suboptsr5   rU   r6   	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   )rx   r%   rQ  r=  r   rH   r   r  removerV  rT   r  r?   r  r+   r   r   rc  r   r  )rV   r!  scountr~  rK  r   r5   r5   r6   _unsubscribeQ  s"   


zApplicationSession._unsubscriber2  c           	         s  t |t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}|rCt|tjsCtdjsJt j  d}jriz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% =  )a{  
        Implements :meth:`autobahn.wamp.interfaces.ICaller.call`

        .. note::

            Regarding type hints for ``*args`` and ``**kwargs``, doesn't work as we
            can receive any Python types as list items or dict values, and because
            of what is discussed here
            https://adamj.eu/tech/2021/05/11/python-type-hints-args-and-kwargs/
        Nz	{}.call()Fr  rS  z)options must be of type a.w.t.CallOptionsTrr   r  c                    s   t  }j| d S r0   )r   CancelrH   r   )r   
cancel_msgr~  rV   r5   r6   	canceller  s   
z*ApplicationSession.call.<locals>.canceller)r  )'ry   rz   rw   r+  r,  r   r  r   r{   r   rI  rx   r   CallOptionsr   rH   r   r  rT   r  rS   r}   rA   failurer`  rs   rt   ru   rv   r  r  r  r  r  r?   r  r,   r   r   )	rV   r2  ro   rp   rS  r   r   r  rK  r5   r  r6   calls  s   





	zApplicationSession.callrW  prefixc              
      s   t |r|dust|dr|rJ jst  fdd}t |r+|d||||S g }t|jtD ],}|d }	d|	j	v r`|	j	d D ]}
|

 r_|
 }|
jpR|}||||	|||
j qDq4tj|ddS )	zN
        Implements :meth:`autobahn.wamp.interfaces.ICallee.register`
        Nr{   c           	         s  t j|djjdddd j }t }|r	|}t
|| |r'|jnd } d ur4d |}t||||j|< |rMt j||fi | }nt ||}|ry|jd ur^|j|_|jd urg|j|_|jd urp|j|_|jd ury|j|_j| |S )Nz{}.register()FTr  z{}{})r   r  r   r{   r   rT   r  r?   r  r   r(   rF  r.   r   rd  r  r  r  r  r  rH   r   )	rE  r   r2  rS  r  r~  rK  endpoint_objr   r  rV   r5   r6   	_register  s8   





z.ApplicationSession.register.<locals>._registerr(  ri   Tr  )r  rj   rH   r   r  r1   r  r{   r7   r  is_endpointr   rS  r   r  r?   r  )rV   rW  r2  rS  r  r  r  r  r  r&  r  r|   regoptsr5   r  r6   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`
        )rx   r'   rQ  r=  r   rH   r   r  rT   r  r?   r  r/   r   r   re  r   )rV   r9  r~  rK  r   r5   r5   r6   _unregister  s   

zApplicationSession._unregisterr0   )NNNNNNNr   )NNN)NNNN)9r   r   r   r   r   r   r   rW   r   r   r   r   r   r   r   r   r   rz   r   r   r   r   r   r9   r=   r   r   r   r   rq  rw  r   rB  r   r   r   r>  r?  r  r   r  r:   rv  r$   r  r   r   r    r%   r  r  r!   r  r"   r'   r  r  r5   r5   r5   r6   r   e  s    	

%

     o
#
&
ZE"h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 )_SessionShimar  
    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 autobahn.asyncio.wamp.Session or
    autobahn.twisted.wamp.Session depending on which async
    framework yo're using.
    Nc                 C   
   |  |S r0   )on_joinry  r5   r5   r6   r   C     
z_SessionShim.onJoinc                 C   sp   | j r2dd | j  D d }dd | j  D d }|  }| j| jjt| j  |||d d S |   d S )Nc                 S      g | ]	}|j d dqS )rc   N_argsgetr   xr5   r5   r6   r   K      z*_SessionShim.onConnect.<locals>.<listcomp>c                 S   r  )rd   Nr  r  r5   r5   r6   r   L  r  )r   rc   rd   rg   )	_authenticatorsr  _merged_authextrar9   r   r`   rw   keys
on_connect)rV   rc   rd   rg   r5   r5   r6   r   F  s   
z_SessionShim.onConnectc                 C   sL   z| j |j }W n ty   td|jtt| j  w || |S )NzBReceived challenge for unknown authmethod '{}' [authenticators={}])	r  r@  r^  rk   r   rz   sortedr  on_challenge)rV   rf  authenticatorr5   r5   r6   rB  [  s   z_SessionShim.onChallengec                 C   sf   |j d u s
| jd u rd S z| j|j  }W n ty+   td|j tt| j w || |j	S )NzBReceived onWelcome for unknown authmethod '{}' [authenticators={}])
re   r  r^  rk   r   rz   r  r  
on_welcomerg   )rV   r   r  r5   r5   r6   r?  g  s   z_SessionShim.onWelcomec                 C   r  r0   )on_leavery  r5   r5   r6   r  v  r  z_SessionShim.onLeavec                 C   s   |   S r0   )on_disconnectrU   r5   r5   r6   rv  y  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 r5   )r  r   ar   r5   r6   r     s
    
zG_SessionShim.add_authenticator.<locals>.at_most_one.<locals>.<listcomp>r(  zInconsistent {}s: {} )setrw   r  r  rV  
ValueErrorr   r9   )r   unir  rV   r  r6   at_most_one  s   z3_SessionShim.add_authenticator.<locals>.at_most_onerc   rd   z4Inconsistent authextra values for '{}': '{}' vs '{}')	rx   r   r  rg   r  r   r  r   r   )rV   r  r  rg   mergedr  vr5   r  r6   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   r   r5   )rg   r  r5   r5   r6   r     r   z2_SessionShim._merged_authextra.<locals>.<listcomp>c                 S   s   | t | B S r0   )r  r  )r  yr5   r5   r6   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  rg   )
authextrasr5   r6   first_value_for  s   z7_SessionShim._merged_authextra.<locals>.first_value_forc                    s   i | ]}| |qS r5   r5   )r   r  )r  r5   r6   
<dictcomp>  s    z2_SessionShim._merged_authextra.<locals>.<dictcomp>)r  r  r	   r  )rV   r  unique_keysr5   )r  r  r6   r    s   
z_SessionShim._merged_authextrac                 C      d S r0   r5   ry  r5   r5   r6   r    r  z_SessionShim.on_joinc                 C   s   |    d S r0   )r=   ry  r5   r5   r6   r    r  z_SessionShim.on_leavec                 C   s   |  | jj d S r0   )r9   r   r`   rU   r5   r5   r6   r    s   z_SessionShim.on_connectc                 C   r  r0   r5   rU   r5   r5   r6   r    r  z_SessionShim.on_disconnect)r   r   r   r   r  r   r   rB  r?  r  rv  r  r  r  r  r  r  r5   r5   r5   r6   r  4  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   r5   r5   r6   rW     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)rV   r   r5   r5   r6   __call__  s   z"ApplicationSessionFactory.__call__r0   )r   r   r   r   r   r   rW   r  r5   r5   r5   r6   r    s    
r  )Atypingr   r   r   r   r   r   r   r?   r1   	functoolsr	   autobahnr
   autobahn.utilr   r   r   autobahn.wampr   r   r   r   r   autobahn.wamp.exceptionr   r   r   r   autobahn.wamp.interfacesr   r   r   r   r   autobahn.wamp.typesr   r   r   r   r    r!   r"   autobahn.exceptionr#   autobahn.wamp.requestr$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r7   r8   r   r  abc_registerobjectr  r5   r5   r5   r6   <module>   sJ   $$8  (           Y 
.