U
    $FZh                     @   s,  d 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	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 ddlmZ ddlmZ dd	lmZ ddlZdd
lmZ ddlmZ ddlmZ dZdZdZ dddddddZ!dZ"dZ#dZ$i Z%dd Z&e&ddddde"efddZ'e&dddde"efddd d!Z(e&d"d"dddddde"ef
dd#d$d%Z)e&d"d"dddd&de"ef	ddd'd(Z*edde"efd&d)d*d+Z+dede"efd,eed-d.d/Z,d0d1 Z-d2d3 Z.d4d5 Z/G d6d7 d7Z0d8d9 Z1d:d; Z2d<d= Z3d>d? Z4d@dA Z5G dBdC dCZ6dS )DzConcurrent media operations.    N)
exceptions)Client)Blob)_get_host_name)_quote)_DEFAULT_TIMEOUT)DEFAULT_RETRY)XMLMPUContainer)
XMLMPUPart)DataCorruptioni      i  @ zCache-ControlzContent-DispositionzContent-EncodingzContent-Languagezx-goog-custom-timezx-goog-storage-class)ZcacheControlZcontentDispositionZcontentEncodingZcontentLanguageZ
customTimeZstorageClassprocessthreadzChecksum mismatch while downloading:

  {}

The object metadata indicated a crc32c checksum of:

  {}

but the actual crc32c checksum of the downloaded contents was:

  {}
c                    s   t   fdd}|S )Nc                     s   t  j| |}|jd}|rz|jd}|jd}|sB|rJtdtd |j} |j	}t
|d< ||d<  | |S  | |S d S )Nthreadsworker_typemax_workerszuThe `threads` parameter is deprecated and conflicts with its replacement parameters, `worker_type` and `max_workers`.zeThe `threads` parameter is deprecated. Please use `worker_type` and `max_workers` parameters instead.)inspect	signaturebind	argumentsget
ValueErrorwarningswarnargskwargsTHREAD)r   r   Zbindingr   r   r   func l/home/aprabhat/apps/x.techxrdev.in/venv/lib/python3.8/site-packages/google/cloud/storage/transfer_manager.pyconvert_threads_or_raiseN   s$    
z:_deprecate_threads_param.<locals>.convert_threads_or_raise)	functoolswraps)r   r!   r   r   r    _deprecate_threads_paramM   s    r$   Fc              
   C   s  |dkri }|r |  }d|d< d|d< t|\}}	||dx}
g }| D ]R\}}|	rft|tsftd||
jt|	r|t|n|t|trdnd	|f| qHt	j
j||t	j
jd
 W 5 Q R X g }|D ]T}| }|r|s|| q|r
|r
t|tjr
|| q||  q|S )aT  Upload many files concurrently via a worker pool.

    :type file_blob_pairs: List(Tuple(IOBase or str, 'google.cloud.storage.blob.Blob'))
    :param file_blob_pairs:
        A list of tuples of a file or filename and a blob. Each file will be
        uploaded to the corresponding blob by using APIs identical to
        `blob.upload_from_file()` or `blob.upload_from_filename()` as
        appropriate.

        File handlers are only supported if worker_type is set to THREAD.
        If worker_type is set to PROCESS, please use filenames only.

    :type skip_if_exists: bool
    :param skip_if_exists:
        If True, blobs that already have a live version will not be overwritten.
        This is accomplished by setting `if_generation_match = 0` on uploads.
        Uploads so skipped will result in a 412 Precondition Failed response
        code, which will be included in the return value but not raised
        as an exception regardless of the value of raise_exception.

    :type upload_kwargs: dict
    :param upload_kwargs:
        A dictionary of keyword arguments to pass to the upload method. Refer
        to the documentation for `blob.upload_from_file()` or
        `blob.upload_from_filename()` for more information. The dict is directly
        passed into the upload methods and is not validated by this function.

    :type threads: int
    :param threads:
        ***DEPRECATED*** Sets `worker_type` to THREAD and `max_workers` to the
        number specified. If `worker_type` or `max_workers` are set explicitly,
        this parameter should be set to None. Please use `worker_type` and
        `max_workers` instead of this parameter.

    :type deadline: int
    :param deadline:
        The number of seconds to wait for all threads to resolve. If the
        deadline is reached, all threads will be terminated regardless of their
        progress and `concurrent.futures.TimeoutError` will be raised. This can
        be left as the default of `None` (no deadline) for most use cases.

    :type raise_exception: bool
    :param raise_exception:
        If True, instead of adding exceptions to the list of return values,
        instead they will be raised. Note that encountering an exception on one
        operation will not prevent other operations from starting. Exceptions
        are only processed and potentially raised after all operations are
        complete in success or failure.

        If skip_if_exists is True, 412 Precondition Failed responses are
        considered part of normal operation and are not raised as an exception.

    :type worker_type: str
    :param worker_type:
        The worker type to use; one of `google.cloud.storage.transfer_manager.PROCESS`
        or `google.cloud.storage.transfer_manager.THREAD`.

        Although the exact performance impact depends on the use case, in most
        situations the PROCESS worker type will use more system resources (both
        memory and CPU) and result in faster operations than THREAD workers.

        Because the subprocesses of the PROCESS worker type can't access memory
        from the main process, Client objects have to be serialized and then
        recreated in each subprocess. The serialization of the Client object
        for use in subprocesses is an approximation and may not capture every
        detail of the Client object, especially if the Client was modified after
        its initial creation or if `Client._http` was modified in any way.

        THREAD worker types are observed to be relatively efficient for
        operations with many small files, but not for operations with large
        files. PROCESS workers are recommended for large file operations.

        PROCESS workers do not support writing to file handlers. Please refer
        to files by filename only when using PROCESS workers.

    :type max_workers: int
    :param max_workers:
        The maximum number of workers to create to handle the workload.

        With PROCESS workers, a larger number of workers will consume more
        system resources (memory and CPU) at once.

        How many workers is optimal depends heavily on the specific use case,
        and the default is a conservative number that should work okay in most
        cases without consuming excessive resources.

    :raises: :exc:`concurrent.futures.TimeoutError` if deadline is exceeded.

    :rtype: list
    :returns: A list of results corresponding to, in order, each item in the
        input list. If an exception was received, it will be the result
        for that operation. Otherwise, the return value from the successful
        upload method is used (which will be None).
    Nr   if_generation_matchztm.upload_manycommandr   Passing in a file object is only supported by the THREAD worker type. Please either select THREAD workers, or pass in filenames only.Z_handle_filename_and_uploadZ_prep_and_do_uploadtimeoutZreturn_when)copy _get_pool_class_and_requirements
isinstancestrr   appendsubmit"_call_method_on_maybe_pickled_blob_pickle_client
concurrentfutureswaitALL_COMPLETED	exceptionr   ZPreconditionFailedresult)file_blob_pairsskip_if_existsupload_kwargsr   deadlineraise_exceptionr   r   
pool_classneeds_picklingexecutorr4   path_or_fileblobresultsfutureexpr   r   r    upload_manyh   sP    i  rF   )r:   c             
   C   s   |dkri }d|d< t |\}}	||d}
g }| D ]n\}}|	rRt|tsRtd|rnt|trntj|rnq4||
jt	|	rt
|n|t|trdnd|f| q4tjj||tjjd W 5 Q R X g }|D ].}|s| }|r|| q||  q|S )	a  Download many blobs concurrently via a worker pool.

    :type blob_file_pairs: List(Tuple('google.cloud.storage.blob.Blob', IOBase or str))
    :param blob_file_pairs:
        A list of tuples of blob and a file or filename. Each blob will be downloaded to the corresponding blob by using APIs identical to blob.download_to_file() or blob.download_to_filename() as appropriate.

        Note that blob.download_to_filename() does not delete the destination file if the download fails.

        File handlers are only supported if worker_type is set to THREAD.
        If worker_type is set to PROCESS, please use filenames only.

    :type download_kwargs: dict
    :param download_kwargs:
        A dictionary of keyword arguments to pass to the download method. Refer
        to the documentation for `blob.download_to_file()` or
        `blob.download_to_filename()` for more information. The dict is directly
        passed into the download methods and is not validated by this function.

    :type threads: int
    :param threads:
        ***DEPRECATED*** Sets `worker_type` to THREAD and `max_workers` to the
        number specified. If `worker_type` or `max_workers` are set explicitly,
        this parameter should be set to None. Please use `worker_type` and
        `max_workers` instead of this parameter.

    :type deadline: int
    :param deadline:
        The number of seconds to wait for all threads to resolve. If the
        deadline is reached, all threads will be terminated regardless of their
        progress and `concurrent.futures.TimeoutError` will be raised. This can
        be left as the default of `None` (no deadline) for most use cases.

    :type raise_exception: bool
    :param raise_exception:
        If True, instead of adding exceptions to the list of return values,
        instead they will be raised. Note that encountering an exception on one
        operation will not prevent other operations from starting. Exceptions
        are only processed and potentially raised after all operations are
        complete in success or failure.

    :type worker_type: str
    :param worker_type:
        The worker type to use; one of `google.cloud.storage.transfer_manager.PROCESS`
        or `google.cloud.storage.transfer_manager.THREAD`.

        Although the exact performance impact depends on the use case, in most
        situations the PROCESS worker type will use more system resources (both
        memory and CPU) and result in faster operations than THREAD workers.

        Because the subprocesses of the PROCESS worker type can't access memory
        from the main process, Client objects have to be serialized and then
        recreated in each subprocess. The serialization of the Client object
        for use in subprocesses is an approximation and may not capture every
        detail of the Client object, especially if the Client was modified after
        its initial creation or if `Client._http` was modified in any way.

        THREAD worker types are observed to be relatively efficient for
        operations with many small files, but not for operations with large
        files. PROCESS workers are recommended for large file operations.

        PROCESS workers do not support writing to file handlers. Please refer
        to files by filename only when using PROCESS workers.

    :type max_workers: int
    :param max_workers:
        The maximum number of workers to create to handle the workload.

        With PROCESS workers, a larger number of workers will consume more
        system resources (memory and CPU) at once.

        How many workers is optimal depends heavily on the specific use case,
        and the default is a conservative number that should work okay in most
        cases without consuming excessive resources.

    :type skip_if_exists: bool
    :param skip_if_exists:
        Before downloading each blob, check if the file for the filename exists;
        if it does, skip that blob.

    :raises: :exc:`concurrent.futures.TimeoutError` if deadline is exceeded.

    :rtype: list
    :returns: A list of results corresponding to, in order, each item in the
        input list. If an exception was received, it will be the result
        for that operation. Otherwise, the return value from the successful
        download method is used (which will be None).
    Nztm.download_manyr&   r'   r(   Z_handle_filename_and_download_prep_and_do_downloadr)   )r,   r-   r.   r   ospathisfiler/   r0   r1   r2   r3   r4   r5   r6   r7   r8   )blob_file_pairsdownload_kwargsr   r<   r=   r   r   r:   r>   r?   r@   r4   rB   rA   rC   rD   rE   r   r   r    download_many  sP    d  
rM    )additional_blob_attributesc             	   C   s   |dkri }|dkri }g }|D ]T}t j||}|| }| j|f|}| D ]\}}t||| qP|||f q t|||||	|
|dS )a  Upload many files concurrently by their filenames.

    The destination blobs are automatically created, with blob names based on
    the source filenames and the blob_name_prefix.

    For example, if the `filenames` include "images/icon.jpg",
    `source_directory` is "/home/myuser/", and `blob_name_prefix` is "myfiles/",
    then the file at "/home/myuser/images/icon.jpg" will be uploaded to a blob
    named "myfiles/images/icon.jpg".

    :type bucket: :class:`google.cloud.storage.bucket.Bucket`
    :param bucket:
        The bucket which will contain the uploaded blobs.

    :type filenames: list(str)
    :param filenames:
        A list of filenames to be uploaded. This may include part of the path.
        The file will be accessed at the full path of `source_directory` +
        `filename`.

    :type source_directory: str
    :param source_directory:
        A string that will be prepended (with `os.path.join()`) to each filename
        in the input list, in order to find the source file for each blob.
        Unlike the filename itself, the source_directory does not affect the
        name of the uploaded blob.

        For instance, if the source_directory is "/tmp/img/" and a filename is
        "0001.jpg", with an empty blob_name_prefix, then the file uploaded will
        be "/tmp/img/0001.jpg" and the destination blob will be "0001.jpg".

        This parameter can be an empty string.

        Note that this parameter allows directory traversal (e.g. "/", "../")
        and is not intended for unsanitized end user input.

    :type blob_name_prefix: str
    :param blob_name_prefix:
        A string that will be prepended to each filename in the input list, in
        order to determine the name of the destination blob. Unlike the filename
        itself, the prefix string does not affect the location the library will
        look for the source data on the local filesystem.

        For instance, if the source_directory is "/tmp/img/", the
        blob_name_prefix is "myuser/mystuff-" and a filename is "0001.jpg" then
        the file uploaded will be "/tmp/img/0001.jpg" and the destination blob
        will be "myuser/mystuff-0001.jpg".

        The blob_name_prefix can be blank (an empty string).

    :type skip_if_exists: bool
    :param skip_if_exists:
        If True, blobs that already have a live version will not be overwritten.
        This is accomplished by setting `if_generation_match = 0` on uploads.
        Uploads so skipped will result in a 412 Precondition Failed response
        code, which will be included in the return value, but not raised
        as an exception regardless of the value of raise_exception.

    :type blob_constructor_kwargs: dict
    :param blob_constructor_kwargs:
        A dictionary of keyword arguments to pass to the blob constructor. Refer
        to the documentation for `blob.Blob()` for more information. The dict is
        directly passed into the constructor and is not validated by this
        function. `name` and `bucket` keyword arguments are reserved by this
        function and will result in an error if passed in here.

    :type upload_kwargs: dict
    :param upload_kwargs:
        A dictionary of keyword arguments to pass to the upload method. Refer
        to the documentation for `blob.upload_from_file()` or
        `blob.upload_from_filename()` for more information. The dict is directly
        passed into the upload methods and is not validated by this function.

    :type threads: int
    :param threads:
        ***DEPRECATED*** Sets `worker_type` to THREAD and `max_workers` to the
        number specified. If `worker_type` or `max_workers` are set explicitly,
        this parameter should be set to None. Please use `worker_type` and
        `max_workers` instead of this parameter.

    :type deadline: int
    :param deadline:
        The number of seconds to wait for all threads to resolve. If the
        deadline is reached, all threads will be terminated regardless of their
        progress and `concurrent.futures.TimeoutError` will be raised. This can
        be left as the default of `None` (no deadline) for most use cases.

    :type raise_exception: bool
    :param raise_exception:
        If True, instead of adding exceptions to the list of return values,
        instead they will be raised. Note that encountering an exception on one
        operation will not prevent other operations from starting. Exceptions
        are only processed and potentially raised after all operations are
        complete in success or failure.

        If skip_if_exists is True, 412 Precondition Failed responses are
        considered part of normal operation and are not raised as an exception.

    :type worker_type: str
    :param worker_type:
        The worker type to use; one of `google.cloud.storage.transfer_manager.PROCESS`
        or `google.cloud.storage.transfer_manager.THREAD`.

        Although the exact performance impact depends on the use case, in most
        situations the PROCESS worker type will use more system resources (both
        memory and CPU) and result in faster operations than THREAD workers.

        Because the subprocesses of the PROCESS worker type can't access memory
        from the main process, Client objects have to be serialized and then
        recreated in each subprocess. The serialization of the Client object
        for use in subprocesses is an approximation and may not capture every
        detail of the Client object, especially if the Client was modified after
        its initial creation or if `Client._http` was modified in any way.

        THREAD worker types are observed to be relatively efficient for
        operations with many small files, but not for operations with large
        files. PROCESS workers are recommended for large file operations.

    :type max_workers: int
    :param max_workers:
        The maximum number of workers to create to handle the workload.

        With PROCESS workers, a larger number of workers will consume more
        system resources (memory and CPU) at once.

        How many workers is optimal depends heavily on the specific use case,
        and the default is a conservative number that should work okay in most
        cases without consuming excessive resources.

    :type additional_blob_attributes: dict
    :param additional_blob_attributes:
        A dictionary of blob attribute names and values. This allows the
        configuration of blobs beyond what is possible with
        blob_constructor_kwargs. For instance, {"cache_control": "no-cache"}
        would set the cache_control attribute of each blob to "no-cache".

        As with blob_constructor_kwargs, this affects the creation of every
        blob identically. To fine-tune each blob individually, use `upload_many`
        and create the blobs as desired before passing them in.

    :raises: :exc:`concurrent.futures.TimeoutError` if deadline is exceeded.

    :rtype: list
    :returns: A list of results corresponding to, in order, each item in the
        input list. If an exception was received, it will be the result
        for that operation. Otherwise, the return value from the successful
        upload method is used (which will be None).
    N)r:   r;   r<   r=   r   r   )rH   rI   joinrB   itemssetattrr/   rF   )bucket	filenamesZsource_directoryblob_name_prefixr:   Zblob_constructor_kwargsr;   r   r<   r=   r   r   rO   r9   filenamerI   	blob_namerB   propvaluer   r   r    upload_many_from_filenames  s,     &rZ   Tc             	   C   sp   g }|D ]P}|| }t j||}|rDt j|\}}t j|dd || ||f qt|||||	|
|dS )a0  Download many files concurrently by their blob names.

    The destination files are automatically created, with paths based on the
    source blob_names and the destination_directory.

    The destination files are not automatically deleted if their downloads fail,
    so please check the return value of this function for any exceptions, or
    enable `raise_exception=True`, and process the files accordingly.

    For example, if the `blob_names` include "icon.jpg", `destination_directory`
    is "/home/myuser/", and `blob_name_prefix` is "images/", then the blob named
    "images/icon.jpg" will be downloaded to a file named
    "/home/myuser/icon.jpg".

    :type bucket: :class:`google.cloud.storage.bucket.Bucket`
    :param bucket:
        The bucket which contains the blobs to be downloaded

    :type blob_names: list(str)
    :param blob_names:
        A list of blobs to be downloaded. The blob name in this string will be
        used to determine the destination file path as well.

        The full name to the blob must be blob_name_prefix + blob_name. The
        blob_name is separate from the blob_name_prefix because the blob_name
        will also determine the name of the destination blob. Any shared part of
        the blob names that need not be part of the destination path should be
        included in the blob_name_prefix.

    :type destination_directory: str
    :param destination_directory:
        A string that will be prepended (with os.path.join()) to each blob_name
        in the input list, in order to determine the destination path for that
        blob.

        For instance, if the destination_directory string is "/tmp/img" and a
        blob_name is "0001.jpg", with an empty blob_name_prefix, then the source
        blob "0001.jpg" will be downloaded to destination "/tmp/img/0001.jpg" .

        This parameter can be an empty string.

        Note that this parameter allows directory traversal (e.g. "/", "../")
        and is not intended for unsanitized end user input.

    :type blob_name_prefix: str
    :param blob_name_prefix:
        A string that will be prepended to each blob_name in the input list, in
        order to determine the name of the source blob. Unlike the blob_name
        itself, the prefix string does not affect the destination path on the
        local filesystem. For instance, if the destination_directory is
        "/tmp/img/", the blob_name_prefix is "myuser/mystuff-" and a blob_name
        is "0001.jpg" then the source blob "myuser/mystuff-0001.jpg" will be
        downloaded to "/tmp/img/0001.jpg". The blob_name_prefix can be blank
        (an empty string).

    :type download_kwargs: dict
    :param download_kwargs:
        A dictionary of keyword arguments to pass to the download method. Refer
        to the documentation for `blob.download_to_file()` or
        `blob.download_to_filename()` for more information. The dict is directly
        passed into the download methods and is not validated by this function.

    :type threads: int
    :param threads:
        ***DEPRECATED*** Sets `worker_type` to THREAD and `max_workers` to the
        number specified. If `worker_type` or `max_workers` are set explicitly,
        this parameter should be set to None. Please use `worker_type` and
        `max_workers` instead of this parameter.

    :type deadline: int
    :param deadline:
        The number of seconds to wait for all threads to resolve. If the
        deadline is reached, all threads will be terminated regardless of their
        progress and `concurrent.futures.TimeoutError` will be raised. This can
        be left as the default of `None` (no deadline) for most use cases.

    :type create_directories: bool
    :param create_directories:
        If True, recursively create any directories that do not exist. For
        instance, if downloading object "images/img001.png", create the
        directory "images" before downloading.

    :type raise_exception: bool
    :param raise_exception:
        If True, instead of adding exceptions to the list of return values,
        instead they will be raised. Note that encountering an exception on one
        operation will not prevent other operations from starting. Exceptions
        are only processed and potentially raised after all operations are
        complete in success or failure. If skip_if_exists is True, 412
        Precondition Failed responses are considered part of normal operation
        and are not raised as an exception.

    :type worker_type: str
    :param worker_type:
        The worker type to use; one of `google.cloud.storage.transfer_manager.PROCESS`
        or `google.cloud.storage.transfer_manager.THREAD`.

        Although the exact performance impact depends on the use case, in most
        situations the PROCESS worker type will use more system resources (both
        memory and CPU) and result in faster operations than THREAD workers.

        Because the subprocesses of the PROCESS worker type can't access memory
        from the main process, Client objects have to be serialized and then
        recreated in each subprocess. The serialization of the Client object
        for use in subprocesses is an approximation and may not capture every
        detail of the Client object, especially if the Client was modified after
        its initial creation or if `Client._http` was modified in any way.

        THREAD worker types are observed to be relatively efficient for
        operations with many small files, but not for operations with large
        files. PROCESS workers are recommended for large file operations.

    :type max_workers: int
    :param max_workers:
        The maximum number of workers to create to handle the workload.

        With PROCESS workers, a larger number of workers will consume more
        system resources (memory and CPU) at once.

        How many workers is optimal depends heavily on the specific use case,
        and the default is a conservative number that should work okay in most
        cases without consuming excessive resources.

    :type skip_if_exists: bool
    :param skip_if_exists:
        Before downloading each blob, check if the file for the filename exists;
        if it does, skip that blob. This only works for filenames.

    :raises: :exc:`concurrent.futures.TimeoutError` if deadline is exceeded.

    :rtype: list
    :returns: A list of results corresponding to, in order, each item in the
        input list. If an exception was received, it will be the result
        for that operation. Otherwise, the return value from the successful
        download method is used (which will be None).
    T)exist_ok)rL   r<   r=   r   r   r:   )rH   rI   rP   splitmakedirsr/   rB   rM   )rS   Z
blob_namesZdestination_directoryrU   rL   r   r<   Zcreate_directoriesr=   r   r   r:   rK   rW   Zfull_blob_namerI   	directory_r   r   r    download_many_to_pathZ  s$     r`   )crc32c_checksumc                C   s  | j }|dkri }d|ks"d|kr*tdd|kr:td| }d|d< d|d< | jr^| jsf|   t|\}	}
|
r~t| n| }g }t|d	}W 5 Q R X |	|d
d}d}| j}||k r|}t	|| |}|
|jt||||d ||d qtjj||tjjd W 5 Q R X g }|D ]}|
|  q|r|rt|}t|d}| j}||kr| j||d|d|d|dd}tdt|||dS )a:  Download a single file in chunks, concurrently.

    In some environments, using this feature with mutiple processes will result
    in faster downloads of large files.

    Using this feature with multiple threads is unlikely to improve download
    performance under normal circumstances due to Python interpreter threading
    behavior. The default is therefore to use processes instead of threads.

    :type blob: :class:`google.cloud.storage.blob.Blob`
    :param blob:
        The blob to be downloaded.

    :type filename: str
    :param filename:
        The destination filename or path.

    :type chunk_size: int
    :param chunk_size:
        The size in bytes of each chunk to send. The optimal chunk size for
        maximum throughput may vary depending on the exact network environment
        and size of the blob.

    :type download_kwargs: dict
    :param download_kwargs:
        A dictionary of keyword arguments to pass to the download method. Refer
        to the documentation for `blob.download_to_file()` or
        `blob.download_to_filename()` for more information. The dict is directly
        passed into the download methods and is not validated by this function.

        Keyword arguments "start" and "end" which are not supported and will
        cause a ValueError if present. The key "checksum" is also not supported
        in `download_kwargs`, but see the argument `crc32c_checksum` (which does
        not go in `download_kwargs`) below.

    :type deadline: int
    :param deadline:
        The number of seconds to wait for all threads to resolve. If the
        deadline is reached, all threads will be terminated regardless of their
        progress and `concurrent.futures.TimeoutError` will be raised. This can
        be left as the default of `None` (no deadline) for most use cases.

    :type worker_type: str
    :param worker_type:
        The worker type to use; one of `google.cloud.storage.transfer_manager.PROCESS`
        or `google.cloud.storage.transfer_manager.THREAD`.

        Although the exact performance impact depends on the use case, in most
        situations the PROCESS worker type will use more system resources (both
        memory and CPU) and result in faster operations than THREAD workers.

        Because the subprocesses of the PROCESS worker type can't access memory
        from the main process, Client objects have to be serialized and then
        recreated in each subprocess. The serialization of the Client object
        for use in subprocesses is an approximation and may not capture every
        detail of the Client object, especially if the Client was modified after
        its initial creation or if `Client._http` was modified in any way.

        THREAD worker types are observed to be relatively efficient for
        operations with many small files, but not for operations with large
        files. PROCESS workers are recommended for large file operations.

    :type max_workers: int
    :param max_workers:
        The maximum number of workers to create to handle the workload.

        With PROCESS workers, a larger number of workers will consume more
        system resources (memory and CPU) at once.

        How many workers is optimal depends heavily on the specific use case,
        and the default is a conservative number that should work okay in most
        cases without consuming excessive resources.

    :type crc32c_checksum: bool
    :param crc32c_checksum:
        Whether to compute a checksum for the resulting object, using the crc32c
        algorithm. As the checksums for each chunk must be combined using a
        feature of crc32c that is not available for md5, md5 is not supported.

    :raises:
        :exc:`concurrent.futures.TimeoutError`
            if deadline is exceeded.
        :exc:`google.cloud.storage._media.common.DataCorruption`
            if the download's checksum doesn't agree with server-computed
            checksum. The `google.cloud.storage._media` exception is used here for
            consistency with other download methods despite the exception
            originating elsewhere.
    NstartendzWDownload arguments 'start' and 'end' are not supported by download_chunks_concurrently.checksumz'checksum' is in download_kwargs, but is not supported because sliced downloads have a different checksum mechanism from regular downloads. Use the 'crc32c_checksum' argument on download_chunks_concurrently instead.ztm.download_shardedr&   wbr'   r      )rb   rc   rL   ra   r)   zutf-8r%   if_generation_not_matchif_metageneration_matchif_metageneration_not_match)r%   rg   rh   ri   )clientr   r+   sizeZ
generationreloadr,   r2   openminr/   r0   "_download_and_write_chunk_in_placer3   r4   r5   r6   r8   '_digest_ordered_checksum_and_size_pairsbase64	b64encodedecodeZcrc32cZ_get_download_urlr   r   !DOWNLOAD_CRC32C_MISMATCH_TEMPLATEformat)rB   rV   
chunk_sizerL   r<   r   r   ra   rj   r>   r?   maybe_pickled_blobr4   r_   r@   cursorrc   rb   rC   rD   
crc_digestZactual_checksumZexpected_checksumdownload_urlr   r   r    download_chunks_concurrently  s    c
  
	  r{   auto)rd   r*   retryc                 C   s  |j }
|j}||}t|j}dj||
jt|jd}|j||| dd\}}}|t	|}|j
dk	rp|j
|d< |jdk	rd|jkr|j|d< t|| ||	d	}|j||d
 |j}tj| }||   }t|\}}|rt|n|}g }||dr}td|d D ]F}|d | }t|| |}||jt|||| ||||||	d qtjj||tjjd W 5 Q R X z8|D ]}| \}}||| qr||| W n( t k
r   |!||  Y nX dS )am  Upload a single file in chunks, concurrently.

    This function uses the XML MPU API to initialize an upload and upload a
    file in chunks, concurrently with a worker pool.

    The XML MPU API is significantly different from other uploads; please review
    the documentation at `https://cloud.google.com/storage/docs/multipart-uploads`
    before using this feature.

    The library will attempt to cancel uploads that fail due to an exception.
    If the upload fails in a way that precludes cancellation, such as a
    hardware failure, process termination, or power outage, then the incomplete
    upload may persist indefinitely. To mitigate this, set the
    `AbortIncompleteMultipartUpload` with a nonzero `Age` in bucket lifecycle
    rules, or refer to the XML API documentation linked above to learn more
    about how to list and delete individual downloads.

    Using this feature with multiple threads is unlikely to improve upload
    performance under normal circumstances due to Python interpreter threading
    behavior. The default is therefore to use processes instead of threads.

    ACL information cannot be sent with this function and should be set
    separately with :class:`ObjectACL` methods.

    :type filename: str
    :param filename:
        The path to the file to upload. File-like objects are not supported.

    :type blob: :class:`google.cloud.storage.blob.Blob`
    :param blob:
        The blob to which to upload.

    :type content_type: str
    :param content_type: (Optional) Type of content being uploaded.

    :type chunk_size: int
    :param chunk_size:
        The size in bytes of each chunk to send. The optimal chunk size for
        maximum throughput may vary depending on the exact network environment
        and size of the blob. The remote API has restrictions on the minimum
        and maximum size allowable, see: `https://cloud.google.com/storage/quotas#requests`

    :type deadline: int
    :param deadline:
        The number of seconds to wait for all threads to resolve. If the
        deadline is reached, all threads will be terminated regardless of their
        progress and `concurrent.futures.TimeoutError` will be raised. This can
        be left as the default of `None` (no deadline) for most use cases.

    :type worker_type: str
    :param worker_type:
        The worker type to use; one of `google.cloud.storage.transfer_manager.PROCESS`
        or `google.cloud.storage.transfer_manager.THREAD`.

        Although the exact performance impact depends on the use case, in most
        situations the PROCESS worker type will use more system resources (both
        memory and CPU) and result in faster operations than THREAD workers.

        Because the subprocesses of the PROCESS worker type can't access memory
        from the main process, Client objects have to be serialized and then
        recreated in each subprocess. The serialization of the Client object
        for use in subprocesses is an approximation and may not capture every
        detail of the Client object, especially if the Client was modified after
        its initial creation or if `Client._http` was modified in any way.

        THREAD worker types are observed to be relatively efficient for
        operations with many small files, but not for operations with large
        files. PROCESS workers are recommended for large file operations.

    :type max_workers: int
    :param max_workers:
        The maximum number of workers to create to handle the workload.

        With PROCESS workers, a larger number of workers will consume more
        system resources (memory and CPU) at once.

        How many workers is optimal depends heavily on the specific use case,
        and the default is a conservative number that should work okay in most
        cases without consuming excessive resources.

    :type checksum: str
    :param checksum:
        (Optional) The checksum scheme to use: either "md5", "crc32c", "auto"
        or None. The default is "auto", which will try to detect if the C
        extension for crc32c is installed and fall back to md5 otherwise.
        Each individual part is checksummed. At present, the selected
        checksum rule is only applied to parts and a separate checksum of the
        entire resulting blob is not computed. Please compute and compare the
        checksum of the file to the resulting blob separately if needed, using
        the "crc32c" algorithm as per the XML MPU documentation.

    :type timeout: float or tuple
    :param timeout:
        (Optional) The amount of time, in seconds, to wait
        for the server response.  See: :ref:`configuring_timeouts`

    :type retry: google.api_core.retry.Retry
    :param retry: (Optional) How to retry the RPC. A None value will disable
        retries. A `google.api_core.retry.Retry` value will enable retries,
        and the object will configure backoff and timeout options. Custom
        predicates (customizable error codes) are not supported for media
        operations such as this one.

        This function does not accept `ConditionalRetryPolicy` values because
        preconditions are not supported by the underlying API call.

        See the retry.py source code and docstrings in this package
        (`google.cloud.storage.retry`) for information on retry types and how
        to configure them.

    :raises: :exc:`concurrent.futures.TimeoutError` if deadline is exceeded.
    z{hostname}/{bucket}/{blob})hostnamerS   rB   ztm.upload_sharded)rV   r&   Nzx-goog-user-projectZcryptoKeyVersionszx-goog-encryption-kms-key-name)headersr}   )	transportcontent_typer'   rf   rb   rc   part_numberrd   r   r}   r)   )"rS   rj   Z_get_transportr   _connectionru   namer   Z_get_upload_arguments_headers_from_metadataZuser_projectZkms_key_namer	   Zinitiate	upload_idrH   rI   getsizer,   r2   rangern   r/   r0   _upload_partr3   r4   r5   r6   r8   Zregister_partfinalize	Exceptioncancel) rV   rB   r   rv   r<   r   r   rd   r*   r}   rS   rj   r   r~   urlbase_headersZobject_metadatar   	containerr   rk   Znum_of_partsr>   r?   maybe_pickled_clientr4   r@   r   rb   rc   rD   etagr   r   r    upload_chunks_concurrently  sx    ~

     


  r   c
                 C   sJ   t | tr| }
n
t| }
t|||||||||	d	}||
j ||jfS )zHelper function that runs inside a thread or subprocess to upload a part.

    `maybe_pickled_client` is either a Client (for threads) or a specially
    pickled Client (for processes) because the default pickling mangles Client
    objects.r   )r-   r   pickleloadsr
   upload_httpr   )r   r   r   rV   rb   rc   r   rd   r   r}   rj   partr   r   r    r     s     

r   c                 C   sX   i }|   D ]\}}|tkr||t| < qd| krT| d   D ]\}}||d| < q>|S )zFHelper function to translate object metadata into a header dictionary.metadatazx-goog-meta-)rQ   METADATA_HEADER_TRANSLATION)r   r   keyrY   r   r   r    r     s    r   c              
   C   sh   t | tr| }n
t| }t|||8}|j|f||d| |j|| d fW  5 Q R  S Q R X dS )a<  Helper function that runs inside a thread or subprocess.

    `maybe_pickled_blob` is either a Blob (for threads) or a specially pickled
    Blob (for processes) because the default pickling mangles Client objects
    which are attached to Blobs.

    Returns a crc if configured (or None) and the size written.
    )rb   rc   rf   N)r-   r   r   r   _ChecksummingSparseFileWrapperrG   crc)rw   rV   rb   rc   rL   ra   rB   fr   r   r    ro     s    

ro   c                   @   s<   e Zd ZdZdd Zdd Zedd Zdd	 Zd
d Z	dS )r   zA file wrapper that writes to a sparse file and optionally checksums.

    This wrapper only implements write() and does not inherit from `io` module
    base classes.
    c                 C   s(   t |d| _| j| d | _|| _d S )Nzrb+)rm   r   seek_crc_crc32c_enabled)selfrV   Zstart_positionZcrc32c_enabledr   r   r    __init__  s    z'_ChecksummingSparseFileWrapper.__init__c                 C   s>   | j r.| jd krt|| _nt| j|| _| j| d S N)r   r   google_crc32crY   extendr   write)r   chunkr   r   r    r     s
    
z$_ChecksummingSparseFileWrapper.writec                 C   s   | j S r   )r   r   r   r   r    r     s    z"_ChecksummingSparseFileWrapper.crcc                 C   s   | S r   r   r   r   r   r    	__enter__  s    z(_ChecksummingSparseFileWrapper.__enter__c                 C   s   | j   d S r   )r   close)r   exc_type	exc_valuetbr   r   r    __exit__  s    z'_ChecksummingSparseFileWrapper.__exit__N)
__name__
__module____qualname____doc__r   r   propertyr   r   r   r   r   r   r    r     s   
r   c                 O   s*   t | tr| }n
t| }t||||S )zHelper function that runs inside a thread or subprocess.

    `maybe_pickled_blob` is either a Blob (for threads) or a specially pickled
    Blob (for processes) because the default pickling mangles Client objects
    which are attached to Blobs.)r-   r   r   r   getattr)rw   method_namer   r   rB   r   r   r    r1     s    	

r1   c                 C   s@   t | }| j}| j}d}| j}| j}| j}t|||||||ffS )zReplicate a Client by constructing a new one with the same params.

    LazyClient performs transparent caching for when the same client is needed
    on the same process multiple times.N)idprojectZ_credentialsZ_initial_client_infoZ_initial_client_options_extra_headers_LazyClient)clZclient_object_idr   credentialsr   Zclient_infoZclient_optionsextra_headersr   r   r    _reduce_client  s     r   c                 C   s:   t  }t|}tj |_t|jt< |	|  |
 S )z=Pickle a Client or an object that owns a Client (like a Blob))ioBytesIOr   Picklercopyregdispatch_tabler+   r   r   dumpgetvalue)objr   pr   r   r    r2     s    	


r2   c                 C   s4   | t krtjjdfS | tkr(tjjdfS tddS )zDReturns the pool class, and whether the pool requires pickled Blobs.TFzuThe worker_type must be google.cloud.storage.transfer_manager.PROCESS or google.cloud.storage.transfer_manager.THREADN)PROCESSr3   r4   ProcessPoolExecutorr   ZThreadPoolExecutorr   )r   r   r   r    r,   -  s    r,   c                 C   s   d }t t}| D ]b\}}|s"|}q|dN }d}||k rbt|| t}t||d | }||7 }q.|dN }||N }qtd|}|S )Nl    r   z>L)bytesMAX_CRC32C_ZERO_ARRAY_SIZErn   r   r   structpack)Zchecksum_and_size_pairsZbase_crcZzeroesZpart_crcrk   paddedZdesired_zeroes_sizery   r   r   r    rp   <  s$    

 rp   c                   @   s   e Zd ZdZdd ZdS )r   zBAn object that will transform into either a cached or a new Clientc                 O   s,   t |}|r|S t||}|t |< |S d S r   )_cached_clientsr   r   )clsr   r   r   Zcached_clientr   r   r    __new__Y  s    

z_LazyClient.__new__N)r   r   r   r   r   r   r   r   r    r   V  s   r   )7r   concurrent.futuresr3   r   r   rH   r   r   r   r   rq   r"   Zgoogle.api_corer   Zgoogle.cloud.storager   r   Zgoogle.cloud.storage.blobr   r   Zgoogle.cloud.storage.constantsr   Zgoogle.cloud.storage.retryr   r   Z+google.cloud.storage._media.requests.uploadr	   r
   Zgoogle.cloud.storage.exceptionsr   ZTM_DEFAULT_CHUNK_SIZEZDEFAULT_MAX_WORKERSr   r   r   r   rt   r   r$   rF   rM   rZ   r`   r{   r   r   r   ro   r   r1   r   r2   r,   rp   r   r   r   r   r    <module>   s   
 	  ? 0	 ;	 K%!