
    yj1B              
          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mZ d dlmZ d dlmZ d dlmZ d d	lmZmZ d d
lmZmZmZmZ d dlmZ d dlmZm Z  d dl!m"Z" d dl#m$Z$ d dl%m&Z&  ee'          Z(e G d d                      Z)dZ* e             dZ+de,de,fdZ- ee*ej.        j/         d e            e           ej0        e*ej.        j1         de+          dede,de2e,ef         dz  fd                        Z3dddedej4        d e5de$ej6                 fd!Z7	 d(d"e2e,ef         dz  de	e8ej6                          fd#Z9dede,dej6        fd$Z:dede,dej;        dej6        fd%Z<dede,ddfd&Z=dede,de)fd'Z>dS ))    )	dataclass)	getLogger)Any)NOT_NONE)Selectdeleteexistsfuncselect)IntegrityError)AsyncSession)make_transient_to_detached)modelsschemas)cacheget_cache_namespacesafe_cache_deletesafe_cache_set)settings)ConflictExceptionResourceNotFoundException)apply_filter)GetOrCreateResult)get_external_vector_storec                   P    e Zd ZU dZej        ed<   eed<   eed<   eed<   eed<   dS )WorkspaceDeletionResultz8Result of a workspace deletion including cascade counts.	workspacepeers_deletedsessions_deletedmessages_deletedconclusions_deletedN)__name__
__module____qualname____doc__r   	Workspace__annotations__int     :/DATA/AppData/hermes/projects/honcho/src/crud/workspace.pyr   r      sW         BB    r*   r   zv2:workspace:{workspace_name}z:lock:v2workspace_namereturnc                 \    t                      dz   t                              |           z   S )z!Generate cache key for workspace.:r,   )r   WORKSPACE_CACHE_KEY_TEMPLATEformatr0   s    r+   workspace_cache_keyr3   *   s4     	
	
&
-
-^
-
L
L	Mr*   s)keyttlprefix	condition)r5   r6   r7   dbNc                   K   |                      t          t          j                                      t          j        j        |k                         d{V }|dS |j        |j        |j        |j        |j	        |j
        dS )zPFetch a workspace from the database and return as a plain dict for safe caching.Nidname
h_metadatainternal_metadataconfiguration
created_at)scalarr   r   r&   wherer=   r<   r>   r?   r@   rA   )r9   r,   objs      r+   _fetch_workspacerE   3   s       		v  &&v'7'<'NOO       C {tfn 2*n  r*   F_retryr   rG   c                  	K   |j         st          d          t          | |j                    d{V }|nt                              d|j                    t          j        di |}t          |           |                     |d           d{V }t          |d          S t          j        |j         |j
        |j                            d          	          }	 |                                 4 d{V  |                     |           ddd          d{V  n# 1 d{V swxY w Y   t                              d
|j                    t          |j                   	|j        |j         |j        |j        |j        |j        d	fd}t          |d|          S # t(          $ r5 |rt+          d|j                    dt-          | |d           d{V cY S w xY w)aO  
    Get an existing workspace or create a new one if it doesn't exist.

    Args:
        db: Database session
        workspace: Workspace creation schema

    Returns:
        GetOrCreateResult containing the workspace and whether it was created

    Raises:
        ConflictException: If we fail to get or create the workspace
    zWorkspace name must be providedNzFound existing workspace: %sFload)createdTexclude_none)r=   r>   r@   z"Workspace created successfully: %sr;   c                  Z   K   t           t          j        j                   d {V  d S )N)expire)r   r   CACHEDEFAULT_TTL_SECONDS)_cache_data
_cache_keys   r+   _warm_workspace_cachez6get_or_create_workspace.<locals>._warm_workspace_cache   sT       ~9           r*   )rK   	on_commitz#Unable to create or get workspace: rF   r)   )r=   
ValueErrorrE   loggerdebugr   r&   r   merger   metadatar@   
model_dumpbegin_nestedaddr3   r<   r>   r?   rA   r   r   get_or_create_workspace)
r9   r   rG   datarD   existing_workspacehoncho_workspacerT   rR   rS   s
           @@r+   r^   r^   Q   s     ( > <:;;; ""in55555555D3Y^DDD&&&&"3'''#%88Ce8#<#<<<<<<< !3UCCCC '^%-88d8KK  
I??$$ 	% 	% 	% 	% 	% 	% 	% 	%FF#$$$	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	%99>JJJ )88
"%$)*5!1!C-;*5
 
	 	 	 	 	 	 !d6K
 
 
 	
  I I I 	#FinFF  -R4HHHHHHHHHHHHIs7   !F' ;D#F' #
D--F' 0D-1A5F' '<G&%G&filtersc                    K   t          t          j                  }t          |t          j        |           }|                    t          j        j                  }|S )z
    Get all workspaces.

    Args:
        db: Database session
        filters: Filter the workspaces by a dictionary of metadata
    )r   r   r&   r   order_byrA   )rb   stmts     r+   get_all_workspacesrf      sH       &"##Df.88D,0MM&:J:U,V,VDKr*   c                    K   t          | |           d{V }|t          d| d          t          j        di |}t	          |           |                     |d           d{V }|S )a  
    Get an existing workspace.

    Args:
        db: Database session
        workspace_name: Name of the workspace

    Returns:
        The workspace if found or created

    Raises:
        ResourceNotFoundException: If the workspace does not exist
    Nz
Workspace z
 not foundFrI   r)   )rE   r   r   r&   r   rY   )r9   r,   r_   rD   r`   s        r+   get_workspacerh      s      " ""n55555555D|'(O^(O(O(OPPP 

"
"T
"
"Cs###!xx%x88888888r*   c                   K   t          | t          j        ||j        pi                      d{V }|j        }d}|j        |j        |j        k    r|j        |_        d}|j        N|j        pi                                 }i ||j                            d          }|j        |k    r	||_        d}|sQ| 	                                 d{V  |
                                 d{V  t                              d|           |S | 	                                 d{V  |
                                 d{V  t          |          }t          |           d{V  t                              d|j                   |S )a,  
    Get or create a workspace, then apply metadata and configuration updates.

    Provided metadata replaces the current metadata when present. Provided
    configuration keys are merged into the existing configuration instead of
    replacing it wholesale.

    Args:
        db: Database session
        workspace_name: Name of the workspace
        workspace: Workspace update schema

    Returns:
        The updated workspace

    Raises:
        ConflictException: If concurrent creation prevents fetching or creating
            the workspace
    )r=   rZ   NFTrL   z'Workspace %s unchanged, skipping updatez)Workspace with id %s updated successfully)r^   r   WorkspaceCreaterZ   resourcer>   r@   copyr[   commitpost_commitrW   rX   r3   r   r<   )	r9   r,   r   	ws_resultra   needs_updatebase_configmerged_config	cache_keys	            r+   update_workspacert      s      , .
'-2	
 	
 	
       I *3); L 	&'9+===&/&8#*'5;AACC

%00d0CC
 )]::-:*L   iikk##%%%%%%%%%>OOO
))++



!
!!!!!!!! $N33I
I
&
&&&&&&&&
LL<>N>QRRRr*   c                 *  K   t          |                     t          t                                          t
          j        j        |k    t
          j        j        dk                                   d{V           }|rt          d| d          dS )z
    Verify that a workspace has no active sessions.

    Args:
        db: Database session
        workspace_name: Name of the workspace

    Raises:
        ConflictException: If active sessions exist in the workspace
    TNzCannot delete workspace 'z7': active session(s) remain. Delete all sessions first.)
boolrB   r   r	   rC   r   Sessionr,   	is_activer   )r9   r,   has_active_sessionss      r+   check_no_active_sessionsrz     s       !%iiN1^CN,4  
 
 	
 	
 	
 	
 	
 	
	! 	!  
oooo
 
 	

 
r*   c           	         K   t                               d|           t          t          j                                      t          j        j        |k              }|                     |           d{V }|                                }|)t                               d|           t                      t          j        |j        |j        |j        |j                  }t          |                     t          t!          j        t          j        j                                                t          j        j        |k                         d{V pd          }t          |                     t          t!          j        t          j        j                                                t          j        j        |k                         d{V pd          }t          |                     t          t!          j        t          j        j                                                t          j        j        |k                         d{V pd          }t          |                     t          t!          j        t          j        j                                                t          j        j        |k                         d{V pd          }		 |                     t1          t          j                                      t!          j        t          j        j        dd          |k                         d{V  |                     t1          t          j                                      t          j        j        |k                         d{V  t          t          j        j                                      t          j        j        |k              }
|                     t1          t          j                                      t          j        j                            |
                               d{V  |                     t          t          j                                      t          j        j        |k                         d{V }|                                 !                                }|                     t1          t          j"                                      t          j"        j        |k                         d{V  |                     t1          t          j                                      t          j        j        |k                         d{V  |                     t1          t          j                                      t          j        j        |k                         d{V  |                     t1          t          j                                      t          j        j        |k                         d{V  |                     t1          t          j#                                      t          j#        j        |k                         d{V  |                     t1          t          j$                                      t          j$        j        |k                         d{V  |                     t1          t          j                                      t          j        j        |k                         d{V  |                     t1          t          j                                      t          j        j        |k                         d{V  |                     |           d{V  | %                                 d{V  tM                      }|r|'                    d|          }	 |(                    |           d{V  t           )                    d	||           n3# tT          $ r&}t                               d
||           Y d}~nd}~ww xY w|D ]}|'                    d||j+        |j,                  }	 |(                    |           d{V  t           )                    d||j+        |j,                   h# tT          $ r&}t                               d||           Y d}~d}~ww xY wt[          |          }| d}t]          j/        |           d{V  t           )                    d|           nD# tT          $ r7 t           0                    d|           | 1                                 d{V   w xY wte          |||||	          S )a  
    Delete a workspace.

    Args:
        db: Database session
        workspace_name: Name of the workspace

    Returns:
        WorkspaceDeletionResult containing a snapshot of the deleted workspace
        and cascade counts for deleted resources
    zDeleting workspace %sNzWorkspace %s not found)r=   r>   r@   rA   r   r/      messagez8Deleted message embeddings namespace %s for workspace %sz4Failed to delete message embeddings namespace %s: %sdocumentz2Deleted document namespace %s for collection %s/%sz*Failed to delete document namespace %s: %s*zWorkspace %s deletedzFailed to delete workspace %s)r   r   r   r    r!   )3rW   warningr   r   r&   rC   r=   executescalar_one_or_noner   r   r>   r@   rA   r(   rB   r
   countPeerr<   r,   rw   MessageDocumentr   ActiveQueueSession
split_partwork_unit_key	QueueItem
message_idin_
CollectionscalarsallMessageEmbeddingWebhookEndpointSessionPeerrm   r   get_vector_namespacedelete_namespacerX   	Exceptionobserverobservedr3   r   delete_match	exceptionrollbackr   )r9   r,   re   resultra   workspace_snapshotpeers_countsessions_countmessages_countconclusions_countmessage_ids_subquerycollections_resultcollectionsexternal_vector_storemessage_namespacee
collectiondoc_namespacers   workspace_patterns                       r+   delete_workspacer   *  s
      NN*N;;;&"##))&*:*?>*QRRD::d########F0022/@@@'))) !*"#.&4#.	   ii4:fkn--..44*n< 
 
 	
 	
 	
 	
 	
 	
 	
  K ii4:fn/001177-? 
 
 	
 	
 	
 	
 	
 	
 	
  N ii4:fn/001177-? 
 
 	
 	
 	
 	
 	
 	
 	
  N ii4:fo0112288..@ 
 
 	
 	
 	
 	
 	
 	
 	
  6Djj6,--33 9 GaPP!" 
 
 	
 	
 	
 	
 	
 	
 	
 jj6#$$** />A 
 
 	
 	
 	
 	
 	
 	
 	
  &fn&788>>N)^; 
  
 jj6#$$** +//0DEE 
 
 	
 	
 	
 	
 	
 	
 	
 $&::6$%%++!0NB $
 $
 
 
 
 
 
 

 )00226688jj6*++11'6.H 
 
 	
 	
 	
 	
 	
 	
 	

 jj6?##))..@ 
 
 	
 	
 	
 	
 	
 	
 	

 jj6$%%++!0NB 
 
 	
 	
 	
 	
 	
 	
 	

 jj6>""((-? 
 
 	
 	
 	
 	
 	
 	
 	
 jj6)**00&5G 
 
 	
 	
 	
 	
 	
 	
 	

 jj6%&&,,"1^C 
 
 	
 	
 	
 	
 	
 	
 	

 jj6>""((-? 
 
 	
 	
 	
 	
 	
 	
 	

 jj6;%%fk&@N&RSS
 
 	
 	
 	
 	
 	
 	
 	
 ii()))))))))iikk !: ; ; ! '	 5 J J>! !+<<=NOOOOOOOOON%"   
    J%        *  
 5 J J"''	! !/@@OOOOOOOOOLLL%"+"+	    !   NND%        (77	(OOO !2333333333+^<<<<   +	
 	
 	
 kkmm #$!''-   sd   T	d8 &7` d8 
a(a	d8 	a)d8 8Ab;:d8 ;
c+c&!d8 &c++Ad8 8Ae9)N)?dataclassesr   loggingr   typingr   cashewsr   
sqlalchemyr   r   r	   r
   r   sqlalchemy.excr   sqlalchemy.ext.asyncior   sqlalchemy.ormr   srcr   r   src.cache.clientr   r   r   r   
src.configr   src.exceptionsr   r   src.utils.filterr   src.utils.typesr   src.vector_storer   r"   rW   r   r1   WORKSPACE_LOCK_PREFIXstrr3   rP   rQ   lockedDEFAULT_LOCK_TTL_SECONDSdictrE   rj   rv   r&   r^   tuplerf   rh   WorkspaceUpdatert   rz   r   r)   r*   r+   <module>r      s(   ! ! ! ! ! !                   ; ; ; ; ; ; ; ; ; ; ; ; ; ; ) ) ) ) ) ) / / / / / / 5 5 5 5 5 5                           G G G G G G G G ) ) ) ) ) ) - - - - - - 6 6 6 6 6 6	8		          ? ..00:::       $>-000  	   $>2555   
&)	#s(^d    . 	GI GI GIGI&GI 	GI
 v'(GI GI GI GIV &* #s(^d"E&"#$        <CC&)C6=6MCC C C CL
| 
S 
T 
 
 
 
6dd&)dd d d d d dr*   