
    h[                       d 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	 ddl
mZmZ ddlmZ ddlmZmZmZmZmZmZmZ ddlmZ dd	lmZ dd
lmZ 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( ddl)m*Z* ddl+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8m9Z9m:Z: ddl;m<Z<  G d dejz                        Z>d Z?d Z@ G d deA      ZBy)a  Tools for connecting to MongoDB.

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

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

.. doctest::

  >>> from pymongo import MongoClient
  >>> c = MongoClient()
  >>> c.test_database
  Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), u'test_database')
  >>> c['test-database']
  Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), u'test-database')
    N)defaultdict)DEFAULT_CODEC_OPTIONS)integer_typesstring_type)SON)commondatabasehelpersmessageperiodic_executor
uri_parserclient_session)ClusterChangeStream)ClientOptions)CommandCursor)CursorManager)	AutoReconnectBulkWriteErrorConfigurationErrorConnectionFailureInvalidOperationNotMasterErrorOperationFailurePyMongoErrorServerSelectionTimeoutError)ReadPreference)"writable_preferred_server_selectorwritable_server_selector)SERVER_TYPE)Topology_ErrorContext)TOPOLOGY_TYPE)TopologySettings)_handle_option_deprecations_handle_security_options_normalize_options)DEFAULT_WRITE_CONCERNc                       e Zd ZdZdZdZdZddedddf fd	ZdTdZ	d Z
d	 Zd
 Z	 dUdZd Z	 	 	 dVdZed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Z ed        Z!ed        Z"d  Z#d! Z$d" Z%d# Z&d$ Z'e(jR                  dTd%       Z*dWd&Z+d' Z,e(jR                  	 dTd(       Z-e(jR                  d)        Z.	 dXd*Z/d+ Z0d, Z1	 	 dYd-Z2d. Z3d/ Z4d0 Z5d1 Z6d2 Z7d3 Z8d4 Z9d5 Z:dWd6Z;d7 Z<dUd8Z=dWd9Z>d: Z?d; Z@d< ZAd= ZB	 	 dZd>ZCd? ZDd@ ZEdWdAZFe(jR                  d[dB       ZGdC ZHdD ZIdWdEZJdWdFZKdWdGZLdWdHZMdWdIZN	 	 d\dJZO	 	 d\dKZPdL ZQedM        ZRdN ZSdWdOZTdP ZUdQ ZVdR ZWdS ZXeXZY xZZS )]MongoClienta|  
    A client-side representation of a MongoDB cluster.

    Instances can represent either a standalone MongoDB server, a replica
    set, or a sharded cluster. Instances of this class are responsible for
    maintaining up-to-date state of the cluster, and possibly cache
    resources related to this, including background threads for monitoring,
    and connection pools.
    	localhostii  )document_classtz_awareconnectNc                 P	   || j                   }t        |t              r|g}|| j                  }t        |t              st        d      |j                  dd      }|j                  dd      }	|j                  dd      }
t        j                  |      |d<   t               }d}d}d}i }d}|D ]  }d|v rj                  d      }|%t        j                  j                  d      |      }t        j                  ||d	d	d
|      }|j                  |d          |d   xs |}|d   xs |}|d   xs |}|d   }|d   }|j                  t        j                   ||              |st#        d      ||d<   ||j                  dd
      }||j                  dd	      }|d<   |d<   t%              t        j                  t'        fdj)                         D                    |j                         t+        |      }t-        |      }t/        |      dkD  r|j                  d      rt#        d      |j                  d|      }|j                  d|      }d|v rt1        j2                  dt4        d       t7        ||||      x| _        }|| _        t=        j>                         | _         d| _!        g | _"        |jF                  jH                  | _%        i | _&        t=        j>                         | _'        tP        tR        |   |jV                  |jX                  |jZ                  |j\                         i | _/        |j`                  }|r| jc                  |jd                  |       tg        ||jh                  ||jF                  |	|
|jj                  |jl                  |jn                  |jp                  ||jr                        | _:        tw        | jt                        | _<        fd}t{        j|                  t        j~                  d |d!"      }t        j                  | |j                        || _C        |r| j                          d| _E        | j8                  j                  r2d#d$lGmH} |j                  | | j8                  j                        | _E        yy)%an  Client for a MongoDB instance, a replica set, or a set of mongoses.

        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
        <http://dochub.mongodb.org/core/connections>`_, in addition to
        a simple hostname. It can also be a list of hostnames or
        URIs. Any port specified in the host string(s) will override
        the `port` parameter. If multiple mongodb URIs containing
        database or auth information are passed, the last database,
        username, and password present will be used.  For username and
        passwords reserved characters like ':', '/', '+' and '@' must be
        percent encoded following RFC 2396::

            try:
                # Python 3.x
                from urllib.parse import quote_plus
            except ImportError:
                # Python 2.x
                from urllib import quote_plus

            uri = "mongodb://%s:%s@%s" % (
                quote_plus(user), quote_plus(password), host)
            client = MongoClient(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 = MongoClient(uri)

        But not when passed as a simple hostname::

            client = MongoClient('/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.rst>`_
        for more details. Note that the use of SRV URIs implicitly enables
        TLS support. Pass tls=false in the URI to override.

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

        .. note:: Starting with version 3.0 the :class:`MongoClient`
          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 = MongoClient()
            try:
                # The ismaster command is cheap and does not require auth.
                client.admin.command('ismaster')
            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.

        :Parameters:
          - `host` (optional): 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 / mongodb URIs. 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.
          - `port` (optional): port number on which to connect
          - `document_class` (optional): default class to use for
            documents returned from queries on this client
          - `type_registry` (optional): instance of
            :class:`~bson.codec_options.TypeRegistry` to enable encoding
            and decoding of custom types.
          - `tz_aware` (optional): if ``True``,
            :class:`~datetime.datetime` instances returned as values
            in a document by this :class:`MongoClient` will be timezone
            aware (otherwise they will be naive)
          - `connect` (optional): if ``True`` (the default), immediately
            begin connecting to MongoDB in the background. Otherwise connect
            on the first operation.
          - `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.

          | **Other optional parameters can be passed as keyword arguments:**

          - `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. Cannot be 0.
          - `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).
          - `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).
          - `waitQueueMultiple`: (integer or None) Multiplied by maxPoolSize
            to give the number of threads allowed to wait for a socket at one
            time. Defaults to ``None`` (no limit).
          - `heartbeatFrequencyMS`: (optional) The number of milliseconds
            between periodic server checks, or None to accept the default
            frequency of 10 seconds.
          - `appname`: (string or None) The name of the application that
            created this MongoClient instance. MongoDB 3.4 and newer will
            print this value in the server log 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 MongoClient will be retried once after a
            network error on MongoDB 3.6+. Defaults to ``True``.
            The supported write operations are:

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

            Unsupported write operations include, but are not limited to,
            :meth:`~pymongo.collection.Collection.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.rst
          - `retryReads`: (boolean) Whether supported read operations
            executed within this MongoClient will be retried once after a
            network error on MongoDB 3.6+. Defaults to ``True``.
            The supported read operations are:
            :meth:`~pymongo.collection.Collection.find`,
            :meth:`~pymongo.collection.Collection.find_one`,
            :meth:`~pymongo.collection.Collection.aggregate` without ``$out``,
            :meth:`~pymongo.collection.Collection.distinct`,
            :meth:`~pymongo.collection.Collection.count`,
            :meth:`~pymongo.collection.Collection.estimated_document_count`,
            :meth:`~pymongo.collection.Collection.count_documents`,
            :meth:`pymongo.collection.Collection.watch`,
            :meth:`~pymongo.collection.Collection.list_indexes`,
            :meth:`pymongo.database.Database.watch`,
            :meth:`~pymongo.database.Database.list_collections`,
            :meth:`pymongo.mongo_client.MongoClient.watch`,
            and :meth:`~pymongo.mongo_client.MongoClient.list_databases`.

            Unsupported read operations include, but are not limited to:
            :meth:`~pymongo.collection.Collection.map_reduce`,
            :meth:`~pymongo.collection.Collection.inline_map_reduce`,
            :meth:`~pymongo.database.Database.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.rst>`_.

          - `socketKeepAlive`: (boolean) **DEPRECATED** Whether to send
            periodic keep-alive packets on connected sockets. Defaults to
            ``True``. Disabling it is not recommended, see
            https://docs.mongodb.com/manual/faq/diagnostics/#does-tcp-keepalive-time-affect-mongodb-deployments",
          - `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.4+ supports snappy
            compression. MongoDB 3.6 adds support for zlib. MongoDB 4.2 adds
            support for zstd.
          - `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 `pythonLegacy` (the default), `javaLegacy`,
            `csharpLegacy`, `standard` and `unspecified`. New applications
            should consider setting this to `standard` for cross language
            compatibility. See :ref:`handling-uuid-data-example` for details.

          | **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`: (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`. Prior to MongoDB 2.6 this option was ignored if the server
            was running without journaling. Starting with MongoDB 2.6 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::

              MongoClient(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 uses MONGODB-CR
            when connected to a pre-3.0 version of MongoDB, SCRAM-SHA-1 when
            connected to MongoDB 3.0 through 3.6, and negotiates the mechanism
            to use (SCRAM-SHA-1 or SCRAM-SHA-256) when connected to MongoDB
            4.0+.
          - `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
            man-in-the-middle attacks.
          - `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 man-in-the-middle attacks.
          - `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. If you want to pass the certificate and private
            key as separate files, use the ``ssl_certfile`` and ``ssl_keyfile``
            options instead. Implies ``tls=True``. Defaults to ``None``.
          - `tlsCRLFile`: A file containing a PEM or DER formatted
            certificate revocation list. Only supported by python 2.7.9+
            (pypy 2.5.1+). Implies ``tls=True``. Defaults to ``None``.
          - `tlsCertificateKeyFilePassword`: The password or passphrase for
            decrypting the private key in ``tlsCertificateKeyFile`` or
            ``ssl_keyfile``. Only necessary if the private key is encrypted.
            Only supported by python 2.7.9+ (pypy 2.5.1+) and 3.3+. Defaults
            to ``None``.
          - `tlsDisableOCSPEndpointCheck`: (boolean) If ``True``, disables
            certificate revocation status checking via the OCSP responder
            specified on the server certificate. Defaults to ``False``.
          - `ssl`: (boolean) Alias for ``tls``.
          - `ssl_certfile`: The certificate file used to identify the local
            connection against mongod. Implies ``tls=True``. Defaults to
            ``None``.
          - `ssl_keyfile`: The private keyfile used to identify the local
            connection against mongod. Can be omitted if the keyfile is
            included with the ``tlsCertificateKeyFile``. Implies ``tls=True``.
            Defaults to ``None``.

          | **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.

        .. mongodoc:: connections

        .. 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.mongo_client.MongoClient` 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.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.mongo_client.MongoClient` 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.MongoClient` accepted a list of
           standalone MongoDB servers and used the first it could connect to::

               MongoClient(['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:`MongoClient.disconnect` method is removed; it was a
           synonym for :meth:`~pymongo.MongoClient.close`.

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

               client['__my_database__']

           Not::

               client.__my_database__
        Nzport must be an instance of int_pool_class_monitor_class_condition_classr+   z://connecttimeoutmsTF)validatewarn	normalizeconnect_timeoutnodelistusernamepasswordr	   optionsfqdnz!need to specify at least one hosttype_registryr,   r-   c              3   n   K   | ],  \  }}t        j                  j                  |      |       . y wN)r   r3   	cased_key).0kvkeyword_optss      W/var/www/html/ranktracker/api/venv/lib/python3.12/site-packages/pymongo/mongo_client.py	<genexpr>z'MongoClient.__init__.<locals>.<genexpr>  s9      >L.2a ?Eoo""1%q?* >Ls   25   directconnectionz8Cannot specify multiple hosts with directConnection=truesocketkeepalivezThe socketKeepAlive option is deprecated. It nowdefaults to true and disabling it is not recommended, see https://docs.mongodb.com/manual/faq/diagnostics/#does-tcp-keepalive-time-affect-mongodb-deployments   
stacklevel)seedsreplica_set_name
pool_classpool_optionsmonitor_classcondition_classlocal_threshold_msserver_selection_timeoutserver_selectorheartbeat_frequencyr;   direct_connectionc                  D            } | yt         j                  |        y)NFT)r)   _process_periodic_tasks)clientself_refs    rD   targetz$MongoClient.__init__.<locals>.target  s#    ZF~//7    g      ?pymongo_kill_cursors_thread)intervalmin_intervalr[   namer   )
_Encrypter)JHOST
isinstancer   PORTint	TypeErrorpopr   _CaseInsensitiveDictionarysetget validate_timeout_or_none_or_zeror?   r   	parse_uriupdatesplit_hostsr   r$   dictitemsr%   r&   lenwarningsr4   DeprecationWarningr   _MongoClient__options#_MongoClient__default_database_name	threadingLock_MongoClient__lock_MongoClient__cursor_manager _MongoClient__kill_cursors_queuerO   event_listeners_event_listeners_MongoClient__index_cache_MongoClient__index_cache_locksuperr)   __init__codec_optionsread_preferencewrite_concernread_concern_MongoClient__all_credentialscredentials_cache_credentialssourcer#   rM   rR   rS   rT   rU   rV   _topology_settingsr    	_topologyr   PeriodicExecutorKILL_CURSOR_FREQUENCYweakrefrefclose_kill_cursors_executor_get_topology
_encrypterauto_encryption_optspymongo.encryptionra   create)selfhostportr+   r,   r-   r<   kwargsrN   rP   rQ   rL   r8   r9   dbaseoptsr;   entitytimeoutresr:   credsr[   executorra   rC   rZ   	__class__s                            @@rD   r   zMongoClient.__init__`   s   ~ <99DdK(6D<99D$$=>> ZZt4


#3T: **%7> 88@)7%& 	CF&**+=>&$EE$../ABGMG **D4de$+- S_-z?6hz?6hJ059~6{Z33FDAB#	C$ $%HII $,9L)xx
E2H?hhy$/G#+Z ")Y 3<@88 >L6B6H6H6J>L :L M 	L!'-!$' u:>dhh'9:$JL L 88J188J1$MMF #q2 $1ht$- 	- (-$nn& $$&! ' 4 4 D D  "+.."2k4)'*?*?*1*A*A*1*?*?*1*>*>	@
 "$####ELL%8"2$55! --'+&99%,%E%E#33 ' ; ;%77#9 "$"9"9:	 %5511.	0 ;;tX^^4&.# >>..5(//dnn99;DO /r\   c                 >   | j                   j                         }||v r|||   k(  ryt        d      |rN| j                         j	                  t
              }|j                  |      5 }|j                  |       ddd       || j                   |<   y# 1 sw Y   xY w)zSave a set of authentication credentials.

        The credentials are used to login a socket whenever one is created.
        If `connect` is True, verify the credentials on the server first.
        NzNAnother user is already authenticated to this database. You must logout first.)r   copyr   r   select_serverr   
get_socketauthenticate)r   r   r   r-   all_credentialsserver	sock_infos          rD   r   zMongoClient._cache_credentials  s     00557_$of55" $N O O '')7724F
 ""?3 4y&&{34 *5v&	4 4s   )BBc                 <    | j                   j                  |d       y)z0Purge credentials from the authentication cache.N)r   rg   )r   r   s     rD   _purge_credentialszMongoClient._purge_credentials  s    ""640r\   c                     | j                   }t        j                  j                         }| j                  5  ||v xr# |||   v xr |||   |   v xr |||   |   |   k  cddd       S # 1 sw Y   yxY w)zTest if `index` is cached.N)r}   datetimeutcnowr~   )r   dbnamecollindexcachenows         rD   _cachedzMongoClient._cached  s    ""&&($$ 	6eO 5E&M)5U6]4005 %--e44		6 	6 	6s   )A**A3c                    t         j                   j                         }t        j                  |      |z   }| j                  5  || j                  vr7i | j                  |<   i | j                  |   |<   || j                  |   |   |<   nN|| j                  |   vr(i | j                  |   |<   || j                  |   |   |<   n|| j                  |   |   |<   ddd       y# 1 sw Y   yxY w)z<Add an index to the index cache for ensure_index operations.)secondsN)r   r   	timedeltar~   r}   )r   r   
collectionr   	cache_forr   expires          rD   _cache_indexzMongoClient._cache_index   s    &&(##I6<$$ 	GT///-/""6*9;""6*:6@F""6*:6u=4#5#5f#==9;""6*:6@F""6*:6u= AG""6*:6u=	G 	G 	Gs   BC!!C*c                 d   | j                   5  || j                  vr
	 ddd       y|| j                  |= 	 ddd       y|| j                  |   vr
	 ddd       y|| j                  |   |= 	 ddd       y|| j                  |   |   v r| j                  |   |   |= ddd       y# 1 sw Y   yxY w)zPurge an index from the index cache.

        If `index_name` is None purge an entire collection.

        If `collection_name` is None purge an entire database.
        N)r~   r}   )r   database_namecollection_name
index_names       rD   _purge_indexzMongoClient._purge_index2  s     $$ 	S D$6$66	S 	S &&&}5	S 	S #d&8&8&GG	S 	S !&&}5oF	S 	S T//>OO&&}5oFzR!	S 	S 	Ss!   B&B&B&B&6'B&&B/c                 l    | j                   j                  t              }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.
        )r   r   r   getattrdescription)r   	attr_namer   s      rD   _server_propertyzMongoClient._server_propertyL  s0     --$& v))955r\   c
                 >    t        | j                  |||||||||	
      S )a  Watch changes on this cluster.

        Performs an aggregation with an implicit initial ``$changeStream``
        stage and returns a
        :class:`~pymongo.change_stream.ClusterChangeStream` 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.change_stream.ClusterChangeStream` iterable
        blocks until the next change document is returned or an error is
        raised. If the
        :meth:`~pymongo.change_stream.ClusterChangeStream.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 ChangeStream 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`_.

        :Parameters:
          - `pipeline` (optional): 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.
          - `full_document` (optional): The fullDocument to pass as an option
            to the ``$changeStream`` stage. Allowed values: 'updateLookup'.
            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.
          - `resume_after` (optional): 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.
          - `max_await_time_ms` (optional): The maximum time in milliseconds
            for the server to wait for changes before responding to a getMore
            operation.
          - `batch_size` (optional): The maximum number of documents to return
            per batch.
          - `collation` (optional): The :class:`~pymongo.collation.Collation`
            to use for the aggregation.
          - `start_at_operation_time` (optional): 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.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `start_after` (optional): The same as `resume_after` except that
            `start_after` can resume notifications after an invalidate event.
            This option and `resume_after` are mutually exclusive.

        :Returns:
          A :class:`~pymongo.change_stream.ClusterChangeStream` cursor.

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

        .. versionadded:: 3.7

        .. mongodoc:: changeStreams

        .. _change streams specification:
            https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.rst
        )r   admin)
r   pipelinefull_documentresume_aftermax_await_time_ms
batch_size	collationstart_at_operation_timesessionstart_afters
             rD   watchzMongoClient.watch\  s/    n #JJ-?P	#:G 	r\   c                 .    | j                   j                  S )zmThe event listeners registered for this client.

        See :mod:`~pymongo.monitoring` for details.
        )r|   r{   r   s    rD   r{   zMongoClient.event_listeners  s     $$444r\   c                     | j                   j                  j                  }|t        j                  k(  rt        d      |t        j                  t        j                  fvry| j                  d      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
        zVCannot use "address" property when load balancing among mongoses, use "nodes" instead.Naddress)	r   _descriptiontopology_typer"   Shardedr   ReplicaSetWithPrimarySingler   )r   r   s     rD   r   zMongoClient.address  sm     33AAM111"23 3 !D!D!.!5!5!7 7$$Y//r\   c                 6    | j                   j                         S )a  The (host, port) of the current primary of the replica set.

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

        .. versionadded:: 3.0
           MongoClient gained this property in version 3.0 when
           MongoReplicaSetClient's functionality was merged in.
        )r   get_primaryr   s    rD   primaryzMongoClient.primary  s     ~~))++r\   c                 6    | j                   j                         S )a  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
           MongoClient gained this property in version 3.0 when
           MongoReplicaSetClient's functionality was merged in.
        )r   get_secondariesr   s    rD   secondarieszMongoClient.secondaries  s     ~~--//r\   c                 6    | j                   j                         S )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.
        )r   get_arbitersr   s    rD   arbiterszMongoClient.arbiters  s     ~~**,,r\   c                 $    | j                  d      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_writabler   r   s    rD   
is_primaryzMongoClient.is_primary  s     $$]33r\   c                 F    | j                  d      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_type)r   r   Mongosr   s    rD   	is_mongoszMongoClient.is_mongos	  s      $$]3{7I7IIIr\   c                 B    | j                   j                  j                  S )aQ  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. Cannot be 0.

        When a server's pool has reached `max_pool_size`, operations for that
        server block waiting for a socket to be returned to the pool. If
        ``waitQueueTimeoutMS`` is set, a blocked operation will raise
        :exc:`~pymongo.errors.ConnectionFailure` after a timeout.
        By default ``waitQueueTimeoutMS`` is not set.
        )rt   rO   max_pool_sizer   s    rD   r   zMongoClient.max_pool_size  s     ~~**888r\   c                 B    | j                   j                  j                  S )zThe minimum required number of concurrent connections that the pool
        will maintain to each connected server. Default is 0.
        )rt   rO   min_pool_sizer   s    rD   r   zMongoClient.min_pool_size   s    
 ~~**888r\   c                 R    | j                   j                  j                  }|yd|z  S )zThe maximum number of milliseconds that a connection can remain
        idle in the pool before being removed and replaced. Defaults to
        `None` (no limit).
        N  )rt   rO   max_idle_time_seconds)r   r   s     rD   max_idle_time_mszMongoClient.max_idle_time_ms'  s+     ..--CC?g~r\   c                 f    | j                   j                  }t        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:`MongoClient`'s view of the replica
          set changes. :attr:`nodes` can also be an empty set when
          :class:`MongoClient` is first instantiated and hasn't yet connected
          to any servers, or a network partition causes it to lose connection
          to all servers.
        c              3   4   K   | ]  }|j                     y wr>   r   )r@   ss     rD   rE   z$MongoClient.nodes.<locals>.<genexpr>>  s     FqFs   )r   r   	frozensetknown_servers)r   r   s     rD   nodeszMongoClient.nodes2  s*     nn00FK,E,EFFFr\   c                 $    | j                  d      S )zThe largest BSON object the connected server accepts in bytes.

        If the client is not connected, this will block until a connection is
        established or raise ServerSelectionTimeoutError if no server is
        available.
        max_bson_sizer   r   s    rD   r   zMongoClient.max_bson_size@  s     $$_55r\   c                 $    | j                  d      S )zThe largest message the connected server accepts in bytes.

        If the client is not connected, this will block until a connection is
        established or raise ServerSelectionTimeoutError if no server is
        available.
        max_message_sizer   r   s    rD   r   zMongoClient.max_message_sizeJ  s     $$%788r\   c                 $    | j                  d      S )aB  The maxWriteBatchSize reported by the server.

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

        Returns a default value when connected to server versions prior to
        MongoDB 2.6.
        max_write_batch_sizer   r   s    rD   r   z MongoClient.max_write_batch_sizeT  s     $$%;<<r\   c                 .    | j                   j                  S )z&The local threshold for this instance.)rt   rR   r   s    rD   rR   zMongoClient.local_threshold_msa  s     ~~000r\   c                 .    | j                   j                  S )z:The server selection timeout for this instance in seconds.)rt   rS   r   s    rD   rS   z$MongoClient.server_selection_timeoutf  s     ~~666r\   c                 .    | j                   j                  S z9If this instance should retry supported write operations.)rt   retry_writesr   s    rD   r  zMongoClient.retry_writesk  s     ~~***r\   c                 .    | j                   j                  S r  )rt   retry_readsr   s    rD   r  zMongoClient.retry_readsp  s     ~~)))r\   c                     | j                         }	 |j                  t              }|j                  j                  S # t
        $ r Y yw xY w)zBAttempt to connect to a writable server, or return False.
        F)r   r   r   r   r   r   )r   topologysvrs      rD   _is_writablezMongoClient._is_writableu  sL     %%'	(()ABC
 ??...  		s   *= 	A	A	c           	         	 | j                  t        j                  d      5 \  }}|j                  s
	 ddd       yt	        dt        |      t        j                        D ]9  }t        d|||t        j                  z    fg      }|j                  d|||        ; 	 ddd       y# 1 sw Y   yxY w# t        $ r Y yw xY w)z7Send endSessions command(s) with the given session ids.Nr   endSessionsr   )slave_okrY   )_socket_for_readsr   PRIMARY_PREFERREDsupports_sessionsrangerq   r   _MAX_END_SESSIONSr   commandr   )r   session_idsr   r  ispecs         rD   _end_sessionszMongoClient._end_sessions  s    	 ''"44 
G2i 22	
G 
G q#k"2F4L4LM GA!,Qq63K3K/K!L!N  O PD%% & GG
G 
G 
G  	 	s9    B2 B&B2 A B&B2 &B/+B2 /B2 2	B>=B>c                 4   | j                   j                         }|r| j                  |       | j                  j	                          | j                          | j                   j	                          | j                  r| j                  j	                          yy)a  Cleanup client resources and disconnect from MongoDB.

        On MongoDB >= 3.6, 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.
        If this instance is used again it will be automatically re-opened and
        the threads restarted unless auto encryption is enabled. A client
        enabled with auto encryption cannot be used again after being closed;
        any attempt will raise :exc:`~.errors.InvalidOperation`.

        .. versionchanged:: 3.6
           End all server sessions created by this client.
        N)r   pop_all_sessionsr  r   r   _process_kill_cursorsr   )r   r  s     rD   r   zMongoClient.close  ss     nn557{+ 	##))+""$??OO!!# r\   c                     t        j                  dt        d        ||       }t        |t              st        d      || _        y)a@  DEPRECATED - Set this client's cursor manager.

        Raises :class:`TypeError` if `manager_class` is not a subclass of
        :class:`~pymongo.cursor_manager.CursorManager`. A cursor manager
        handles closing cursors. Different managers can implement different
        policies in terms of when to actually kill a cursor that has
        been closed.

        :Parameters:
          - `manager_class`: cursor manager to use

        .. versionchanged:: 3.3
           Deprecated, for real this time.

        .. versionchanged:: 3.0
           Undeprecated.
        z set_cursor_manager is DeprecatedrI   rJ   z1manager_class must be a subclass of CursorManagerN)rr   r4   rs   rc   r   rf   ry   )r   manager_classmanagers      rD   set_cursor_managerzMongoClient.set_cursor_manager  sK    $ 	.	  %'=1 , - - !(r\   c                     | j                   j                          | j                  5  | j                  j                          ddd       | j                   S # 1 sw Y   | j                   S xY w)zGet the internal :class:`~pymongo.topology.Topology` object.

        If this client was created with "connect=False", calling _get_topology
        launches the connection process in the background.
        N)r   openrx   r   r   s    rD   r   zMongoClient._get_topology  sQ     	[[ 	/'',,.	/~~	/~~s   AA*c              #   V  K   t        | ||      5 }|j                  | j                  |      5 }|j                  |       | j                  r0| j                  j
                  s|j                  dk  rt        d      | d d d        d d d        y # 1 sw Y   xY w# 1 sw Y   y xY ww)N)checkout   z9Auto-encryption requires a minimum MongoDB version of 4.2)_MongoClientErrorHandlerr   r   contribute_socketr   _bypass_auto_encryptionmax_wire_versionr   )r   r   r   exhausterr_handlerr   s         rD   _get_socketzMongoClient._get_socket  s     %dFG< 
	 ""**W # > 	 AJ--i8OO OOCC!22Q6,!" "  	 
	  
	 	  	 
	  
	 s4   B)BAB B	B)B	BB&"B)c                    	 | j                         }|xs |xr |j                  }|r#|j                  |      }|st        d|z        |S |j	                  |      }|j
                  j                  r|r|j                  r|j                  |       |S # t        $ r5}|r-|j                  r!|j                  d       |j                           d}~ww xY 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 ClientSession 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.
        z server %s:%d no longer availableTransientTransactionErrorN)r   _pinned_addressselect_server_by_addressr   r   r   mongosin_transaction_pin_mongosr   _add_error_label_unpin_mongos)r   rT   r   r   r	  r   excs          rD   _select_serverzMongoClient._select_server  s    	))+HF'"Eg.E.EG!::7C'(J*1)2 3 3 M "//@ %%,,'292H2H''/M 	711$$%@A%%'	s   AB AB 	C0CCc                 R    | j                  t        |      }| j                  ||      S r>   )r6  r   r+  )r   r   r   s      rD   _socket_for_writeszMongoClient._socket_for_writes  s(    $$%=wG00r\   c              #   6  K   |J d       | j                         }|j                  j                  t        j                  k(  }| j                  |||      5 }|xr |j                   xs |t        j                  k7  }||f d d d        y # 1 sw Y   y xY ww)N read_preference must not be Noner)  )	r   r   r   r"   r   r+  r   r   PRIMARY)	r   r   r   r   r)  r	  singler   r  s	            rD   _slaveok_for_serverzMongoClient._slaveok_for_server  s      *N,NN* %%'%%33}7K7KKfgw? 	&9:y':':#: ;>#9#99 X%%	& 	& 	&s   AB-B	BBBc              #   V  K   |J d       | j                         }|j                  j                  t        j                  k(  }| j                  ||      }| j                  ||      5 }|xr |j                   xs |t        j                  k7  }||f d d d        y # 1 sw Y   y xY ww)Nr:  )
r   r   r   r"   r   r6  r+  r   r   r<  )r   r   r   r	  r=  r   r   r  s           rD   r  zMongoClient._socket_for_reads"  s     *N,NN* %%'%%33}7K7KK$$_g>fg. 	&):y':':#: ;>#9#99 X%%	& 	& 	&s   A%B)'-B	B)B&"B)c           
          j                   r j                  j                  j                  |      }t	         |j                        5 }|j                  j                   j                         |j                  j                   j                  d j                        cddd       S  fd} j                  |j                  j                  |t        t        j                              S # 1 sw Y   TxY w)a  Run a _Query/_GetMore operation and return a Response.

        :Parameters:
          - `operation`: a _Query or _GetMore object.
          - `unpack_res`: A callable that decodes the wire protocol response.
          - `exhaust` (optional): If True, the socket used stays checked out.
            It is returned along with its Pool in the Response.
          - `address` (optional): Optional address when sending a message
            to a specific server, used for getMore.
        r   TNc                 D    |j                  ||j                        S r>   )run_operation_with_responser|   )r   r   r   r  r)  	operationr   
unpack_ress       rD   _cmdz6MongoClient._run_operation_with_response.<locals>._cmdO  s.    55%% r\   )r   	retryabler)  )exhaust_mgrr6  r   r   r%  r&  sockrB  r|   _retryable_readrc   r   _Query)r   rC  rD  r)  r   r   r*  rE  s   ````    rD   _run_operation_with_responsez(MongoClient._run_operation_with_response4  s       (())9+<+<g ) OF *&)"3"35 	 8C--i.C.C.H.HI99))..)) 	  	 	 ##)++Y->-> GNN;	 $  	)	  	 s   AC>>Dc                 p    |xr | j                   xr |xr |j                   }| j                  ||||      S )Execute an operation with at most one consecutive retries

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

        Re-raises any exception thrown by func().
        )r  r1  _retry_internal)r   rF  funcr   bulks        rD   _retry_with_sessionzMongoClient._retry_with_session^  sL      @4#4#4 @ @)0)?)?%? 	##ItWdCCr\   c                 Z   d}d}dfd}|r'|r%|j                   s|j                          rd_        	 	 | j                  t        |      }|duxr |j
                  j                  }	| j                  ||      5 }
|
j                  }|r|	s |       r|d} |||
|      cddd       S # 1 sw Y   nxY wnr# t        $ r  |       r| t        $ rT}|s t        ||       |j                  d      }|r|j                           |       s|s rd_        nd|}Y d}~nd}~ww xY w) Internal retryable write helper.r   NFc                  $     r j                   S S r>   )retrying)rP  rU  s   rD   is_retryingz0MongoClient._retry_internal.<locals>.is_retryingp  s    $(4==6h6r\   TRetryableWriteError)r1  _start_retryable_writestarted_retryable_writer6  r   r   retryable_writes_supportedr+  r(  r   r   _add_retryable_write_errorhas_error_labelr4  rU  )r   rF  rO  r   rP  r(  
last_errorrV  r   supports_sessionr   r5  retryable_errorrU  s       `        @rD   rN  zMongoClient._retry_internalj  sY   
	7
 )?)?**,/3,&!,,-EwO4' B&&AA ! %%fg6 ?)'0'A'A$ )9&= #-,$)	I>? ? ? ? / 	= %$  ! *30@A"%"5"56K"L"))+=$(DM#H 
!3 s1   AB: >%B-#	B: -B62B: :D)A
D$$D)c                    |xr | j                   xr |xr |j                   }d}d}	 	 | j                  |||      }	|	j                  j                  sd}| j                  ||	||      5 \  }
}|r|s| |||	|
|      cddd       S # 1 sw Y   nxY wnc# t        $ r |r| t        $ r}|r|r d}|}Y d}~n?d}~wt        $ r0}|r|r |j                  t        j                  vr d}|}Y d}~nd}~ww xY w)rM  NFTr   r;  )r  r1  r6  r   retryable_reads_supportedr>  r   r   r   coder
   _RETRYABLE_ERROR_CODES)r   rO  	read_prefr   r   rF  r)  r]  rU  r   r   r  r5  s                rD   rI  zMongoClient._retryable_read  sI     B%%B%@'*@*@A 	 
"!,,w - 9))CC %I--i6= . ? FCM9CK	 )(HEF F F F / 	 %$ $ ! H 
# ! H887#A#AA 
!; s<   AB +B	?	B 	BB C6,	B::C6&C11C6c                 x    | j                  |      5 }| j                  |||d      cddd       S # 1 sw Y   yxY w)rS  N)_tmp_sessionrQ  )r   rF  rO  r   r   s        rD   _retryable_writezMongoClient._retryable_write  s?    w' 	F1++ItQE	F 	F 	Fs   09c                 <    | j                   j                  ||       y)z@Clear our pool for a server, mark it Unknown, and check it soon.N)r   handle_getlasterror)r   r   	error_msgs      rD   _handle_getlasterrorz MongoClient._handle_getlasterror  s    **7I>r\   c                 l    t        || j                        r| j                  |j                  k(  S t        S r>   )rc   r   r   NotImplementedr   others     rD   __eq__zMongoClient.__eq__  s)    eT^^,<<5==00r\   c                     | |k(   S r>    rn  s     rD   __ne__zMongoClient.__ne__  s    5=  r\   c                 N    d d j                   j                  D cg c]  \  }}|d||fz  n| c}}z  g}|j                   fd j                  D               |j                   fd j                  j
                  D               dj                  |      S c c}}w )Nc                     | dk(  r%|t         u ryd|j                  d|j                  S | t        j                  v r|| dt        |dz        S | d|S )z9Fix options whose __repr__ isn't usable in a constructor.r+   zdocument_class=dictzdocument_class=.=r   )ro   
__module____name__r   TIMEOUT_OPTIONSre   )optionvalues     rD   option_reprz-MongoClient._repr_helper.<locals>.option_repr  sj    ))D=0 ! 6;5E5E5:^^E E///E4E"(#edl*;<<$e,,r\   zhost=%rz%s:%dc              3   ^   K   | ]$  } |j                   j                  |          & y wr>   )rt   _optionsr@   keyr}  r   s     rD   rE   z+MongoClient._repr_helper.<locals>.<genexpr>  s/      / T^^44S9:/s   *-c              3      K   | ]E  }|t        j                        vr,|d k7  r'|dk7  r" |j                  j                  |          G yw)r8   r9   N)ri   _constructor_argsrt   r  r  s     rD   rE   z+MongoClient._repr_helper.<locals>.<genexpr>  sQ      9#d4455z!cZ&7 T^^44S9:9s   AAz, )r   rL   extendr  rt   r  join)r   r   r   r:   r}  s   `   @rD   _repr_helperzMongoClient._repr_helper  s    	- "55;; =d '+&6GtTl"D@ = = > 	 /--/ 	/ 	 9~~..9 	9
 yy!! =s   B!c                 *    d| j                         dS )NzMongoClient())r  r   s    rD   __repr__zMongoClient.__repr__  s    %)%6%6%8:;r\   c           	      p    |j                  d      rt        d|d|d|d      | j                  |      S )Get a database by name.

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

        :Parameters:
          - `name`: the name of the database to get
        _zMongoClient has no attribute z. To access the z database, use client[z].)
startswithAttributeError__getitem__r   r`   s     rD   __getattr__zMongoClient.__getattr__	  s?     ??3 04dDBC C %%r\   c                 .    t        j                  | |      S )r  )r	   Databaser  s     rD   r  zMongoClient.__getitem__  s       t,,r\   c                     t        j                  dt        d       t        |t              st        d      | j                  ||       y)a  DEPRECATED - Send a kill cursors message soon with the given id.

        Raises :class:`TypeError` if `cursor_id` is not an instance of
        ``(int, long)``. What closing the cursor actually means
        depends on this client's cursor manager.

        This method may be called from a :class:`~pymongo.cursor.Cursor`
        destructor during garbage collection, so it isn't safe to take a
        lock or do network I/O. Instead, we schedule the cursor to be closed
        soon on a background thread.

        :Parameters:
          - `cursor_id`: id of cursor to close
          - `address` (optional): (host, port) pair of the cursor's server.
            If it is not provided, the client attempts to close the cursor on
            the primary or standalone, or a mongos server.

        .. versionchanged:: 3.7
           Deprecated.

        .. versionchanged:: 3.0
           Added ``address`` parameter.
        zclose_cursor is deprecated.rI   rJ   ,cursor_id must be an instance of (int, long)N)rr   r4   rs   rc   r   rf   _close_cursorr   	cursor_idr   s      rD   close_cursorzMongoClient.close_cursor#  sA    0 	)	 )]3JKK9g.r\   c                     | j                   | j                   j                  ||       y| j                  j                  ||gf       y)zSend a kill cursors message with the given id.

        What closing the cursor actually means depends on this client's
        cursor manager. If there is none, the cursor is closed asynchronously
        on a background thread.
        N)ry   r   rz   appendr  s      rD   r  zMongoClient._close_cursorD  sA       ,!!''	7;%%,,g	{-CDr\   c                 .   t        |t              st        d      | j                  | j                  j	                  ||       y	 | j                  |g|| j                         |       y# t        $ r! | j                  j                  ||gf       Y yw xY w)zSend a kill cursors message with the given id.

        What closing the cursor actually means depends on this client's
        cursor manager. If there is none, the cursor is closed synchronously
        on the current thread.
        r  N)
rc   r   rf   ry   r   _kill_cursorsr   r   rz   r  )r   r  r   r   s       rD   _close_cursor_nowzMongoClient._close_cursor_nowP  s     )]3JKK  ,!!''	7;I""K$*<*<*>I I))00'I;1GHIs   #A* *'BBc                     t        j                  dt        d       t        |t              st        d      | j                  j                  ||f       y)a  DEPRECATED - Send a kill cursors message soon with the given ids.

        Raises :class:`TypeError` if `cursor_ids` is not an instance of
        ``list``.

        :Parameters:
          - `cursor_ids`: list of cursor ids to kill
          - `address` (optional): (host, port) pair of the cursor's server.
            If it is not provided, the client attempts to close the cursor on
            the primary or standalone, or a mongos server.

        .. versionchanged:: 3.3
           Deprecated.

        .. versionchanged:: 3.0
           Now accepts an `address` argument. Schedules the cursors to be
           closed on a background thread instead of sending the message
           immediately.
        zkill_cursors is deprecated.rI   rJ   zcursor_ids must be a listN)rr   r4   rs   rc   listrf   rz   r  )r   
cursor_idsr   s      rD   kill_cursorszMongoClient.kill_cursorsd  sL    ( 	)	
 *d+788 	!!((':)>?r\   c                    | j                   }|j                  }|r|j                  t        |            }n|j	                  t
              }	 |j                  }|j                  dd      \  }	}
t        d|
fd|fg      }|j                  | j                        5 }|j                  dk\  r||j                  |	|||        n|rt        j                  j                         }t!        j"                  |      \  }}|r\t        j                  j                         z
  }|j%                  ||	|t        |             t        j                  j                         }	 |j'                  |d	       |rGt        j                  j                         z
  z   }|dd
}|j/                  ||d|t        |             ddd       y# t        $ r
 d}dx}	}
Y aw xY w# t(        $ r]}|rUt        j                  j                         z
  z   }|j+                  |t!        j,                  |      d|t        |              d}~ww xY w# 1 sw Y   yxY w)z/Send a kill cursors message with the given ids.rv  rF   NOP_KILL_CURSORSkillCursorscursors   r   rY   r   )cursorsUnknownok)r|   enabled_for_commandsr/  tupler   r   	namespacesplitr  r   r   r   r(  r  r   r   r   r  publish_command_startsend_message	Exceptionpublish_command_failure_convert_exceptionpublish_command_success)r   r  r   r	  r   	listenerspublishr   r  dbr   r  r   start
request_idmsgdurationr5  durreplys                       rD   r  zMongoClient._kill_cursors  s7   ))	00 66uW~FF ++,DEF	*))I sA.HB
 ]D)Iz+BCDt556 "	()))Q.93H!!"dGD!I$--113E")"6"6z"B
C'00446>H
 33b*eGn>$--113E	**32 !)!2!2!6!6!85!@H LH/9CE55 %
g(A"	( "	(  	*I))B	*0 !  ( 1 1 5 5 7% ?8K!99!;!;C!@):!'N, '"	( "	(sE   !F< B>H;G*A	H;<GG	H8AH33H88H;;Ic                 p   t        t              }	 	 | j                  j                         \  }}||   j                  |       3# t        $ r Y nw xY w|rb| j                         }|j                         D ]>  \  }}	 | j                  |||d       # t        $ r t        j                          Y <w xY w yy)z*Process any pending kill cursors requests.Nr   )r   r  rz   rg   
IndexErrorr  r   rp   r  r  r
   _handle_exception)r   address_to_cursor_idsr   r  r	  s        rD   r  z!MongoClient._process_kill_cursors  s     +D 1 &*&?&?&C&C&E# "'*11*=    !))+H'<'B'B'D 0#0&&"GXt ' E  0--/0	0 !s#   A 	AA<BB21B2c                     | j                          	 | j                  j                  | j                         y# t        $ r t        j                          Y yw xY w)zZProcess any pending kill cursors requests and
        maintain connection pool parameters.N)r  r   update_poolr   r  r
   r  r   s    rD   rX   z#MongoClient._process_periodic_tasks  sH     	""$	(NN&&t'='=> 	(%%'	(s   %8 AAc                     t        | j                  j                               }t        |      dkD  rt	        d      | j                         }t        j                  di |}t        j                  | ||||      S )NrF   z?Cannot call start_session when multiple users are authenticatedrr  )	ri   r   valuesrq   r   _get_server_sessionr   SessionOptionsClientSession)r   implicitr   authsetserver_sessionr   s         rD   __start_sessionzMongoClient.__start_session  s     d,,3356w<!" $G H H 113,,6v6++.$; 	;r\   c                 *    | j                  d||      S )a  Start a logical session.

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

        Requires MongoDB 3.6. It is an error to call :meth:`start_session`
        if this client has been authenticated to multiple databases using the
        deprecated method :meth:`~pymongo.database.Database.authenticate`.

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

        :Returns:
          An instance of :class:`~pymongo.client_session.ClientSession`.

        .. versionadded:: 3.6
        F)causal_consistencydefault_transaction_options)_MongoClient__start_session)r   r  r  s      rD   start_sessionzMongoClient.start_session  s'    0 ##1(C $ E 	Er\   c                 6    | j                   j                         S )z+Internal: start or resume a _ServerSession.)r   get_server_sessionr   s    rD   r  zMongoClient._get_server_session  s    ~~0022r\   c                 :    | j                   j                  ||      S )z.Internal: return a _ServerSession to the pool.)r   return_server_session)r   r  locks      rD   _return_server_sessionz"MongoClient._return_server_session  s    ~~33NDIIr\   c                 \    |r|S 	 | j                  dd      S # t        t        f$ r Y yw xY w)6If provided session is None, lend a temporary session.TF)r  N)r  r   r   r   r   s     rD   _ensure_sessionzMongoClient._ensure_session  s?    N	 '''GG"$45 		s    ++c              #   D  K   |r| y| j                  |      }|r	 | 	 |r|j                          yyd y# t        $ r@}t        |t              r|j                  j                          |j                           d}~ww xY w# |r|j                          w w xY ww)r  N)r  r  rc   r   _server_session
mark_dirtyend_session)r   r   r   r   r5  s        rD   rf  zMongoClient._tmp_session  s      M  )$ MMO  J  c#45%%002  MMO s1   B < B 	B;B  BB BB c                     | j                   j                         }|r|j                  nd }|r|r|d   |d   kD  r|}n	|}n|xs |}|r||d<   y y )NclusterTime$clusterTime)r   max_cluster_timecluster_time)r   r  r   topology_timesession_timer  s         rD   _send_cluster_timezMongoClient._send_cluster_time7  s`    779/6w++D\]+l=.II,+(8LL&2GN# r\   c                     | j                   j                  |j                  d             ||j                  |       y y )Nr  )r   receive_cluster_timerj   _process_response)r   r  r   s      rD   r  zMongoClient._process_responseD  s6    ++EIIn,EF%%e, r\   c                 Z    | j                   j                  dt        j                  |      S )a  Get information about the MongoDB server we're connected to.

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        	buildinfo)r   r   )r   r  r   r<  r  s     rD   server_infozMongoClient.server_infoI  s.     zz!!+2@2H2H*1 " 3 	3r\   c                     t        dg      }|j                  |       | j                  d      }|j                  ||      }d|d   dd}t	        |d   |d	      S )
a_  Get a cursor over the databases of the connected server.

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): Optional parameters of the
            `listDatabases command
            <https://docs.mongodb.com/manual/reference/command/listDatabases/>`_
            can be passed as keyword arguments to this method. The supported
            options differ by server version.

        :Returns:
          An instance of :class:`~pymongo.command_cursor.CommandCursor`.

        .. versionadded:: 3.6
        )listDatabasesrF   r   r  r   	databasesz
admin.$cmd)id
firstBatchnsz$cmdN)r   rm   _database_default_options_retryable_read_commandr   )r   r   r   cmdr   r   cursors          rD   list_databaseszMongoClient.list_databasesW  so    " '()

6..w7++C+A k*

 U6]FD99r\   c                 T    | j                  |d      D cg c]  }|d   	 c}S c c}w )zGet a list of the names of all databases on the connected server.

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        .. versionadded:: 3.6
        T)nameOnlyr`   )r  )r   r   docs      rD   list_database_nameszMongoClient.list_database_namest  s<      ..w.FH F H 	H Hs   %c                 \    t        j                  dt        d       | j                  |      S )a  **DEPRECATED**: Get a list of the names of all databases on the
        connected server.

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        .. versionchanged:: 3.7
           Deprecated. Use :meth:`list_database_names` instead.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        z>database_names is deprecated. Use list_database_names instead.rI   rJ   )rr   r4   rs   r  r  s     rD   database_nameszMongoClient.database_names  s,     	 !"4	D''00r\   c           	         |}t        |t        j                        r|j                  }t        |t              st        dt        j                  d      | j                  |       | j                  |      5 }| |   j                  |dt        j                  | j                  |      d|       ddd       y# 1 sw Y   yxY w)a  Drop a database.

        Raises :class:`TypeError` if `name_or_database` is not an instance of
        :class:`basestring` (:class:`str` in python 3) or
        :class:`~pymongo.database.Database`.

        :Parameters:
          - `name_or_database`: the name of a database to drop, or a
            :class:`~pymongo.database.Database` instance representing the
            database to drop
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

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

        .. note:: The :attr:`~pymongo.mongo_client.MongoClient.write_concern` of
           this client is automatically applied to this operation when using
           MongoDB >= 3.4.

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

        z(name_or_database must be an instance of z or a DatabasedropDatabaseT)r   r   parse_write_concern_errorr   N)rc   r	   r  r`   r   rf   ry  r   r8  _commandr   r<  _write_concern_for)r   name_or_databaser   r`   r   s        rD   drop_databasezMongoClient.drop_database  s    4  dH--.99D$,5@5I5IL M M 	$$$W- 	!J . 6 6"55g>*.   !	! 	! 	!s   88B99Cc                     | j                   |t        d      t        j                  | | j                   xs |||||      S )a  Get the database named in the MongoDB connection URI.

        >>> uri = 'mongodb://host/my_database'
        >>> client = MongoClient(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.

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

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

        .. versionchanged:: 3.5
           Deprecated, use :meth:`get_database` instead.
        z-No default database name defined or provided.ru   r   r	   r  )r   defaultr   r   r   r   s         rD   get_default_databasez MongoClient.get_default_database  sU    T ''/GO$?A A   $..9'=]L: 	:r\   c                     |#| j                   t        d      | j                   }t        j                  | |||||      S )a  Get a :class:`~pymongo.database.Database` with the given name and
        options.

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

          >>> 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)

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

        .. versionchanged:: 3.5
           The `name` parameter is now optional, defaulting to the database
           named in the MongoDB connection URI.
        zNo default database definedr  )r   r`   r   r   r   r   s         rD   get_databasezMongoClient.get_database  sN    Z <++3()FGG//D  $<) 	)r\   c                 X    | j                  |t        t        j                  t              S )z2Get a Database instance with the default settings.)r   r   r   )r  r   r   r<  r'   r  s     rD   r  z%MongoClient._database_default_options&  s,       5*22/ ! 1 	1r\   c                     t        j                  dt        d       | j                  d      j	                         }t        |j                  dd            S )a  **DEPRECATED**: Is this server locked? While locked, all write
        operations are blocked, although read operations may still be allowed.
        Use :meth:`unlock` to unlock.

        Deprecated. Users of MongoDB version 3.2 or newer can run the
        `currentOp command`_ directly with
        :meth:`~pymongo.database.Database.command`::

            is_locked = client.admin.command('currentOp').get('fsyncLock')

        Users of MongoDB version 2.6 and 3.0 can query the "inprog" virtual
        collection::

            is_locked = client.admin["$cmd.sys.inprog"].find_one().get('fsyncLock')

        .. versionchanged:: 3.11
           Deprecated.

        .. _currentOp command: https://docs.mongodb.com/manual/reference/command/currentOp/
        zDis_locked is deprecated. See the documentation for more information.rI   rJ   r   	fsyncLockr   )rr   r4   rs   r  _current_opboolrj   )r   opss     rD   	is_lockedzMongoClient.is_locked-  sJ    , 	 *+=!	M,,W5AACCGGK+,,r\   c                     t        j                  dt        d        | j                  j                  ddt
        j                  i| y)a  **DEPRECATED**: Flush all pending writes to datafiles.

        Optional parameters can be passed as keyword arguments:
          - `lock`: If True lock the server to disallow writes.
          - `async`: If True don't block while synchronizing.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        .. note:: Starting with Python 3.7 `async` is a reserved keyword.
          The async option to the fsync command can be passed using a
          dictionary instead::

            options = {'async': True}
            client.fsync(**options)

        Deprecated. Run the `fsync command`_ directly with
        :meth:`~pymongo.database.Database.command` instead. For example::

            client.admin.command('fsync', lock=True)

        .. versionchanged:: 3.11
           Deprecated.

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

        .. warning:: `async` and `lock` can not be used together.

        .. warning:: MongoDB does not support the `async` option
                     on Windows and will raise an exception on that
                     platform.

        .. _fsync command: https://docs.mongodb.com/manual/reference/command/fsync/
        z?fsync is deprecated. Use client.admin.command('fsync') instead.rI   rJ   r   N)fsync)rr   r4   rs   r   r  r   r<  )r   r   s     rD   r  zMongoClient.fsyncH  sJ    F 	 ?(Q	8 	

 	M+9+A+A	MEK	Mr\   c                    t        j                  dt        d       t        dg      }| j	                  |      5 }|j
                  dk\  r1	 | j                  |      5 }|j                  d|||        ddd       n@t        j                  |dd
i dd| j                  t        j                  || j                  
       ddd       y# 1 sw Y   SxY w# t        $ r}|j                  d	k7  r Y d}~3d}~ww xY w# 1 sw Y   yxY w)a	  **DEPRECATED**: Unlock a previously locked server.

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        Deprecated. Users of MongoDB version 3.2 or newer can run the
        `fsyncUnlock command`_ directly with
        :meth:`~pymongo.database.Database.command`::

             client.admin.command('fsyncUnlock')

        Users of MongoDB version 2.6 and 3.0 can query the "unlock" virtual
        collection::

            client.admin["$cmd.sys.unlock"].find_one()

        .. versionchanged:: 3.11
           Deprecated.

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

        .. _fsyncUnlock command: https://docs.mongodb.com/manual/reference/command/fsyncUnlock/
        zunlock is deprecated. Use client.admin.command('fsyncUnlock') instead. For MongoDB 2.6 and 3.0, see the documentation for more information.rI   rJ   )fsyncUnlockrF   r  r   r  N}   z$cmd.sys.unlockT)rr   r4   rs   r   r8  r(  rf  r  r   rb  r   _first_batchr   r   r<  r|   )r   r   r  r   r   r5  s         rD   unlockzMongoClient.unlockq  s   4 	 * )Q		8
 %&'$$W- 	<))Q.**73 Bq!))#S!D * BB $$Y9J%'T43E3E%3%;%;S%)%:%:<	< 	<B B ( xx3 '	< 	<sN   C6CC2C:AC6C		C	C3C.)C6.C33C66C?c                     | S r>   rr  r   s    rD   	__enter__zMongoClient.__enter__      r\   c                 $    | j                          y r>   )r   )r   exc_typeexc_valexc_tbs       rD   __exit__zMongoClient.__exit__  s    

r\   c                     | S r>   rr  r   s    rD   __iter__zMongoClient.__iter__  r  r\   c                     t        d      )Nz$'MongoClient' object is not iterable)rf   r   s    rD   __next__zMongoClient.__next__  s    >??r\   )F)NN)	NNNNNNNNNr>   )FN)NTF)TN)T)NNNNN)[ry  rx  __qualname____doc__rb   rd   r  ro   r   r   r   r   r   r   r   r   propertyr{   r   r   r   r   r   r   r   r   r   r   r   r   r   rR   rS   r  r  r  r  r   r  r   
contextlibcontextmanagerr+  r6  r8  r>  r  rK  rQ  rN  rI  rg  rk  rp  rs  r  r  r  r  r  r  r  r  r  r  rX   r  r  r  r  r  rf  r  r  r  r  r  r  r  r
  r  r  r  r  r  r  r#  r%  r'  next__classcell__)r   s   @rD   r)   r)   P   s    DD B T
;l5816G& 7;S46  EIAEFJZx 5 5 0 0. , , 0 0 - - 4 4 J J 9 9 9 9   G G 6 6 9 9 
= 
= 1 1 7 7 + + * **$6(:	    !F1 $)& &" & &$ =A(T
D7!r AE052!hF
?
!"<<&	-/B
EI(@>6(p00(;  *.26E:3J  23-
3::
H1$*!X @DCG0:d KO6:4)l1 - -4'MR.<`@ Dr\   r)   c                     t        | t              r| j                  d   }|r|d   }|S d}|S t        | t        t        f      r| j                  S y)z:Return the server response from PyMongo exception or None.writeConcernErrorsr  N)rc   r   detailsr   r   )r5  wceswces      rD   _retryable_error_docr4    sV    #~& {{/0d2h
 %)
#(89:{{r\   c                    t        |       }|r|j                  dd      }|dk(  r3t        |       j                  d      rd}t	        ||| j
                        |dk\  r)|j                  dg       D ]  }| j                  |        n#|t        j                  v r| j                  d       t        | t              r#t        | t              s| j                  d       y y y )	Nrb  r      zTransaction numberszrThis MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.	   errorLabelsrW  )r4  rj   strr  r   r1  r3  r
   rc  rc   r   r   )r5  r(  r  rb  errmsglabels         rD   r[  r[    s    
s
#C
wwvq!BJC##$9:-  #64==q 3 ,$$U+, w555$$%:; 	3)*3/23 0 	+r\   c                   ,    e Zd ZdZdZd Zd Zd Zd Zy)r%  z1Handle errors raised when executing an operation.)rY   server_addressr   r(  sock_generationcompleted_handshakec                     || _         |j                  j                  | _        || _        t
        j                  | _        |j                  j                  | _
        d| _        y )NF)rY   r   r   r=  r   r   MIN_WIRE_VERSIONr(  pool
generationr>  r?  )r   rY   r   r   s       rD   r   z!_MongoClientErrorHandler.__init__  sN    $0088 & 7 7
  &{{55#( r\   c                 V    |j                   | _         |j                  | _        d| _        y)z0Provide socket information to the error handler.TN)r(  rC  r>  r?  )r   r   s     rD   r&  z*_MongoClientErrorHandler.contribute_socket  s&     ) : :(33#' r\   c                     | S r>   rr  r   s    rD   r  z"_MongoClientErrorHandler.__enter__  r  r\   c                 (   |y | j                   rt        |t              rK| j                   j                  r|j	                  d       | j                   j
                  j                          t        |t              r<|j                  d      s|j                  d      r| j                   j                          t        || j                  | j                  | j                        }| j                  j                  j!                  | j"                  |       y )Nr-  rW  )r   
issubclassr   r1  r3  r  r  r   r\  r4  r!   r(  r>  r?  rY   r   handle_errorr=  )r   r   r!  r"  err_ctxs        rD   r#  z!_MongoClientErrorHandler.__exit__  s    <<($56<<..,,-HI,,779(L1++,GH//0EFLL..0T**D,@,@$$& 	**4+>+>Hr\   N)	ry  rx  r(  r)  	__slots__r   r&  r  r#  rr  r\   rD   r%  r%    s!    ;;I
)(Ir\   r%  )Cr)  r+  r   rv   rr   r   collectionsr   bson.codec_optionsr   bson.py3compatr   r   bson.sonr   pymongor   r	   r
   r   r   r   r   pymongo.change_streamr   pymongo.client_optionsr   pymongo.command_cursorr   pymongo.cursor_managerr   pymongo.errorsr   r   r   r   r   r   r   r   r   pymongo.read_preferencesr   pymongo.server_selectorsr   r   pymongo.server_typer   pymongo.topologyr    r!   pymongo.topology_descriptionr"   pymongo.settingsr#   pymongo.uri_parserr$   r%   r&   pymongo.write_concernr'   
BaseObjectr)   r4  r[  objectr%  rr  r\   rD   <module>r_     s   &      # 4) % % % 6 0 0 09 9 9 4@ +- 6 -4 4 8]!&## ]!@C
46,Iv ,Ir\   