U
    W+dn-                     @   s   d dl Zd dlmZ d dlZd dlZd dlm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dS )    N)json)CloudSearchDomainConnectionc                   @   s   e Zd ZdS )SearchServiceExceptionN)__name__
__module____qualname__ r   r   >/tmp/pip-unpacked-wheel-dlxw5sjy/boto/cloudsearch2/document.pyr      s   r   c                   @   s   e Zd ZdZdS )CommitMismatchErrorN)r   r   r   errorsr   r   r   r	   r
   #   s   r
   c                   @   s   e Zd ZdZdS )EncodingErrorz
    Content sent for Cloud Search indexing was incorrectly encoded.

    This usually happens when a document is marked as unicode but non-unicode
    characters are present.
    Nr   r   r   __doc__r   r   r   r	   r   )   s   r   c                   @   s   e Zd ZdZdS )ContentTooLongErrorz
    Content sent for Cloud Search indexing was too long

    This will usually happen when documents queued for indexing add up to more
    than the limit allowed per upload batch (5MB)

    Nr   r   r   r   r	   r   3   s   r   c                   @   sZ   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd ZdS )DocumentServiceConnectiona/  
    A CloudSearch document service.

    The DocumentServiceConection is used to add, remove and update documents in
    CloudSearch. Commands are uploaded to CloudSearch in SDF (Search Document
    Format).

    To generate an appropriate SDF, use :func:`add` to add or update documents,
    as well as :func:`delete` to remove documents.

    Once the set of documents is ready to be index, use :func:`commit` to send
    the commands to CloudSearch.

    If there are a lot of documents to index, it may be preferable to split the
    generation of SDF data and the actual uploading into CloudSearch. Retrieve
    the current SDF with :func:`get_sdf`. If this file is the uploaded into S3,
    it can be retrieved back afterwards for upload into CloudSearch using
    :func:`add_sdf_from_s3`.

    The SDF is not cleared after a :func:`commit`. If you wish to continue
    using the DocumentServiceConnection for another batch upload of commands,
    you will need to :func:`clear_sdf` first to stop the previous batch of
    commands from being uploaded again.

    Nc                 C   s   || _ || _| js|j| _g | _d | _i | _d| _| j r| j jr| j jjr\d| j j	 i| _t
| j jdd| _| jr| j j}t| j|j|j|j|jd| _d S )NFhttpsign_request)hostaws_access_key_idaws_secret_access_keyregionprovider)domainendpointZdoc_service_endpointdocuments_batch_sdfproxyr   layer1	use_proxyZget_proxy_url_with_authgetattrr   r   r   r   r   domain_connection)selfr   r   r   r   r   r	   __init__Y   s*    
z"DocumentServiceConnection.__init__c                 C   s   d||d}| j | dS )aV  
        Add a document to be processed by the DocumentService

        The document will not actually be added until :func:`commit` is called

        :type _id: string
        :param _id: A unique ID used to refer to this document.

        :type fields: dict
        :param fields: A dictionary of key-value pairs to be uploaded .
        add)typeidfieldsNr   append)r!   _idr&   dr   r   r	   r#   u   s    zDocumentServiceConnection.addc                 C   s   d|d}| j | dS )a  
        Schedule a document to be removed from the CloudSearch service

        The document will not actually be scheduled for removal until
        :func:`commit` is called

        :type _id: string
        :param _id: The unique ID of this document.
        delete)r$   r%   Nr'   )r!   r)   r*   r   r   r	   r+      s    
z DocumentServiceConnection.deletec                 C   s   | j r| j S t| jS )z
        Generate the working set of documents in Search Data Format (SDF)

        :rtype: string
        :returns: JSON-formatted string of the documents in SDF
        )r   r   dumpsr   r!   r   r   r	   get_sdf   s    z!DocumentServiceConnection.get_sdfc                 C   s   d| _ g | _dS )z
        Clear the working documents from this DocumentServiceConnection

        This should be used after :func:`commit` if the connection will be
        reused for another set of documents.
        N)r   r   r-   r   r   r	   	clear_sdf   s    z#DocumentServiceConnection.clear_sdfc                 C   s   |  | _dS )a  
        Load an SDF from S3

        Using this method will result in documents added through
        :func:`add` and :func:`delete` being ignored.

        :type key_obj: :class:`boto.s3.key.Key`
        :param key_obj: An S3 key which contains an SDF
        N)Zget_contents_as_stringr   )r!   Zkey_objr   r   r	   add_sdf_from_s3   s    z)DocumentServiceConnection.add_sdf_from_s3c                 C   s   | j |dS )Napplication/json)r    Zupload_documents)r!   sdfapi_versionr   r   r	   _commit_with_auth   s    z+DocumentServiceConnection._commit_with_authc                 C   s`   d| j |f }t }| j|_tjjdddd}|d| |d| |j||dd	id
}|S )Nzhttp://%s/%s/documents/batch   2      )pool_connectionspool_maxsizemax_retrieszhttp://zhttps://zContent-Typer1   )dataheaders)	r   requestsSessionr   proxiesadaptersHTTPAdaptermountpost)r!   r2   r3   urlsessionadapterrespr   r   r	   _commit_without_auth   s    z.DocumentServiceConnection._commit_without_authc                 C   s   |   }d|krBtjd |d}tj||d |d   d}| jr^| jjr^| jjj}| jrr| 	||}n| 
||}t|| || jdS )aD  
        Actually send an SDF to CloudSearch for processing

        If an SDF file has been explicitly loaded it will be used. Otherwise,
        documents added through :func:`add` and :func:`delete` will be used.

        :rtype: :class:`CommitResponse`
        :returns: A summary of documents added and deleted
        z: nullz?null value in sdf detected. This will probably raise 500 error.d   z
2013-01-01)signed_request)r.   botologerrorindexr   r   Z
APIVersionr   r4   rH   CommitResponse)r!   r2   rN   r3   rr   r   r	   commit   s    

z DocumentServiceConnection.commit)NN)r   r   r   r   r"   r#   r+   r.   r/   r0   r4   rH   rQ   r   r   r   r	   r   >   s   

r   c                   @   s"   e Zd ZdZdddZdd ZdS )	rO   an  Wrapper for response to Cloudsearch document batch commit.

    :type response: :class:`requests.models.Response`
    :param response: Response from Cloudsearch /documents/batch API

    :type doc_service: :class:`boto.cloudsearch2.document.DocumentServiceConnection`
    :param doc_service: Object containing the documents posted and methods to
        retry

    :raises: :class:`boto.exception.BotoServerError`
    :raises: :class:`boto.cloudsearch2.document.SearchServiceException`
    :raises: :class:`boto.cloudsearch2.document.EncodingError`
    :raises: :class:`boto.cloudsearch2.document.ContentTooLongError`
    Fc              	   C   s  || _ || _|| _|| _| jr&|| _nV|jd}zt|| _W n8   tj	
d|| j tjj| j jd|dY nX | jd | _| jdkrdd | jd	g D | _| jD ]&}d
|krtdq|dkrtdqng | _| jd | _| jd | _| d| j | d| j d S )Nzutf-8z9Error indexing documents.
Response Content:
{0}

SDF:
{1} )bodystatusrM   c                 S   s   g | ]}| d qS )message)get).0er   r   r	   
<listcomp>  s     z+CommitResponse.__init__.<locals>.<listcomp>r   zIllegal Unicode characterz%Illegal Unicode character in documentzThe Content-Length is too longzContent was too longaddsdeletesr#   r+   )responsedoc_servicer2   rJ   contentdecoder   loadsrK   rL   rM   format	exceptionZBotoServerErrorstatus_coderT   rV   r   r   r   rZ   r[   _check_num_ops)r!   r\   r]   r2   rJ   _bodyrX   r   r   r	   r"      s@    
 



zCommitResponse.__init__c                    sj   t  fdd| jjD }||krf| jr8tj| j ntj| jj t	d
 ||}| j|_|dS )aY  Raise exception if number of ops in response doesn't match commit

        :type type_: str
        :param type_: Type of commit operation: 'add' or 'delete'

        :type response_num: int
        :param response_num: Number of adds or deletes in the response.

        :raises: :class:`boto.cloudsearch2.document.CommitMismatchError`
        c                    s   g | ]}|d   kr|qS )r$   r   )rW   r*   type_r   r	   rY   '  s    z1CommitResponse._check_num_ops.<locals>.<listcomp>z<Incorrect number of {0}s returned. Commit: {1} Response: {2}N)lenr]   r   rJ   rK   rL   debugr\   r^   r
   ra   r   )r!   rg   Zresponse_numZ
commit_numexcr   rf   r	   rd     s      zCommitResponse._check_num_opsN)F)r   r   r   r   r"   rd   r   r   r   r	   rO      s   
$rO   )Zboto.exceptionrK   Zboto.compatr   r=   Zboto.cloudsearchdomain.layer1r   	Exceptionr   r
   r   r   objectr   rO   r   r   r   r	   <module>   s   
 ,