
    &g                   T   S r SSKJr  SSKrSSKrSSKrSSKrSSKrSSKJ	r	  SSK
JrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJr  SSKJrJrJ r   SSK!J"r"  SSK#J$r$J%r%J&r&J'r'  SS	K(J)r)J*r*J+r+  SS
K,J-r-J.r.  SSK/J0r0  SSK1J2r2  SSK3J4r4  SSK5J6r6  SSK7J8r8J9r9  SSK:J;r;  SSK<J=r=J>r>J?r?J@r@JArAJBrBJCrCJDrDJErEJFrFJGrGJHrH  SSKIJJrJJKrKJLrL  SSKMJNrNJOrOJPrPJQrQJRrR  SSKSJTrTJUrUJVrV  SSKWJXrXJYrY  SSKZJ[r[J\r\J]r]J^r^J_r_J`r`Jara  SSKbJcrcJdrd  SSKeJfrf  SSKgJhrh  SSKiJjrj  SSKkJlrlJmrm  SSKnJoroJprpJqrqJrrrJsrsJtrt  SSKuJvrvJwrwJxrxJyryJzrzJ{r{J|r|  SSK}J~r~Jr  \(       aD  SSKJr  SS KJr  SS!KJr  SS"K1JrJr  SS#KJr  SS$KJr  SS%KJr  SS&KJr  SS'KJr  SS(KJr  SS)KgJr  \" S*5      r\\S+   S,\/\\\\4   4   r\\S+   S-S,\d/\\\\4   4   rS.r\\]\\\[\^\`\_4   r " S/ S0\%GR6                  \\r   5      rS:S1 jrS;S2 jr " S3 S45      r " S5 S6\\   5      rS<S7 jrS=S8 jr\J(       a  \GRF                  " \S99  gg)>a  Tools for connecting to MongoDB.

.. seealso:: :doc:`/examples/high_availability` for examples of connecting
   to replica sets or sets of mongos servers.

To get a :class:`~pymongo.asynchronous.database.AsyncDatabase` instance from a
:class:`AsyncMongoClient` use either dictionary-style or attribute-style
access:

.. doctest::

  >>> from pymongo import AsyncMongoClient
  >>> c = AsyncMongoClient()
  >>> c.test_database
  AsyncDatabase(AsyncMongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test_database')
  >>> c["test-database"]
  AsyncDatabase(AsyncMongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test-database')
    )annotationsN)defaultdict)TYPE_CHECKINGAnyAsyncContextManagerAsyncGeneratorCallable
Collection	Coroutine	FrozenSetGenericMappingMutableMappingNoReturnOptionalSequenceTypeTypeVarUnioncast)DEFAULT_CODEC_OPTIONSCodecOptionsTypeRegistry)	Timestamp)_csotcommonhelpers_sharedperiodic_executor)client_sessiondatabase
uri_parser)AsyncChangeStreamAsyncClusterChangeStream)_AsyncClientBulk)_EmptyServerSession)AsyncCommandCursor)TopologySettings)Topology_ErrorContext)ClientOptions)AutoReconnectBulkWriteErrorClientBulkWriteExceptionConfigurationErrorConnectionFailureInvalidOperationNotPrimaryErrorOperationFailurePyMongoErrorServerSelectionTimeoutErrorWaitQueueTimeoutErrorWriteConcernError)_HAS_REGISTER_AT_FORK_async_create_lock_release_locks)_CLIENT_LOGGER_COMMAND_LOGGER
_debug_log_log_client_error_log_or_warn)_CursorAddress_GetMore_Query)ConnectionClosedReason_EventListeners)
DeleteMany	DeleteOne	InsertOne
ReplaceOne
UpdateMany	UpdateOne_Op)ReadPreference_ServerMode)ClientBulkWriteResult)writable_server_selector)SERVER_TYPE)TOPOLOGY_TYPETopologyDescription)ClusterTime_Address_CollationIn_DocumentType_DocumentTypeArg	_Pipeline)
SRV_SCHEME_check_options_handle_option_deprecations_handle_security_options_normalize_options_validate_urisplit_hosts)DEFAULT_WRITE_CONCERNWriteConcern)TracebackType)ObjectId)
_AsyncBulk)AsyncClientSession_ServerSession)_ConnectionManager
_Encrypter)AsyncConnection)Server)ReadConcern)Response)	SelectionTrd   ri   rj   Fc                    ^  \ rS rSr% SrSrSr\R                  " 5       r	S\
S'         SO               SPU 4S jjjrSQS	 jr        SRS
 jr      SSS jr      STS jrSQS jrSUSVS jjrSWS jrSQS jrSXS jr            SY                         SZS jj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SaS jrSaS jrSbS jr SbS jr!SQS jr" SU       ScS jjr#SdS  jr$   Se       SfS! jjr% SU   SgS" jjr&      ShS# jr'     Si           SjS$ jjr(     Si           SkS% jjr)SlS& jr*SmS' jr+SnS( jr,Sr-SoS) jr.\.r/SpS* jr0\SqS+ j5       r1\SqS, j5       r2\SrS- j5       r3\SrS. j5       r4\SsS/ j5       r5\SsS0 j5       r6StS1 jr7SQS2 jr8\9(       d  \8r:SuS3 jr;\<Rz                        SvS4 j5       r>   Sw             SxS5 jjr?      SyS6 jr@\<Rz                          SzS7 j5       rA        S{S8 jrB\CR                   SU       S|S9 jj5       rE SU             S}S: jjrF\CR                       S~                   SS; jj5       rG   S               SS< jjrH  S             SS= jjrI            SS> jrJ            SS? jrK  S         SS@ jjrL          SSA jrM          SSB jrNSQSC jrOSQSD jrP    SSE jrQ\<Rz                   S     SSF jj5       rR      SSG jrS SU   SSH jjrT  S       SSI jjrU  S       SSJ jjrV  S     SSK jjrW\CR                    S       SSL jj5       rX\CR                         S                 SSM jj5       rYSNrZU =r[$ )AsyncMongoClient   	localhostii  )document_classtz_awareconnectzweakref.WeakValueDictionary_clientsNc                  > U=(       d    [         nUUUUUUS.UEU l        Uc  U R                  n[        U[        5      (       a  U/nUc  U R
                  n[        U[        5      (       d  [        S[        U5       35      eXl	        X l
        SU l        SU l        SU l        SU l        UR                  SS5      n	UR                  SS5      n
UR                  SS5      n[         R"                  " U5      nXS'   SU0U l        ['        5       nS	nSnSnSn[         R"                  " 5       nSnUR)                  S
5      nUR)                  S5      n[+        U R                   Vs/ s H  nSU;   d  M  UPM     sn5      S:  a  [-        S5      eU R                   H  nSU;   am  [/        UUSSS	US9nUR1                  [2        5      nUR5                  US   5        US   =(       d    UnUS   =(       d    UnUS   =(       d    UnUS   nUS   nMv  UR5                  [7        UU R                  5      5        M     U(       d  [-        S5      eU Vs/ s H  nUS   PM
     sn H  n[9        U5      (       d  M    O   Ub  XlS'   Uc  UR)                  SS	5      nUc"  SSKJn  UR)                  SU" 5       (       + 5      nXLS'   X\S'   U R?                  UU5      nUc   UR)                  S[         R@                  5      nU=(       d    UR)                  S5      nU RC                  UU5      nUR)                  SU5      nUR)                  SU5      n[E        UUUU[F        5      U l$        UU l%        [M        5       U l'        / U l(        SU l)        U R$                  R5                  UUUUUUUU	U
US.
5        [T        TU ]  U RH                  RX                  U RH                  RZ                  U RH                  R\                  U RH                  R^                  5        U(       d  U Ra                  UUU5        S	U l1        S	U l2        SU l3        U(       d  U Ri                  5         [F        (       a  U(       a  U Rk                  5         gggs  snf s  snf )al  Client for a MongoDB instance, a replica set, or a set of mongoses.

.. warning:: Starting in PyMongo 4.0, ``directConnection`` now has a default value of
  False instead of None.
  For more details, see the relevant section of the PyMongo 4.x migration guide:
  :ref:`pymongo4-migration-direct-connection`.

.. warning:: This API is currently in beta, meaning the classes, methods, and behaviors described within may change before the full release.

The client object is thread-safe and has connection-pooling built in.
If an operation fails because of a network error,
:class:`~pymongo.errors.ConnectionFailure` is raised and the client
reconnects in the background. Application code should handle this
exception (recognizing that the operation failed) and then continue to
execute.

The `host` parameter can be a full `mongodb URI
<https://dochub.mongodb.org/core/connections>`_, in addition to
a simple hostname. It can also be a list of hostnames but no more
than one URI. Any port specified in the host string(s) will override
the `port` parameter. For username and
passwords reserved characters like ':', '/', '+' and '@' must be
percent encoded following RFC 2396::

    from urllib.parse import quote_plus

    uri = "mongodb://%s:%s@%s" % (
        quote_plus(user), quote_plus(password), host)
    client = AsyncMongoClient(uri)

Unix domain sockets are also supported. The socket path must be percent
encoded in the URI::

    uri = "mongodb://%s:%s@%s" % (
        quote_plus(user), quote_plus(password), quote_plus(socket_path))
    client = AsyncMongoClient(uri)

But not when passed as a simple hostname::

    client = AsyncMongoClient('/tmp/mongodb-27017.sock')

Starting with version 3.6, PyMongo supports mongodb+srv:// URIs. The
URI must include one, and only one, hostname. The hostname will be
resolved to one or more DNS `SRV records
<https://en.wikipedia.org/wiki/SRV_record>`_ which will be used
as the seed list for connecting to the MongoDB deployment. When using
SRV URIs, the `authSource` and `replicaSet` configuration options can
be specified using `TXT records
<https://en.wikipedia.org/wiki/TXT_record>`_. See the
`Initial DNS Seedlist Discovery spec
<https://github.com/mongodb/specifications/blob/master/source/
initial-dns-seedlist-discovery/initial-dns-seedlist-discovery.md>`_
for more details. Note that the use of SRV URIs implicitly enables
TLS support. Pass tls=false in the URI to override.

.. note:: AsyncMongoClient creation will block waiting for answers from
  DNS when mongodb+srv:// URIs are used.

.. note:: Starting with version 3.0 the :class:`AsyncMongoClient`
  constructor no longer blocks while connecting to the server or
  servers, and it no longer raises
  :class:`~pymongo.errors.ConnectionFailure` if they are
  unavailable, nor :class:`~pymongo.errors.ConfigurationError`
  if the user's credentials are wrong. Instead, the constructor
  returns immediately and launches the connection process on
  background threads. You can check if the server is available
  like this::

    from pymongo.errors import ConnectionFailure
    client = AsyncMongoClient()
    try:
        # The ping command is cheap and does not require auth.
        client.admin.command('ping')
    except ConnectionFailure:
        print("Server not available")

.. warning:: When using PyMongo in a multiprocessing context, please
  read :ref:`multiprocessing` first.

.. note:: Many of the following options can be passed using a MongoDB
  URI or keyword parameters. If the same option is passed in a URI and
  as a keyword parameter the keyword parameter takes precedence.

:param host: hostname or IP address or Unix domain socket
    path of a single mongod or mongos instance to connect to, or a
    mongodb URI, or a list of hostnames (but no more than one mongodb
    URI). If `host` is an IPv6 literal it must be enclosed in '['
    and ']' characters
    following the RFC2732 URL syntax (e.g. '[::1]' for localhost).
    Multihomed and round robin DNS addresses are **not** supported.
:param port: port number on which to connect
:param document_class: default class to use for
    documents returned from queries on this client
:param tz_aware: if ``True``,
    :class:`~datetime.datetime` instances returned as values
    in a document by this :class:`AsyncMongoClient` will be timezone
    aware (otherwise they will be naive)
:param connect: **Not supported by AsyncMongoClient**.
:param type_registry: instance of
    :class:`~bson.codec_options.TypeRegistry` to enable encoding
    and decoding of custom types.
:param kwargs: **Additional optional parameters available as keyword arguments:**

  - `datetime_conversion` (optional): Specifies how UTC datetimes should be decoded
    within BSON. Valid options include 'datetime_ms' to return as a
    DatetimeMS, 'datetime' to return as a datetime.datetime and
    raising a ValueError for out-of-range values, 'datetime_auto' to
    return DatetimeMS objects when the underlying datetime is
    out-of-range and 'datetime_clamp' to clamp to the minimum and
    maximum possible datetimes. Defaults to 'datetime'. See
    :ref:`handling-out-of-range-datetimes` for details.
  - `directConnection` (optional): if ``True``, forces this client to
     connect directly to the specified MongoDB host as a standalone.
     If ``false``, the client connects to the entire replica set of
     which the given MongoDB host(s) is a part. If this is ``True``
     and a mongodb+srv:// URI or a URI containing multiple seeds is
     provided, an exception will be raised.
  - `maxPoolSize` (optional): The maximum allowable number of
    concurrent connections to each connected server. Requests to a
    server will block if there are `maxPoolSize` outstanding
    connections to the requested server. Defaults to 100. Can be
    either 0 or None, in which case there is no limit on the number
    of concurrent connections.
  - `minPoolSize` (optional): The minimum required number of concurrent
    connections that the pool will maintain to each connected server.
    Default is 0.
  - `maxIdleTimeMS` (optional): The maximum number of milliseconds that
    a connection can remain idle in the pool before being removed and
    replaced. Defaults to `None` (no limit).
  - `maxConnecting` (optional): The maximum number of connections that
    each pool can establish concurrently. Defaults to `2`.
  - `timeoutMS`: (integer or None) Controls how long (in
    milliseconds) the driver will wait when executing an operation
    (including retry attempts) before raising a timeout error.
    ``0`` or ``None`` means no timeout.
  - `socketTimeoutMS`: (integer or None) Controls how long (in
    milliseconds) the driver will wait for a response after sending an
    ordinary (non-monitoring) database operation before concluding that
    a network error has occurred. ``0`` or ``None`` means no timeout.
    Defaults to ``None`` (no timeout).
  - `connectTimeoutMS`: (integer or None) Controls how long (in
    milliseconds) the driver will wait during server monitoring when
    connecting a new socket to a server before concluding the server
    is unavailable. ``0`` or ``None`` means no timeout.
    Defaults to ``20000`` (20 seconds).
  - `server_selector`: (callable or None) Optional, user-provided
    function that augments server selection rules. The function should
    accept as an argument a list of
    :class:`~pymongo.server_description.ServerDescription` objects and
    return a list of server descriptions that should be considered
    suitable for the desired operation.
  - `serverSelectionTimeoutMS`: (integer) Controls how long (in
    milliseconds) the driver will wait to find an available,
    appropriate server to carry out a database operation; while it is
    waiting, multiple server monitoring operations may be carried out,
    each controlled by `connectTimeoutMS`. Defaults to ``30000`` (30
    seconds).
  - `waitQueueTimeoutMS`: (integer or None) How long (in milliseconds)
    a thread will wait for a socket from the pool if the pool has no
    free sockets. Defaults to ``None`` (no timeout).
  - `heartbeatFrequencyMS`: (optional) The number of milliseconds
    between periodic server checks, or None to accept the default
    frequency of 10 seconds.
  - `serverMonitoringMode`: (optional) The server monitoring mode to use.
    Valid values are the strings: "auto", "stream", "poll". Defaults to "auto".
  - `appname`: (string or None) The name of the application that
    created this AsyncMongoClient instance. The server will log this value
    upon establishing each connection. It is also recorded in the slow
    query log and profile collections.
  - `driver`: (pair or None) A driver implemented on top of PyMongo can
    pass a :class:`~pymongo.driver_info.DriverInfo` to add its name,
    version, and platform to the message printed in the server log when
    establishing a connection.
  - `event_listeners`: a list or tuple of event listeners. See
    :mod:`~pymongo.monitoring` for details.
  - `retryWrites`: (boolean) Whether supported write operations
    executed within this AsyncMongoClient will be retried once after a
    network error. Defaults to ``True``.
    The supported write operations are:

      - :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, as long as
        :class:`~pymongo.asynchronous.operations.UpdateMany` or
        :class:`~pymongo.asynchronous.operations.DeleteMany` are not included.
      - :meth:`~pymongo.asynchronous.collection.AsyncCollection.delete_one`
      - :meth:`~pymongo.asynchronous.collection.AsyncCollection.insert_one`
      - :meth:`~pymongo.asynchronous.collection.AsyncCollection.insert_many`
      - :meth:`~pymongo.asynchronous.collection.AsyncCollection.replace_one`
      - :meth:`~pymongo.asynchronous.collection.AsyncCollection.update_one`
      - :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one_and_delete`
      - :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one_and_replace`
      - :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one_and_update`

    Unsupported write operations include, but are not limited to,
    :meth:`~pymongo.asynchronous.collection.AsyncCollection.aggregate` using the ``$out``
    pipeline operator and any operation with an unacknowledged write
    concern (e.g. {w: 0})). See
    https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.md
  - `retryReads`: (boolean) Whether supported read operations
    executed within this AsyncMongoClient will be retried once after a
    network error. Defaults to ``True``.
    The supported read operations are:
    :meth:`~pymongo.asynchronous.collection.AsyncCollection.find`,
    :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one`,
    :meth:`~pymongo.asynchronous.collection.AsyncCollection.aggregate` without ``$out``,
    :meth:`~pymongo.asynchronous.collection.AsyncCollection.distinct`,
    :meth:`~pymongo.asynchronous.collection.AsyncCollection.count`,
    :meth:`~pymongo.asynchronous.collection.AsyncCollection.estimated_document_count`,
    :meth:`~pymongo.asynchronous.collection.AsyncCollection.count_documents`,
    :meth:`pymongo.asynchronous.collection.AsyncCollection.watch`,
    :meth:`~pymongo.asynchronous.collection.AsyncCollection.list_indexes`,
    :meth:`pymongo.asynchronous.database.AsyncDatabase.watch`,
    :meth:`~pymongo.asynchronous.database.AsyncDatabase.list_collections`,
    :meth:`pymongo.asynchronous.mongo_client.AsyncMongoClient.watch`,
    and :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.list_databases`.

    Unsupported read operations include, but are not limited to
    :meth:`~pymongo.asynchronous.database.AsyncDatabase.command` and any getMore
    operation on a cursor.

    Enabling retryable reads makes applications more resilient to
    transient errors such as network failures, database upgrades, and
    replica set failovers. For an exact definition of which errors
    trigger a retry, see the `retryable reads specification
    <https://github.com/mongodb/specifications/blob/master/source/retryable-reads/retryable-reads.md>`_.

  - `compressors`: Comma separated list of compressors for wire
    protocol compression. The list is used to negotiate a compressor
    with the server. Currently supported options are "snappy", "zlib"
    and "zstd". Support for snappy requires the
    `python-snappy <https://pypi.org/project/python-snappy/>`_ package.
    zlib support requires the Python standard library zlib module. zstd
    requires the `zstandard <https://pypi.org/project/zstandard/>`_
    package. By default no compression is used. Compression support
    must also be enabled on the server. MongoDB 3.6+ supports snappy
    and zlib compression. MongoDB 4.2+ adds support for zstd.
    See :ref:`network-compression-example` for details.
  - `zlibCompressionLevel`: (int) The zlib compression level to use
    when zlib is used as the wire protocol compressor. Supported values
    are -1 through 9. -1 tells the zlib library to use its default
    compression level (usually 6). 0 means no compression. 1 is best
    speed. 9 is best compression. Defaults to -1.
  - `uuidRepresentation`: The BSON representation to use when encoding
    from and decoding to instances of :class:`~uuid.UUID`. Valid
    values are the strings: "standard", "pythonLegacy", "javaLegacy",
    "csharpLegacy", and "unspecified" (the default). New applications
    should consider setting this to "standard" for cross language
    compatibility. See :ref:`handling-uuid-data-example` for details.
  - `unicode_decode_error_handler`: The error handler to apply when
    a Unicode-related error occurs during BSON decoding that would
    otherwise raise :exc:`UnicodeDecodeError`. Valid options include
    'strict', 'replace', 'backslashreplace', 'surrogateescape', and
    'ignore'. Defaults to 'strict'.
  - `srvServiceName`: (string) The SRV service name to use for
    "mongodb+srv://" URIs. Defaults to "mongodb". Use it like so::

        AsyncMongoClient("mongodb+srv://example.com/?srvServiceName=customname")
  - `srvMaxHosts`: (int) limits the number of mongos-like hosts a client will
    connect to. More specifically, when a "mongodb+srv://" connection string
    resolves to more than srvMaxHosts number of hosts, the client will randomly
    choose an srvMaxHosts sized subset of hosts.


  | **Write Concern options:**
  | (Only set if passed. No default values.)

  - `w`: (integer or string) If this is a replica set, write operations
    will block until they have been replicated to the specified number
    or tagged set of servers. `w=<int>` always includes the replica set
    primary (e.g. w=3 means write to the primary and wait until
    replicated to **two** secondaries). Passing w=0 **disables write
    acknowledgement** and all other write concern options.
  - `wTimeoutMS`: **DEPRECATED** (integer) Used in conjunction with `w`.
    Specify a value in milliseconds to control how long to wait for write propagation
    to complete. If replication does not complete in the given
    timeframe, a timeout exception is raised. Passing wTimeoutMS=0
    will cause **write operations to wait indefinitely**.
  - `journal`: If ``True`` block until write operations have been
    committed to the journal. Cannot be used in combination with
    `fsync`. Write operations will fail with an exception if this
    option is used when the server is running without journaling.
  - `fsync`: If ``True`` and the server is running without journaling,
    blocks until the server has synced all data files to disk. If the
    server is running with journaling, this acts the same as the `j`
    option, blocking until write operations have been committed to the
    journal. Cannot be used in combination with `j`.

  | **Replica set keyword arguments for connecting with a replica set
    - either directly or via a mongos:**

  - `replicaSet`: (string or None) The name of the replica set to
    connect to. The driver will verify that all servers it connects to
    match this name. Implies that the hosts specified are a seed list
    and the driver should attempt to find all members of the set.
    Defaults to ``None``.

  | **Read Preference:**

  - `readPreference`: The replica set read preference for this client.
    One of ``primary``, ``primaryPreferred``, ``secondary``,
    ``secondaryPreferred``, or ``nearest``. Defaults to ``primary``.
  - `readPreferenceTags`: Specifies a tag set as a comma-separated list
    of colon-separated key-value pairs. For example ``dc:ny,rack:1``.
    Defaults to ``None``.
  - `maxStalenessSeconds`: (integer) 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.
    Defaults to ``-1``, meaning no maximum. If maxStalenessSeconds
    is set, it must be a positive integer greater than or equal to
    90 seconds.

  .. seealso:: :doc:`/examples/server_selection`

  | **Authentication:**

  - `username`: A string.
  - `password`: A string.

    Although username and password must be percent-escaped in a MongoDB
    URI, they must not be percent-escaped when passed as parameters. In
    this example, both the space and slash special characters are passed
    as-is::

      AsyncMongoClient(username="user name", password="pass/word")

  - `authSource`: The database to authenticate on. Defaults to the
    database specified in the URI, if provided, or to "admin".
  - `authMechanism`: See :data:`~pymongo.auth.MECHANISMS` for options.
    If no mechanism is specified, PyMongo automatically negotiates the
    mechanism to use (SCRAM-SHA-1 or SCRAM-SHA-256) with the MongoDB server.
  - `authMechanismProperties`: Used to specify authentication mechanism
    specific options. To specify the service name for GSSAPI
    authentication pass authMechanismProperties='SERVICE_NAME:<service
    name>'.
    To specify the session token for MONGODB-AWS authentication pass
    ``authMechanismProperties='AWS_SESSION_TOKEN:<session token>'``.

  .. seealso:: :doc:`/examples/authentication`

  | **TLS/SSL configuration:**

  - `tls`: (boolean) If ``True``, create the connection to the server
    using transport layer security. Defaults to ``False``.
  - `tlsInsecure`: (boolean) Specify whether TLS constraints should be
    relaxed as much as possible. Setting ``tlsInsecure=True`` implies
    ``tlsAllowInvalidCertificates=True`` and
    ``tlsAllowInvalidHostnames=True``. Defaults to ``False``. Think
    very carefully before setting this to ``True`` as it dramatically
    reduces the security of TLS.
  - `tlsAllowInvalidCertificates`: (boolean) If ``True``, continues
    the TLS handshake regardless of the outcome of the certificate
    verification process. If this is ``False``, and a value is not
    provided for ``tlsCAFile``, PyMongo will attempt to load system
    provided CA certificates. If the python version in use does not
    support loading system CA certificates then the ``tlsCAFile``
    parameter must point to a file of CA certificates.
    ``tlsAllowInvalidCertificates=False`` implies ``tls=True``.
    Defaults to ``False``. Think very carefully before setting this
    to ``True`` as that could make your application vulnerable to
    on-path attackers.
  - `tlsAllowInvalidHostnames`: (boolean) If ``True``, disables TLS
    hostname verification. ``tlsAllowInvalidHostnames=False`` implies
    ``tls=True``. Defaults to ``False``. Think very carefully before
    setting this to ``True`` as that could make your application
    vulnerable to on-path attackers.
  - `tlsCAFile`: A file containing a single or a bundle of
    "certification authority" certificates, which are used to validate
    certificates passed from the other end of the connection.
    Implies ``tls=True``. Defaults to ``None``.
  - `tlsCertificateKeyFile`: A file containing the client certificate
    and private key. Implies ``tls=True``. Defaults to ``None``.
  - `tlsCRLFile`: A file containing a PEM or DER formatted
    certificate revocation list. Implies ``tls=True``. Defaults to
    ``None``.
  - `tlsCertificateKeyFilePassword`: The password or passphrase for
    decrypting the private key in ``tlsCertificateKeyFile``. Only
    necessary if the private key is encrypted. Defaults to ``None``.
  - `tlsDisableOCSPEndpointCheck`: (boolean) If ``True``, disables
    certificate revocation status checking via the OCSP responder
    specified on the server certificate.
    ``tlsDisableOCSPEndpointCheck=False`` implies ``tls=True``.
    Defaults to ``False``.
  - `ssl`: (boolean) Alias for ``tls``.

  | **Read Concern options:**
  | (If not set explicitly, this will use the server default)

  - `readConcernLevel`: (string) The read concern level specifies the
    level of isolation for read operations.  For example, a read
    operation using a read concern level of ``majority`` will only
    return data that has been written to a majority of nodes. If the
    level is left unspecified, the server default will be used.

  | **Client side encryption options:**
  | (If not set explicitly, client side encryption will not be enabled.)

  - `auto_encryption_opts`: A
    :class:`~pymongo.encryption_options.AutoEncryptionOpts` which
    configures this client to automatically encrypt collection commands
    and automatically decrypt results. See
    :ref:`automatic-client-side-encryption` for an example.
    If a :class:`AsyncMongoClient` is configured with
    ``auto_encryption_opts`` and a non-None ``maxPoolSize``, a
    separate internal ``AsyncMongoClient`` is created if any of the
    following are true:

      - A ``key_vault_client`` is not passed to
        :class:`~pymongo.encryption_options.AutoEncryptionOpts`
      - ``bypass_auto_encrpytion=False`` is passed to
        :class:`~pymongo.encryption_options.AutoEncryptionOpts`

  | **Stable API options:**
  | (If not set explicitly, Stable API will not be enabled.)

  - `server_api`: A
    :class:`~pymongo.server_api.ServerApi` which configures this
    client to use Stable API. See :ref:`versioned-api-ref` for
    details.

.. seealso:: The MongoDB documentation on `connections <https://dochub.mongodb.org/core/connections>`_.

.. versionchanged:: 4.5
   Added the ``serverMonitoringMode`` keyword argument.

.. versionchanged:: 4.2
   Added the ``timeoutMS`` keyword argument.

.. versionchanged:: 4.0

     - Removed the fsync, unlock, is_locked, database_names, and
       close_cursor methods.
       See the :ref:`pymongo4-migration-guide`.
     - Removed the ``waitQueueMultiple`` and ``socketKeepAlive``
       keyword arguments.
     - The default for `uuidRepresentation` was changed from
       ``pythonLegacy`` to ``unspecified``.
     - Added the ``srvServiceName``, ``maxConnecting``, and ``srvMaxHosts`` URI and
       keyword arguments.

.. versionchanged:: 3.12
   Added the ``server_api`` keyword argument.
   The following keyword arguments were deprecated:

     - ``ssl_certfile`` and ``ssl_keyfile`` were deprecated in favor
       of ``tlsCertificateKeyFile``.

.. versionchanged:: 3.11
   Added the following keyword arguments and URI options:

     - ``tlsDisableOCSPEndpointCheck``
     - ``directConnection``

.. versionchanged:: 3.9
   Added the ``retryReads`` keyword argument and URI option.
   Added the ``tlsInsecure`` keyword argument and URI option.
   The following keyword arguments and URI options were deprecated:

     - ``wTimeout`` was deprecated in favor of ``wTimeoutMS``.
     - ``j`` was deprecated in favor of ``journal``.
     - ``ssl_cert_reqs`` was deprecated in favor of
       ``tlsAllowInvalidCertificates``.
     - ``ssl_match_hostname`` was deprecated in favor of
       ``tlsAllowInvalidHostnames``.
     - ``ssl_ca_certs`` was deprecated in favor of ``tlsCAFile``.
     - ``ssl_certfile`` was deprecated in favor of
       ``tlsCertificateKeyFile``.
     - ``ssl_crlfile`` was deprecated in favor of ``tlsCRLFile``.
     - ``ssl_pem_passphrase`` was deprecated in favor of
       ``tlsCertificateKeyFilePassword``.

.. versionchanged:: 3.9
   ``retryWrites`` now defaults to ``True``.

.. versionchanged:: 3.8
   Added the ``server_selector`` keyword argument.
   Added the ``type_registry`` keyword argument.

.. versionchanged:: 3.7
   Added the ``driver`` keyword argument.

.. versionchanged:: 3.6
   Added support for mongodb+srv:// URIs.
   Added the ``retryWrites`` keyword argument and URI option.

.. versionchanged:: 3.5
   Add ``username`` and ``password`` options. Document the
   ``authSource``, ``authMechanism``, and ``authMechanismProperties``
   options.
   Deprecated the ``socketKeepAlive`` keyword argument and URI option.
   ``socketKeepAlive`` now defaults to ``True``.

.. versionchanged:: 3.0
   :class:`~pymongo.asynchronous.mongo_client.AsyncMongoClient` is now the one and only
   client class for a standalone server, mongos, or replica set.
   It includes the functionality that had been split into
   :class:`~pymongo.asynchronous.mongo_client.MongoReplicaSetClient`: it can connect
   to a replica set, discover all its members, and monitor the set for
   stepdowns, elections, and reconfigs.

   The :class:`~pymongo.asynchronous.mongo_client.AsyncMongoClient` constructor no
   longer blocks while connecting to the server or servers, and it no
   longer raises :class:`~pymongo.errors.ConnectionFailure` if they
   are unavailable, nor :class:`~pymongo.errors.ConfigurationError`
   if the user's credentials are wrong. Instead, the constructor
   returns immediately and launches the connection process on
   background threads.

   Therefore the ``alive`` method is removed since it no longer
   provides meaningful information; even if the client is disconnected,
   it may discover a server in time to fulfill the next operation.

   In PyMongo 2.x, :class:`~pymongo.asynchronous.AsyncMongoClient` accepted a list of
   standalone MongoDB servers and used the first it could connect to::

       AsyncMongoClient(['host1.com:27017', 'host2.com:27017'])

   A list of multiple standalones is no longer supported; if multiple
   servers are listed they must be members of the same replica set, or
   mongoses in the same sharded cluster.

   The behavior for a list of mongoses is changed from "high
   availability" to "load balancing". Before, the client connected to
   the lowest-latency mongos in the list, and used it until a network
   error prompted it to re-evaluate all mongoses' latencies and
   reconnect to one of them. In PyMongo 3, the client monitors its
   network latency to all the mongoses continuously, and distributes
   operations evenly among those with the lowest latency. See
   :ref:`mongos-load-balancing` for more information.

   The ``connect`` option is added.

   The ``start_request``, ``in_request``, and ``end_request`` methods
   are removed, as well as the ``auto_start_request`` option.

   The ``copy_database`` method is removed, see the
   :doc:`copy_database examples </examples/copydb>` for alternatives.

   The :meth:`AsyncMongoClient.disconnect` method is removed; it was a
   synonym for :meth:`~pymongo.asynchronous.AsyncMongoClient.close`.

   :class:`~pymongo.asynchronous.mongo_client.AsyncMongoClient` no longer returns an
   instance of :class:`~pymongo.asynchronous.database.AsyncDatabase` for attribute names
   with leading underscores. You must use dict-style lookups instead::

       client['__my_database__']

   Not::

       client.__my_database__

.. versionchanged:: 4.7
    Deprecated parameter ``wTimeoutMS``, use :meth:`~pymongo.timeout`.

.. versionchanged:: 4.9
    The default value of ``connect`` is changed to ``False`` when running in a
    Function-as-a-service environment.
)hostportrs   rt   ru   type_registryNz%port must be an instance of int, not _pool_class_monitor_class_condition_classrs   keyword_optsFsrvservicenamesrvmaxhosts/   z+host must not contain multiple MongoDB URIsT)validatewarn	normalizesrv_max_hostsnodelistusernamepasswordr    optionsfqdn!need to specify at least one hostr   rz   rt   _is_faasru   srvServiceName)
is_srvr   r   dbaseseedsr   srv_service_name
pool_classmonitor_classcondition_class)6dict_init_kwargsHOST
isinstancestrPORTint	TypeErrortype_host_port	_topology_timeout_topology_settings_event_listenerspopr   _CaseInsensitiveDictionary_resolve_srv_infosetgetlenr.   r]   
startswithrX   updater^   _detect_external_dbpymongo.pool_optionsr    _validate_kwargs_and_update_optsSRV_SERVICE_NAME_normalize_and_validate_optionsr*   _IS_SYNC_options_default_database_namer8   _lock_kill_cursors_queue
_encryptersuper__init__codec_optionsread_preferencewrite_concernread_concern_init_based_on_options_opened_closed_loop_init_background_get_topology)selfrx   ry   rs   rt   ru   rz   kwargs	doc_classr   r   r   r~   r   r   r   r   r   optsr   r   r   hentityresnodehostnamer   	__class__s                               fC:\Suresh\moveshuttle\MDcreated\moveengine\venv\Lib\site-packages\pymongo/asynchronous/mongo_client.pyr   AsyncMongoClient.__init__   sO   l #*d	' *-
 -
 <99DdC  6D<99D$$$CDJ<PQQ

#'&*488< ZZt4


#3T: **%7> 88@)2%&2@,1O002'++,<=$((74::2:a:23a7$%RSSjjF f}#!#"/  **:6S_-z?6hz?6hJ059~6{[<=+ !, $%HII-23UTaU3H"8,, 4
 $,9)xx
E2H?5hhyhj.9G#+Z ")Y44\4H##xx(8&:Q:QR%@-)@33D%@ 88J188J1%h%xP&+#')
)+ 04%% $$$4(!.#2	
 	MM''MM))MM''MM&&		
 ''}>NO:>
!!#8   8} 36 4s   "
Q50Q5Q:c                  #    U R                   S   n[        5       n[        R                  " 5       nUR	                  S5      nUR	                  S5      nU R
                   GH  nSU;   a  UR	                  S5      nUb&  [        R                  " UR                  S5      U5      n[        R                  " UU R                  SSSUUUS9I S h  vN nUR                  US	   5        US
   nO$UR                  [        X`R                  5      5        U(       d  [        S5      eU V	s/ s H  oS   PM	     sn	 H  n
[        U
5      (       d  M    O   US   nUS   nUc  UR	                  SS5      nUc"  SSKJn  UR	                  SU" 5       (       + 5      nXS'   XS'   U R#                  X5      nUc   UR	                  S[        R$                  5      nU=(       d    UR	                  S5      nU R'                  X25      nUR	                  SU R                   S   5      nUR	                  SU R                   S   5      n[)        XU R                   S   U[*        5      U l        U R/                  X%U5        GM     g  GNs  sn	f 7f)Nr~   r   r   r   connecttimeoutmsTF)r   r   r   connect_timeoutr   r   r   r   r   r   rt   ru   r   r   r   r   r   )r   r   r   r   r   r    validate_timeout_or_none_or_zero	cased_keyr!   
_parse_srvr   r   r^   r.   r   r   r   r   r   r   r*   r   r   r   )r   r~   r   r   r   r   r   timeoutr   r   r   rt   ru   r   r   r   s                   r   _resolve_srvAsyncMongoClient._resolve_srvx  sU    --n=002'++,<=$((7jjF f}&**+=>&$EE$../ABGG '11JJ!#$+%5"/	 	 S_-9~[<=()LMM167!W7&x00 8
 $J/H"9-G88J69((9(*n='/$&-#88LD'#'88,<f>U>U#V )DTXXm-DM77DD xx
D,B,B:,NOHxx
D,B,B:,NOH)D$:$:7$CT8DM ''>NO{ !	$ 8s,   C	I;I3AI;$I62I;
D*I;6I;c                T   U R                   R                  R                  U l        [        S0 SU_SU R                   R                  _SU R
                  S   _SU R                   R                  _SU R
                  S   _SU R
                  S   _SU R                   R                  _SU R                   R                  _S	U R                   R                  _S
U R                   R                  _SU R
                  S   _SU R                   R                  _SU R                   R                  _SU_SU_SU R                   R                  _6U l        U R                   R                  (       a'  SSKJn  U" X R                   R                  5      U l        U R                   R$                  U l        g )Nr   replica_set_namer   pool_optionsr   r   local_threshold_msserver_selection_timeoutserver_selectorheartbeat_frequencyr   direct_connectionload_balancedr   r   server_monitoring_moder   rg    )r   r   r   r'   r   r   r   r   r   r   r   r   r   r   auto_encryption_optspymongo.asynchronous.encryptionrh   r   r   r   )r   r   r   r   rh   s        r   r   'AsyncMongoClient._init_based_on_options  s    !% : : K K"2 #
#
!]];;#
 --l;#
 33	#

 00A#
 !223DE#
  $}}??#
 &*]]%K%K#
 !MM99#
 !% A A#
 ''/#
 #mm==#
 --55#
 .#
 (#
  $(==#G#G!#
$ ==--B(}}/Q/QRDO--    c                H    [        U5      n[        U5      n[        X!5        U$ N)r[   r\   rY   )r   r   r   s      r   r   0AsyncMongoClient._normalize_and_validate_options  s%     (-!$'u#r   c                   ^ [        T5      m[        R                  " [        U4S jTR	                  5        5       5      5      mUR                  T5        U$ )Nc              3  t   >#    U  H-  u  p[         R                  " TR                  U5      U5      v   M/     g 7fr   )r   r   r   ).0kvr~   s      r   	<genexpr>DAsyncMongoClient._validate_kwargs_and_update_opts.<locals>.<genexpr>  s.     `K_41!7!7!:A>>K_s   58)rZ   r   r   r   itemsr   )r   r~   r   s    ` r   r   1AsyncMongoClient._validate_kwargs_and_update_opts  sI     3<@88`<K]K]K_``
 	L!r   c                @   #    U R                  5       I Sh  vN   g N7f)zOExplicitly connect to MongoDB asynchronously instead of on the first operation.N)r   r   s    r   aconnectAsyncMongoClient.aconnect  s       """   c                  ^ [        U R                  5      U l        [        (       a'  U [        R
                  U R                  R                  '   XR                  l        SU4S jjn[        R                  " [        R                  [        R                  USS9n[        R                  " XR                  5      mX0l        SU l        g )Nc                 b   >#    T" 5       n U c  g[         R                  U 5      I S h  vN   g N7f)NFT)rp   _process_periodic_tasks)clientself_refs    r   target1AsyncMongoClient._init_background.<locals>.target   s2     ZF~"::6BBB Cs   $/-/pymongo_kill_cursors_thread)intervalmin_intervalr   nameFreturnbool)r(   r   r   r7   rp   rv   _topology_id_pidr   AsyncPeriodicExecutorr   KILL_CURSOR_FREQUENCYMIN_HEARTBEAT_INTERVALweakrefrefclose_kill_cursors_executorr   )r   old_pidr   executorr   s       @r   r   !AsyncMongoClient._init_background  s    !$"9"9:   FJ%%dnn&A&AB &	 %::1166.	
  D..9&.#r   c                p    U R                   R                  =(       a    U=(       a    UR                  (       + $ r   )r   r   in_transactionr   sessions     r   _should_pin_cursor#AsyncMongoClient._should_pin_cursor  s%    }}**WG4V@V@V/WWr   c                    U R                  U R                  R                  5        U R                  R                  R	                  5         g)z6Resets topology in a child after successfully forking.N)r   r   r	  _session_poolresetr   s    r   _after_forkAsyncMongoClient._after_fork  s0    dnn112$$**,r   c                n    U R                   R                  5       nUR                  U5        [        S0 UD6$ Nr   )r   copyr   rp   )r   r   argss      r   
_duplicateAsyncMongoClient._duplicate  s0      %%'F'$''r   c                   #    [        U R                  UUUUUUUUU	U
UUS9nUR                  5       I Sh  vN   U$  N7f)a  Watch changes on this cluster.

Performs an aggregation with an implicit initial ``$changeStream``
stage and returns a
:class:`~pymongo.asynchronous.change_stream.AsyncClusterChangeStream` cursor which
iterates over changes on all databases on this cluster.

Introduced in MongoDB 4.0.

.. code-block:: python

   with client.watch() as stream:
       for change in stream:
           print(change)

The :class:`~pymongo.asynchronous.change_stream.AsyncClusterChangeStream` iterable
blocks until the next change document is returned or an error is
raised. If the
:meth:`~pymongo.asynchronous.change_stream.AsyncClusterChangeStream.next` method
encounters a network error when retrieving a batch from the server,
it will automatically attempt to recreate the cursor such that no
change events are missed. Any error encountered during the resume
attempt indicates there may be an outage and will be raised.

.. code-block:: python

    try:
        with client.watch([{"$match": {"operationType": "insert"}}]) as stream:
            for insert_change in stream:
                print(insert_change)
    except pymongo.errors.PyMongoError:
        # The AsyncChangeStream encountered an unrecoverable error or the
        # resume attempt failed to recreate the cursor.
        logging.error("...")

For a precise description of the resume process see the
`change streams specification`_.

:param pipeline: A list of aggregation pipeline stages to
    append to an initial ``$changeStream`` stage. Not all
    pipeline stages are valid after a ``$changeStream`` stage, see the
    MongoDB documentation on change streams for the supported stages.
:param full_document: The fullDocument to pass as an option
    to the ``$changeStream`` stage. Allowed values: 'updateLookup',
    'whenAvailable', 'required'. When set to 'updateLookup', the
    change notification for partial updates will include both a delta
    describing the changes to the document, as well as a copy of the
    entire document that was changed from some time after the change
    occurred.
:param full_document_before_change: Allowed values: 'whenAvailable'
    and 'required'. Change events may now result in a
    'fullDocumentBeforeChange' response field.
:param resume_after: A resume token. If provided, the
    change stream will start returning changes that occur directly
    after the operation specified in the resume token. A resume token
    is the _id value of a change document.
:param max_await_time_ms: The maximum time in milliseconds
    for the server to wait for changes before responding to a getMore
    operation.
:param batch_size: The maximum number of documents to return
    per batch.
:param collation: The :class:`~pymongo.collation.Collation`
    to use for the aggregation.
:param start_at_operation_time: If provided, the resulting
    change stream will only return changes that occurred at or after
    the specified :class:`~bson.timestamp.Timestamp`. Requires
    MongoDB >= 4.0.
:param session: a
    :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
:param start_after: The same as `resume_after` except that
    `start_after` can resume notifications after an invalidate event.
    This option and `resume_after` are mutually exclusive.
:param comment: A user-provided comment to attach to this
    command.
:param show_expanded_events: Include expanded events such as DDL events like `dropIndexes`.

:return: A :class:`~pymongo.asynchronous.change_stream.AsyncClusterChangeStream` cursor.

.. versionchanged:: 4.3
   Added `show_expanded_events` parameter.

.. versionchanged:: 4.2
    Added ``full_document_before_change`` parameter.

.. versionchanged:: 4.1
   Added ``comment`` parameter.

.. versionchanged:: 3.9
   Added the ``start_after`` parameter.

.. versionadded:: 3.7

.. seealso:: The MongoDB documentation on `changeStreams <https://mongodb.com/docs/manual/changeStreams/>`_.

.. _change streams specification:
    https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.md
)show_expanded_eventsN)r#   admin_initialize_cursor)r   pipelinefull_documentresume_aftermax_await_time_ms
batch_size	collationstart_at_operation_timer  start_aftercommentfull_document_before_changer&  change_streams                 r   watchAsyncMongoClient.watch"  s\     ` 1JJ#'!5
  ..000 	1s   3><>c                .    U R                   R                  $ )al  The description of the connected MongoDB deployment.

>>> client.topology_description
<TopologyDescription id: 605a7b04e76489833a7c6113, topology_type: ReplicaSetWithPrimary, servers: [<ServerDescription ('localhost', 27017) server_type: RSPrimary, rtt: 0.0007973677999995488>, <ServerDescription ('localhost', 27018) server_type: RSSecondary, rtt: 0.0005540556000003249>, <ServerDescription ('localhost', 27019) server_type: RSSecondary, rtt: 0.0010367483999999649>]>
>>> client.topology_description.topology_type_name
'ReplicaSetWithPrimary'

Note that the description is periodically updated in the background
but the returned object itself is immutable. Access this property again
to get a more recent
:class:`~pymongo.topology_description.TopologyDescription`.

:return: An instance of
  :class:`~pymongo.topology_description.TopologyDescription`.

.. versionadded:: 4.0
)r   descriptionr   s    r   topology_description%AsyncMongoClient.topology_description  s    & ~~)))r   c                f    U R                   R                  n[        S UR                   5       5      $ )a  Set of all currently connected servers.

.. warning:: When connected to a replica set the value of :attr:`nodes`
  can change over time as :class:`AsyncMongoClient`'s view of the replica
  set changes. :attr:`nodes` can also be an empty set when
  :class:`AsyncMongoClient` is first instantiated and hasn't yet connected
  to any servers, or a network partition causes it to lose connection
  to all servers.
c              3  8   #    U  H  oR                   v   M     g 7fr   address)r   ss     r   r   )AsyncMongoClient.nodes.<locals>.<genexpr>  s     F,Eq,Es   )r   r7  	frozensetknown_servers)r   r7  s     r   nodesAsyncMongoClient.nodes  s*     nn00FK,E,EFFFr   c                    U R                   $ )zThe configuration options for this client.

:return: An instance of :class:`~pymongo.client_options.ClientOptions`.

.. versionadded:: 4.0
r   r   s    r   r   AsyncMongoClient.options  s     }}r   c                    [        [        U R                  S   5      5      U R                  R                  U R                  S   U R                  S   4$ )Nr   r   r   )tuplesortedr   r   r   r   s    r   eq_propsAsyncMongoClient.eq_props  sN    &//89:MM**""6*""#56	
 	
r   c                    [        XR                  5      (       a!  U R                  5       UR                  5       :H  $ [        $ r   )r   r   rJ  NotImplementedr   others     r   __eq__AsyncMongoClient.__eq__  s/    e^^,,==?enn&666r   c                    X:X  + $ r   r   rN  s     r   __ne__AsyncMongoClient.__ne__  s      r   c                4    [        U R                  5       5      $ r   )hashrJ  r   s    r   __hash__AsyncMongoClient.__hash__  s    DMMO$$r   c                  ^ ^ S
S jmT R                   c  ST R                  S    S3/nO8ST R                  R                   VVs/ s H  u  p#Ub  SX#4-  OUPM     snn-  /nUR	                  UU 4S jT R
                   5       5        UR	                  UU 4S jT R                  R                   5       5        S	R                  U5      $ s  snnf )Nc                    U S:X  a&  U[         L a  gSUR                   SUR                   3$ U [        R                  ;   a  Ub  U  S[        US-  5       3$ U  SU< 3$ )z9Fix options whose __repr__ isn't usable in a constructor.rs   zdocument_class=dictzdocument_class=.=i  )r   
__module____name__r   TIMEOUT_OPTIONSr   )optionvalues     r   option_repr2AsyncMongoClient._repr_helper.<locals>.option_repr  ss    ))D=0,U-=-=,>a?OPP///E4E 3ut|#4"566XQui((r   zhost='mongodb+srv://r   'zhost=%rz%s:%dc              3  d   >#    U  H%  nT" UTR                   R                   U   5      v   M'     g 7fr   rE  r   keyrb  r   s     r   r   0AsyncMongoClient._repr_helper.<locals>.<genexpr>  s.      
E[cKT]]33C899E[s   -0c              3     >#    U  HP  nU[        TR                  5      ;  d  M  US :w  d  M&  US:w  d  M.  T" UTR                  R                  U   5      v   MR     g7f)r   r   N)r   _constructor_argsr   rf  s     r   r   rh    sa      
-#d4455 ::=:K :PSWaPa :KT]]33C899-s   AAA'Az, )r`  r   ra  r   r  r   )r   r   r   r   extendrj  r   join)r   r   rx   ry   rb  s   `   @r   _repr_helperAsyncMongoClient._repr_helper  s    
	) >>!-d.D.DV.L-MQOPG  '+&=&=&C&C&C
 /3.>Gtl*DH&CG 	 
EIE[E[
 	
 	 
}}--
 	

 yy!!s   C	c                T    [        U 5      R                   SU R                  5        S3$ )N())r   r^  rm  r   s    r   __repr__AsyncMongoClient.__repr__	  s*    t*%%&a(9(9(;'<A>>r   c           
         UR                  S5      (       a,  [        [        U 5      R                   SU< SU SU< S35      eU R	                  U5      $ )Get a database by name.

Raises :class:`~pymongo.errors.InvalidName` if an invalid
database name is used.

:param name: the name of the database to get
_z has no attribute z. To access the z database, use client[z].)r   AttributeErrorr   r^  __getitem__r   r  s     r   __getattr__AsyncMongoClient.__getattr__  sa     ??3 :&&''9$AQRVQW(4  %%r   c                .    [         R                  " X5      $ )ru  )r    AsyncDatabasery  s     r   rx  AsyncMongoClient.__getitem__  s     %%d11r   c           
     6    U R                   (       aq  U R                  (       d_  [        R                  " S[	        U 5      R
                   SU R                  R                   S[	        U 5      R
                   S3[        SS9  ggg! [        [        4 a     gf = f)zLCheck that this AsyncMongoClient has been closed and issue a warning if not.z	Unclosed z opened at:
zCall z?.close() to safely shut down your client and free up resources.   )
stacklevelN)r   r   warningsr   r   r^  r   _stackResourceWarningrw  r   r   s    r   __del__AsyncMongoClient.__del__%  s    	||DLL#DJ$7$7#8dF]F]FdFdEeT
 3 344su $  %1| 	* 		s   B B BBc                >    U R                   R                  X!U45        g)z;Request that a cursor and/or connection be cleaned up soon.N)r   append)r   	cursor_idr=  conn_mgrs       r   _close_cursor_soon#AsyncMongoClient._close_cursor_soon5  s     	  ''X(FGr   c                p    [        5       n[        R                  " S0 UD6n[        R                  " XXA5      $ r   )r%   r   SessionOptionsrd   )r   implicitr   server_sessionr   s        r   _start_sessionAsyncMongoClient._start_session>  s0    ,.,,6v600tVVr   c                &    U R                  SUUUS9$ )a  Start a logical session.

This method takes the same parameters as
:class:`~pymongo.asynchronous.client_session.SessionOptions`. See the
:mod:`~pymongo.asynchronous.client_session` module for details and examples.

A :class:`~pymongo.asynchronous.client_session.AsyncClientSession` may only be used with
the AsyncMongoClient that started it. :class:`AsyncClientSession` instances are
**not thread-safe or fork-safe**. They can only be used by one thread
or process at a time. A single :class:`AsyncClientSession` cannot be used
to run multiple operations concurrently.

:return: An instance of :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.

.. versionadded:: 3.6
F)causal_consistencydefault_transaction_optionssnapshot)r  )r   r  r  r  s       r   start_sessionAsyncMongoClient.start_sessionC  s(    , ""1(C	 # 
 	
r   c                b    U(       a  U$  U R                  SSS9$ ! [        [        4 a     gf = f)6If provided session is None, lend a temporary session.TF)r  N)r  r.   r0   r  s     r   _ensure_session AsyncMongoClient._ensure_session`  sA     N	 &&t&FF"$45 		s    ..c                    U R                   R                  5       nU(       a  UR                  OS nU(       a  U(       a  US   US   :  a  UnOUnOU=(       d    UnU(       a  XQS'   g g )NclusterTime$clusterTime)r   max_cluster_timecluster_time)r   commandr  topology_timesession_timer  s         r   _send_cluster_time#AsyncMongoClient._send_cluster_timeo  s`     779/6w++D\]+l=.II6C+(8LL&2N# r   c                    U R                   c  Uc  [        S5      e[        [        U R                   =(       d    U5      n[        R
                  " XX#XE5      $ )aM  Get the database named in the MongoDB connection URI.

>>> uri = 'mongodb://host/my_database'
>>> client = AsyncMongoClient(uri)
>>> db = client.get_default_database()
>>> assert db.name == 'my_database'
>>> db = client.get_database()
>>> assert db.name == 'my_database'

Useful in scripts where you want to choose which database to use
based only on the URI in a configuration file.

:param default: the database name to use if no database name
    was provided in the URI.
:param codec_options: An instance of
    :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
    default) the :attr:`codec_options` of this :class:`AsyncMongoClient` is
    used.
:param read_preference: The read preference to use. If
    ``None`` (the default) the :attr:`read_preference` of this
    :class:`AsyncMongoClient` is used. See :mod:`~pymongo.read_preferences`
    for options.
:param write_concern: An instance of
    :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
    default) the :attr:`write_concern` of this :class:`AsyncMongoClient` is
    used.
:param read_concern: An instance of
    :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
    default) the :attr:`read_concern` of this :class:`AsyncMongoClient` is
    used.
:param comment: A user-provided comment to attach to this
    command.

.. versionchanged:: 4.1
   Added ``comment`` parameter.

.. versionchanged:: 3.8
   Undeprecated. Added the ``default``, ``codec_options``,
   ``read_preference``, ``write_concern`` and ``read_concern``
   parameters.

.. versionchanged:: 3.5
   Deprecated, use :meth:`get_database` instead.
z-No default database name defined or provided.)r   r.   r   r   r    r}  )r   defaultr   r   r   r   r  s          r   get_default_database%AsyncMongoClient.get_default_database~  sR    h &&.7?$%TUUC44?@%%
 	
r   c                    Uc$  U R                   c  [        S5      eU R                   n[        R                  " XX#XE5      $ )aT  Get a :class:`~pymongo.asynchronous.database.AsyncDatabase` with the given name and
options.

Useful for creating a :class:`~pymongo.asynchronous.database.AsyncDatabase` with
different codec options, read preference, and/or write concern from
this :class:`AsyncMongoClient`.

  >>> client.read_preference
  Primary()
  >>> db1 = client.test
  >>> db1.read_preference
  Primary()
  >>> from pymongo import ReadPreference
  >>> db2 = client.get_database(
  ...     'test', read_preference=ReadPreference.SECONDARY)
  >>> db2.read_preference
  Secondary(tag_sets=None)

:param name: The name of the database - a string. If ``None``
    (the default) the database named in the MongoDB connection URI is
    returned.
:param codec_options: An instance of
    :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
    default) the :attr:`codec_options` of this :class:`AsyncMongoClient` is
    used.
:param read_preference: The read preference to use. If
    ``None`` (the default) the :attr:`read_preference` of this
    :class:`AsyncMongoClient` is used. See :mod:`~pymongo.read_preferences`
    for options.
:param write_concern: An instance of
    :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
    default) the :attr:`write_concern` of this :class:`AsyncMongoClient` is
    used.
:param read_concern: An instance of
    :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
    default) the :attr:`read_concern` of this :class:`AsyncMongoClient` is
    used.

.. versionchanged:: 3.5
   The `name` parameter is now optional, defaulting to the database
   named in the MongoDB connection URI.
zNo default database defined)r   r.   r    r}  )r   r  r   r   r   r   s         r   get_databaseAsyncMongoClient.get_database  sG    d <**2()FGG..D%%
 	
r   c                R    U R                  U[        [        R                  [        S9$ )z7Get a AsyncDatabase instance with the default settings.)r   r   r   )r  r   rK   PRIMARYr_   ry  s     r   _database_default_options*AsyncMongoClient._database_default_options  s,      /*22/	 ! 
 	
r   c                   #    U $ 7fr   r   r   s    r   
__aenter__AsyncMongoClient.__aenter__  
        c                @   #    U R                  5       I S h  vN   g  N7fr   )r  r   exc_typeexc_valexc_tbs       r   	__aexit__AsyncMongoClient.__aexit__  s     jjlr   c                    [        S5      e)Nz)'AsyncMongoClient' object is not iterable)r   r   s    r   __next__AsyncMongoClient.__next__  s    CDDr   c                   #    U R                  5       I Sh  vN R                  [        [        R                  5      I Sh  vN n[        UR                  U5      $  ND N7f)a{  An attribute of the current server's description.

If the client is not connected, this will block until a connection is
established or raise ServerSelectionTimeoutError if no server is
available.

Not threadsafe if used multiple times in a single method, since
the server may change. In such cases, store a local reference to a
ServerDescription first, then use its properties.
N)r   select_serverrN   rJ   TESTgetattrr7  )r   	attr_nameservers      r   _server_property!AsyncMongoClient._server_property  sP      #0022AA$chh
 
 v))955	 3 
s!   AA)A AAAc                  #    U R                   R                  R                  nU[        R                  :X  a2  [        U R                  R                  5       5      S:  a  [        S5      eU R                  S5      I Sh  vN $  N7f)a  (host, port) of the current standalone, primary, or mongos, or None.

Accessing :attr:`address` raises :exc:`~.errors.InvalidOperation` if
the client is load-balancing among mongoses, since there is no single
address. Use :attr:`nodes` instead.

If the client is not connected, this will block until a connection is
established or raise ServerSelectionTimeoutError if no server is
available.

.. versionadded:: 3.0
r   zVCannot use "address" property when load balancing among mongoses, use "nodes" instead.r=  N)
r   _descriptiontopology_typerP   Shardedr   r8  server_descriptionsr0   r  )r   r  s     r   r=  AsyncMongoClient.address  sq      33AA]222D--AACDqH"2  **95555s   A;B=B>Bc                R   #    U R                   R                  5       I Sh  vN $  N7f)a!  The (host, port) of the current primary of the replica set.

Returns ``None`` if this client is not connected to a replica set,
there is no primary, or this client was created without the
`replicaSet` option.

.. versionadded:: 3.0
   AsyncMongoClient gained this property in version 3.0.
N)r   get_primaryr   s    r   primaryAsyncMongoClient.primary6  s       ^^//1111   '%'c                R   #    U R                   R                  5       I Sh  vN $  N7f)a5  The secondary members known to this client.

A sequence of (host, port) pairs. Empty if this client is not
connected to a replica set, there are no visible secondaries, or this
client was created without the `replicaSet` option.

.. versionadded:: 3.0
   AsyncMongoClient gained this property in version 3.0.
N)r   get_secondariesr   s    r   secondariesAsyncMongoClient.secondariesC  s       ^^335555r  c                R   #    U R                   R                  5       I Sh  vN $  N7f)zArbiters in the replica set.

A sequence of (host, port) pairs. Empty if this client is not
connected to a replica set, there are no arbiters, or this client was
created without the `replicaSet` option.
N)r   get_arbitersr   s    r   arbitersAsyncMongoClient.arbitersP  s       ^^002222r  c                @   #    U R                  S5      I Sh  vN $  N7f)a(  If this client is connected to a server that can accept writes.

True if the current server is a standalone, mongos, or the primary of
a replica set. If the client is not connected, this will block until a
connection is established or raise ServerSelectionTimeoutError if no
server is available.
is_writableN)r  r   s    r   
is_primaryAsyncMongoClient.is_primaryZ  s      **=9999   c                b   #    U R                  S5      I Sh  vN [        R                  :H  $  N7f)zIf this client is connected to mongos. If the client is not
connected, this will block until a connection is established or raise
ServerSelectionTimeoutError if no server is available.
server_typeN)r  rO   Mongosr   s    r   	is_mongosAsyncMongoClient.is_mongose  s)      **=99[=O=OOO9s   /-/c           	       #     U R                  [        R                  S[        R                  S9I Sh  vN  ISh  vN u  nnUR
                  (       d   SSS5      ISh  vN   g[        S[        U5      [        R                  5       H3  nSXU[        R                  -    0nUR                  SXSU S9I Sh  vN   M5     SSS5      ISh  vN   g N N Nu N N! , ISh  vN  (       d  f       g= f! [         a     gf = f7f)z7Send endSessions command(s) with the given session ids.N	operationr   endSessionsr'  )r   r   )_conn_for_readsrK   PRIMARY_PREFERREDrJ   END_SESSIONSsupports_sessionsranger   r   _MAX_END_SESSIONSr  r3   )r   session_idsconn	read_prefispecs         r   _end_sessionsAsyncMongoClient._end_sessionsm  s     	 "1100$#BRBR 2    --   q#k"2F4L4LMA);1v?W?W;W+XYD,,wX\,]]] N   ^     	 	s   D0C8 CC8 CC8 CC8 "C#C8 'D(AC:C;CC8 CC8 DC8 C8 C8 CC8 C5$C'%C51C8 4D5C8 8
DDDDc                  #    U R                   c  gU R                   R                  5       nU(       a  U R                  U5      I Sh  vN   U R                  R	                  5         U R                  5       I Sh  vN   U R                   R	                  5       I Sh  vN   U R                  (       a"  U R                  R	                  5       I Sh  vN   SU l        [        (       dO  [        R                  " U R                   R                  5       U R                  R                  5       SS9I Sh  vN   gg N N N Nl N7f)a  Cleanup client resources and disconnect from MongoDB.

End all server sessions created by this client by sending one or more
endSessions commands.

Close all sockets in the connection pools and stop the monitor threads.

.. versionchanged:: 4.0
   Once closed, the client cannot be used again and any attempt will
   raise :exc:`~pymongo.errors.InvalidOperation`.

.. versionchanged:: 3.6
   End all server sessions created by this client.
NT)return_exceptions)r   pop_all_sessionsr  r  r  _process_kill_cursorsr   r   r   asynciogathercleanup_monitorsrl  )r   r  s     r   r  AsyncMongoClient.close  s      >>!nn557$$[111 	##))+((***nn""$$$??//'')))x..//1++002"&    2 	+$ *s[   AD>D41D>8D69!D>D82D>D:AD>-D<.D>6D>8D>:D><D>c                  #    [         (       dV  U R                  c  [        R                  " 5       U l        O.U R                  [        R                  " 5       :w  a  [	        S5      eU R
                  (       d  U R                  S   (       a(  U R                  5       I Sh  vN   U R                  5         U R                  R                  5       I Sh  vN   U R                   ISh  vN   U R                  R                  5         SSS5      ISh  vN   SU l        U R                  $  N NX NE N! , ISh  vN  (       d  f       N2= f7f)zGet the internal :class:`~pymongo.asynchronous.topology.Topology` object.

If this client was created with "connect=False", calling _get_topology
launches the connection process in the background.
NzCannot use AsyncMongoClient in different event loop. AsyncMongoClient uses low-level asyncio APIs that bind it to the event loop it was created on.r   T)r   r   r  get_running_loopRuntimeErrorr   r   r   r   r   openr   r  r   s    r   r   AsyncMongoClient._get_topology  s      xzz!$557
w7799" j  ||%%h/'')))%%'..%%'''zzz++002 "zDL~~ *'!zzzsl   BED%1ED'E#D)$E'D-ED+E'E)E+E-E3D64E Ec                 #    U=(       a    UR                   n[        XU5       IS h  vN nU(       aT  U(       aM  UR                  (       a<  UR                  UR                  5        UR                  7v    S S S 5      IS h  vN   g UR	                  US9I S h  vN  IS h  vN nU(       aP  U(       aI  UR
                  R                  [        R                  [        R                  4;   a  UR                  X5        UR                  U5        U R                  (       a6  U R                  R                  (       d  UR                  S:  a  [        S5      eU7v   S S S 5      IS h  vN   S S S 5      IS h  vN   g  GNU N N N N! , IS h  vN  (       d  f       N3= f N*! , IS h  vN  (       d  f       g = f7f)N)handler   z9Auto-encryption requires a minimum MongoDB version of 4.2)r  _MongoClientErrorHandler_pinned_connectioncontribute_socketcheckoutr7  r  rO   r  LoadBalancer_pinr   _bypass_auto_encryptionmax_wire_versionr.   )r   r  r  in_txnerr_handlerr  s         r   	_checkoutAsyncMongoClient._checkout  s9     3W33+D'BBk'g&@&@--g.H.HI000 CBB $__[_AAAAT **66#**#00 LL.--d3OO OOCC--1,S  
+ BA CBB BAAA CBBBs   &F>E=F>AF$7F>F F>F$FF$#F$F$'B5FF$'F(F$,F>7F"8F> F>F$F$F$F	FF	F$"F>$F;*F-+F;7F>c                D  #     U R                  5       I Sh  vN nU(       a3  UR                  (       d"  UR                  R                  5       I Sh  vN   U(       d  U(       a  UR                  nU(       a0  UR                  XCUS9I Sh  vN nU(       d  [        SU-  5      e U$ UR                  UUUUS9I Sh  vN nU$  N Ns N< N! [         aH  n	U(       a;  UR                  (       a*  U	R                  S5        UR                  5       I Sh  vN    e Sn	A	ff = f7f)a  Select a server to run an operation on this client.

:Parameters:
  - `server_selector`: The server selector to use if the session is
    not pinned and no address is given.
  - `session`: The AsyncClientSession for the next operation, or None. May
    be pinned to a mongos server address.
  - `address` (optional): Address when sending a message
    to a specific server, used for getMore.
N)operation_idz server %s:%s no longer available)deprioritized_serversr  TransientTransactionError)r   r  _transactionr  _pinned_addressselect_server_by_addressr+   r  r3   _add_error_label_unpin)
r   r   r  r  r=  r  r  topologyr  excs
             r   _select_serverAsyncMongoClient._select_server  s    &	!//11Hw55**00222w!11'@@\  A    '(JW(TUU  M  (55#*?!-	  6    M' 22
  	711$$%@Ann&&&	s   D C C9C C8C 
CC &D 'C <C	=C D C C C 	C 
D<DDDDD c                l   #    U R                  [        X5      I S h  vN nU R                  X15      $  N7fr   )r  rN   r  )r   r  r  r  s       r   _conn_for_writes!AsyncMongoClient._conn_for_writes  s2      **+CWXX~~f.. Ys   424c                 #    Uc   S5       eU R                   R                  R                  [        R                  :H  nU R                  X#5       IS h  vN nU(       a[  UR                  (       a)  U(       a  UR                  (       d  [        R                  nO!UR                  (       a  [        R                  nXQ47v   S S S 5      IS h  vN   g  N} N! , IS h  vN  (       d  f       g = f7fNz read_preference must not be None)r   r7  r  rP   Singler  is_replr  rK   r  is_standaloner  )r   r   r  r  singler  s         r   _conn_from_server"AsyncMongoClient._conn_from_server  s      *N,NN* ++99]=Q=QQ>>&22d<<W5K5K '5&F&FO''&4&<&<O'' 322222sI   AC/CC/A)C C/CC/C/C,CC,(C/c                z   #    Uc   S5       eU R                  XU5      I S h  vN nU R                  XU5      $  N7fr$  )r  r)  )r   r   r  r  r  s        r   r   AsyncMongoClient._conn_for_reads2  sG      *N,NN***?YOO%%owGG Ps    ;9;c           
       ^ ^^#    TR                   (       Ga  T R                  TR                  TR                  TR                  US9I Sh  vN nTR                   R
                   ISh  vN   [        T UTR                  5       ISh  vN nUR                  TR                   R                  5        UR                  TR                   R                  TTR                  T R                  TT 5      I Sh  vN sSSS5      ISh  vN   sSSS5      ISh  vN   $           SUU U4S jjnT R                  UTR                  TR                  U[        T[        5      TR                  S9I Sh  vN $  GN- GN N N N| Nm! , ISh  vN  (       d  f       O= fSSS5      ISh  vN    M  ! , ISh  vN  (       d  f       N= f NY7f)a  Run a _Query/_GetMore operation and return a Response.

:param operation: a _Query or _GetMore object.
:param unpack_res: A callable that decodes the wire protocol response.
:param address: Optional address when sending a message
    to a specific server, used for getMore.
r<  Nc                   >#    TR                  5         UR                  UTUTR                  TT5      I S h  vN $  N7fr   )r  run_operationr   )_sessionr  r  r   r  r   
unpack_ress       r   _cmd-AsyncMongoClient._run_operation.<locals>._cmd^  sG      OO--%%   s   4><>)r=  	retryabler  )
r0  Optional[AsyncClientSession]r  rj   r  ri   r   rL   r  rl   )r  r  r   r  r  r   r  r	  r  r/  r   _retryable_readr   rA   )r   r  r1  r=  r  r  r2  s   ```    r   _run_operationAsyncMongoClient._run_operation<  s     ..))!!	 /  F !))///3D&)BSBSTTXc11)2D2D2I2IJ!'!5!5!**//!!11--""  UTT 0//	2		 "	 )		
 	 	  ))%% F3nn * 
 
 	
G 0T U 0TTT 0/////8
s   AGE8G*E;+G.F3
E>F3A'F5F 6F9F3FF3
GFAG3G4G;G>F3 FF3GF	FF	F3 G+F.,G3G
9F<:G
Gc           	        #    [        U=(       a7    U R                  R                  =(       a    U=(       a    UR                  (       + 5      nU R	                  UUUUUUS9I Sh  vN $  N7f)zExecute an operation with at most one consecutive retries

Returns func()'s return value on success. On error retries the same
command.

Re-raises any exception thrown by func().
)funcr  bulkr  r4  r  N)r  r   retry_writesr  _retry_internal)r   r4  r:  r  r;  r  r  s          r   _retry_with_session$AsyncMongoClient._retry_with_sessionw  sl     $ ^$,,33^^H^H^D^
	 ))% * 
 
 	
 
s   A!A*#A($A*c
                ^   #    [        U UUUUUUUUU	S9
R                  5       I Sh  vN $  N7f)ag  Internal retryable helper for all client transactions.

:param func: Callback function we want to retry
:param session: Client Session on which the transaction should occur
:param bulk: Abstraction to handle bulk write operations
:param operation: The name of the operation that the server is being selected for
:param is_read: If this is an exclusive read transaction, defaults to False
:param address: Server Address, defaults to None
:param read_pref: Topology of read operation, defaults to None
:param retryable: If the operation should be retried once, defaults to None

:return: Output of the calling func()
)
mongo_clientr:  r;  r  is_readr  r  r=  r4  r  N)_ClientConnectionRetryablerun)
r   r:  r  r;  r  rB  r=  r  r4  r  s
             r   r=   AsyncMongoClient._retry_internal  sE     4 0%
 #% 	 s   $-+-c                   #    [        U=(       a7    U R                  R                  =(       a    U=(       a    UR                  (       + 5      nU R	                  UUSUSUUUUS9	I Sh  vN $  N7f)af  Execute an operation with consecutive retries if possible

Returns func()'s return value on success. On error retries the same
command.

Re-raises any exception thrown by func().

:param func: Read call we want to execute
:param read_pref: Desired topology of read operation
:param session: Client session we should use to execute operation
:param operation: The name of the operation that the server is being selected for
:param address: Optional address when sending a message, defaults to None
:param retryable: if we should attempt retries
    (may not always be supported even if supplied), defaults to False
NT)rB  r=  r  r4  r  )r  r   retry_readsr  r=  )r   r:  r  r  r  r=  r4  r  s           r   r6   AsyncMongoClient._retryable_read  su     8 _$,,22_G<^H^H^7_
	 ))% * 

 

 
	
 

s   A$A-&A+'A-c           	        #    U R                  U5       ISh  vN nU R                  XXuXF5      I Sh  vN sSSS5      ISh  vN   $  N0 N N	! , ISh  vN  (       d  f       g= f7f)a#  Execute an operation with consecutive retries if possible

Returns func()'s return value on success. On error retries the same
command.

Re-raises any exception thrown by func().

:param retryable: if we should attempt retries (may not always be supported)
:param func: write call we want to execute during a session
:param session: Client session we will use to execute write operation
:param operation: The name of the operation that the server is being selected for
:param bulk: bulk abstraction to execute operations in bulk, defaults to None
N)_tmp_sessionr>  )r   r4  r:  r  r  r;  r  r>  s           r   _retryable_write!AsyncMongoClient._retryable_write  sK     , $$W--11)1Idd .--d .---sS   A)A	A)AAAA)AA)AA)A&AA&"A)c                    U(       d  U(       a  U R                  XU5        U(       a  U(       d  UR                  5         ggg)a^  Cleanup a cursor from __del__ without locking.

This method handles cleanup for Cursors/CommandCursors including any
pinned connection attached at the time the cursor
was garbage collected.

:param cursor_id: The cursor id which may be 0.
:param address: The _CursorAddress.
:param conn_mgr: The _ConnectionManager for the pinned connection or None.
N)r  _end_implicit_sessionr   r  r=  r  r  explicit_sessions         r   _cleanup_cursor_no_lock(AsyncMongoClient._cleanup_cursor_no_lock   s2    & ##IA+))+ ,7r   c                  #    U(       aq  U(       aR  UR                   (       aA  UR                  c   eUR                  R                  [        R                  5      I Sh  vN   OU R                  XXCS9I Sh  vN   U(       a  UR                  5       I Sh  vN   U(       a  U(       d  UR                  5         ggg N] NF N)7f)a  Cleanup a cursor from cursor.close() using a lock.

This method handles cleanup for Cursors/CommandCursors including any
pinned connection or implicit session attached at the time the cursor
was closed or garbage collected.

:param cursor_id: The cursor id which may be 0.
:param address: The _CursorAddress.
:param conn_mgr: The _ConnectionManager for the pinned connection or None.
:param session: The cursor's session.
:param explicit_session: True if the session was passed explicitly.
N)r  r  )more_to_comer  
close_connrB   ERROR_close_cursor_nowr  rN  rO  s         r   _cleanup_cursor_lock%AsyncMongoClient._cleanup_cursor_lock  s     ( H11  }}000mm../E/K/KLLL,,Y,ddd.."""+))+ ,7 Md"s6   ACB;C6B=7CB?&C=C?Cc                "  #    [        U[        5      (       d  [        S[        U5       35      e U(       a`  UR                   ISh  vN   Uc   eUR
                  c   eU R                  U/X#UR
                  5      I Sh  vN   SSS5      ISh  vN   gU R                  U/X R                  5       I Sh  vN U5      I Sh  vN   g N NJ N<! , ISh  vN  (       d  f       g= f N2 N'! [         a    U R                  X5         gf = f7f)zjSend a kill cursors message with the given id.

The cursor is closed synchronously on the current thread.
z*cursor_id must be an instance of int, not N)r   r   r   r   r   r  _kill_cursor_impl_kill_cursorsr   r3   r  )r   r  r=  r  r  s        r   rW  "AsyncMongoClient._close_cursor_now:  s      )S))HiHYZ[[	8#>>>"...#==44400)gPXP]P]^^^	 *>> (()gEWEWEY?Y[bccc * _	 *>>> @Zc 	8##I7	8s   -DC. C
C. 6CCCC. CC. D C. 7C*8C. C,C. 	D
C. CC. C'CC'#C. &D'C. ,C. .D	DDDc                  #    U(       a2  UR                  [        U5      [        R                  5      I Sh  vN nO,UR	                  [
        [        R                  5      I Sh  vN nU R                  XT5       ISh  vN nUc   eU R                  XXF5      I Sh  vN   SSS5      ISh  vN   g N{ NP N8 N N! , ISh  vN  (       d  f       g= f7f)z/Send a kill cursors message with the given ids.N)r  rH  rJ   KILL_CURSORSr  rN   r  r[  )r   
cursor_idsr=  r  r  r  r  s          r   r\  AsyncMongoClient._kill_cursorsU  s       $<<U7^SM]M]^^F $112JCL\L\]]F>>&22d&&&((gLLL 322 _ ^2L 3222s{   4CB2,C#B4$C=B6>CB<B8B<!C,B:-C4C6C8B<:C<CCCCc                   #    UR                   nUR                  SS5      u  pgXqS.nUR                  XhX0S9I S h  vN   g  N7f)Nr[  r   )killCursorscursors)r  r   )	namespacesplitr  )	r   r`  r=  r  r  re  dbcollr  s	            r   r[  "AsyncMongoClient._kill_cursor_impli  sB      %%	??3*#;ll2WlBBBs   8AA Ac                6  #    [        [        5      n/ n  U R                  R                  5       u  p4nU(       a  UR                  X4U45        OX   R                  U5        MN  ! [         a     Of = fU Hw  u  p4n U R                  XCUSS5      I Sh  vN    M&  ! [         aF  n[        U[        5      (       a  U R                  R                  (       a  e [        5          SnAMq  SnAff = f   U(       a  U R                  5       I Sh  vN  nUR                  5        Hs  u  p8 U R                  XUSS9I Sh  vN    M"  ! [         aF  n[        U[        5      (       a  U R                  R                  (       a  e [        5          SnAMm  SnAff = f   gg7f)z*Process any pending kill cursors requests.NF)r  )r   listr   r   
IndexErrorr  rX  	Exceptionr   r0   r   r   r=   r   r   r\  )	r   address_to_cursor_idspinned_cursorsr=  r  r  r  r  r`  s	            r   r  &AsyncMongoClient._process_kill_cursorsu  so     +D 1 /3/G/G/K/K/M,H %%w8&DE%.55i@    -;(G(//	HdTYZZZ (c#3449O9O %''( -; !!//111H'<'B'B'D#,,,Z(TX,YYY  ,!#'788T^^=S=S)++	, (E !s   FA# 0F#
A0-F/A00F<BBBF
C+%;C& F&C++F
DF&E:D=;E F
F;FFFFc                6  #     U R                  5       I Sh  vN   U R                  R                  5       I Sh  vN   g N' N! [         aI  n[	        U[
        5      (       a   U R                  R                  (       a   SnAg[        5          SnAgSnAff = f7f)zSProcess any pending kill cursors requests and
maintain connection pool parameters.
N)r  r   update_poolrm  r   r0   r   r=   )r   r  s     r   r   (AsyncMongoClient._process_periodic_tasks  so     	$,,.....,,... /. 	$#/00T^^5K5K!##		$sW   BA ?!A AA BA A 
B0B=B
BBBBc                d    [        U[        5      (       a  gU R                  R                  U5      $ )z.Internal: return a _ServerSession to the pool.N)r   r%   r   return_server_session)r   r  s     r   _return_server_session'AsyncMongoClient._return_server_session  s*     n&9::~~33NCCr   c                 #    Ub<  [        U[        R                  5      (       d  [        S[	        U5       35      eU7v   gU R                  U5      nU(       a(   U7v    U(       a  UR                  5       I Sh  vN   ggS7v   g! [         aN  n[        U[        5      (       a  UR                  R                  5         UR                  5       I Sh  vN    e SnAff = f Ng! U(       a  UR                  5       I Sh  vN    f f = f7f)r  Nz>'session' argument must be an AsyncClientSession or None, not )r   r   rd   
ValueErrorr   r  rm  r/   _server_session
mark_dirtyend_session)r   r  r  r>  r  s        r   rJ  AsyncMongoClient._tmp_session  s     
 g~'H'HII TUYZaUbTcd  M  )* --/))  J  c#455%%002 mmo%% * --/)) sa   ADB !D;C#<D
C ACCCC  C% #D%D DDDc                   #    U R                   R                  UR                  S5      5      I S h  vN   Ub  UR                  U5        g g  N7f)Nr  )r   receive_cluster_timer   _process_response)r   replyr  s      r   r  "AsyncMongoClient._process_response  sG      nn11%))N2KLLL%%e,  	Ms   .AAAc           	        #    [        [        U R                  R                  S[        R
                  US9I Sh  vN 5      $  N7f)zGet information about the MongoDB server we're connected to.

:param session: a
    :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.

.. versionchanged:: 3.6
   Added ``session`` parameter.
	buildinfo)r   r  N)r   r   r'  r  rK   r  r  s     r   server_infoAsyncMongoClient.server_info  sE      **$$^-C-CW %  
 	
s   7AA
	Ac                   #    SS0nUR                  U5        Ub  X$S'   U R                  S5      nUR                  XA[        R                  S9I S h  vN nSUS   SS	.n[        US
   US US9$  N7f)NlistDatabasesr   r1  r'  )r  r  r   	databasesz
admin.$cmd)id
firstBatchnsz$cmd)r1  )r   r  _retryable_read_commandrJ   LIST_DATABASESr&   )r   r  r1  r   cmdr'  r   cursors           r   _list_databases AsyncMongoClient._list_databases  s      "

6$	N..w711C,>,> 2 
 

 k*

 "%-wOO
s   AA0A.A0c                D   #    U R                   " X40 UD6I Sh  vN $  N7f)aE  Get a cursor over the databases of the connected server.

:param session: a
    :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
:param comment: A user-provided comment to attach to this
    command.
:param kwargs: Optional parameters of the
    `listDatabases command
    <https://mongodb.com/docs/manual/reference/command/listDatabases/>`_
    can be passed as keyword arguments to this method. The supported
    options differ by server version.


:return: An instance of :class:`~pymongo.asynchronous.command_cursor.AsyncCommandCursor`.

.. versionadded:: 3.6
Nr  )r   r  r1  r   s       r   list_databasesAsyncMongoClient.list_databases	  s#     . ))'EfEEEEs     c                   #    U R                  USUS9I Sh  vN nU Vs/ s Sh  vN oDS   PM   N N
 sn$ s  snf 7f)a2  Get a list of the names of all databases on the connected server.

:param session: a
    :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
:param comment: A user-provided comment to attach to this
    command.

.. versionchanged:: 4.1
   Added ``comment`` parameter.

.. versionadded:: 3.6
T)nameOnlyr1  Nr  r  )r   r  r1  r   docs        r   list_database_names$AsyncMongoClient.list_database_names	  s@     " ((4(QQ-011cF R111s0   >1>953
59>59>c           
       #    Un[        U[        R                  5      (       a  UR                  n[        U[        5      (       d  [        S[        U5       35      eU R                  U[        R                  S9I Sh  vN  ISh  vN nX   R                  USUS.[        R                  U R                  U5      SUS9I Sh  vN   SSS5      ISh  vN   g N\ NU N N! , ISh  vN  (       d  f       g= f7f)as  Drop a database.

Raises :class:`TypeError` if `name_or_database` is not an instance of
:class:`str` or :class:`~pymongo.asynchronous.database.AsyncDatabase`.

:param name_or_database: the name of a database to drop, or a
    :class:`~pymongo.asynchronous.database.AsyncDatabase` instance representing the
    database to drop
:param session: a
    :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
:param comment: A user-provided comment to attach to this
    command.

.. versionchanged:: 4.1
   Added ``comment`` parameter.

.. versionchanged:: 3.6
   Added ``session`` parameter.

.. note:: The :attr:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.write_concern` of
   this client is automatically applied to this operation.

.. versionchanged:: 3.4
   Apply this client's write concern automatically to this operation
   when connected to MongoDB >= 3.4.

zDname_or_database must be an instance of str or a AsyncDatabase, not r  Nr   )dropDatabaser1  T)r   r   parse_write_concern_errorr  )r   r    r}  r  r   r   r   r!  rJ   DROP_DATABASE_commandrK   r  _write_concern_for)r   name_or_databaser  r1  r  r  s         r   drop_databaseAsyncMongoClient.drop_database/	  s     D  dH223399D$$$VW[\`WaVbc  ..w#BSBS.TTTTX\*%%!"w7 . 6 6"55g>*. &    UTT UTTTsl   A;C<=C>C<CC<
:C"CC"	C<C C<C<C" C<"C9(C+)C95C<c	           
       #    U R                   R                  (       a  [        S5      eU(       aD  UR                  (       a3  U(       a  [        S5      eUR                  R
                  R                  nOU(       d  U R                  nU(       a#  UR                  (       d  U(       a  [        S5      eU(       a#  UR                  (       d  U(       a  [        S5      e[        R                  " SU5        [        U UUUUUUS9n	U H  n
 U
R                  U	5        M     U	R                  U[        R                   5      I Sh  vN $ ! [         a    [        U
< S35      Sef = f N"7f)	a  Send a batch of write operations, potentially across multiple namespaces, to the server.

Requests are passed as a list of write operation instances (
:class:`~pymongo.operations.InsertOne`,
:class:`~pymongo.operations.UpdateOne`,
:class:`~pymongo.operations.UpdateMany`,
:class:`~pymongo.operations.ReplaceOne`,
:class:`~pymongo.operations.DeleteOne`, or
:class:`~pymongo.operations.DeleteMany`).

  >>> async for doc in db.test.find({}):
  ...     print(doc)
  ...
  {'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')}
  {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')}
  ...
  >>> async for doc in db.coll.find({}):
  ...     print(doc)
  ...
  {'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')}
  ...
  >>> # DeleteMany, UpdateOne, and UpdateMany are also available.
  >>> from pymongo import InsertOne, DeleteOne, ReplaceOne
  >>> models = [InsertOne(namespace="db.test", document={'y': 1}),
  ...           DeleteOne(namespace="db.test", filter={'x': 1}),
  ...           InsertOne(namespace="db.coll", document={'y': 2}),
  ...           ReplaceOne(namespace="db.test", filter={'w': 1}, replacement={'z': 1}, upsert=True)]
  >>> result = await client.bulk_write(models=models)
  >>> result.inserted_count
  2
  >>> result.deleted_count
  1
  >>> result.modified_count
  0
  >>> result.upserted_count
  1
  >>> async for doc in db.test.find({}):
  ...     print(doc)
  ...
  {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')}
  {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')}
  {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')}
  ...
  >>> async for doc in db.coll.find({}):
  ...     print(doc)
  ...
  {'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')}
  {'y': 2, '_id': ObjectId('507f1f77bcf86cd799439012')}

:param models: A list of write operation instances.
:param session: (optional) An instance of
    :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
:param ordered: If ``True`` (the default), requests will be
    performed on the server serially, in the order provided. If an error
    occurs all remaining operations are aborted. If ``False``, requests
    will be still performed on the server serially, in the order provided,
    but all operations will be attempted even if any errors occur.
:param verbose_results: If ``True``, detailed results for each
    successful operation will be included in the returned
    :class:`~pymongo.results.ClientBulkWriteResult`. Default is ``False``.
:param bypass_document_validation: (optional) If ``True``, allows the
    write to opt-out of document level validation. Default is ``False``.
:param comment: (optional) A user-provided comment to attach to this
    command.
:param let: (optional) Map of parameter names and values. Values must be
    constant or closed expressions that do not reference document
    fields. Parameters can then be accessed as variables in an
    aggregate expression context (e.g. "$$var").
:param write_concern: (optional) The write concern to use for this bulk write.

:return: An instance of :class:`~pymongo.results.ClientBulkWriteResult`.

.. seealso:: For more info, see :doc:`/examples/client_bulk`.

.. seealso:: :ref:`writes-and-ids`

.. note:: requires MongoDB server version 8.0+.

.. versionadded:: 4.9
zFMongoClient.bulk_write does not currently support automatic encryptionz5Cannot set write concern after starting a transactionz?Cannot request unacknowledged write concern and verbose resultsz>Cannot request unacknowledged write concern and ordered writesmodels)r   orderedbypass_document_validationr1  letverbose_resultsz is not a valid requestN)r   r   r0   r  r  r   r   acknowledgedr   validate_listr$   _add_to_client_bulkrw  r   executerJ   
BULK_WRITE)r   r  r  r  r  r  r1  r  r   blkmodels              r   
bulk_writeAsyncMongoClient.bulk_writed	  s6    x ==--"X  w--&'^__#0055CCM ! $ 2 2!;!;"Q  =#=#='"#cddXv.''A+
 EO))#.  [[#..999 " O5)+B CD$NO :s*   DE$E'E$?E" E$EE$)r   r   r   r   r   r   r  r   r   r   r   r   r   r   r   r   r   )NNNNNN)rx   z#Optional[Union[str, Sequence[str]]]ry   Optional[int]rs   zOptional[Type[_DocumentType]]rt   Optional[bool]ru   r  rz   zOptional[TypeRegistry]r   r   r  Noner  r  )r   zCollection[tuple[str, int]]r   r   r   r   r  r  )r   !common._CaseInsensitiveDictionaryr   zset[tuple[str, int | None]]r  r  )r~   r  r   r  r  r  r   )r  r  r  r  )r  r5  r  r  )r   r   r  rp   )NNNNNNNNNNNN)r)  zOptional[_Pipeline]r*  Optional[str]r+  Optional[Mapping[str, Any]]r,  r  r-  r  r.  zOptional[_CollationIn]r/  zOptional[Timestamp]r  +Optional[client_session.AsyncClientSession]r0  r  r1  Optional[Any]r2  r  r&  r  r  z AsyncChangeStream[_DocumentType])r  rQ   )r  zFrozenSet[_Address])r  r*   )r  z>tuple[tuple[_Address, ...], Optional[str], Optional[str], str])rO  r   r  r  )r  r   )r  r   )r  r   r  %database.AsyncDatabase[_DocumentType])r  r   r=  Optional[_CursorAddress]r  Optional[_ConnectionManager]r  r  )r  r  r   r   r  rd   )NNF)r  r  r  z+Optional[client_session.TransactionOptions]r  r  r  z!client_session.AsyncClientSession)r  r5  r  r5  )r  zMutableMapping[str, Any]r  r5  r  r  )NNNNN)r  r  r   (Optional[CodecOptions[_DocumentTypeArg]]r   Optional[_ServerMode]r   Optional[WriteConcern]r   Optional[ReadConcern]r  r  )r  r  r   r  r   r  r   r  r   r  r  r  )r  r   r  zdatabase.AsyncDatabase)r  zAsyncMongoClient[_DocumentType])r  r   r  r   r  r   r  r  )r  r   )r  r   r  r   )r  zOptional[tuple[str, int]])r  zset[_Address]r  )r  zlist[_ServerSession]r  r  )r  r(   )r  rj   r  r5  r  z%AsyncGenerator[AsyncConnection, None])NNN)r   z Callable[[Selection], Selection]r  r5  r  r   r=  Optional[_Address]r  zOptional[list[Server]]r  r  r  rj   )r  r5  r  r   r  z$AsyncContextManager[AsyncConnection])r   rL   r  rj   r  r5  r  z9AsyncGenerator[tuple[AsyncConnection, _ServerMode], None])r   rL   r  r5  r  r   r  z8AsyncContextManager[tuple[AsyncConnection, _ServerMode]])r  zUnion[_Query, _GetMore]r1  r	   r=  r  r  rl   )r4  r  r:  _WriteCall[T]r  r5  r;  -Optional[Union[_AsyncBulk, _AsyncClientBulk]]r  r   r  r  r  rn   )FNNFN)r:  _WriteCall[T] | _ReadCall[T]r  r5  r;  r  r  r   rB  r  r=  r  r  r  r4  r  r  r  r  rn   )NTN)r:  z_ReadCall[T]r  rL   r  r5  r  r   r=  r  r4  r  r  r  r  rn   )NN)r4  r  r:  r  r  r5  r  r   r;  r  r  r  r  rn   )r  r   r=  r  r  rf   r  r5  rP  r  r  r  )
r  r   r=  r  r  r5  r  r  r  r  )
r`  Sequence[int]r=  r  r  r(   r  r5  r  r  )
r`  r  r=  r?   r  r5  r  ri   r  r  )r  z*Union[_ServerSession, _EmptyServerSession]r  r  T)r  r  r  r  r  zGAsyncGenerator[Optional[client_session.AsyncClientSession], None, None])r  zMapping[str, Any]r  r5  r  r  )r  r  r  zdict[str, Any])r  r  r1  r  r   r   r  z"AsyncCommandCursor[dict[str, Any]])r  r  r1  r  r  z	list[str])r  z4Union[str, database.AsyncDatabase[_DocumentTypeArg]]r  r  r1  r  r  r  )NTFNNNN)r  z!Sequence[_WriteOp[_DocumentType]]r  r5  r  r  r  r  r  r  r1  r  r  zOptional[Mapping]r   r  r  rM   )\r^  r]  __qualname____firstlineno__r   r   rj  r  WeakValueDictionaryrv   __annotations__r   r   r   r   r   r   r   r  r  r#  r4  propertyr8  rB  r   rJ  rP  rS  rW  rm  rr  rz  rx  r  r  r  r  r  r  r  r  r  r  r  __iter__r  nextr  r=  r  r  r  r  r  r  r  r   acloser   
contextlibasynccontextmanagerr  r  r!  r)  r  r   applyr7  r>  r=  r6  rK  rQ  rX  rW  r\  r[  r  r   rv  rJ  r  r  r  r  r  r  r  __static_attributes____classcell__)r   s   @r   rp   rp      sy
   DD B,3,G,G,IH)I 59"8<#'"&04C!1C! C! 6	C!
 !C!  C! .C! C! 
C! C!JCPJ.0.AD.X[.	.85>Y	*7 0 
+	#<X-( )-'+48+/$(,07;?C37!%59/3A%A %A 2	A
 )A "A *A "5A =A 1A A &3A -A 
*AF * *( G G  

!%""H?&2( 26	HH *H /	H
 
HW .2SW#(	
*
 &Q
 !	

 
+
< 7;3	%3/3:V3	3" "&BF1504.2:
:
 @:
 /	:

 .:
 ,:
 
/:
| #BF1504.29
9
 @9
 /	9

 .9
 ,9
 
/9
v
 HE D6" 6 60 
2 
2 
6 
6 3 3 : : P P,"H . ##'C	. $L '+8<&*-9- .- 	-
 $-  6- $- 
-^/3/@C/	-/ ##(*(4:(Ea(	B( $(0H$H .H 	H
 
BH [[
 '+	8
*8
 8
 $	8

 
8
 8
B '+

 
 .	

 <
 
 $
 

< [[ &*+/&*$*$ .$ <	$
 $ $ $$ )$ $ $$ 
$ $X '+&*)
)
 )
 .	)

 )
 $)
 )
 $)
 
)
b ?C&*ee e .	e
 e <e $e 
e2,, *, %	,
 ., , 
,0 , , * , %	 ,
 . ,  , 
 ,L 151588 *8 .	8
 /8 
86M!M *M 	M
 .M 
M(
C!
C  
C .	
C
 
C 

C&,R$DHD	D ##RVBKO	P $>-&-1M-	- FJ
B
	
( @D!%P<P P 	P
 
,P0 @D!%F<F F 	F
 
,F6 @D!%2<2 2 
	2( [[ @D!%	2N2 =2 	2
 
2 2h [[ 15 %59!%!%04B:1B: .B: 	B:
 B: %3B: B: B: .B: 
B: B:r   rp   c                    [        U [        [        45      (       a  U R                  S   nU(       a  US   $ S$ [        U [        [
        45      (       a'  [        [        [        [        4   U R                  5      $ g)z:Return the server response from PyMongo exception or None.writeConcernErrorsN)
r   r,   r-   detailsr1   r2   r   r   r   r   )r  wcess     r   _retryable_error_docr  	  sg    #(@ABB {{/0tBx)T)#)9:;;GCH%s{{33r   c                z   [        U 5      nU(       a  UR                  SS5      nUS:X  a7  [        U 5      R                  S5      (       a  Sn[	        XTU R
                  5      eUS:  a+  UR                  S/ 5       H  nU R                  U5        M     OB[        U [        5      (       a  U(       a  O%U[        R                  ;   a  U R                  S5        [        U [        5      (       a  U R                  nOU n[        U[        5      (       a.  [        U[        [        45      (       d  UR                  S5        g g g )	Ncoder      zTransaction numberszrThis MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.	   errorLabelsRetryableWriteError)r  r   r   r   r2   r  r  r   r6   r   _RETRYABLE_ERROR_CODESr-   errorr/   r1   r5   )r  r  r  r  r  errmsglabelexc_to_checks           r   _add_retryable_write_errorr  	  s   
s
#C
wwvq!2:#c(--.CDD- 
 #6==q 3$$U+ 4 #011i>>>$$%:; #/00yy, 122:(=>< < 	%%&;<<2r   c                  z    \ rS rSrSrSr      SS jrSSS jjr      SS jrSS jr	        SS jr
S	rg
)r  i
  z1Handle errors raised when executing an operation.)r   server_addressr  r  sock_generationcompleted_handshake
service_idhandledc                   [        U[        5      (       dK  [        S [        U5      R                   5       5      (       d!  [        S[        U5      R                   35      eXl        UR                  R                  U l
        X0l        [        R                  U l        UR                  R                   R#                  5       U l        SU l        S U l        SU l        g )Nc              3  >   #    U  H  oR                   S :H  v   M     g7f)rp   N)r^  )r   clss     r   r   4_MongoClientErrorHandler.__init__.<locals>.<genexpr>,
  s     ZEYc||'99EYs   z$AsyncMongoClient required but given F)r   rp   anyr   __mro__r   r^  r   r7  r=  r  r  r   MIN_WIRE_VERSIONr  poolgenget_overallr  r  r  r  )r   r   r  r  s       r   r   !_MongoClientErrorHandler.__init__'
  s     &"233ZT&\EYEYZZZ"FtF|G\G\F] ^__$0088 & 7 7
  &{{::<#( .2r   c                v    UR                   U l         UR                  U l        UR                  U l        X l        g)z0Provide socket information to the error handler.N)r  
generationr  r  r  )r   r  r  s      r   r	  *_MongoClientErrorHandler.contribute_socket<
  s-     $ 5 5#//#6 r   c                P  #    U R                   (       d  Uc  g SU l         U R                  (       a  [        U[        5      (       a  UR                  n[        U[
        5      (       aP  U R                  R                  (       a  UR                  S5        U R                  R                  R                  5         [        U[        5      (       aN  UR                  S5      (       d  UR                  S5      (       a"  U R                  R                  5       I S h  vN   [        UU R                  U R                  U R                   U R"                  5      nU R$                  R&                  c   eU R$                  R&                  R)                  U R*                  U5      I S h  vN   g  N N7f)NTr  r  )r  r  r   r-   r  r/   r  r  rz  r{  r3   has_error_labelr  r)   r  r  r  r  r   r   handle_errorr  )r   r  r  err_ctxs       r   handle_MongoClientErrorHandler.handleC
  s@     <<7?<<'#;<<!--'#455<<..,,-HI,,779'<00**+FGG7KbKb)L L ,,--///!!  $$OO
 {{$$000kk##001D1DgNNN 0 	Os%   DF&F"BF&F$F&$F&c                   #    U $ 7fr   r   r   s    r   r  #_MongoClientErrorHandler.__aenter__`
  r  r  c                @   #    U R                  X5      I S h  vN $  N7fr   )r  r  s       r   r  "_MongoClientErrorHandler.__aexit__c
  s      [[3333r  )r   r  r  r  r  r  r  r  N)r   rp   r  rj   r  r5  r  )r  ri   r  r  r  r  )r  zOptional[Type[BaseException]]r  zOptional[BaseException]r  r  )r  r  )r  zOptional[Type[Exception]]r  zOptional[Exception]r  zOptional[TracebackType]r  r  )r^  r]  r  r  __doc__	__slots__r   r	  r  r  r  r  r   r   r   r  r  
  s    ;	I&06A]*7O5O@WO	O:4+4 %4 (	4
 
4r   r  c                      \ rS rSrSr      S                   SS jjrSS jrSS jrSS jrSS jr	SSS	 jjr
SS
 jrSS jrSS jrSrg)rC  il
  zKResponsible for executing retryable connections on read or write operationsNc                "   S U l         SU l        [        R                  " 5       S LU l        Xl        X l        X0l        X`l        XPl	        Xl
        Xpl        U(       a  UO[        U l        Xl        S U l        / U l        X@l        Xl        SU l        g )NFr   )_last_error	_retryingr   get_timeout_multiple_retries_client_func_bulkr0  _is_read
_retryable
_read_prefrN   _server_selector_address_server_deprioritized_servers
_operation_operation_id_attempt_number)r   rA  r:  r;  r  rB  r  r  r=  r4  r  s              r   r   #_ClientConnectionRetryable.__init__o
  s     15!&!2!2!4D!@#

## I&> 	  #46##) r   c                  #    U R                  5       (       a^  U R                  (       aM  U R                  (       d<  U R                  R	                  5         U R
                  (       a  SU R
                  l         U R                  SS9   U R                  (       a  U R                  5       I Sh  vN $ U R                  5       I Sh  vN $  N N! [         a    U R                  5         e [         Ga  nU R                  (       a  [        U[        [        45      (       ao  [        USS5      nU R!                  5       (       d)  [        U[        5      (       a  U["        R$                  ;  a  e SU l        Xl        U =R*                  S-  sl        Oe U R                  (       Gd  U R                  (       d  e [        U[,        5      (       aN  UR.                  (       a=  [        UR.                  [        5      =(       a    UR.                  R1                  S5      nOUR1                  S5      nU(       a6  U R                  (       d   eU R                  R3                  5       I Sh  vN    U(       a  U R!                  5       (       a5  UR1                  S5      (       a  U R(                  (       a  U R(                  Uee U =R*                  S-  sl        U R
                  (       a  SU R
                  l        OSU l        UR1                  S5      (       d  Xl        U R(                  c  Xl        U R6                  R8                  R:                  [<        R>                  :X  a%  U R@                  RC                  U RD                  5         SnAOSnAff = fGM  7f)zRuns the supplied func() and attempts a retry

:raises: self._last_error: Last exception raised

:return: Result of the func() call
T)
check_csotNr  r   r  NoWritesPerformed)#_is_session_state_retryabler  r  r0  _start_retryable_writer  started_retryable_write_check_last_error_read_writer4   r3   r   r/   r2   r  _is_not_eligible_for_retryr   r  r  r  r  r-   r  r  r  retryingr  r8  r  rP   r  r  r  r  )r   r  exc_coderetryable_write_error_excs       r   rD  _ClientConnectionRetryable.run
  s     ++--$//$--MM002zz59

2""d"39E-1]]TZZ\)Sdkkm@SS)@S.  &&(  .E==!#(9;K'LMM#*3#=::<<&s,<== (0U0U U!)-+.(,,1, }}}??!#'?@@SYY4>II|5 5O!ii778MN 2 584G4GH]4^10#}},}"mm2244448W8W8Y8Y../BCCHXHX"&"2"2;!((A-(zz.2

+)-../BCC+.(''/+.(<<44BBmF[F[[//66t||D].E sn   BN$C +C,C /N0C C
C NC 
C %N1E+M=IDM=8N=NNc                    U R                   (       + =(       d(    U R                  5       =(       a    U R                  (       + $ )z0Checks if the exchange is not eligible for retry)r  _is_retryingr  r   s    r   r&  5_ClientConnectionRetryable._is_not_eligible_for_retry
  s+    ??"Zt'8'8':'Y4CYCY?YZr   c                h    U R                   (       a  U R                   R                  $ U R                  $ )z6Checks if the exchange is currently undergoing a retry)r  r'  r  r   s    r   r,  '_ClientConnectionRetryable._is_retrying
  s!    &*jjtzz""DdnnDr   c                    U R                   (       a.  U R                  =(       a    U R                  R                  (       + $ [        U R                  =(       a    U R                  R                  (       + 5      $ )zChecks if provided session is eligible for retry

reads: Make sure there is no ongoing transaction (if provided a session)
writes: Make sure there is a session without an active transaction
)r  r0  r  r  r   s    r   r   6_ClientConnectionRetryable._is_session_state_retryable
  sH     ==F$--*F*FGGDMMF$--*F*F&FGGr   c                    U R                  5       (       aB  [        R                  " 5       nU(       a	  Ub"  US::  a  U R                  c   eU R                  eggg)zChecks if the ongoing client exchange experienced a exception previously.
If so, raise last error

:param check_csot: Checks CSOT to ensure we are retrying with time remaining defaults to False
Nr   )r,  r   	remainingr  )r   r  r3  s      r   r#  ,_ClientConnectionRetryable._check_last_error
  sY     )I)"7IN''333&&& =K"7 r   c           	        #    U R                   R                  U R                  U R                  U R                  U R
                  U R                  U R                  S9I Sh  vN $  N7f)zfRetrieves a server object based on provided object context

:return: Abstraction to connect to server
)r=  r  r  N)r  r  r  r0  r  r  r  r  r   s    r   _get_server&_ClientConnectionRetryable._get_server
  s]     
 \\00!!MMOOMM"&"="=++ 1 
 
 	
 
s   AA' A%!A'c           	       #     SnSnU R                  5       I Sh  vN U l        U R                  R                  U R                  U R                  5       ISh  vN nUR
                  nU R                  =(       a3    U R                  R                  R                  =(       a    UR                  nUR                  nU(       d  U R                  5         SU l        U R                  (       aP  [        [        SU R                   3U R                  R                   R"                  U R$                  U R&                  S9  U R)                  U R                  X0R                  5      I Sh  vN sSSS5      ISh  vN   $  GN_ GN$ N N! , ISh  vN  (       d  f       g= f! [*         a%  nU R                  (       d  e [-        UWW5        e SnAff = f7f)z]Wrapper method for write-type retryable client executions

:return: Output for func()'s call
r   FNzRetrying write attempt number messageclientIdcommandNameoperationId)r6  r  r  r  r0  r  r7  retryable_writes_supportedr  r  r#  r  r  r<   r;   r  r   r  r  r  r  r3   r  )r   r  r  r  sessions_supportedr  s         r   r%  !_ClientConnectionRetryable._write	  s_    
	 I!%!1!1!33DL||--dllDMMJJd#'#8#8 MM /00KK/.. #
 !NN	) **,&+DO>>'"@AUAU@V W!%!@!@!M!M$(OO$($6$6 "ZZt__MM+ KJJ 4J* N+ KJJJ,  	??&s,<iH	s   GF E:=F E=F DF$F %F(F 4F5F 9G:F =F  FF F
FFF GF 
G( GGGc           	       #    U R                  5       I Sh  vN U l        U R                  c   S5       eU R                  R	                  U R                  U R                  U R
                  5       ISh  vN u  nnU R                  (       a!  U R                  (       d  U R                  5         U R                  (       aP  [        [        SU R                   3U R                  R                  R                  U R                  U R                  S9  U R!                  U R
                  U R                  X5      I Sh  vN sSSS5      ISh  vN   $  GN8 N N N! , ISh  vN  (       d  f       g= f7f)z\Wrapper method for read-type retryable client executions

:return: Output for func()'s call
Nz&Read Preference required on read callszRetrying read attempt number r9  )r6  r  r  r  r)  r0  r  r  r#  r<   r;   r  r   r  r  r  r  )r   r  r  s      r   r$   _ClientConnectionRetryable._read/  s	    
 "--//*T,TT*<<11$//4<<QUQ^Q^__ d
~~doo&&(~~#;D<P<P;QR!\\<<II $ $ 2 2 DMM4<<QQ `__ 0_ R `___sk   E1EAE13E4E17CE8E9E<E1E	E1E1EE1E.E E.*E1)r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r0  )FNNNFN)rA  rp   r:  r  r;  r  r  r   rB  r  r  r5  r  r  r=  r  r4  r  r  r  )r  rn   r  )F)r  r  r  r  )r  rj   )r^  r]  r  r  r  r   rD  r&  r,  r   r#  r6  r%  r$  r  r   r   r   rC  rC  l
  s    U 04+/&*&* !& ! + ! <	 !
  !  ! . ! ) ! $ !  ! $ !DJEX[EH
'
$LRr   rC  c                     [        5         [        R                  R                  5        H  u  pUR	                  5         M     g)zSReleases the locks in child process and resets the
topologies in all MongoClients.
N)r9   rp   rv   r   r  )rv  r   s     r   _after_fork_childrD  G  s3    
  &..446	 7r   c                    U R                  5       n S/nSS/nU H+  nU R                  U5      (       d  M  [        [        S5          g   U H+  nU R                  U5      (       d  M  [        [        S5          g   g)zTDetects external database hosts and logs an informational message at the INFO level.z.cosmos.azure.comz.docdb.amazonaws.comz.docdb-elastic.amazonaws.comzYou appear to be connected to a CosmosDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/cosmosdbTzYou appear to be connected to a DocumentDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/documentdbF)lowerendswithr>   r:   )r   cosmos_db_hostsdocument_db_hostsrx   s       r   r   r   S  s    \\^F*+O/1OP??4  i
    "??4  k
  " r   )after_in_child)r  r3   r  r  )r  r3   r  r   r  r  r  r  r  )r   r   r  r  )r  
__future__r   r  r  osr  r  collectionsr   typingr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   bson.codec_optionsr   r   r   bson.timestampr   pymongor   r   r   r   pymongo.asynchronousr   r    r!   "pymongo.asynchronous.change_streamr"   r#    pymongo.asynchronous.client_bulkr$   #pymongo.asynchronous.client_sessionr%   #pymongo.asynchronous.command_cursorr&   pymongo.asynchronous.settingsr'   pymongo.asynchronous.topologyr(   r)   pymongo.client_optionsr*   pymongo.errorsr+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   pymongo.lockr7   r8   r9   pymongo.loggerr:   r;   r<   r=   r>   pymongo.messager?   r@   rA   pymongo.monitoringrB   rC   pymongo.operationsrD   rE   rF   rG   rH   rI   rJ   pymongo.read_preferencesrK   rL   pymongo.resultsrM   pymongo.server_selectorsrN   pymongo.server_typerO   pymongo.topology_descriptionrP   rQ   pymongo.typingsrR   rS   rT   rU   rV   rW   pymongo.uri_parser_sharedrX   rY   rZ   r[   r\   r]   r^   pymongo.write_concernr_   r`   typesra   bson.objectidrb   pymongo.asynchronous.bulkrc   rd   re   pymongo.asynchronous.cursorrf   r   rh   pymongo.asynchronous.poolri   pymongo.asynchronous.serverrj   pymongo.read_concernrk   pymongo.responserl   rm   rn   r  
_WriteCall	_ReadCallr   _WriteOp
BaseObjectrp   r  r  r  rC  rD  r   register_at_forkr   r   r   <module>ru     s  $ #   	   #    * Q P $ D D E E Z = C B : A 0    
  = < F   A 1 = + K    F#&4V>:920)2 CL"#%6=ycST?UU
 "#X/@+Nc3k	
 |$:v(('-*@ |$:~I	 =FP4 P4fXR XRv	2  '89	 r   