o
    NDik                     @   sp  d dl mZ d dlmZ d dlmZmZmZmZ d dl	Z	d dl
mZmZ d dlmZ d dlZd dlZe	eZd dlmZ eZd dlmZ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G dd deZ G dd deZ!G dd deZ"G dd de"Z#G dd deZ$G dd  d e$Z%G d!d" d"e$Z&G d#d$ d$eZ'G d%d& d&e'Z(G d'd( d(e'Z)G d)d* d*eZ*G d+d, d,e*Z+G d-d. d.e*Z,G d/d0 d0eZ-G d1d2 d2eZ.G d3d4 d4e.Z/G d5d6 d6e-Z0G d7d8 d8e-Z1G d9d: d:eZ2G d;d< d<e2Z3G d=d> d>e3Z4G d?d@ d@e'Z5edAg dBZ6G dCdD dDeZ7dS )E    )
namedtuple)	lru_cache)islicecyclegroupbyrepeatN)randintshuffle)Lock)	WriteType)ConsistencyLevelOperationTimedOutc                   @   s    e Zd ZdZdZ	 dZ	 dZdS )HostDistancez
    A measure of how "distant" a node is from the client, which
    may influence how the load balancer distributes requests
    and how many connections are opened to the node.
    r      N)__name__
__module____qualname____doc__IGNOREDLOCALREMOTE r   r   K/var/www/Datamplify/venv/lib/python3.10/site-packages/cassandra/policies.pyr   #   s    
r   c                   @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
HostStateListenerc                 C      t  )z" Called when a node is marked up. NotImplementedErrorselfhostr   r   r   on_upI      zHostStateListener.on_upc                 C   r   )z$ Called when a node is marked down. r   r   r   r   r   on_downM   r"   zHostStateListener.on_downc                 C   r   )zt
        Called when a node is added to the cluster.  The newly added node
        should be considered up.
        r   r   r   r   r   on_addQ      zHostStateListener.on_addc                 C   r   )z1 Called when a node is removed from the cluster. r   r   r   r   r   	on_removeX   r"   zHostStateListener.on_removeN)r   r   r   r!   r#   r$   r&   r   r   r   r   r   G   s
    r   c                   @   s>   e Zd ZdZdZdd Zdd Zdd Zdd	d
Zdd Z	dS )LoadBalancingPolicya  
    Load balancing policies are used to decide how to distribute
    requests among all possible coordinator nodes in the cluster.

    In particular, they may focus on querying "near" nodes (those
    in a local datacenter) or on querying nodes who happen to
    be replicas for the requested data.

    You may also use subclasses of :class:`.LoadBalancingPolicy` for
    custom behavior.
    Nc                 C   s   t  | _d S N)r
   _hosts_lockr   r   r   r   __init__l      zLoadBalancingPolicy.__init__c                 C   r   )z
        Returns a measure of how remote a :class:`~.pool.Host` is in
        terms of the :class:`.HostDistance` enums.
        r   r   r   r   r   distanceo   r%   zLoadBalancingPolicy.distancec                 C   r   )z
        This method is called to initialize the load balancing
        policy with a set of :class:`.Host` instances before its
        first use.  The `cluster` parameter is an instance of
        :class:`.Cluster`.
        r   r   clusterhostsr   r   r   populatev      zLoadBalancingPolicy.populatec                 C   r   )a  
        Given a :class:`~.query.Statement` instance, return a iterable
        of :class:`.Host` instances which should be queried in that
        order.  A generator may work well for custom implementations
        of this method.

        Note that the `query` argument may be :const:`None` when preparing
        statements.

        `working_keyspace` should be the string name of the current keyspace,
        as set through :meth:`.Session.set_keyspace()` or with a ``USE``
        statement.
        r   )r   working_keyspacequeryr   r   r   make_query_plan   s   z#LoadBalancingPolicy.make_query_planc                 C      dS )a  
        This will be called after the cluster Metadata has been initialized.
        If the load balancing policy implementation cannot be supported for
        some reason (such as a missing C extension), this is the point at
        which it should raise an exception.
        Nr   r*   r   r   r   check_supported   s   z#LoadBalancingPolicy.check_supportedNN)
r   r   r   r   r)   r+   r-   r1   r5   r7   r   r   r   r   r'   ]   s    
	r'   c                   @   sV   e Zd ZdZedZdZdd Zdd Zdd	d
Z	dd Z
dd Zdd Zdd ZdS )RoundRobinPolicyz
    A subclass of :class:`.LoadBalancingPolicy` which evenly
    distributes queries across all nodes in the cluster,
    regardless of what datacenter the nodes may be in.
    r   r   c                 C   s2   t || _t|dkrtdt|d | _d S d S )Nr   r   )	frozenset_live_hostslenr   	_positionr.   r   r   r   r1      s   
zRoundRobinPolicy.populatec                 C   s   t jS r(   )r   r   r   r   r   r   r-         zRoundRobinPolicy.distanceNc                 C   sF   | j }|  j d7  _ | j}t|}|r!||; }tt|||| S g S )Nr   )r=   r;   r<   r   r   )r   r3   r4   posr0   lengthr   r   r   r5      s   z RoundRobinPolicy.make_query_planc                 C   <   | j  | j|f| _W d    d S 1 sw   Y  d S r(   r)   r;   unionr   r   r   r   r!         "zRoundRobinPolicy.on_upc                 C   rA   r(   r)   r;   
differencer   r   r   r   r#      rD   zRoundRobinPolicy.on_downc                 C   rA   r(   rB   r   r   r   r   r$      rD   zRoundRobinPolicy.on_addc                 C   rA   r(   rE   r   r   r   r   r&      rD   zRoundRobinPolicy.on_remover8   )r   r   r   r   r:   r;   r=   r1   r-   r5   r!   r#   r$   r&   r   r   r   r   r9      s    
r9   c                   @   sd   e Zd ZdZdZdZdddZdd Zd	d
 Zdd Z	dddZ
dd Zdd Zdd Zdd ZdS )DCAwareRoundRobinPolicyz
    Similar to :class:`.RoundRobinPolicy`, but prefers hosts
    in the local datacenter and only uses nodes in remote
    datacenters as a last resort.
    Nr    c                 C   s,   || _ || _i | _d| _g | _t|  dS )a  
        The `local_dc` parameter should be the name of the datacenter
        (such as is reported by ``nodetool ring``) that should
        be considered local. If not specified, the driver will choose
        a local_dc based on the first host among :attr:`.Cluster.contact_points`
        having a valid DC. If relying on this mechanism, all specified
        contact points should be nodes in a single, local DC.

        `used_hosts_per_remote_dc` controls how many nodes in
        each remote datacenter will have connections opened
        against them. In other words, `used_hosts_per_remote_dc` hosts
        will be considered :attr:`~.HostDistance.REMOTE` and the
        rest will be considered :attr:`~.HostDistance.IGNORED`.
        By default, all remote hosts are ignored.
        r   N)local_dcused_hosts_per_remote_dc_dc_live_hostsr=   
_endpointsr'   r+   )r   rI   rJ   r   r   r   r+      s   z DCAwareRoundRobinPolicy.__init__c                 C   s   |j p| jS r(   )
datacenterrI   r   r   r   r   _dc   r,   zDCAwareRoundRobinPolicy._dcc                    sl   t | fddD ]\}}tt| j|< q	 js#dd |jD  _|r1tdt|d  _	d S d _	d S )Nc                    s
     | S r(   )rN   )hr*   r   r   <lambda>   s   
 z2DCAwareRoundRobinPolicy.populate.<locals>.<lambda>c                 S   s   g | ]}|qS r   r   ).0endpointr   r   r   
<listcomp>   s    z4DCAwareRoundRobinPolicy.populate.<locals>.<listcomp>r   r   )
r   tuplesetrK   rI   endpoints_resolvedrL   r   r<   r=   )r   r/   r0   dcdc_hostsr   r*   r   r1      s   &z DCAwareRoundRobinPolicy.populatec                 C   s^   |  |}|| jkrtjS | jstjS | j|}|stjS |t|d | j v r,tj	S tjS r(   )
rN   rI   r   r   rJ   r   rK   getlistr   )r   r    rW   rX   r   r   r   r-      s   

z DCAwareRoundRobinPolicy.distancec           	      #   s     j }  j d7  _  j jd}|r|t| nd}tt|||t| D ]}|V  q) fdd j  D }|D ]} j|d}|d  j	 D ]}|V  qOq?d S )Nr   r   r   c                    s   g | ]	}| j kr|qS r   )rI   )rQ   rW   r*   r   r   rS     s    z;DCAwareRoundRobinPolicy.make_query_plan.<locals>.<listcomp>)
r=   rK   rY   rI   r<   r   r   copykeysrJ   )	r   r3   r4   r?   
local_liver    	other_dcsrW   remote_liver   r*   r   r5   	  s   z'DCAwareRoundRobinPolicy.make_query_planc                 C   s   | j s|jr|j| jv r|j| _ td| j |jf  | `| |}| j$ | j	|d}||vrA||f | j|< W d    d S W d    d S 1 sLw   Y  d S )NzUsing datacenter '%s' for DCAwareRoundRobinPolicy (via host '%s'); if incorrect, please specify a local_dc to the constructor, or limit contact points to local cluster nodesr   )
rI   rM   rR   rL   loginforN   r)   rK   rY   )r   r    rW   current_hostsr   r   r   r!     s   

"zDCAwareRoundRobinPolicy.on_upc                    s   |   }| j; | j|d} |v r3t fdd|D }|r'|| j|< n| j|= W d    d S W d    d S W d    d S 1 sFw   Y  d S )Nr   c                 3   s    | ]	}| kr|V  qd S r(   r   rQ   rO   r    r   r   	<genexpr>2  s    z2DCAwareRoundRobinPolicy.on_down.<locals>.<genexpr>)rN   r)   rK   rY   rT   )r   r    rW   rb   r0   r   rd   r   r#   -  s   

"zDCAwareRoundRobinPolicy.on_downc                 C      |  | d S r(   )r!   r   r   r   r   r$   8     zDCAwareRoundRobinPolicy.on_addc                 C   rf   r(   )r#   r   r   r   r   r&   ;  rg   z!DCAwareRoundRobinPolicy.on_remove)rH   r   r8   )r   r   r   r   rI   rJ   r+   rN   r1   r-   r5   r!   r#   r$   r&   r   r   r   r   rG      s    

rG   c                   @   sj   e Zd ZdZdZdZdZ	 dddZdd Zdd	 Z	d
d Z
dddZdd Zdd Zdd Zdd ZdS )TokenAwarePolicya  
    A :class:`.LoadBalancingPolicy` wrapper that adds token awareness to
    a child policy.

    This alters the child policy's behavior so that it first attempts to
    send queries to :attr:`~.HostDistance.LOCAL` replicas (as determined
    by the child policy) based on the :class:`.Statement`'s
    :attr:`~.Statement.routing_key`. If :attr:`.shuffle_replicas` is
    truthy, these replicas will be yielded in a random order. Once those
    hosts are exhausted, the remaining hosts in the child policy's query
    plan will be used in the order provided by the child policy.

    If no :attr:`~.Statement.routing_key` is set on the query, the child
    policy's query plan will be used as is.
    NFc                 C      || _ || _d S r(   )_child_policyshuffle_replicas)r   child_policyrk   r   r   r   r+   W     
zTokenAwarePolicy.__init__c                 C      |j | _| j|| d S r(   metadata_cluster_metadatarj   r1   r.   r   r   r   r1   [     zTokenAwarePolicy.populatec                 C   s&   | j  std| jj| j jf d S )Nz%s cannot be used with the cluster partitioner (%s) because the relevant C extension for this driver was not compiled. See the installation instructions for details on building and installing the C extensions.)rq   can_support_partitionerRuntimeError	__class__r   partitionerr*   r   r   r   r7   _  s   
z TokenAwarePolicy.check_supportedc                 O      | j j|i |S r(   rj   r-   r   argskwargsr   r   r   r-   h     zTokenAwarePolicy.distancec           	      c   s    |r
|j r
|j }n|}| j}|d u r!|||D ]}|V  qd S |j}|d u s,|d u r:|||D ]}|V  q2d S | j||}| jrHt| |D ]}|jrZ|	|t
jkrZ|V  qJ|||D ]}||vso|	|t
jkrr|V  qad S r(   )keyspacerj   r5   routing_keyrq   get_replicasrk   r	   is_upr-   r   r   r   )	r   r3   r4   r}   childr    r~   replicasreplicar   r   r   r5   k  s8   
z TokenAwarePolicy.make_query_planc                 O   rw   r(   rj   r!   ry   r   r   r   r!     r|   zTokenAwarePolicy.on_upc                 O   rw   r(   rj   r#   ry   r   r   r   r#     r|   zTokenAwarePolicy.on_downc                 O   rw   r(   rj   r$   ry   r   r   r   r$     r|   zTokenAwarePolicy.on_addc                 O   rw   r(   rj   r&   ry   r   r   r   r&     r|   zTokenAwarePolicy.on_remove)Fr8   )r   r   r   r   rj   rq   rk   r+   r1   r7   r-   r5   r!   r#   r$   r&   r   r   r   r   rh   ?  s    
	
rh   c                   @   8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )WhiteListRoundRobinPolicya  
    A subclass of :class:`.RoundRobinPolicy` which evenly
    distributes queries across all nodes in the cluster,
    regardless of what datacenter the nodes may be in, but
    only if that node exists in the list of allowed nodes

    This policy is addresses the issue described in
    https://datastax-oss.atlassian.net/browse/JAVA-145
    Where connection errors occur when connection
    attempts are made to private IP addresses remotely
    c                 C   s*   t || _dd | jD | _t|  dS )zg
        The `hosts` parameter should be a sequence of hosts to permit
        connections to.
        c                 S   s2   g | ]}t |d t jt jD ]}|d d qqS )N   r   )socketgetaddrinfo	AF_UNSPECSOCK_STREAM)rQ   arR   r   r   r   rS     s
    z6WhiteListRoundRobinPolicy.__init__.<locals>.<listcomp>N)rT   _allowed_hosts_allowed_hosts_resolvedr9   r+   )r   r0   r   r   r   r+     s   
z"WhiteListRoundRobinPolicy.__init__c                    sF   t  fdd|D  _t|dkrd _d S tdt|d  _d S )Nc                 3   s     | ]}|j  jv r|V  qd S r(   )addressr   rc   r*   r   r   re     s    z5WhiteListRoundRobinPolicy.populate.<locals>.<genexpr>r   r   )r:   r;   r<   r=   r   r.   r   r*   r   r1     s   
z"WhiteListRoundRobinPolicy.populatec                 C   s   |j | jv r	tjS tjS r(   )r   r   r   r   r   r   r   r   r   r-     s   z"WhiteListRoundRobinPolicy.distancec                 C       |j | jv rt| | d S d S r(   )r   r   r9   r!   r   r   r   r   r!        zWhiteListRoundRobinPolicy.on_upc                 C   r   r(   )r   r   r9   r$   r   r   r   r   r$     r   z WhiteListRoundRobinPolicy.on_addN)	r   r   r   r   r+   r1   r-   r!   r$   r   r   r   r   r     s    r   c                       sn   e Zd ZdZ fddZdd Zdd Zdd	 Zd
d Ze	dd Z
dd Zdd ZdddZdd Z  ZS )HostFilterPolicyal  
    A :class:`.LoadBalancingPolicy` subclass configured with a child policy,
    and a single-argument predicate. This policy defers to the child policy for
    hosts where ``predicate(host)`` is truthy. Hosts for which
    ``predicate(host)`` is falsy will be considered :attr:`.IGNORED`, and will
    not be used in a query plan.

    This can be used in the cases where you need a whitelist or blacklist
    policy, e.g. to prepare for decommissioning nodes or for testing:

    .. code-block:: python

        def address_is_ignored(host):
            return host.address in [ignored_address0, ignored_address1]

        blacklist_filter_policy = HostFilterPolicy(
            child_policy=RoundRobinPolicy(),
            predicate=address_is_ignored
        )

        cluster = Cluster(
            primary_host,
            load_balancing_policy=blacklist_filter_policy,
        )

    See the note in the :meth:`.make_query_plan` documentation for a caveat on
    how wrapping ordering polices (e.g. :class:`.RoundRobinPolicy`) may break
    desirable properties of the wrapped policy.

    Please note that whitelist and blacklist policies are not recommended for
    general, day-to-day use. You probably want something like
    :class:`.DCAwareRoundRobinPolicy`, which prefers a local DC but has
    fallbacks, over a brute-force method like whitelisting or blacklisting.
    c                    s   t t|   || _|| _dS )a|  
        :param child_policy: an instantiated :class:`.LoadBalancingPolicy`
                             that this one will defer to.
        :param predicate: a one-parameter function that takes a :class:`.Host`.
                          If it returns a falsy value, the :class:`.Host` will
                          be :attr:`.IGNORED` and not returned in query plans.
        N)superr   r+   rj   
_predicate)r   rl   	predicateru   r   r   r+     s   
zHostFilterPolicy.__init__c                 O      | j j|g|R i |S r(   r   r   r    rz   r{   r   r   r   r!        zHostFilterPolicy.on_upc                 O   r   r(   r   r   r   r   r   r#     r   zHostFilterPolicy.on_downc                 O   r   r(   r   r   r   r   r   r$     r   zHostFilterPolicy.on_addc                 O   r   r(   r   r   r   r   r   r&     r   zHostFilterPolicy.on_removec                 C   s   | j S )a  
        A predicate, set on object initialization, that takes a :class:`.Host`
        and returns a value. If the value is falsy, the :class:`.Host` is
        :class:`~HostDistance.IGNORED`. If the value is truthy,
        :class:`.HostFilterPolicy` defers to the child policy to determine the
        host's distance.

        This is a read-only value set in ``__init__``, implemented as a
        ``property``.
        )r   r*   r   r   r   r     s   zHostFilterPolicy.predicatec                 C   s   |  |r| j|S tjS )z
        Checks if ``predicate(host)``, then returns
        :attr:`~HostDistance.IGNORED` if falsy, and defers to the child policy
        otherwise.
        )r   rj   r-   r   r   r   r   r   r   r-     s   
zHostFilterPolicy.distancec                 C   s   | j j||d d S )N)r/   r0   rj   r1   r.   r   r   r   r1     s   zHostFilterPolicy.populateNc                 c   s0    | j j||d}|D ]
}| |r|V  qdS )aw  
        Defers to the child policy's
        :meth:`.LoadBalancingPolicy.make_query_plan` and filters the results.

        Note that this filtering may break desirable properties of the wrapped
        policy in some cases. For instance, imagine if you configure this
        policy to filter out ``host2``, and to wrap a round-robin policy that
        rotates through three hosts in the order ``host1, host2, host3``,
        ``host2, host3, host1``, ``host3, host1, host2``, repeating. This
        policy will yield ``host1, host3``, ``host3, host1``, ``host3, host1``,
        disproportionately favoring ``host3``.
        )r3   r4   N)rj   r5   r   )r   r3   r4   child_qpr    r   r   r   r5     s   
z HostFilterPolicy.make_query_planc                 C   s
   | j  S r(   )rj   r7   r*   r   r   r   r7   1     
z HostFilterPolicy.check_supportedr8   )r   r   r   r   r+   r!   r#   r$   r&   propertyr   r-   r1   r5   r7   __classcell__r   r   r   r   r     s    #

r   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	ConvictionPolicyz
    A policy which decides when hosts should be considered down
    based on the types of failures and the number of failures.

    If custom behavior is needed, this class may be subclassed.
    c                 C   s
   || _ dS )z:
        `host` is an instance of :class:`.Host`.
        Nrd   r   r   r   r   r+   =  s   
zConvictionPolicy.__init__c                 C   r   )z
        Implementations should return :const:`True` if the host should be
        convicted, :const:`False` otherwise.
        r   r   connection_excr   r   r   add_failureC  r%   zConvictionPolicy.add_failurec                 C   r   )zg
        Implementations should clear out any convictions or state regarding
        the host.
        r   r*   r   r   r   resetJ  r%   zConvictionPolicy.resetN)r   r   r   r   r+   r   r   r   r   r   r   r   5  s
    r   c                   @   s    e Zd ZdZdd Zdd ZdS )SimpleConvictionPolicyz
    The default implementation of :class:`ConvictionPolicy`,
    which simply marks a host as down after the first failure
    of any kind.
    c                 C   s   t |t S r(   )
isinstancer   r   r   r   r   r   Y  r,   z"SimpleConvictionPolicy.add_failurec                 C   s   d S r(   r   r*   r   r   r   r   \     zSimpleConvictionPolicy.resetN)r   r   r   r   r   r   r   r   r   r   r   R  s    r   c                   @      e Zd ZdZdd ZdS )ReconnectionPolicyz
    This class and its subclasses govern how frequently an attempt is made
    to reconnect to nodes that are marked as dead.

    If custom behavior is needed, this class may be subclassed.
    c                 C   r   )a%  
        This should return a finite or infinite iterable of delays (each as a
        floating point number of seconds) in-between each failed reconnection
        attempt.  Note that if the iterable is finite, reconnection attempts
        will cease once the iterable is exhausted.
        r   r*   r   r   r   new_scheduleh  r2   zReconnectionPolicy.new_scheduleN)r   r   r   r   r   r   r   r   r   r   `  s    r   c                   @   s"   e Zd ZdZdddZdd ZdS )	ConstantReconnectionPolicyzz
    A :class:`.ReconnectionPolicy` subclass which sleeps for a fixed delay
    in-between each reconnection attempt.
    @   c                 C   s8   |dk rt d|dur|dk rt d|| _|| _dS )a(  
        `delay` should be a floating point number of seconds to wait in-between
        each attempt.

        `max_attempts` should be a total number of attempts to be made before
        giving up, or :const:`None` to continue reconnection attempts forever.
        The default is 64.
        r   zdelay must not be negativeN!max_attempts must not be negative)
ValueErrordelaymax_attemptsr   r   r   r   r   r   r+   x  s   	
z#ConstantReconnectionPolicy.__init__c                 C   s   | j r
t| j| j S t| jS r(   )r   r   r   r*   r   r   r   r     s   
z'ConstantReconnectionPolicy.new_scheduleNr   )r   r   r   r   r+   r   r   r   r   r   r   r  s    
r   c                   @   s*   e Zd ZdZd
ddZdd Zdd Zd	S )ExponentialReconnectionPolicya}  
    A :class:`.ReconnectionPolicy` subclass which exponentially increases
    the length of the delay in-between each reconnection attempt up to
    a set maximum delay.

    A random amount of jitter (+/- 15%) will be added to the pure exponential
    delay value to avoid the situations where many reconnection handlers are
    trying to reconnect at exactly the same time.
    r   c                 C   sV   |dk s|dk rt d||k rt d|dur |dk r t d|| _|| _|| _dS )a  
        `base_delay` and `max_delay` should be in floating point units of
        seconds.

        `max_attempts` should be a total number of attempts to be made before
        giving up, or :const:`None` to continue reconnection attempts forever.
        The default is 64.
        r   zDelays may not be negativez)Max delay must be greater than base delayNr   )r   
base_delay	max_delayr   )r   r   r   r   r   r   r   r+     s   	
z&ExponentialReconnectionPolicy.__init__c                 c   s    d\}}| j d u s|| j k rG|r| jV  n!z| t| jd|  | jV  W n ty6   d}| jV  Y nw |d7 }| j d u s|| j k sd S d S )N)r   F   Tr   )r   r   _add_jitterminr   OverflowError)r   i
overflowedr   r   r   r     s   
"z*ExponentialReconnectionPolicy.new_schedulec                 C   s*   t dd}|| d }tt| j|| jS )NU   s   d   )r   r   maxr   r   )r   valuejitterr   r   r   r   r     s   
z)ExponentialReconnectionPolicy._add_jitterNr   )r   r   r   r   r+   r   r   r   r   r   r   r     s
    
r   c                   @   sH   e Zd ZdZdZ	 dZ	 dZ	 dZ	 dd Zdd	 Z	d
d Z
dd ZdS )RetryPolicya  
    A policy that describes whether to retry, rethrow, or ignore coordinator
    timeout and unavailable failures. These are failures reported from the
    server side. Timeouts are configured by
    `settings in cassandra.yaml <https://github.com/apache/cassandra/blob/cassandra-2.1.4/conf/cassandra.yaml#L568-L584>`_.
    Unavailable failures occur when the coordinator cannot achieve the consistency
    level for a request. For further information see the method descriptions
    below.

    To specify a default retry policy, set the
    :attr:`.Cluster.default_retry_policy` attribute to an instance of this
    class or one of its subclasses.

    To specify a retry policy per query, set the :attr:`.Statement.retry_policy`
    attribute to an instance of this class or one of its subclasses.

    If custom behavior is needed for retrying certain operations,
    this class may be subclassed.
    r   r   r      c                 C   s2   |dkr	| j dfS ||kr|s| j|fS | j dfS )a  
        This is called when a read operation times out from the coordinator's
        perspective (i.e. a replica did not respond to the coordinator in time).
        It should return a tuple with two items: one of the class enums (such
        as :attr:`.RETRY`) and a :class:`.ConsistencyLevel` to retry the
        operation at or :const:`None` to keep the same consistency level.

        `query` is the :class:`.Statement` that timed out.

        `consistency` is the :class:`.ConsistencyLevel` that the operation was
        attempted at.

        The `required_responses` and `received_responses` parameters describe
        how many replicas needed to respond to meet the requested consistency
        level and how many actually did respond before the coordinator timed
        out the request. `data_retrieved` is a boolean indicating whether
        any of those responses contained data (as opposed to just a digest).

        `retry_num` counts how many times the operation has been retried, so
        the first time this method is called, `retry_num` will be 0.

        By default, operations will be retried at most once, and only if
        a sufficient number of replicas responded (with data digests).
        r   N)RETHROWRETRYr   r4   consistencyrequired_responsesreceived_responsesdata_retrieved	retry_numr   r   r   on_read_timeout  s
   


zRetryPolicy.on_read_timeoutc                 C   s0   |dkr	| j dfS |tjkr| j|fS | j dfS )a!  
        This is called when a write operation times out from the coordinator's
        perspective (i.e. a replica did not respond to the coordinator in time).

        `query` is the :class:`.Statement` that timed out.

        `consistency` is the :class:`.ConsistencyLevel` that the operation was
        attempted at.

        `write_type` is one of the :class:`.WriteType` enums describing the
        type of write operation.

        The `required_responses` and `received_responses` parameters describe
        how many replicas needed to acknowledge the write to meet the requested
        consistency level and how many replicas actually did acknowledge the
        write before the coordinator timed out the request.

        `retry_num` counts how many times the operation has been retried, so
        the first time this method is called, `retry_num` will be 0.

        By default, failed write operations will retried at most once, and
        they will only be retried if the `write_type` was
        :attr:`~.WriteType.BATCH_LOG`.
        r   N)r   r   	BATCH_LOGr   r   r4   r   
write_typer   r   r   r   r   r   on_write_timeout  s
   



zRetryPolicy.on_write_timeoutc                 C   s   |dkr	| j dfS | jdfS )a  
        This is called when the coordinator node determines that a read or
        write operation cannot be successful because the number of live
        replicas are too low to meet the requested :class:`.ConsistencyLevel`.
        This means that the read or write operation was never forwarded to
        any replicas.

        `query` is the :class:`.Statement` that failed.

        `consistency` is the :class:`.ConsistencyLevel` that the operation was
        attempted at.

        `required_replicas` is the number of replicas that would have needed to
        acknowledge the operation to meet the requested consistency level.
        `alive_replicas` is the number of replicas that the coordinator
        considered alive at the time of the request.

        `retry_num` counts how many times the operation has been retried, so
        the first time this method is called, `retry_num` will be 0.

        By default, if this is the first retry, it triggers a retry on the next
        host in the query plan with the same consistency level. If this is not the
        first retry, no retries will be attempted and the error will be re-raised.
        r   N)RETRY_NEXT_HOSTr   r   r4   r   required_replicasalive_replicasr   r   r   r   on_unavailable7  s   zRetryPolicy.on_unavailablec                 C   s
   | j dfS )a  
        This is called when an unexpected error happens. This can be in the
        following situations:

        * On a connection error
        * On server errors: overloaded, isBootstrapping, serverError, etc.

        `query` is the :class:`.Statement` that timed out.

        `consistency` is the :class:`.ConsistencyLevel` that the operation was
        attempted at.

        `error` the instance of the exception.

        `retry_num` counts how many times the operation has been retried, so
        the first time this method is called, `retry_num` will be 0.

        By default, it triggers a retry on the next host in the query plan
        with the same consistency level.
        N)r   )r   r4   r   errorr   r   r   r   on_request_errorR  s   
zRetryPolicy.on_request_errorN)r   r   r   r   r   r   IGNOREr   r   r   r   r   r   r   r   r   r     s    !!r   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )FallthroughRetryPolicyzb
    A retry policy that never retries and always propagates failures to
    the application.
    c                 O   
   | j d fS r(   r   ry   r   r   r   r   r  r   z&FallthroughRetryPolicy.on_read_timeoutc                 O   r   r(   r   ry   r   r   r   r   u  r   z'FallthroughRetryPolicy.on_write_timeoutc                 O   r   r(   r   ry   r   r   r   r   x  r   z%FallthroughRetryPolicy.on_unavailablec                 O   r   r(   r   ry   r   r   r   r   {  r   z'FallthroughRetryPolicy.on_request_errorN)r   r   r   r   r   r   r   r   r   r   r   r   r   l  s    r   c                       s@   e Zd ZdZ fddZdd Zdd Zdd	 Zd
d Z  Z	S )!DowngradingConsistencyRetryPolicya
  
    *Deprecated:* This retry policy will be removed in the next major release.

    A retry policy that sometimes retries with a lower consistency level than
    the one initially requested.

    **BEWARE**: This policy may retry queries using a lower consistency
    level than the one initially requested. By doing so, it may break
    consistency guarantees. In other words, if you use this retry policy,
    there are cases (documented below) where a read at :attr:`~.QUORUM`
    *may not* see a preceding write at :attr:`~.QUORUM`. Do not use this
    policy unless you have understood the cases where this can happen and
    are ok with that. It is also recommended to subclass this class so
    that queries that required a consistency level downgrade can be
    recorded (so that repairs can be made later, etc).

    This policy implements the same retries as :class:`.RetryPolicy`,
    but on top of that, it also retries in the following cases:

    * On a read timeout: if the number of replicas that responded is
      greater than one but lower than is required by the requested
      consistency level, the operation is retried at a lower consistency
      level.
    * On a write timeout: if the operation is an :attr:`~.UNLOGGED_BATCH`
      and at least one replica acknowledged the write, the operation is
      retried at a lower consistency level.  Furthermore, for other
      write types, if at least one replica acknowledged the write, the
      timeout is ignored.
    * On an unavailable exception: if at least one replica is alive, the
      operation is retried at a lower consistency level.

    The reasoning behind this retry policy is as follows: if, based
    on the information the Cassandra coordinator node returns, retrying the
    operation with the initially requested consistency has a chance to
    succeed, do it. Otherwise, if based on that information we know the
    initially requested consistency level cannot be achieved currently, then:

    * For writes, ignore the exception (thus silently failing the
      consistency requirement) if we know the write has been persisted on at
      least one replica.
    * For reads, try reading at a lower consistency level (thus silently
      failing the consistency requirement).

    In other words, this policy implements the idea that if the requested
    consistency level cannot be achieved, the next best thing for writes is
    to make sure the data is persisted, and that reading something is better
    than reading nothing, even if there is a risk of reading stale data.
    c                    &   t t| j|i | tdt d S )Nz^DowngradingConsistencyRetryPolicy is deprecated and will be removed in the next major release.)r   r   r+   warningswarnDeprecationWarningry   r   r   r   r+     s   z*DowngradingConsistencyRetryPolicy.__init__c                 C   sF   |dkr
| j tjfS |dkr| j tjfS |dkr| j tjfS | jd fS )Nr   r   r   )r   r   THREETWOONEr   )r   num_responsesr   r   r   _pick_consistency  s   
z3DowngradingConsistencyRetryPolicy._pick_consistencyc                 C   sP   |dkr	| j d fS t|r| j d fS ||k r| |S |s#| j|fS | j d fS Nr   )r   r   	is_serialr   r   r   r   r   r   r     s   





z1DowngradingConsistencyRetryPolicy.on_read_timeoutc                 C   st   |dkr	| j d fS |tjtjtjfv r!|dkr| jd fS | j d fS |tjkr+| |S |tjkr5| j	|fS | j d fS r   )
r   r   SIMPLEBATCHCOUNTERr   UNLOGGED_BATCHr   r   r   r   r   r   r   r     s   







z2DowngradingConsistencyRetryPolicy.on_write_timeoutc                 C   s0   |dkr	| j d fS t|r| jd fS | |S r   )r   r   r   r   r   r   r   r   r   r     s
   



z0DowngradingConsistencyRetryPolicy.on_unavailable)
r   r   r   r   r+   r   r   r   r   r   r   r   r   r   r     s    0
r   c                   @   r   )AddressTranslatora  
    Interface for translating cluster-defined endpoints.

    The driver discovers nodes using server metadata and topology change events. Normally,
    the endpoint defined by the server is the right way to connect to a node. In some environments,
    these addresses may not be reachable, or not preferred (public vs. private IPs in cloud environments,
    suboptimal routing, etc). This interface allows for translating from server defined endpoints to
    preferred addresses for driver connections.

    *Note:* :attr:`~Cluster.contact_points` provided while creating the :class:`~.Cluster` instance are not
    translated using this mechanism -- only addresses received from Cassandra nodes are.
    c                 C   r   )zs
        Accepts the node ip address, and returns a translated address to be used connecting to this node.
        r   r   addrr   r   r   	translate  s   zAddressTranslator.translateNr   r   r   r   r   r   r   r   r   r     s    r   c                   @   r   )IdentityTranslatorz2
    Returns the endpoint with no translation
    c                 C   s   |S r(   r   r   r   r   r   r     r   zIdentityTranslator.translateNr   r   r   r   r   r         r   c                   @   r   )EC2MultiRegionTranslatorz
    Resolves private ips of the hosts in the same datacenter as the client, and public ips of hosts in other datacenters.
    c              	   C   sf   t |dt jt jd d }t |}t |d|t jD ]}z	|d d W   S  ty0   Y qw |S )z
        Reverse DNS the public broadcast_address, then lookup that hostname to get the AWS-resolved IP, which
        will point to the private IP address within the same datacenter.
        r   r   )r   r   r   r   getfqdn	Exception)r   r   familyr    r   r   r   r   r   
  s   
z"EC2MultiRegionTranslator.translateNr   r   r   r   r   r     r   r   c                   @   r   )SpeculativeExecutionPolicyz>
    Interface for specifying speculative execution plans
    c                 C   r   )z^
        Returns

        :param keyspace:
        :param statement:
        :return:
        r   r   r}   	statementr   r   r   new_plan  s   z#SpeculativeExecutionPolicy.new_planN)r   r   r   r   r   r   r   r   r   r     s    r   c                   @      e Zd Zdd ZdS )SpeculativeExecutionPlanc                 C   r   r(   r   r   r   r   r   next_execution+  r>   z'SpeculativeExecutionPlan.next_executionNr   r   r   r   r   r   r   r   r   *      r   c                   @   r   )NoSpeculativeExecutionPlanc                 C   r6   )Nr   r   r   r   r   r   r   0  r   z)NoSpeculativeExecutionPlan.next_executionNr   r   r   r   r   r  /  r  r  c                   @   r   )NoSpeculativeExecutionPolicyc                 C   s   t  S r(   )r  r   r   r   r   r   6  r>   z%NoSpeculativeExecutionPolicy.new_planN)r   r   r   r   r   r   r   r   r  4  s    r  c                   @   s0   e Zd ZdZdd ZG dd deZdd ZdS )	"ConstantSpeculativeExecutionPolicyz
    A speculative execution policy that sends a new query every X seconds (**delay**) for a maximum of Y attempts (**max_attempts**).
    c                 C   ri   r(   )r   r   r   r   r   r   r+   ?  rm   z+ConstantSpeculativeExecutionPolicy.__init__c                   @   s   e Zd Zdd Zdd ZdS )zCConstantSpeculativeExecutionPolicy.ConstantSpeculativeExecutionPlanc                 C   ri   r(   )r   	remainingr   r   r   r   r+   D  rm   zLConstantSpeculativeExecutionPolicy.ConstantSpeculativeExecutionPlan.__init__c                 C   s"   | j dkr|  j d8  _ | jS dS )Nr   r   r   )r  r   r   r   r   r   r   H  s   
zRConstantSpeculativeExecutionPolicy.ConstantSpeculativeExecutionPlan.next_executionN)r   r   r   r+   r   r   r   r   r    ConstantSpeculativeExecutionPlanC  s    r  c                 C   s   |  | j| jS r(   )r  r   r   r   r   r   r   r   O  s   z+ConstantSpeculativeExecutionPolicy.new_planN)r   r   r   r   r+   r   r  r   r   r   r   r   r  :  s
    r  c                   @   sD   e Z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 )WrapperPolicyc                 C   s
   || _ d S r(   )rj   )r   rl   r   r   r   r+   U  r   zWrapperPolicy.__init__c                 O   rw   r(   rx   ry   r   r   r   r-   X  r|   zWrapperPolicy.distancec                 C   s   | j || d S r(   r   r.   r   r   r   r1   [  r|   zWrapperPolicy.populatec                 O   rw   r(   r   ry   r   r   r   r!   ^  r|   zWrapperPolicy.on_upc                 O   rw   r(   r   ry   r   r   r   r#   a  r|   zWrapperPolicy.on_downc                 O   rw   r(   r   ry   r   r   r   r$   d  r|   zWrapperPolicy.on_addc                 O   rw   r(   r   ry   r   r   r   r&   g  r|   zWrapperPolicy.on_removeN)
r   r   r   r+   r-   r1   r!   r#   r$   r&   r   r   r   r   r  S  s    r  c                   @   s&   e Zd ZdZdZdd ZdddZdS )DefaultLoadBalancingPolicyz
    A :class:`.LoadBalancingPolicy` wrapper that adds the ability to target a specific host first.

    If no host is set on the query, the child policy's query plan will be used as is.
    Nc                 C   rn   r(   ro   r.   r   r   r   r1   t  rr   z#DefaultLoadBalancingPolicy.populatec                 c   s    |r
|j r
|j }n|}|rt|dd nd }| j|}| j}|r9|jr9|V  |||D ]	}||kr6|V  q-d S |||D ]}|V  q?d S )Ntarget_host)r}   getattrrq   get_hostrj   r   r5   )r   r3   r4   r}   r   r	  r   rO   r   r   r   r5   x  s"   

z*DefaultLoadBalancingPolicy.make_query_planr8   )r   r   r   r   rq   r1   r5   r   r   r   r   r  k  s
    r  c                       s    e Zd ZdZ fddZ  ZS )DSELoadBalancingPolicyz
    *Deprecated:* This will be removed in the next major release,
    consider using :class:`.DefaultLoadBalancingPolicy`.
    c                    r   )NzYDSELoadBalancingPolicy will be removed in 4.0. Consider using DefaultLoadBalancingPolicy.)r   r  r+   r   r   r   ry   r   r   r   r+     s   zDSELoadBalancingPolicy.__init__)r   r   r   r   r+   r   r   r   r   r   r    s    r  c                   @   s    e Zd Zdd ZeZeZeZdS )NeverRetryPolicyc                 O   r   r(   r   ry   r   r   r   _rethrow  r   zNeverRetryPolicy._rethrowN)r   r   r   r  r   r   r   r   r   r   r   r    s
    r  ColDesc)kstablecolc                   @   r   )ColumnEncryptionPolicya  
    A policy enabling (mostly) transparent encryption and decryption of data before it is
    sent to the cluster.

    Key materials and other configurations are specified on a per-column basis.  This policy can
    then be used by driver structures which are aware of the underlying columns involved in their
    work.  In practice this includes the following cases:

    * Prepared statements - data for columns specified by the cluster's policy will be transparently
      encrypted before they are sent
    * Rows returned from any query - data for columns specified by the cluster's policy will be
      transparently decrypted before they are returned to the user

    To enable this functionality, create an instance of this class (or more likely a subclass)
    before creating a cluster.  This policy should then be configured and supplied to the Cluster
    at creation time via the :attr:`.Cluster.column_encryption_policy` attribute.
    c                 C   r   )a  
        Encrypt the specified bytes using the cryptography materials for the specified column.
        Largely used internally, although this could also be used to encrypt values supplied
        to non-prepared statements in a way that is consistent with this policy.
        r   )r   coldesc	obj_bytesr   r   r   encrypt     zColumnEncryptionPolicy.encryptc                 C   r   )z
        Decrypt the specified (encrypted) bytes using the cryptography materials for the
        specified column.  Used internally; could be used externally as well but there's
        not currently an obvious use case.
        r   )r   r  encrypted_bytesr   r   r   decrypt  r  zColumnEncryptionPolicy.decryptc                 C   r   )z
        Provide cryptography materials to be used when encrypted and/or decrypting data
        for the specified column.
        r   )r   r  keyr   r   r   
add_column  r%   z!ColumnEncryptionPolicy.add_columnc                 C   r   )z
        Predicate to determine if a specific column is supported by this policy.
        Currently only used internally.
        r   )r   r  r   r   r   contains_column  r%   z&ColumnEncryptionPolicy.contains_columnc                 C   r   )zp
        Helper function to enable use of this policy on simple (i.e. non-prepared)
        statements.
        r   )r   r  objr   r   r   encode_and_encrypt  r%   z)ColumnEncryptionPolicy.encode_and_encryptN)	r   r   r   r   r  r  r  r  r  r   r   r   r   r    s    r  )8collectionsr   	functoolsr   	itertoolsr   r   r   r   loggingrandomr   r	   	threadingr
   r   r   	getLoggerr   r`   	cassandrar   WTr   r   objectr   r   r'   r9   rG   rh   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r  r  r  r   r   r   r   <module>   sV   
$<0vW/p9 %k#	