
    %`i`                     2   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	 d dl
mZmZmZmZmZ d dlZd dlmZ d dlmZ  e	dd          Z ej        e          Zded	ed
edefdZdedeeeef         fdZ G d de j                  Z G d de          Z G d de          Z  G d de          Z! e            a" G d de           Z# G d de           Z$d Z%d Z&d Z'dee         d ee         fd!Z(d"ee         fd#Z)dee         fd$Z*dS )%    N)
namedtuple)IOListOptionalTupleUnion)DEFAULT_OBJECT_PREFIX)	ObjectRef	ParsedURLzbase_url, offset, sizeurloffsetsizereturnc                     |  d| d| S )at  Methods to create a URL with offset.

    When ray spills objects, it fuses multiple objects
    into one file to optimize the performance. That says, each object
    needs to keep tracking of its own special url to store metadata.

    This method creates an url_with_offset, which is used internally
    by Ray.

    Created url_with_offset can be passed to the self._get_base_url method
    to parse the filename used to store files.

    Example) file://path/to/file?offset=""&size=""

    Args:
        url: url to the object stored in the external storage.
        offset: Offset from the beginning of the file to
            the first bytes of this object.
        size: Size of the object that is stored in the url.
            It is used to calculate the last offset.

    Returns:
        url_with_offset stored internally to find
        objects from external storage.
    z?offset=z&size= r   r   r   s      q/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/_private/external_storage.pycreate_url_with_offsetr      s     4 //6/////    url_with_offsetc                    t           j                            |           }t           j                            |j                  }|                                                    d          d         }d|vsd|vrt          d|            t          |d         d                   }t          |d         d                   }t          |||          S )a  Parse url_with_offset to retrieve information.

    base_url is the url where the object ref
    is stored in the external storage.

    Args:
        url_with_offset: url created by create_url_with_offset.

    Returns:
        named tuple of base_url, offset, and size.
    ?r   r   r   zFailed to parse URL: )base_urlr   r   )
urllibparseurlparseparse_qsquerygeturlsplit
ValueErrorintr   )r   parsed_result
query_dictr   r   r   s         r   parse_url_with_offsetr%   1   s     L))/::M&&}':;;J##%%++C003Hz!!V:%=%=BBBCCCH%a())Fz&!!$%%DhvDAAAAr   c                   T   e Zd ZdZdZdZd Zedd            Zd Z	d	 Z
d
edee         dee         dedee         f
dZd Zej        dee         fd            Zej        dee         dee         defd            Zej        dee         fd            Zej        d             ZdS )ExternalStoragea  The base class for external storage.

    This class provides some useful functions for zero-copy object
    put/get from plasma store. Also it specifies the interface for
    object spilling.

    When inheriting this class, please make sure to implement validation
    logic inside __init__ method. When ray instance starts, it will
    instantiating external storage to validate the config.

    Raises:
        ValueError: when given configuration for
            the external storage is invalid.
          c                     d | _         d S N)_core_workerselfs    r   __init__zExternalStorage.__init__[   s     AEr   r   ray._raylet.CoreWorkerc                 :   | j         t          j        j        j        }t          j                    }|j        sRt          j        d           t          j                    |z
  | j        k    rt          d| j         d          |j        R|j
        | _         | j         S )a*  Get the core_worker initialized in this process.

        In rare cases, the core worker may not be fully initialized by the time an I/O
        worker begins to execute an operation because there is no explicit flag set to
        indicate that the Python layer is ready to execute tasks.
        NgMbP?z4CoreWorker didn't initialize within grace period of zs.)r,   ray_privateworkerglobal_workertime	connectedsleepCORE_WORKER_INIT_GRACE_PERIOD_SRuntimeErrorcore_worker)r.   r4   starts      r   r;   zExternalStorage.core_worker`   s     $\(6FIKKE& 
5!!!9;;&)MMM&D?D D D   &  !' 2D  r   c                 6    | j                             |          S r+   )r;   get_if_local)r.   object_refss     r   _get_objects_from_storez'ExternalStorage._get_objects_from_storew   s    
 ,,[999r   c                 B    | j                             |||||           d S r+   )r;   put_file_like_object)r.   metadata	data_size	file_like
object_refowner_addresss         r   _put_object_to_storez$ExternalStorage._put_object_to_store~   s4     	--iJ	
 	
 	
 	
 	
r   fr?   owner_addressesr   c                 8   g }d}|                      |          }t          |||          D ]Y\  }\  }	}
}}t          |          }t          |
          }|	:t          |
          dk    r'd|                                 d}t	          |          |	dnt          |	          }|                    dd          |                    dd          z   |                    dd          z   |z   |
z   |rt          |	          ndz   }t          |          }| j        |z   |z   |z   |k    sJ |                    |          }||k    sJ t          |||	          }|
                    |                                           ||z  }[|                                 |S )
a  Fuse all given objects into a given file handle.

        Args:
            f: File handle to fusion all given object refs.
            object_refs: Object references to fusion to a single file.
            owner_addresses: Owner addresses for the provided objects.
            url: url where the object ref is stored
                in the external storage.

        Return:
            List of urls_with_offset of fused objects.
            The order of returned keys are equivalent to the one
            with given object_refs.
        r   NzObject z does not exist.   little	byteorderr   r   )r@   ziplenhexr!   to_bytes
memoryviewHEADER_LENGTHwriter   appendencodeflush)r.   rI   r?   rJ   r   keysr   ray_object_pairsrefbufrC   _rG   address_lenmetadata_lenerrorbuf_lenpayloadpayload_lenwritten_bytesr   s                        r   _write_multiple_objectsz'ExternalStorage._write_multiple_objects   s   " 77DD69)?7
 7
 	$ 	$2C##x] m,,Kx==L{s8}}11=#''))=== ''';aaCHHG$$Q($;;''X'>>?""1"99:    	
 '.6:c???38  g,,K"[0<?'I[XXXXGGG,,M K////4]  O KK..00111m#FF				r   c                 ^    ||z   |z   | j         z   }||k    rt          d| d| d          dS )a  Check whether or not the obtained_data_size is as expected.

        Args:
            address_len: Length of the address.
            metadata_len: Actual metadata length of the object.
            buffer_len: Actual buffer length of the object.
            obtained_data_size: Data size specified in the url_with_offset.

        Raises:
            ValueError: If obtained_data_size is different from
                address_len + metadata_len + buffer_len + 24 (first 8 bytes to store length).
        zObtained data has a size of z., although it is supposed to have the size of .N)rU   r!   )r.   r_   r`   
buffer_lenobtained_data_sizedata_size_in_bytess         r   _size_checkzExternalStorage._size_check   sj     ,&3d6HH 	 !3331/A 1 1-1 1 1   43r   c                     dS )aN  Spill objects to the external storage. Objects are specified
        by their object refs.

        Args:
            object_refs: The list of the refs of the objects to be spilled.
            owner_addresses: Owner addresses for the provided objects.
        Returns:
            A list of internal URLs with object offset.
        Nr   r.   r?   rJ   s      r   spill_objectszExternalStorage.spill_objects         r   url_with_offset_listc                     dS )a  Restore objects from the external storage.

        Args:
            object_refs: List of object IDs (note that it is not ref).
            url_with_offset_list: List of url_with_offset.

        Returns:
            The total number of bytes restored.
        Nr   r.   r?   rq   s      r   restore_spilled_objectsz'ExternalStorage.restore_spilled_objects   rp   r   urlsc                     dS )zDelete objects that are spilled to the external storage.

        Args:
            urls: URLs that store spilled object files.

        NOTE: This function should not fail if some of the urls
        do not exist.
        Nr   r.   ru   s     r   delete_spilled_objectsz&ExternalStorage.delete_spilled_objects   rp   r   c                     dS )zDestroy external storage when a head node is down.

        NOTE: This is currently working when the cluster is
        started by ray.init
        Nr   r-   s    r   destroy_external_storagez(ExternalStorage.destroy_external_storage   rp   r   N)r   r0   )__name__
__module____qualname____doc__rU   r9   r/   propertyr;   r@   rH   r   r   r
   strrf   rl   abcabstractmethodro   r"   rt   rx   rz   r   r   r   r'   r'   H   s         M&'#E E E
 ! ! ! X!,: : :
 
 
33"&y/3DHI3TW3	c3 3 3 3j  . 		T#Y 	 	 	 	 		?BFs)	    	49     	    r   r'   )	metaclassc                   N    e Zd ZdZdee         fdZd Zdee         fdZd Z	dS )	NullStoragez<The class that represents an uninitialized external storage.r   c                      t          d          Nz#External storage is not initializedNotImplementedErrorrn   s      r   ro   zNullStorage.spill_objects      !"GHHHr   c                      t          d          r   r   rs   s      r   rt   z#NullStorage.restore_spilled_objects  r   r   ru   c                      t          d          r   r   rw   s     r   rx   z"NullStorage.delete_spilled_objects  r   r   c                      t          d          r   r   r-   s    r   rz   z$NullStorage.destroy_external_storage  r   r   N)
r{   r|   r}   r~   r   r   ro   rt   rx   rz   r   r   r   r   r      s        FFIT#Y I I I II I II49 I I I II I I I Ir   r   c                        e Zd ZdZ	 ddedeeee         f         dee         f fdZ	dee         fdZ
d	ee         d
ee         fdZdee         fdZd Zd Z xZS )FileSystemStoragezThe class for filesystem-like external storage.

    Raises:
        ValueError: Raises directory path to
            spill objects doesn't exist.
    Nnode_iddirectory_pathbuffer_sizec                    t                                                       g | _        d| _        d| _        |
J d            t          |t                    r|g}t          |t                    s
J d            |&t          |t                    s
J d            || _        |D ]}t          j
                            |t           d|           }t          j        |d           t          j
                            |          st          d	| d
          | j                            |           t#          | j                  t#          |          k    sJ t%          j        dt#          | j                            | _        d S )Nr   z9directory_path should be provided to use object spilling.zBDirectory_path must be either a single string or a list of stringsbuffer_size must be an integer.r^   T)exist_okz+The given directory path to store objects, z, could not be created.)superr/   _directory_paths_current_directory_index_buffer_size
isinstancer   listr"   ospathjoinr	   makedirsexistsr!   rW   rQ   random	randrange)r.   r   r   r   r   full_dir_path	__class__s         r   r/   zFileSystemStorage.__init__  s    	 !#()% &&F '&&nc** 	.,-ND
 
 	P 	PO	P 	P 
 "k3//RR1RRR/ +D # 	8 	8DGLL2G/S/S'/S/STTMK55557>>-00  >$> > >   !((77774())S-@-@@@@@ )/(8C@U<V<V(W(W%%%r   r   c                    t          |          dk    rg S | j        dz   t          | j                  z  | _        | j        | j                 }t          |          }t          j                            ||           }t          |d| j                  5 }| 	                    ||||          cd d d            S # 1 swxY w Y   d S )Nr   r)   wb)	buffering)
rQ   r   r   _get_unique_spill_filenamer   r   r   openr   rf   )r.   r?   rJ   r   filenamer   rI   s          r   ro   zFileSystemStorage.spill_objectsC  s   {q  I)-)F)Jc!O
 O
 )
% .t/LM-k::nh779#tt'8999 	VQ//;QTUU	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	Vs   B88B<?B<r?   rq   c           	      (   d}t          t          |                    D ]q}||         }||                                         }t          |          }|j        }|j        }	t          |d          5 }
|
                    |	           t          	                    |

                    d          d          }t          	                    |

                    d          d          }t          	                    |

                    d          d          }|                     ||||j                   ||z  }|

                    |          }|

                    |          }|                     |||
||           d d d            n# 1 swxY w Y   s|S )Nr   rbrL   rM   rN   )rangerQ   decoder%   r   r   r   seekr"   
from_bytesreadrl   r   rH   )r.   r?   rq   totalirF   r   r#   r   r   rI   r_   r`   rb   rG   rC   s                   r   rt   z)FileSystemStorage.restore_spilled_objectsQ  s    s;''(( 	 	A$QJ215<<>>O1/BBM$-H")Fh%% v!nnQVVAYY(nKK"~~affQii8~LL..h.GG  lG]EWXXX  !{ 3 366,//))gq*m                 s   1DFF		F		ru   c                     |D ]M}t          |                                          j        }	 t          j        |           ># t
          $ r Y Jw xY wd S r+   )r%   r   r   r   removeFileNotFoundError)r.   ru   r   r   s       r   rx   z(FileSystemStorage.delete_spilled_objectsl  sg     	 	C(66?D	$$   		 	s   A
AAc                 D    | j         D ]}|                     |           d S r+   )r   _destroy_external_storager.   r   s     r   rz   z*FileSystemStorage.destroy_external_storageu  s5    "3 	; 	;N**>::::	; 	;r   c                    t           j                            |          rm	 t          j        |           n6# t
          $ r Y n*t          $ r t                              d           Y d S w xY wt           j                            |          kd S d S )NzuError cleaning up spill files. You might still have remaining spilled objects inside `ray_spilled_objects` directory.)	r   r   isdirshutilrmtreer   	Exceptionlogger	exceptionr   s     r   r   z+FileSystemStorage._destroy_external_storagey  s    
 gmmN++ 	n----%         F  
  gmmN++ 	 	 	 	 	s   6 
A)#A)(A)r+   )r{   r|   r}   r~   r   r   r   r   r"   r/   ro   r
   rt   rx   rz   r   __classcell__r   s   @r   r   r     s         &*	*X *X*X c49n-*X c]	*X *X *X *X *X *XXVT#Y V V V V	?BFs)   649    ; ; ;      r   r   c                        e Zd ZdZ	 	 ddedepedef fdZdee         fd	Z	d
ee
         dee         fdZdee         fdZd Z xZS )ExternalStorageSmartOpenImpla  The external storage class implemented by smart_open.
    (https://github.com/RaRe-Technologies/smart_open)

    Smart open supports multiple backend with the same APIs.

    To use this implementation, you should pre-create the given uri.
    For example, if your uri is a local file path, you should pre-create
    the directory.

    Args:
        uri: Storage URI used for smart open.
        prefix: Prefix of objects that are stored.
        override_transport_params: Overriding the default value of
            transport_params for smart-open library.

    Raises:
        ModuleNotFoundError: If it fails to setup.
            For example, if smart open library
            is not downloaded, this will fail.
    N   r   urioverride_transport_paramsc                    t                                                       	 ddlm} n$# t          $ r}t	          d|           d }~ww xY w|
J d            t          |t                    r|g}t          |t                    s
J d            t          |t                    s
J d            d |D             }t          |          | _
        | j
        s!t          |          r
J d            || _        nd	 |D             | _        t          | j                  t          |          k    sJ t          j        dt          | j                            | _        t"           d
| | _        |pi | _        | j
        r0dd l}|                    d          | _        d| j        |d| _        ni | _        | j                            | j                   d S )Nr   r   z{Smart open is chosen to be a object spilling external storage, but smart_open and boto3 is not downloaded. Original error: z.uri should be provided to use object spilling.z/uri must be a single string or list of strings.r   c                 8    g | ]}|                     d           S )zs3://)
startswith.0us     r   
<listcomp>z9ExternalStorageSmartOpenImpl.__init__.<locals>.<listcomp>  s$    888qQ\\'**888r   z'all uri's must be s3 or none can be s3.c                 8    g | ]}|                     d           S )/)stripr   s     r   r   z9ExternalStorageSmartOpenImpl.__init__.<locals>.<listcomp>  s"    4441!''#,,444r   r^   s3)service_nameT)
defer_seekresourcer   )r   r/   
smart_openr   ModuleNotFoundErrorr   r   r   r"   all	is_for_s3any_urisrQ   r   r   _current_uri_indexr	   prefixr   boto3r   r   transport_paramsupdate)
r.   r   r   r   r   r   e	uri_is_s3r   r   s
            r   r/   z%ExternalStorageSmartOpenImpl.__init__  s    		'''''''" 	 	 	%:67: :  	  Pc3 	%C#t$$WW&WWW$+s++NN-NNN+88C888	Y~ 	59~~PP'PPP%DJJ44444DJ4:#c((****"("21c$*oo"F"F.::::)B)Hb&> 	'LLL
 nn$n77DG # G*% %D!! %'D!$$T%CDDDDDs   * 
AAAr   c                 n   t          |          dk    rg S ddlm} | j        dz   t          | j                  z  | _        | j        | j                 }| j         dt          |           }| d| } ||d| j                  5 }|                     ||||          cd d d            S # 1 swxY w Y   d S )Nr   r   r)   -r   r   )moder   )	rQ   r   r   r   r   r   r   r   rf   )r.   r?   rJ   r   r   keyr   rE   s           r   ro   z*ExternalStorageSmartOpenImpl.spill_objects  s*   {q  I###### $(#:Q#>#dj//"Qj01HH9+FFHHnnsnnT!2
 
 
 	 //; 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   B**B.1B.r?   rq   c           	      :   ddl m} d}t          t          |                    D ]t}||         }||                                         }t          |          }|j        }	|j        }
 ||	d| j                  5 }|	                    |
           t                              |                    d          d          }t                              |                    d          d          }t                              |                    d          d          }|                     ||||j                   |                    |          }||z  }|                    |          }|                     |||||           d d d            n# 1 swxY w Y   v|S )Nr   r   r   )r   rL   rM   rN   )r   r   r   rQ   r   r%   r   r   r   r   r"   r   r   rl   r   rH   )r.   r?   rq   r   r   r   rF   r   r#   r   r   rI   r_   r`   rb   rG   rC   s                    r   rt   z4ExternalStorageSmartOpenImpl.restore_spilled_objects  s    	$#####s;''(( 	 	A$QJ215<<>>O 2/BBM$-H")Fht7LMMM QR v!nnQVVAYY(nKK"~~affQii8~LL..h.GG  lG]EWXXX !{ 3 3 66,//))gq*m                 s   :DFF	F	ru   c                     d S r+   r   rw   s     r   rx   z3ExternalStorageSmartOpenImpl.delete_spilled_objects      r   c                     d S r+   r   r-   s    r   rz   z5ExternalStorageSmartOpenImpl.destroy_external_storage  r   r   )Nr   )r{   r|   r}   r~   r   r   dictr/   r   ro   r
   rt   rx   rz   r   r   s   @r   r   r     s         2 +/9E 9E9E [D9E $(	9E 9E 9E 9E 9E 9EvT#Y    *	?BFs)   @49          r   r   c                   D     e Zd ZdZdef fdZdee         f fdZ xZS )UnstableFileStoragez/This class is for testing with writing failure.r   c                 X     t                      j        |fi | d| _        d| _        d S )Ng?g?)r   r/   _failure_rate_partial_failure_ratior.   r   kwargsr   s      r   r/   zUnstableFileStorage.__init__!  s8    ++F+++ &)###r   r   c                    t          j                     | j        k     }|| j        k     }|| j        k     }|rt          d          |rXt          j        t          t          |                              }t                                          |d |         |          S t                                          ||          S )Nz1Spilling object failed intentionally for testing.)	r   r   r   IOErrorchoicer   rQ   r   ro   )r.   r?   rJ   rfailedpartial_failedr   r   s          r   ro   z!UnstableFileStorage.spill_objects&  s    MOOd00T''T88 	GMNNN 	GeC$4$45566A77((RaR/JJJ77((oFFFr   	r{   r|   r}   r~   r   r/   r   ro   r   r   s   @r   r   r     s~        99* * * * * * *

GT#Y 
G 
G 
G 
G 
G 
G 
G 
G 
G 
Gr   r   c                   D     e Zd ZdZdef fdZdee         f fdZ xZS )SlowFileStoragez/This class is for testing slow object spilling.r   c                 X     t                      j        |fi | d| _        d| _        d S )Nr)      )r   r/   
_min_delay
_max_delayr   s      r   r/   zSlowFileStorage.__init__6  s4    ++F+++r   r   c                     t          j                     | j        | j        z
  z  | j        z   }t          j        |           t                                          ||          S r+   )r   r  r   r6   r8   r   ro   )r.   r?   rJ   delayr   s       r   ro   zSlowFileStorage.spill_objects;  sM    4?T_#DEW
5ww$$[/BBBr   r   r   s   @r   r   r   3  s~        99      
CT#Y C C C C C C C C C Cr   r   c                    |
J d            | r| d         }|dk    rt          |fi | d         an|dk    rt          |fi | d         ann|dk    rt          |fi | d         anT|dk    rt          |fi | d         an:|d	k    rt	          |fi | d         an t          d
|           t                      at          S )z3Setup the external storage according to the config.Nznode_id should be provided.type
filesystemparamsr   mock_distributed_fsunstable_fsslow_fszUnknown external storage type: )r   _external_storager   r   r   r!   r   )configr   session_namestorage_types       r   setup_external_storager  A  s-    = *f~<'' 1' N NVH=M N N\)) <! !!(+! ! 222 !2' N NVH=M N N]** !4G P Pvh?O P PY&& / L L6(;K L LM|MMNNN'MMr   c                  "    t                      ad S r+   )r   r  r   r   r   reset_external_storager  _  s    #r   c                 8    t                               | |          S )aD  Spill objects to the external storage. Objects are specified
    by their object refs.

    Args:
        object_refs: The list of the refs of the objects to be spilled.
        owner_addresses: The owner addresses of the provided object refs.
    Returns:
        A list of keys corresponding to the input object refs.
    )r  ro   )r?   rJ   s     r   ro   ro   d  s     **;HHHr   r?   rq   c                 8    t                               | |          S )zRestore objects from the external storage.

    Args:
        object_refs: List of object IDs (note that it is not ref).
        url_with_offset_list: List of url_with_offset.
    )r  rt   )r?   rq   s     r   rt   rt   q  s     44[BVWWWr   ru   c                 :    t                               |            dS )z|Delete objects that are spilled to the external storage.

    Args:
        urls: URLs that store spilled object files.
    N)r  rx   )ru   s    r   rx   rx   }  s     ,,T22222r   c                 V    t          j                    j         dt          |            S )zkGenerate a unqiue spill file name.

    Args:
        object_refs: objects to be spilled in this file.
    z-multi-)uuiduuid4rR   rQ   )r?   s    r   r   r     s)     jll99s;'7'7999r   )+r   loggingr   r   r   r6   r   r  collectionsr   typingr   r   r   r   r   r2   ray._private.ray_constantsr	   ray._rayletr
   r   	getLoggerr{   r   r   r"   r   r%   ABCMetar'   r   r   r   r  r   r   r  r  ro   rt   rx   r   r   r   r   <module>r     s.   



  				      " " " " " " 3 3 3 3 3 3 3 3 3 3 3 3 3 3 



 < < < < < < ! ! ! ! ! !J{$<==			8	$	$03 0 03 03 0 0 0 0:B3 B5c33G B B B B.t t t t t t t t tnI I I I I/ I I I | | | | | | | |~J J J J J? J J JZ  KMM G G G G G+ G G G*C C C C C' C C C  <& & &

I 
I 
I	Xi	X8<S		X 	X 	X 	X3c 3 3 3 3:DO : : : : : :r   