
    yj                     L   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
 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 d dlmZmZ  ee          ZdZ e             dZdedededefdZ  eeej!        j"         d e            e           ej#        eej!        j$         de          dedededede%eef         dz  f
d                        Z&dddedededede'dej(        fdZ)dddedededede'dej(        fdZ*dedededed e%eef         ddfd!Z+dS )"    )	getLogger)Any)NOT_NONE)selectupdate)IntegrityError)AsyncSession)make_transient_to_detached)models)cacheget_cache_namespacesafe_cache_deletesafe_cache_set)settings)ConflictExceptionResourceNotFoundExceptionz>v2:workspace:{workspace_name}:collection:{observer}:{observed}z:lock:v2workspace_nameobserverobservedreturnc                 `    t                      dz   t                              | ||          z   S )z"Generate cache key for collection.:r   r   r   )r   COLLECTION_CACHE_KEY_TEMPLATEformatr   s      ;/DATA/AppData/hermes/projects/honcho/src/crud/collection.pycollection_cache_keyr      s@     	
	
'
.
.) / 
 
	
    s)keyttlprefix	condition)r    r!   r"   dbNc                   K   |                      t          t          j                                      t          j        j        |k                                  t          j        j        |k                                  t          j        j        |k                         d{V }|dS |j        |j        |j        |j        |j	        |j
        |j        dS )zQFetch a collection from the database and return as a plain dict for safe caching.Nidr   r   r   
h_metadatainternal_metadata
created_at)scalarr   r   
Collectionwherer   r   r   r'   r(   r)   r*   )r$   r   r   r   objs        r   _fetch_collectionr/   )   s      $ 		v !!	v />A	B	B	v )X5	6	6	v )X5	6	6	       C {tfLL,n 2n  r   F)with_for_updater0   c                p  K   |rt          t          j                                      t          j        j        |k                                  t          j        j        |k                                  t          j        j        |k                                              }|                     |           d{V }|t          d          |S t          | |||           d{V }|t          d          t          j        di |}t          |           |                     |d           d{V }|S )a  
    Get a collection by observer/observed for a workspace.

    Args:
        db: Database session
        workspace_name: Name of the workspace
        observer: Name of the observing peer (owns the collection)
        observed: Name of the observed peer
        with_for_update: If True, acquire a row-level lock (SELECT ... FOR UPDATE)
            on the collection. Bypasses the cache so the lock is actually held
            by the current transaction. Callers using this flag must wrap the
            read and subsequent write in the same transaction (the lock is
            released on commit/rollback).

    Returns:
        The collection if found

    Raises:
        ResourceNotFoundException: If the collection does not exist
    NzCollection not foundF)load )r   r   r,   r-   r   r   r   r0   r+   r   r/   r
   merge)	r$   r   r   r   r0   stmt
collectiondatar.   s	            r   get_collectionr8   N   s@     8  
 6$%%U6$3~EFFU6$-9::U6$-9::_ 	 99T??******
+,BCCC"2~xJJJJJJJJD|'(>???


#
#d
#
#Cs###xx%x00000000Jr   )_retryr9   c                p  K   	 t          | |||           d {V S # t          $ r 	 t          j        |||          }|                     |           |                                  d {V  t          |||          }t          ||j        |j	        |j
        |j        |j        |j        |j        dt          j        j                   d {V  |cY S # t$          $ rQ |                                  d {V  |rt)          d| d|           d t+          | |||d           d {V cY cY S w xY ww xY w)	N)r   r   r   r&   )expirez$Unable to create or get collection: /T)r   r   r9   )r8   r   r   r,   addcommitr   r   r'   r   r   r   r(   r)   r*   r   CACHEDEFAULT_TTL_SECONDSr   rollbackr   get_or_create_collection)r$   r   r   r   r9   honcho_collectionr    s          r   rB   rB      s     &#H
 
 
 
 
 
 
 
 
 	
 % " " "!	 & 1-!!! ! !
 FF$%%%))++&~xJJC +. 1 : 1 :&7&F"3">):)L"3">   ~9          %$$$ 	 	 	++-- 'P8PPhPP  2NXQU             	5"s.    D5B*CD5AD1,D50D11D5update_datac                   K   t          t          j                                      t          j        j        |k    t          j        j        |k    t          j        j        |k                                  t          j        j        	                    d          |                    }| 
                    |           d{V  |                                  d{V  t          t          |||                     d{V  dS )zTMerge a patch into a collection's internal_metadata (JSONB ||) and invalidate cache.z||)r)   N)r   r   r,   r-   r   r   r   valuesr)   opexecuter>   r   r   )r$   r   r   r   rD   r5   s         r   #update_collection_internal_metadatarI      s      	v !!	,>&(2&(2

 


 
$/ADDTJJ;WW 
 

 

 	 **T


))++
08TT
U
UUUUUUUUUUr   ),loggingr   typingr   cashewsr   
sqlalchemyr   r   sqlalchemy.excr   sqlalchemy.ext.asyncior	   sqlalchemy.ormr
   srcr   src.cache.clientr   r   r   r   
src.configr   src.exceptionsr   r   __name__loggerr   COLLECTION_LOCK_PREFIXstrr   r?   r@   lockedDEFAULT_LOCK_TTL_SECONDSdictr/   boolr,   r8   rB   rI   r3   r   r   <module>r]      s[                     % % % % % % % % ) ) ) ) ) ) / / / / / / 5 5 5 5 5 5                         G G G G G G G G	8		 E  0/11;;; 
 
 
s 
s 
 
 
 
 %>-000  	   %>2555!  
  	
 
#s(^d    @ "3 3 333 	3
 3 3 3 3 3 3x . . ... 	.
 . . . . . .bVVV V 	V
 c3hV 
V V V V V Vr   