kover 2.2.0__tar.gz → 2.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. {kover-2.2.0 → kover-2.6.0}/.gitignore +3 -1
  2. {kover-2.2.0 → kover-2.6.0}/PKG-INFO +11 -6
  3. {kover-2.2.0 → kover-2.6.0}/README.md +4 -3
  4. {kover-2.2.0 → kover-2.6.0}/kover/__init__.py +5 -6
  5. kover-2.6.0/kover/_internals/__init__.py +7 -0
  6. {kover-2.2.0 → kover-2.6.0}/kover/_internals/_mixins.py +4 -1
  7. {kover-2.2.0 → kover-2.6.0}/kover/_internals/_serializers.py +22 -10
  8. kover-2.6.0/kover/client.py +431 -0
  9. kover-2.6.0/kover/codes.py +533 -0
  10. {kover-2.2.0 → kover-2.6.0}/kover/collection.py +126 -282
  11. {kover-2.2.0 → kover-2.6.0}/kover/cursor.py +11 -62
  12. {kover-2.2.0 → kover-2.6.0}/kover/database.py +55 -140
  13. {kover-2.2.0 → kover-2.6.0}/kover/exceptions.py +4 -0
  14. {kover-2.2.0 → kover-2.6.0}/kover/gridfs/__init__.py +2 -5
  15. {kover-2.2.0 → kover-2.6.0}/kover/gridfs/gridfs.py +27 -63
  16. kover-2.2.0/kover/utils.py → kover-2.6.0/kover/helpers.py +17 -13
  17. {kover-2.2.0 → kover-2.6.0}/kover/metadata/__init__.py +2 -2
  18. {kover-2.2.0 → kover-2.6.0}/kover/metadata/definitions.py +13 -13
  19. {kover-2.2.0 → kover-2.6.0}/kover/models/__init__.py +6 -3
  20. kover-2.2.0/kover/gridfs/models.py → kover-2.6.0/kover/models/gridfs.py +10 -20
  21. {kover-2.2.0 → kover-2.6.0}/kover/models/operations.py +2 -2
  22. {kover-2.2.0 → kover-2.6.0}/kover/models/other.py +17 -8
  23. kover-2.2.0/kover/models/replica_set.py → kover-2.6.0/kover/models/replset.py +2 -2
  24. kover-2.6.0/kover/network/__init__.py +14 -0
  25. {kover-2.2.0 → kover-2.6.0}/kover/network/auth.py +38 -49
  26. kover-2.6.0/kover/network/compressors.py +74 -0
  27. kover-2.6.0/kover/network/resolver.py +15 -0
  28. kover-2.6.0/kover/network/transport.py +125 -0
  29. kover-2.6.0/kover/network/wirehelper.py +223 -0
  30. {kover-2.2.0 → kover-2.6.0}/kover/schema.py +44 -57
  31. {kover-2.2.0 → kover-2.6.0}/kover/session.py +18 -47
  32. kover-2.6.0/kover/typings.py +29 -0
  33. {kover-2.2.0 → kover-2.6.0}/pyproject.toml +14 -16
  34. kover-2.6.0/requirements.txt +3 -0
  35. kover-2.2.0/kover/_internals/__init__.py +0 -7
  36. kover-2.2.0/kover/client.py +0 -460
  37. kover-2.2.0/kover/codes.py +0 -104
  38. kover-2.2.0/kover/network/__init__.py +0 -10
  39. kover-2.2.0/kover/network/msocket.py +0 -199
  40. kover-2.2.0/kover/network/saslprep.py +0 -116
  41. kover-2.2.0/kover/network/serializer.py +0 -124
  42. kover-2.2.0/kover/typings.py +0 -18
  43. kover-2.2.0/requirements.txt +0 -2
  44. {kover-2.2.0 → kover-2.6.0}/CODE_OF_CONDUCT.md +0 -0
  45. {kover-2.2.0 → kover-2.6.0}/LICENSE +0 -0
  46. {kover-2.2.0 → kover-2.6.0}/kover/bson/__init__.py +0 -0
  47. {kover-2.2.0 → kover-2.6.0}/kover/bson/_helpers.py +0 -0
  48. {kover-2.2.0 → kover-2.6.0}/kover/bson/binary.py +0 -0
  49. {kover-2.2.0 → kover-2.6.0}/kover/bson/code.py +0 -0
  50. {kover-2.2.0 → kover-2.6.0}/kover/bson/codec_options.py +0 -0
  51. {kover-2.2.0 → kover-2.6.0}/kover/bson/datetime_ms.py +0 -0
  52. {kover-2.2.0 → kover-2.6.0}/kover/bson/dbref.py +0 -0
  53. {kover-2.2.0 → kover-2.6.0}/kover/bson/decimal128.py +0 -0
  54. {kover-2.2.0 → kover-2.6.0}/kover/bson/errors.py +0 -0
  55. {kover-2.2.0 → kover-2.6.0}/kover/bson/int64.py +0 -0
  56. {kover-2.2.0 → kover-2.6.0}/kover/bson/json_util.py +0 -0
  57. {kover-2.2.0 → kover-2.6.0}/kover/bson/max_key.py +0 -0
  58. {kover-2.2.0 → kover-2.6.0}/kover/bson/min_key.py +0 -0
  59. {kover-2.2.0 → kover-2.6.0}/kover/bson/objectid.py +0 -0
  60. {kover-2.2.0 → kover-2.6.0}/kover/bson/raw_bson.py +0 -0
  61. {kover-2.2.0 → kover-2.6.0}/kover/bson/regex.py +0 -0
  62. {kover-2.2.0 → kover-2.6.0}/kover/bson/son.py +0 -0
  63. {kover-2.2.0 → kover-2.6.0}/kover/bson/timestamp.py +0 -0
  64. {kover-2.2.0 → kover-2.6.0}/kover/bson/typings.py +0 -0
  65. {kover-2.2.0 → kover-2.6.0}/kover/bson/tz_util.py +0 -0
  66. {kover-2.2.0 → kover-2.6.0}/kover/enums.py +0 -0
  67. {kover-2.2.0 → kover-2.6.0}/kover/gridfs/exceptions.py +0 -0
  68. {kover-2.2.0 → kover-2.6.0}/kover/py.typed +0 -0
@@ -8,4 +8,6 @@ badges.txt
8
8
  dist
9
9
  .ruff_cache
10
10
  .python-version
11
- .token
11
+ .token
12
+ uv.lock
13
+ kover/bulk
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: kover
3
- Version: 2.2.0
3
+ Version: 2.6.0
4
4
  Summary: Fully async mongodb driver for mongod and replica sets.
5
5
  Project-URL: Repository, https://github.com/megawattka/kover
6
6
  Project-URL: Documentation, https://github.com/megawattka/kover
7
7
  Author-email: megawattka <gunter56741@gmail.com>
8
8
  License-Expression: MIT
9
9
  License-File: LICENSE
10
- Keywords: Kover API mongo,Mongo Kover,async driver,kover,kover mongodb,megawattka,mongo async,mongo kover,mongod driver,mongodb
10
+ Keywords: Kover API mongo,Mongo Kover,async driver,kover,kover mongodb,mongo async,mongo kover,mongod driver,mongodb
11
11
  Classifier: Development Status :: 4 - Beta
12
12
  Classifier: Intended Audience :: Developers
13
13
  Classifier: License :: OSI Approved :: MIT License
@@ -19,9 +19,13 @@ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
19
  Classifier: Topic :: Software Development :: Quality Assurance
20
20
  Classifier: Typing :: Typed
21
21
  Requires-Python: >=3.10
22
- Requires-Dist: dnspython<3.0.0,>=1.16.0
22
+ Requires-Dist: dnspython>=2.7.0
23
23
  Requires-Dist: pydantic>=2.10.6
24
24
  Requires-Dist: typing-extensions>=4.12.2
25
+ Provides-Extra: snappy
26
+ Requires-Dist: python-snappy; extra == 'snappy'
27
+ Provides-Extra: zstd
28
+ Requires-Dist: zstd; extra == 'zstd'
25
29
  Description-Content-Type: text/markdown
26
30
 
27
31
  # kover
@@ -33,7 +37,7 @@ Description-Content-Type: text/markdown
33
37
  ![Last Commit](https://img.shields.io/github/last-commit/megawattka/kover)
34
38
  ![MongoDB](https://img.shields.io/badge/MongoDB-6.0+-green)
35
39
 
36
- **Kover** is a model-orientied strict typed mongodb driver supporting local mongod and replica sets. Battle tests are still required*<br>
40
+ **Kover** is a model-orientied strictly typed mongodb driver supporting local mongod, replica sets and remote atlases. Battle tests are still required*<br>
37
41
  this library was inspired by <a href=https://github.com/sakal/aiomongo>this project</a> i like it very much. Though its 8 years old.
38
42
  Kover is linted by Ruff and supports pyright strict type checking mode.
39
43
 
@@ -62,14 +66,15 @@ The main reason why i created this project is that Motor - official async wrappe
62
66
 
63
67
  # Status
64
68
  it still missing features. <br>
65
- e.g: **bulk write API** and **Compression**<br>
69
+ e.g: **bulk write API** and **Encryption**
66
70
  but its already very cool! <br>
67
71
 
68
72
  # Dependencies
69
73
  - All platforms.
70
- - python 3.10
74
+ - python 3.10+
71
75
  - MongoDB 6.0+ (not sure about older versions)
72
76
  - pydantic 2.10.6 or later
77
+ - dnspython 2.7.0 or later
73
78
 
74
79
  # Features
75
80
  Almost all features from pymongo. All auth types are supported. Integration with Pydantic supported.
@@ -7,7 +7,7 @@
7
7
  ![Last Commit](https://img.shields.io/github/last-commit/megawattka/kover)
8
8
  ![MongoDB](https://img.shields.io/badge/MongoDB-6.0+-green)
9
9
 
10
- **Kover** is a model-orientied strict typed mongodb driver supporting local mongod and replica sets. Battle tests are still required*<br>
10
+ **Kover** is a model-orientied strictly typed mongodb driver supporting local mongod, replica sets and remote atlases. Battle tests are still required*<br>
11
11
  this library was inspired by <a href=https://github.com/sakal/aiomongo>this project</a> i like it very much. Though its 8 years old.
12
12
  Kover is linted by Ruff and supports pyright strict type checking mode.
13
13
 
@@ -36,14 +36,15 @@ The main reason why i created this project is that Motor - official async wrappe
36
36
 
37
37
  # Status
38
38
  it still missing features. <br>
39
- e.g: **bulk write API** and **Compression**<br>
39
+ e.g: **bulk write API** and **Encryption**
40
40
  but its already very cool! <br>
41
41
 
42
42
  # Dependencies
43
43
  - All platforms.
44
- - python 3.10
44
+ - python 3.10+
45
45
  - MongoDB 6.0+ (not sure about older versions)
46
46
  - pydantic 2.10.6 or later
47
+ - dnspython 2.7.0 or later
47
48
 
48
49
  # Features
49
50
  Almost all features from pymongo. All auth types are supported. Integration with Pydantic supported.
@@ -20,8 +20,8 @@
20
20
  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  # SOFTWARE.
22
22
 
23
- __version__ = "2.2.0"
24
- __author__ = "oMegaPB"
23
+ __version__ = "2.6.0"
24
+ __author__ = "megawattka"
25
25
  __license__ = "MIT"
26
26
  __copyright__ = "Copyright (C) 2024-present megawattka"
27
27
 
@@ -41,6 +41,7 @@ from .exceptions import (
41
41
  OperationFailure,
42
42
  SchemaGenerationException,
43
43
  )
44
+ from .helpers import chain, filter_non_null, maybe_to_dict
44
45
  from .models import (
45
46
  BuildInfo,
46
47
  Collation,
@@ -59,9 +60,8 @@ from .network import AuthCredentials
59
60
  from .schema import Document, SchemaGenerator
60
61
  from .session import Session, Transaction
61
62
  from .typings import xJsonT
62
- from .utils import HasToDict, chain, filter_non_null, maybe_to_dict
63
63
 
64
- __all__ = [
64
+ __all__ = (
65
65
  "AuthCredentials",
66
66
  "BuildInfo",
67
67
  "Collation",
@@ -73,7 +73,6 @@ __all__ = [
73
73
  "Database",
74
74
  "Delete",
75
75
  "Document",
76
- "HasToDict",
77
76
  "HelloResult",
78
77
  "Index",
79
78
  "IndexDirection",
@@ -96,4 +95,4 @@ __all__ = [
96
95
  "filter_non_null",
97
96
  "maybe_to_dict",
98
97
  "xJsonT",
99
- ]
98
+ )
@@ -0,0 +1,7 @@
1
+ from ._mixins import EmptyReprMixin
2
+ from ._serializers import value_to_json_schema
3
+
4
+ __all__ = (
5
+ "EmptyReprMixin",
6
+ "value_to_json_schema",
7
+ )
@@ -9,7 +9,7 @@ if TYPE_CHECKING:
9
9
  from ..typings import xJsonT
10
10
 
11
11
 
12
- class ReprMixin:
12
+ class EmptyReprMixin:
13
13
  def __repr__(self) -> str:
14
14
  return f"{self.__class__.__name__}()"
15
15
 
@@ -30,3 +30,6 @@ class ModelMixin(BaseModel):
30
30
  def to_dict(self) -> xJsonT:
31
31
  """Convert the model to a dictionary with camel case keys."""
32
32
  return self.model_dump(by_alias=True, exclude_none=True)
33
+
34
+ def __str__(self) -> str:
35
+ return self.__repr__()
@@ -8,11 +8,14 @@ from typing import (
8
8
  Literal,
9
9
  get_origin,
10
10
  )
11
+ from typing import is_typeddict as t_is_typeddict
11
12
  from uuid import UUID
12
13
 
14
+ from typing_extensions import is_typeddict as te_is_typeddict
15
+
13
16
  from ..bson import Binary, Int64, ObjectId, Timestamp
14
- from ..exceptions import UnsupportedAnnotation
15
- from ..utils import chain
17
+ from ..exceptions import SchemaGenerationException, UnsupportedAnnotation
18
+ from ..helpers import chain
16
19
 
17
20
  if TYPE_CHECKING:
18
21
  from types import UnionType
@@ -60,20 +63,27 @@ def _serialize_literal(
60
63
  }
61
64
 
62
65
 
66
+ def _is_typeddict_ex(attr_t: type[object]) -> bool:
67
+ return t_is_typeddict(attr_t) or te_is_typeddict(attr_t)
68
+
69
+
63
70
  # passing type data to dict unsupported and ignored
64
71
  # use Document for that
65
72
  # in that case it just creates AnyDict
66
73
  # accepting any data passed to it. e.g custom metadata
67
- # TODO @megawattka: probably add something here?
74
+ # TODO @megawattka: TypedDict support
68
75
  def _serialize_dict(
69
- attr_t: type[object], # noqa: ARG001
76
+ attr_t: type[object],
70
77
  /,
71
78
  *,
72
79
  is_optional: bool = False,
73
80
  ) -> xJsonT:
74
- return {
75
- "bsonType": ["object"] + (["null"] if is_optional else []),
76
- }
81
+ if not _is_typeddict_ex(attr_t):
82
+ return {
83
+ "bsonType": ["object"] + (["null"] if is_optional else []),
84
+ }
85
+ comment = "TypedDict currently not supported. Use Document."
86
+ raise SchemaGenerationException(comment)
77
87
 
78
88
 
79
89
  def _serialize_enum(
@@ -105,12 +115,15 @@ def _serialize_simple_type(
105
115
 
106
116
 
107
117
  def value_to_json_schema(
108
- attr_t: object,
118
+ attr_t: type[object],
109
119
  /,
110
120
  *,
111
121
  is_optional: bool = False,
112
122
  ) -> xJsonT | None:
113
123
  origin = get_origin(attr_t)
124
+ if origin is None and _is_typeddict_ex(attr_t):
125
+ origin = dict
126
+
114
127
  func = None
115
128
  origin_map: dict[Any, Any] = {
116
129
  Literal: _serialize_literal,
@@ -119,12 +132,11 @@ def value_to_json_schema(
119
132
  if origin in origin_map:
120
133
  func = origin_map[origin] # type: ignore
121
134
 
122
- elif isinstance(attr_t, type) and issubclass(attr_t, Enum):
135
+ elif isinstance(attr_t, type) and issubclass(attr_t, Enum): # type: ignore
123
136
  func = _serialize_enum
124
137
 
125
138
  elif attr_t in _TYPE_MAP:
126
139
  func = _serialize_simple_type
127
-
128
140
  if func is not None:
129
141
  return func(attr_t, is_optional=is_optional) # type: ignore
130
142
 
@@ -0,0 +1,431 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import json
5
+ import random
6
+ import ssl
7
+ from typing import TYPE_CHECKING, Literal, cast
8
+ from urllib.parse import parse_qs, urlparse
9
+
10
+ from typing_extensions import Self
11
+
12
+ from .database import Database
13
+ from .helpers import classrepr, filter_non_null, maybe_to_dict
14
+ from .models import BuildInfo
15
+ from .network import Auth, AuthCredentials, MongoTransport, SrvResolver
16
+ from .session import Session
17
+
18
+ if TYPE_CHECKING:
19
+ from .models import ReplicaSetConfig
20
+ from .typings import COMPRESSION_T, xJsonT
21
+
22
+
23
+ @classrepr("signature", "transport", "is_primary")
24
+ class Kover:
25
+ """Kover client for interacting with a MongoDB server.
26
+
27
+ Attributes:
28
+ transport : The underlying transport to the MongoDB server.
29
+ signature : The authentication signature, if authenticated.
30
+ default_database : The name of the default database.
31
+ is_primary : The flag that tells us whether that
32
+ this is primary or secondary instance
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ transport: MongoTransport,
38
+ signature: bytes | None,
39
+ default_database: str | None = None,
40
+ *,
41
+ is_primary: bool = False,
42
+ ) -> None:
43
+ self.transport = transport
44
+ self.signature = signature
45
+ self._default_database = default_database
46
+ self._is_primary = is_primary
47
+
48
+ async def __aenter__(self) -> Self:
49
+ return self
50
+
51
+ async def __aexit__(self, *exc: object) -> bool:
52
+ if self.signature is not None:
53
+ await self.logout()
54
+ await self.close()
55
+ return True
56
+
57
+ @property
58
+ def is_primary(self) -> bool:
59
+ """Whether this instance is a primary or not."""
60
+ return self._is_primary
61
+
62
+ async def close(self) -> None:
63
+ """Close the underlying transport connection.
64
+
65
+ This method closes the transport writer
66
+ and waits until the connection is fully closed.
67
+ """
68
+ self.transport.writer.close()
69
+ await self.transport.writer.wait_closed()
70
+
71
+ def get_database(self, name: str) -> Database:
72
+ """Get a Database instance for the specified database name.
73
+
74
+ Parameters:
75
+ name : The name of the database to retrieve.
76
+
77
+ Returns:
78
+ An instance of the Database class for the given name.
79
+ """
80
+ return Database(name=name, client=self)
81
+
82
+ def __getattr__(self, name: str) -> Database:
83
+ return self.get_database(name=name)
84
+
85
+ @classmethod
86
+ async def from_uri(cls, uri: str) -> Kover:
87
+ """Create an instance of Kover client by passing a uri."""
88
+ parts = urlparse(uri)
89
+ if parts.hostname is None:
90
+ raise ValueError("Incorrect uri passed.")
91
+
92
+ parameters = parse_qs(parts.query)
93
+
94
+ tls = parameters.get("tls", ["true"])[0] == "true"
95
+ default_database = parts.path[1:] if len(parts.path) > 1 else None
96
+ app_name = parameters.get("appName", [None])[0]
97
+
98
+ if parts.username is not None and parts.password is not None:
99
+ credentials = AuthCredentials(
100
+ username=parts.username,
101
+ password=parts.password,
102
+ )
103
+ else:
104
+ credentials = None
105
+
106
+ resolver = SrvResolver()
107
+ nodes = await resolver.get_nodes(parts.hostname)
108
+ compressors = parameters.get("compressors", [])
109
+ if compressors:
110
+ compressors = compressors[0].split(",")
111
+
112
+ # TODO @megawattka: proper primary discovery.
113
+ clients = await asyncio.gather(*[cls.make_client(
114
+ node,
115
+ parts.port or 27017,
116
+ credentials=credentials,
117
+ compression=cast("COMPRESSION_T", compressors),
118
+ tls=tls,
119
+ default_database=default_database,
120
+ application={"name": app_name},
121
+ ) for node in nodes])
122
+
123
+ return next(filter(lambda k: k.is_primary, clients))
124
+
125
+ @classmethod
126
+ async def make_client(
127
+ cls,
128
+ host: str = "127.0.0.1",
129
+ port: int = 27017,
130
+ *,
131
+ credentials: AuthCredentials | None = None,
132
+ loop: asyncio.AbstractEventLoop | None = None,
133
+ compression: COMPRESSION_T | None = None,
134
+ default_database: str | None = None,
135
+ tls: bool = False,
136
+ application: xJsonT | None = None,
137
+ ) -> Kover:
138
+ """Create and return a new Kover client instance.
139
+
140
+ Parameters:
141
+ host : The hostname of the MongoDB server, by default "127.0.0.1".
142
+ port : The port number of the MongoDB server, by default 27017.
143
+ credentials : Authentication credentials, if required.
144
+ loop : The event loop to use for asynchronous operations.
145
+ compression : List of compression options.
146
+ default_database : the name of a database that will be returned
147
+ by Kover.get_default_database().
148
+ tls : the boolean value that indicated whether to use tls or no.
149
+ application : document that will be included in hello payload
150
+ under the "application" field.
151
+
152
+ Returns:
153
+ An instance of the Kover client.
154
+ """
155
+ ssl_ctx = ssl.create_default_context() if tls else None
156
+ transport = await MongoTransport.make(
157
+ host=host,
158
+ port=port,
159
+ loop=loop,
160
+ ssl_ctx=ssl_ctx,
161
+ )
162
+ hello = await transport.hello(
163
+ credentials=credentials,
164
+ compression=compression,
165
+ application=application,
166
+ )
167
+ if hello.requires_auth and credentials:
168
+ mechanism = random.choice(hello.sasl_supported_mechs or []) # noqa: S311
169
+ signature = await Auth(transport).create(mechanism, credentials)
170
+ else:
171
+ signature = None
172
+
173
+ if hello.compression:
174
+ transport.set_compressor(hello.compression[0])
175
+
176
+ return cls(
177
+ transport,
178
+ signature,
179
+ default_database,
180
+ is_primary=hello.is_primary,
181
+ )
182
+
183
+ def get_default_database(self) -> Database:
184
+ """Get the default database if default name was provided.
185
+
186
+ Returns:
187
+ An instance of `Database` with specified default name
188
+ """
189
+ if self._default_database is not None:
190
+ return self.get_database(self._default_database)
191
+
192
+ message = "Cannot get the default database. "
193
+ message += "No default name was provided."
194
+ raise ValueError(message)
195
+
196
+ async def refresh_sessions(self, sessions: list[Session]) -> None:
197
+ """Refresh the provided list of sessions.
198
+
199
+ Parameters:
200
+ sessions : A list of Session objects to be refreshed.
201
+ """
202
+ documents: list[xJsonT] = [x.document for x in sessions]
203
+ await self.transport.request({"refreshSessions": documents})
204
+
205
+ async def end_sessions(self, sessions: list[Session]) -> None:
206
+ """End the provided list of sessions.
207
+
208
+ Parameters:
209
+ sessions : A list of Session objects to be ended.
210
+ """
211
+ documents: list[xJsonT] = [x.document for x in sessions]
212
+ await self.transport.request({"endSessions": documents})
213
+
214
+ async def start_session(self) -> Session:
215
+ """Start a new session.
216
+
217
+ Returns:
218
+ An instance of the Session class representing the started session.
219
+ """
220
+ req = await self.transport.request({"startSession": 1.0})
221
+ return Session(document=req["id"], transport=self.transport)
222
+
223
+ async def build_info(self) -> BuildInfo:
224
+ """Retrieve build information from the MongoDB server.
225
+
226
+ Returns:
227
+ An instance of BuildInfo containing server build details.
228
+ """
229
+ request = await self.transport.request({"buildInfo": 1.0})
230
+ return BuildInfo.model_validate(request)
231
+
232
+ async def logout(self) -> None:
233
+ """Log out the current user session.
234
+
235
+ This method sends a logout request to the server
236
+ to terminate the current authenticated session.
237
+ """
238
+ await self.transport.request({"logout": 1.0})
239
+
240
+ async def list_database_names(self) -> list[str]:
241
+ """Retrieve the names of all databases on the MongoDB server.
242
+
243
+ Returns:
244
+ A list containing the names of all databases.
245
+ """
246
+ command: xJsonT = {
247
+ "listDatabases": 1.0,
248
+ "nameOnly": True # noqa: COM812
249
+ }
250
+ request = await self.transport.request(command)
251
+ return [x["name"] for x in request["databases"]]
252
+
253
+ async def drop_database(self, name: str) -> None:
254
+ """Drop the specified database from the MongoDB server.
255
+
256
+ Parameters:
257
+ name : The name of the database to drop.
258
+ """
259
+ await self.transport.request({"dropDatabase": 1.0}, db_name=name)
260
+
261
+ # https://www.mongodb.com/docs/manual/reference/command/replSetInitiate/
262
+ async def replica_set_initiate(
263
+ self,
264
+ config: ReplicaSetConfig | None = None,
265
+ ) -> None:
266
+ """Initiate a replica set with the provided configuration.
267
+
268
+ Parameters:
269
+ config : The configuration document for the replica set. If None,
270
+ default configuration is used.
271
+ """
272
+ document = maybe_to_dict(config) or {}
273
+ await self.transport.request({"replSetInitiate": document})
274
+
275
+ # https://www.mongodb.com/docs/manual/reference/command/replSetReconfig/
276
+ async def replica_set_reconfig(
277
+ self,
278
+ config: ReplicaSetConfig,
279
+ *,
280
+ force: bool = False,
281
+ max_time_ms: int | None = None,
282
+ ) -> None:
283
+ """Perform Reconfiguration of a replica set.
284
+
285
+ Parameters:
286
+ config : The configuration document for the replica set.
287
+ """
288
+ document: xJsonT = filter_non_null({
289
+ "replSetReconfig": maybe_to_dict(config) or {},
290
+ "force": force,
291
+ "maxTimeMS": max_time_ms,
292
+ })
293
+ await self.transport.request(document)
294
+
295
+ # https://www.mongodb.com/docs/manual/reference/command/replSetGetStatus/
296
+ async def get_replica_set_status(self) -> xJsonT:
297
+ """Retrieve the status of the replica set.
298
+
299
+ Returns:
300
+ A JSON document containing the replica set status information.
301
+ """
302
+ return await self.transport.request({"replSetGetStatus": 1.0})
303
+
304
+ # https://www.mongodb.com/docs/manual/reference/command/shutdown/
305
+ async def shutdown(
306
+ self,
307
+ *,
308
+ force: bool = False,
309
+ timeout: int | None = None,
310
+ comment: str | None = None,
311
+ ) -> None:
312
+ """Shut down the MongoDB server.
313
+
314
+ Parameters:
315
+ force : Whether to force the shutdown, by default False.
316
+ timeout : Timeout in seconds before shutdown, by default None.
317
+ comment : Optional comment for the shutdown command.
318
+ """
319
+ command = filter_non_null({
320
+ "shutdown": 1.0,
321
+ "force": force,
322
+ "timeoutSecs": timeout,
323
+ "comment": comment,
324
+ })
325
+ await self.transport.request(command, wait_response=False)
326
+
327
+ # https://www.mongodb.com/docs/manual/reference/command/getCmdLineOpts/
328
+ async def get_commandline(self) -> list[str]:
329
+ """Retrieve the command line args used to start the MongoDB server.
330
+
331
+ Returns:
332
+ A list of command line arguments.
333
+ """
334
+ r = await self.transport.request({"getCmdLineOpts": 1.0})
335
+ return r["argv"]
336
+
337
+ # https://www.mongodb.com/docs/manual/reference/command/getLog/#getlog
338
+ async def get_log(
339
+ self,
340
+ parameter: Literal["global", "startupWarnings"] = "startupWarnings",
341
+ ) -> list[xJsonT]:
342
+ """Retrieve log entries from the MongoDB server.
343
+
344
+ Parameters:
345
+ parameter : The log type to retrieve,
346
+ defaults to "startupWarnings".
347
+
348
+ Returns:
349
+ A list of log entries as JSON objects.
350
+ """
351
+ r = await self.transport.request({"getLog": parameter})
352
+ return [
353
+ json.loads(info) for info in r["log"]
354
+ ]
355
+
356
+ # https://www.mongodb.com/docs/manual/reference/command/renameCollection/
357
+ async def rename_collection(
358
+ self,
359
+ target: str,
360
+ *,
361
+ new_name: str,
362
+ drop_target: bool = False,
363
+ comment: str | None = None,
364
+ ) -> None:
365
+ """Rename a collection in the MongoDB server.
366
+
367
+ Parameters:
368
+ target : The full name of the source collection to rename.
369
+ new_name : The new name for the collection.
370
+ drop_target : Whether to drop the target collection if it exists,
371
+ by default False.
372
+ comment : Optional comment for the rename operation.
373
+ """
374
+ command = filter_non_null({
375
+ "renameCollection": target,
376
+ "to": new_name,
377
+ "dropTarget": drop_target,
378
+ "comment": comment,
379
+ })
380
+ await self.transport.request(command)
381
+
382
+ # https://www.mongodb.com/docs/manual/reference/command/setUserWriteBlockMode/
383
+ async def set_user_write_block_mode(self, *, param: bool) -> None:
384
+ """Set the user write block mode on the MongoDB server.
385
+
386
+ Parameters:
387
+ param : Blocks writes on a cluster when set to true.
388
+ To enable writes on a cluster, set global: false.
389
+ """
390
+ await self.transport.request({
391
+ "setUserWriteBlockMode": 1.0,
392
+ "global": param,
393
+ })
394
+
395
+ # https://www.mongodb.com/docs/manual/reference/command/fsync/
396
+ async def fsync(
397
+ self,
398
+ *,
399
+ timeout: int = 90000,
400
+ lock: bool = True,
401
+ comment: str | None = None,
402
+ ) -> None:
403
+ """Flush all pending writes to disk and optionally lock the database.
404
+
405
+ Parameters:
406
+ timeout : Timeout in milliseconds for acquiring the
407
+ fsync lock, by default 90000.
408
+ lock : Whether to lock the database after flushing,
409
+ by default True.
410
+ comment : Optional comment for the fsync operation.
411
+ """
412
+ command = filter_non_null({
413
+ "fsync": 1.0,
414
+ "fsyncLockAcquisitionTimeoutMillis": timeout,
415
+ "lock": lock,
416
+ "comment": comment,
417
+ })
418
+ await self.transport.request(command)
419
+
420
+ # https://www.mongodb.com/docs/manual/reference/command/fsyncUnlock/
421
+ async def fsync_unlock(self, comment: str | None = None) -> None:
422
+ """Unlock the database after a previous fsync lock operation.
423
+
424
+ Parameters:
425
+ comment : Optional comment for the fsync unlock operation.
426
+ """
427
+ command = filter_non_null({
428
+ "fsyncUnlock": 1.0,
429
+ "comment": comment,
430
+ })
431
+ await self.transport.request(command)