
    FCf}S                       d Z ddlmZ ddlmZ ddlmZmZmZm	Z	m
Z
 ddlmZ ddlmZ ddlmZmZ erddlmZ dd	lmZ dZd
ZdZdZdZdZeeef   Ze
eeef      Zd)dZd*dZd+dZ d,dZ! G d 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       Z(e#e$e%e&e'fZ)	 d-	 	 	 	 	 	 	 d.d!Z*d"Z+ G d# d$      Z,d/d%Z- G d& d'      Z.y()0zBUtilities for choosing which member of a replica set to read from.    )annotations)abc)TYPE_CHECKINGAnyMappingOptionalSequence)max_staleness_selectors)ConfigurationError) member_with_tags_server_selector#secondary_with_tags_server_selector)	Selection)TopologyDescription            )primaryprimaryPreferred	secondarysecondaryPreferrednearestc                   | | S t        | t        t        f      st        d| d      t	        |       dk(  rt        d| d      | D ]+  }t        |t        j                        rt        d|d       t        |       S )z$Validate tag sets for a MongoClient.z	Tag sets z invalid, must be a sequencer   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tuple	TypeErrorlen
ValueErrorr   r   )tag_setstagss     X/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/pymongo/read_preferences.py_validate_tag_setsr#   4   s    hu.)H</KLMM
8}|#]^
 	
  $,4( #% %  >    c                    d| z  S )Nz6maxStalenessSeconds must be a positive integer, not %s max_stalenesss    r"   _invalid_max_staleness_msgr)   K   s    CmSSr$   c                    | dk(  ryt        | t              st        t        |             | dk  rt	        t        |             | S )zValidate max_staleness.r   )r   intr   r)   r   r'   s    r"   _validate_max_stalenessr-   P   sG    mS)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_hedger1   ^   s,    }eT":5)DEELr$   c                      e Zd ZdZdZ	 	 	 d	 	 	 	 	 	 	 	 	 ddZedd       Zedd       Zedd       Z	edd       Z
edd	       Zedd
       Zedd       Zedd       ZddZddZddZddZddZd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_stalenessr1   _ServerMode__hedge)selfmoder    r(   r0   s        r"   __init__z_ServerMode.__init__n   s=     +40,X66}E&u-r$   c                .    | j                   j                  S )z!The name of this read preference.)	__class____name__rA   s    r"   namez_ServerMode.name{   s     ~~&&&r$   c                    | j                   S )z(The mongos mode of this read preference.)r<   rG   s    r"   mongos_modez_ServerMode.mongos_mode   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.rB   Nr!   r+   maxStalenessSecondsr0   )r<   r>   r?   r@   )rA   docs     r"   documentz_ServerMode.document   st      &t'9'9:??4",.//CK2%)-)=)=C%&<<bz)<<CL
r$   c                    | j                   S )z*The mode of this read preference instance.)r=   rG   s    r"   rB   z_ServerMode.mode   s     {{r$   c                J    | j                   rt        | j                         S i gS )aW  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." MongoClient tries each set of tags in turn
        until it finds a set of tags with at least one matching member.
        For example, to only send a query to an analytic node::

           Nearest(tag_sets=[{"node":"analytics"}])

        Or using :class:`SecondaryPreferred`::

           SecondaryPreferred(tag_sets=[{"node":"analytics"}])

           .. seealso:: `Data-Center Awareness
               <https://www.mongodb.com/docs/manual/data-center-awareness/>`_
        )r>   r   rG   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.
        r?   rG   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
        )r@   rG   s    r"   r0   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      rR   rG   s    r"   min_wire_versionz_ServerMode.min_wire_version   s     ((B.q5A5r$   c                z    dj                  | j                  | j                  | j                  | j                        S )Nz1{}(tag_sets={!r}, max_staleness={!r}, hedge={!r}))formatrH   r>   r?   r@   rG   s    r"   __repr__z_ServerMode.__repr__   s3    BIIIIOO  LL	
 	
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 r:   )r   r3   rB   r    r(   r0   NotImplementedrA   others     r"   __eq__z_ServerMode.__eq__   sn    e[)		UZZ' .MMU^^3.&&%*=*==. JJ%++-	 r$   c                    | |k(   S r:   r&   r\   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.
        )rB   r    r(   r0   )r=   r>   r?   r@   rG   s    r"   __getstate__z_ServerMode.__getstate__   s,     KK!11\\	
 	
r$   c                    |d   | _         t        | j                      | _        t        |d         | _        t        |d         | _        t        |d         | _        y)zRestore from pickling.rB   r    r(   r0   N)	r=   r;   r<   r#   r>   r-   r?   r1   r@   )rA   values     r"   __setstate__z_ServerMode.__setstate__   sQ    Fm*4;;7,U:->?6u_7MN&uW~6r$   c                    |S r:   r&   rA   	selections     r"   __call__z_ServerMode.__call__  s    r$   Nr+   N)
rB   r,   r    Optional[_TagSets]r(   r,   r0   Optional[_Hedge]returnNonerm   str)rm   zdict[str, Any])rm   r,   )rm   _TagSets)rm   rl   r]   r   rm   bool)rd   zMapping[str, Any]rm   rn   rh   r   rm   r   )rF   
__module____qualname____doc__	__slots__rC   propertyrH   rJ   rN   rB   r    r(   r0   rV   rY   r^   r`   rb   re   ri   r&   r$   r"   r3   r3   i   s
   .WI
 (,"&.. %. 	.
  . 
. ' ' " " 	 	   B B* $ $  . 
6 
6
!

7r$   r3   c                  @     e Zd ZdZdZd fdZddZd	dZd
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                ,    t         |   t               y r:   )superrC   _PRIMARY)rA   rE   s    r"   rC   zPrimary.__init__  s    "r$   c                    |j                   S z*Apply this read preference to a Selection.)primary_selectionrg   s     r"   ri   zPrimary.__call__  s    ***r$   c                     y)Nz	Primary()r&   rG   s    r"   rY   zPrimary.__repr__  s    r$   c                T    t        |t              r|j                  t        k(  S t        S r:   )r   r3   rB   r~   r[   r\   s     r"   r^   zPrimary.__eq__  s!    e[)::))r$   rm   rn   rt   ro   rr   )
rF   ru   rv   rw   rx   rC   ri   rY   r^   __classcell__rE   s   @r"   r{   r{     s#     I#+r$   r{   c                  F     e Zd ZdZdZ	 	 	 d	 	 	 	 	 	 	 d fdZd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.

    .. note:: When a :class:`~pymongo.mongo_client.MongoClient` is first
      created reads will be routed to an available secondary until the
      primary of the replica set is discovered.

    :param tag_sets: The :attr:`~tag_sets` to use if the primary is not
        available.
    :param 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.
    :param hedge: The :attr:`~hedge` to use if the primary is not available.

    .. versionchanged:: 3.11
       Added ``hedge`` parameter.
    r&   c                2    t         |   t        |||       y r:   )r}   rC   _PRIMARY_PREFERREDrA   r    r(   r0   rE   s       r"   rC   zPrimaryPreferred.__init__?  s     	+X}eLr$   c                    |j                   r|j                  S t        | j                  t	        j
                  | j                  |            S z(Apply this read preference to Selection.)r   r   r   r    r
   selectr(   rg   s     r"   ri   zPrimaryPreferred.__call__G  sB    ...66==d>P>PR[\ r$   rj   r    rk   r(   r,   r0   rl   rm   rn   rt   rF   ru   rv   rw   rx   rC   ri   r   r   s   @r"   r   r   "  sO    4 I (,"&	M$M M  	M
 
Mr$   r   c                  F     e Zd ZdZdZ	 	 	 d	 	 	 	 	 	 	 d fdZd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.

    :param tag_sets: The :attr:`~tag_sets` for this read preference.
    :param 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.
    :param hedge: The :attr:`~hedge` for this read preference.

    .. versionchanged:: 3.11
       Added ``hedge`` parameter.
    r&   c                2    t         |   t        |||       y r:   )r}   rC   
_SECONDARYr   s       r"   rC   zSecondary.__init__i  s     	X}eDr$   c                j    t        | j                  t        j                  | j                  |            S r   )r   r    r
   r   r(   rg   s     r"   ri   zSecondary.__call__q  s,    2MM299$:L:LiX
 	
r$   rj   r   rt   r   r   s   @r"   r   r   Q  sO    * I (,"&	E$E E  	E
 
E
r$   r   c                  F     e Zd ZdZdZ	 	 	 d	 	 	 	 	 	 	 d fdZd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.

    .. note:: When a :class:`~pymongo.mongo_client.MongoClient` is first
      created reads will be routed to the primary of the replica set until
      an available secondary is discovered.

    :param tag_sets: The :attr:`~tag_sets` for this read preference.
    :param 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.
    :param hedge: The :attr:`~hedge` for this read preference.

    .. versionchanged:: 3.11
       Added ``hedge`` parameter.
    r&   c                2    t         |   t        |||       y r:   )r}   rC   _SECONDARY_PREFERREDr   s       r"   rC   zSecondaryPreferred.__init__  s     	-xNr$   c                    t        | j                  t        j                  | j                  |            }|r|S |j
                  S r   )r   r    r
   r   r(   r   )rA   rh   secondariess      r"   ri   zSecondaryPreferred.__call__  s@    9MM299$:L:LiX
 ...r$   rj   r   rt   r   r   s   @r"   r   r   x  sO    2 I (,"&	O$O O  	O
 
O	/r$   r   c                  F     e Zd ZdZdZ	 	 	 d	 	 	 	 	 	 	 d fdZddZ xZS )Nearestah  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.

    :param tag_sets: The :attr:`~tag_sets` for this read preference.
    :param 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.
    :param hedge: The :attr:`~hedge` for this read preference.

    .. versionchanged:: 3.11
       Added ``hedge`` parameter.
    r&   c                2    t         |   t        |||       y r:   )r}   rC   _NEARESTr   s       r"   rC   zNearest.__init__  s     	8]EBr$   c                j    t        | j                  t        j                  | j                  |            S r   )r   r    r
   r   r(   rg   s     r"   ri   zNearest.__call__  s,    /MM299$:L:LiX
 	
r$   rj   r   rt   r   r   s   @r"   r   r     sO    * I (,"&	C$C C  	C
 
C
r$   r   c                  <    e Zd ZdZdZd	dZd
dZddZddZddZ	y)_AggWritePrefzAgg $out/$merge write preference.

    * If there are readable servers and there is any pre-5.0 server, use
      primary read preference.
    * Otherwise use `pref` read preference.

    :param pref: The read preference to use on MongoDB 5.0+.
    )prefeffective_prefc                <    || _         t        j                  | _        y r:   )r   ReadPreferencePRIMARYr   )rA   r   s     r"   rC   z_AggWritePref.__init__  s    	+9+A+Ar$   c                    |j                   }|j                  t        j                        r|r|dk  rt        j                  | _        y | j                  | _        y )N   )common_wire_versionhas_readable_serverr   PRIMARY_PREFERREDr   r   r   )rA   topology_description	common_wvs      r"   selection_hookz_AggWritePref.selection_hook  sE    (<<	 44^5U5UVB"0"8"8D"&))Dr$   c                $    | j                  |      S r   )r   rg   s     r"   ri   z_AggWritePref.__call__  s    ""9--r$   c                "    d| j                   dS )Nz_AggWritePref(pref=))r   rG   s    r"   rY   z_AggWritePref.__repr__  s    $TYYM33r$   c                .    t        | j                  |      S r:   )getattrr   )rA   rH   s     r"   __getattr__z_AggWritePref.__getattr__  s    t**D11r$   N)r   r3   )r   r   rm   rn   rt   ro   )rH   rp   rm   r   )
rF   ru   rv   rw   rx   rC   r   ri   rY   r   r&   r$   r"   r   r     s(     +IB	,.4
2r$   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)r~   r   r{   _ALL_READ_PREFERENCES)rB   r    r(   s      r"   make_read_preferencer     sZ     xD2$<'$%[\\B$U  y &x??r$   )r   r   	SECONDARYSECONDARY_PREFERREDNEARESTc                  V    e Zd ZdZ e       Z e       Z e       Z	 e
       Z e       Zy)r   a  An enum that defines some commonly used read preference modes.

    Apps can also create a custom read preference, for example::

       Nearest(tag_sets=[{"node":"analytics"}])

    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)rF   ru   rv   rw   r{   r   r   r   r   r   r   r   r   r   r&   r$   r"   r   r     s1    4l iG(*I,.iGr$   r   c                ,    t         j                  |       S )z2Get the read preference mode from mongos/uri name.)r;   index)rH   s    r"   read_pref_mode_from_namer   O  s    t$$r$   c                  <    e Zd ZU dZded<   d	dZd
dZddZd	dZy)MovingAveragez0Tracks an exponentially-weighted moving average.Optional[float]averagec                    d | _         y r:   r   rG   s    r"   rC   zMovingAverage.__init__Y  	    r$   c                l    |dk  ry | j                   || _         y d| j                   z  d|z  z   | _         y )Nr   g?g?r   )rA   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   rG   s    r"   getzMovingAverage.geti  s    ||r$   c                    d | _         y r:   r   rG   s    r"   resetzMovingAverage.resetm  r   r$   Nr   )r   floatrm   rn   )rm   r   )	rF   ru   rv   rw   __annotations__rC   r   r   r   r&   r$   r"   r   r   T  s    :=r$   r   N)r    rk   rm   rk   )r(   r   rm   rp   )r(   r   rm   r,   )r0   rl   rm   rl   )r+   )rB   r,   r    rk   r(   r,   rm   r3   )rH   rp   rm   r,   )/rw   
__future__r   collectionsr   typingr   r   r   r   r	   pymongor
   pymongo.errorsr   pymongo.server_selectorsr   r   r   pymongo.topology_descriptionr   r~   r   r   r   r   r;   rp   _Hedgerq   r#   r)   r-   r1   r3   r{   r   r   r   r   r   r   r   _MODESr   r   r   r&   r$   r"   <module>r      sG   I "  B B + -
 2@ 
  
c	GCH%&.T
Z Zzk 8,{ ,^$
 $
N-/ -/`$
k $
N%2 %2P !"2I?QSZ[  CE@
@+@<?@@
; ;|%
 r$   