a
    ø£BelM  ã                   @   s  d Z ddlZddlZddlZddlmZmZmZmZm	Z	m
Z
 edeƒZedeƒZzddlZW n eyz   ddlmZ Y n0 ddlmZ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 ddl m!Z! G dd„ de"ƒZ#eG dd„ dƒƒZ$G dd„ dƒZ%G dd„ deƒZ&dS )zA base class session manager.é    N)ÚAnyÚDictÚListÚNewTypeÚOptionalÚUnionÚ
KernelNameÚ	ModelName)Údbapi2)Ú	dataclassÚfields)Úensure_async)Úweb)ÚInstanceÚ
TraitErrorÚUnicodeÚvalidate)ÚLoggingConfigurable)ÚInstanceFromClassesc                   @   s   e Zd ZdZdS )ÚKernelSessionRecordConflictzgException class to use when two KernelSessionRecords cannot
    merge because of conflicting data.
    N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__© r   r   úr/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/jupyter_server/services/sessions/sessionmanager.pyr      s   r   c                   @   sR   e Zd ZU dZdZee ed< dZee ed< e	e
dœdd„Zd ddœdd	„ZdS )
ÚKernelSessionRecordzèA record object for tracking a Jupyter Server Kernel Session.

    Two records that share a session_id must also share a kernel_id, while
    kernels can have multiple session (and thereby) session_ids
    associated with them.
    NÚ
session_idÚ	kernel_id)ÚotherÚreturnc                 C   s€   t |tƒr|| jo| j|jk}t| j|jk| jdu p:|jdu gƒ}t||gƒrPdS t| j| j|jk| j|jkgƒr|d}t|ƒ‚dS )z Whether a record equals another.NTzåA single session_id can only have one kernel_id associated with. These two KernelSessionRecords share the same session_id but have different kernel_ids. This should not be possible and is likely an issue with the session records.F)Ú
isinstancer   r   Úallr   Úanyr   )Úselfr   Z
condition1Z
condition2Úmsgr   r   r   Ú__eq__1   s&    

þÿ

ýÿÿzKernelSessionRecord.__eq__c                 C   sz   t |tƒsd}t|ƒ‚|jr:| jr:|j| jkr:d}t|ƒ‚t| ƒD ]2}t||jƒrBt||jƒrBt	| |jt||jƒƒ qBdS )zCUpdates in-place a kernel from other (only accepts positive updatesz3'other' must be an instance of KernelSessionRecord.zJCould not update the record from 'other' because the two records conflict.N)
r!   r   Ú	TypeErrorr   r   r   ÚhasattrÚnameÚgetattrÚsetattr)r$   r   r%   Úfieldr   r   r   ÚupdateQ   s    
zKernelSessionRecord.update)r   r   r   r   r   r   ÚstrÚ__annotations__r   ÚobjectÚboolr&   r-   r   r   r   r   r   %   s
   
 r   c                   @   sŒ   e Zd ZU dZee ed< edœdd„Zdd„ Ze	ee
f edœd	d
„Zdd„ Ze	ee
f edœdd„Zeddœdd„Zeddœdd„ZdS )ÚKernelSessionRecordLista.  An object for storing and managing a list of KernelSessionRecords.

    When adding a record to the list, the KernelSessionRecordList
    first checks if the record already exists in the list. If it does,
    the record will be updated with the new information; otherwise,
    it will be appended.
    Ú_records)Úrecordsc                 G   s   g | _ |D ]}|  |¡ q
dS ©zInitialize a record list.N)r3   r-   )r$   r4   Úrecordr   r   r   Ú__init__k   s    z KernelSessionRecordList.__init__c                 C   s
   t | jƒS )z+The string representation of a record list.)r.   r3   ©r$   r   r   r   Ú__str__q   s    zKernelSessionRecordList.__str__)r6   r    c                 C   sH   t |tƒr|| jv rdS t |tƒrD| jD ]}||j|jfv r( dS q(dS )z.Search for records by kernel_id and session_idTF)r!   r   r3   r.   r   r   )r$   r6   Úrr   r   r   Ú__contains__u   s    

z$KernelSessionRecordList.__contains__c                 C   s
   t | jƒS )zThe length of the record list.)Úlenr3   r8   r   r   r   Ú__len__€   s    zKernelSessionRecordList.__len__c                 C   sl   t |tƒr0| jD ]}||j|jfv r|  S qn&t |tƒrV| jD ]}||kr@|  S q@|› d�}t|ƒ‚dS )zsReturn a full KernelSessionRecord from a session_id, kernel_id, or
        incomplete KernelSessionRecord.
        z& not found in KernelSessionRecordList.N)r!   r.   r3   r   r   r   Ú
ValueError)r$   r6   r:   r%   r   r   r   Úget„   s    





zKernelSessionRecordList.getNc                 C   sD   z | j  |¡}| j |  |¡ W n ty>   | j  |¡ Y n0 dS )z9Update a record in-place or append it if not in the list.N)r3   Úindexr-   r>   Úappend)r$   r6   Úidxr   r   r   r-   “   s
    zKernelSessionRecordList.updatec                 C   s   || j v r| j  |¡ dS )zYRemove a record if its found in the list. If it's not found,
        do nothing.
        N)r3   Úremove)r$   r6   r   r   r   rC   ›   s    
zKernelSessionRecordList.remove)r   r   r   r   r   r   r/   r7   r9   r   r.   r1   r;   r=   r?   r-   rC   r   r   r   r   r2   `   s   
r2   c                	       sl  e Zd ZdZeddd�jdd�Zedƒdd	„ ƒZe	d
ƒZ
eddgƒZ‡ fdd„ZdZdZh d£Zedd„ ƒZedd„ ƒZdd„ Zdd„ Zdd„ Zedœdd„Zd7ee ee ee ee ee eeef dœdd „Zd8ee ee eeef d!œd"d#„Zeee ee ee ee ed$œd%d&„Z d9d'd(„Z!d)d*„ Z"d+d,„ Z#ee$d-œd.d/„Z%d:d1d2„Z&d3d4„ Z'd5d6„ Z(‡  Z)S );ÚSessionManagerzA session manager.ú:memory:zíThe filesystem path to SQLite Database file (e.g. /path/to/session_database.db). By default, the session database is stored in-memory (i.e. `:memory:` setting from sqlite3) and does not persist when the current Jupyter Server shuts down.)Údefault_valueÚhelpT)ÚconfigÚdatabase_filepathc                 C   s�   |d }|dkr|S t  |¡}| ¡ rŒ| ¡ r:d}t|ƒ‚t|dƒ�}| d¡}W d  ƒ n1 sd0    Y  | d¡sŒ|dkrŒd	}t|ƒ‚|S )
zValidate a database file path.ÚvaluerE   zL`database_filepath` expected a file path, but the given path is a directory.Úrbéd   Ns   SQLite format 3ó    z.The given file is not an SQLite database file.)ÚpathlibÚPathÚexistsÚis_dirr   ÚopenÚreadÚ
startswith)r$   ZproposalrJ   Úpathr%   ÚfÚheaderr   r   r   Ú_validate_database_filepath°   s    
(z*SessionManager._validate_database_filepathzBjupyter_server.services.kernels.kernelmanager.MappingKernelManagerz8jupyter_server.services.contents.manager.ContentsManagerz2notebook.services.contents.manager.ContentsManagerc                    s   t ƒ j|i |¤Ž tƒ | _dS r5   )Úsuperr7   r2   Ú_pending_sessions)r$   ÚargsÚkwargs©Ú	__class__r   r   r7   Í   s    zSessionManager.__init__N>   rU   Útyper   r)   r   c                 C   s(   | j du r"| j ¡ | _ | j  d¡ | j S )z5Start a cursor and create a database called 'session'Nz\CREATE TABLE IF NOT EXISTS session
                (session_id, path, name, type, kernel_id))Ú_cursorÚ
connectionÚcursorÚexecuter8   r   r   r   rb   ×   s    
ÿzSessionManager.cursorc                 C   s,   | j du r&tj| jdd�| _ tj| j _| j S )zStart a database connectionN)Zisolation_level)Ú_connectionÚsqlite3ÚconnectrI   ÚRowZrow_factoryr8   r   r   r   ra   â   s    

zSessionManager.connectionc                 C   s   | j dur| j  ¡  d| _ dS )zClose the sqlite connectionN)r`   Úcloser8   r   r   r   rh   ë   s    

zSessionManager.closec                 C   s   |   ¡  dS )z+Close connection once SessionManager closesN)rh   r8   r   r   r   Ú__del__ñ   s    zSessionManager.__del__c                 Ã   sJ   d}| j  d|f¡ | j  ¡ }|durF| j|dd�I dH }|durFd}|S )z2Check to see if the session of a given name existsFz"SELECT * FROM session WHERE path=?NT)Útolerate_culled)rb   rc   ÚfetchoneÚrow_to_model)r$   rU   rP   ÚrowÚmodelr   r   r   Úsession_existsõ   s    
zSessionManager.session_exists)r    c                 C   s   t t ¡ ƒS )zCreate a uuid for a new session)r.   ÚuuidÚuuid4r8   r   r   r   Únew_session_id  s    zSessionManager.new_session_id)rU   r)   r_   Úkernel_namer   r    c           	      Ã   s†   |   ¡ }t|d�}| j |¡ |dur2|| jv r2n|  |||||¡I dH }||_| j |¡ | j|||||d�I dH }| j |¡ |S )zÖCreates a session and returns its model

        Parameters
        ----------
        name: ModelName(str)
            Usually the model name, like the filename associated with current
            kernel.
        ©r   N)rU   r)   r_   r   )	rr   r   rZ   r-   Úkernel_managerÚstart_kernel_for_sessionr   Úsave_sessionrC   )	r$   rU   r)   r_   rs   r   r   r6   Úresultr   r   r   Úcreate_session	  s    

ÿ

ÿzSessionManager.create_session)rU   r)   r    c                 C   sB   |dur"| j  |¡}tj ||¡}t|tƒs0J ‚i tj¥d|i¥S )a[  Return the environment variables that need to be set in the kernel

        Parameters
        ----------
        path : str
            the url path for the given session.
        name: ModelName(str), optional
            Here the name is likely to be the name of the associated file
            with the current kernel at startup time.
        NZJPY_SESSION_NAME)ru   Zcwd_for_pathÚosrU   Újoinr!   r.   Úenviron)r$   rU   r)   Úcwdr   r   r   Úget_kernel_env*  s
    zSessionManager.get_kernel_env)r   rU   r)   r_   rs   r    c           	      Ã   s@   t | jj|d�ƒI dH }|  ||¡}| jj|||d�I dH }|S )aQ  Start a new kernel for a given session.

        Parameters
        ----------
        session_id : str
            uuid for the session; this method must be given a session_id
        path : str
            the path for the given session - seem to be a session id sometime.
        name : str
            Usually the model name, like the filename associated with current
            kernel.
        type : str
            the type of the session
        kernel_name : str
            the name of the kernel specification to use.  The default kernel name will be used if not provided.
        )rU   N)rU   rs   Úenv)r   Úcontents_managerZget_kernel_pathr~   ru   Zstart_kernel)	r$   r   rU   r)   r_   rs   Zkernel_pathZ
kernel_envr   r   r   r   rv   =  s    ýz'SessionManager.start_kernel_for_sessionc                 Ã   s.   | j  d|||||f¡ | j|d�I dH }|S )aã  Saves the items for the session with the given session_id

        Given a session_id (and any other of the arguments), this method
        creates a row in the sqlite session database that holds the information
        for a session.

        Parameters
        ----------
        session_id : str
            uuid for the session; this method must be given a session_id
        path : str
            the path for the given session
        name : str
            the name of the session
        type : str
            the type of the session
        kernel_id : str
            a uuid for the kernel associated with this session

        Returns
        -------
        model : dict
            a dictionary of the session model
        z&INSERT INTO session VALUES (?,?,?,?,?)rt   N)rb   rc   Úget_session)r$   r   rU   r)   r_   r   rx   r   r   r   rw   `  s    þzSessionManager.save_sessionc              
   Ë   s0  |sd}t |ƒ‚g }|D ].}|| jvr8d|› �}t |ƒ‚| d| ¡ qdd |¡ }| j |t| ¡ ƒ¡ z| j ¡ }W n t	y�   d}Y n0 |du rÚg }| 
¡ D ]\}}	| |› d|	›�¡ q¦t dd	d
 |¡ ¡‚z|  |¡I dH }
W n< t	�y* } z"t dd	t|ƒ ¡|‚W Y d}~n
d}~0 0 |
S )a:  Returns the model for a particular session.

        Takes a keyword argument and searches for the value in the session
        database, then returns the rest of the session's info.

        Parameters
        ----------
        **kwargs : dict
            must be given one of the keywords and values from the session database
            (i.e. session_id, path, name, type, kernel_id)

        Returns
        -------
        model : dict
            returns a dictionary that includes all the information from the
            session described by the kwarg.
        zmust specify a column to queryzNo such column: ú%s=?zSELECT * FROM session WHERE %sz AND Nú=i”  zSession not found: %sú, )r'   Ú_columnsrA   r{   rb   rc   ÚlistÚvaluesrk   ÚKeyErrorÚitemsr   Ú	HTTPErrorrl   r.   )r$   r\   r%   Z
conditionsÚcolumnÚqueryrm   ÚqÚkeyrJ   rn   Úer   r   r   r�   €  s2    


,zSessionManager.get_sessionc                 Ë   s|   | j |d�I dH  |sdS g }|D ](}|| jvr<td| ƒ‚| d| ¡ q"dd |¡ }| j |g t| ¡ ƒ¢|‘¡ dS )aõ  Updates the values in the session database.

        Changes the values of the session with the given session_id
        with the values from the keyword arguments.

        Parameters
        ----------
        session_id : str
            a uuid that identifies a session in the sqlite3 database
        **kwargs : str
            the key must correspond to a column title in session database,
            and the value replaces the current value in the session
            with session_id.
        rt   NzNo such column: %rr‚   z(UPDATE session SET %s WHERE session_id=?r„   )	r�   r…   r'   rA   r{   rb   rc   r†   r‡   )r$   r   r\   Zsetsr‹   rŒ   r   r   r   Úupdate_session³  s    
zSessionManager.update_session)r   r    c                 Ã   s
   || j vS )zQChecks if the kernel is still considered alive and returns true if its not found.)ru   )r$   r   r   r   r   Úkernel_culledÐ  s    zSessionManager.kernel_culledFc                 Ã   sÈ   t |  |d ¡ƒI dH }|rh| j d|d f¡ dj|d |d d�}|r`| j |› d�¡ dS t|ƒ‚t | j 	|d ¡ƒI dH }|d |d |d	 |d
 |dœ}|d
 dkrÄ|d |d	 dœ|d< |S )z@Takes sqlite database session row and turns it into a dictionaryr   Nú&DELETE FROM session WHERE session_id=?r   z‰Kernel '{kernel_id}' appears to have been culled or died unexpectedly, invalidating session '{session_id}'. The session has been removed.)r   r   z  Continuing...rU   r)   r_   )ÚidrU   r)   r_   ÚkernelÚnotebook)rU   r)   )
r   r‘   rb   rc   ÚformatÚlogÚwarningrˆ   ru   Úkernel_model)r$   rm   rj   r‘   r%   r™   rn   r   r   r   rl   Ô  s*    þÿûzSessionManager.row_to_modelc              	   Ã   sT   | j  d¡}g }| ¡ D ]6}z|  |¡I dH }| |¡ W q tyL   Y q0 q|S )z_Returns a list of dictionaries containing all the information from
        the session databasezSELECT * FROM sessionN)rb   rc   Zfetchallrl   rA   rˆ   )r$   Úcrx   rm   rn   r   r   r   Úlist_sessionsø  s    zSessionManager.list_sessionsc                 Ã   sf   t |d�}| j |¡ | j|d�I dH }t| j |d d ¡ƒI dH  | j d|f¡ | j 	|¡ dS )z=Deletes the row in the session database with given session_idrt   Nr”   r“   r’   )
r   rZ   r-   r�   r   ru   Zshutdown_kernelrb   rc   rC   )r$   r   r6   Úsessionr   r   r   Údelete_session  s    
zSessionManager.delete_session)NNNNN)N)NNNN)F)*r   r   r   r   r   ÚtagrI   r   rX   r   ru   r   r€   r7   r`   rd   r…   Úpropertyrb   ra   rh   ri   ro   r.   rr   r   r	   r   r   r   ry   r~   rv   rw   r�   r�   r1   r‘   rl   r›   r�   Ú__classcell__r   r   r]   r   rD   £   sv   ýø

þÿ


     ú
ù" ÿ
þù#
 3
$rD   )'r   rz   rN   rp   Útypingr   r   r   r   r   r   r.   r   r	   re   ÚImportErrorZ	pysqlite2r
   Údataclassesr   r   Zjupyter_core.utilsr   Útornador   Z	traitletsr   r   r   r   Ztraitlets.config.configurabler   Zjupyter_server.traittypesr   Ú	Exceptionr   r   r2   rD   r   r   r   r   Ú<module>   s*    

:C