
    Ii`S                       S r SSKJr  SSKJr  SSKJrJrJrJ	r	J
r
  SSKJr  SSKJr  SSKJrJr  \(       a  SSKJr  SS	KJr  SrS
rSrSrSrSr\\\4   r\
\\\4      rS)S jrS*S jrS+S jr S,S jr! " S S5      r" " S S\"5      r# " S S\"5      r$ " S S\"5      r% " S S\"5      r& " S S\"5      r' " S S 5      r(\#\$\%\&\'4r) S-       S.S! jjr*S"r+ " S# S$5      r,S/S% jr- " S& S'5      r.g()0zUtilities for choosing which member of a replica set to read from.

.. seealso:: This module is compatible with both the synchronous and asynchronous PyMongo APIs.
    )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                &   U c  U $ [        U [        [        45      (       d  [        SU < S35      e[	        U 5      S:X  a  [        SU < S35      eU  H2  n[        U[        R                  5      (       a  M$  [        SU< S35      e   [        U 5      $ )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     >/venv/lib/python3.13/site-packages/pymongo/read_preferences.py_validate_tag_setsr#   8   s    hu..)H</KLMM
8}|#]^
 	
 $,,4( #% %   >    c                    SU -  $ )Nz6maxStalenessSeconds must be a positive integer, not %s max_stalenesss    r"   _invalid_max_staleness_msgr)   O   s    CmSSr$   c                    U S:X  a  g[        U [        5      (       d  [        [        U 5      5      eU S::  a  [	        [        U 5      5      eU $ )zValidate max_staleness.r   )r   intr   r)   r   r'   s    r"   _validate_max_stalenessr-   T   sJ    mS))2=ABB3MBCCr$   c                V    U c  g[        U [        5      (       d  [        SU < 35      eU $ )zValidate hedge.Nz hedge must be a dictionary, not )r   dictr   )hedges    r"   _validate_hedger1   b   s/    }eT"":5)DEELr$   c                     \ rS rSrSrSr   S         SS jjr\SS j5       r\SS j5       r	\SS j5       r
\SS	 j5       r\SS
 j5       r\SS j5       r\SS j5       r\SS j5       rSS jrSS jrSS jrSS jrSS jrSS jrSrg)_ServerModem   z$Base class for all read preferences.)__mongos_mode__mode
__tag_sets__max_staleness__hedgeNc                    [         U   U l        Xl        [        U5      U l        [        U5      U l        [        U5      U l        g N)	_MONGOS_MODES_ServerMode__mongos_mode_ServerMode__moder#   _ServerMode__tag_setsr-   _ServerMode__max_stalenessr1   _ServerMode__hedge)selfmoder    r(   r0   s        r"   __init___ServerMode.__init__r   s;     +40,X66}E&u-r$   c                .    U R                   R                  $ )z!The name of this read preference.)	__class____name__rB   s    r"   name_ServerMode.name   s     ~~&&&r$   c                    U R                   $ )z(The mongos mode of this read preference.)r=   rI   s    r"   mongos_mode_ServerMode.mongos_mode   s     !!!r$   c                    SU R                   0nU R                  S0 /4;  a  U R                  US'   U R                  S:w  a  U R                  US'   U R                  S0 4;  a  U R                  US'   U$ )zRead preference as a document.rC   Nr!   r+   maxStalenessSecondsr0   )r=   r?   r@   rA   )rB   docs     r"   document_ServerMode.document   st      &t'9'9:??4",.//CK2%)-)=)=C%&<<bz)<<CL
r$   c                    U R                   $ )z*The mode of this read preference instance.)r>   rI   s    r"   rC   _ServerMode.mode   s     {{r$   c                T    U R                   (       a  [        U R                   5      $ 0 /$ )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." 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   rI   s    r"   r    _ServerMode.tag_sets   s     ( )-tDOO$AbTAr$   c                    U R                   $ )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@   rI   s    r"   r(   _ServerMode.max_staleness   s     ###r$   c                    U R                   $ )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
)rA   rI   s    r"   r0   _ServerMode.hedge   s    , ||r$   c                *    U R                   S:X  a  S$ S$ )aR  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      rY   rI   s    r"   min_wire_version_ServerMode.min_wire_version   s     ((B.q5A5r$   c                z    SR                  U R                  U R                  U R                  U R                  5      $ )Nz1{}(tag_sets={!r}, max_staleness={!r}, hedge={!r}))formatrJ   r?   r@   rA   rI   s    r"   __repr___ServerMode.__repr__   s3    BIIIIOO  LL	
 	
r$   c                *   [        U[        5      (       ay  U R                  UR                  :H  =(       aY    U R                  UR                  :H  =(       a9    U R                  UR                  :H  =(       a    U R
                  UR
                  :H  $ [        $ r;   )r   r3   rC   r    r(   r0   NotImplementedrB   others     r"   __eq___ServerMode.__eq__   sq    e[))		UZZ' .MMU^^3.&&%*=*==. JJ%++-	 r$   c                    X:X  + $ r;   r&   rg   s     r"   __ne___ServerMode.__ne__   s      r$   c                `    U R                   U R                  U R                  U R                  S.$ )zUReturn value of object for pickling.

Needed explicitly because __slots__() defined.
)rC   r    r(   r0   )r>   r?   r@   rA   rI   s    r"   __getstate___ServerMode.__getstate__   s,     KK!11\\	
 	
r$   c                    US   U l         [        U R                      U l        [        US   5      U l        [        US   5      U l        [        US   5      U l        g)zRestore from pickling.rC   r    r(   r0   N)	r>   r<   r=   r#   r?   r-   r@   r1   rA   )rB   values     r"   __setstate___ServerMode.__setstate__   sQ    Fm*4;;7,U:->?6u_7MN&uW~6r$   c                    U$ r;   r&   rB   	selections     r"   __call___ServerMode.__call__  s    r$   )r9   r8   r6   r5   r7   Nr+   N)
rC   r,   r    Optional[_TagSets]r(   r,   r0   Optional[_Hedge]returnNoner}   str)r}   zdict[str, Any])r}   r,   )r}   _TagSets)r}   r|   rh   r   r}   bool)rr   zMapping[str, Any]r}   r~   rw   r   r}   r   )rH   
__module____qualname____firstlineno____doc__	__slots__rD   propertyrJ   rM   rR   rC   r    r(   r0   r_   rc   ri   rl   ro   rs   rx   __static_attributes__r&   r$   r"   r3   r3   m   s
   .WI
 (,"&.. %. 	.
  . 
. ' ' " " 	 	   B B* $ $  . 
6 
6
!

7r$   r3   c                  R   ^  \ rS rSrSrSrSU 4S jjrS	S jrS
S jrSS jr	Sr
U =r$ )Primaryi
  a/  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U ]  [        5        g r;   )superrD   _PRIMARY)rB   rG   s    r"   rD   Primary.__init__  s    "r$   c                    UR                   $ z*Apply this read preference to a Selection.)primary_selectionrv   s     r"   rx   Primary.__call__  s    ***r$   c                    g)Nz	Primary()r&   rI   s    r"   rc   Primary.__repr__  s    r$   c                ^    [        U[        5      (       a  UR                  [        :H  $ [        $ r;   )r   r3   rC   r   rf   rg   s     r"   ri   Primary.__eq__   s$    e[))::))r$   r}   r~   r   r   r   )rH   r   r   r   r   r   rD   rx   rc   ri   r   __classcell__rG   s   @r"   r   r   
  s(     I#+ r$   r   c                  V   ^  \ rS rSrSrSr   S       SU 4S jjjrSS jrSrU =r	$ )	PrimaryPreferredi&  a@  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                0   > [         TU ]  [        XU5        g r;   )r   rD   _PRIMARY_PREFERREDrB   r    r(   r0   rG   s       r"   rD   PrimaryPreferred.__init__C  s     	+XeLr$   c                    UR                   (       a  UR                  $ [        U R                  [        R
                  " U R                  U5      5      $ z(Apply this read preference to Selection.)r   r   r   r    r
   selectr(   rv   s     r"   rx   PrimaryPreferred.__call__K  sB    ...66==d>P>PR[\ r$   rz   r    r{   r(   r,   r0   r|   r}   r~   r   
rH   r   r   r   r   r   rD   rx   r   r   r   s   @r"   r   r   &  sZ    4 I (,"&	M$M M  	M
 
M M r$   r   c                  V   ^  \ rS rSrSrSr   S       SU 4S jjjrSS jrSrU =r	$ )		SecondaryiU  a  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                0   > [         TU ]  [        XU5        g r;   )r   rD   
_SECONDARYr   s       r"   rD   Secondary.__init__m  s     	XeDr$   c                l    [        U R                  [        R                  " U R                  U5      5      $ r   )r   r    r
   r   r(   rv   s     r"   rx   Secondary.__call__u  s,    2MM299$:L:LiX
 	
r$   rz   r   r   r   r   s   @r"   r   r   U  sZ    * I (,"&	E$E E  	E
 
E E
 
r$   r   c                  V   ^  \ rS rSrSrSr   S       SU 4S jjjrSS jrSrU =r	$ )	SecondaryPreferredi|  aC  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                0   > [         TU ]  [        XU5        g r;   )r   rD   _SECONDARY_PREFERREDr   s       r"   rD   SecondaryPreferred.__init__  s     	-xNr$   c                    [        U R                  [        R                  " U R                  U5      5      nU(       a  U$ UR
                  $ r   )r   r    r
   r   r(   r   )rB   rw   secondariess      r"   rx   SecondaryPreferred.__call__  s@    9MM299$:L:LiX
 ...r$   rz   r   r   r   r   s   @r"   r   r   |  sZ    2 I (,"&	O$O O  	O
 
O O	/ 	/r$   r   c                  V   ^  \ rS rSrSrSr   S       SU 4S jjjrSS jrSrU =r	$ )	Nearesti  a(  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                0   > [         TU ]  [        XU5        g r;   )r   rD   _NEARESTr   s       r"   rD   Nearest.__init__  s     	8EBr$   c                l    [        U R                  [        R                  " U R                  U5      5      $ r   )r   r    r
   r   r(   rv   s     r"   rx   Nearest.__call__  s,    /MM299$:L:LiX
 	
r$   rz   r   r   r   r   s   @r"   r   r     sZ    * I (,"&	C$C C  	C
 
C C
 
r$   r   c                  N    \ rS rSrSrSrSS jrSS jrSS jrSS jr	SS jr
S	rg
)_AggWritePrefi  zAgg $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                :    Xl         [        R                  U l        g r;   )r   ReadPreferencePRIMARYr   )rB   r   s     r"   rD   _AggWritePref.__init__  s    	+9+A+Ar$   c                    UR                   nUR                  [        R                  5      (       a#  U(       a  US:  a  [        R                  U l        g U R                  U l        g )N   )common_wire_versionhas_readable_serverr   PRIMARY_PREFERREDr   r   r   )rB   topology_description	common_wvs      r"   selection_hook_AggWritePref.selection_hook  sH    (<<	 44^5U5UVVB"0"8"8D"&))Dr$   c                $    U R                  U5      $ r   )r   rv   s     r"   rx   _AggWritePref.__call__  s    ""9--r$   c                $    SU R                   < S3$ )Nz_AggWritePref(pref=))r   rI   s    r"   rc   _AggWritePref.__repr__  s    $TYYM33r$   c                .    [        U R                  U5      $ r;   )getattrr   )rB   rJ   s     r"   __getattr___AggWritePref.__getattr__  s    t**D11r$   )r   r   N)r   r3   )r   r   r}   r~   r   r   )rJ   r   r}   r   )rH   r   r   r   r   r   rD   r   rx   rc   r   r   r&   r$   r"   r   r     s(     +IB	,.4
2r$   r   c                    U [         :X  a/  US 0 /4;  a  [        S5      eUS:w  a  [        S5      e[        5       $ [        U    " X5      $ )Nz4Read preference primary cannot be combined with tagsr+   zCRead preference primary cannot be combined with maxStalenessSeconds)r   r   r   _ALL_READ_PREFERENCES)rC   r    r(   s      r"   make_read_preferencer     sX     xD2$<'$%[\\B$U  y &x??r$   )r   r   	SECONDARYSECONDARY_PREFERREDNEARESTc                  ^    \ rS rSrSr\" 5       r\" 5       r\	" 5       r
\" 5       r\" 5       rSrg)r   i  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.
r&   N)rH   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r&   r$   r"   r   r     s1    4l iG(*I,.iGr$   r   c                ,    [         R                  U 5      $ )z2Get the read preference mode from mongos/uri name.)r<   index)rJ   s    r"   read_pref_mode_from_namer   S  s    t$$r$   c                  L    \ rS rSr% SrS\S'   SS jrSS jrSS jrSS jr	S	r
g
)MovingAverageiX  z0Tracks an exponentially-weighted moving average.Optional[float]averagec                    S U l         g r;   r   rI   s    r"   rD   MovingAverage.__init__]  	    r$   c                    US:  a  [        SU 35      eU R                  c  Xl        g SU R                  -  SU-  -   U l        g )Nr   zduration cannot be negative g?g?)r   r   )rB   samples     r"   
add_sampleMovingAverage.add_sample`  sF    A:;F8DEE<<!L -f<DLr$   c                    U R                   $ )z6Get the calculated average, or None if no samples yet.r   rI   s    r"   getMovingAverage.getj  s    ||r$   c                    S U l         g r;   r   rI   s    r"   resetMovingAverage.resetn  r   r$   r   Nr   )r   floatr}   r~   )r}   r   )rH   r   r   r   r   __annotations__rD   r   r   r   r   r&   r$   r"   r   r   X  s    :=r$   r   N)r    r{   r}   r{   )r(   r   r}   r   )r(   r   r}   r,   )r0   r|   r}   r|   )r+   )rC   r,   r    r{   r(   r,   r}   r3   )rJ   r   r}   r,   )/r   
__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<   r   _Hedger   r#   r)   r-   r1   r3   r   r   r   r   r   r   r   r   _MODESr   r   r   r&   r$   r"   <module>r      sJ  
 #  B B + -
 2@  
  
c	GCH%&.T
Z Zzk 8,{ ,^$
 $
N-/ -/`$
k $
N%2 %2P !"2I?QSZ[  CE@
@+@<?@@
; ;|%
 r$   