o
    'h.                    @  s  d Z ddlmZ ddlZddlZddlZddlZddlZddlm	Z	 ddl
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ ddlmZmZm Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z&m'Z' dd	l(m)Z)m*Z*m+Z+ dd
l,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8m9Z9 ddl:m;Z; ddl<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZH ddlImJZJmKZKmLZL ddlMmNZNmOZOmPZPmQZQmRZR ddlSmTZTmUZUmVZV ddlWmXZXmYZY ddlZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZa ddlbmcZcmdZd ddlemfZf ddlgmhZh ddlimjZj ddlkmlZl ddlmmnZnmoZo ddlpmqZqmrZrmsZsmtZtmuZumvZv ddlwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~ ddlmZmZ erdd lmZ dd!lmZ dd"lmZ dd#l1mZmZ dd$lmZ dd%lmZ dd&lmZ dd'lmZ dd(lmZ dd)lmZ dd*limZ ed+Zeed, d-egeeeef f Zeed, d.d-edgeeeef f Zd/Zee]e\e[e^e`e_f ZG d0d1 d1e%jeet ZdJd6d7ZdKd=d>ZG d?d@ d@ZG dAdB dBee ZdLdCdDZdMdGdHZeJrejedI dS dS )Na  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ServerDescription)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Tre   rj   rk   Fc                      s  e Zd ZU dZdZdZe Zde	d< 						d&d' fddZ
d(ddZd)ddZd*d#d$Zd+d&d'Zd(d(d)Zd,d-d+d,Zd.d/d0Zd(d1d2Zd/d3d4Z												d0d1dHdIZed2dKdLZed3dNdOZed4dQdRZd5dTdUZd6dXdYZd6dZd[Zd7d]d^Zd8d`daZd8dbdcZd9dfdgZd9dhdiZ d(djdkZ!	d,d:dqdrZ"d;dudvZ#			wd<d=d}d~Z$	d,d>ddZ%d?ddZ&					d@dAddZ'					d@dBddZ(dCddZ)dDddZ*dEddZ+dZ,dFddZ-e-Z.dGddZ/edHddZ0edHddZ1edIddZ2edIddZ3edJddZ4edJddZ5dKddZ6d(ddZ7e8sce7Z9dLddZ:e;j<dMddZ=			dNdOddǄZ>dPddʄZ?e;j<dQdd΄Z@dRddфZAeBjC	d,dSddׄZD	d,dTdd߄ZEeBjC	w			w	dUdVddZF			dWdXddZG		dYdZddZHd[ddZId[ddZJ		dYd\ddZKd]ddZLd^ddZMd(ddZNd(dd ZOd_ddZPe;j<	d`daddZQdbddZR	d,dcddZS		dYddddZT		dYddddZU		dYdeddZVeBjC		dYdfddZWeBjC			w				dgdhd$d%ZX  ZYS (i  AsyncMongoClient	localhostii  )document_classtz_awareconnectzweakref.WeakValueDictionary_clientsNhost#Optional[Union[str, Sequence[str]]]portOptional[int]rr   Optional[Type[_DocumentType]]rs   Optional[bool]rt   type_registryOptional[TypeRegistry]kwargsr   returnNonec                   sX  |pt }||||||d|| _|du r| j}t|tr|g}|du r&| j}t|ts4tdt| || _	|| _
d| _d| _d| _d| _|dd}	|dd}
|dd}t|}||d< d|i| _t | _d	}d}d}d}t }d}|d
}|d}tdd | j	D dkrtd| j	D ]B}d|v rt||ddd	|d}|t}| j|d  |d p|}|d p|}|d p|}|d }|d }q| jt|| j
 q| jstddd | jD D ]}t|r nq|dur||d< |du r|dd	}|du rddlm} |d|  }||d< ||d< |  ||}|du r0|d tj!}|p7|d}| "|| j}|d|}|d|}t#||||t$| _%|| _&t' | _(g | _)d| _*| j||||| j|||	|
|d!
 t+ ,| j%j-| j%j.| j%j/| j%j0 | 1| j|| d	| _2d	| _3d| _4|s| 5  t$r|r| 6  dS dS dS )"a{  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.
        )rv   rx   rr   rs   rt   r|   Nz%port must be an instance of int, not _pool_class_monitor_class_condition_classrr   keyword_optsFsrvservicenamesrvmaxhostsc                 S  s   g | ]}d |v r|qS )/ ).0hr   r   ]/var/www/html/olx_land/venv/lib/python3.10/site-packages/pymongo/asynchronous/mongo_client.py
<listcomp>  s    z-AsyncMongoClient.__init__.<locals>.<listcomp>   z+host must not contain multiple MongoDB URIsr   T)validatewarn	normalizesrv_max_hostsnodelistusernamepasswordr   optionsfqdn!need to specify at least one hostc                 S     g | ]}|d  qS r   r   r   noder   r   r   r   3      r|   rs   r   _is_faasrt   srvServiceName)
is_srvr   r   dbaseseedsr   srv_service_name
pool_classmonitor_classcondition_class)7dict_init_kwargsHOST
isinstancestrPORTint	TypeErrortype_host_port	_topology_timeout_topology_settings_event_listenerspopr   _CaseInsensitiveDictionary_resolve_srv_infoset_seedsgetlenr-   r^   
startswithrY   updater_   _detect_external_dbpymongo.pool_optionsr    _validate_kwargs_and_update_optsSRV_SERVICE_NAME_normalize_and_validate_optionsr)   _IS_SYNC_options_default_database_namer7   _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)selfrv   rx   rr   rs   rt   r|   r~   	doc_classr   r   r   r   r   r   r   r   optsr   r   r   entityreshostnamer   	__class__r   r   r      s       :












zAsyncMongoClient.__init__c                   s  | j d }t }t }|d}|d}| jD ]}d|v rO|d}|d ur2t|d|}tj	|| j
ddd|||dI d H }||d	  |d
 }n	|t|| j
 |s^tddd |D D ]}	t|	rm nqe|d }
|d }|
d u r|dd}
|d u rddlm} |d|  }|
|d< ||d< | ||}|d u r|dtj}|p|d}| ||}|d| j d }|d| j d }t||| j d |t| _| ||| qd S )Nr   r   r   r   connecttimeoutmsTF)r   r   r   connect_timeoutr   r   r   r   r   c                 S  r   r   r   r   r   r   r   r     r   z1AsyncMongoClient._resolve_srv.<locals>.<listcomp>rs   rt   r   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   rs   rt   r   r   r   r   r   r   _resolve_srvx  sj   







zAsyncMongoClient._resolve_srvr   Collection[tuple[str, int]]r   r   c                 C  s   | j jj| _tdi d|d| j jd| jd d| j jd| jd d| jd d| j jd| j jd	| j jd
| j j	d| jd d| j j
d| j jd|d|d| j jd| jr_| jjnd | _| j jrvddlm} || | j j| _| j j| _d S )Nr   replica_set_namer   pool_optionsr   r   local_threshold_msserver_selection_timeoutserver_selectorheartbeat_frequencyr   direct_connectionload_balancedr   r   server_monitoring_modetopology_idr   rh   r   )r   r   r   r&   r   r   r   r   r   r   r   r   r   r   _topology_idauto_encryption_optspymongo.asynchronous.encryptionri   r   r   r   )r   r   r   r   ri   r   r   r   r     sR   


	

z'AsyncMongoClient._init_based_on_optionsr   !common._CaseInsensitiveDictionaryset[tuple[str, int | None]]c                 C  s   t |}t|}t|| |S N)r\   r]   rZ   )r   r   r   r   r   r   r     s   
z0AsyncMongoClient._normalize_and_validate_optionsr   c                   s6   t   tt fdd  D  |  |S )Nc                 3  s&    | ]\}}t  ||V  qd S r   )r   r   r   )r   kvr   r   r   	<genexpr>  s   $ zDAsyncMongoClient._validate_kwargs_and_update_opts.<locals>.<genexpr>)r[   r   r   r   itemsr   )r   r   r   r   r   r   r     s   
z1AsyncMongoClient._validate_kwargs_and_update_optsc                   s   |   I dH  dS )zOExplicitly connect to MongoDB asynchronously instead of on the first operation.N)r   r   r   r   r   aconnect  s   zAsyncMongoClient.aconnectold_pidc                   sh   t | j| _tr| tj| jj< || j_d fdd}tj	t
jt
j|dd}t| |j || _d| _d S )	Nr   boolc                    s(     } | d u r
dS t | I d H  dS )NFT)rp   _process_periodic_tasks)clientself_refr   r   target  s   z1AsyncMongoClient._init_background.<locals>.targetpymongo_kill_cursors_thread)intervalmin_intervalr  nameFr   r   )r'   r   r   r6   rp   ru   r   _pidr   AsyncPeriodicExecutorr   KILL_CURSOR_FREQUENCYMIN_HEARTBEAT_INTERVALweakrefrefclose_kill_cursors_executorr   )r   r   r  executorr   r  r   r     s   	
z!AsyncMongoClient._init_backgroundsessionOptional[AsyncClientSession]c                 C  s   | j jo	|o|j S r   )r   r   in_transactionr   r  r   r   r   _should_pin_cursor  s   z#AsyncMongoClient._should_pin_cursorc                 C  s   |  | jj | jj  dS )z6Resets topology in a child after successfully forking.N)r   r   r	  _session_poolresetr   r   r   r   _after_fork  s   zAsyncMongoClient._after_forkc                 K  s"   | j  }|| tdi |S Nr   )r   copyr   rp   )r   r~   argsr   r   r   
_duplicate  s   

zAsyncMongoClient._duplicatepipelineOptional[_Pipeline]full_documentOptional[str]resume_afterOptional[Mapping[str, Any]]max_await_time_ms
batch_size	collationOptional[_CollationIn]start_at_operation_timeOptional[Timestamp]+Optional[client_session.AsyncClientSession]start_aftercommentOptional[Any]full_document_before_changeshow_expanded_events AsyncChangeStream[_DocumentType]c                   s8   t | j|||||||||	|
||d}| I dH  |S )aH  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
        )r/  N)r"   admin_initialize_cursor)r   r  r   r"  r$  r%  r&  r(  r  r+  r,  r.  r/  change_streamr   r   r   watch#  s$   pzAsyncMongoClient.watchrR   c                 C  s8   | j du rdd | jD }ttj|ddd| jS | j jS )a  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
        Nc                 S  s"   i | ]\}}||ft ||fqS r   rM   r   rv   rx   r   r   r   
<dictcomp>  s   " z9AsyncMongoClient.topology_description.<locals>.<dictcomp>)r   r   rR   rQ   Unknownr   description)r   serversr   r   r   topology_description  s   
z%AsyncMongoClient.topology_descriptionFrozenSet[_Address]c                 C  s,   | j du rt S | j j}tdd |jD S )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.
        Nc                 s  s    | ]}|j V  qd S r   address)r   sr   r   r   r     s    z)AsyncMongoClient.nodes.<locals>.<genexpr>)r   	frozensetr8  known_servers)r   r8  r   r   r   nodes  s   
zAsyncMongoClient.nodesr)   c                 C  s   | j S )zThe configuration options for this client.

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

        .. versionadded:: 4.0
        r   r   r   r   r   r     s   zAsyncMongoClient.options>tuple[tuple[_Address, ...], Optional[str], Optional[str], str]c                 C  s*   t t| jd | jj| jd | jd fS )Nr   r   r   )tuplesortedr   r   r   r   r   r   r   eq_props  s
   zAsyncMongoClient.eq_propsotherr   c                 C  s    t || jr|  | kS tS r   )r   r   rF  NotImplementedr   rG  r   r   r   __eq__  s   zAsyncMongoClient.__eq__c                 C  s
   | |k S r   r   rI  r   r   r   __ne__  s   
zAsyncMongoClient.__ne__r   c                 C  s   t |  S r   )hashrF  r   r   r   r   __hash__  s   zAsyncMongoClient.__hash__r   c                   s   ddd j d u rdjd	  d
g}nddd jjD  g}| fddjD  | fddjjD  d|S )Noptionr   valuer   r   c                 S  s^   | dkr|t u r
dS d|j d|j S | tjv r(|dur(|  dt|d  S |  d|S )z9Fix options whose __repr__ isn't usable in a constructor.rr   zdocument_class=dictzdocument_class=.N=i  )r   
__module____name__r   TIMEOUT_OPTIONSr   )rN  rO  r   r   r   option_repr  s   z2AsyncMongoClient._repr_helper.<locals>.option_reprzhost='mongodb+srv://r   'zhost=%rc                 S  s(   g | ]\}}|d urd||f n|qS )Nz%s:%dr   r5  r   r   r   r     s    z1AsyncMongoClient._repr_helper.<locals>.<listcomp>c                 3  s"    | ]} |j j | V  qd S r   rB  r   keyrU  r   r   r   r     s    
z0AsyncMongoClient._repr_helper.<locals>.<genexpr>c                 3  s@    | ]}|t jvr|d kr|dkr |jj| V  qdS )r   r   N)r   _constructor_argsr   rW  rY  r   r   r     s    z, )rN  r   rO  r   r   r   )r   r   r   r   extendrZ  r   join)r   r   r   rY  r   _repr_helper  s    


zAsyncMongoClient._repr_helperc                 C  s   t | j d|   dS )N())r   rS  r]  r   r   r   r   __repr__  s   zAsyncMongoClient.__repr__r  %database.AsyncDatabase[_DocumentType]c              	   C  s:   | drtt| j d|d| d|d| |S )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   rS  __getitem__r   r  r   r   r   __getattr__  s   

zAsyncMongoClient.__getattr__c                 C  s   t | |S )rb  )r   AsyncDatabaserf  r   r   r   re  (  s   zAsyncMongoClient.__getitem__c              	   C  sl   z)| j r$| js'tjdt| j d| jj dt| j dtdd W dS W dS W dS  t	t
fy5   Y dS w )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   rS  r   _stackResourceWarningrd  r   r   r   r   r   __del__2  s   	zAsyncMongoClient.__del__	cursor_idr=  Optional[_CursorAddress]conn_mgrOptional[_ConnectionManager]c                 C  s   | j |||f dS )z;Request that a cursor and/or connection be cleaned up soon.N)r   append)r   ro  r=  rq  r   r   r   _close_cursor_soonB  s   z#AsyncMongoClient._close_cursor_soonimplicitre   c                 K  s&   t  }tjdi |}t| |||S r  )r$   r   SessionOptionsre   )r   ru  r~   server_sessionr   r   r   r   _start_sessionK  s   zAsyncMongoClient._start_sessionFcausal_consistencydefault_transaction_options+Optional[client_session.TransactionOptions]snapshot!client_session.AsyncClientSessionc                 C  s   | j d|||dS )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)ry  rz  r|  )rx  )r   ry  rz  r|  r   r   r   start_sessionP  s   zAsyncMongoClient.start_sessionc              	   C  s2   |r|S z| j dddW S  ttfy   Y dS w )6If provided session is None, lend a temporary session.TF)ry  N)rx  r-   r/   r  r   r   r   _ensure_sessionm  s   z AsyncMongoClient._ensure_sessioncommandMutableMapping[str, Any]c                 C  sX   | j  }|r
|jnd }|r|r|d |d kr|}n|}n|p!|}|r*||d< d S d S )NclusterTime$clusterTime)r   max_cluster_timecluster_time)r   r  r  topology_timesession_timer  r   r   r   _send_cluster_time|  s   
z#AsyncMongoClient._send_cluster_timedefaultr   (Optional[CodecOptions[_DocumentTypeArg]]r   Optional[_ServerMode]r   Optional[WriteConcern]r   Optional[ReadConcern]c                 C  s>   | j du r|du rtdtt| j p|}t| |||||S )au  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.
        Nz-No default database name defined or provided.)r   r-   r   r   r   rh  )r   r  r   r   r   r   r  r   r   r   get_default_database  s   4z%AsyncMongoClient.get_default_databasec                 C  s4   |du r| j du rtd| j }t| |||||S )a|  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.
        NzNo default database defined)r   r-   r   rh  )r   r  r   r   r   r   r   r   r   get_database  s   2
zAsyncMongoClient.get_databasedatabase.AsyncDatabasec                 C  s   | j |ttjtdS )z7Get a AsyncDatabase instance with the default settings.)r   r   r   )r  r   rJ   PRIMARYr`   rf  r   r   r   _database_default_options  s   z*AsyncMongoClient._database_default_optionsAsyncMongoClient[_DocumentType]c                      | S r   r   r   r   r   r   
__aenter__     zAsyncMongoClient.__aenter__exc_typeexc_valexc_tbc                   s   |   I d H  d S r   )r  r   r  r  r  r   r   r   	__aexit__  s   zAsyncMongoClient.__aexit__r   c                 C  s   t d)Nz)'AsyncMongoClient' object is not iterable)r   r   r   r   r   __next__  s   zAsyncMongoClient.__next__	attr_namec                   s,   |   I dH ttjI dH }t|j|S )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_serverrO   rI   TESTgetattrr8  )r   r  serverr   r   r   _server_property  s
   
z!AsyncMongoClient._server_propertyOptional[tuple[str, int]]c                   sX   | j du r|  I dH  | j jj}|tjkr$t| j dkr$t	d| 
dI dH S )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
        Nr   zVCannot use "address" property when load balancing among mongoses, use "nodes" instead.r=  )r   r   _descriptiontopology_typerQ   Shardedr   r:  server_descriptionsr/   r  )r   r  r   r   r   r=  *  s   


zAsyncMongoClient.addressc                   *   | j du r|  I dH  | j  I dH S )aQ  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   r   get_primaryr   r   r   r   primaryE     
zAsyncMongoClient.primaryset[_Address]c                   r  )ae  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   r   get_secondariesr   r   r   r   secondariesT  r  zAsyncMongoClient.secondariesc                   r  )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   r   get_arbitersr   r   r   r   arbitersc  s   
zAsyncMongoClient.arbitersc                   s   |  dI dH S )aP  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   r   r   r   
is_primaryo  s   	zAsyncMongoClient.is_primaryc                   s   |  dI dH tjkS )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  rP   Mongosr   r   r   r   	is_mongosz  s   zAsyncMongoClient.is_mongossession_idslist[_ServerSession]c              	     s   za| j tjdtjdI dH 4 I dH B\}}|js&	 W d  I dH  W dS tdt|tj	D ]}d|||tj	  i}|j
d||| dI dH  q/W d  I dH  W dS 1 I dH s[w   Y  W dS  tyl   Y dS w )z7Send endSessions command(s) with the given session ids.N	operationr   endSessionsr1  )r   r   )_conn_for_readsrJ   PRIMARY_PREFERREDrI   END_SESSIONSsupports_sessionsranger   r   _MAX_END_SESSIONSr  r2   )r   r  conn	read_prefispecr   r   r   _end_sessions  s&   
	2zAsyncMongoClient._end_sessionsc                   s   | j du rdS | j  }|r| |I dH  | j  |  I dH  | j  I dH  | jr6| j I dH  d| _tsNt	j
| j  | j ddI dH  dS dS )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_monitorsr\  )r   r  r   r   r   r    s&   


zAsyncMongoClient.closer'   c              	     s   t s| jdu rt | _n| jt krtd| jsY| jd r,|  I dH  |   | j	
 I dH  | j4 I dH  | j
  W d  I dH  n1 I dH sQw   Y  d| _| j	S )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   r   r   r   r     s$   

(zAsyncMongoClient._get_topologyr  rk   %AsyncGenerator[AsyncConnection, None]c              
   C s*  |o|j }t| ||4 I d H x}|r.|r.|jr.||j |jV  	 W d   I d H  d S |j|dI d H 4 I d H 7}|rP|rP|jjtjtj	fv rP|
|| || | jre| jjse|jdk retd|V  W d   I d H  n1 I d H sxw   Y  W d   I d H  d S 1 I d H sw   Y  d S )N)handler   z9Auto-encryption requires a minimum MongoDB version of 4.2)r  _MongoClientErrorHandler_pinned_connectioncontribute_socketcheckoutr8  r  rP   r  LoadBalancer_pinr   _bypass_auto_encryptionmax_wire_versionr-   )r   r  r  in_txnerr_handlerr  r   r   r   	_checkout  s>   


*.zAsyncMongoClient._checkoutr    Callable[[Selection], Selection]r  Optional[_Address]deprioritized_serversOptional[list[Server]]operation_idc           
   
     s   zB|   I dH }|r|js|j I dH  |s|r|j}|r5|j|||dI dH }|s2td| |W S |j||||dI dH }|W S  tya }	 z|r\|jr\|		d |
 I dH   d}	~	ww )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)r  z server %s:%s no longer available)r  r  TransientTransactionError)r   r  _transactionr  _pinned_addressselect_server_by_addressr*   r  r2   _add_error_label_unpin)
r   r   r  r  r=  r  r  topologyr  excr   r   r   _select_server  s8   


zAsyncMongoClient._select_server$AsyncContextManager[AsyncConnection]c                   s"   |  t||I d H }| ||S r   )r  rO   r  )r   r  r  r  r   r   r   _conn_for_writes(  s   z!AsyncMongoClient._conn_for_writesrK   9AsyncGenerator[tuple[AsyncConnection, _ServerMode], None]c              	   C s   |d us	J d| j jjtjk}| ||4 I d H %}|r0|jr*|r&|js*tj	}n|j
r0tj}||fV  W d   I d H  d S 1 I d H sFw   Y  d S Nz read_preference must not be None)r   r8  r  rQ   Singler  is_replr  rJ   r  is_standaloner  )r   r   r  r  singler  r   r   r   _conn_from_server.  s   	.z"AsyncMongoClient._conn_from_server8AsyncContextManager[tuple[AsyncConnection, _ServerMode]]c                   s4   |d us	J d|  |||I d H }| |||S r  )r  r  )r   r   r  r  r  r   r   r   r  G  s   z AsyncMongoClient._conn_for_readsUnion[_Query, _GetMore]
unpack_resr   rm   c              
     s"   j rtj j j j|dI dH } j j4 I dH N t| j4 I dH -}| j j |	 j j  jj
I dH W  d  I dH  W  d  I dH  S 1 I dH sZw   Y  W d  I dH  n1 I dH sow   Y  d fdd}j| j j|t t jdI dH S )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<  N_sessionr  r  rk   r  rj   r   rK   r   rm   c                   s&       || |jI d H S r   )r  run_operationr   )r  r  r  r   r  r   r  r   r   _cmds  s   
z-AsyncMongoClient._run_operation.<locals>._cmd)r=  	retryabler  )
r  r  r  rk   r  rj   r   rK   r   rm   )rq  r  r   r  r  r   r  r  r  r  r   _retryable_readr   r@   )r   r  r  r=  r  r  r  r   r  r   _run_operationQ  s@   (zAsyncMongoClient._run_operationr  func_WriteCall[T]bulk-Optional[Union[_AsyncBulk, _AsyncClientBulk]]ro   c                   s:   t |o| jjo|o|j }| j||||||dI dH S )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().
        )r  r  r  r  r  r  N)r   r   retry_writesr  _retry_internal)r   r  r  r  r  r  r  r   r   r   _retry_with_session  s   z$AsyncMongoClient._retry_with_session_WriteCall[T] | _ReadCall[T]is_readr  c
           
        s(   t | |||||||||	d
 I dH S )a  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  r  r  r  r=  r  r  N)_ClientConnectionRetryablerun)
r   r  r  r  r  r  r=  r  r  r  r   r   r   r    s   z AsyncMongoClient._retry_internalT_ReadCall[T]c                   s@   t |o| jjo|o|j }| j||d|d||||d	I dH S )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 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)r  r=  r  r  r  )r   r   retry_readsr  r  )r   r  r  r  r  r=  r  r  r   r   r   r    s   z AsyncMongoClient._retryable_readc              	     s^   |  |4 I dH }| ||||||I dH W  d  I dH  S 1 I dH s(w   Y  dS )ak  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   r  r  r  r  r  r  r>  r   r   r   _retryable_write  s   0z!AsyncMongoClient._retryable_writerg   explicit_sessionc                 C  s2   |s|r|  ||| |r|s|  dS dS dS )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)rt  _end_implicit_sessionr   ro  r=  rq  r  r  r   r   r   _cleanup_cursor_no_lock  s
   z(AsyncMongoClient._cleanup_cursor_no_lockc                   sz   |r&|r|j r|jdusJ |jtjI dH  n| j||||dI dH  |r/| I dH  |r9|s;|  dS dS dS )a2  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  rq  )more_to_comer  
close_connrA   ERROR_close_cursor_nowr  r  r  r   r   r   _cleanup_cursor_lock-  s   
z%AsyncMongoClient._cleanup_cursor_lockc              	     s   t |tstdt| zS|rO|j4 I dH % |dus J |jdus'J | |g|||jI dH  W d  I dH  n1 I dH sDw   Y  W dS W dS | |g||  I dH |I dH  W dS  t	yr   | 
|| Y dS w )zzSend 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   r2   rt  )r   ro  r=  r  rq  r   r   r   r  O  s   
4(z"AsyncMongoClient._close_cursor_now
cursor_idsSequence[int]r  c              	     s   |r| t|tjI dH }n
|ttjI dH }| ||4 I dH }|dus+J | ||||I dH  W d  I dH  dS 1 I dH sGw   Y  dS )z/Send a kill cursors message with the given ids.N)r  rD  rI   KILL_CURSORSr  rO   r  r  )r   r  r=  r  r  r  r  r   r   r   r  j  s   .zAsyncMongoClient._kill_cursorsr>   r  rj   c           	        s>   |j }|dd\}}||d}|j|||| dI d H  d S )NrP  r   )killCursorscursors)r  r   )	namespacesplitr  )	r   r  r=  r  r  r  dbcollr  r   r   r   r  ~  s
   
z"AsyncMongoClient._kill_cursor_implc           	        sN  t t}g }	 z
| j \}}}W n	 ty   Y nw |r'||||f n|| | q|D ]2\}}}z| |||ddI dH  W q1 tyc } zt|t	rV| j
jrV t  W Y d}~q1d}~ww |r|  I dH }| D ]3\}}z| j|||ddI dH  W qq ty } zt|t	r| j
jr t  W Y d}~qqd}~ww dS dS )z*Process any pending kill cursors requests.TNF)r  )r   listr   r   
IndexErrorrs  r  	Exceptionr   r/   r   r   r<   r   r   r  )	r   address_to_cursor_idspinned_cursorsr=  ro  rq  r  r  r  r   r   r   r    sF   	z&AsyncMongoClient._process_kill_cursorsc              
     st   z|   I dH  | j I dH  W dS  ty9 } zt|tr+| jjr+W Y d}~dS t  W Y d}~dS d}~ww )zcProcess any pending kill cursors requests and
        maintain connection pool parameters.
        N)r  r   update_poolr%  r   r/   r   r<   )r   r  r   r   r   r     s   z(AsyncMongoClient._process_periodic_tasksrw  *Union[_ServerSession, _EmptyServerSession]c                 C  s   t |trdS | j|S )z.Internal: return a _ServerSession to the pool.N)r   r$   r   return_server_session)r   rw  r   r   r   _return_server_session  s   
z'AsyncMongoClient._return_server_sessionr  GAsyncGenerator[Optional[client_session.AsyncClientSession], None, None]c              
   C s   |durt |tjstdt| |V  dS | |}|r^z2z|V  W n tyD } zt |tr8|j	  |
 I dH   d}~ww W |rQ|
 I dH  dS dS |r]|
 I dH  w w dV  dS )r  Nz>'session' argument must be an AsyncClientSession or None, not )r   r   re   
ValueErrorr   r  r%  r.   _server_session
mark_dirtyend_session)r   r  r  r>  r  r   r   r   r    s4   





zAsyncMongoClient._tmp_sessionreplyMapping[str, Any]c                   s4   | j |dI d H  |d ur|| d S d S )Nr  )r   receive_cluster_timer   _process_response)r   r1  r  r   r   r   r4    s
   z"AsyncMongoClient._process_responsedict[str, Any]c                   s"   t t| jjdtj|dI dH S )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   r1  r  rJ   r  r  r   r   r   server_info  s   
zAsyncMongoClient.server_info"AsyncCommandCursor[dict[str, Any]]c                   sj   ddi}| | |d ur||d< | d}|j||tjdI d H }d|d dd	}t|d
 |d |dS )NlistDatabasesr   r,  r1  )r  r  r   	databasesz
admin.$cmd)id
firstBatchnsz$cmd)r,  )r   r  _retryable_read_commandrI   LIST_DATABASESr%   )r   r  r,  r~   cmdr1  r   cursorr   r   r   _list_databases	  s   

z AsyncMongoClient._list_databasesc                   s   | j ||fi |I dH S )a  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rB  )r   r  r,  r~   r   r   r   list_databases	  s   zAsyncMongoClient.list_databases	list[str]c                   s,   | j |d|dI dH }dd |2 I dH S )ar  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)nameOnlyr,  Nc                   s    g | z
3 d H W }|d q6 S )Nr  r   )r   docr   r   r   r   B	  s    z8AsyncMongoClient.list_database_names.<locals>.<listcomp>rC  )r   r  r,  r   r   r   r   list_database_names0	  s   z$AsyncMongoClient.list_database_namesname_or_database4Union[str, database.AsyncDatabase[_DocumentTypeArg]]c              	     s   |}t |tjr|j}t |tstdt| | j|tj	dI dH 4 I dH #}| | j
|d|dtj| |d|dI dH  W d  I dH  dS 1 I dH sRw   Y  dS )a  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   )dropDatabaser,  T)r   r   parse_write_concern_errorr  )r   r   rh  r  r   r   r   r  rI   DROP_DATABASE_commandrJ   r  _write_concern_for)r   rI  r  r,  r  r  r   r   r   drop_databaseD	  s$   "
 .zAsyncMongoClient.drop_databasemodels!Sequence[_WriteOp[_DocumentType]]orderedverbose_resultsbypass_document_validationletOptional[Mapping]rL   c	              	     s   | j jr	td|r|jr|rtd|jjj}n|s| j}|r*|js*|r*td|r5|js5|r5tdt	d| t
| ||||||d}	|D ]}
z|
|	 W qH ty`   t|
ddw |	|tjI dH S )	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 writesrQ  )r   rS  rU  r,  rV  rT  z is not a valid requestN)r   r   r/   r  r  r   r   acknowledgedr   validate_listr#   _add_to_client_bulkrd  r   executerI   
BULK_WRITE)r   rQ  r  rS  rT  rU  r,  rV  r   blkmodelr   r   r   
bulk_writey	  sD   \
	zAsyncMongoClient.bulk_write)NNNNNN)rv   rw   rx   ry   rr   rz   rs   r{   rt   r{   r|   r}   r~   r   r   r   r   r   )r   r   r   r   r   r   r   r   )r   r   r   r   r   r   )r   r   r   r   r   r   r   )r   ry   r   r   )r  r  r   r{   )r~   r   r   rp   )NNNNNNNNNNNN)r  r  r   r!  r"  r#  r$  ry   r%  ry   r&  r'  r(  r)  r  r*  r+  r#  r,  r-  r.  r!  r/  r{   r   r0  )r   rR   )r   r;  )r   r)   )r   rC  )rG  r   r   r   )r   r   )r   r   )r  r   r   ra  )ro  r   r=  rp  rq  rr  r   r   )ru  r   r~   r   r   re   )NNF)ry  r{   rz  r{  r|  r{   r   r}  )r  r  r   r  )r  r  r  r  r   r   )NNNNN)r  r!  r   r  r   r  r   r  r   r  r   ra  )r  r!  r   r  r   r  r   r  r   r  r   ra  )r  r   r   r  )r   r  )r  r   r  r   r  r   r   r   )r   r   )r  r   r   r   )r   r  )r   r  r  )r  r  r   r   )r   r'   )r  rk   r  r  r   r  )NNN)r   r  r  r  r  r   r=  r  r  r  r  ry   r   rk   )r  r  r  r   r   r  )r   rK   r  rk   r  r  r   r  )r   rK   r  r  r  r   r   r  )r  r  r  r   r=  r  r   rm   )r  r   r  r   r  r  r  r  r  r   r  ry   r   ro   )FNNFN)r  r  r  r  r  r  r  r   r  r   r=  r  r  r  r  r   r  ry   r   ro   )NTN)r  r  r  rK   r  r  r  r   r=  r  r  r   r  ry   r   ro   )NN)r  r   r  r   r  r  r  r   r  r  r  ry   r   ro   )ro  r   r=  rp  rq  rg   r  r  r  r   r   r   )
ro  r   r=  rp  r  r  rq  rr  r   r   )
r  r  r=  rp  r  r'   r  r  r   r   )
r  r  r=  r>   r  r  r  rj   r   r   )rw  r)  r   r   T)r  r*  r  r   r   r,  )r1  r2  r  r  r   r   )r  r*  r   r5  )r  r*  r,  r-  r~   r   r   r8  )r  r*  r,  r-  r   rE  )rI  rJ  r  r*  r,  r-  r   r   )NTFNNNN)rQ  rR  r  r  rS  r   rT  r   rU  r{   r,  r-  rV  rW  r   r  r   rL   )ZrS  rR  __qualname__r   r   rZ  r  WeakValueDictionaryru   __annotations__r   r   r   r   r   r   r   r  r  r  r4  propertyr:  rA  r   rF  rJ  rK  rM  r]  r`  rg  re  rn  rt  rx  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   applyr  r  r  r  r  r  r  r  r  r  r  r   r+  r  r4  r7  rB  rD  rH  rP  r_  __classcell__r   r   r   r   rp      sP  
      IE
 	$
	>;	
$&/
A,1&)4rp   r  r2   r   r#  c                 C  sN   t | ttfr| jd }|r|d S dS t | ttfr%tttt	f | jS dS )z:Return the server response from PyMongo exception or None.writeConcernErrorsN)
r   r+   r,   detailsr0   r1   r   r   r   r   )r  wcesr   r   r   _retryable_error_doc	  s   
rq  r  r   r  r   r   c                 C  s   t | }|rE|dd}|dkr t| dr d}t||| j|dkr3|dg D ]}| | q*nt| tr;|r;n
|t	j
v rE| d t| trN| j}n| }t|trct|ttfse|d d S d S d S )	Ncoder      zTransaction numberszrThis MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.	   errorLabelsRetryableWriteError)rq  r   r   r   r1   ro  r  r   r5   r   _RETRYABLE_ERROR_CODESr,   errorr.   r0   r4   )r  r  r  rG  rr  errmsglabelexc_to_checkr   r   r   _add_retryable_write_error
  s.   


r|  c                   @  sH   e Zd ZdZdZd#d	d
Zd$d%ddZd&ddZd'ddZd(d d!Z	d"S ))r  z1Handle errors raised when executing an operation.)r   server_addressr  r  sock_generationcompleted_handshake
service_idhandledr   rp   r  rk   r  r  c                 C  sx   t |tstdd t|jD stdt|j || _|jj	| _
|| _tj| _|jj | _d| _d | _d| _d S )Nc                 s  s    | ]}|j d kV  qdS )rp   N)rS  )r   clsr   r   r   r   A
  s    z4_MongoClientErrorHandler.__init__.<locals>.<genexpr>z$AsyncMongoClient required but given F)r   rp   anyr   __mro__r   rS  r   r8  r=  r}  r  r   MIN_WIRE_VERSIONr  poolgenget_overallr~  r  r  r  )r   r   r  r  r   r   r   r   <
  s   


z!_MongoClientErrorHandler.__init__Tr  rj   r  r   r   r   c                 C  s"   |j | _ |j| _|j| _|| _dS )z0Provide socket information to the error handler.N)r  
generationr~  r  r  )r   r  r  r   r   r   r  Q
  s   
z*_MongoClientErrorHandler.contribute_socketr  Optional[Type[BaseException]]r  Optional[BaseException]c                   s   | j s|d u r
d S d| _ | jrCt|tr|j}t|tr,| jjr&|d | jj	  t|t
rC|ds;|drC| j I d H  t|| j| j| j| j}| jjd usWJ | jj| j|I d H  d S )NTr  rv  )r  r  r   r,   rx  r.   r  r  r.  r/  r2   has_error_labelr  r(   r  r~  r  r  r   r   handle_errorr}  )r   r  r  err_ctxr   r   r   handleX
  s2   



z_MongoClientErrorHandler.handlec                   r  r   r   r   r   r   r   r  u
  r  z#_MongoClientErrorHandler.__aenter__Optional[Type[Exception]]Optional[Exception]r  Optional[TracebackType]c                   s   |  ||I d H S r   )r  r  r   r   r   r  x
  s   z"_MongoClientErrorHandler.__aexit__N)r   rp   r  rk   r  r  ra  )r  rj   r  r   r   r   )r  r  r  r  r   r   )r   r  )r  r  r  r  r  r  r   r   )
rS  rR  rb  __doc__	__slots__r   r  r  r  r  r   r   r   r   r  .
  s    


r  c                   @  sz   e Zd ZdZ						d.d/ddZd0ddZd1ddZd1dd Zd1d!d"Zd2d3d%d&Z	d4d(d)Z
d0d*d+Zd0d,d-ZdS )5r	  zKResponsible for executing retryable connections on read or write operationsFNr  rp   r  r  r  r  r  r   r  r   r  r  r  r  r=  r  r  r  ry   c                 C  sz   d | _ d| _t d u| _|| _|| _|| _|| _|| _	|	| _
|| _|r&|nt| _|| _d | _g | _|| _|
| _d| _d S )NFr   )_last_error	_retryingr   get_timeout_multiple_retries_client_func_bulkr  _is_read
_retryable
_read_prefrO   _server_selector_address_server_deprioritized_servers
_operation_operation_id_attempt_number)r   r  r  r  r  r  r  r  r=  r  r  r   r   r   r   
  s$   

z#_ClientConnectionRetryable.__init__r   ro   c              
     s  |   r| jr| js| j  | jrd| j_	 | jdd z| jr*|  I dH W S | 	 I dH W S  t
y=   |     ty } z| jrrt|ttfrqt|dd}|  sbt|trc|tjvrc d| _|| _|  jd7  _n | js| jsy t|tr|jrt|jto|jd}n|d}|r| jsJ | j I dH  |r|  r|dr| jr| j| |  jd7  _| jrd| j_nd| _|ds|| _| jdu r|| _| jjjtjkr| j !| j" W Y d}~nd}~ww q)zRuns the supplied func() and attempts a retry

        :raises: self._last_error: Last exception raised

        :return: Result of the func() call
        T)
check_csotNrr  r   rv  NoWritesPerformed)#_is_session_state_retryabler  r  r  _start_retryable_writer  started_retryable_write_check_last_error_read_writer3   r2   r   r.   r1   r  _is_not_eligible_for_retryr   rw  r  r  r  r,   rx  r  r  retryingr  r:  r  rQ   r  r  rs  r  )r   r  exc_coderetryable_write_error_excr   r   r   r
  
  sn   

&






z_ClientConnectionRetryable.runc                 C  s   | j  p|  o| j S )z0Checks if the exchange is not eligible for retry)r  _is_retryingr  r   r   r   r   r  
  s   z5_ClientConnectionRetryable._is_not_eligible_for_retryc                 C  s   | j r| j jS | jS )z6Checks if the exchange is currently undergoing a retry)r  r  r  r   r   r   r   r  
  s   z'_ClientConnectionRetryable._is_retryingc                 C  s*   | j r| jo	| jj S t| jo| jj S )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  r  r  r   r   r   r   r   r  
  s   z6_ClientConnectionRetryable._is_session_state_retryabler  r   c                 C  sD   |   rt }|r|dur|dkr | jdusJ | jdS dS dS )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  r  r   r   r   r    s   z,_ClientConnectionRetryable._check_last_errorrk   c                   s,   | j j| j| j| j| j| j| jdI dH S )zvRetrieves a server object based on provided object context

        :return: Abstraction to connect to server
        )r=  r  r  N)r  r  r  r  r  r  r  r  r   r   r   r   _get_server  s   z&_ClientConnectionRetryable._get_serverc              
     s  znd}d}|   I dH | _| j| j| j4 I dH G}|j}| jo)| jjjo)|j}|j	}|s6| 
  d| _| jrKttd| j | jjj| j| jd | | j|| jI dH W  d  I dH  W S 1 I dH shw   Y  W dS  ty } z| js{ t|||  d}~ww )zmWrapper method for write-type retryable client executions

        :return: Output for func()'s call
        r   FNzRetrying write attempt number messageclientIdcommandNameoperationId)r  r  r  r  r  r  r8  retryable_writes_supportedr  r  r  r  r  r;   r:   r  r   r   r  r  r  r2   r|  )r   r  r  r  sessions_supportedr  r   r   r   r    sB   
4z!_ClientConnectionRetryable._writec              	     s   |   I dH | _| jdusJ d| j| j| j| j4 I dH 9\}}| jr.| js.|   | jrCt	t
d| j | jjj| j| jd | | j| j||I dH W  d  I dH  S 1 I dH s`w   Y  dS )zlWrapper method for read-type retryable client executions

        :return: Output for func()'s call
        Nz&Read Preference required on read callszRetrying read attempt number r  )r  r  r  r  r  r  r  r  r  r;   r:   r  r   r   r  r  r  )r   r  r  r   r   r   r  D  s$    
0z _ClientConnectionRetryable._read)FNNNFN)r  rp   r  r  r  r  r  r   r  r   r  r  r  r  r=  r  r  r   r  ry   )r   ro   r  )F)r  r   r   r   )r   rk   )rS  rR  rb  r  r   r
  r  r  r  r  r  r  r  r   r   r   r   r	  
  s"    
"
L




&r	  c                  C  s&   t   tj D ]\} }|  qdS )z[Releases the locks in child process and resets the
    topologies in all MongoClients.
    N)r8   rp   ru   r   r  )rc  r   r   r   r   _after_fork_child\  s   
r  r   r   c                 C  sb   |   } dg}ddg}|D ]}| |rttd  dS q|D ]}| |r.ttd  dS qdS )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=   r9   )r   cosmos_db_hostsdocument_db_hostsrv   r   r   r   r   h  s(   

r   )after_in_child)r  r2   r   r#  )r  r2   r  r   r  r   r   r   r`  )r   r   r   r   )r  
__future__r   r  ri  osrk  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.   r/   r0   r1   r2   r3   r4   r5   pymongo.lockr6   r7   r8   pymongo.loggerr9   r:   r;   r<   r=   pymongo.messager>   r?   r@   pymongo.monitoringrA   rB   pymongo.operationsrC   rD   rE   rF   rG   rH   rI   pymongo.read_preferencesrJ   rK   pymongo.resultsrL   pymongo.server_descriptionrN   pymongo.server_selectorsrO   pymongo.server_typerP   pymongo.topology_descriptionrQ   rR   pymongo.typingsrS   rT   rU   rV   rW   rX   pymongo.uri_parser_sharedrY   rZ   r[   r\   r]   r^   r_   pymongo.write_concernr`   ra   typesrb   bson.objectidrc   pymongo.asynchronous.bulkrd   re   rf   pymongo.asynchronous.cursorrg   r   ri   pymongo.asynchronous.poolrj   pymongo.asynchronous.serverrk   pymongo.read_concernrl   pymongo.responserm   rn   ro   r   
_WriteCall	_ReadCallr   _WriteOp
BaseObjectrp   rq  r|  r  r	  r  r   register_at_forkr   r   r   r   <module>   s   P8$	 $	
                  
e
#S 
\
