
    MhN                     p   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	  ede
          Z ede
          Z	 ddlZn# e$ r	 ddlmZ Y nw xY w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e!          Z"e G d d                      Z# G d d          Z$ G d de          Z%dS )zA base class session manager.    N)AnyNewTypeOptionalUnioncast
KernelName	ModelName)dbapi2)	dataclassfields)ensure_async)web)Instance
TraitErrorUnicodevalidate)LoggingConfigurable)InstanceFromClassesc                       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__     o/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/jupyter_server/services/sessions/sessionmanager.pyr   r      s           r   r   c                   `    e Zd ZU dZdZee         ed<   dZee         ed<   de	de
fdZd	dZdS )
KernelSessionRecordzA 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                 j   t          |t                    r| j        o| j        |j        k    }t          | j        |j        k    | j        du p|j        du g          }t          ||g          rdS t          | j        | j        |j        k    | j        |j        k    g          rd}t          |          dS )z Whether a record equals another.NTzA 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"   
condition1
condition2msgs        r   __eq__zKernelSessionRecord.__eq__/   s    e011 	7MDNeo,MJOu'77Nd*Eeo.E J J
+,, t OOu'77Neo5  7  2#666ur   c           	      z   t          |t                    sd}t          |          |j        r(| j        r!|j        | j        k    rd}t	          |          t          |           D ]U}t          ||j                  r>t          ||j                  r)t          | |j        t          ||j                             Vd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+   fields       r   updatezKernelSessionRecord.updateO   s    %!455 	!GCC.. ? 	3t~ 	3%/T^2S2S^C-c222D\\ 	F 	FEuej)) FgeUZ.H.H Fej'%*D*DEEE	F 	Fr   )r"   r   r#   N)r   r   r   r   r    r   str__annotations__r!   objectboolr,   r4   r   r   r   r   r   #   s           !%J$$$#Ix}###F t    @F F F F F Fr   r   c                       e Zd ZU dZee         ed<   defdZd Zde	ee
f         defdZd	 Zde	ee
f         defd
ZdeddfdZdeddf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                 H    g | _         |D ]}|                     |           dS zInitialize a record list.N)r;   r4   )r(   r<   records      r   __init__z KernelSessionRecordList.__init__i   s7     	  	 FKK	  	 r   c                 *    t          | j                  S )z+The string representation of a record list.)r5   r;   r(   s    r   __str__zKernelSessionRecordList.__str__o       4=!!!r   r?   r#   c                     t          |t                    r|| j        v rdS t          |t                    r| j        D ]}||j        |j        fv r dS dS )z.Search for records by kernel_id and session_idTF)r%   r   r;   r5   r    r!   )r(   r?   rs      r   __contains__z$KernelSessionRecordList.__contains__s   sn    f122 	v7N7N4fc"" 	 ]    alAK88844 9ur   c                 *    t          | j                  S )zThe length of the record list.)lenr;   rB   s    r   __len__zKernelSessionRecordList.__len__~   rD   r   c                     t          |t                    r| j        D ]}||j        |j        fv r|c S n)t          |t
                    r| j        D ]}||k    r|c S | d}t          |          )zsReturn a full KernelSessionRecord from a session_id, kernel_id, or
        incomplete KernelSessionRecord.
        z& not found in KernelSessionRecordList.)r%   r5   r;   r!   r    r   
ValueError)r(   r?   rF   r+   s       r   getzKernelSessionRecordList.get   s     fc"" 	"]  ak1<888HHH 9  344 	"] " "Q;;!MMM ???oor   Nc                     	 | j                             |          }| j         |                             |           dS # t          $ r | j                             |           Y dS w xY w)z9Update a record in-place or append it if not in the list.N)r;   indexr4   rL   append)r(   r?   idxs      r   r4   zKernelSessionRecordList.update   sw    	)-%%f--CM#%%f----- 	) 	) 	)M  ((((((	)s   :> $A&%A&c                 P    || j         v r| j                             |           dS dS )zYRemove a record if its found in the list. If it's not found,
        do nothing.
        N)r;   remove)r(   r?   s     r   rS   zKernelSessionRecordList.remove   s5     T]""M  ((((( #"r   )r   r   r   r   listr   r6   r@   rC   r   r5   r8   rG   rJ   rM   r4   rS   r   r   r   r:   r:   ^   s          &'''' !4        " " "	5)<c)A#B 	t 	 	 	 	" " "% 3S 89 >Q    )0 )T ) ) ) ))0 )T ) ) ) ) ) )r   r:   c                   V    e Zd ZdZ edd                              d          Z ed          d             Z e	d	          Z
 ed
dg          Z fdZdZdZh dZed             Zed             Zd Zd Zd ZdefdZ	 	 	 	 	 d'dee         dee         dee         dee         dee         deeef         fdZ	 d(dee         dee         deeef         fdZdedee         dee         dee         dee         defdZ d)dZ!d  Z"d! Z#dede$fd"Z%d*d$Z&d% Z'd& Z( xZ)S )+SessionManagerzA session manager.:memory:zThe 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                    |d         }|dk    r|S t          j        |          }|                                r|                                rd}t	          |          t          |d          5 }|                    d          }ddd           n# 1 swxY w Y   |                    d          s|dk    rd	}t	          |          |S )
zValidate a database file path.valuerW   zL`database_filepath` expected a file path, but the given path is a directory.rbd   Ns   SQLite format 3r   z.The given file is not an SQLite database file.)pathlibPathexistsis_dirr   openread
startswith)r(   proposalr]   pathr+   fheaders          r   _validate_database_filepathz*SessionManager._validate_database_filepath   s    !JL|E"";;== 	&{{}} &d oo%eT"" %a% % % % % % % % % % % % % % % $$%788 &Vs]]F oo%s   .BBBzBjupyter_server.services.kernels.kernelmanager.MappingKernelManagerz8jupyter_server.services.contents.manager.ContentsManagerz2notebook.services.contents.manager.ContentsManagerc                 `     t                      j        |i | t                      | _        dS r>   )superr@   r:   _pending_sessions)r(   argskwargs	__class__s      r   r@   zSessionManager.__init__   s3    $)&)))!8!:!:r   N>   r0   rh   typer!   r    c                     | j         8| 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executerB   s    r   rv   zSessionManager.cursor   sJ     <?1133DLL  =   |r   c                     | j         6t          j        | j        d          | _         t          j        | j         _        | j         S )zStart a database connectionN)isolation_level)_connectionsqlite3connectr[   Rowrow_factoryrB   s    r   ru   zSessionManager.connection   s>     #&t/EW[\\\D+2;D(r   c                 X    | j         "| j                                          d| _         dS dS )zClose the sqlite connectionN)rt   closerB   s    r   r   zSessionManager.close   s1    <#L   DLLL $#r   c                 .    |                                   dS )z+Close connection once SessionManager closesN)r   rB   s    r   __del__zSessionManager.__del__   s    

r   c                    K   d}| j                             d|f           | j                                         }|!|                     |d           d{V }|d}|S )z2Check to see if the session of a given name existsFz"SELECT * FROM session WHERE path=?NT)tolerate_culled)rv   rw   fetchonerow_to_model)r(   rh   rb   rowmodels        r   session_existszSessionManager.session_exists   sz      @4'JJJk""$$? ++C+FFFFFFFFE r   r#   c                 B    t          t          j                              S )zCreate a uuid for a new session)r5   uuiduuid4rB   s    r   new_session_idzSessionManager.new_session_id  s    4:<<   r   rh   r0   rr   kernel_namer!   c                   K   |                                  }t          |          }| j                            |           |
|| j        v rn|                     |||||           d{V }||_        | j                            |           |                     |||||           d{V }| j                            |           t          t          t          t          f         |          S )zCreates a session and returns its model

        Parameters
        ----------
        name: ModelName(str)
            Usually the model name, like the filename associated with current
            kernel.
        r    N)rh   r0   rr   r!   )r   r   rn   r4   kernel_managerstart_kernel_for_sessionr!   save_sessionrS   r   dictr5   r   )	r(   rh   r0   rr   r   r!   r    r?   results	            r   create_sessionzSessionManager.create_session  s)       ((**
$
;;;%%f--- Y$2E%E%E";;D$k       I %%%f---((T49 ) 
 
 
 
 
 
 
 
 	%%f---DcNF+++r   c                     |:| j                             |          }t          j                            ||          }t          |t                    sJ 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.
        NJPY_SESSION_NAME)r   cwd_for_pathosrh   joinr%   r5   environ)r(   rh   r0   cwds       r   get_kernel_envzSessionManager.get_kernel_env(  sc     %22488C7<<T**D$$$$$$7"*70$777r   r    c                    K   t          | j                            |                     d{V }|                     ||          }| j                            |||           d{V }t          t          |          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.
        )rh   N)rh   r   env)r   contents_managerget_kernel_pathr   r   start_kernelr   r5   )	r(   r    rh   r0   rr   r   kernel_path
kernel_envr!   s	            r   r   z'SessionManager.start_kernel_for_session;  s      2 ))>)N)NTX)N)Y)YZZZZZZZZ((t44
-::# ; 
 
 
 
 
 
 
 
	
 C###r   c                    K   | j                             d|||||f           |                     |           d{V }|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 (?,?,?,?,?)r   N)rv   rw   get_session)r(   r    rh   r0   rr   r!   r   s          r   r   zSessionManager.save_session^  sb      2 	4tT95	
 	
 	
 '':'>>>>>>>>r   c                   K   |sd}t          |          g }|D ]7}|| j        vrd| }t          |          |                    d|z             8dd                    |          z  }| j                            |t          |                                                     	 | j                                        }n# t          $ r d}Y nw xY w|ag }|
                                D ]\  }}	|                    | d|	            t          j        dd	d
                    |          z            	 |                     |           d{V }
n8# t          $ r+}t          j        dd	t          |          z            |d}~ww xY w|
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.   _columnsrP   r   rv   rw   rT   valuesr   KeyErroritemsr   	HTTPErrorr   r5   )r(   rp   r+   
conditionscolumnqueryr   qkeyr]   r   es               r   r   zSessionManager.get_session~  s     $  	!2CC.. 
 	/ 	/FT]**111nn$fvo....0GLL4L4LME4#8#8999	+&&((CC 	 	 	CCC	 ;A$llnn - -
UC++%++,,,,-%<		!%MNNN	N++C00000000EE 	N 	N 	N-%<s1vv%EFFAM	Ns*   %B? ?CC5E 
F&FFc                 j  K   |                      |           d{V  |sdS g }|D ]5}|| j        vrt          d|z            |                    d|z             6dd                    |          z  }| j                            |g t          |                                          |           t          | j
        d          rk| j                            d|g           | j                                        \  }}}| j
                            ||                     ||          	           dS 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.
        r   NzNo such column: %rr   z(UPDATE session SET %s WHERE session_id=?r   
update_envz<SELECT path, name, kernel_id FROM session WHERE session_id=?)r!   r   )r   r   r.   rP   r   rv   rw   rT   r   r/   r   r   r   r   )	r(   r    rp   setsr   r   rh   r0   r!   s	            r   update_sessionzSessionManager.update_session  sh      *555555555 	F 	) 	)FT]** 4v =>>>KK((((:diiooNE#GT&--//%:%:#GJ#GHHH4&55 	eKNQ[P\   %)K$8$8$:$:!D$	**YDDWDWX\^bDcDc*ddddd	e 	er   c                    K   || j         vS )zQChecks if the kernel is still considered alive and returns true if its not found.)r   )r(   r!   s     r   kernel_culledzSessionManager.kernel_culled  s       333r   Fc                 :  K   t          |                     |d                              d{V }|ru| j                            d|d         f           d                    |d         |d                   }|r| j                            | d           dS t          |          t          | j        	                    |d                              d{V }|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    zKernel '{kernel_id}' appears to have been culled or died unexpectedly, invalidating session '{session_id}'. The session has been removed.)r!   r    z  Continuing...rh   r0   rr   )idrh   r0   rr   kernelnotebook)rh   r0   )
r   r   rv   rw   formatlogwarningr   r   kernel_model)r(   r   r   r   r+   r   r   s          r   r   zSessionManager.row_to_model  sa     $01C1CCDT1U1U$V$VVVVVVV 	  K H3|K\J^___UU[U[!+.3|;L V\ V V     C!8!8!8999t3--)$*=*J*J3{K[*\*\]]]]]]]]l#KKK"
 
 v;*$$),Vc&k J JE*r   c                    K   | j                             d          }g }|                                D ]C}	 |                     |           d{V }|                    |           4# t
          $ r Y @w xY w|S )z_Returns a list of dictionaries containing all the information from
        the session databasezSELECT * FROM sessionN)rv   rw   fetchallr   rP   r   )r(   cr   r   r   s        r   list_sessionszSessionManager.list_sessions  s       K 788 ::<< 	 	C"//44444444e$$$$   s   0A''
A43A4c                 t  K   t          |          }| j                            |           |                     |           d{V }t	          | j                            |d         d                              d{V  | j                            d|f           | j        	                    |           dS )z=Deletes the row in the session database with given session_idr   Nr   r   r   )
r   rn   r4   r   r   r   shutdown_kernelrv   rw   rS   )r(   r    r?   sessions       r   delete_sessionzSessionManager.delete_session  s      $
;;;%%f---((J(????????4.>>wx?PQU?VWWXXXXXXXXXDzmTTT%%f-----r   )NNNNN)N)NNNN)F)*r   r   r   r   r   tagr[   r   rk   r   r   r   r   r@   rt   rz   r   propertyrv   ru   r   r   r   r5   r   r   r	   r   r   r   r   r   r   r   r   r   r8   r   r   r   r   __classcell__)rq   s   @r   rV   rV      s        O   
cc  X!""  #"( XbccN**F@	
 ; ; ; ; ; GKBBBH  X     X           ! ! ! ! ! #$(",0#', ,sm, y!, sm	,
 j), C=, 
c3h, , , ,D @D8 8SM8)1))<8	c3h8 8 8 8&!$!$ sm!$ y!	!$
 sm!$ j)!$ 
!$ !$ !$ !$F   @1 1 1f"e "e "eH4S 4T 4 4 4 4" " " "H  . . . . . . .r   rV   )&r   r   r`   r   typingr   r   r   r   r   r5   r   r	   r{   ImportError	pysqlite2r
   dataclassesr   r   jupyter_core.utilsr   tornador   	traitletsr   r   r   r   traitlets.config.configurabler   jupyter_server.traittypesr   	Exceptionr   r   r:   rV   r   r   r   <module>r      s   # # 
			   6 6 6 6 6 6 6 6 6 6 6 6 6 6W\3''
GK%%	,NNNN , , ,++++++++, * ) ) ) ) ) ) ) + + + + + +       = = = = = = = = = = = = = = = = = = 9 9 9 9 9 9    )    7F 7F 7F 7F 7F 7F 7F 7Ft@) @) @) @) @) @) @) @)Fr. r. r. r. r.( r. r. r. r. r.s   ; A	A	