o
    ܀cm                     @   sp  d dl Z d dlZd dl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mZmZmZmZmZ eeZG dd dZG d	d
 d
eZG dd deZG dd deZG dd deZG dd de
ZG dd deZG dd deZ G dd deZ!G dd deZ"G dd deZ#G dd deZ$G dd  d eZ%G d!d" d"Z&G d#d$ d$Z'dS )%    Nseekable)RetriesExceededErrorIN_MEMORY_DOWNLOAD_TAG)SubmissionTaskTask)	S3_RETRYABLE_DOWNLOAD_ERRORSCountCallbackInvokerDeferredOpenFileFunctionContainerStreamReaderProgresscalculate_num_partscalculate_range_parameterget_callbacksinvoke_progress_callbacksc                   @   sT   e Zd ZdZdd Zedd Zdd Zdd	 Zd
d Z	dd Z
dd Zdd ZdS )DownloadOutputManagera  Base manager class for handling various types of files for downloads

    This class is typically used for the DownloadSubmissionTask class to help
    determine the following:

        * Provides the fileobj to write to downloads to
        * Get a task to complete once everything downloaded has been written

    The answers/implementations differ for the various types of file outputs
    that may be accepted. All implementations must subclass and override
    public methods from this class.
    c                 C   s   || _ || _|| _d S N)_osutil_transfer_coordinator_io_executorselfosutiltransfer_coordinatorio_executor r   >/usr/local/lib/python3.10/dist-packages/s3transfer/download.py__init__2   s   
zDownloadOutputManager.__init__c                 C      t d)ae  Determines if the target for the download is compatible with manager

        :param download_target: The target for which the upload will write
            data to.

        :param osutil: The os utility to be used for the transfer

        :returns: True if the manager can handle the type of target specified
            otherwise returns False.
        zmust implement is_compatible()NotImplementedErrorclsdownload_targetr   r   r   r   is_compatible7   s   z#DownloadOutputManager.is_compatiblec                 C   s   dS )zGet the tag (if any) to associate all GetObjectTasks

        :rtype: s3transfer.futures.TaskTag
        :returns: The tag to associate all GetObjectTasks with
        Nr   r   r   r   r   get_download_task_tagE   s   z+DownloadOutputManager.get_download_task_tagc                 C   r   )a  Get file-like object to use for io writes in the io executor

        :type transfer_future: s3transfer.futures.TransferFuture
        :param transfer_future: The future associated with upload request

        returns: A file-like object to write to
        z*must implement get_fileobj_for_io_writes()r    r   transfer_futurer   r   r   get_fileobj_for_io_writesM   s   z/DownloadOutputManager.get_fileobj_for_io_writesc                 C   s   | j | j| ||| dS )a  Queue IO write for submission to the IO executor.

        This method accepts an IO executor and information about the
        downloaded data, and handles submitting this to the IO executor.

        This method may defer submission to the IO executor if necessary.

        N)r   submitr   get_io_write_taskr   fileobjdataoffsetr   r   r   queue_file_io_taskW   s   	z(DownloadOutputManager.queue_file_io_taskc                 C   s   t | j|||ddS )a  Get an IO write task for the requested set of data

        This task can be ran immediately or be submitted to the IO executor
        for it to run.

        :type fileobj: file-like object
        :param fileobj: The file-like object to write to

        :type data: bytes
        :param data: The data to write out

        :type offset: integer
        :param offset: The offset to write the data to in the file-like object

        :returns: An IO task to be used to write data to a file-like object
        )r.   r/   r0   main_kwargs)IOWriteTaskr   r-   r   r   r   r,   d   s   z'DownloadOutputManager.get_io_write_taskc                 C   r   )a  Get the final io task to complete the download

        This is needed because based on the architecture of the TransferManager
        the final tasks will be sent to the IO executor, but the executor
        needs a final task for it to signal that the transfer is done and
        all done callbacks can be run.

        :rtype: s3transfer.tasks.Task
        :returns: A final task to completed in the io executor
        z"must implement get_final_io_task()r    r&   r   r   r   get_final_io_task~   s   z'DownloadOutputManager.get_final_io_taskc                 C   s$   t |d| jjd}| j|j |S )Nwb)modeopen_function)r   r   openr   add_failure_cleanupclose)r   filenamefr   r   r   _get_fileobj_from_filename   s
   
z0DownloadOutputManager._get_fileobj_from_filenameN)__name__
__module____qualname____doc__r   classmethodr%   r'   r*   r1   r,   r5   r>   r   r   r   r   r   $   s    

r   c                       s@   e Zd Z fddZedd Zdd Zdd Zd	d
 Z  Z	S )DownloadFilenameOutputManagerc                    s&   t  ||| d | _d | _d | _d S r   )superr   _final_filename_temp_filename_temp_fileobjr   	__class__r   r   r      s   
z&DownloadFilenameOutputManager.__init__c                 C   s
   t |tS r   )
isinstancestrr"   r   r   r   r%         
z+DownloadFilenameOutputManager.is_compatiblec                 C   s.   |j jj}|| _| j|| _|  | _| jS r   )	meta	call_argsr.   rF   r   get_temp_filenamerG   _get_temp_fileobjrH   )r   r)   r.   r   r   r   r*      s
   

z7DownloadFilenameOutputManager.get_fileobj_for_io_writesc                 C   s   t | j| j| j| jdddS )N)r.   final_filenamer   T)r   r3   is_final)IORenameFileTaskr   rH   rF   r   r&   r   r   r   r5      s   z/DownloadFilenameOutputManager.get_final_io_taskc                 C   s$   |  | j}| j| jj| j |S r   )r>   rG   r   r:   r   remove_file)r   r=   r   r   r   rQ      s
   
z/DownloadFilenameOutputManager._get_temp_fileobj)
r?   r@   rA   r   rC   r%   r*   r5   rQ   __classcell__r   r   rI   r   rD      s    
rD   c                   @   s(   e Zd Zedd Zdd Zdd ZdS )DownloadSeekableOutputManagerc                 C   s   t |S r   r   r"   r   r   r   r%      s   z+DownloadSeekableOutputManager.is_compatiblec                 C   
   |j jjS r   rN   rO   r.   r(   r   r   r   r*      rM   z7DownloadSeekableOutputManager.get_fileobj_for_io_writesc                 C      t | jdS N)r   CompleteDownloadNOOPTaskr   r&   r   r   r   r5      s   z/DownloadSeekableOutputManager.get_final_io_taskN)r?   r@   rA   rC   r%   r*   r5   r   r   r   r   rW      s
    
rW   c                       sX   e Zd Z	d fdd	Zedd Zdd Zdd	 Zd
d Z fddZ	dd Z
  ZS ) DownloadNonSeekableOutputManagerNc                    s2   t  ||| |d u rt }|| _t | _d S r   )rE   r   
DeferQueue_defer_queue	threadingLock_io_submit_lockr   r   r   r   defer_queuerI   r   r   r      s
   z)DownloadNonSeekableOutputManager.__init__c                 C   s
   t |dS )Nwrite)hasattrr"   r   r   r   r%      rM   z.DownloadNonSeekableOutputManager.is_compatiblec                 C   s   t S r   r   r&   r   r   r   r'         z6DownloadNonSeekableOutputManager.get_download_task_tagc                 C   rX   r   rY   r(   r   r   r   r*      s   
z:DownloadNonSeekableOutputManager.get_fileobj_for_io_writesc                 C   rZ   r[   r\   r&   r   r   r   r5      s   z2DownloadNonSeekableOutputManager.get_final_io_taskc                    sn   | j * | j||}|D ]}|d }td|d | t ||| qW d    d S 1 s0w   Y  d S )Nr/   z%Queueing IO offset %s for fileobj: %sr0   )rc   r`   request_writesloggerdebugrE   r1   )r   r.   r/   r0   writesrf   rI   r   r   r1      s   "z3DownloadNonSeekableOutputManager.queue_file_io_taskc                 C   s   t | j||ddS )N)r.   r/   r2   )IOStreamingWriteTaskr   r-   r   r   r   r,      s   z2DownloadNonSeekableOutputManager.get_io_write_taskr   )r?   r@   rA   r   rC   r%   r'   r*   r5   r1   r,   rV   r   r   rI   r   r^      s    	
r^   c                       s<   e Zd Z	d
 fdd	Zedd Zdd Zdd	 Z  ZS )$DownloadSpecialFilenameOutputManagerNc                    s   t  |||| d | _d S r   )rE   r   _fileobjrd   rI   r   r   r      s   
z-DownloadSpecialFilenameOutputManager.__init__c                 C   s   t |to	||S r   )rK   rL   is_special_filer"   r   r   r   r%     s   z2DownloadSpecialFilenameOutputManager.is_compatiblec                 C   s   |j jj}| || _| jS r   )rN   rO   r.   r>   ro   )r   r)   r<   r   r   r   r*     s   
z>DownloadSpecialFilenameOutputManager.get_fileobj_for_io_writesc                 C   s   t | jdd| jidS )NTr.   )r   rS   r3   )IOCloseTaskr   ro   r&   r   r   r   r5     s
   z6DownloadSpecialFilenameOutputManager.get_final_io_taskr   )	r?   r@   rA   r   rC   r%   r*   r5   rV   r   r   rI   r   rn      s    
rn   c                   @   sD   e Zd ZdZdd Z	dddZdd Zd	d
 Zdd Zdd Z	dS )DownloadSubmissionTaskz/Task for submitting tasks to execute a downloadc                 C   sH   t tttg}|jjj}|D ]}|||r|  S qtd	|t
|)a  Retrieves a class for managing output for a download

        :type transfer_future: s3transfer.futures.TransferFuture
        :param transfer_future: The transfer future for the request

        :type osutil: s3transfer.utils.OSUtils
        :param osutil: The os utility associated to the transfer

        :rtype: class of DownloadOutputManager
        :returns: The appropriate class to use for managing a specific type of
            input for downloads.
        z'Output {} of type: {} is not supported.)rn   rD   rW   r^   rN   rO   r.   r%   RuntimeErrorformattype)r   r)   r   download_manager_resolver_chainr.   download_manager_clsr   r   r    _get_download_output_manager_cls  s   
z7DownloadSubmissionTask._get_download_output_manager_clsNc           
   
   C   s   |j jdu r"|jd|j jj|j jjd|j jj}|j |d  | |||| j	|}	|j j|j
k rB| ||||||	|| dS | ||||||	|| dS )a  
        :param client: The client associated with the transfer manager

        :type config: s3transfer.manager.TransferConfig
        :param config: The transfer config associated with the transfer
            manager

        :type osutil: s3transfer.utils.OSUtil
        :param osutil: The os utility associated to the transfer manager

        :type request_executor: s3transfer.futures.BoundedExecutor
        :param request_executor: The request executor associated with the
            transfer manager

        :type io_executor: s3transfer.futures.BoundedExecutor
        :param io_executor: The io executor associated with the
            transfer manager

        :type transfer_future: s3transfer.futures.TransferFuture
        :param transfer_future: The transfer future associated with the
            transfer request that tasks are being submitted for

        :type bandwidth_limiter: s3transfer.bandwidth.BandwidthLimiter
        :param bandwidth_limiter: The bandwidth limiter to use when
            downloading streams
        NBucketKeyContentLengthr   )rN   sizehead_objectrO   bucketkey
extra_argsprovide_transfer_sizerx   r   multipart_threshold_submit_download_request_submit_ranged_download_request)
r   clientconfigr   request_executorr   r)   bandwidth_limiterresponsedownload_output_managerr   r   r   _submit;  sH   $zDownloadSubmissionTask._submitc	                 C   sp   |j j}	||}
t|d}| }| }| jj|t| j||	j	|	j
|
|	j||j||j|d
|gd|d d S )Nprogress)
r   r   r   r.   r   	callbacksmax_attemptsr   io_chunksizer   r   r3   done_callbackstag)rN   rO   r*   r   r'   r5   r   r+   ImmediatelyWriteIOGetObjectTaskr   r   r   num_download_attemptsr   )r   r   r   r   r   r   r   r)   r   rO   r.   progress_callbacksget_object_tag
final_taskr   r   r   r     s4   

z/DownloadSubmissionTask._submit_download_requestc	                 C   s   |j j}	t|d}
||}|j}t|j j|}| }t| 	||}t
|D ]9}t|||}d|i}||	j |  | jj|t| j||	j|	j|||
|j|| ||j|d|jgd|d q(|  d S )Nr   Range)r   r   r   r.   r   r   r   start_indexr   r   r   r   r   )rN   rO   r   r*   multipart_chunksizer   r}   r'   r
   &_get_final_io_task_submission_callbackranger   updater   	incrementr   r+   GetObjectTaskr   r   r   r   	decrementfinalize)r   r   r   r   r   r   r   r)   r   rO   r   r.   	part_size	num_partsr   finalize_download_invokerirange_parameterr   r   r   r   r     sR   
z6DownloadSubmissionTask._submit_ranged_download_requestc                 C   s   |  }t| jj||S r   )r5   r   r   r+   )r   download_managerr   r   r   r   r   r     s   
z=DownloadSubmissionTask._get_final_io_task_submission_callbackc                 C   s:   || }||d krd}n|| d }d| d| }|S )N    zbytes=-r   )r   r   
part_indexr   start_range	end_rangerange_paramr   r   r   _calculate_range_param	  s   z-DownloadSubmissionTask._calculate_range_paramr   )
r?   r@   rA   rB   rx   r   r   r   r   r   r   r   r   r   rr     s    &
M2Grr   c                   @   s"   e Zd Z		dddZdd ZdS )r   r   Nc                 C   s   d}t |D ]j}zC|
}|jd||d|}t|d |}|r&||| j}t||	}|D ]}| j sC| |||| |t|7 }q- W  dS W  dS  t	yp } zt
jd|||dd |}t||
|  W Y d}~qd}~ww t|)a  Downloads an object and places content into io queue

        :param client: The client to use when calling GetObject
        :param bucket: The bucket to download from
        :param key: The key to download from
        :param fileobj: The file handle to write content to
        :param exta_args: Any extra arguments to include in GetObject request
        :param callbacks: List of progress callbacks to invoke on download
        :param max_attempts: The number of retries to do when downloading
        :param download_output_manager: The download output manager associated
            with the current download.
        :param io_chunksize: The size of each io chunk to read from the
            download stream and queue in the io queue.
        :param start_index: The location in the file to start writing the
            content of the key to.
        :param bandwidth_limiter: The bandwidth limiter to use when throttling
            the downloading of data in streams.
        Nry   BodyzCRetrying exception caught (%s), retrying request, (attempt %s / %s)T)exc_infor   )r   
get_objectr   get_bandwith_limited_streamr   DownloadChunkIteratordone
_handle_iolenr	   rj   rk   r   r   )r   r   r   r   r.   r   r   r   r   r   r   r   last_exceptionr   current_indexr   streaming_bodychunkschunker   r   r   _main  sZ    


zGetObjectTask._mainc                 C   s   | ||| d S r   )r1   )r   r   r.   r   indexr   r   r   r   i  s   zGetObjectTask._handle_io)r   N)r?   r@   rA   r   r   r   r   r   r   r     s
    
Tr   c                   @      e Zd ZdZdd ZdS )r   a   GetObjectTask that immediately writes to the provided file object

    This is useful for downloads where it is known only one thread is
    downloading the object so there is no reason to go through the
    overhead of using an IO queue and executor.
    c                 C   s   | |||}|  d S r   )r,   )r   r   r.   r   r   taskr   r   r   r   u  s   
z*ImmediatelyWriteIOGetObjectTask._handle_ioN)r?   r@   rA   rB   r   r   r   r   r   r   m  s    r   c                   @   s   e Zd Zdd ZdS )r4   c                 C   s   | | || dS )zPulls off an io queue to write contents to a file

        :param fileobj: The file handle to write content to
        :param data: The data to write
        :param offset: The offset to write the data to.
        N)seekrf   r-   r   r   r   r   {  s   
zIOWriteTask._mainN)r?   r@   rA   r   r   r   r   r   r4   z  s    r4   c                   @   r   )rm   z/Task for writing data to a non-seekable stream.c                 C   s   | | dS )zWrite data to a fileobj.

        Data will be written directly to the fileobj without
        any prior seeking.

        :param fileobj: The fileobj to write content to
        :param data: The data to write

        N)rf   )r   r.   r/   r   r   r   r     s   
zIOStreamingWriteTask._mainNr?   r@   rA   rB   r   r   r   r   r   rm     s    rm   c                   @   r   )rT   a  A task to rename a temporary file to its final filename

    :param fileobj: The file handle that content was written to.
    :param final_filename: The final name of the file to rename to
        upon completion of writing the contents.
    :param osutil: OS utility
    c                 C   s   |   ||j| d S r   )r;   rename_filename)r   r.   rR   r   r   r   r   r     s   zIORenameFileTask._mainNr   r   r   r   r   rT     s    rT   c                   @   r   )rq   ziA task to close out a file once the download is complete.

    :param fileobj: The fileobj to close.
    c                 C   s   |   d S r   )r;   )r   r.   r   r   r   r     s   zIOCloseTask._mainNr   r   r   r   r   rq     s    rq   c                       s2   e Zd ZdZ				d fdd	Zdd Z  ZS )	r]   zA NOOP task to serve as an indicator that the download is complete

    Note that the default for is_final is set to True because this should
    always be the last task.
    NTc                    s   t  j|||||d d S )N)r   r3   pending_main_kwargsr   rS   )rE   r   )r   r   r3   r   r   rS   rI   r   r   r     s   
z!CompleteDownloadNOOPTask.__init__c                 C   s   d S r   r   r&   r   r   r   r     rh   zCompleteDownloadNOOPTask._main)NNNT)r?   r@   rA   rB   r   r   rV   r   r   rI   r   r]     s    	r]   c                   @   s(   e Zd Zdd Zdd Zdd ZeZdS )r   c                 C   s   || _ || _d| _dS )zIterator to chunk out a downloaded S3 stream

        :param body: A readable file-like object
        :param chunksize: The amount to read each time
        r   N)_body
_chunksize
_num_reads)r   body	chunksizer   r   r   r     s   
zDownloadChunkIterator.__init__c                 C   s   | S r   r   r&   r   r   r   __iter__  rh   zDownloadChunkIterator.__iter__c                 C   s8   | j | j}|  jd7  _|r|S | jdkr|S t )Nr   )r   readr   r   StopIteration)r   r   r   r   r   __next__  s   
zDownloadChunkIterator.__next__N)r?   r@   rA   r   r   r   nextr   r   r   r   r     s
    
r   c                   @   s    e Zd ZdZdd Zdd ZdS )r_   a"  IO queue that defers write requests until they are queued sequentially.

    This class is used to track IO data for a *single* fileobj.

    You can send data to this queue, and it will defer any IO write requests
    until it has the next contiguous block available (starting at 0).

    c                 C   s   g | _ t | _d| _d S )Nr   )_writesset_pending_offsets_next_offsetr&   r   r   r   r     s   
zDeferQueue.__init__c                 C   s   || j k rg S g }|| jv rg S t| j||f | j| | jr^| jd d | j kr^t| j}||d |d d | j|d  |  j t	|d 7  _ | jr^| jd d | j ks,|S )a  Request any available writes given new incoming data.

        You call this method by providing new data along with the
        offset associated with the data.  If that new data unlocks
        any contiguous writes that can now be submitted, this
        method will return all applicable writes.

        This is done with 1 method call so you don't have to
        make two method calls (put(), get()) which acquires a lock
        each method call.

        r   r   )r0   r/   )
r   r   heapqheappushr   addheappopappendremover   )r   r0   r/   rl   
next_writer   r   r   ri     s   

zDeferQueue.request_writesN)r?   r@   rA   rB   r   ri   r   r   r   r   r_     s    	r_   )(r   loggingra   s3transfer.compatr   s3transfer.exceptionsr   s3transfer.futuresr   s3transfer.tasksr   r   s3transfer.utilsr	   r
   r   r   r   r   r   r   r   	getLoggerr?   rj   r   rD   rW   r^   rn   rr   r   r   r4   rm   rT   rq   r]   r   r_   r   r   r   r   <module>   s2   ,
q(/ {Y
