+\hVdZddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z m Z m Z mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZddlmZmZm Z ddl!m"Z"ddl#m$Z$m%Z%m&Z&m'Z'dd l(m)Z)m*Z*m+Z+dd l,m-Z-m.Z.dd l/m0Z0dd l1m2Z2dd l3m4Z4ddl5m6Z6ddl7m8Z8m9Z9ddl:m;Z;ddlm?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJddlKmLZLmMZMmNZNddlOmPZPmQZQmRZRmSZSmTZTddlUmVZVmWZWmXZXddlYmZZZm[Z[ddl\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcddldmeZemfZfddlgmhZhddlimjZjddlkmlZlddlmmnZnddlompZpmqZqddlrmsZsmtZtmuZumvZvmwZwmxZxddlymzZzm{Z{m|Z|m}Z}m~Z~mZmZdd lmZmZe rDdd!lmZdd"lmZdd#lmZdd$l1mZmZdd%lmZdd&lmZdd'lmZdd(lmZdd)lmZdd*lmZdd+lkmZed,Zeed-d.egee e effZeed-d/d.efgee e effZd0Zee_e^e]e`ebeafZGd1d2e%j>eevZdd9Zd?d:ZeLrejNe;yy)@aTools for connecting to MongoDB. .. seealso:: :doc:`/examples/high_availability` for examples of connecting to replica sets or sets of mongos servers. To get a :class:`~pymongo.asynchronous.database.AsyncDatabase` instance from a :class:`AsyncMongoClient` use either dictionary-style or attribute-style access: .. doctest:: >>> from pymongo import AsyncMongoClient >>> c = AsyncMongoClient() >>> c.test_database AsyncDatabase(AsyncMongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test_database') >>> c["test-database"] AsyncDatabase(AsyncMongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test-database') ) annotationsN) defaultdict) TYPE_CHECKINGAnyAsyncContextManagerAsyncGeneratorCallable Collection Coroutine FrozenSetGenericMappingMutableMappingNoReturnOptionalSequenceTypeTypeVarUnioncast)DEFAULT_CODEC_OPTIONS CodecOptions TypeRegistry) Timestamp)_csotcommonhelpers_sharedperiodic_executor)client_sessiondatabase uri_parser)AsyncChangeStreamAsyncClusterChangeStream)_AsyncClientBulk)_EmptyServerSession)AsyncCommandCursor)TopologySettings)Topology _ErrorContext) ClientOptions) DriverInfo) AutoReconnectBulkWriteErrorClientBulkWriteExceptionConfigurationErrorConnectionFailureInvalidOperationNotPrimaryErrorOperationFailure PyMongoErrorServerSelectionTimeoutErrorWaitQueueTimeoutErrorWriteConcernError)_HAS_REGISTER_AT_FORK_async_create_lock_release_locks)_CLIENT_LOGGER_COMMAND_LOGGER _debug_log_log_client_error _log_or_warn)_CursorAddress_GetMore_Query)ConnectionClosedReason_EventListeners) DeleteMany DeleteOne InsertOne ReplaceOne UpdateMany UpdateOne_Op)ReadPreference _ServerMode)ClientBulkWriteResult)ServerDescription)writable_server_selector) SERVER_TYPE) TOPOLOGY_TYPETopologyDescription) ClusterTime_Address _CollationIn _DocumentType_DocumentTypeArg _Pipeline) SRV_SCHEME_check_options_handle_option_deprecations_handle_security_options_normalize_options _validate_uri split_hosts)DEFAULT_WRITE_CONCERN WriteConcern) TracebackType)ObjectId) _AsyncBulk)AsyncClientSession_ServerSession)_ConnectionManager _Encrypter)AsyncConnection)Server) ReadConcern)Response) SelectionTrfrkrlFceZdZUdZdZdZejZde d< dN dOfd Z dPdZ dQd Z dRd Z dSd ZdPd ZdTdUd ZdVdZdWdZdPdZdXdZ dY dZdZed[dZed\dZed]dZd^dZd_dZd_dZd`dZdadZdadZdbdZ dbdZ!dPdZ" dT dcdZ#ddd Z$ de dfd!Z% dT dgd"Z& dhd#Z' di djd$Z( di dkd%Z)dld&Z*dmd'Z+dnd(Z,dZ-dod)Z.e.Z/dpd*Z0edqd+Z1edqd,Z2edrd-Z3edrd.Z4edsd/Z5edsd0Z6dtd1Z7dPd2Z8e9se8Z:dud3Z;e dw dxd5Z? dyd6Z@eZJ dd?ZK d dd@ZL ddAZM ddBZNdPdCZOdPdDZP ddEZQe`_, in addition to a simple hostname. It can also be a list of hostnames but no more than one URI. Any port specified in the host string(s) will override the `port` parameter. For username and passwords reserved characters like ':', '/', '+' and '@' must be percent encoded following RFC 2396:: from urllib.parse import quote_plus uri = "mongodb://%s:%s@%s" % ( quote_plus(user), quote_plus(password), host) client = AsyncMongoClient(uri) Unix domain sockets are also supported. The socket path must be percent encoded in the URI:: uri = "mongodb://%s:%s@%s" % ( quote_plus(user), quote_plus(password), quote_plus(socket_path)) client = AsyncMongoClient(uri) But not when passed as a simple hostname:: client = AsyncMongoClient('/tmp/mongodb-27017.sock') Starting with version 3.6, PyMongo supports mongodb+srv:// URIs. The URI must include one, and only one, hostname. The hostname will be resolved to one or more DNS `SRV records `_ 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 `_. See the `Initial DNS Seedlist Discovery spec `_ for more details. Note that the use of SRV URIs implicitly enables TLS support. Pass tls=false in the URI to override. .. note:: AsyncMongoClient creation will block waiting for answers from DNS when mongodb+srv:// URIs are used. .. note:: Starting with version 3.0 the :class:`AsyncMongoClient` constructor no longer blocks while connecting to the server or servers, and it no longer raises :class:`~pymongo.errors.ConnectionFailure` if they are unavailable, nor :class:`~pymongo.errors.ConfigurationError` if the user's credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads. You can check if the server is available like this:: from pymongo.errors import ConnectionFailure client = AsyncMongoClient() try: # The ping command is cheap and does not require auth. client.admin.command('ping') except ConnectionFailure: print("Server not available") .. warning:: When using PyMongo in a multiprocessing context, please read :ref:`multiprocessing` first. .. note:: Many of the following options can be passed using a MongoDB URI or keyword parameters. If the same option is passed in a URI and as a keyword parameter the keyword parameter takes precedence. :param host: hostname or IP address or Unix domain socket path of a single mongod or mongos instance to connect to, or a mongodb URI, or a list of hostnames (but no more than one mongodb URI). If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost). Multihomed and round robin DNS addresses are **not** supported. :param port: port number on which to connect :param document_class: default class to use for documents returned from queries on this client :param tz_aware: if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`AsyncMongoClient` will be timezone aware (otherwise they will be naive) :param connect: **Not supported by AsyncMongoClient**. :param type_registry: instance of :class:`~bson.codec_options.TypeRegistry` to enable encoding and decoding of custom types. :param kwargs: **Additional optional parameters available as keyword arguments:** - `datetime_conversion` (optional): Specifies how UTC datetimes should be decoded within BSON. Valid options include 'datetime_ms' to return as a DatetimeMS, 'datetime' to return as a datetime.datetime and raising a ValueError for out-of-range values, 'datetime_auto' to return DatetimeMS objects when the underlying datetime is out-of-range and 'datetime_clamp' to clamp to the minimum and maximum possible datetimes. Defaults to 'datetime'. See :ref:`handling-out-of-range-datetimes` for details. - `directConnection` (optional): if ``True``, forces this client to connect directly to the specified MongoDB host as a standalone. If ``false``, the client connects to the entire replica set of which the given MongoDB host(s) is a part. If this is ``True`` and a mongodb+srv:// URI or a URI containing multiple seeds is provided, an exception will be raised. - `maxPoolSize` (optional): The maximum allowable number of concurrent connections to each connected server. Requests to a server will block if there are `maxPoolSize` outstanding connections to the requested server. Defaults to 100. Can be either 0 or None, in which case there is no limit on the number of concurrent connections. - `minPoolSize` (optional): The minimum required number of concurrent connections that the pool will maintain to each connected server. Default is 0. - `maxIdleTimeMS` (optional): The maximum number of milliseconds that a connection can remain idle in the pool before being removed and replaced. Defaults to `None` (no limit). - `maxConnecting` (optional): The maximum number of connections that each pool can establish concurrently. Defaults to `2`. - `timeoutMS`: (integer or None) Controls how long (in milliseconds) the driver will wait when executing an operation (including retry attempts) before raising a timeout error. ``0`` or ``None`` means no timeout. - `socketTimeoutMS`: (integer or None) Controls how long (in milliseconds) the driver will wait for a response after sending an ordinary (non-monitoring) database operation before concluding that a network error has occurred. ``0`` or ``None`` means no timeout. Defaults to ``None`` (no timeout). - `connectTimeoutMS`: (integer or None) Controls how long (in milliseconds) the driver will wait during server monitoring when connecting a new socket to a server before concluding the server is unavailable. ``0`` or ``None`` means no timeout. Defaults to ``20000`` (20 seconds). - `server_selector`: (callable or None) Optional, user-provided function that augments server selection rules. The function should accept as an argument a list of :class:`~pymongo.server_description.ServerDescription` objects and return a list of server descriptions that should be considered suitable for the desired operation. - `serverSelectionTimeoutMS`: (integer) Controls how long (in milliseconds) the driver will wait to find an available, appropriate server to carry out a database operation; while it is waiting, multiple server monitoring operations may be carried out, each controlled by `connectTimeoutMS`. Defaults to ``30000`` (30 seconds). - `waitQueueTimeoutMS`: (integer or None) How long (in milliseconds) a thread will wait for a socket from the pool if the pool has no free sockets. Defaults to ``None`` (no timeout). - `heartbeatFrequencyMS`: (optional) The number of milliseconds between periodic server checks, or None to accept the default frequency of 10 seconds. - `serverMonitoringMode`: (optional) The server monitoring mode to use. Valid values are the strings: "auto", "stream", "poll". Defaults to "auto". - `appname`: (string or None) The name of the application that created this AsyncMongoClient instance. The server will log this value upon establishing each connection. It is also recorded in the slow query log and profile collections. - `driver`: (pair or None) A driver implemented on top of PyMongo can pass a :class:`~pymongo.driver_info.DriverInfo` to add its name, version, and platform to the message printed in the server log when establishing a connection. - `event_listeners`: a list or tuple of event listeners. See :mod:`~pymongo.monitoring` for details. - `retryWrites`: (boolean) Whether supported write operations executed within this AsyncMongoClient will be retried once after a network error. Defaults to ``True``. The supported write operations are: - :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, as long as :class:`~pymongo.asynchronous.operations.UpdateMany` or :class:`~pymongo.asynchronous.operations.DeleteMany` are not included. - :meth:`~pymongo.asynchronous.collection.AsyncCollection.delete_one` - :meth:`~pymongo.asynchronous.collection.AsyncCollection.insert_one` - :meth:`~pymongo.asynchronous.collection.AsyncCollection.insert_many` - :meth:`~pymongo.asynchronous.collection.AsyncCollection.replace_one` - :meth:`~pymongo.asynchronous.collection.AsyncCollection.update_one` - :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one_and_delete` - :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one_and_replace` - :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one_and_update` Unsupported write operations include, but are not limited to, :meth:`~pymongo.asynchronous.collection.AsyncCollection.aggregate` using the ``$out`` pipeline operator and any operation with an unacknowledged write concern (e.g. {w: 0})). See https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.md - `retryReads`: (boolean) Whether supported read operations executed within this AsyncMongoClient will be retried once after a network error. Defaults to ``True``. The supported read operations are: :meth:`~pymongo.asynchronous.collection.AsyncCollection.find`, :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one`, :meth:`~pymongo.asynchronous.collection.AsyncCollection.aggregate` without ``$out``, :meth:`~pymongo.asynchronous.collection.AsyncCollection.distinct`, :meth:`~pymongo.asynchronous.collection.AsyncCollection.count`, :meth:`~pymongo.asynchronous.collection.AsyncCollection.estimated_document_count`, :meth:`~pymongo.asynchronous.collection.AsyncCollection.count_documents`, :meth:`pymongo.asynchronous.collection.AsyncCollection.watch`, :meth:`~pymongo.asynchronous.collection.AsyncCollection.list_indexes`, :meth:`pymongo.asynchronous.database.AsyncDatabase.watch`, :meth:`~pymongo.asynchronous.database.AsyncDatabase.list_collections`, :meth:`pymongo.asynchronous.mongo_client.AsyncMongoClient.watch`, and :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.list_databases`. Unsupported read operations include, but are not limited to :meth:`~pymongo.asynchronous.database.AsyncDatabase.command` and any getMore operation on a cursor. Enabling retryable reads makes applications more resilient to transient errors such as network failures, database upgrades, and replica set failovers. For an exact definition of which errors trigger a retry, see the `retryable reads specification `_. - `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 `_ package. zlib support requires the Python standard library zlib module. zstd requires the `zstandard `_ package. By default no compression is used. Compression support must also be enabled on the server. MongoDB 3.6+ supports snappy and zlib compression. MongoDB 4.2+ adds support for zstd. See :ref:`network-compression-example` for details. - `zlibCompressionLevel`: (int) The zlib compression level to use when zlib is used as the wire protocol compressor. Supported values are -1 through 9. -1 tells the zlib library to use its default compression level (usually 6). 0 means no compression. 1 is best speed. 9 is best compression. Defaults to -1. - `uuidRepresentation`: The BSON representation to use when encoding from and decoding to instances of :class:`~uuid.UUID`. Valid values are the strings: "standard", "pythonLegacy", "javaLegacy", "csharpLegacy", and "unspecified" (the default). New applications should consider setting this to "standard" for cross language compatibility. See :ref:`handling-uuid-data-example` for details. - `unicode_decode_error_handler`: The error handler to apply when a Unicode-related error occurs during BSON decoding that would otherwise raise :exc:`UnicodeDecodeError`. Valid options include 'strict', 'replace', 'backslashreplace', 'surrogateescape', and 'ignore'. Defaults to 'strict'. - `srvServiceName`: (string) The SRV service name to use for "mongodb+srv://" URIs. Defaults to "mongodb". Use it like so:: AsyncMongoClient("mongodb+srv://example.com/?srvServiceName=customname") - `srvMaxHosts`: (int) limits the number of mongos-like hosts a client will connect to. More specifically, when a "mongodb+srv://" connection string resolves to more than srvMaxHosts number of hosts, the client will randomly choose an srvMaxHosts sized subset of hosts. | **Write Concern options:** | (Only set if passed. No default values.) - `w`: (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. `w=` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). Passing w=0 **disables write acknowledgement** and all other write concern options. - `wTimeoutMS`: **DEPRECATED** (integer) Used in conjunction with `w`. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised. Passing wTimeoutMS=0 will cause **write operations to wait indefinitely**. - `journal`: If ``True`` block until write operations have been committed to the journal. Cannot be used in combination with `fsync`. Write operations will fail with an exception if this option is used when the server is running without journaling. - `fsync`: If ``True`` and the server is running without journaling, blocks until the server has synced all data files to disk. If the server is running with journaling, this acts the same as the `j` option, blocking until write operations have been committed to the journal. Cannot be used in combination with `j`. | **Replica set keyword arguments for connecting with a replica set - either directly or via a mongos:** - `replicaSet`: (string or None) The name of the replica set to connect to. The driver will verify that all servers it connects to match this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. Defaults to ``None``. | **Read Preference:** - `readPreference`: The replica set read preference for this client. One of ``primary``, ``primaryPreferred``, ``secondary``, ``secondaryPreferred``, or ``nearest``. Defaults to ``primary``. - `readPreferenceTags`: Specifies a tag set as a comma-separated list of colon-separated key-value pairs. For example ``dc:ny,rack:1``. Defaults to ``None``. - `maxStalenessSeconds`: (integer) The maximum estimated length of time a replica set secondary can fall behind the primary in replication before it will no longer be selected for operations. Defaults to ``-1``, meaning no maximum. If maxStalenessSeconds is set, it must be a positive integer greater than or equal to 90 seconds. .. seealso:: :doc:`/examples/server_selection` | **Authentication:** - `username`: A string. - `password`: A string. Although username and password must be percent-escaped in a MongoDB URI, they must not be percent-escaped when passed as parameters. In this example, both the space and slash special characters are passed as-is:: AsyncMongoClient(username="user name", password="pass/word") - `authSource`: The database to authenticate on. Defaults to the database specified in the URI, if provided, or to "admin". - `authMechanism`: See :data:`~pymongo.auth.MECHANISMS` for options. If no mechanism is specified, PyMongo automatically negotiates the mechanism to use (SCRAM-SHA-1 or SCRAM-SHA-256) with the MongoDB server. - `authMechanismProperties`: Used to specify authentication mechanism specific options. To specify the service name for GSSAPI authentication pass authMechanismProperties='SERVICE_NAME:'. To specify the session token for MONGODB-AWS authentication pass ``authMechanismProperties='AWS_SESSION_TOKEN:'``. .. seealso:: :doc:`/examples/authentication` | **TLS/SSL configuration:** - `tls`: (boolean) If ``True``, create the connection to the server using transport layer security. Defaults to ``False``. - `tlsInsecure`: (boolean) Specify whether TLS constraints should be relaxed as much as possible. Setting ``tlsInsecure=True`` implies ``tlsAllowInvalidCertificates=True`` and ``tlsAllowInvalidHostnames=True``. Defaults to ``False``. Think very carefully before setting this to ``True`` as it dramatically reduces the security of TLS. - `tlsAllowInvalidCertificates`: (boolean) If ``True``, continues the TLS handshake regardless of the outcome of the certificate verification process. If this is ``False``, and a value is not provided for ``tlsCAFile``, PyMongo will attempt to load system provided CA certificates. If the python version in use does not support loading system CA certificates then the ``tlsCAFile`` parameter must point to a file of CA certificates. ``tlsAllowInvalidCertificates=False`` implies ``tls=True``. Defaults to ``False``. Think very carefully before setting this to ``True`` as that could make your application vulnerable to on-path attackers. - `tlsAllowInvalidHostnames`: (boolean) If ``True``, disables TLS hostname verification. ``tlsAllowInvalidHostnames=False`` implies ``tls=True``. Defaults to ``False``. Think very carefully before setting this to ``True`` as that could make your application vulnerable to on-path attackers. - `tlsCAFile`: A file containing a single or a bundle of "certification authority" certificates, which are used to validate certificates passed from the other end of the connection. Implies ``tls=True``. Defaults to ``None``. - `tlsCertificateKeyFile`: A file containing the client certificate and private key. Implies ``tls=True``. Defaults to ``None``. - `tlsCRLFile`: A file containing a PEM or DER formatted certificate revocation list. Implies ``tls=True``. Defaults to ``None``. - `tlsCertificateKeyFilePassword`: The password or passphrase for decrypting the private key in ``tlsCertificateKeyFile``. Only necessary if the private key is encrypted. Defaults to ``None``. - `tlsDisableOCSPEndpointCheck`: (boolean) If ``True``, disables certificate revocation status checking via the OCSP responder specified on the server certificate. ``tlsDisableOCSPEndpointCheck=False`` implies ``tls=True``. Defaults to ``False``. - `ssl`: (boolean) Alias for ``tls``. | **Read Concern options:** | (If not set explicitly, this will use the server default) - `readConcernLevel`: (string) The read concern level specifies the level of isolation for read operations. For example, a read operation using a read concern level of ``majority`` will only return data that has been written to a majority of nodes. If the level is left unspecified, the server default will be used. | **Client side encryption options:** | (If not set explicitly, client side encryption will not be enabled.) - `auto_encryption_opts`: A :class:`~pymongo.encryption_options.AutoEncryptionOpts` which configures this client to automatically encrypt collection commands and automatically decrypt results. See :ref:`automatic-client-side-encryption` for an example. If a :class:`AsyncMongoClient` is configured with ``auto_encryption_opts`` and a non-None ``maxPoolSize``, a separate internal ``AsyncMongoClient`` is created if any of the following are true: - A ``key_vault_client`` is not passed to :class:`~pymongo.encryption_options.AutoEncryptionOpts` - ``bypass_auto_encrpytion=False`` is passed to :class:`~pymongo.encryption_options.AutoEncryptionOpts` | **Stable API options:** | (If not set explicitly, Stable API will not be enabled.) - `server_api`: A :class:`~pymongo.server_api.ServerApi` which configures this client to use Stable API. See :ref:`versioned-api-ref` for details. .. seealso:: The MongoDB documentation on `connections `_. .. versionchanged:: 4.5 Added the ``serverMonitoringMode`` keyword argument. .. versionchanged:: 4.2 Added the ``timeoutMS`` keyword argument. .. versionchanged:: 4.0 - Removed the fsync, unlock, is_locked, database_names, and close_cursor methods. See the :ref:`pymongo4-migration-guide`. - Removed the ``waitQueueMultiple`` and ``socketKeepAlive`` keyword arguments. - The default for `uuidRepresentation` was changed from ``pythonLegacy`` to ``unspecified``. - Added the ``srvServiceName``, ``maxConnecting``, and ``srvMaxHosts`` URI and keyword arguments. .. versionchanged:: 3.12 Added the ``server_api`` keyword argument. The following keyword arguments were deprecated: - ``ssl_certfile`` and ``ssl_keyfile`` were deprecated in favor of ``tlsCertificateKeyFile``. .. versionchanged:: 3.11 Added the following keyword arguments and URI options: - ``tlsDisableOCSPEndpointCheck`` - ``directConnection`` .. versionchanged:: 3.9 Added the ``retryReads`` keyword argument and URI option. Added the ``tlsInsecure`` keyword argument and URI option. The following keyword arguments and URI options were deprecated: - ``wTimeout`` was deprecated in favor of ``wTimeoutMS``. - ``j`` was deprecated in favor of ``journal``. - ``ssl_cert_reqs`` was deprecated in favor of ``tlsAllowInvalidCertificates``. - ``ssl_match_hostname`` was deprecated in favor of ``tlsAllowInvalidHostnames``. - ``ssl_ca_certs`` was deprecated in favor of ``tlsCAFile``. - ``ssl_certfile`` was deprecated in favor of ``tlsCertificateKeyFile``. - ``ssl_crlfile`` was deprecated in favor of ``tlsCRLFile``. - ``ssl_pem_passphrase`` was deprecated in favor of ``tlsCertificateKeyFilePassword``. .. versionchanged:: 3.9 ``retryWrites`` now defaults to ``True``. .. versionchanged:: 3.8 Added the ``server_selector`` keyword argument. Added the ``type_registry`` keyword argument. .. versionchanged:: 3.7 Added the ``driver`` keyword argument. .. versionchanged:: 3.6 Added support for mongodb+srv:// URIs. Added the ``retryWrites`` keyword argument and URI option. .. versionchanged:: 3.5 Add ``username`` and ``password`` options. Document the ``authSource``, ``authMechanism``, and ``authMechanismProperties`` options. Deprecated the ``socketKeepAlive`` keyword argument and URI option. ``socketKeepAlive`` now defaults to ``True``. .. versionchanged:: 3.0 :class:`~pymongo.asynchronous.mongo_client.AsyncMongoClient` is now the one and only client class for a standalone server, mongos, or replica set. It includes the functionality that had been split into :class:`~pymongo.asynchronous.mongo_client.MongoReplicaSetClient`: it can connect to a replica set, discover all its members, and monitor the set for stepdowns, elections, and reconfigs. The :class:`~pymongo.asynchronous.mongo_client.AsyncMongoClient` constructor no longer blocks while connecting to the server or servers, and it no longer raises :class:`~pymongo.errors.ConnectionFailure` if they are unavailable, nor :class:`~pymongo.errors.ConfigurationError` if the user's credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads. Therefore the ``alive`` method is removed since it no longer provides meaningful information; even if the client is disconnected, it may discover a server in time to fulfill the next operation. In PyMongo 2.x, :class:`~pymongo.asynchronous.AsyncMongoClient` accepted a list of standalone MongoDB servers and used the first it could connect to:: AsyncMongoClient(['host1.com:27017', 'host2.com:27017']) A list of multiple standalones is no longer supported; if multiple servers are listed they must be members of the same replica set, or mongoses in the same sharded cluster. The behavior for a list of mongoses is changed from "high availability" to "load balancing". Before, the client connected to the lowest-latency mongos in the list, and used it until a network error prompted it to re-evaluate all mongoses' latencies and reconnect to one of them. In PyMongo 3, the client monitors its network latency to all the mongoses continuously, and distributes operations evenly among those with the lowest latency. See :ref:`mongos-load-balancing` for more information. The ``connect`` option is added. The ``start_request``, ``in_request``, and ``end_request`` methods are removed, as well as the ``auto_start_request`` option. The ``copy_database`` method is removed, see the :doc:`copy_database examples ` for alternatives. The :meth:`AsyncMongoClient.disconnect` method is removed; it was a synonym for :meth:`~pymongo.asynchronous.AsyncMongoClient.close`. :class:`~pymongo.asynchronous.mongo_client.AsyncMongoClient` no longer returns an instance of :class:`~pymongo.asynchronous.database.AsyncDatabase` for attribute names with leading underscores. You must use dict-style lookups instead:: client['__my_database__'] Not:: client.__my_database__ .. versionchanged:: 4.7 Deprecated parameter ``wTimeoutMS``, use :meth:`~pymongo.timeout`. .. versionchanged:: 4.9 The default value of ``connect`` is changed to ``False`` when running in a Function-as-a-service environment. )hostportrtrurv type_registryNz%port must be an instance of int, not _pool_class_monitor_class_condition_classrt keyword_optsFsrvservicename srvmaxhosts/z+host must not contain multiple MongoDB URIsT)validatewarn normalize srv_max_hostsnodelistusernamepasswordr optionsfqdn!need to specify at least one hostrr{ru_is_faasrvsrvServiceName) is_srvrrdbaseseedsrsrv_service_name pool_class monitor_classcondition_class)7dict _init_kwargsHOST isinstancestrPORTint TypeErrortype_host_port _topology_timeout_topology_settings_event_listenerspopr_CaseInsensitiveDictionary_resolve_srv_infoset_seedsgetlenr/r_ startswithrZupdater`_detect_external_dbpymongo.pool_optionsr _validate_kwargs_and_update_optsSRV_SERVICE_NAME_normalize_and_validate_optionsr*_IS_SYNC_options_default_database_namer9_lock_kill_cursors_queue _encryptersuper__init__ codec_optionsread_preference write_concern read_concern_init_based_on_options_opened_closed_loop_init_background _get_topology)selfryrzrtrurvr{kwargs doc_classrrrrrrrroptsrrrhentityresnodehostnamer __class__s d/root/niggaflix-v3/playground/venv/lib/python3.12/site-packages/pymongo/asynchronous/mongo_client.pyrzAsyncMongoClient.__init__ssh#*d ' * - -  <99D dC 6D <99D$$CDJ<PQ Q  #'&* 488<ZZ t4  #3T:  **%7>88@ )2 %&2@,1Oe 002'++,<=$((7 4::2a2 3a 7$%RS Sjj DFf}#!#"/  **:6 ""3z?3z?6hz?6hJ059~6{ "";vtzz#BC+ D,{{$%HI I-1[[9Ta9 H"8,   $,9L )  xx E2H ? 5hhyhj.9G#+ Z ") Y44\4H  ##xx(8&:Q:QR %@-)@ 33D$++F88J188J1%h%xP &+#') )+ 04 %% $$$4(!.#2    MM ' ' MM ) ) MM ' ' MM & &   ##DKK@PQ  :>   ! ! #      8{36:s Q)!Q) Q.c K|jd}t}tj}|j d}|j d}|j D]}d|vr|j d}|%tj |jd|}tj||jddd|||d{}|j|d |d }n%|jt||j|s td |D cgc]} | d  c} D]} t| sn|d } |d} | |j d d} | d dlm} |j d| } | |d <| |d<|j#||}| |j dtj$}|xs|j d}|j'||}|j d|jd}|j d|jd}t)|||jd|t*|_|j/|||y7cc} ww)NrrrrconnecttimeoutmsTF)rrrconnect_timeoutrrrrrrrurvrrrrr)rrrrrr validate_timeout_or_none_or_zero cased_keyr! _parse_srvrrr`r/rrrrrrr*rrr)rrrrrrrtimeoutrrrrurvrrrs r _resolve_srvzAsyncMongoClient._resolve_srvwsk--n= 002'++,<=$((7 jj= PFf}&**+=>&$EE$../ABGG'11JJ!#$+%5"/   S_-9~ [<=()LMM167T!W7 &x0  $J/H"9-G88J69((9(*n='/L $&-L #88tLD'#'88,U>U#V )DTXXm-DM77eDDxx D,B,B:,NOHxx D,B,B:,NOH)(D$:$:7$CT8DM  ' '}>N O{= P $8s,CI#I AI# I)I#;D!I#I#c|jjj|_tdid|d|jjd|j dd|jjd|j dd|j dd|jj d|jjd |jjd |jjd |j d d |jjd |jjd|d|d|jjd|jr|jjnd|_ |jjr(ddlm}|||jj|_|jj&|_y)Nrreplica_set_namer pool_optionsrrlocal_threshold_msserver_selection_timeoutserver_selectorheartbeat_frequencyrdirect_connection load_balancedrrserver_monitoring_mode topology_idrri)rrrr'rrrrrrrrrr _topology_idauto_encryption_optspymongo.asynchronous.encryptionrjrrr)rrrrrjs rrz'AsyncMongoClient._init_based_on_optionss!% : : K K"2# # !]];;# --l;# 33 # 00A # !223DE #  $}}??# &*]]%K%K# !MM99# !% A A# ''/# #mm==# --55# .# (# $(==#G#G!# "AE@W@W//<<]a## & == - - B(t}}/Q/QRDO -- cJt|}t|}t|||SN)r]r^r[)rrrs rrz0AsyncMongoClient._normalize_and_validate_optionss'(-!$'ud# rcttjtfdj D|j |S)Nc3nK|],\}}tjj||.ywr)rrr).0kvrs r zDAsyncMongoClient._validate_kwargs_and_update_opts..s+`41a!7!7!:A>`s25)r\rrritemsr)rrrs ` rrz1AsyncMongoClient._validate_kwargs_and_update_optssI 3<@ 88 `.targets3ZF~"::6B B B Cs #.,.pymongo_kill_cursors_thread)interval min_intervalrnameFreturnbool)r(rrr8rrrwr_pidrAsyncPeriodicExecutorrKILL_CURSOR_FREQUENCYMIN_HEARTBEAT_INTERVALweakrefrefclose_kill_cursors_executorr)rold_pidrexecutorrs @rrz!AsyncMongoClient._init_backgrounds!$"9"9: FJ  % %dnn&A&A B& %::1166.   D(..9&.# rct|tstdt||jj j |y)zAppends the given metadata to existing driver metadata. :param driver_info: a :class:`~pymongo.driver_info.DriverInfo` .. versionadded:: 4.14 z3driver_info must be an instance of DriverInfo, not N)rr+rrrr_update_metadata)r driver_infos rappend_metadataz AsyncMongoClient.append_metadatasE+z2Ed;FWEXY  ""33K@rcT|jjxr|xr |j Sr)rrin_transactionrsessions r_should_pin_cursorz#AsyncMongoClient._should_pin_cursor"s%}}**WG4V@V@V/WWrc|j|jj|jjj y)z6Resets topology in a child after successfully forking.N)rrr _session_poolresetrs r _after_forkzAsyncMongoClient._after_fork%s0 dnn112 $$**,rc n|jj}|j|tdi|SNr)rcopyrrr)rrargss r _duplicatezAsyncMongoClient._duplicate+s0  %%' F'$''rc Kt|j||||||||| | | |  } | jd{| S7w)aHWatch changes on this cluster. Performs an aggregation with an implicit initial ``$changeStream`` stage and returns a :class:`~pymongo.asynchronous.change_stream.AsyncClusterChangeStream` cursor which iterates over changes on all databases on this cluster. Introduced in MongoDB 4.0. .. code-block:: python with client.watch() as stream: for change in stream: print(change) The :class:`~pymongo.asynchronous.change_stream.AsyncClusterChangeStream` iterable blocks until the next change document is returned or an error is raised. If the :meth:`~pymongo.asynchronous.change_stream.AsyncClusterChangeStream.next` method encounters a network error when retrieving a batch from the server, it will automatically attempt to recreate the cursor such that no change events are missed. Any error encountered during the resume attempt indicates there may be an outage and will be raised. .. code-block:: python try: with client.watch([{"$match": {"operationType": "insert"}}]) as stream: for insert_change in stream: print(insert_change) except pymongo.errors.PyMongoError: # The AsyncChangeStream encountered an unrecoverable error or the # resume attempt failed to recreate the cursor. logging.error("...") For a precise description of the resume process see the `change streams specification`_. :param pipeline: A list of aggregation pipeline stages to append to an initial ``$changeStream`` stage. Not all pipeline stages are valid after a ``$changeStream`` stage, see the MongoDB documentation on change streams for the supported stages. :param full_document: The fullDocument to pass as an option to the ``$changeStream`` stage. Allowed values: 'updateLookup', 'whenAvailable', 'required'. When set to 'updateLookup', the change notification for partial updates will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. :param full_document_before_change: Allowed values: 'whenAvailable' and 'required'. Change events may now result in a 'fullDocumentBeforeChange' response field. :param resume_after: A resume token. If provided, the change stream will start returning changes that occur directly after the operation specified in the resume token. A resume token is the _id value of a change document. :param max_await_time_ms: The maximum time in milliseconds for the server to wait for changes before responding to a getMore operation. :param batch_size: The maximum number of documents to return per batch. :param collation: The :class:`~pymongo.collation.Collation` to use for the aggregation. :param start_at_operation_time: If provided, the resulting change stream will only return changes that occurred at or after the specified :class:`~bson.timestamp.Timestamp`. Requires MongoDB >= 4.0. :param session: a :class:`~pymongo.asynchronous.client_session.AsyncClientSession`. :param start_after: The same as `resume_after` except that `start_after` can resume notifications after an invalidate event. This option and `resume_after` are mutually exclusive. :param comment: A user-provided comment to attach to this command. :param show_expanded_events: Include expanded events such as DDL events like `dropIndexes`. :return: A :class:`~pymongo.asynchronous.change_stream.AsyncClusterChangeStream` cursor. .. versionchanged:: 4.3 Added `show_expanded_events` parameter. .. versionchanged:: 4.2 Added ``full_document_before_change`` parameter. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.9 Added the ``start_after`` parameter. .. versionadded:: 3.7 .. seealso:: The MongoDB documentation on `changeStreams `_. .. _change streams specification: https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.md )show_expanded_eventsN)r#admin_initialize_cursor)rpipeline full_document resume_aftermax_await_time_ms batch_size collationstart_at_operation_timer start_aftercommentfull_document_before_changer! change_streams rwatchzAsyncMongoClient.watch0s]`1 JJ       #    '!5 ..000 1s6A?Ac |jT|jDcic]\}}||ft||f}}}ttj |ddd|j S|jjScc}}w)aThe description of the connected MongoDB deployment. >>> client.topology_description , , ]> >>> client.topology_description.topology_type_name 'ReplicaSetWithPrimary' Note that the description is periodically updated in the background but the returned object itself is immutable. Access this property again to get a more recent :class:`~pymongo.topology_description.TopologyDescription`. :return: An instance of :class:`~pymongo.topology_description.TopologyDescription`. .. versionadded:: 4.0 N)rrrOrSrRUnknownr description)rryrzserverss rtopology_descriptionz%AsyncMongoClient.topology_descriptions& >> !W[WbWbctd|%6d|%DDcGc&%%''  ~~)))dsA7c|j tS|jj}td|jDS)aSet of all currently connected servers. .. warning:: When connected to a replica set the value of :attr:`nodes` can change over time as :class:`AsyncMongoClient`'s view of the replica set changes. :attr:`nodes` can also be an empty set when :class:`AsyncMongoClient` is first instantiated and hasn't yet connected to any servers, or a network partition causes it to lose connection to all servers. c34K|]}|jywraddress)rss rrz)AsyncMongoClient.nodes..sFqFs)r frozensetr2 known_servers)rr2s rnodeszAsyncMongoClient.nodess< >> !; nn00 FK,E,EFFFrc|jS)zThe configuration options for this client. :return: An instance of :class:`~pymongo.client_options.ClientOptions`. .. versionadded:: 4.0 rrs rrzAsyncMongoClient.optionss}}rctt|jd|jj|jd|jdfS)Nrrr)tuplesortedrrrrs req_propszAsyncMongoClient.eq_propssN &//89 : MM * *  " "6 *  " "#5 6   rc|t||jr!|j|jk(StSr)rrrBNotImplementedrothers r__eq__zAsyncMongoClient.__eq__s. eT^^ ,==?enn&66 6rc||k( SrrrEs r__ne__zAsyncMongoClient.__ne__s5=  rc4t|jSr)hashrBrs r__hash__zAsyncMongoClient.__hash__sDMMO$$rcd djdjddg}n6djjDcgc]\}}|d||fzn|c}}zg}|j fdj D|j fdj j Dd j|Scc}}w) Nc|dk(r%|turyd|jd|jS|tjvr||dt |dzS|d|S)z9Fix options whose __repr__ isn't usable in a constructor.rtzdocument_class=dictzdocument_class=.=i)r __module____name__rTIMEOUT_OPTIONSr)optionvalues r option_reprz2AsyncMongoClient._repr_helper..option_reprss))D=0,U-=-=,>a?OPP///E4E 3ut|#4"566XQui( (rzhost='mongodb+srv://r'zhost=%rz%s:%dc3^K|]$}|jj|&ywrr>rkeyrVrs rrz0AsyncMongoClient._repr_helper..s, >AKT]]33C8 9 s*-c3K|]E}|tjvr,|dk7r'|dk7r"|jj|Gyw)rrN)r_constructor_argsrrYs rrz0AsyncMongoClient._repr_helper..sR #d4455#:KPSWaPa T]]33C8 9 sA Az, )rTrrUrrr)rrrrextendr\rjoin)rrryrzrVs` @r _repr_helperzAsyncMongoClient._repr_helpers ) >> !-d.D.DV.L-MQOPG'+&=&=&C&C"d/3.>GtTl*DHG  EIE[E[    }}--  yy!!sCcTt|jd|jdS)N())rrRr_rs r__repr__zAsyncMongoClient.__repr__#s*t*%%&a(9(9(;'>rc |jdr*tt|jd|d|d|d|j |S)Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :param name: the name of the database to get _z has no attribute z. To access the z database, use client[z].)rAttributeErrorrrR __getitem__rrs r __getattr__zAsyncMongoClient.__getattr__&s^ ??3  :&&''9$AQRVQW(4 %%rc.tj||S)re)r AsyncDatabaseris rrhzAsyncMongoClient.__getitem__5s%%dD11rc $ |jrn|jsatjdt |j d|j jdt |j dtdyyy#ttf$rYywxYw)zLCheck that this AsyncMongoClient has been closed and issue a warning if not.z Unclosed z opened at: zCall z?.close() to safely shut down your client and free up resources.) stacklevelN) rrwarningsrrrRr_stackResourceWarningrgrrs r__del__zAsyncMongoClient.__del__?s ||DLL #DJ$7$7#8 dF]F]FdFdEeT 3 344su$ %1| *   sA8A==BBc@|jj|||fy)z;Request that a cursor and/or connection be cleaned up soon.N)rappend)r cursor_idr8conn_mgrs r_close_cursor_soonz#AsyncMongoClient._close_cursor_soonOs   '')X(FGrc pt}tjdi|}tj||||Sr)r%rSessionOptionsrf)rimplicitrserver_sessionrs r_start_sessionzAsyncMongoClient._start_sessionXs4,.,,6v600~tXVVrc,|jd|||S)aStart a logical session. This method takes the same parameters as :class:`~pymongo.asynchronous.client_session.SessionOptions`. See the :mod:`~pymongo.asynchronous.client_session` module for details and examples. A :class:`~pymongo.asynchronous.client_session.AsyncClientSession` may only be used with the AsyncMongoClient that started it. :class:`AsyncClientSession` instances are **not thread-safe or fork-safe**. They can only be used by one thread or process at a time. A single :class:`AsyncClientSession` cannot be used to run multiple operations concurrently. :return: An instance of :class:`~pymongo.asynchronous.client_session.AsyncClientSession`. .. versionadded:: 3.6 F)causal_consistencydefault_transaction_optionssnapshot)r})rrrrs r start_sessionzAsyncMongoClient.start_session]s(,"" 1(C #  rc\|r|S |jddS#ttf$rYywxYw)6If provided session is None, lend a temporary session.TF)rN)r}r/r1rs r_ensure_sessionz AsyncMongoClient._ensure_sessionzsA N &&t&F F"$45  s ++c|jj}|r |jnd}|r|r|d|dkDr|}n |}n|xs|}|r||d<yy)N clusterTime $clusterTime)rmax_cluster_time cluster_time)rcommandr topology_time session_timers r_send_cluster_timez#AsyncMongoClient._send_cluster_timesb779 /6w++D \]+l=.II6C + (8LL &2GN # rc|j | tdtt|jxs|}t j ||||||S)auGet the database named in the MongoDB connection URI. >>> uri = 'mongodb://host/my_database' >>> client = AsyncMongoClient(uri) >>> db = client.get_default_database() >>> assert db.name == 'my_database' >>> db = client.get_database() >>> assert db.name == 'my_database' Useful in scripts where you want to choose which database to use based only on the URI in a configuration file. :param default: the database name to use if no database name was provided in the URI. :param codec_options: An instance of :class:`~bson.codec_options.CodecOptions`. If ``None`` (the default) the :attr:`codec_options` of this :class:`AsyncMongoClient` is used. :param read_preference: The read preference to use. If ``None`` (the default) the :attr:`read_preference` of this :class:`AsyncMongoClient` is used. See :mod:`~pymongo.read_preferences` for options. :param write_concern: An instance of :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the default) the :attr:`write_concern` of this :class:`AsyncMongoClient` is used. :param read_concern: An instance of :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the default) the :attr:`read_concern` of this :class:`AsyncMongoClient` is used. :param comment: A user-provided comment to attach to this command. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.8 Undeprecated. Added the ``default``, ``codec_options``, ``read_preference``, ``write_concern`` and ``read_concern`` parameters. .. versionchanged:: 3.5 Deprecated, use :meth:`get_database` instead. z-No default database name defined or provided.)rr/rrr rl)rdefaultrrrrrs rget_default_databasez%AsyncMongoClient.get_default_databasesXh  & & .7?$%TU UC44?@%% $  |  rc|#|j td|j}tj||||||S)a|Get a :class:`~pymongo.asynchronous.database.AsyncDatabase` with the given name and options. Useful for creating a :class:`~pymongo.asynchronous.database.AsyncDatabase` with different codec options, read preference, and/or write concern from this :class:`AsyncMongoClient`. >>> client.read_preference Primary() >>> db1 = client.test >>> db1.read_preference Primary() >>> from pymongo import ReadPreference >>> db2 = client.get_database( ... 'test', read_preference=ReadPreference.SECONDARY) >>> db2.read_preference Secondary(tag_sets=None) :param name: The name of the database - a string. If ``None`` (the default) the database named in the MongoDB connection URI is returned. :param codec_options: An instance of :class:`~bson.codec_options.CodecOptions`. If ``None`` (the default) the :attr:`codec_options` of this :class:`AsyncMongoClient` is used. :param read_preference: The read preference to use. If ``None`` (the default) the :attr:`read_preference` of this :class:`AsyncMongoClient` is used. See :mod:`~pymongo.read_preferences` for options. :param write_concern: An instance of :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the default) the :attr:`write_concern` of this :class:`AsyncMongoClient` is used. :param read_concern: An instance of :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the default) the :attr:`read_concern` of this :class:`AsyncMongoClient` is used. .. versionchanged:: 3.5 The `name` parameter is now optional, defaulting to the database named in the MongoDB connection URI. zNo default database defined)rr/r rl)rrrrrrs r get_databasezAsyncMongoClient.get_databasesMd <**2()FGG..D%% $  |  rcX|j|ttjtS)z7Get a AsyncDatabase instance with the default settings.)rrr)rrrLPRIMARYraris r_database_default_optionsz*AsyncMongoClient._database_default_optionss,  /*22/ !  rcK|Swrrrs r __aenter__zAsyncMongoClient.__aenter__  c@K|jd{y7wr)r rexc_typeexc_valexc_tbs r __aexit__zAsyncMongoClient.__aexit__sjjlrctd)Nz)'AsyncMongoClient' object is not iterable)rrs r__next__zAsyncMongoClient.__next__!sCDDrcK|jd{jttjd{}t |j |S7D7w)aAn attribute of the current server's description. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available. Not threadsafe if used multiple times in a single method, since the server may change. In such cases, store a local reference to a ServerDescription first, then use its properties. N)r select_serverrPrKTESTgetattrr2)r attr_nameservers r_server_propertyz!AsyncMongoClient._server_property&sR#0022AA $chh  v))955 3 s!AA)AAAAcTK|j|jd{|jjj}|tj k(r1t |jjdkDr td|jdd{S77w)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 NrzVCannot use "address" property when load balancing among mongoses, use "nodes" instead.r8) rr _description topology_typerRShardedrr4server_descriptionsr1r)rrs rr8zAsyncMongoClient.address7s >> !$$& & &33AA ]22 2D--AACDqH"2 **9555 '6s" B(B$A> !$$& & &^^//111 '1! A A !A A A  A cK|j|jd{|jjd{S7&7w)aeThe secondary members known to this client. A sequence of (host, port) pairs. Empty if this client is not connected to a replica set, there are no visible secondaries, or this client was created without the `replicaSet` option. .. versionadded:: 3.0 AsyncMongoClient gained this property in version 3.0. N)rrget_secondariesrs r secondarieszAsyncMongoClient.secondariesasC >> !$$& & &^^33555 '5rcK|j|jd{|jjd{S7&7w)zArbiters in the replica set. A sequence of (host, port) pairs. Empty if this client is not connected to a replica set, there are no arbiters, or this client was created without the `replicaSet` option. N)rr get_arbitersrs rarbiterszAsyncMongoClient.arbiterspsC >> !$$& & &^^00222 '2rc@K|jdd{S7w)aPIf this client is connected to a server that can accept writes. True if the current server is a standalone, mongos, or the primary of a replica set. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available. is_writableN)rrs r is_primaryzAsyncMongoClient.is_primary|s**=9999s cbK|jdd{tjk(S7w)zIf this client is connected to mongos. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available. server_typeN)rrQMongosrs r is_mongoszAsyncMongoClient.is_mongoss* **=99[=O=OOO9s /-/c K |jtjdtjd{4d{\}}|j s dddd{yt dt|tjD]7}d|||tjzi}|jd|||d{9dddd{y777x77 #1d{7swYyxYw#t$rYywxYww)z7Send endSessions command(s) with the given session ids.N operationr endSessionsr")rr) _conn_for_readsrLPRIMARY_PREFERREDrK END_SESSIONSsupports_sessionsrangerr_MAX_END_SESSIONSrr4)r session_idsconn read_prefispecs r _end_sessionszAsyncMongoClient._end_sessionss& "1100$#BRBR2 ^ ^-- ^ ^ ^q#k"2F4L4LM^A);q1v?W?W;W+XYD,,wiX\,]]]^ ^ ^ ^ ^ ^^ ^ ^ ^ ^   sD3C4CC4CC4C C4 C!C4%D&AC=C>C C4CC4DC4C4C4CC4C1%C( &C1-C40D1C44 D=D?DDcdK|jy|jj}|r|j|d{|jj |j d{|jj d{|j r"|j j d{d|_tsQtj|jj|jjdd{yy7777i7w)aCleanup client resources and disconnect from MongoDB. End all server sessions created by this client by sending one or more endSessions commands. Close all sockets in the connection pools and stop the monitor threads. .. versionchanged:: 4.0 Once closed, the client cannot be used again and any attempt will raise :exc:`~pymongo.errors.InvalidOperation`. .. versionchanged:: 3.6 End all server sessions created by this client. NT)return_exceptions) rpop_all_sessionsrr r _process_kill_cursorsrrrasynciogathercleanup_monitorsr^)rrs rr zAsyncMongoClient.closes >> ! nn557 $$[1 1 1 ##))+((***nn""$$$ ??//'') ) ) ..//1++002"&   2 +$ * sZ>D0D&1D02D(3!D0D*-D0D,AD0D. D0(D0*D0,D0.D0cbKtsR|jtj|_n,|jtjk7r t d|j s|j dr(|jd{|j|jjd{|j4d{|jjdddd{d|_|jS77X7E7#1d{7swY-xYww)zGet the internal :class:`~pymongo.asynchronous.topology.Topology` object. If this client was created with "connect=False", calling _get_topology launches the connection process in the background. NzCannot use AsyncMongoClient in different event loop. AsyncMongoClient uses low-level asyncio APIs that bind it to the event loop it was created on.rT) rrrget_running_loop RuntimeErrorrrrrropenrr rs rrzAsyncMongoClient._get_topologys zz!$557 w7799"j||%%h/'')))%%'..%%' ' 'zz 3 3++002 3 3DL~~ * ' 3 3 3 3 3slBD/ D 1D/;D<D/DD/D/ D/:D;D/D/D/D/D, D# !D,(D/c K|xr |j}t|||4d{}|rJ|rH|jr<|j|j|j dddd{y|j |d{4d{}|rJ|rH|j j tjtjfvr|j|||j||jr0|jjs|jdkr td|dddd{dddd{y737777#1d{7swY.xYw7%#1d{7swYyxYww)N)handlerz9Auto-encryption requires a minimum MongoDB version of 4.2)r_MongoClientErrorHandler_pinned_connectioncontribute_socketcheckoutr2rrQr LoadBalancer_pinr_bypass_auto_encryptionmax_wire_versionr/)rrrin_txn err_handlerrs r _checkoutzAsyncMongoClient._checkoutsp3W33+D&'B  k'g&@&@--g.H.HI000     $__[_AA  T**66#**#00 LL.--d3OO OOCC--1,S +        B          s"FEF} |r6|jr*| jd|jd{7d} ~ wwxYww)aSelect a server to run an operation on this client. :Parameters: - `server_selector`: The server selector to use if the session is not pinned and no address is given. - `session`: The AsyncClientSession for the next operation, or None. May be pinned to a mongos server address. - `address` (optional): Address when sending a message to a specific server, used for getMore. N) operation_idz server %s:%s no longer available)deprioritized_serversrTransientTransactionError) rr _transactionr_pinned_addressselect_server_by_addressr,rr4_add_error_label_unpin) rrrrr8rrtopologyrexcs r_select_serverzAsyncMongoClient._select_servers& !//11Hw55**00222w!11'@@Y\ A '(JW(TUUM (55#*?!- 6  M'22   711$$%@Ann&&&   sC=B3B+/B3B--B35B/6B3 C= B3$B1%B3*C=+B3-B3/B31B33 C:<2C5.C1/C55C::C=cpK|jt||d{}|j||S7wr)rrPr)rrrrs r_conn_for_writesz!AsyncMongoClient._conn_for_writes5s7**+CWiXX~~fg..Ys 646cK|Jd|jjjtjk(}|j ||4d{}|rG|j r|r |jstj}n|jrtj}||fdddd{y7e7#1d{7swYyxYwwNz read_preference must not be None) rr2rrRSingleris_replrrLr is_standaloner)rrrrsinglers r_conn_from_serverz"AsyncMongoClient._conn_from_server;s*N,NN*++99]=Q=QQ>>&'2 ( (d<<W5K5K'5&F&FO''&4&<&._cmdsH OO --%%  s 4><>)r8 retryabler) rOptional[AsyncClientSession]rrlrrkrrMrrn)rwrrrrrrrrrr_retryable_readrrB)rrrr8rrrs``` r_run_operationzAsyncMongoClient._run_operation^s   ..))!! /F!))//  3D&)BSBST  Xc11)2D2D2I2IJ!'!5!5!**//!!11--" "       2  " )      ))   % %    F3nn *   G            8 sAG E7 G(E:)G,F,E= F, A'F3E?4F7 F,FF, GFAG2G3G:G=F,?FF,GF F F F, G%F(&G,F>2F5 3F>:GcKt|xr)|jjxr|xr |j }|j ||||||d{S7w)zExecute an operation with at most one consecutive retries Returns func()'s return value on success. On error retries the same command. Re-raises any exception thrown by func(). )funcrbulkrrrN)rr retry_writesr_retry_internal)rrr rr rrs r_retry_with_sessionz$AsyncMongoClient._retry_with_sessionsm$  ^$,,33 ^ ^H^H^D^ ))% *    sAAAAc dKt||||||||||  jd{S7w)aInternal retryable helper for all client transactions. :param func: Callback function we want to retry :param session: Client Session on which the transaction should occur :param bulk: Abstraction to handle bulk write operations :param operation: The name of the operation that the server is being selected for :param is_read: If this is an exclusive read transaction, defaults to False :param address: Server Address, defaults to None :param read_pref: Topology of read operation, defaults to None :param retryable: If the operation should be retried once, defaults to None :return: Output of the calling func() ) mongo_clientr r ris_readrrr8rrN)_ClientConnectionRetryablerun) rr rr rrr8rrrs rr z AsyncMongoClient._retry_internalsF40%   #%   s '0.0c Kt|xr)|jjxr|xr |j }|j ||d|d|||| d{S7w)aExecute an operation with consecutive retries if possible Returns func()'s return value on success. On error retries the same command. Re-raises any exception thrown by func(). :param func: Read call we want to execute :param read_pref: Desired topology of read operation :param session: Client session we should use to execute operation :param operation: The name of the operation that the server is being selected for :param address: Optional address when sending a message, defaults to None :param retryable: if we should attempt retries (may not always be supported even if supplied), defaults to False NT)rr8rrr)rr retry_readsrr )rr rrrr8rrs rrz AsyncMongoClient._retryable_readsv8  _$,,22 _G<^H^H^7_ ))    %*    sAAAAc K|j|4d{}|j||||||d{cdddd{S7377 #1d{7swYyxYww)akExecute an operation with consecutive retries if possible Returns func()'s return value on success. On error retries the same command. Re-raises any exception thrown by func(). :param retryable: if we should attempt retries (may not always be supported) :param func: write call we want to execute during a session :param session: Client session we will use to execute write operation :param operation: The name of the operation that the server is being selected for :param bulk: bulk abstraction to execute operations in bulk, defaults to None N) _tmp_sessionr)rrr rrr rr9s r_retryable_writez!AsyncMongoClient._retryable_write sp,$$W- e e11)T1dIWcdd e e ed e e e esSA'A A'AAA A'AA'AA'A$A A$ A'c^|s|r|j||||r|s|jyyy)aCleanup a cursor from __del__ without locking. This method handles cleanup for Cursors/CommandCursors including any pinned connection attached at the time the cursor was garbage collected. :param cursor_id: The cursor id which may be 0. :param address: The _CursorAddress. :param conn_mgr: The _ConnectionManager for the pinned connection or None. N)rx_end_implicit_sessionrrvr8rwrexplicit_sessions r_cleanup_cursor_no_lockz(AsyncMongoClient._cleanup_cursor_no_lock"s4&   # #Iw A +  ) ) +,7rcRK|rk|rL|jr@|jJ|jjtjd{n|j ||||d{|r|j d{|r|s|jyyy7S777w)a2Cleanup a cursor from cursor.close() using a lock. This method handles cleanup for Cursors/CommandCursors including any pinned connection or implicit session attached at the time the cursor was closed or garbage collected. :param cursor_id: The cursor id which may be 0. :param address: The _CursorAddress. :param conn_mgr: The _ConnectionManager for the pinned connection or None. :param session: The cursor's session. :param explicit_session: True if the session was passed explicitly. N)rrw) more_to_comer close_connrCERROR_close_cursor_nowr rrs r_cleanup_cursor_lockz%AsyncMongoClient._cleanup_cursor_lock:s( H11 }}000mm../E/K/KLLL,,Y[c,ddd .." " " +  ) ) +,7 Md "s6A B' B!B'+B#,B'B%B'#B'%B'cKt|tstdt| |r_|j4d{|J|j J|j |g|||j d{dddd{y|j|g||jd{|d{y77K7=#1d{7swYyxYw7-7"#t$r|j||YywxYww)zzSend a kill cursors message with the given id. The cursor is closed synchronously on the current thread. z*cursor_id must be an instance of int, not N) rrrrrr_kill_cursor_impl _kill_cursorsrr4rx)rrvr8rrws rr"z"AsyncMongoClient._close_cursor_now\s)S)HiHYZ[ [ 8#>>__"...#==44400)gwPXP]P]^^^ ___ (()gTEWEWEY?Y[bccc __ ____ @Zc 8  # #Iw 7 8s(DCCC5C6C7C; CCC D !C-C . C:C;C?DCCCC C CCDCCC=:D<C==DcK|r2|jt|tjd{}n,|j t tjd{}|j ||4d{}|J|j||||d{dddd{y7}7R7977 #1d{7swYyxYww)z/Send a kill cursors message with the given ids.N)rr@rK KILL_CURSORSrrPrr%)r cursor_idsr8rrrrs rr&zAsyncMongoClient._kill_cursorsws $<>&'2 M Md& &&((WgtL L L M M M _^ M L M M M Ms{/CB/,CB1C9B3:C=B9B5B9 C)B7*C1C3C5B97C9C ?C C CcK|j}|jdd\}}||d}|j||||d{y7w)NrOr) killCursorscursors)rr) namespacesplitr) rr)r8rrr-dbcollrs rr%z"AsyncMongoClient._kill_cursor_implsK%% ??3*D# ;ll2tWTlBBBs?A AA cKtt}g} |jj\}}}|r|j |||fn||j |K#t$rYnwxYw|D]l\}}} |j |||ddd{7'#t$r;}t|tr|jjrtYd}~fd}~wwxYw|r|jd{7}|jD]k\}} |j|||dd{7&#t$r;}t|tr|jjrtYd}~ed}~wwxYwyyw)z*Process any pending kill cursors requests.NF)r)rlistrr IndexErrorrur# Exceptionrr1rrr>rrr&) raddress_to_cursor_idspinned_cursorsr8rvrwrrr)s rrz&AsyncMongoClient._process_kill_cursorss +D 1 /3/G/G/K/K/M,H%%w 8&DE%g.55i@  -; ( (GY (// 7HdTYZZZ (c#349O9O%''  ( ( !!//111H'<'B'B'D ,#,,,Z(TX,YYY ,!#'78T^^=S=S)++ , , !sE;A ,E; A,)E;+A,, E;9BBBE; C!1CE;CE;5C86E;D1*D-+D10E;1 E5:1E0+E;0E55E;c K |jd{|jjd{y7'7#t$r?}t |t r|jj rYd}~ytYd}~yd}~wwxYww)zcProcess any pending kill cursors requests and maintain connection pool parameters. N)rr update_poolr4rr1rr>)rrs rrz(AsyncMongoClient._process_periodic_taskssn $,,. . ...,,. . . / . $#/0T^^5K5K!##  $sWBA?!AAABAA B  &B2B7 BBB  BcZt|try|jj|S)z.Internal: return a _ServerSession to the pool.N)rr%rreturn_server_session)rr|s r_return_server_sessionz'AsyncMongoClient._return_server_sessions' n&9 :~~33NCCrcK|7t|tjstdt ||y|j |}|r# | |r|jd{yydy#t $rI}t|tr|jj|jd{7d}~wwxYw7a#|r|jd{7wwxYww)rNz>'session' argument must be an AsyncClientSession or None, not ) rrrf ValueErrorrrr4r0_server_session mark_dirty end_session)rrr r9rs rrzAsyncMongoClient._tmp_sessions  g~'H'HI TUYZaUbTcdM    )  *--/))J c#45%%002mmo%%  *--/))s`A C0A8C0+C , C08 C =C>C?CC  C C0C-%C(&C--C0cK|jj|jdd{||j|yy7w)Nr)rreceive_cluster_timer_process_response)rreplyrs rrCz"AsyncMongoClient._process_responsesHnn11%))N2KLLL    % %e ,  Ms.A A A cKtt|jjdtj |d{S7w)zGet information about the MongoDB server we're connected to. :param session: a :class:`~pymongo.asynchronous.client_session.AsyncClientSession`. .. versionchanged:: 3.6 Added ``session`` parameter. buildinfo)rrN)rrr"rrLrrs r server_infozAsyncMongoClient.server_infosF **$$^-C-CW%    s:AA AcKddi}|j||||d<|jd}|j||tjd{}d|ddd }t |d |d| S7w) N listDatabasesrr,r")rrr databasesz admin.$cmd)id firstBatchnsz$cmd)r,)rr_retryable_read_commandrKLIST_DATABASESr&)rrr,rcmdr"rcursors r_list_databasesz AsyncMongoClient._list_databases s " 6  $C N..w711 C,>,>2   k*  "%-wOO sAA7A5 A7cFK|j||fi|d{S7w)aGet a cursor over the databases of the connected server. :param session: a :class:`~pymongo.asynchronous.client_session.AsyncClientSession`. :param comment: A user-provided comment to attach to this command. :param kwargs: Optional parameters of the `listDatabases command `_ can be passed as keyword arguments to this method. The supported options differ by server version. :return: An instance of :class:`~pymongo.asynchronous.command_cursor.AsyncCommandCursor`. .. versionadded:: 3.6 NrR)rrr,rs rlist_databaseszAsyncMongoClient.list_databases$ s(.*T))'7EfEEEEs !!cK|j|d|d{}|2cgc3d{}|d77 6c}Scc}ww)arGet a list of the names of all databases on the connected server. :param session: a :class:`~pymongo.asynchronous.client_session.AsyncClientSession`. :param comment: A user-provided comment to attach to this command. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionadded:: 3.6 T)nameOnlyr,NrrT)rrr,rdocs rlist_database_namesz$AsyncMongoClient.list_database_names= sH"((4(QQ-011cF R1111s4A4A<86 8<A8<Ac K|}t|tjr |j}t|tst dt ||j|tjd{4d{}||j|d|dtj|j|d|d{dddd{y7`7Y77 #1d{7swYyxYww)a Drop a database. Raises :class:`TypeError` if `name_or_database` is not an instance of :class:`str` or :class:`~pymongo.asynchronous.database.AsyncDatabase`. :param name_or_database: the name of a database to drop, or a :class:`~pymongo.asynchronous.database.AsyncDatabase` instance representing the database to drop :param session: a :class:`~pymongo.asynchronous.client_session.AsyncClientSession`. :param comment: A user-provided comment to attach to this command. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. note:: The :attr:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.write_concern` of this client is automatically applied to this operation. .. versionchanged:: 3.4 Apply this client's write concern automatically to this operation when connected to MongoDB >= 3.4. zDname_or_database must be an instance of str or a AsyncDatabase, not rNr) dropDatabaser,T)rrparse_write_concern_errorr)rr rlrrrrrrK DROP_DATABASE_commandrLr_write_concern_for)rname_or_databaserr,rrs r drop_databasezAsyncMongoClient.drop_databaseQ sD  dH22 399D$$VW[\`WaVbc ..w#BSBS.TT  X\t*%%!"w7 . 6 6"55g>*. &     T      slA4C46C7C4?CC4>CCC C4CC4C4CC4C1%C( &C1-C4c ZK|jjr td|r:|jr.|r td|jj j }n|s |j }|r|js |r td|r|js |r tdtjd|t|||||||} |D]} | j| | j|tj d{S#t$rt| ddwxYw7 w) aSend a batch of write operations, potentially across multiple namespaces, to the server. Requests are passed as a list of write operation instances ( :class:`~pymongo.operations.InsertOne`, :class:`~pymongo.operations.UpdateOne`, :class:`~pymongo.operations.UpdateMany`, :class:`~pymongo.operations.ReplaceOne`, :class:`~pymongo.operations.DeleteOne`, or :class:`~pymongo.operations.DeleteMany`). >>> async for doc in db.test.find({}): ... print(doc) ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')} {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} ... >>> async for doc in db.coll.find({}): ... print(doc) ... {'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')} ... >>> # DeleteMany, UpdateOne, and UpdateMany are also available. >>> from pymongo import InsertOne, DeleteOne, ReplaceOne >>> models = [InsertOne(namespace="db.test", document={'y': 1}), ... DeleteOne(namespace="db.test", filter={'x': 1}), ... InsertOne(namespace="db.coll", document={'y': 2}), ... ReplaceOne(namespace="db.test", filter={'w': 1}, replacement={'z': 1}, upsert=True)] >>> result = await client.bulk_write(models=models) >>> result.inserted_count 2 >>> result.deleted_count 1 >>> result.modified_count 0 >>> result.upserted_count 1 >>> async for doc in db.test.find({}): ... print(doc) ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')} {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')} ... >>> async for doc in db.coll.find({}): ... print(doc) ... {'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')} {'y': 2, '_id': ObjectId('507f1f77bcf86cd799439012')} :param models: A list of write operation instances. :param session: (optional) An instance of :class:`~pymongo.asynchronous.client_session.AsyncClientSession`. :param ordered: If ``True`` (the default), requests will be performed on the server serially, in the order provided. If an error occurs all remaining operations are aborted. If ``False``, requests will be still performed on the server serially, in the order provided, but all operations will be attempted even if any errors occur. :param verbose_results: If ``True``, detailed results for each successful operation will be included in the returned :class:`~pymongo.results.ClientBulkWriteResult`. Default is ``False``. :param bypass_document_validation: (optional) If ``True``, allows the write to opt-out of document level validation. Default is ``False``. :param comment: (optional) A user-provided comment to attach to this command. :param let: (optional) Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). :param write_concern: (optional) The write concern to use for this bulk write. :return: An instance of :class:`~pymongo.results.ClientBulkWriteResult`. .. seealso:: For more info, see :doc:`/examples/client_bulk`. .. seealso:: :ref:`writes-and-ids` .. note:: requires MongoDB server version 8.0+. .. versionadded:: 4.9 zFMongoClient.bulk_write does not currently support automatic encryptionz5Cannot set write concern after starting a transactionz?Cannot request unacknowledged write concern and verbose resultsz>Cannot request unacknowledged write concern and ordered writesmodels)rorderedbypass_document_validationr,letverbose_resultsz is not a valid requestN)rrr1rrrr acknowledgedr validate_listr$_add_to_client_bulkrgrexecuterK BULK_WRITE) rrcrrdrgrer,rfrblkmodels r bulk_writezAsyncMongoClient.bulk_write s>x == - -"X  w--&'^__#0055CCM! $ 2 2 !;!;"Q =#=#='"#cd dXv. ''A+  OE O))#. O [[#..999" O5)+B CD$N O:s*CD+D #%D+D) D+ D&&D+)NNNNNN)ryz#Optional[Union[str, Sequence[str]]]rz Optional[int]rtzOptional[Type[_DocumentType]]ruOptional[bool]rvrqr{zOptional[TypeRegistry]rrrNonerrr)rzCollection[tuple[str, int]]rrrrrrr)r!common._CaseInsensitiveDictionaryrzset[tuple[str, int | None]]rrt)rrtrrtrrtr)r rprrr)rr+rrr)rrrrq)rrrrr) NNNNNNNNNNNN)r$zOptional[_Pipeline]r% Optional[str]r&Optional[Mapping[str, Any]]r'rpr(rpr)zOptional[_CollationIn]r*zOptional[Timestamp]r+Optional[client_session.AsyncClientSession]r+rvr, Optional[Any]r-rur!rqrz AsyncChangeStream[_DocumentType])rrS)rzFrozenSet[_Address])rr*)rz>tuple[tuple[_Address, ...], Optional[str], Optional[str], str])rFrrr)rr)rr)rrr%database.AsyncDatabase[_DocumentType])rvrr8Optional[_CursorAddress]rwOptional[_ConnectionManager]rrr)r{rrrrrf)NNF)rrqrz+Optional[client_session.TransactionOptions]rrqrz!client_session.AsyncClientSession)rrrr)rzMutableMapping[str, Any]rrrrr)NNNNN) rrur(Optional[CodecOptions[_DocumentTypeArg]]rOptional[_ServerMode]rOptional[WriteConcern]rOptional[ReadConcern]rry) rrurr|rr}rr~rrrry)rrrzdatabase.AsyncDatabase)rzAsyncMongoClient[_DocumentType])rrrrrrrrr)rr)rrrr)rzOptional[tuple[str, int]])rz set[_Address]r)rzlist[_ServerSession]rrr)rr()rrlrrrz%AsyncGenerator[AsyncConnection, None])NNN)rz Callable[[Selection], Selection]rrrrr8Optional[_Address]rzOptional[list[Server]]rrprrl)rrrrrz$AsyncContextManager[AsyncConnection])rrMrrlrrrz9AsyncGenerator[tuple[AsyncConnection, _ServerMode], None])rrMrrrrrz8AsyncContextManager[tuple[AsyncConnection, _ServerMode]])rzUnion[_Query, _GetMore]rr r8rrrn)rrr  _WriteCall[T]rrr -Optional[Union[_AsyncBulk, _AsyncClientBulk]]rrrrprrp)FNNFN)r _WriteCall[T] | _ReadCall[T]rrr rrrrrr8rrr}rrrrprrp)NTN)r z _ReadCall[T]rrMrrrrr8rrrrrprrp)NN)rrr rrrrrr rrrprrp) rvrr8rzrwrhrrrrrrr) rvrr8rzrrrwr{rrr) r) Sequence[int]r8rzrr(rrrrr) r)rr8r@rrrrkrrr)r|z*Union[_ServerSession, _EmptyServerSession]rrrT)rrwr rrzGAsyncGenerator[Optional[client_session.AsyncClientSession], None, None])rDzMapping[str, Any]rrrrr)rrwrzdict[str, Any])rrwr,rxrrrz"AsyncCommandCursor[dict[str, Any]])rrwr,rxrz list[str])r`z4Union[str, database.AsyncDatabase[_DocumentTypeArg]]rrwr,rxrrr)NTFNNNN)rcz!Sequence[_WriteOp[_DocumentType]]rrrdrrgrrerqr,rxrfzOptional[Mapping]rr~rrN)[rRrQ __qualname__rrr\rWeakValueDictionaryrw__annotations__rrrrrrrrrrrr/propertyr4r<rrBrGrIrLr_rcrjrhrsrxr}rrrrrrrr__iter__rnextrr8rrrrrrr racloser contextlibasynccontextmanagerrrrrrrapplyrrr rrrr#r"r&r%rrr;rrCrGrRrUrYraro __classcell__)rs@rrrrrs{ D DB,GG,G,G,IH)I59"8<#'"&04@ !1@ !@ !6 @ ! ! @ !  @ !.@ !@ ! @ !DCPJ.0.AD.X[. .:5>Y * 7 0  + #< AX- ()-'+48+/$(,07;?C37!%59/3A%A%A2 A ) A " A*A"5A=A1AA&3A-A *AF**< G G  !%""H? &2(26 HH*H/ H  HW.2SW#(  * &Q !  +  <7; 3  %  3/ 3:V 3  3""&BF1504.2 : : @: / : . : , :  /: |#BF1504.2 9 9 @9 / 9 . 9 , 9  /9 v HE D6"664 2 2 6 6 3 3::PP,"H .##'C .$L'+8<&*-9-.- - $ - 6 -$- -^/3/@C/ -/ ##(*(4:(Ea( B($(0H$H.H H B H [[ '+ 8 *8 8 $ 8  8 8 B'+   .  <    $   < [[&*+/&*$*$.$< $  $  $$$)$$$$ $$X'+&*) ) ) . )  ) $ ) ) $)  ) b?C&*eee. e  e < e$e e2,,*,% , . ,  , ,0 , ,* ,% , . ,  ,  ,L1515 88*8. 8 / 8  86M!M*M M . M  M( C! C  C. C  C  C&,R $DHD D##RVBKO P$>-&-1M- -FJ B  (@D!%P<PP P , P0@D!%F<FF F , F6@D!%2<22  2( [[@D!% 2N2=2 2  22h [[15 %59!%!%04B:1B:.B: B:  B: %3 B:B:B:.B: B:B:rrrct|ttfr|jd}|r|dSdSt|tt fr't tttf|jSy)z:Return the server response from PyMongo exception or None.writeConcernErrorsN) rr-r.detailsr2r3rrrr)rwcess r_retryable_error_docr sa#(@AB{{/0tBx)T)#)9:;GCH%s{{33 rc*t|}|r|jdd}|dk(r3t|jdrd}t |||j |dk\r)|jdgD]}|j |n6t|tr|rn#|tjvr|j dt|tr |j}n|}t|tr)t|ttfs|j dyyy) NcoderzTransaction numberszrThis MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string. errorLabelsRetryableWriteError)rrrrr3rrrr7r_RETRYABLE_ERROR_CODESr.errorr0r2r6)rrrrXrerrmsglabel exc_to_checks r_add_retryable_write_errorr s s #C wwvq! 2:#c(--.CD-  #64= = q 3 ,$$U+ ,#01i>>>$$%:;#/0yy  , 12:(=>< %%&;<<2rcfeZdZdZdZ d dZd d dZ d dZd dZ ddZ y)rz1Handle errors raised when executing an operation.)rserver_addressrrsock_generationcompleted_handshake service_idhandledct|tsFtdt|jDs!t dt|j ||_|jj|_ ||_ tj|_|jj j#|_d|_d|_d|_y)Nc3:K|]}|jdk(yw)rrN)rR)rclss rrz4_MongoClientErrorHandler.__init__..N sZcs||'99Zsz$AsyncMongoClient required but given F)rrranyr__mro__rrRrr2r8rrrMIN_WIRE_VERSIONrpoolgen get_overallrrrr)rrrrs rrz!_MongoClientErrorHandler.__init__I s&"23ZT&\EYEYZZ"FtF|G\G\F] ^__ $0088 & 7 7 &{{::<#( .2 rcx|j|_|j|_|j|_||_y)z0Provide socket information to the error handler.N)r generationrrr)rrrs rrz*_MongoClientErrorHandler.contribute_socket^ s/ $ 5 5#//#6 rcK|js|yd|_|jrt|tr |j}t|t rK|jj r|jd|jjjt|trD|jds|jdr"|jjd{t||j|j|j |j"}|j$j&J|j$j&j)|j*|d{y77w)NTrr)rrrr.rr0rrr>r?r4has_error_labelrr)rrrrrr handle_errorr)rrrerr_ctxs rhandlez_MongoClientErrorHandler.handlee s0 <<7?  <<'#;<!--'#45<<..,,-HI ,,779'<0**+FG7KbKb)L,,--///   ! !   $ $ OO  {{$$000kk##001D1DgNNN0 Os%C)E<+E8,BE<2E:3E<:E<cK|Swrrrs rrz#_MongoClientErrorHandler.__aenter__ rrcBK|j||d{S7wr)rrs rrz"_MongoClientErrorHandler.__aexit__ s [[73333s N)rrrrrlrrr)rrkrrrrr)rzOptional[Type[BaseException]]rzOptional[BaseException]rrr)rr)rzOptional[Type[Exception]]rzOptional[Exception]rzOptional[TracebackType]rrr) rRrQr__doc__ __slots__rrrrrrrrrr; s; I&06A]*7O5O@WO O:4+4%4( 4  4rrceZdZdZ d d dZddZddZddZddZdddZ dd Z dd Z dd Z y)rzKResponsible for executing retryable connections on read or write operationsNc *d|_d|_tjdu|_||_||_||_||_||_ | |_ ||_ |r|nt|_ ||_d|_g|_||_| |_d|_y)NFr) _last_error _retryingr get_timeout_multiple_retries_client_func_bulkr_is_read _retryable _read_prefrP_server_selector_address_server_deprioritized_servers _operation _operation_id_attempt_number) rrr r rrrrr8rrs rrz#_ClientConnectionRetryable.__init__ s15!&!2!2!4D!@#     ## I&>   # 46##) rc6K|jrO|jrC|js7|jj |j rd|j _ |jd |jr|jd{S|jd{S77#t$r|jt$r;}|jr{t|ttfrdt|dd}|j!s"t|tr|t"j$vrd|_||_|xj*dz c_n|jsG|jst|t,rD|j.r8t|j.txr|j.j1d}n|j1d}|r1|jsJ|jj3d{7|r|j!r+|j1dr|j(r |j(||xj*dz c_|j rd|j _nd|_|j1ds||_|j(||_|j6j8j:t<j>k(r%|j@jC|jDYd}~nd}~wwxYww)zRuns the supplied func() and attempts a retry :raises: self._last_error: Last exception raised :return: Result of the func() call T) check_csotNrrrNoWritesPerformed)#_is_session_state_retryablerrr_start_retryable_writerstarted_retryable_write_check_last_error_read_writer5r4rr0r3r_is_not_eligible_for_retryrrrrrr.rrrretryingrr4rrRrrrur)rrexc_coderetryable_write_error_excs rrz_ClientConnectionRetryable.run sz  + + -$//$-- MM 0 0 2zz59 2  " "d " 39 E-1]]TZZ\)Sdkkm@SS)@S. &&(. E==!#(9;K'LM#*3#=::<&s,<= (0U0U U!)-+.(,,1,}}??!#'?@SYY4>II|55O!ii778MN2584G4GH]4^10#}},}"mm2244448W8W8Y../BCHXHX"&"2"2;!((A-(zz.2 +)-../BC+.(''/+.(<<44BBmF[F[[//66t||D]. EsnA3L6B6B2B6LB6-B4.B61L2B64B66#LD3L H C=L LLLc^|j xs|jxr |j S)z0Checks if the exchange is not eligible for retry)r _is_retryingrrs rrz5_ClientConnectionRetryable._is_not_eligible_for_retry s+??"Zt'8'8':'Y4CYCY?YZrc^|jr|jjS|jS)z6Checks if the exchange is currently undergoing a retry)rrrrs rrz'_ClientConnectionRetryable._is_retrying s!&*jjtzz""DdnnDrc|jr%|jxr|jj St|jxr|jj S)zChecks if provided session is eligible for retry reads: Make sure there is no ongoing transaction (if provided a session) writes: Make sure there is a session without an active transaction )rrrrrs rrz6_ClientConnectionRetryable._is_session_state_retryable sH == F$--*F*FG GDMMF$--*F*F&FGGrc|jr9tj}|r| |dkr|jJ|jyyy)zChecks if the ongoing client exchange experienced a exception previously. If so, raise last error :param check_csot: Checks CSOT to ensure we are retrying with time remaining defaults to False Nr)rr remainingr)rrrs rrz,_ClientConnectionRetryable._check_last_error sV    )I)"7IN''333&&&=K"7 rcK|jj|j|j|j|j |j |jd{S7w)zvRetrieves a server object based on provided object context :return: Abstraction to connect to server )r8rrN)rrrrrrrrrs r _get_serverz&_ClientConnectionRetryable._get_server s^ \\00  ! ! MM OOMM"&"="=++ 1    sA!A*#A($A*cnK d}d}|jd{|_|jj|j|j4d{}|j }|jxr.|jj jxr |j}|j}|s|jd|_ |jrSttd|j|jj j"|j$|j&|j)|j||jd{cdddd{S7O777 #1d{7swYyxYw#t*$r }|jst-|d}~wwxYww)zmWrapper method for write-type retryable client executions :return: Output for func()'s call rFNzRetrying write attempt number messageclientId commandName operationId)rrrrrrr2retryable_writes_supportedrrrrrr=r<rrrrrrr4r)rrrrsessions_supportedrs rrz!_ClientConnectionRetryable._write+ s   I!%!1!1!33DL||--dllDMMJ N Nd#'#8#8 MM/ 00KK/..# !NN )**,&+DO>>'"@AUAU@V W!%!@!@!M!M$(OO$($6$6 "ZZ tT__MM+ N N N4 N*N+ N N N N, ?? &s,r?pymongo.messager@rArBpymongo.monitoringrCrDpymongo.operationsrErFrGrHrIrJrKpymongo.read_preferencesrLrMpymongo.resultsrNpymongo.server_descriptionrOpymongo.server_selectorsrPpymongo.server_typerQpymongo.topology_descriptionrRrSpymongo.typingsrTrUrVrWrXrYpymongo.uri_parser_sharedrZr[r\r]r^r_r`pymongo.write_concernrarbtypesrc bson.objectidrdpymongo.asynchronous.bulkrerfrgpymongo.asynchronous.cursorrhrrjpymongo.asynchronous.poolrkpymongo.asynchronous.serverrlpymongo.read_concernrmpymongo.responsernrorpr _WriteCall _ReadCallr_WriteOp BaseObjectrrrrrrrrregister_at_forkrrrr"s$# #*QP$DDEEZ=CB:A0*     =<FA18=+KF#&4V>:920)2 CL  "#%6=ycST?UU   "#X/@+N c3k        \%:v(('-*@\%:~J  =FP4P4fXRXRv 2B'89 r