
    hVG                     @   d Z ddlmZmZ ddlmZ ddlmZ ddlm	Z	m
Z
 dZdZdZdZd	Zd
Zd Zd Zd Zd Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      ZeeeeefZd#dZdZ G d de      Zd Z  G d  d!e      Z!y")$zBUtilities for choosing which member of a replica set to read from.    )abcinteger_types)max_staleness_selectors)ConfigurationError) member_with_tags_server_selector#secondary_with_tags_server_selector            )primaryprimaryPreferred	secondarysecondaryPreferrednearestc                     | | S t        | t              st        d| d      t        |       dk(  rt	        d| d      | D ]+  }t        |t
        j                        rt        d|d       | S )z3Validate tag sets for a MongoReplicaSetClient.
    z	Tag sets z invalid, must be a listr   z: invalid, must be None or contain at least one set of tagszTag set zg invalid, must be an instance of dict, bson.son.SON or other type that inherits from collection.Mapping)
isinstancelist	TypeErrorlen
ValueErrorr   Mapping)tag_setstagss     [/var/www/html/ranktracker/api/venv/lib/python3.12/site-packages/pymongo/read_preferences.py_validate_tag_setsr   (   s     h%6>A B 	B
8} # $ 	$  0$, )-/0 00 O    c                     d| z  S )Nz6maxStalenessSeconds must be a positive integer, not %s max_stalenesss    r   _invalid_max_staleness_msgr"   @   s    D r   c                     | dk(  ryt        | t              st        t        |             | dk  rt	        t        |             | S )zValidate max_staleness.r   )r   r   r   r"   r   r    s    r   _validate_max_stalenessr%   F   sG    m]32=ABB3MBCCr   c                 H    | yt        | t              st        d|       | S )zValidate hedge.Nz hedge must be a dictionary, not )r   dictr   )hedges    r   _validate_hedger)   T   s'    }eT"GHHLr   c                       e Zd ZdZdZddZed        Zed        Zed        Z	ed        Z
ed	        Zed
        Zed        Zed        Zd Zd Zd Zd Zd Zy)_ServerModez)Base class for all read preferences.
    )__mongos_mode__mode
__tag_sets__max_staleness__hedgeNc                     t         |   | _        || _        t        |      | _        t        |      | _        t        |      | _        y N)	_MONGOS_MODES_ServerMode__mongos_mode_ServerMode__moder   _ServerMode__tag_setsr%   _ServerMode__max_stalenessr)   _ServerMode__hedge)selfmoder   r!   r(   s        r   __init__z_ServerMode.__init__f   s;    *40,X66}E&u-r   c                 .    | j                   j                  S )z*The name of this read preference.
        )	__class____name__r9   s    r   namez_ServerMode.namem   s     ~~&&&r   c                     | j                   S )z1The mongos mode of this read preference.
        )r4   r?   s    r   mongos_modez_ServerMode.mongos_modes   s     !!!r   c                     d| j                   i}| j                  di gfvr| j                  |d<   | j                  dk7  r| j                  |d<   | j                  di fvr| j                  |d<   |S )z'Read preference as a document.
        r:   Nr   r$   maxStalenessSecondsr(   )r4   r6   r7   r8   )r9   docs     r   documentz_ServerMode.documenty   st     t))*??4",.//CK2%)-)=)=C%&<<bz)<<CL
r   c                     | j                   S )z3The mode of this read preference instance.
        )r5   r?   s    r   r:   z_ServerMode.mode   s     {{r   c                 J    | j                   rt        | j                         S i gS )a{  Set ``tag_sets`` to a list of dictionaries like [{'dc': 'ny'}] to
        read only from members whose ``dc`` tag has the value ``"ny"``.
        To specify a priority-order for tag sets, provide a list of
        tag sets: ``[{'dc': 'ny'}, {'dc': 'la'}, {}]``. A final, empty tag
        set, ``{}``, means "read from any member that matches the mode,
        ignoring tags." MongoReplicaSetClient tries each set of tags in turn
        until it finds a set of tags with at least one matching member.

           .. seealso:: `Data-Center Awareness
               <http://www.mongodb.org/display/DOCS/Data+Center+Awareness>`_
        )r6   r   r?   s    r   r   z_ServerMode.tag_sets   s      )-tDOO$AbTAr   c                     | j                   S )zThe maximum estimated length of time (in seconds) a replica set
        secondary can fall behind the primary in replication before it will
        no longer be selected for operations, or -1 for no maximum.r7   r?   s    r   r!   z_ServerMode.max_staleness   s    
 ###r   c                     | j                   S )a  The read preference ``hedge`` parameter.

        A dictionary that configures how the server will perform hedged reads.
        It consists of the following keys:

        - ``enabled``: Enables or disables hedged reads in sharded clusters.

        Hedged reads are automatically enabled in MongoDB 4.4+ when using a
        ``nearest`` read preference. To explicitly enable hedged reads, set
        the ``enabled`` key  to ``true``::

            >>> Nearest(hedge={'enabled': True})

        To explicitly disable hedged reads, set the ``enabled`` key  to
        ``False``::

            >>> Nearest(hedge={'enabled': False})

        .. versionadded:: 3.11
        )r8   r?   s    r   r(   z_ServerMode.hedge   s    , ||r   c                 (    | j                   dk(  rdS dS )a  The wire protocol version the server must support.

        Some read preferences impose version requirements on all servers (e.g.
        maxStalenessSeconds requires MongoDB 3.4 / maxWireVersion 5).

        All servers' maxWireVersion must be at least this read preference's
        `min_wire_version`, or the driver raises
        :exc:`~pymongo.errors.ConfigurationError`.
        r$   r      rJ   r?   s    r   min_wire_versionz_ServerMode.min_wire_version   s     ((B.q5A5r   c                 n    | j                   d| j                  d| j                  d| j                  dS )Nz
(tag_sets=z, max_staleness=z, hedge=))r@   r6   r7   r8   r?   s    r   __repr__z_ServerMode.__repr__   s)    IIt(<(<dllL 	Lr   c                    t        |t              rj| j                  |j                  k(  xrO | j                  |j                  k(  xr4 | j                  |j                  k(  xr | j
                  |j
                  k(  S t        S r2   )r   r+   r:   r   r!   r(   NotImplementedr9   others     r   __eq__z_ServerMode.__eq__   sn    e[)II+ .MMU^^3.&&%*=*==. JJ%++-/ r   c                     | |k(   S r2   r   rT   s     r   __ne__z_ServerMode.__ne__   s    5=  r   c                 `    | j                   | j                  | j                  | j                  dS )zeReturn value of object for pickling.

        Needed explicitly because __slots__() defined.
        )r:   r   r!   r(   )r5   r6   r7   r8   r?   s    r   __getstate__z_ServerMode.__getstate__   s,    
  OO!%!5!5' 	'r   c                     |d   | _         t        | j                      | _        t        |d         | _        t        |d         | _        t        |d         | _        y)zRestore from pickling.r:   r   r!   r(   N)	r5   r3   r4   r   r6   r%   r7   r)   r8   )r9   values     r   __setstate__z_ServerMode.__setstate__   sQ    Fm*4;;7,U:->?6u_7MN&uW~6r   Nr$   N)r>   
__module____qualname____doc__	__slots__r;   propertyr@   rB   rF   r:   r   r!   r(   rN   rQ   rV   rX   rZ   r]   r   r   r   r+   r+   _   s    I. ' '
 " "
 
 
  
 B B $ $  . 
6 
6L!'7r   r+   c                   8     e Zd ZdZdZ fdZd Zd Zd Z xZ	S )PrimaryaG  Primary read preference.

    * When directly connected to one mongod queries are allowed if the server
      is standalone or a replica set primary.
    * When connected to a mongos queries are sent to the primary of a shard.
    * When connected to a replica set queries are sent to the primary of
      the replica set.
    r   c                 4    t         t        |   t               y r2   )superre   r;   _PRIMARY)r9   r=   s    r   r;   zPrimary.__init__   s    gt%h/r   c                     |j                   S )z*Apply this read preference to a Selection.)primary_selectionr9   	selections     r   __call__zPrimary.__call__   s    ***r   c                      y)Nz	Primary()r   r?   s    r   rQ   zPrimary.__repr__   s    r   c                 T    t        |t              r|j                  t        k(  S t        S r2   )r   r+   r:   rh   rS   rT   s     r   rV   zPrimary.__eq__   s!    e[)::))r   )
r>   r_   r`   ra   rb   r;   rm   rQ   rV   __classcell__r=   s   @r   re   re      s#     I0+r   re   c                   .     e Zd ZdZdZd fd	Zd Z xZS )PrimaryPreferreda  PrimaryPreferred read preference.

    * When directly connected to one mongod queries are allowed to standalone
      servers, to a replica set primary, or to replica set secondaries.
    * When connected to a mongos queries are sent to the primary of a shard if
      available, otherwise a shard secondary.
    * When connected to a replica set queries are sent to the primary if
      available, otherwise a secondary.

    :Parameters:
      - `tag_sets`: The :attr:`~tag_sets` to use if the primary is not
        available.
      - `max_staleness`: (integer, in seconds) The maximum estimated
        length of time a replica set secondary can fall behind the primary in
        replication before it will no longer be selected for operations.
        Default -1, meaning no maximum. If it is set, it must be at least
        90 seconds.
      - `hedge`: The :attr:`~hedge` to use if the primary is not available.

    .. versionchanged:: 3.11
       Added ``hedge`` parameter.
    r   c                 :    t         t        |   t        |||       y r2   )rg   rs   r;   _PRIMARY_PREFERREDr9   r   r!   r(   r=   s       r   r;   zPrimaryPreferred.__init__  s    .-	@r   c                     |j                   r|j                  S t        | j                  t	        j
                  | j                  |            S z(Apply this read preference to Selection.)r   rj   r   r   r   selectr!   rk   s     r   rm   zPrimaryPreferred.__call__#  sD    ...6'..&&	34 4r   r^   r>   r_   r`   ra   rb   r;   rm   rp   rq   s   @r   rs   rs     s    . I@4r   rs   c                   .     e Zd ZdZdZd fd	Zd Z xZS )	Secondarya  Secondary read preference.

    * When directly connected to one mongod queries are allowed to standalone
      servers, to a replica set primary, or to replica set secondaries.
    * When connected to a mongos queries are distributed among shard
      secondaries. An error is raised if no secondaries are available.
    * When connected to a replica set queries are distributed among
      secondaries. An error is raised if no secondaries are available.

    :Parameters:
      - `tag_sets`: The :attr:`~tag_sets` for this read preference.
      - `max_staleness`: (integer, in seconds) The maximum estimated
        length of time a replica set secondary can fall behind the primary in
        replication before it will no longer be selected for operations.
        Default -1, meaning no maximum. If it is set, it must be at least
        90 seconds.
      - `hedge`: The :attr:`~hedge` for this read preference.

    .. versionchanged:: 3.11
       Added ``hedge`` parameter.
    r   c                 :    t         t        |   t        |||       y r2   )rg   r|   r;   
_SECONDARYrv   s       r   r;   zSecondary.__init__G  s    i'-	8r   c                 j    t        | j                  t        j                  | j                  |            S rx   )r   r   r   ry   r!   rk   s     r   rm   zSecondary.__call__K  s/    2MM#**""I/0 	0r   r^   rz   rq   s   @r   r|   r|   .  s    , I80r   r|   c                   .     e Zd ZdZdZd fd	Zd Z xZS )SecondaryPreferreda  SecondaryPreferred read preference.

    * When directly connected to one mongod queries are allowed to standalone
      servers, to a replica set primary, or to replica set secondaries.
    * When connected to a mongos queries are distributed among shard
      secondaries, or the shard primary if no secondary is available.
    * When connected to a replica set queries are distributed among
      secondaries, or the primary if no secondary is available.

    :Parameters:
      - `tag_sets`: The :attr:`~tag_sets` for this read preference.
      - `max_staleness`: (integer, in seconds) The maximum estimated
        length of time a replica set secondary can fall behind the primary in
        replication before it will no longer be selected for operations.
        Default -1, meaning no maximum. If it is set, it must be at least
        90 seconds.
      - `hedge`: The :attr:`~hedge` for this read preference.

    .. versionchanged:: 3.11
       Added ``hedge`` parameter.
    r   c                 :    t         t        |   t        |||       y r2   )rg   r   r;   _SECONDARY_PREFERREDrv   s       r   r;   zSecondaryPreferred.__init__l  s     $0 (M5	Br   c                     t        | j                  t        j                  | j                  |            }|r|S |j
                  S rx   )r   r   r   ry   r!   rj   )r9   rl   secondariess      r   rm   zSecondaryPreferred.__call__p  sC    9MM#**""I/0
 ...r   r^   rz   rq   s   @r   r   r   S  s    , IB
/r   r   c                   .     e Zd ZdZdZd fd	Zd Z xZS )Nearestav  Nearest read preference.

    * When directly connected to one mongod queries are allowed to standalone
      servers, to a replica set primary, or to replica set secondaries.
    * When connected to a mongos queries are distributed among all members of
      a shard.
    * When connected to a replica set queries are distributed among all
      members.

    :Parameters:
      - `tag_sets`: The :attr:`~tag_sets` for this read preference.
      - `max_staleness`: (integer, in seconds) The maximum estimated
        length of time a replica set secondary can fall behind the primary in
        replication before it will no longer be selected for operations.
        Default -1, meaning no maximum. If it is set, it must be at least
        90 seconds.
      - `hedge`: The :attr:`~hedge` for this read preference.

    .. versionchanged:: 3.11
       Added ``hedge`` parameter.
    r   c                 :    t         t        |   t        |||       y r2   )rg   r   r;   _NEARESTrv   s       r   r;   zNearest.__init__  s    gt%hu	6r   c                 j    t        | j                  t        j                  | j                  |            S rx   )r   r   r   ry   r!   rk   s     r   rm   zNearest.__call__  s/    /MM#**""I/0 	0r   r^   rz   rq   s   @r   r   r   }  s    , I60r   r   c                     | t         k(  r,|d i gfvrt        d      |dk7  rt        d      t               S t        |    ||      S )Nz4Read preference primary cannot be combined with tagsr$   zCRead preference primary cannot be combined with maxStalenessSeconds)rh   r   re   _ALL_READ_PREFERENCES)r:   r   r!   s      r   make_read_preferencer     sd    xD2$<'$ &D E EB$ &I J Jy &x??r   )PRIMARYPRIMARY_PREFERRED	SECONDARYSECONDARY_PREFERREDNEARESTc                   V    e Zd ZdZ e       Z e       Z e       Z	 e
       Z e       Zy)ReadPreferenceaD  An enum that defines the read preference modes supported by PyMongo.

    See :doc:`/examples/high_availability` for code examples.

    A read preference is used in three cases:

    :class:`~pymongo.mongo_client.MongoClient` connected to a single mongod:

    - ``PRIMARY``: Queries are allowed if the server is standalone or a replica
      set primary.
    - All other modes allow queries to standalone servers, to a replica set
      primary, or to replica set secondaries.

    :class:`~pymongo.mongo_client.MongoClient` initialized with the
    ``replicaSet`` option:

    - ``PRIMARY``: Read from the primary. This is the default, and provides the
      strongest consistency. If no primary is available, raise
      :class:`~pymongo.errors.AutoReconnect`.

    - ``PRIMARY_PREFERRED``: Read from the primary if available, or if there is
      none, read from a secondary.

    - ``SECONDARY``: Read from a secondary. If no secondary is available,
      raise :class:`~pymongo.errors.AutoReconnect`.

    - ``SECONDARY_PREFERRED``: Read from a secondary if available, otherwise
      from the primary.

    - ``NEAREST``: Read from any member.

    :class:`~pymongo.mongo_client.MongoClient` connected to a mongos, with a
    sharded cluster of replica sets:

    - ``PRIMARY``: Read from the primary of the shard, or raise
      :class:`~pymongo.errors.OperationFailure` if there is none.
      This is the default.

    - ``PRIMARY_PREFERRED``: Read from the primary of the shard, or if there is
      none, read from a secondary of the shard.

    - ``SECONDARY``: Read from a secondary of the shard, or raise
      :class:`~pymongo.errors.OperationFailure` if there is none.

    - ``SECONDARY_PREFERRED``: Read from a secondary of the shard if available,
      otherwise from the shard primary.

    - ``NEAREST``: Read from any shard member.
    N)r>   r_   r`   ra   re   r   rs   r   r|   r   r   r   r   r   r   r   r   r   r     s1    0b iG(*I,.iGr   r   c                 ,    t         j                  |       S )z7Get the read preference mode from mongos/uri name.
    )r3   index)r@   s    r   read_pref_mode_from_namer     s     t$$r   c                   (    e Zd ZdZd Zd Zd Zd Zy)MovingAveragez0Tracks an exponentially-weighted moving average.c                     d | _         y r2   averager?   s    r   r;   zMovingAverage.__init__  	    r   c                 l    |dk  ry | j                   || _         y d| j                   z  d|z  z   | _         y )Nr   g?g?r   )r9   samples     r   
add_samplezMovingAverage.add_sample  s:    A: <<!DL -f<DLr   c                     | j                   S )z6Get the calculated average, or None if no samples yet.r   r?   s    r   getzMovingAverage.get  s    ||r   c                     d | _         y r2   r   r?   s    r   resetzMovingAverage.reset  r   r   N)r>   r_   r`   ra   r;   r   r   r   r   r   r   r   r     s    :=r   r   N)r$   )"ra   bson.py3compatr   r   pymongor   pymongo.errorsr   pymongo.server_selectorsr   r   rh   ru   r~   r   r   r3   r   r"   r%   r)   objectr+   re   rs   r|   r   r   r   r   _MODESr   r   r   r   r   r   <module>r      s    I - + -K  
 0G7& G7Tk 8&4{ &4R"0 "0J'/ '/T"0k "0J !"2"$6A 	@
6V 6r%F r   