o
    
i                  	   @  s  d Z ddlm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 zddlZddlZddlZddlZW n eyQ   dZY nw ddlZddlZddlZddlmZ errddlmZ dd	lm Z  e!e"Z#d
Z$	 dZ%	 dZ&	 dZ'dZ(dZ)dZ*dZ+dZ,G dd dZ-de. vre- Z/G dd dZ0dd Z1dd Z2dd Z3de*e%ddddddf	dd Z4d!d" Z5d#d$ Z6G d%d& d&e7Z8d'd( Z9G d)d* d*ej:Z;G d+d, d,ej:Z<G d-d. d.ej:Z=d/d0 Z>	1			2	3	4	d@d5d6Z?d1d7d8 d9d:d;Z@d<d= ZAd>d? ZBdS )AzDImplements file-like objects for reading and writing from/to AWS S3.    )annotationsN)inf)CallableListTYPE_CHECKINGT)	constants)S3Client)Bufferi  P i   l        )s3s3ns3us3ai  zs3.amazonaws.comi   )zs3://my_bucket/my_keyz&s3://my_key:my_secret@my_bucket/my_keyz8s3://my_key:my_secret@my_server:my_port@my_bucket/my_keyInvalidRangec                   @  s   e Zd Zdd ZdddZdS )	Retryc                 C  s$   d| _ d| _tjjg| _dg| _d S )N   
   NoSuchUpload)attemptssleep_secondsbotocore
exceptionsEndpointConnectionErrorclient_error_codesself r   A/home/ubuntu/.local/lib/python3.10/site-packages/smart_open/s3.py__init__U   s   zRetry.__init__fnr   c                 C  s   t | jD ]l}z| W   S  t| jy9 } ztd|| j| d  t| t| j	 W Y d }~qd }~w t
jjyq } z+|jd d}|| jvrP td|| j| d  t| t| j	 W Y d }~qd }~ww td td|j| j)Nz+Caught non-fatal %s, retrying %d more times   ErrorCodez9Caught non-fatal ClientError (%s), retrying %d more timesz0encountered too many non-fatal errors, giving upz%s failed after %d attempts)ranger   tupler   loggercritical	exceptiontimesleepr   r   ClientErrorresponsegetr   IOErrorfunc)r   r   attempterr
error_coder   r   r   _do[   s6   



z	Retry._doN)r   r   )__name__
__module____qualname__r   r1   r   r   r   r   r   T   s    r   MISSING_DEPSc                   @  s    e Zd ZdZdd Zdd ZdS )_ClientWrapperax  Wraps a client to inject the appropriate keyword args into each method call.

    The keyword args are a dictionary keyed by the fully qualified method name.
    For example, S3.Client.create_multipart_upload.

    See https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#client

    This wrapper behaves identically to the client otherwise.
    c                 C  s   || _ || _d S N)clientkwargs)r   r8   r9   r   r   r   r      s   
z_ClientWrapper.__init__c                 C  s0   t | j|}| jd| i }tj|fi |S )NzS3.Client.%s)getattrr8   r9   r+   	functoolspartial)r   method_namemethodr9   r   r   r   __getattr__   s   z_ClientWrapper.__getattr__N)r2   r3   r4   __doc__r   r?   r   r   r   r   r6      s    	r6   c              
   C  s  t j| }|jtv sJ t}t}d}d\}}|j|j }d|v r@|	dd\}}	d|v r@|	dd\}
}d|
vr@|
|}}|	}|	dd\}}d|v rfd|v rfd}|	d\}}|	dd\}}t
|}nd|v rtd}|	d\}}n|}t|j|||||||dS )	NFNN@r   :/T)scheme	bucket_idkey_idporthostordinary_calling_format	access_idaccess_secret)
smart_openutilssafe_urlsplitrE   SCHEMESDEFAULT_PORTDEFAULT_HOSTnetlocpathsplitintdict)uri_as_string	split_urirH   rI   rJ   rK   rL   uri
maybe_authrestmaybe_idmaybe_secretheadrG   	host_portrF   r   r   r   	parse_uri   sD   	

ra   c                   s   t    fdd} d}|dur(| d s| d r(td | jddd n| d rA| d rA|| d | d d	 | jddd |durZ| d
 tkrZtd | jdd |  fS | d
 tkrz| d dkrid}nd}||d|   d | jdd |  fS )a`  Consolidates the parsed Uri with the additional parameters.

    This is necessary because the user can pass some of the parameters can in
    two different ways:

    1) Via the URI itself
    2) Via the transport parameters

    These are not mutually exclusive, but we have to pick one over the other
    in a sensible way in order to proceed.

    c                    sl   z d }W n t y   i  } d< Y nw z|d }W n t y+   i  }|d< Y nw |jdi |  d S )Nclient_kwargs	S3.Clientr   )KeyErrorupdate)r9   rb   init_kwargstransport_paramsr   r   inject   s   z#_consolidate_params.<locals>.injectr8   NrK   rL   zignoring credentials parsed from URL because they conflict with transport_params["client"]. Set transport_params["client"] to None to suppress this warning.)rK   rL   )aws_access_key_idaws_secret_access_keyrI   zignoring endpoint_url parsed from URL because they conflict with transport_params["client"]. Set transport_params["client"] to None to suppress this warning.)rI   rE   r   httphttpsz://%(host)s:%(port)d)endpoint_url)rW   r+   r$   warningre   rR   )rZ   rh   ri   r8   rE   r   rg   r   _consolidate_params   s6   
	rp   c           	        sv   d} fdd|D }|rd}d||f }t |t t| }t| \} tjt }t|d |d |fi |S )N)multipart_upload_kwargsobject_kwargsresourceresource_kwargssessionsinglepart_upload_kwargsc                   s   g | ]}| v r|qS r   r   ).0krg   r   r   
<listcomp>   s    zopen_uri.<locals>.<listcomp>zVhttps://github.com/piskvorky/smart_open/blob/develop/MIGRATING_FROM_OLDER_VERSIONS.rstzPignoring the following deprecated transport parameters: %r. See <%s> for detailsrF   rG   )	warningswarnUserWarningra   rp   rM   rN   check_kwargsopen)	rZ   moderh   
deprecateddetecteddoc_urlmessage
parsed_urir9   r   rg   r   open_uri  s   r   Fc              
   C  s   t dt  |tjvrtd|tjf |tjkr"|dur"td|tjkr4t	| ||||||	|d}n"|tjkrP|rFt
| |||	|
|d}nt| |||	|
d}nJ d	| ||_|S )
a  Open an S3 object for reading or writing.

    Parameters
    ----------
    bucket_id: str
        The name of the bucket this object resides in.
    key_id: str
        The name of the key within the bucket.
    mode: str
        The mode for opening the object.  Must be either "rb" or "wb".
    buffer_size: int, optional
        Default: 128KB
        The buffer size in bytes for reading. Controls memory usage. Data is streamed
        from a S3 network stream in buffer_size chunks. Forward seeks within
        the current buffer are satisfied without additional GET requests. Backward
        seeks always open a new GET request. For forward seek-intensive workloads,
        increase buffer_size to reduce GET requests at the cost of higher memory usage.
    min_part_size: int, optional
        The minimum part size for multipart uploads, in bytes.
        When the writebuffer contains this many bytes, smart_open will upload
        the bytes to S3 as a single part of a multi-part upload, freeing the
        buffer either partially or entirely.  When you close the writer, it
        will assemble the parts together.
        The value determines the upper limit for the writebuffer.  If buffer
        space is short (e.g. you are buffering to memory), then use a smaller
        value for min_part_size, or consider buffering to disk instead (see
        the writebuffer option).
        The value must be between 5MB and 5GB.  If you specify a value outside
        of this range, smart_open will adjust it for you, because otherwise the
        upload _will_ fail.
        For writing only.  Does not apply if you set multipart_upload=False.
    multipart_upload: bool, optional
        Default: `True`
        If set to `True`, will use multipart upload for writing to S3. If set
        to `False`, S3 upload will use the S3 Single-Part Upload API, which
        is more ideal for small file sizes.
        For writing only.
    version_id: str, optional
        Version of the object, used when reading object.
        If None, will fetch the most recent version.
    defer_seek: boolean, optional
        Default: `False`
        If set to `True` on a file opened for reading, GetObject will not be
        called until the first seek() or read().
        Avoids redundant API queries when seeking before reading.
    range_chunk_size: int, optional
        Default: `None`
        Maximum byte range per S3 GET request when reading.
        When None (default), a single GET request is made for the entire file,
        and data is streamed from that single botocore.response.StreamingBody
        in buffer_size chunks.
        When set to a positive integer, multiple GET requests are made, each
        limited to at most this many bytes via HTTP Range headers. Each GET
        returns a new StreamingBody that is streamed in buffer_size chunks.
        Useful for reading small portions of large files without forcing
        S3-compatible systems like SeaweedFS/Ceph to load the entire file.
        Larger values mean fewer billable GET requests but higher load on S3
        servers. Smaller values mean more GET requests but less server load per request.
        Values larger than the file size result in a single GET for the whole file.
        Affects reading only. Does not affect memory usage (controlled by buffer_size).
    client: object, optional
        The S3 client to use when working with boto3.
        If you don't specify this, then smart_open will create a new client for you.
    client_kwargs: dict, optional
        Additional parameters to pass to the relevant functions of the client.
        The keys are fully qualified method names, e.g. `S3.Client.create_multipart_upload`.
        The values are kwargs to pass to that method each time it is called.
    writebuffer: IO[bytes], optional
        By default, this module will buffer data in memory using io.BytesIO
        when writing. Pass another binary IO instance here to use it instead.
        For example, you may pass a file object to buffer to local disk instead
        of in RAM. Use this to keep RAM usage low at the expense of additional
        disk IO. If you pass in an open file, then you are responsible for
        cleaning it up after writing completes.
    z%rzbad mode: %r expected one of %rNz$version_id must be None when writing)
version_idbuffer_size
defer_seekr8   rb   range_chunk_size)r8   rb   writebuffer	part_size)r8   rb   r   Fzunexpected mode: %r)r$   debuglocalsr   BINARY_MODESNotImplementedErrorWRITE_BINARY
ValueErrorREAD_BINARYReaderMultipartWriterSinglepartWritername)rF   rG   r   r   r   min_part_sizemultipart_uploadr   r8   rb   r   r   fileobjr   r   r   r~   9  sH   Y



	r~   c              
   C  st   zt ||d}|r||d< |r||d< | jdi |W S  tjjy9 } ztd||||f }||_||d }~ww )NBucketKey	VersionIdRangez9unable to access bucket: %r key: %r version: %r error: %sr   )rW   
get_objectr   r8   r)   r,   backend_error)r8   bucketkeyversionrange_stringparamserrorwrapped_errorr   r   r   _get  s"   r   c              	   C  s(   z| j jd W S  ttfy   Y dS w )zDGiven an IOError from _get, return the 'Error' dictionary from boto.r    N)r   r*   AttributeErrorrd   )ioer   r   r   _unwrap_ioerror  s
   r   c                   @  s\   e Zd ZdZ		dddZedd Zdd Zej	fd	d
Z
dddZdddZdd ZdS )_SeekableRawReaderzHRead an S3 object.

    This class is internal to the S3 submodule.
    Nc                 C  s4   || _ || _|| _|| _|| _d | _d| _d | _d S )Nr   )_client_bucket_key_version_id_range_chunk_size_content_length	_position_body)r   r8   r   r   r   r   r   r   r   r     s   
z_SeekableRawReader.__init__c                 C  
   | j d u S r7   )r   r   r   r   r   closed     
z_SeekableRawReader.closedc                 C  s   | j s| j  d | _d S d S r7   )r   r   closer   r   r   r   r     s   

z_SeekableRawReader.closec                 C  s  |t jvrtdt j |   d}d}|t jkrtd|}n|t jkr-td|| j }n|t jkr8td| }| j	du rV|du rS|dkrS| j
ddd |   d}nd}n|durb|| j	krbd}n	|dkrid}nd}|ryt | _| j	| _| jS | 
|| | jS )zSeek to the specified position.

        :param int offset: The offset in bytes.
        :param int whence: Where the offset is from.

        :returns: the position after seeking.
        :rtype: int
        z"invalid whence, expected one of %rNr   startstopTF)r   WHENCE_CHOICESr   r   WHENCE_STARTmaxWHENCE_CURRENTr   
WHENCE_ENDr   
_open_bodyioBytesIOr   )r   offsetwhencer   r   reached_eofr   r   r   seek  s8   
	




z_SeekableRawReader.seekc              
   C  s&  |du r|du r| j }|du r(| jdur(|| j d }| jdur(t|| jd }tj||}zt| j| j	| j
| j|}W nT ty } zHt|}|du sT|dtkrU t|dd}|dure||ksq|du r}|dur}||kr}| | _ | _t | _n	| j||d d W Y d}~dS d}~ww td| |d d	  |d d
 }|tjjkrtj|d \}	}
}	}|
| _ || _|d | _dS |tjjkrd| _ |d | _|d | _|durt| j|}n|du r|durtd| j| }nd}|dkrtd| | t| j|| _ dS dS td| )a  Open a connection to download the specified range of bytes. Store
        the open file handle in self._body.

        If no range is specified, start defaults to self._position.
        start and stop follow the semantics of the http range header,
        so a stop without a start will read bytes beginning at stop.

        If self._range_chunk_size is set, the S3 server is protected from open range
        headers and stop will be set such that at most self._range_chunk_size bytes
        are returned in a single GET request.

        As a side effect, set self._content_length. Set self._position
        to self._content_length if start is past end of file.
        Nr   r!   ActualObjectSizer   r   z%s: RetryAttempts: %dResponseMetadataRetryAttemptsHTTPStatusCodeContentRangeBodyContentLengthz2%s: discarding %d bytes to reach expected positionzUnexpected status code %r) r   r   r   minrM   rN   make_range_stringr   r   r   r   r   r,   r   r+   _OUT_OF_RANGErV   r   r   r   r   r$   r   rl   
HTTPStatusPARTIAL_CONTENTparse_content_rangeOKr   lenreadr   )r   r   r   r   r*   r   error_responseactual_object_sizestatus_code_
resp_startlengthexpected_positionr   r   r   r   /  sr   

	


z_SeekableRawReader._open_bodyc                   s   dk rt d dkrtt  d	d
 fdd}jdu s0jjk rX  k rX| } jt|7  _ | |sG	  jdu s0jjk rX  k s0 
 S )z9Read from the continuous connection with the remote peer.r   zsize must be >= -1, got r               returnbytesc                   s   | D ]S}j r  ztkrj W   S j   W   S  ttjj	t
jjfyU } ztd|tkr>dn|   t| W Y d }~qd }~ww tdtkr_dnt| f )Nz?%s: caught %r while reading %d bytes, sleeping %ds before retryr   z-%s: failed to read %d bytes after %d attempts)r   r   r   r   r   tellConnectionResetErrorr   r   BotoCoreErrorurllib3	HTTPErrorr$   ro   r   r'   r(   r,   r   )r   secondsr/   binary_collectedr   sizer   r   
retry_read  s8   z+_SeekableRawReader.read.<locals>.retry_readN)r   )r   r   )r   r   r   r   r   r   r   r   writer   getvalue)r   r   r   binaryr   r   r   r     s$   


	z_SeekableRawReader.readc                 C     d| j | jf S )Nz%smart_open.s3._SeekableReader(%r, %r)r   r   r   r   r   r   __str__     z_SeekableRawReader.__str__rA   r   )r2   r3   r4   r@   r   propertyr   r   r   r   r   r   r   r   r   r   r   r   r     s    



6
fAr   c                 C  sx   |du ri }|du r*| di }d|vr"tjjdddddd	|d< tjdi |}|s.J t||| _|| _|| _dS )z~Created the required objects for accessing S3.  Ideally, they have
    been already created for us and we can just reuse them.Nrc   config@   Tr   adaptivemax_attemptsr   max_pool_connectionstcp_keepaliveretriesr
   r
   )	r+   r   r8   Configboto3r6   r   r   r   )rwr8   rb   r   r   rf   r   r   r   _initialize_boto3  s   
	
r  c                   @  s   e Zd ZdZdeejddddfddZdd Zdd	 Z	d)ddZ
d)ddZdd Zd)ddZdd ZejfddZdd Zd*ddZdd Zdd Zdd  Zd)d!d"Zd)d#d$Zd%d& Zd'd( ZdS )+r   z]Reads bytes from S3.

    Implements the io.BufferedIOBase interface of the standard library.NFc
           
      C  sp   || _ || _t| |||| t| j||| j |	d| _d| _tj	|| _
d| _|| _d| _|s6| d d S d S )N)r   r   F)r   _buffer_sizer  r   r   _raw_reader_current_posrM   
bytebuffer
ByteBuffer_buffer_eof_line_terminator_seek_initializedr   )
r   r   r   r   r   line_terminatorr   r8   rb   r   r   r   r   r     s$   zReader.__init__c                 C  s   t d dS )zFlush and close this stream.close: calledN)r$   r   r   r   r   r   r     s   
zReader.closec                 C     dS )z+Return True if the stream can be read from.Tr   r   r   r   r   readable#     zReader.readabler   c                 C  sn   |dkrdS |dk r|   | j  }| jj| _|S t| j|kr&|  |S | jr-|   S | | |  |S )z6Read up to size bytes from the object and return them.r       )	_read_from_bufferr	  r   r   r
  r   r  r  _fill_buffer)r   r   outr   r   r   r   '  s   



zReader.readc                 C  s   | j |dS )zThis is the same as read().)r   )r   r   r   r   r   r   read1@     zReader.read1c                 C  s.   |  t|}|sdS ||dt|< t|S )zLRead up to len(b) bytes into b, and return the number of bytes
        read.r   N)r   r   )r   bdatar   r   r   readintoD  s
   zReader.readintoc                 C  s   |dkrt dt }| jrt| jdksD| j| j}|| |  j	t|7  _	|
| jr6	 | S |   | jrt| jdkr| S )zCRead up to and including the next newline.  Returns the bytes read.r   z(limits other than -1 not implemented yetr   )r   r   r   r  r   r  readliner  r   r
  endswithr  r   )r   limitline	line_partr   r   r   r   M  s   

zReader.readlinec                 C  r  )zyIf False, seek(), tell() and truncate() will raise IOError.

        We offer only seek support, and no truncate support.Tr   r   r   r   r   seekableb     zReader.seekablec                 C  s   |t jkrt j}|| j7 }|t jkr2|| jkr2| jt| j }||kr2| j|| j  || _| jS | jr?|t jkr?|| jksL| j	||| _| j
  | j| jjk| _d| _| jS )zSeek to the specified position.

        :param int offset: The offset in bytes.
        :param int whence: Where the offset is from.

        Returns the position after seeking.T)r   r   r   r
  r   r  r   r  r	  r   emptyr   r  )r   r   r   
buffer_endr   r   r   r   h  s    
	

zReader.seekc                 C     | j S )z,Return the current position within the file.)r
  r   r   r   r   r        zReader.tellc                 C     t jzUnsupported.r   UnsupportedOperationr  r   r   r   truncate  r*  zReader.truncatec                 C  r+  r,  r-  r   r   r   r   detach  r*  zReader.detachc                 C  r  )zDo nothing.Nr   r   r   r   r   	terminate  r  zReader.terminatec                 C  s6   |sJ d| | j| j}| jdur|| jS |S )Create an **independent** `boto3.s3.Object` instance that points to
        the same S3 object as this instance.
        Changes to the returned object will not affect the current instance.
        *resource must be a boto3.resource instanceN)Objectr   r   r   Version)r   rs   objr   r   r   to_boto3  s
   
zReader.to_boto3c                 C  s8   |dkr|nt | j}| j|}|  jt |7  _|S )z:Remove at most size bytes from our buffer and return them.r   )r   r  r   r
  )r   r   partr   r   r   r    s   zReader._read_from_bufferc                 C  sn   t || jj}t| j|k r1| js3| j| j}|dkr%td|  d| _t| j|k r5| jrd S d S d S d S )Nr   z$%s: reached EOF while filling bufferT)	r   r  _chunk_sizer   r  fillr	  r$   r   )r   r   
bytes_readr   r   r   r    s   $zReader._fill_bufferc                 C  r   )Nzsmart_open.s3.Reader(%r, %r)r   r   r   r   r   r     r   zReader.__str__c                 C  s   d| j | j| j| j| jf S )NzZsmart_open.s3.Reader(bucket=%r, key=%r, version_id=%r, buffer_size=%r, line_terminator=%r))r   r   r   r  r  r   r   r   r   __repr__  s   zReader.__repr__r   r7   )r2   r3   r4   r@   DEFAULT_BUFFER_SIZEr   BINARY_NEWLINEr   r   r  r   r  r  r   r%  r   r   r   r/  r0  r1  r7  r  r  r   r<  r   r   r   r   r     s6    
%


	!


r   c                   @  s   e Zd ZdZdZedddfd.ddZdd Zd	d
 Ze	dd Z
dd Zdd ZejfddZd/ddZdd Zdd Zd0ddZdd  Zd!d" Zd1d$d%Zd&d' Zd(d) Zd*d+ Zd,d- ZdS )2r   zuWrites bytes to S3 using the multi part API.

    Implements the io.BufferedIOBase interface of the standard library.Nr   io.BytesIO | Nonec           
   
   C  s   t j|tt}||krtd| d|  |}|| _t| |||| |  |  |  zt	j
| jj||d}t|d | _W n tjjyU }	 z	td||	f |	d }	~	ww |d u r`t | _n|| _d| _d| _g | _d S )Nzadjusting part_size from z to r   UploadIdz=the bucket %r does not exist, or is forbidden for access (%r)r   )rM   rN   clampMIN_PART_SIZEMAX_PART_SIZEr$   ro   
_part_sizer  r;   r<   r   create_multipart_uploadRETRYr1   
_upload_idr   r8   r)   r   r   r   _buf_total_bytes_total_parts_parts)
r   r   r   r   r8   rb   r   adjusted_psr<   r   r   r   r   r     s@   	
zMultipartWriter.__init__c                 C     d S r7   r   r   r   r   r   flush     zMultipartWriter.flushc                 C  s   t d | jr
d S | j r|   t d|  | jr=| jr=tj	| j
j| j| j| jd| jid}t| t d|  n | jr]| j
j| j| j| jd | j
j| j| jdd t d	|  d | _d S )
Nr  z%s: completing multipart uploadParts)r   r   r@  MultipartUploadz%s: completed multipart uploadr   r   r@  r  r   r   r   z-%s: wrote 0 bytes to imitate multipart upload)r$   r   r   rH  r   _upload_next_partrI  rG  r;   r<   r   complete_multipart_uploadr   r   rK  rF  r1   abort_multipart_upload
put_object)r   r<   r   r   r   r     s:   



zMultipartWriter.closec                 C  r   r7   )rG  r   r   r   r   r   *  r   zMultipartWriter.closedc                 C  r  )z+Return True if the stream supports writing.Tr   r   r   r   r   writable.  r  zMultipartWriter.writablec                 C  r  )zIf False, seek(), tell() and truncate() will raise IOError.

        We offer only tell support, and no seek or truncate support.Tr   r   r   r   r   r%  2  r&  zMultipartWriter.seekablec                 C  r+  r,  r-  r   r   r   r   r   r   r   8  r*  zMultipartWriter.seekc                 C  r+  r,  r-  r  r   r   r   r/  <  r*  zMultipartWriter.truncatec                 C  r)  )z#Return the current stream position.)rI  r   r   r   r   r   @  r*  zMultipartWriter.tellc                 C  s
   t d)Nzdetach() not supportedr-  r   r   r   r   r0  G  s   
zMultipartWriter.detachr  r	   r   rV   c                 C  s   d}t |}|  jt|7  _|t|k rK|}|| j | j  }| j|||  | j | jk r?|t|ks;J t|S |   |}|t|k st|S )aJ  Write the given buffer (bytes, bytearray, memoryview or any buffer
        interface implementation) to the S3 file.

        For more information about buffers, see https://docs.python.org/3/c-api/buffer.html

        There's buffering happening under the covers, so this may not actually
        do any HTTP transfer right away.r   )
memoryviewrI  r   rD  rH  r   r   rT  )r   r  r   mvr   endr   r   r   r   J  s   zMultipartWriter.writec                 C  sD   | j rdS td|  | jj| j| j| jd d| _td|  dS )z'Cancel the underlying multipart upload.Nz %s: terminating multipart uploadrR  z%s: terminated multipart upload)r   r$   r   r   rV  r   r   rG  r   r   r   r   r1  k  s   zMultipartWriter.terminatec                 C  s   |sJ d| | j| jS )r2  r3  )r4  r   r   )r   rs   r   r   r   r7  x  s   zMultipartWriter.to_boto3Nonec              
   C  s   | j d }td| || j | jd  | jd tt	j
| jj| j| j| j|| jd}| j|d |d td| | |  j d7  _ | jd | jd d S )	Nr   z3%s: uploading part_num: %i, %i bytes (total %.3fGB)g      Ar   )r   r   r@  
PartNumberr   ETag)r_  r^  z#%s: upload of part_num #%i finished)rJ  r$   inforH  r   rI  r   rF  r1   r;   r<   r   upload_partr   r   rG  rK  appendr   r/  )r   part_numuploadr   r   r   rT    s0   
z!MultipartWriter._upload_next_partc                 C     | S r7   r   r   r   r   r   	__enter__  rO  zMultipartWriter.__enter__c                 C      |d ur
|    d S |   d S r7   r1  r   r   exc_typeexc_valexc_tbr   r   r   __exit__     zMultipartWriter.__exit__c                 C  r   )Nz%smart_open.s3.MultipartWriter(%r, %r)r   r   r   r   r   r     r   zMultipartWriter.__str__c                 C  s   d| j | j| jf S )Nz>smart_open.s3.MultipartWriter(bucket=%r, key=%r, part_size=%r))r   r   rD  r   r   r   r   r<    s
   zMultipartWriter.__repr__)r   r?  r7   )r  r	   r   rV   )r   r]  )r2   r3   r4   r@   rG  DEFAULT_PART_SIZEr   rN  r   r   r   rX  r%  r   r   r   r/  r   r0  r   r1  r7  rT  rf  rm  r   r<  r   r   r   r   r     s4    +(


!
$r   c                   @  s   e Zd ZdZdZ			d(ddZdd Zdd Zed	d
 Z	dd Z
dd Zdd ZejfddZd)ddZdd Zdd Zd*ddZd*ddZdd Zd d! Zd"d# Zd$d% Zd&d' ZdS )+r   a  Writes bytes to S3 using the single part API.

    Implements the io.BufferedIOBase interface of the standard library.

    This class buffers all of its input in memory until its `close` method is called. Only then will
    the data be written to S3 and the buffer is released.Nc                 C  s@   t | |||| |d u rt | _d S | std|| _d S )Nz writebuffer needs to be seekable)r  r   r   rH  r%  r   )r   r   r   r8   rb   r   r   r   r   r     s   
zSinglepartWriter.__init__c                 C  rM  r7   r   r   r   r   r   rN    rO  zSinglepartWriter.flushc              
   C  s   t d | jr
d S | d z3z| jj| j| j| jd W n t	j
jy4 } ztd| j |d }~ww t d|  W | j  d S | j  w )Nr  r   rS  z8the bucket %r does not exist, or is forbidden for accessz%s: direct upload finished)r$   r   r   r   r   rW  r   r   rH  r   r8   r)   r   r   )r   er   r   r   r     s(   


zSinglepartWriter.closec                 C  s   | j d u p| j jS r7   )rH  r   r   r   r   r   r     s   zSinglepartWriter.closedc                 C  
   | j  S z
Propagate.)rH  r  r   r   r   r   r    r   zSinglepartWriter.readablec                 C  rq  rr  )rH  rX  r   r   r   r   rX    r   zSinglepartWriter.writablec                 C  rq  rr  )rH  r%  r   r   r   r   r%    r   zSinglepartWriter.seekablec                 C  s   | j ||S rr  )rH  r   rY  r   r   r   r      s   zSinglepartWriter.seekc                 C     | j |S rr  )rH  r/  r  r   r   r   r/    r  zSinglepartWriter.truncatec                 C  rq  rr  )rH  r   r   r   r   r   r     r   zSinglepartWriter.tellc                 C  rs  )a(  Write the given buffer (bytes, bytearray, memoryview or any buffer
        interface implementation) into the buffer. Content of the buffer will be
        written to S3 on close as a single-part upload.

        For more information about buffers, see https://docs.python.org/3/c-api/buffer.html)rH  r   )r   r  r   r   r   r     s   zSinglepartWriter.writer   c                 C  rs  rr  )rH  r   r  r   r   r   r     r  zSinglepartWriter.readc                 C  rs  rr  )rH  r  r  r   r   r   r    r  zSinglepartWriter.read1c                 C  s   | j   td|  dS )zClose buffer and skip upload.z %s: terminated singlepart uploadN)rH  r   r$   r   r   r   r   r   r1    s   
zSinglepartWriter.terminatec                 C  re  r7   r   r   r   r   r   rf  $  rO  zSinglepartWriter.__enter__c                 C  rg  r7   rh  ri  r   r   r   rm  '  rn  zSinglepartWriter.__exit__c                 C  r   )Nz&smart_open.s3.SinglepartWriter(%r, %r)r   r   r   r   r   r   -  r   zSinglepartWriter.__str__c                 C  r   )Nz1smart_open.s3.SinglepartWriter(bucket=%r, key=%r)r   r   r   r   r   r<  0  r   zSinglepartWriter.__repr__)NNNr7   r   )r2   r3   r4   r@   rH  r   rN  r   r   r   r  rX  r%  r   r   r   r/  r   r   r   r  r1  rf  rm  r   r<  r   r   r   r   r     s2    




r   c                 C  r  NTr   )r   r   r   r   _accept_all4  rO  ru   r      r   c              
   k  s   |du rt }z| j} W n	 ty   Y nw | du rtdd\}	}
tjjdi |}|du r1i }d|vrItjj	|| d d|d dd	d
|d< |jdi |}tj
jj|d}t| |||d}tjt| |||d}t||}tj|>}|||}t|ddD ])\}
\}}|du rq|
d dkrtd|
|t||	d  ||fV  |	t|7 }	qW d   n1 sw   Y  td|
|	d  dS )a	  
    Iterate and download all S3 objects under `s3://bucket_name/prefix`.

    Parameters
    ----------
    bucket_name: str
        The name of the bucket.
    prefix: str, optional
        Limits the iteration to keys starting with the prefix.
    accept_key: callable, optional
        This is a function that accepts a key name (unicode string) and
        returns True/False, signalling whether the given key should be downloaded.
        The default behavior is to accept all keys.
    key_limit: int, optional
        If specified, the iterator will stop after yielding this many results.
    workers: int, optional
        The number of objects to download concurrently. The entire operation uses
        a single ThreadPoolExecutor and shared thread-safe boto3 S3.Client. Default: 16
    retries: int, optional
        The number of time to retry a failed download. Default: 3
    max_threads_per_fileobj: int, optional
        The maximum number of download threads per worker. The maximum size of the
        connection pool will be `workers * max_threads_per_fileobj + 1`. Default: 4
    client_kwargs: dict, optional
        Keyword arguments to pass when creating a new session.
        For a list of available names and values, see:
        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html#boto3.session.Session.client
    session_kwargs: dict, optional
        Keyword arguments to pass when creating a new session.
        For a list of available names and values, see:
        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html#boto3.session.Session


    Yields
    ------
    str
        The full key name (does not include the bucket name).
    bytes
        The full contents of the key.

    Notes
    -----
    The keys are processed in parallel, using `workers` processes (default: 16),
    to speed up downloads greatly. If multiprocessing is not available, thus
    _MULTIPROCESSING is False, this parameter will be ignored.

    Examples
    --------

      >>> # get all JSON files under "mybucket/foo/"
      >>> for key, content in iter_bucket(
      ...         bucket_name, prefix='foo/',
      ...         accept_key=lambda key: key.endswith('.json')):
      ...     print key, len(content)

      >>> # limit to 10k files, using 32 parallel workers (default is 16)
      >>> for key, content in iter_bucket(bucket_name, key_limit=10000, workers=32):
      ...     print key, len(content)
    Nzbucket_name may not be None)r   r   r   r   Tr   r   r   r   r
   )max_concurrency)bucket_nameprefix
accept_keyr8   )ry  r  r8   transfer_config)r   i  r   z-yielding key #%i: %s, size %i (total %.1f MB)g      0Az%processed %i keys, total size %.1f MBr   r  )ru  r   r   r   r  ru   Sessionr   r8   r  r
   transferTransferConfig_list_bucketr;   r<   _download_key	itertoolsislicerM   concurrencyThreadPoolExecutorimap	enumerater$   r`  r   )ry  rz  r{  	key_limitworkersr  max_threads_per_fileobjrb   session_kwargs
total_sizekey_noru   r8   r|  key_iteratordownload_keyexecutorresult_iteratorr   contentr   r   r   iter_bucket8  sn   F


	
r  c                 C  r  rt  r   )rx   r   r   r   <lambda>  s    r  )rz  r{  c           
      c  s    d }	 |rt | ||d}nt | |d}|jdi |}z|d }W n	 ty+   Y nw |D ]}|d }	||	r;|	V  q.|dd }|sFd S q)NT)r   PrefixContinuationToken)r   r  Contentsr   NextContinuationTokenr   )rW   list_objects_v2rd   r+   )
ry  r8   rz  r{  ctokenr9   r*   r  cr   r   r   r   r    s*   r  c                C  s   t |d D ]B}z
t||| |d}W n0 tjjyB } z"d|jv r3|jd ddkr3W Y d }~ dS ||kr8 W Y d }~qd }~ww | |f  S d S )Nr   )r8   ry  key_namer|  r    r!   404rA   )r"   _download_fileobjr   r   r)   r*   r+   )r  r8   ry  r  r|  xcontent_bytesr/   r   r   r   r    s$   
r  c                 C  s"   t  }| j||||d | S )N)r   r   Fileobjr  )r   r   download_fileobjr   )r8   ry  r  r|  bufr   r   r   r     s   r  )rv  NNr   rw  r   N)Cr@   
__future__r   rl   r   r;   r  loggingr'   rz   mathr   typingr   r   r   r  botocore.clientr   botocore.exceptionsurllib3.exceptionsr   ImportErrorr5   smart_open.bytebufferrM   smart_open.concurrencysmart_open.utilsr   mypy_boto3_s3.clientr   typing_extensionsr	   	getLoggerr2   r$   rB  ro  rC  rP   rQ   rR   r=  URI_EXAMPLESr   r   r   rF  r6   ra   rp   r   r~   r   r   objectr   r  BufferedIOBaser   r   r   ru  r  r  r  r  r   r   r   r   <module>   s   

'G=&
    X qy
 