o SbP @sdZddlmZddlmZmZmZmZmZddl m Z ddl m Z ddl mZmZdZdZdZd Zd Zd Zd d ZddZddZddZeeefZeeeefZGdddeZGdddeZGdddeZ GdddeZ!GdddeZ"GdddeZ#Gd d!d!Z$ee e!e"e#fZ% "d2d#e&d$eed%e&d&efd'd(Z'd)Z(Gd*d+d+eZ)d,ed&e&fd-d.Z*Gd/d0d0eZ+d1S)3zBUtilities for choosing which member of a replica set to read from.)abc)AnyDictMappingOptionalSequence)max_staleness_selectors)ConfigurationError) member_with_tags_server_selector#secondary_with_tags_server_selector)primaryZprimaryPreferredZ secondaryZsecondaryPreferredZnearestcCsn|dur|St|ttfstd|ft|dkr!td|f|D]}t|tjs2td|fq#t|S)z$Validate tag sets for a MongoClient.Nz'Tag sets %r invalid, must be a sequencerzETag sets %r invalid, must be None or contain at least one set of tagszqTag set %r invalid, must be an instance of dict, bson.son.SON or other type that inherits from collection.Mapping) isinstancelisttuple TypeErrorlen ValueErrorrr)tag_setstagsr?/tmp/pip-target-onvjaxws/lib/python/pymongo/read_preferences.py_validate_tag_sets+s"  rcCsd|S)Nz6maxStalenessSeconds must be a positive integer, not %sr max_stalenessrrr_invalid_max_staleness_msgBsrcCs:|dkrdSt|tstt||dkrtt||S)zValidate max_staleness.r)rintrrrrrrr_validate_max_stalenessGs   r!cCs(|durdSt|tstd|f|S)zValidate hedge.Nz"hedge must be a dictionary, not %r)rdictr)hedgerrr_validate_hedgeUs  r$c @seZdZdZdZ   d'dedeededeed df d d Z e d e fd d Z e d e fddZ e d ee effddZe d efddZe d efddZe d efddZe d eefddZe d efddZddZded efdd Zded efd!d"Zd#d$Zd%d&ZdS)( _ServerModez$Base class for all read preferences.)Z __mongos_modeZ__modeZ __tag_setsZ__max_stalenessZ__hedgeNrmoderrr#returncCs2t||_||_t||_t||_t||_dSN) _MONGOS_MODES_ServerMode__mongos_mode_ServerMode__moder_ServerMode__tag_setsr!_ServerMode__max_stalenessr$_ServerMode__hedge)selfr&rrr#rrr__init__is   z_ServerMode.__init__cCs|jjS)z!The name of this read preference.) __class____name__r/rrrnamevsz_ServerMode.namecC|jS)z(The mongos mode of this read preference.)r*r3rrr mongos_mode{z_ServerMode.mongos_modecCsTd|ji}|jdigfvr|j|d<|jdkr|j|d<|jdifvr(|j|d<|S)zRead preference as a document.r&NrrZmaxStalenessSecondsr#)r*r,r-r.)r/docrrrdocuments     z_ServerMode.documentcCr5)z*The mode of this read preference instance.)r+r3rrrr&r7z_ServerMode.modecCs|jrt|jSigS)arSet ``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. .. seealso:: `Data-Center Awareness `_ )r,rr3rrrrs z_ServerMode.tag_setscCr5)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-r3rrrrsz_ServerMode.max_stalenesscCr5)aThe 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.r3rrrr#sz_ServerMode.hedgecCs|jdkrdSdS)aThe 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`. rrr:r3rrrmin_wire_versions z_ServerMode.min_wire_versioncCsd|j|j|j|jfS)Nz+%s(tag_sets=%r, max_staleness=%r, hedge=%r))r4r,r-r.r3rrr__repr__s z_ServerMode.__repr__othercCs>t|tr|j|jko|j|jko|j|jko|j|jkStSr()rr%r&rrr#NotImplementedr/r>rrr__eq__s     z_ServerMode.__eq__cCs ||k Sr(rr@rrr__ne__ z_ServerMode.__ne__cCs|j|j|j|jdS)zeReturn value of object for pickling. Needed explicitly because __slots__() defined. )r&rrr#)r+r,r-r.r3rrr __getstate__s z_ServerMode.__getstate__cCsD|d|_t|j|_t|d|_t|d|_t|d|_dS)zRestore from pickling.r&rrr#N) r+r)r*rr,r!r-r$r.)r/valuerrr __setstate__s  z_ServerMode.__setstate__NrN)r2 __module__ __qualname____doc__ __slots__r r_TagSets_Hedger0propertystrr4r6rrr9r&rrr#r<r=boolrArBrDrFrrrrr%dsL      r%csReZdZdZdZdfdd Zdedefdd Zd d Zd ede fd dZ Z S)PrimaryaGPrimary 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. rr'Ncstt|tdSr()superrQr0_PRIMARYr3r1rrr0szPrimary.__init__ selectioncCs|jSz*Apply this read preference to a Selection.)primary_selectionr/rUrrr__call__zPrimary.__call__cCsdS)Nz Primary()rr3rrrr= szPrimary.__repr__r>cCst|tr |jtkStSr()rr%r&rSr?r@rrrrA s  zPrimary.__eq__r'N) r2rHrIrJrKr0rrYr=rPrA __classcell__rrrTrrQs rQc XeZdZdZdZ   ddeededeeddffd d Z d e de fd d Z Z S)PrimaryPreferredaPrimaryPreferred 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. :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. rNrrrr#r'ctt|t|||dSr()rRr^r0_PRIMARY_PREFERREDr/rrr#rTrrr00zPrimaryPreferred.__init__rUcCs"|jr|jSt|jt|j|Sz(Apply this read preference to Selection.)rrWr rrselectrrXrrrrY8s zPrimaryPreferred.__call__rG r2rHrIrJrKrrLr rMr0rrYr\rrrTrr^s r^c r]) SecondaryaSecondary 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. rNrrrr#r'cr_r()rRrfr0 _SECONDARYrarTrrr0[rbzSecondary.__init__rUcCt|jt|j|Src)r rrrdrrXrrrrYczSecondary.__call__rGrerrrTrrfB rfc r])SecondaryPreferredaSecondaryPreferred 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. :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. rNrrrr#r'cr_r()rRrkr0_SECONDARY_PREFERREDrarTrrr0s zSecondaryPreferred.__init__rUcCs$t|jt|j|}|r|S|jSrc)r rrrdrrW)r/rUZ secondariesrrrrYs zSecondaryPreferred.__call__rGrerrrTrrkjs  rkc r])NearestavNearest 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. rNrrrr#r'cr_r()rRrmr0_NEARESTrarTrrr0rbzNearest.__init__rUcCrhrc)r rrrdrrXrrrrYrizNearest.__call__rGrerrrTrrmrjrmc@s<eZdZdZdZddZddZddZd d Zd d Z d S) _AggWritePrefa Agg $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. :Parameters: - `pref`: The read preference to use on MongoDB 5.0+. )prefeffective_prefcCs||_tj|_dSr()rpReadPreferencePRIMARYrq)r/rprrrr0s z_AggWritePref.__init__cCs6|j}|tjr|r|dkrtj|_dS|j|_dS)N )Zcommon_wire_versionZhas_readable_serverrrPRIMARY_PREFERREDrsrqrp)r/Ztopology_descriptionZ common_wvrrrselection_hooks   z_AggWritePref.selection_hookcCs ||SrV)rqrXrrrrY z_AggWritePref.__call__cCs d|jfS)Nz_AggWritePref(pref=%r))rpr3rrrr= z_AggWritePref.__repr__cCs t|j|Sr()getattrrq)r/r4rrr __getattr__rxz_AggWritePref.__getattr__N) r2rHrIrJrKr0rvrYr=rzrrrrros   rorr&rrr'cCsB|tkr|digfvrtd|dkrtdtSt|||S)Nz4Read preference primary cannot be combined with tagsrzCRead preference primary cannot be combined with maxStalenessSeconds)rSr rQ_ALL_READ_PREFERENCES)r&rrrrrmake_read_preferencesr|)rsru SECONDARYSECONDARY_PREFERREDNEARESTc@s.eZdZdZeZeZeZ e Z e Z dS)rraDAn 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)r2rHrIrJrQrsr^rurfr}rkr~rmrrrrrrrs2 rrr4cCs t|S)z2Get the read preference mode from mongos/uri name.)r)index)r4rrrread_pref_mode_from_nameBrwrc@sVeZdZUdZeeed<dddZdeddfdd Zdeefd d Z dd d Z dS) MovingAveragez0Tracks an exponentially-weighted moving average.averager'NcC d|_dSr(rr3rrrr0LrCzMovingAverage.__init__samplecCs8|dkrdS|jdur||_dSd|jd||_dS)Nrg?g?r)r/rrrr add_sampleOs   zMovingAverage.add_samplecCr5)z6Get the calculated average, or None if no samples yet.rr3rrrget\rZzMovingAverage.getcCrr(rr3rrrreset`rCzMovingAverage.resetr[) r2rHrIrJrfloat__annotations__r0rrrrrrrrGs    rN)r),rJ collectionsrtypingrrrrrZpymongorZpymongo.errorsr Zpymongo.server_selectorsr r rSr`rgrlrnr)rrr!r$rOrMrLobjectr%rQr^rfrkrmror{r r|Z_MODESrrrrrrrrsR     0(3()  :