sendproof-core 0.1.0a1__py3-none-any.whl

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 (209) hide show
  1. sendproof_core/__init__.py +56 -0
  2. sendproof_core/assets.py +71 -0
  3. sendproof_core/capture.py +416 -0
  4. sendproof_core/effects.py +79 -0
  5. sendproof_core/identity.py +22 -0
  6. sendproof_core/jsonsafe.py +103 -0
  7. sendproof_core/limits.py +24 -0
  8. sendproof_core/marker.py +131 -0
  9. sendproof_core/options.py +129 -0
  10. sendproof_core/protocol.py +132 -0
  11. sendproof_core/provider.py +121 -0
  12. sendproof_core/py.typed +0 -0
  13. sendproof_core/redaction.py +88 -0
  14. sendproof_core/scope.py +146 -0
  15. sendproof_core/stores/__init__.py +119 -0
  16. sendproof_core/stores/base.py +99 -0
  17. sendproof_core/stores/cassandra_hook.py +173 -0
  18. sendproof_core/stores/classify.py +153 -0
  19. sendproof_core/stores/classify_batch_two.py +397 -0
  20. sendproof_core/stores/cosmos_hook.py +214 -0
  21. sendproof_core/stores/dynamodb_hook.py +214 -0
  22. sendproof_core/stores/elasticsearch_hook.py +248 -0
  23. sendproof_core/stores/firestore_hook.py +459 -0
  24. sendproof_core/stores/guard.py +205 -0
  25. sendproof_core/stores/mongo_hook.py +1406 -0
  26. sendproof_core/stores/redis_hook.py +536 -0
  27. sendproof_core/stores/tables.py +1486 -0
  28. sendproof_core/stores/versions.py +46 -0
  29. sendproof_core/sync_engine.py +308 -0
  30. sendproof_core/trace_store.py +92 -0
  31. sendproof_core/txguard.py +237 -0
  32. sendproof_core/ui/action-bar.js +91 -0
  33. sendproof_core/ui/api.js +239 -0
  34. sendproof_core/ui/app.css +848 -0
  35. sendproof_core/ui/app.js +742 -0
  36. sendproof_core/ui/autofill.js +137 -0
  37. sendproof_core/ui/code-copy.js +71 -0
  38. sendproof_core/ui/code-picker.js +149 -0
  39. sendproof_core/ui/commands.js +197 -0
  40. sendproof_core/ui/components.js +77 -0
  41. sendproof_core/ui/context-bar.js +82 -0
  42. sendproof_core/ui/copy.js +92 -0
  43. sendproof_core/ui/coverage-popover.js +35 -0
  44. sendproof_core/ui/crumb-fit.js +80 -0
  45. sendproof_core/ui/deprecation.js +164 -0
  46. sendproof_core/ui/display-settings.js +175 -0
  47. sendproof_core/ui/doc-diff.js +209 -0
  48. sendproof_core/ui/docs-view.js +347 -0
  49. sendproof_core/ui/favicon.png +0 -0
  50. sendproof_core/ui/favicon.svg +1 -0
  51. sendproof_core/ui/field-help.js +52 -0
  52. sendproof_core/ui/field-modules.js +23 -0
  53. sendproof_core/ui/fields/controls.js +179 -0
  54. sendproof_core/ui/fields/dom.js +36 -0
  55. sendproof_core/ui/fields/infer.js +71 -0
  56. sendproof_core/ui/fields/lookup-source.js +63 -0
  57. sendproof_core/ui/fields/lookup.js +285 -0
  58. sendproof_core/ui/fields/render.js +496 -0
  59. sendproof_core/ui/fields/select.js +175 -0
  60. sendproof_core/ui/fields/validate.js +363 -0
  61. sendproof_core/ui/fields/validation-formats.js +164 -0
  62. sendproof_core/ui/fields/validation-references.js +68 -0
  63. sendproof_core/ui/fields/validation-values.js +137 -0
  64. sendproof_core/ui/generate-menu.js +44 -0
  65. sendproof_core/ui/generate.js +184 -0
  66. sendproof_core/ui/header-editor.js +777 -0
  67. sendproof_core/ui/headers.js +188 -0
  68. sendproof_core/ui/highlight.js +257 -0
  69. sendproof_core/ui/history-popover.js +24 -0
  70. sendproof_core/ui/i18n.js +253 -0
  71. sendproof_core/ui/icons.js +87 -0
  72. sendproof_core/ui/index.html +70 -0
  73. sendproof_core/ui/issues.js +187 -0
  74. sendproof_core/ui/json-view.js +166 -0
  75. sendproof_core/ui/lang-icons.js +62 -0
  76. sendproof_core/ui/layout.js +262 -0
  77. sendproof_core/ui/listbox.js +334 -0
  78. sendproof_core/ui/locales/ar-capture.js +366 -0
  79. sendproof_core/ui/locales/ar-stores.js +116 -0
  80. sendproof_core/ui/locales/ar.js +561 -0
  81. sendproof_core/ui/locales/cs-capture.js +442 -0
  82. sendproof_core/ui/locales/cs-stores.js +116 -0
  83. sendproof_core/ui/locales/cs.js +689 -0
  84. sendproof_core/ui/locales/da-capture.js +347 -0
  85. sendproof_core/ui/locales/da-stores.js +116 -0
  86. sendproof_core/ui/locales/da.js +522 -0
  87. sendproof_core/ui/locales/de-capture.js +347 -0
  88. sendproof_core/ui/locales/de-stores.js +116 -0
  89. sendproof_core/ui/locales/de.js +519 -0
  90. sendproof_core/ui/locales/el-capture.js +347 -0
  91. sendproof_core/ui/locales/el-stores.js +116 -0
  92. sendproof_core/ui/locales/el.js +520 -0
  93. sendproof_core/ui/locales/en-capture.js +349 -0
  94. sendproof_core/ui/locales/en-stores.js +95 -0
  95. sendproof_core/ui/locales/en.js +522 -0
  96. sendproof_core/ui/locales/es-capture.js +353 -0
  97. sendproof_core/ui/locales/es-stores.js +116 -0
  98. sendproof_core/ui/locales/es.js +525 -0
  99. sendproof_core/ui/locales/fa-capture.js +348 -0
  100. sendproof_core/ui/locales/fa-stores.js +116 -0
  101. sendproof_core/ui/locales/fa.js +521 -0
  102. sendproof_core/ui/locales/fi-capture.js +347 -0
  103. sendproof_core/ui/locales/fi-stores.js +116 -0
  104. sendproof_core/ui/locales/fi.js +523 -0
  105. sendproof_core/ui/locales/fr-capture.js +353 -0
  106. sendproof_core/ui/locales/fr-stores.js +116 -0
  107. sendproof_core/ui/locales/fr.js +525 -0
  108. sendproof_core/ui/locales/he-capture.js +358 -0
  109. sendproof_core/ui/locales/he-stores.js +116 -0
  110. sendproof_core/ui/locales/he.js +529 -0
  111. sendproof_core/ui/locales/hi-capture.js +348 -0
  112. sendproof_core/ui/locales/hi-stores.js +116 -0
  113. sendproof_core/ui/locales/hi.js +523 -0
  114. sendproof_core/ui/locales/id-capture.js +347 -0
  115. sendproof_core/ui/locales/id-stores.js +116 -0
  116. sendproof_core/ui/locales/id.js +521 -0
  117. sendproof_core/ui/locales/it-capture.js +361 -0
  118. sendproof_core/ui/locales/it-stores.js +116 -0
  119. sendproof_core/ui/locales/it.js +523 -0
  120. sendproof_core/ui/locales/ja-capture.js +346 -0
  121. sendproof_core/ui/locales/ja-stores.js +116 -0
  122. sendproof_core/ui/locales/ja.js +521 -0
  123. sendproof_core/ui/locales/ko-capture.js +346 -0
  124. sendproof_core/ui/locales/ko-stores.js +116 -0
  125. sendproof_core/ui/locales/ko.js +522 -0
  126. sendproof_core/ui/locales/nb-capture.js +349 -0
  127. sendproof_core/ui/locales/nb-stores.js +116 -0
  128. sendproof_core/ui/locales/nb.js +521 -0
  129. sendproof_core/ui/locales/nl-capture.js +355 -0
  130. sendproof_core/ui/locales/nl-stores.js +116 -0
  131. sendproof_core/ui/locales/nl.js +520 -0
  132. sendproof_core/ui/locales/pl-capture.js +432 -0
  133. sendproof_core/ui/locales/pl-stores.js +116 -0
  134. sendproof_core/ui/locales/pl.js +528 -0
  135. sendproof_core/ui/locales/pt-BR-capture.js +350 -0
  136. sendproof_core/ui/locales/pt-BR-stores.js +116 -0
  137. sendproof_core/ui/locales/pt-BR.js +523 -0
  138. sendproof_core/ui/locales/pt-PT-capture.js +350 -0
  139. sendproof_core/ui/locales/pt-PT-stores.js +116 -0
  140. sendproof_core/ui/locales/pt-PT.js +523 -0
  141. sendproof_core/ui/locales/ru-capture.js +437 -0
  142. sendproof_core/ui/locales/ru-stores.js +116 -0
  143. sendproof_core/ui/locales/ru.js +624 -0
  144. sendproof_core/ui/locales/sv-capture.js +349 -0
  145. sendproof_core/ui/locales/sv-stores.js +116 -0
  146. sendproof_core/ui/locales/sv.js +518 -0
  147. sendproof_core/ui/locales/th-capture.js +347 -0
  148. sendproof_core/ui/locales/th-stores.js +116 -0
  149. sendproof_core/ui/locales/th.js +521 -0
  150. sendproof_core/ui/locales/tr-capture.js +348 -0
  151. sendproof_core/ui/locales/tr-stores.js +116 -0
  152. sendproof_core/ui/locales/tr.js +521 -0
  153. sendproof_core/ui/locales/uk-capture.js +442 -0
  154. sendproof_core/ui/locales/uk-stores.js +116 -0
  155. sendproof_core/ui/locales/uk.js +630 -0
  156. sendproof_core/ui/locales/vi-capture.js +346 -0
  157. sendproof_core/ui/locales/vi-stores.js +116 -0
  158. sendproof_core/ui/locales/vi.js +523 -0
  159. sendproof_core/ui/locales/zh-Hans-capture.js +347 -0
  160. sendproof_core/ui/locales/zh-Hans-stores.js +116 -0
  161. sendproof_core/ui/locales/zh-Hans.js +523 -0
  162. sendproof_core/ui/locales/zh-Hant-capture.js +346 -0
  163. sendproof_core/ui/locales/zh-Hant-stores.js +116 -0
  164. sendproof_core/ui/locales/zh-Hant.js +522 -0
  165. sendproof_core/ui/manifest.json +866 -0
  166. sendproof_core/ui/markdown.js +39 -0
  167. sendproof_core/ui/model-view.js +182 -0
  168. sendproof_core/ui/navigation.js +233 -0
  169. sendproof_core/ui/operation-header.js +76 -0
  170. sendproof_core/ui/operations.js +7 -0
  171. sendproof_core/ui/overview-view.js +63 -0
  172. sendproof_core/ui/personas.js +59 -0
  173. sendproof_core/ui/popover.js +71 -0
  174. sendproof_core/ui/preview-false.js +108 -0
  175. sendproof_core/ui/request-editor.js +496 -0
  176. sendproof_core/ui/response-metadata.js +354 -0
  177. sendproof_core/ui/response-viewer.js +618 -0
  178. sendproof_core/ui/result-blocked.js +155 -0
  179. sendproof_core/ui/result-capture.js +25 -0
  180. sendproof_core/ui/result-database.js +185 -0
  181. sendproof_core/ui/result-effects.js +176 -0
  182. sendproof_core/ui/result-headers.js +106 -0
  183. sendproof_core/ui/result-logs.js +408 -0
  184. sendproof_core/ui/result-states.js +213 -0
  185. sendproof_core/ui/results.js +371 -0
  186. sendproof_core/ui/router.js +118 -0
  187. sendproof_core/ui/schema-model.js +336 -0
  188. sendproof_core/ui/schema-tree.js +344 -0
  189. sendproof_core/ui/schema.js +397 -0
  190. sendproof_core/ui/security.js +31 -0
  191. sendproof_core/ui/seeded-menu.js +69 -0
  192. sendproof_core/ui/settings.js +93 -0
  193. sendproof_core/ui/shortcuts-sheet.js +73 -0
  194. sendproof_core/ui/shortcuts.js +190 -0
  195. sendproof_core/ui/sidebar.js +289 -0
  196. sendproof_core/ui/signin.js +259 -0
  197. sendproof_core/ui/snippets.js +530 -0
  198. sendproof_core/ui/store-marks.js +47 -0
  199. sendproof_core/ui/stores.js +131 -0
  200. sendproof_core/ui/styles.css +971 -0
  201. sendproof_core/ui/toggletip.js +53 -0
  202. sendproof_core/ui/uuid.js +10 -0
  203. sendproof_core/ui/view.js +122 -0
  204. sendproof_core/ui/views.css +653 -0
  205. sendproof_core/workbench.py +310 -0
  206. sendproof_core-0.1.0a1.dist-info/METADATA +116 -0
  207. sendproof_core-0.1.0a1.dist-info/RECORD +209 -0
  208. sendproof_core-0.1.0a1.dist-info/WHEEL +4 -0
  209. sendproof_core-0.1.0a1.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1406 @@
1
+ """Sendproof Preview and write guard for MongoDB (``spec/data-stores.md`` "MongoDB in Preview").
2
+
3
+ On a replica set or sharded cluster a Preview runs every command in one transaction that is
4
+ aborted after the handler, and reports document changes. On a standalone server MongoDB cannot
5
+ run transactions, so the store runs in ``guard`` mode like Redis: reads run and the first write
6
+ blocks the Preview.
7
+
8
+ Usage::
9
+
10
+ client = MongoClient(url) # PyMongo or AsyncMongoClient
11
+ catalog = mongo_store(client, name="catalog") # handlers use catalog.client
12
+ app.get("/documents/{id}")(lambda id: catalog.client["shop"]["documents"].find_one({"_id": id}))
13
+
14
+ No MongoDB driver offers a documented pre-send hook, so ``catalog.client`` is a guarded handle:
15
+ ``client[db][collection]`` return handles with the driver's own API. During a Preview each call is
16
+ checked before the driver builds a command:
17
+
18
+ * every call gets the Preview session (``preview`` mode), so the command carries the Preview's
19
+ ``lsid``, ``txnNumber`` and ``autocommit: false``;
20
+ * an explicit session other than the Preview's is refused, failing the Preview with 500;
21
+ * the guard classifies the command the method sends and blocks writes (``guard`` mode) or what a
22
+ transaction cannot run (``preview`` mode);
23
+ * a method the tables below do not list is refused, so a new driver method fails closed.
24
+
25
+ Command monitoring backs the handles up as a **tripwire**: a global ``CommandListener`` sees every
26
+ command of every client created after this module was imported (or given the listener), in the
27
+ request's context. A write during a Preview without the Preview's ``lsid`` and
28
+ ``autocommit: false`` has escaped the transaction and cannot be undone: the Preview fails with 500,
29
+ so no rollback is ever claimed for it. A write that no request accounts for (a thread a handler
30
+ started without its context) while any Preview is open fails every open Preview the same way,
31
+ unless the host marked it :func:`~sendproof_core.detached`. The same listener supplies the ``Db``
32
+ log entries, the change candidates, the snapshot time and the code 263 block.
33
+
34
+ The Preview's driver session carries the transaction, and the driver hands it back on cursors
35
+ (``cursor.session``). Its class is swapped for the Preview, so its ``commit_transaction`` and
36
+ ``abort_transaction`` are refused before anything is sent, whoever holds it.
37
+
38
+ Limits: a client created before this module was imported has no listener and is refused (pass
39
+ ``event_listeners=[mongo_monitor]``); a client whose own detection ``hello`` the listener never
40
+ saw cannot Preview. Motor is refused: it is deprecated in favour of PyMongo's ``AsyncMongoClient``,
41
+ and its thread pool drops ``contextvars``, so the tripwire could not attribute its commands.
42
+ """
43
+
44
+ from __future__ import annotations
45
+
46
+ import asyncio
47
+ import inspect
48
+ import json
49
+ import logging
50
+ import threading
51
+ import time
52
+ import weakref
53
+ from contextvars import ContextVar
54
+ from dataclasses import dataclass, field
55
+ from typing import Any, Callable, Generator, Iterable, Mapping, Optional
56
+
57
+ from bson import json_util
58
+ from pymongo import monitoring
59
+ from pymongo.errors import OperationFailure
60
+ from pymongo.read_concern import ReadConcern
61
+ from pymongo.write_concern import WriteConcern
62
+
63
+ from ..provider import PreviewChange
64
+ from ..scope import RequestScope, attributed, current_scope, open_previews
65
+ from .base import DataStore
66
+ from .classify import READ, SESSION, WRITE, classify_mongo
67
+ from .guard import (
68
+ PreviewTransactionControl,
69
+ current_preview,
70
+ guard,
71
+ read_set,
72
+ refuse_in_preview,
73
+ refuse_unattributed,
74
+ sanitize_document,
75
+ store_label,
76
+ unattributed_write,
77
+ )
78
+
79
+ #: The reason a standalone server, or any reply the binding does not recognise, runs in ``guard`` mode.
80
+ STANDALONE_REASON = "Preview unavailable: this MongoDB server doesn't support transactions"
81
+ #: The reason when the detection ``hello`` could not be sent or answered: whether the server supports
82
+ #: transactions is unknown, so the store runs in ``guard`` mode for now and detects again on the next Preview.
83
+ UNREACHABLE_REASON = ("Preview unavailable: couldn't reach MongoDB to check whether it supports transactions, "
84
+ "so this Preview runs in guard mode")
85
+
86
+ #: The default Preview time limit in seconds: below the server's 60-second
87
+ #: ``transactionLifetimeLimitSeconds``, so the binding, not the server, ends a Preview whose handler
88
+ #: runs too long.
89
+ DEFAULT_PREVIEW_TIMEOUT = 50.0
90
+
91
+
92
+ def refused_reason(operation: str) -> str:
93
+ """The reason for a command MongoDB refuses inside a transaction."""
94
+ return f"Preview unavailable: MongoDB can't run {operation} inside a transaction"
95
+
96
+
97
+ #: Commands the monitoring specification marks security-sensitive: never logged.
98
+ _SENSITIVE = frozenset({"authenticate", "saslstart", "saslcontinue", "getnonce", "createuser", "updateuser",
99
+ "copydbgetnonce", "copydbsaslstart", "copydb"})
100
+ #: Fields the driver adds to every command; they carry no meaning for the log and are dropped.
101
+ _ENVELOPE = frozenset({"lsid", "txnNumber", "autocommit", "startTransaction", "$clusterTime", "$db",
102
+ "$readPreference", "readConcern", "writeConcern", "apiVersion", "apiStrict",
103
+ "apiDeprecationErrors", "maxTimeMS", "comment"})
104
+ #: Most candidate documents read back for change capture in one Preview.
105
+ _CANDIDATE_LIMIT = 1000
106
+ #: Server error codes meaning the collection or snapshot did not exist at the start time.
107
+ _ABSENT_AT_START = frozenset({26, 246}) # NamespaceNotFound, SnapshotUnavailable
108
+ _SYSTEM_DATABASES = frozenset({"admin", "config", "local"})
109
+ _EXTENSION = "sendproof.mongodb"
110
+ #: ``NoSuchTransaction``: the server has no such transaction, so nothing holds its locks.
111
+ _NO_SUCH_TRANSACTION = 251
112
+ #: How long the engine keeps trying to end a Preview transaction whose abort the server never
113
+ #: acknowledged, and the backoff between tries, in seconds: well inside the 60-second lifetime limit.
114
+ _KILL_RETRY_LIMIT = 10.0
115
+ _KILL_FIRST_DELAY = 0.1
116
+ _KILL_MAX_DELAY = 2.0
117
+ #: Each ``killSessions`` try gives up after this long, or the time left, whichever is shorter.
118
+ _KILL_TRY_LIMIT = 2.0
119
+
120
+ logger = logging.getLogger("sendproof")
121
+
122
+
123
+ def _ends_transaction(name: str) -> bool:
124
+ """Commands that end a transaction. In a Preview only the engine may send them."""
125
+ return name in ("committransaction", "aborttransaction")
126
+
127
+
128
+ def system_database(name: Optional[str]) -> bool:
129
+ """Commands on these databases cannot join a transaction."""
130
+ return name in _SYSTEM_DATABASES
131
+
132
+
133
+ # --------------------------------------------------------------------------- sans-IO driving
134
+ # The engine's server calls are written once, as generators that yield zero-argument callables
135
+ # and receive their results. ``_drive_sync`` runs them against PyMongo, ``_drive_async`` against
136
+ # AsyncMongoClient, where a result may need awaiting. Both run the generator in the caller's
137
+ # context, so a ``ContextVar`` the generator sets is seen by the calls it yields.
138
+ Steps = Generator[Callable[[], Any], Any, Any]
139
+
140
+ #: Set while the engine itself ends the Preview transaction: only then may the Preview's driver
141
+ #: session commit, abort or end. A ``ContextVar``, so a handler thread never inherits the permission.
142
+ _engine_call: ContextVar[bool] = ContextVar("sendproof_mongo_engine_call", default=False)
143
+ #: The engine whose detection ``hello`` is being sent, so the monitor can prove it sees that client.
144
+ _probe: ContextVar[Optional["MongoEngine"]] = ContextVar("sendproof_mongo_probe", default=None)
145
+
146
+
147
+ def _drive_sync(steps: Steps) -> Any:
148
+ try:
149
+ step = next(steps)
150
+ while True:
151
+ try:
152
+ value = step()
153
+ except BaseException as error: # delivered to the generator, which may handle it
154
+ step = steps.throw(error)
155
+ continue
156
+ step = steps.send(value)
157
+ except StopIteration as done:
158
+ return done.value
159
+
160
+
161
+ async def _drive_async(steps: Steps) -> Any:
162
+ try:
163
+ step = next(steps)
164
+ while True:
165
+ try:
166
+ value = step()
167
+ if inspect.isawaitable(value):
168
+ value = await value
169
+ except BaseException as error:
170
+ step = steps.throw(error)
171
+ continue
172
+ step = steps.send(value)
173
+ except StopIteration as done:
174
+ return done.value
175
+
176
+
177
+ def plain(value: Any) -> Any:
178
+ """Convert BSON to plain JSON, using MongoDB Extended JSON v2 relaxed form for the types JSON lacks
179
+ (``{"$oid": ...}``, ``{"$date": ...}``)."""
180
+ return json.loads(json_util.dumps(value, json_options=json_util.RELAXED_JSON_OPTIONS))
181
+
182
+
183
+ def _lsid_hex(command: Mapping[str, Any]) -> Optional[str]:
184
+ """Hex of a command's session id (``lsid.id``, a BSON UUID)."""
185
+ lsid = command.get("lsid") if hasattr(command, "get") else None
186
+ identifier = lsid.get("id") if hasattr(lsid, "get") else None
187
+ return bytes(identifier).hex() if identifier is not None else None
188
+
189
+
190
+ # ----------------------------------------------------------------------------- Preview state
191
+ @dataclass
192
+ class PreviewState:
193
+ """The state of one ``preview``-mode Preview."""
194
+
195
+ engine: "MongoEngine"
196
+ scope: RequestScope
197
+ #: The real driver session carrying the Preview transaction.
198
+ session: Any
199
+ lsid: str
200
+ #: What the handler sees as its session: transaction calls join, they never end the transaction.
201
+ view: Any = None
202
+ #: Set once a write carried the session to the server.
203
+ used: bool = False
204
+ #: Set once any command carried the session towards the server: from then on the server may hold
205
+ #: the transaction, and its locks, until an abort reaches it.
206
+ sent: bool = False
207
+ finished: bool = False
208
+ #: Set while the engine itself aborts, so the monitor does not mistake it for the handler's.
209
+ aborting: bool = False
210
+ #: Set when the server answered the engine's ``abortTransaction``: acknowledged, or no such
211
+ #: transaction. The driver hides that outcome, so the monitor records it.
212
+ abort_acknowledged: bool = False
213
+ #: Set when the Preview outlived its time limit: later commands are refused.
214
+ expired: bool = False
215
+ #: Candidate documents: key -> (namespace, collection, id, via).
216
+ candidates: dict[str, tuple[str, str, Any, Optional[str]]] = field(default_factory=dict)
217
+ #: Filters whose matches, before and inside the transaction, are change candidates.
218
+ filters: list[tuple[str, str, Any, Optional[str]]] = field(default_factory=list)
219
+ #: The transaction's snapshot time: the ``operationTime`` of the first reply to a command the
220
+ #: Preview session sent. ``before`` images are read at this time, so a concurrent commit by
221
+ #: another request never shows up as a Preview change.
222
+ start_time: Any = None
223
+ timer: Any = None
224
+ lock: threading.RLock = field(default_factory=threading.RLock)
225
+ #: Guarded calls currently running, so neither the time limit nor the end of the Preview aborts
226
+ #: under one: the abort waits for the last of them to return (see ``release``).
227
+ inflight: int = 0
228
+ #: Set once the Preview has ended (handler finished or time limit hit), before the abort runs.
229
+ #: Every later guarded call is refused, so a late write never runs on a session whose transaction
230
+ #: is gone, where the driver would autocommit it.
231
+ ending: bool = False
232
+
233
+
234
+ #: Preview states by lsid, so a command is attributed to its Preview even where ``contextvars``
235
+ #: are lost (the time limit's timer thread aborting a transaction).
236
+ _states: dict[str, PreviewState] = {}
237
+ _states_lock = threading.Lock()
238
+ #: Host-declared reads of every engine, for the monitor's write classification.
239
+ _extra_reads: set[str] = set()
240
+ #: Background ``killSessions`` tasks of async clients, kept so they aren't collected while they run.
241
+ _background: set[Any] = set()
242
+
243
+
244
+ def _state_of(lsid: Optional[str]) -> Optional[PreviewState]:
245
+ with _states_lock:
246
+ return _states.get(lsid) if lsid else None
247
+
248
+
249
+ # ------------------------------------------------------------------------------ the monitor
250
+ @dataclass
251
+ class _Pending:
252
+ capture: Any
253
+ state: Optional[PreviewState]
254
+ name: str
255
+ namespace: str
256
+ target: Optional[str]
257
+ statement: str
258
+ lsid: Optional[str]
259
+
260
+
261
+ class MongoMonitor(monitoring.CommandListener):
262
+ """The tripwire and logger for every MongoDB command the process sends.
263
+
264
+ Registered globally when this module is imported, so every client created afterwards has it.
265
+ Pass the instance as ``event_listeners=[mongo_monitor]`` for a client created earlier.
266
+ """
267
+
268
+ def __init__(self) -> None:
269
+ self._pending: dict[tuple[Any, Any], _Pending] = {}
270
+ #: The engine's own ``abortTransaction`` commands in flight, and the Preview each ends.
271
+ self._aborts: dict[tuple[Any, Any], PreviewState] = {}
272
+ self._lock = threading.Lock()
273
+
274
+ # -- events
275
+ def started(self, event: Any) -> None:
276
+ command = event.command or {}
277
+ name = event.command_name
278
+ lower = name.lower()
279
+ probe = _probe.get()
280
+ if probe is not None and lower == "hello":
281
+ probe.monitored = True # the guarded client's own detection reached the listener
282
+ if lower == "killsessions" and _engine_call.get():
283
+ return # the engine ending a Preview whose abort was lost
284
+ lsid = _lsid_hex(command)
285
+ state = _state_of(lsid)
286
+ if state is not None:
287
+ if lower == "aborttransaction" and state.aborting:
288
+ with self._lock:
289
+ self._aborts[(event.request_id, event.connection_id)] = state
290
+ else:
291
+ state.sent = True # the server may hold the transaction until an abort reaches it
292
+ context = current_scope()
293
+ scope = context if context is not None else (state.scope if state is not None else None)
294
+ if scope is None: # nothing to guard or log: the common case for an application's ordinary traffic
295
+ if not _ends_transaction(lower):
296
+ kind, _ = classify_mongo(command if command else {name: 1}, frozenset(_extra_reads) or None)
297
+ if kind == WRITE:
298
+ unattributed_write("mongodb", name)
299
+ return
300
+ preview = scope if scope.rollback else None
301
+ kind, _ = classify_mongo(command if command else {name: 1}, frozenset(_extra_reads) or None)
302
+ if preview is not None:
303
+ if _ends_transaction(lower):
304
+ # Sent around the hook, for example through an unguarded handle: it may have
305
+ # committed the Preview transaction, so the Preview can never be confirmed.
306
+ if not (state is not None and state.aborting):
307
+ preview.capture.refuse(PreviewTransactionControl(
308
+ f"A MongoDB {name} reached the server during a Preview; the Preview can't be confirmed."))
309
+ elif kind == WRITE:
310
+ self._watch_write(preview, state, command, event.database_name, lower)
311
+ if kind == SESSION or lower in _SENSITIVE or _ends_transaction(lower):
312
+ return
313
+ target = command.get(name) if isinstance(command.get(name), str) else None
314
+ body = {key: value for key, value in command.items() if key not in _ENVELOPE}
315
+ pending = _Pending(scope.capture, state if state is not None and state.scope is scope else None, name,
316
+ event.database_name, target, json.dumps(sanitize_document(body)), lsid)
317
+ with self._lock:
318
+ if len(self._pending) > 10000: # a leak guard: replies that never arrive
319
+ self._pending.clear()
320
+ self._pending[(event.request_id, event.connection_id)] = pending
321
+
322
+ def succeeded(self, event: Any) -> None:
323
+ self._abort_answered(event, acknowledged=True)
324
+ pending = self._take(event)
325
+ if pending is None:
326
+ return
327
+ reply = event.reply or {}
328
+ state = pending.state
329
+ if state is not None:
330
+ with state.lock:
331
+ # The first reply in the transaction carries its snapshot time (the read timestamp).
332
+ if state.start_time is None and reply.get("operationTime") is not None and pending.lsid == state.lsid:
333
+ state.start_time = reply["operationTime"]
334
+ if pending.target:
335
+ # Upserted ids appear only in the reply.
336
+ for upsert in reply.get("upserted") or ():
337
+ self._candidate(state, pending.namespace, pending.target, upsert.get("_id"), "upsert")
338
+ value = reply.get("value")
339
+ if pending.name.lower() == "findandmodify" and isinstance(value, Mapping) and "_id" in value:
340
+ self._candidate(state, pending.namespace, pending.target, value["_id"], None)
341
+ upserted = (reply.get("lastErrorObject") or {}).get("upserted")
342
+ if upserted is not None:
343
+ self._candidate(state, pending.namespace, pending.target, upserted, "upsert")
344
+ # A write the transaction cannot run (a capped collection) is refused per write, inside an
345
+ # otherwise successful reply: code 263, OperationNotSupportedInTransaction.
346
+ if state is not None and any(isinstance(e, Mapping) and e.get("code") == 263 for e in reply.get("writeErrors") or ()):
347
+ state.scope.capture.block("mongodb", pending.name, refused_reason(pending.name))
348
+ cursor = reply.get("cursor")
349
+ if isinstance(cursor, Mapping):
350
+ rows: Optional[int] = len(cursor.get("firstBatch") or cursor.get("nextBatch") or ())
351
+ else:
352
+ rows = reply.get("n") if isinstance(reply.get("n"), int) else None
353
+ self._log(pending, event.duration_micros / 1000, rows, None)
354
+
355
+ def failed(self, event: Any) -> None:
356
+ failure = event.failure if isinstance(event.failure, Mapping) else {}
357
+ # A network error (reported as ``errtype``, with no server code) proves nothing reached the
358
+ # server; only the server's own NoSuchTransaction counts.
359
+ self._abort_answered(event, acknowledged="errtype" not in failure and failure.get("code") == _NO_SUCH_TRANSACTION)
360
+ pending = self._take(event)
361
+ if pending is None:
362
+ return
363
+ # The server refused something a transaction cannot do and applied nothing: a block, not a crash.
364
+ if pending.state is not None and failure.get("code") == 263:
365
+ pending.state.scope.capture.block("mongodb", pending.name, refused_reason(pending.name))
366
+ self._log(pending, event.duration_micros / 1000, None, failure.get("codeName") or "Error")
367
+
368
+ # -- helpers
369
+ def _abort_answered(self, event: Any, acknowledged: bool) -> None:
370
+ """Note on the engine's own abort whether the server answered that the transaction is over."""
371
+ with self._lock:
372
+ state = self._aborts.pop((event.request_id, event.connection_id), None)
373
+ if state is not None and acknowledged:
374
+ state.abort_acknowledged = True
375
+
376
+ def _take(self, event: Any) -> Optional[_Pending]:
377
+ with self._lock:
378
+ return self._pending.pop((event.request_id, event.connection_id), None)
379
+
380
+ @staticmethod
381
+ def _log(pending: _Pending, elapsed_ms: float, rows: Optional[int], error: Optional[str]) -> None:
382
+ pending.capture.record_db(
383
+ "mongodb", pending.name, namespace=pending.namespace, target=pending.target,
384
+ statement=pending.statement, rows_affected=rows, error=error, elapsed_ms=elapsed_ms,
385
+ )
386
+
387
+ def _watch_write(self, preview: RequestScope, state: Optional[PreviewState], command: Mapping[str, Any],
388
+ namespace: str, name: str) -> None:
389
+ """A write seen during a Preview: collect change candidates, or trip if it escaped the session."""
390
+ # Only a command inside the Preview transaction (its lsid and autocommit: false) rolls back.
391
+ if state is None or state.finished or state.scope is not preview or command.get("autocommit") is not False:
392
+ # The hook could not stop it and nothing can undo it: never claim a rollback.
393
+ preview.capture.refuse(PreviewTransactionControl(
394
+ f"A MongoDB {name} escaped the Preview session; the Preview can't be confirmed."))
395
+ return
396
+ with state.lock:
397
+ state.used = True
398
+ first = next(iter(command), "")
399
+ collection = command[first] if isinstance(command.get(first), str) else ""
400
+ if name == "insert" and isinstance(command.get("documents"), list):
401
+ for document in command["documents"]:
402
+ self._candidate(state, namespace, collection, document.get("_id") if hasattr(document, "get") else None, None)
403
+ elif name == "update" and isinstance(command.get("updates"), list):
404
+ for update in command["updates"]:
405
+ via = "upsert" if update.get("upsert") else "replace" if _replaces(update.get("u")) else None
406
+ state.filters.append((namespace, collection, update.get("q") or {}, via))
407
+ elif name == "delete" and isinstance(command.get("deletes"), list):
408
+ for removal in command["deletes"]:
409
+ state.filters.append((namespace, collection, removal.get("q") or {}, None))
410
+ elif name == "findandmodify":
411
+ via = "upsert" if command.get("upsert") else "replace" if _replaces(command.get("update")) else None
412
+ state.filters.append((namespace, collection, command.get("query") or {}, via))
413
+ elif name == "bulkwrite" and isinstance(command.get("ops"), list) and isinstance(command.get("nsInfo"), list):
414
+ # The client-level bulkWrite command: each op names its namespace by index.
415
+ namespaces = [str(info.get("ns", "")).split(".", 1) for info in command["nsInfo"]]
416
+ for op in command["ops"]:
417
+ index = next((op[key] for key in ("insert", "update", "delete") if key in op), 0)
418
+ database, target = (namespaces[index] + [""])[:2] if index < len(namespaces) else (namespace, "")
419
+ if "document" in op:
420
+ self._candidate(state, database, target, op["document"].get("_id"), None)
421
+ else:
422
+ state.filters.append((database, target, op.get("filter") or {}, "upsert" if op.get("upsert") else None))
423
+
424
+ @staticmethod
425
+ def _candidate(state: PreviewState, namespace: str, collection: str, identifier: Any, via: Optional[str]) -> None:
426
+ if identifier is None:
427
+ return
428
+ key = f"{namespace}\u0000{collection}\u0000{json_util.dumps(identifier)}"
429
+ known = state.candidates.get(key)
430
+ if known is None or (known[3] is None and via):
431
+ state.candidates[key] = (namespace, collection, identifier, via)
432
+
433
+
434
+ def _replaces(update: Any) -> bool:
435
+ """Whether an update document replaces the whole document rather than applying operators."""
436
+ if not isinstance(update, Mapping) or not update:
437
+ return False
438
+ return not str(next(iter(update))).startswith("$")
439
+
440
+
441
+ #: The listener instance: registered globally on import, and passable to a client's ``event_listeners``.
442
+ mongo_monitor = MongoMonitor()
443
+ monitoring.register(mongo_monitor)
444
+
445
+
446
+ # -------------------------------------------------------------------------------- the engine
447
+ def _flavor(client: Any) -> str:
448
+ """``sync`` (PyMongo) or ``async`` (``AsyncMongoClient``). Motor is refused."""
449
+ if type(client).__module__.split(".", 1)[0] == "motor":
450
+ raise TypeError(
451
+ "Motor is not supported: it is deprecated in favour of PyMongo's AsyncMongoClient, and its thread "
452
+ "pool drops the Preview's context, so a stray write could not be attributed. Use "
453
+ "pymongo.AsyncMongoClient with mongo_store.")
454
+ try:
455
+ from pymongo.asynchronous.mongo_client import AsyncMongoClient
456
+
457
+ if isinstance(client, AsyncMongoClient):
458
+ return "async"
459
+ except ImportError:
460
+ pass
461
+ from pymongo import MongoClient
462
+
463
+ if isinstance(client, MongoClient):
464
+ return "sync"
465
+ raise TypeError("mongo_store takes a MongoClient or AsyncMongoClient.")
466
+
467
+
468
+ def _listeners_of(client: Any) -> Optional[list[Any]]:
469
+ """The command listeners a client was built with, or ``None`` when this driver version hides them."""
470
+ try:
471
+ return list(client.options.pool_options._event_listeners.event_listeners())
472
+ except Exception:
473
+ return None
474
+
475
+
476
+ #: Why a Preview refuses to begin on a client the monitor has not been proven on.
477
+ UNMONITORED = ("The MongoDB client's commands never reached the Sendproof monitor, so a write that escaped the "
478
+ "Preview could not be caught. Create the client after importing sendproof_core.stores.mongo_hook, "
479
+ "or pass event_listeners=[mongo_monitor].")
480
+
481
+
482
+ class MongoEngine:
483
+ """One engine per hooked client: topology, Preview transaction, guard, change capture."""
484
+
485
+ def __init__(self, client: Any, reads: Optional[frozenset[str]], timeout: float) -> None:
486
+ self.client = client
487
+ self.flavor = _flavor(client)
488
+ self.is_async = self.flavor != "sync"
489
+ self.reads = reads
490
+ self.timeout = timeout
491
+ #: The guarded client handlers use; set by :class:`MongoStore`.
492
+ self.guarded: Any = None
493
+ self._detected: Optional[tuple[str, Optional[str]]] = None
494
+ #: The detected mode, known before any Preview runs: ``begin`` awaits detection.
495
+ self.mode: Optional[str] = None
496
+ #: Set when the monitor saw this client's own detection ``hello``: the proof that the
497
+ #: tripwire is installed on it. A Preview never begins without it.
498
+ self.monitored = False
499
+ listeners = _listeners_of(client)
500
+ if listeners is not None and not any(isinstance(item, MongoMonitor) for item in listeners):
501
+ raise TypeError(
502
+ "Create the MongoDB client after importing sendproof_core.stores.mongo_store, or pass "
503
+ "event_listeners=[mongo_monitor]: the Preview tripwire needs command monitoring.")
504
+ if reads:
505
+ _extra_reads.update(reads)
506
+
507
+ # -- per-Preview records, kept on the scope so a Preview keeps the mode it began in
508
+ def _records(self, scope: RequestScope) -> dict[int, Any]:
509
+ return scope.extensions.setdefault(_EXTENSION, {})
510
+
511
+ def state(self, scope: Optional[RequestScope] = None) -> Optional[PreviewState]:
512
+ """The current Preview's state, when this code runs in a ``preview``-mode Preview that began."""
513
+ scope = scope or current_preview()
514
+ found = self._records(scope).get(id(self)) if scope is not None else None
515
+ return found if isinstance(found, PreviewState) else None
516
+
517
+ def mode_of(self, scope: RequestScope) -> str:
518
+ """The mode the Preview began in; ``guard`` for a Preview that never began on this store.
519
+
520
+ A shared, mutable mode would let a Preview that began without a session have its writes
521
+ treated as joining a transaction it never had, once a later detection succeeded.
522
+ """
523
+ found = self._records(scope).get(("mode", id(self)))
524
+ return found if found in ("preview", "guard") else "guard"
525
+
526
+ # -- detection
527
+ def _detect_steps(self) -> Steps:
528
+ if self._detected is not None:
529
+ return self._detected
530
+ token = _probe.set(self)
531
+ try:
532
+ hello = yield (lambda: self.client["admin"].command({"hello": 1}))
533
+ except Exception as error:
534
+ # Guard mode for now, and ask again next time. A server that answered with an error is one
535
+ # the binding doesn't recognise; one that never answered may support transactions or not.
536
+ self.mode = self.mode or "guard"
537
+ return "guard", STANDALONE_REASON if isinstance(error, OperationFailure) else UNREACHABLE_REASON
538
+ finally:
539
+ _probe.reset(token)
540
+ transactions = bool((hello.get("setName") or hello.get("msg") == "isdbgrid")
541
+ and hello.get("logicalSessionTimeoutMinutes") is not None)
542
+ self._detected = ("preview", None) if transactions else ("guard", STANDALONE_REASON)
543
+ self.mode = self._detected[0]
544
+ return self._detected
545
+
546
+ def detect(self) -> tuple[str, Optional[str]]:
547
+ """Detect the topology once: ``preview`` on a replica set or mongos with logical sessions."""
548
+ self._require_sync()
549
+ return _drive_sync(self._detect_steps())
550
+
551
+ async def adetect(self) -> tuple[str, Optional[str]]:
552
+ """Async form of :meth:`detect`."""
553
+ return await (_drive_async(self._detect_steps()) if self.is_async else asyncio.to_thread(self.detect))
554
+
555
+ def _require_sync(self) -> None:
556
+ if self.is_async:
557
+ raise RuntimeError("An asynchronous MongoDB client needs the ASGI adapter (FastAPI or Starlette).")
558
+
559
+ # -- begin
560
+ def _begin_steps(self, scope: RequestScope) -> Steps:
561
+ mode, _ = yield from self._detect_steps()
562
+ if scope.rollback is not True:
563
+ return None
564
+ # A server detection couldn't reach gave no chance for the proof; its Preview runs in guard mode,
565
+ # where the guarded handles refuse every write before it is sent.
566
+ if not self.monitored and (mode == "preview" or self._detected is not None):
567
+ # Without the proof, a write that escaped the guarded handles could persist while the
568
+ # Preview reports a rollback. Fail the Preview instead (500).
569
+ raise RuntimeError(UNMONITORED)
570
+ records = self._records(scope)
571
+ records[("mode", id(self))] = mode
572
+ if mode != "preview":
573
+ return None
574
+ session = yield (lambda: self.client.start_session())
575
+ try:
576
+ yield (lambda: _start_transaction(session))
577
+ except BaseException:
578
+ yield from self._discard_steps(session)
579
+ raise
580
+ lsid = _lsid_hex({"lsid": session.session_id})
581
+ if lsid is None:
582
+ yield from self._discard_steps(session)
583
+ raise RuntimeError("The MongoDB driver did not expose the Preview session id.")
584
+ state = PreviewState(self, scope, session, lsid)
585
+ _seal_session(state)
586
+ state.view = _SessionView(state)
587
+ records[id(self)] = state
588
+ with _states_lock:
589
+ _states[lsid] = state
590
+ self._arm_timer(state)
591
+ return state
592
+
593
+ def _discard_steps(self, session: Any) -> Steps:
594
+ try:
595
+ yield (lambda: session.end_session())
596
+ except Exception:
597
+ pass
598
+
599
+ def begin(self, scope: RequestScope) -> Optional[PreviewState]:
600
+ """Prepare a Preview: detect the mode and, in ``preview`` mode, start its session and transaction."""
601
+ self._require_sync()
602
+ return _drive_sync(self._begin_steps(scope))
603
+
604
+ async def abegin(self, scope: RequestScope) -> Optional[PreviewState]:
605
+ """Async form of :meth:`begin`."""
606
+ if self.is_async:
607
+ return await _drive_async(self._begin_steps(scope))
608
+ return await asyncio.to_thread(self.begin, scope)
609
+
610
+ # -- the time limit
611
+ def _arm_timer(self, state: PreviewState) -> None:
612
+ """Abort a Preview that outlives its limit: a handler still running loses its transaction,
613
+ later commands fail, nothing commits, and the Preview answers 500 when it ends."""
614
+ if self.is_async:
615
+ state.timer = asyncio.get_running_loop().call_later(self.timeout, lambda: self._expire_async(state))
616
+ else:
617
+ state.timer = threading.Timer(self.timeout, self._expire_sync, (state,))
618
+ state.timer.daemon = True
619
+ state.timer.start()
620
+
621
+ def _expire_common(self, state: PreviewState) -> bool:
622
+ state.scope.capture.refuse(PreviewTransactionControl(
623
+ f"The Preview ran longer than {self.timeout:g} s, so its MongoDB transaction was aborted."))
624
+ state.expired = True
625
+ return not state.finished
626
+
627
+ def _expire_sync(self, state: PreviewState) -> None:
628
+ with state.lock:
629
+ if not self._expire_common(state):
630
+ return
631
+ # A session is not thread-safe: abort now only when no guarded call is running.
632
+ # Otherwise the last call to return aborts (see ``release``).
633
+ if state.inflight == 0:
634
+ self._abort_now(state)
635
+
636
+ def _abort_now(self, state: PreviewState) -> None:
637
+ try:
638
+ _drive_sync(self._end_steps(state))
639
+ except Exception:
640
+ pass
641
+
642
+ def _expire_async(self, state: PreviewState) -> None:
643
+ if self._expire_common(state):
644
+ asyncio.ensure_future(self._aend(state))
645
+
646
+ def acquire(self, state: PreviewState) -> None:
647
+ """Mark a guarded call as running. Refuses it once the Preview has expired or ended."""
648
+ with state.lock:
649
+ if state.expired:
650
+ error = PreviewTransactionControl("The Preview ran past its time limit, so its MongoDB transaction was aborted.")
651
+ elif state.ending or state.finished:
652
+ error = PreviewTransactionControl(
653
+ "The Preview has ended, so its MongoDB session refuses every further call.")
654
+ else:
655
+ state.inflight += 1
656
+ return
657
+ state.scope.capture.refuse(error)
658
+ raise error
659
+
660
+ def release(self, state: PreviewState) -> None:
661
+ """Mark a guarded call as finished. If the Preview expired or ended while it ran, the last call
662
+ to return runs the abort the end deferred (see ``_end_steps``)."""
663
+ with state.lock:
664
+ state.inflight -= 1
665
+ if not ((state.expired or state.ending) and state.inflight == 0 and not state.finished):
666
+ return
667
+ if not self.is_async:
668
+ self._abort_now(state)
669
+ return
670
+ asyncio.ensure_future(self._aend(state))
671
+
672
+ # -- guard
673
+ def check(self, command: Mapping[str, Any], operation: Optional[str] = None, database: Optional[str] = None) -> None:
674
+ """Classify a command before it is sent and let the guard refuse it.
675
+
676
+ In ``guard`` mode every write blocks; in ``preview`` mode only what MongoDB cannot run inside
677
+ a transaction does. Commands on the admin, config or local databases run outside the
678
+ transaction, so their writes block too.
679
+ """
680
+ scope = current_preview()
681
+ if scope is None:
682
+ return
683
+ operation = operation or str(next(iter(command), "command"))
684
+ if _ends_transaction(operation.lower()):
685
+ raise refuse_in_preview( # type: ignore[misc]
686
+ f"Preview owns the MongoDB transaction, so the handler's {operation} cannot run during Preview.")
687
+ kind, refused = classify_mongo(command, self.reads)
688
+ if self.mode_of(scope) == "preview" and not system_database(database):
689
+ if refused:
690
+ guard("mongodb", operation, WRITE, refused_reason(refused))
691
+ return
692
+ guard("mongodb", operation, kind)
693
+
694
+ def check_unattributed(self, rule: Optional[Rule], name: str, collection: str, args: tuple, kwargs: dict) -> None:
695
+ """Refuse, before it is sent, a write through a guarded handle that no request accounts for.
696
+
697
+ While any Preview is open such a write may come from a Preview handler's own thread, so every
698
+ open Preview is blocked, or fails with 500 when it began in ``preview`` mode (the write could
699
+ never join its transaction), and :class:`PreviewWriteBlocked` is raised.
700
+ """
701
+ if attributed() or not open_previews():
702
+ return
703
+ if rule is None:
704
+ operation, kind = name, WRITE # a method the guard does not know
705
+ else:
706
+ command = rule(collection, args, kwargs)
707
+ operation = str(next(iter(command), name))
708
+ kind, _ = classify_mongo(command, self.reads)
709
+ if _ends_transaction(operation.lower()):
710
+ kind = WRITE
711
+ if kind == WRITE:
712
+ refuse_unattributed("mongodb", operation, must_fail=lambda scope: self.mode_of(scope) == "preview")
713
+
714
+ # -- finish
715
+ def _finish_steps(self, scope: RequestScope) -> Steps:
716
+ state = self.state(scope)
717
+ if state is None or state.finished:
718
+ return
719
+ failure: Optional[BaseException] = None
720
+ try:
721
+ if state.used:
722
+ yield from self._capture_steps(scope, state)
723
+ except Exception as error:
724
+ # A failed command inside a transaction makes the server abort it: nothing to capture.
725
+ # A network error's ``details`` is a list, so only a server reply is read for its code name.
726
+ details = getattr(error, "details", None)
727
+ code_name = details.get("codeName") if isinstance(details, Mapping) else None
728
+ if getattr(error, "code", None) != _NO_SUCH_TRANSACTION and code_name != "NoSuchTransaction":
729
+ failure = error
730
+ finally:
731
+ ended = yield from self._end_steps(state)
732
+ if not ended and failure is None:
733
+ # The server may still hold the transaction's locks; the session is killed in the background.
734
+ failure = RuntimeError(
735
+ "MongoDB didn't acknowledge the abort of the Preview transaction, so the rollback can't be confirmed.")
736
+ if failure is not None:
737
+ raise failure
738
+
739
+ def finish(self, scope: RequestScope) -> None:
740
+ """After the handler: capture document changes, then abort the transaction and end the session."""
741
+ self._require_sync()
742
+ _drive_sync(self._finish_steps(scope))
743
+
744
+ async def afinish(self, scope: RequestScope) -> None:
745
+ """Async form of :meth:`finish`."""
746
+ if self.is_async:
747
+ await _drive_async(self._finish_steps(scope))
748
+ else:
749
+ await asyncio.to_thread(self.finish, scope)
750
+
751
+ def _end_steps(self, state: PreviewState) -> Steps:
752
+ """Abort the Preview transaction and end its session, once. Returns whether the transaction is
753
+ known to be over.
754
+
755
+ The driver ignores abort errors, as the transactions specification requires: an unacknowledged
756
+ abort still commits nothing, because no ``commitTransaction`` is ever sent for the Preview
757
+ session. But the server then keeps the transaction, and its locks, until its 60-second lifetime
758
+ limit. So when a command was sent on the session and the server never answered the abort (the
759
+ connection dropped), this returns ``False`` at once, and the Preview answers 500, while the
760
+ session is killed in the background (see ``_kill_steps``).
761
+
762
+ A guarded call still running when the Preview ends (a thread the handler left behind) holds the
763
+ abort until it returns, so it never runs on a session without a transaction; ``release`` then
764
+ aborts. The Preview can't list that call's write, so it answers 500."""
765
+ with state.lock: # the time limit and the end of the handler may race to abort
766
+ if state.finished:
767
+ return True
768
+ state.ending = True
769
+ if state.inflight > 0:
770
+ if not state.expired:
771
+ state.scope.capture.refuse(PreviewTransactionControl(
772
+ "A MongoDB call was still running when the Preview ended; the Preview can't be confirmed."))
773
+ return True
774
+ state.finished = True
775
+ state.aborting = True
776
+ timer = state.timer
777
+ permission = _engine_call.set(True) # the sealed session ends only for the engine
778
+ ended = True
779
+ try:
780
+ if timer is not None:
781
+ timer.cancel()
782
+ if state.session.in_transaction:
783
+ try:
784
+ yield (lambda: state.session.abort_transaction())
785
+ except Exception:
786
+ pass
787
+ ended = not state.sent or state.abort_acknowledged
788
+ if ended:
789
+ try:
790
+ yield (lambda: state.session.end_session())
791
+ except Exception:
792
+ pass
793
+ finally:
794
+ _engine_call.reset(permission)
795
+ state.aborting = False
796
+ with _states_lock:
797
+ _states.pop(state.lsid, None)
798
+ if not ended:
799
+ self._kill_in_background(state)
800
+ return ended
801
+
802
+ def _kill_in_background(self, state: PreviewState) -> None:
803
+ if self.is_async:
804
+ task = asyncio.ensure_future(_drive_async(self._kill_steps(state, asyncio.sleep)))
805
+ _background.add(task)
806
+ task.add_done_callback(_background.discard)
807
+ else:
808
+ threading.Thread(target=_drive_sync, args=(self._kill_steps(state, time.sleep),), daemon=True,
809
+ name="sendproof-mongodb-kill").start()
810
+
811
+ def _bounded(self, seconds: float, call: Callable[[], Any]) -> Any:
812
+ """Run one server call, giving up after ``seconds`` even while no server can be selected."""
813
+ if self.is_async:
814
+ return asyncio.wait_for(call(), seconds)
815
+ import pymongo
816
+
817
+ with pymongo.timeout(seconds):
818
+ return call()
819
+
820
+ def _kill_steps(self, state: PreviewState, sleep: Callable[[float], Any]) -> Steps:
821
+ """End a Preview transaction whose abort the server never acknowledged with ``killSessions``. The
822
+ session is ended only afterwards, so the driver can't hand its id to another operation meanwhile."""
823
+ permission = _engine_call.set(True)
824
+ try:
825
+ yield from self._kill_session_steps(state.session.session_id, state.lsid, sleep)
826
+ try:
827
+ yield (lambda: state.session.end_session())
828
+ except Exception:
829
+ pass
830
+ finally:
831
+ _engine_call.reset(permission)
832
+
833
+ def _kill_session_steps(self, session_id: Any, lsid: str, sleep: Callable[[float], Any]) -> Steps:
834
+ """Send ``killSessions`` for one session id, retrying with backoff for up to 10 s while the server
835
+ can't be reached. Each try gives up after 2 s, or the time left, so a try never waits out the
836
+ driver's 30-second server selection timeout. Returns whether the server killed the session; a
837
+ final failure is logged as a warning with ``lsid``: the server then ends the transaction at its
838
+ lifetime limit."""
839
+ permission = _engine_call.set(True) # the monitor leaves the engine's own killSessions alone
840
+ deadline = time.monotonic() + _KILL_RETRY_LIMIT
841
+ delay = _KILL_FIRST_DELAY
842
+ failure: Optional[str] = f"MongoDB couldn't be reached for {_KILL_RETRY_LIMIT:g} s"
843
+ command = {"killSessions": [session_id]}
844
+ try:
845
+ while (remaining := deadline - time.monotonic()) > 0:
846
+ bound = min(_KILL_TRY_LIMIT, remaining)
847
+ try:
848
+ yield (lambda: self._bounded(bound, lambda: self.client["admin"].command(command)))
849
+ failure = None
850
+ break
851
+ except OperationFailure as error: # the server answered no: retrying won't help
852
+ failure = str(error)
853
+ break
854
+ except Exception: # a network error, no server to select or a try that timed out
855
+ pass
856
+ pause = max(0.0, min(delay, deadline - time.monotonic()))
857
+ yield (lambda: sleep(pause))
858
+ delay = min(delay * 2, _KILL_MAX_DELAY)
859
+ finally:
860
+ _engine_call.reset(permission)
861
+ if failure is not None:
862
+ logger.warning("Couldn't end a MongoDB Preview transaction (session %s): %s. The server ends it, "
863
+ "and releases its locks, at transactionLifetimeLimitSeconds.", lsid, failure)
864
+ return failure is None
865
+
866
+ async def _aend(self, state: PreviewState) -> None:
867
+ try:
868
+ await _drive_async(self._end_steps(state))
869
+ except Exception:
870
+ pass
871
+
872
+ def _at_start_steps(self, state: PreviewState, namespace: str, collection: str, query: Any,
873
+ projection: Optional[dict] = None) -> Steps:
874
+ """Find documents as they were when the Preview transaction started: a snapshot read at its start
875
+ time, outside the transaction. Without a start time (no reply carried one) it reads the
876
+ majority-committed view, which the spec allows: nothing the Preview wrote is committed, so the
877
+ only difference is a concurrent commit by another request."""
878
+ concern = {"level": "majority"} if state.start_time is None else {"level": "snapshot", "atClusterTime": state.start_time}
879
+ command: dict[str, Any] = {"find": collection, "filter": query}
880
+ if projection:
881
+ command["projection"] = projection
882
+ command.update({"batchSize": _CANDIDATE_LIMIT, "limit": _CANDIDATE_LIMIT, "singleBatch": True, "readConcern": concern})
883
+ try:
884
+ reply = yield (lambda: self.client[namespace].command(command))
885
+ except OperationFailure as error:
886
+ # The collection was created after the start time: nothing in it existed then.
887
+ if error.code in _ABSENT_AT_START:
888
+ return []
889
+ raise
890
+ return list((reply.get("cursor") or {}).get("firstBatch") or [])
891
+
892
+ def _list_steps(self, namespace: str, collection: str, query: Any, state: PreviewState) -> Steps:
893
+ projection = {"_id": 1}
894
+ target = self.client[namespace][collection]
895
+ if self.is_async:
896
+ return (yield (lambda: target.find(query, projection, session=state.session).to_list(None)))
897
+ return (yield (lambda: list(target.find(query, projection, session=state.session))))
898
+
899
+ def _capture_steps(self, scope: RequestScope, state: PreviewState) -> Steps:
900
+ """Compare each candidate's start-time and in-transaction versions and record the differences."""
901
+ for namespace, collection, query, via in list(state.filters):
902
+ matched = yield from self._list_steps(namespace, collection, query, state)
903
+ earlier = yield from self._at_start_steps(state, namespace, collection, query, {"_id": 1})
904
+ for document in [*matched, *earlier]:
905
+ MongoMonitor._candidate(state, namespace, collection, document["_id"], via)
906
+ if len(state.candidates) >= _CANDIDATE_LIMIT:
907
+ break
908
+ read = 0
909
+ for namespace, collection, identifier, via in list(state.candidates.values()):
910
+ if read >= _CANDIDATE_LIMIT:
911
+ scope.store_changes_truncated = True
912
+ break
913
+ read += 1
914
+ found = yield from self._at_start_steps(state, namespace, collection, {"_id": identifier})
915
+ before = found[0] if found else None
916
+ target = self.client[namespace][collection]
917
+ after = yield (lambda: target.find_one({"_id": identifier}, session=state.session))
918
+ was = None if before is None else plain(before)
919
+ now = None if after is None else plain(after)
920
+ if was == now:
921
+ continue
922
+ operation = "insert" if was is None else "delete" if now is None else "update"
923
+ scope.store_changes.append(PreviewChange(
924
+ operation, collection, {"_id": plain(identifier)}, was, now, "mongodb", namespace,
925
+ via if via and operation != "delete" else None,
926
+ ))
927
+
928
+
929
+ def _start_transaction(session: Any) -> Any:
930
+ """Start the Preview transaction: snapshot reads, majority writes."""
931
+ return session.start_transaction(read_concern=ReadConcern("snapshot"), write_concern=WriteConcern("majority"))
932
+
933
+
934
+ def _session_refusal(session: Any, what: str) -> PreviewTransactionControl:
935
+ """Record and return the refusal of a handler's attempt to end the Preview transaction."""
936
+ error = PreviewTransactionControl(
937
+ f"Preview owns the MongoDB transaction, so the handler's {what} cannot run during Preview.")
938
+ state = getattr(session, "_sendproof_state", None)
939
+ if state is not None:
940
+ state.scope.capture.refuse(error)
941
+ return error
942
+
943
+
944
+ def _sealed_methods(base: type) -> dict[str, Any]:
945
+ """The methods of a sealed session class: only the engine may end the Preview transaction.
946
+
947
+ The driver hands the Preview's session back to handler code (``cursor.session``), so the
948
+ refusal lives on the session itself rather than on the view the handler is given. The class
949
+ must derive from the driver's class alone (a mixin changes the object layout, which forbids the
950
+ ``__class__`` swap), so the methods call the driver's own explicitly.
951
+ """
952
+ if inspect.iscoroutinefunction(base.commit_transaction):
953
+ async def commit_transaction(self: Any) -> None:
954
+ if not _engine_call.get():
955
+ raise _session_refusal(self, "commit_transaction")
956
+ await base.commit_transaction(self)
957
+
958
+ async def abort_transaction(self: Any) -> None:
959
+ if not _engine_call.get():
960
+ raise _session_refusal(self, "abort_transaction")
961
+ await base.abort_transaction(self)
962
+
963
+ async def _end_session(self: Any, lock: bool) -> None:
964
+ if _engine_call.get(): # anyone else's end_session leaves the session to the Preview
965
+ await base._end_session(self, lock)
966
+ else:
967
+ def commit_transaction(self: Any) -> None: # type: ignore[misc]
968
+ if not _engine_call.get():
969
+ raise _session_refusal(self, "commit_transaction")
970
+ base.commit_transaction(self)
971
+
972
+ def abort_transaction(self: Any) -> None: # type: ignore[misc]
973
+ if not _engine_call.get():
974
+ raise _session_refusal(self, "abort_transaction")
975
+ base.abort_transaction(self)
976
+
977
+ def _end_session(self: Any, lock: bool) -> None: # type: ignore[misc]
978
+ if _engine_call.get():
979
+ base._end_session(self, lock)
980
+ return {"commit_transaction": commit_transaction, "abort_transaction": abort_transaction,
981
+ "_end_session": _end_session, "__module__": __name__}
982
+
983
+
984
+ _sealed: dict[type, type] = {}
985
+
986
+
987
+ def _seal_session(state: PreviewState) -> None:
988
+ """Swap the Preview session's class for one whose transaction only the engine can end."""
989
+ session = state.session
990
+ base = type(session)
991
+ sealed = _sealed.get(base)
992
+ if sealed is None:
993
+ sealed = _sealed[base] = type(f"Preview{base.__name__}", (base,), _sealed_methods(base))
994
+ session._sendproof_state = state
995
+ session.__class__ = sealed
996
+
997
+
998
+ # -------------------------------------------------------------------------- the guarded handles
999
+ Rule = Callable[[str, tuple, dict], dict]
1000
+
1001
+
1002
+ def _simple(command: str) -> Rule:
1003
+ return lambda name, args, kwargs: {command: name}
1004
+
1005
+
1006
+ def _aggregate(name: str, args: tuple, kwargs: dict) -> dict:
1007
+ pipeline = args[0] if args else kwargs.get("pipeline", [])
1008
+ return {"aggregate": name, "pipeline": pipeline}
1009
+
1010
+
1011
+ def _stream(name: str, args: tuple, kwargs: dict) -> dict:
1012
+ return {"aggregate": name, "pipeline": [{"$changeStream": {}}, *(args[0] if args else kwargs.get("pipeline") or [])]}
1013
+
1014
+
1015
+ #: ``Database.command`` keywords that are driver options; every other keyword becomes a command field.
1016
+ _COMMAND_OPTIONS = frozenset({"command", "value", "check", "allowable_errors", "read_preference", "codec_options",
1017
+ "session", "comment", "max_await_time_ms"})
1018
+
1019
+
1020
+ def _command_document(name: str, args: tuple, kwargs: dict) -> dict:
1021
+ """The document ``Database.command`` sends. The driver adds extra keywords as fields
1022
+ (``command("aggregate", "c", pipeline=[...])``), so an ``$out`` given that way is classified
1023
+ like any other."""
1024
+ command = args[0] if args else kwargs.get("command")
1025
+ if isinstance(command, str):
1026
+ document: dict = {command: args[1] if len(args) > 1 else kwargs.get("value", 1)}
1027
+ elif isinstance(command, Mapping):
1028
+ document = dict(command)
1029
+ else:
1030
+ return {}
1031
+ document.update({key: value for key, value in kwargs.items() if key not in _COMMAND_OPTIONS})
1032
+ return document
1033
+
1034
+
1035
+ def _db_aggregate(name: str, args: tuple, kwargs: dict) -> dict:
1036
+ return {"aggregate": 1, "pipeline": args[0] if args else kwargs.get("pipeline", [])}
1037
+
1038
+
1039
+ def _named(command: str, index: int = 0, key: str = "name") -> Rule:
1040
+ def rule(name: str, args: tuple, kwargs: dict) -> dict:
1041
+ value = args[index] if len(args) > index else kwargs.get(key)
1042
+ return {command: value if isinstance(value, str) else getattr(value, "name", value)}
1043
+ return rule
1044
+
1045
+
1046
+ #: Collection methods: the command each sends, for classification. Unlisted methods are refused in a Preview.
1047
+ _COLLECTION_RULES: dict[str, Rule] = {
1048
+ "insert_one": _simple("insert"), "insert_many": _simple("insert"), "bulk_write": _simple("bulkWrite"),
1049
+ "update_one": _simple("update"), "update_many": _simple("update"), "replace_one": _simple("update"),
1050
+ "delete_one": _simple("delete"), "delete_many": _simple("delete"),
1051
+ "find_one": _simple("find"), "find": _simple("find"), "find_raw_batches": _simple("find"),
1052
+ "count_documents": lambda name, a, k: {"aggregate": name, "pipeline": []}, "distinct": _simple("distinct"),
1053
+ "find_one_and_delete": _simple("findAndModify"), "find_one_and_replace": _simple("findAndModify"),
1054
+ "find_one_and_update": _simple("findAndModify"),
1055
+ "aggregate": _aggregate, "aggregate_raw_batches": _aggregate,
1056
+ "estimated_document_count": _simple("count"), "rename": _simple("renameCollection"), "drop": _simple("drop"),
1057
+ "options": _simple("listCollections"),
1058
+ "create_index": _simple("createIndexes"), "create_indexes": _simple("createIndexes"),
1059
+ "drop_index": _simple("dropIndexes"), "drop_indexes": _simple("dropIndexes"),
1060
+ "list_indexes": _simple("listIndexes"), "index_information": _simple("listIndexes"),
1061
+ "list_search_indexes": lambda name, a, k: {"aggregate": name, "pipeline": [{"$listSearchIndexes": {}}]},
1062
+ "create_search_index": _simple("createSearchIndexes"), "create_search_indexes": _simple("createSearchIndexes"),
1063
+ "drop_search_index": _simple("dropSearchIndex"), "update_search_index": _simple("updateSearchIndex"),
1064
+ "watch": _stream,
1065
+ }
1066
+ #: Database methods.
1067
+ _DATABASE_RULES: dict[str, Rule] = {
1068
+ "command": _command_document, "cursor_command": _command_document, "aggregate": _db_aggregate,
1069
+ "create_collection": _named("create"), "drop_collection": _named("drop"),
1070
+ "list_collection_names": _simple("listCollections"), "list_collections": _simple("listCollections"),
1071
+ "validate_collection": _named("validate"), "dereference": _simple("find"), "watch": _stream,
1072
+ }
1073
+ #: Client methods, beyond ``start_session`` and ``with_session`` which need no rule.
1074
+ _CLIENT_RULES: dict[str, Rule] = {
1075
+ "bulk_write": lambda name, a, k: {"bulkWrite": 1},
1076
+ "list_database_names": lambda name, a, k: {"listDatabases": 1}, "list_databases": lambda name, a, k: {"listDatabases": 1},
1077
+ "drop_database": lambda name, a, k: {"dropDatabase": 1}, "server_info": lambda name, a, k: {"buildInfo": 1},
1078
+ "watch": lambda name, a, k: {"aggregate": 1, "pipeline": [{"$changeStream": {}}]},
1079
+ }
1080
+ #: Callables that are neither commands nor handles; they pass through untouched.
1081
+ _INERT = frozenset({"close", "aclose", "with_options", "get_collection", "get_database", "get_default_database",
1082
+ "get_io_loop", "__enter__", "__exit__", "__aenter__", "__aexit__", "__getitem__", "__getattr__"})
1083
+
1084
+
1085
+ def _classes() -> tuple[tuple[type, ...], tuple[type, ...], tuple[type, ...], tuple[type, ...]]:
1086
+ """The driver classes of clients, databases, collections and sessions, for every installed flavor."""
1087
+ from pymongo import MongoClient
1088
+ from pymongo.client_session import ClientSession
1089
+ from pymongo.collection import Collection
1090
+ from pymongo.database import Database
1091
+
1092
+ clients: list[type] = [MongoClient]
1093
+ databases: list[type] = [Database]
1094
+ collections: list[type] = [Collection]
1095
+ sessions: list[type] = [ClientSession]
1096
+ try:
1097
+ from pymongo.asynchronous.client_session import AsyncClientSession
1098
+ from pymongo.asynchronous.collection import AsyncCollection
1099
+ from pymongo.asynchronous.database import AsyncDatabase
1100
+ from pymongo.asynchronous.mongo_client import AsyncMongoClient
1101
+
1102
+ clients.append(AsyncMongoClient)
1103
+ databases.append(AsyncDatabase)
1104
+ collections.append(AsyncCollection)
1105
+ sessions.append(AsyncClientSession)
1106
+ except ImportError:
1107
+ pass
1108
+ return tuple(clients), tuple(databases), tuple(collections), tuple(sessions)
1109
+
1110
+
1111
+ _CLIENTS, _DATABASES, _COLLECTIONS, _SESSIONS = _classes()
1112
+
1113
+
1114
+ class _SessionView:
1115
+ """The Preview session as the handler sees it: its transaction calls join the Preview transaction.
1116
+
1117
+ ``start_transaction`` and ``with_transaction`` run inside the Preview transaction;
1118
+ ``commit_transaction`` and ``abort_transaction`` never reach the server and fail the Preview
1119
+ with 500, like a raw SQL ``COMMIT``; ``end_session`` leaves the session to the Preview. Anything
1120
+ else is the real session's.
1121
+ """
1122
+
1123
+ def __init__(self, state: PreviewState) -> None:
1124
+ object.__setattr__(self, "_sp_state", state)
1125
+
1126
+ #: What the handler may read from the real session. Anything else fails closed: a private
1127
+ #: member would hand handler code the driver session itself (which is sealed too, see
1128
+ #: ``_seal_session``, but the view never relies on that alone).
1129
+ _READABLE = frozenset({
1130
+ "session_id", "cluster_time", "operation_time", "in_transaction", "has_ended", "options",
1131
+ "advance_cluster_time", "advance_operation_time",
1132
+ })
1133
+
1134
+ def __getattr__(self, name: str) -> Any:
1135
+ state = self._sp_state
1136
+ if name == "client":
1137
+ return state.engine.guarded
1138
+ if name in self._READABLE:
1139
+ return getattr(state.session, name)
1140
+ raise AttributeError(f"The Preview owns this MongoDB session, so '{name}' is not available during Preview.")
1141
+
1142
+ def __setattr__(self, name: str, value: Any) -> None:
1143
+ raise AttributeError("The Preview owns this MongoDB session.")
1144
+
1145
+ # -- joining
1146
+ def start_transaction(self, *args: Any, **kwargs: Any) -> Any:
1147
+ context = _JoinedTransaction()
1148
+ if self._sp_state.engine.flavor == "async":
1149
+ async def started() -> Any:
1150
+ return context
1151
+ return started() # AsyncMongoClient: ``async with await session.start_transaction()``
1152
+ return context
1153
+
1154
+ def with_transaction(self, callback: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
1155
+ return callback(self)
1156
+
1157
+ # -- refusing
1158
+ def _refuse(self, what: str) -> Any:
1159
+ state = self._sp_state
1160
+ error = PreviewTransactionControl(
1161
+ f"Preview owns the MongoDB transaction, so the handler's {what} cannot run during Preview.")
1162
+ state.scope.capture.refuse(error)
1163
+ raise error
1164
+
1165
+ def commit_transaction(self, *args: Any, **kwargs: Any) -> Any:
1166
+ return self._refuse("commit_transaction")
1167
+
1168
+ def abort_transaction(self, *args: Any, **kwargs: Any) -> Any:
1169
+ return self._refuse("abort_transaction")
1170
+
1171
+ def end_session(self, *args: Any, **kwargs: Any) -> Any:
1172
+ if self._sp_state.engine.is_async:
1173
+ async def nothing() -> None:
1174
+ return None
1175
+ return nothing()
1176
+ return None
1177
+
1178
+ # -- context managers and awaiting
1179
+ def __enter__(self) -> "_SessionView":
1180
+ return self
1181
+
1182
+ def __exit__(self, *exc: Any) -> None:
1183
+ return None
1184
+
1185
+ async def __aenter__(self) -> "_SessionView":
1186
+ return self
1187
+
1188
+ async def __aexit__(self, *exc: Any) -> None:
1189
+ return None
1190
+
1191
+ def __await__(self) -> Any:
1192
+ async def me() -> "_SessionView":
1193
+ return self
1194
+ return me().__await__()
1195
+
1196
+
1197
+ class _JoinedTransaction:
1198
+ """What ``start_transaction`` returns inside a Preview: entering and leaving it change nothing."""
1199
+
1200
+ def __enter__(self) -> "_JoinedTransaction":
1201
+ return self
1202
+
1203
+ def __exit__(self, *exc: Any) -> None:
1204
+ return None
1205
+
1206
+ async def __aenter__(self) -> "_JoinedTransaction":
1207
+ return self
1208
+
1209
+ async def __aexit__(self, *exc: Any) -> None:
1210
+ return None
1211
+
1212
+
1213
+ class _Handle:
1214
+ """A guarded client, database or collection with the driver's own API."""
1215
+
1216
+ __slots__ = ("_sp_target", "_sp_engine", "_sp_rules", "_sp_name", "_sp_database", "_sp_kind")
1217
+
1218
+ def __init__(self, target: Any, engine: MongoEngine) -> None:
1219
+ kind = "client" if isinstance(target, _CLIENTS) else "database" if isinstance(target, _DATABASES) else "collection"
1220
+ object.__setattr__(self, "_sp_target", target)
1221
+ object.__setattr__(self, "_sp_engine", engine)
1222
+ object.__setattr__(self, "_sp_kind", kind)
1223
+ object.__setattr__(self, "_sp_rules", {"client": _CLIENT_RULES, "database": _DATABASE_RULES, "collection": _COLLECTION_RULES}[kind])
1224
+ object.__setattr__(self, "_sp_name", {"client": "", "database": getattr(target, "name", ""), "collection": getattr(target, "name", "")}[kind])
1225
+ object.__setattr__(self, "_sp_database", {"client": None, "database": getattr(target, "name", None),
1226
+ "collection": getattr(getattr(target, "database", None), "name", None)}[kind])
1227
+
1228
+ # -- wrapping what comes back
1229
+ def _wrap(self, value: Any) -> Any:
1230
+ engine = self._sp_engine
1231
+ if isinstance(value, _CLIENTS):
1232
+ return engine.guarded if value is engine.client else value
1233
+ if isinstance(value, (*_DATABASES, *_COLLECTIONS)):
1234
+ return _Handle(value, engine)
1235
+ return value
1236
+
1237
+ def __getattr__(self, name: str) -> Any:
1238
+ target = self._sp_target
1239
+ value = getattr(target, name)
1240
+ if not callable(value) or isinstance(value, (*_CLIENTS, *_DATABASES, *_COLLECTIONS)):
1241
+ return self._wrap(value)
1242
+ if name in _INERT:
1243
+ return lambda *args, **kwargs: self._wrap(value(*args, **kwargs))
1244
+ rule = self._sp_rules.get(name)
1245
+ engine = self._sp_engine
1246
+
1247
+ def call(*args: Any, **kwargs: Any) -> Any:
1248
+ scope = current_preview()
1249
+ if scope is None:
1250
+ if current_scope() is None:
1251
+ engine.check_unattributed(rule, name, self._sp_name, args, kwargs)
1252
+ return self._wrap(value(*args, **kwargs))
1253
+ if rule is None:
1254
+ # A method this guard does not know: refuse it in a Preview rather than let it escape.
1255
+ guard("mongodb", name, WRITE, refused_reason(name))
1256
+ args, kwargs, state = self._prepare(rule, name, args, kwargs) # type: ignore[arg-type]
1257
+ if state is None:
1258
+ return self._wrap(value(*args, **kwargs))
1259
+ engine.acquire(state)
1260
+ try:
1261
+ result = value(*args, **kwargs)
1262
+ except BaseException:
1263
+ engine.release(state)
1264
+ raise
1265
+ if inspect.isawaitable(result):
1266
+ return _release_after(result, engine, state)
1267
+ engine.release(state)
1268
+ return self._wrap(result)
1269
+
1270
+ return call
1271
+
1272
+ def _prepare(self, rule: Rule, name: str, args: tuple, kwargs: dict) -> tuple[tuple, dict, Optional[PreviewState]]:
1273
+ """Guard one call during a Preview and give it the Preview session. Raises the guard's error,
1274
+ or a refusal for a foreign session."""
1275
+ engine = self._sp_engine
1276
+ command = rule(self._sp_name, args, kwargs)
1277
+ engine.check(command, str(next(iter(command), name)), self._sp_database)
1278
+ state = engine.state()
1279
+ if state is None or system_database(self._sp_database):
1280
+ return args, kwargs, None
1281
+ real, replaced = state.session, []
1282
+ for item in args:
1283
+ if isinstance(item, (*_SESSIONS, _SessionView)):
1284
+ if item is not state.view and item is not real:
1285
+ raise refuse_in_preview( # type: ignore[misc]
1286
+ "A MongoDB call passed its own session during a Preview; the Preview session must carry every command.")
1287
+ item = real
1288
+ replaced.append(item)
1289
+ given = kwargs.get("session")
1290
+ if given is not None and given is not state.view and given is not real:
1291
+ raise refuse_in_preview( # type: ignore[misc]
1292
+ "A MongoDB call passed its own session during a Preview; the Preview session must carry every command.")
1293
+ return tuple(replaced), {**kwargs, "session": real}, state
1294
+
1295
+ def __getitem__(self, name: str) -> Any:
1296
+ return self._wrap(self._sp_target[name])
1297
+
1298
+ def __eq__(self, other: object) -> bool:
1299
+ return self._sp_target == (other._sp_target if isinstance(other, _Handle) else other)
1300
+
1301
+ def __hash__(self) -> int:
1302
+ return hash(self._sp_target)
1303
+
1304
+ def __repr__(self) -> str:
1305
+ return f"Guarded({self._sp_target!r})"
1306
+
1307
+ def __bool__(self) -> bool:
1308
+ return True
1309
+
1310
+
1311
+ class _GuardedClient(_Handle):
1312
+ """The guarded client: in a Preview ``start_session`` and ``with_session`` hand out the Preview session."""
1313
+
1314
+ __slots__ = ()
1315
+
1316
+ def start_session(self, *args: Any, **kwargs: Any) -> Any:
1317
+ state = self._sp_engine.state()
1318
+ if state is not None:
1319
+ return state.view
1320
+ return self._sp_target.start_session(*args, **kwargs)
1321
+
1322
+
1323
+ async def _release_after(awaitable: Any, engine: MongoEngine, state: PreviewState) -> Any:
1324
+ try:
1325
+ return await awaitable
1326
+ finally:
1327
+ engine.release(state)
1328
+
1329
+
1330
+ def _guarded_client(engine: MongoEngine) -> Any:
1331
+ return _GuardedClient(engine.client, engine)
1332
+
1333
+
1334
+ # ----------------------------------------------------------------------------------- the store
1335
+ class MongoStore(DataStore):
1336
+ """A hooked MongoDB client, ready for ``data_stores``."""
1337
+
1338
+ system = "mongodb"
1339
+
1340
+ def __init__(self, engine: MongoEngine, name: Optional[str]) -> None:
1341
+ self.engine = engine
1342
+ self.name = name
1343
+ #: The guarded client handlers must use: same API, Preview session added during a Preview.
1344
+ self.client = engine.guarded = _guarded_client(engine)
1345
+
1346
+ def _description(self, detected: tuple[str, Optional[str]]) -> dict[str, Any]:
1347
+ mode, reason = detected
1348
+ return {"system": "mongodb", **({"name": self.name} if self.name else {}), "mode": mode,
1349
+ **({"reason": reason} if reason else {})}
1350
+
1351
+ def describe(self) -> dict[str, Any]:
1352
+ return self._description(self.engine.detect())
1353
+
1354
+ async def adescribe(self) -> dict[str, Any]:
1355
+ return self._description(await self.engine.adetect())
1356
+
1357
+ def begin(self, scope: RequestScope) -> None:
1358
+ self.engine.begin(scope)
1359
+
1360
+ async def abegin(self, scope: RequestScope) -> None:
1361
+ await self.engine.abegin(scope)
1362
+
1363
+ def finish(self, scope: RequestScope) -> None:
1364
+ self.engine.finish(scope)
1365
+
1366
+ async def afinish(self, scope: RequestScope) -> None:
1367
+ await self.engine.afinish(scope)
1368
+
1369
+
1370
+ #: Clients already hooked, by identity: two clients for the same seeds compare equal, so a set would conflate them.
1371
+ _hooked: dict[int, "weakref.ref[Any]"] = {}
1372
+
1373
+
1374
+ def mongo_store(
1375
+ client: Any, *, name: Optional[str] = None, treat_as_read: Optional[Iterable[str]] = None,
1376
+ preview_timeout: float = DEFAULT_PREVIEW_TIMEOUT,
1377
+ ) -> MongoStore:
1378
+ """Hook a PyMongo ``MongoClient`` or ``AsyncMongoClient`` and return the store for ``data_stores``.
1379
+
1380
+ Motor is refused with a ``TypeError``: it is deprecated in favour of ``AsyncMongoClient``, and
1381
+ its thread pool drops the context the tripwire needs to attribute a stray write.
1382
+
1383
+ Handlers must use the returned store's ``client``; the original stays unguarded. Create the
1384
+ client after importing this module (or pass ``event_listeners=[mongo_monitor]``): the store
1385
+ relies on command monitoring and refuses a client without it.
1386
+
1387
+ Args:
1388
+ name: A display label for discovery, such as ``catalog``. Never a connection string or host.
1389
+ treat_as_read: Commands you state never write, by exact name (compared case-insensitively,
1390
+ as MongoDB does). **The guard trusts this list**: a wrongly listed write is not blocked
1391
+ in ``guard`` mode.
1392
+ preview_timeout: Seconds a Preview may hold its MongoDB transaction; 50 by default, below
1393
+ the server's 60-second transaction lifetime. A Preview still running at the limit has
1394
+ its transaction aborted and answers 500 without confirmation.
1395
+ """
1396
+ if preview_timeout is None or not isinstance(preview_timeout, (int, float)) or preview_timeout <= 0:
1397
+ raise ValueError("preview_timeout must be a positive number of seconds.")
1398
+ label = store_label(name)
1399
+ if id(client) in _hooked and _hooked[id(client)]() is client:
1400
+ raise TypeError("This MongoDB client is already hooked.")
1401
+ engine = MongoEngine(client, read_set(treat_as_read, lambda item: item.lower()), float(preview_timeout))
1402
+ try:
1403
+ _hooked[id(client)] = weakref.ref(client, lambda _ref, key=id(client): _hooked.pop(key, None))
1404
+ except TypeError: # a client that cannot be weakly referenced is simply not tracked
1405
+ pass
1406
+ return MongoStore(engine, label)