1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
|
# Copyright 2018-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Execute Transactions Spec tests."""
from __future__ import annotations
import sys
from io import BytesIO
from test.asynchronous.utils_spec_runner import AsyncSpecRunner
from gridfs.asynchronous.grid_file import AsyncGridFS, AsyncGridFSBucket
from pymongo.asynchronous.pool import PoolState
from pymongo.server_selectors import writable_server_selector
sys.path[0:0] = [""]
from test.asynchronous import AsyncIntegrationTest, async_client_context, unittest
from test.utils_shared import (
OvertCommandListener,
async_wait_until,
)
from typing import List
from bson import encode
from bson.raw_bson import RawBSONDocument
from pymongo import WriteConcern, _csot
from pymongo.asynchronous import client_session
from pymongo.asynchronous.client_session import TransactionOptions
from pymongo.asynchronous.command_cursor import AsyncCommandCursor
from pymongo.asynchronous.cursor import AsyncCursor
from pymongo.asynchronous.helpers import anext
from pymongo.errors import (
AutoReconnect,
CollectionInvalid,
ConfigurationError,
ConnectionFailure,
InvalidOperation,
OperationFailure,
)
from pymongo.operations import IndexModel, InsertOne
from pymongo.read_concern import ReadConcern
from pymongo.read_preferences import ReadPreference
_IS_SYNC = False
# Max number of operations to perform after a transaction to prove unpinning
# occurs. Chosen so that there's a low false positive rate. With 2 mongoses,
# 50 attempts yields a one in a quadrillion chance of a false positive
# (1/(0.5^50)).
UNPIN_TEST_MAX_ATTEMPTS = 50
class AsyncTransactionsBase(AsyncSpecRunner):
def maybe_skip_scenario(self, test):
super().maybe_skip_scenario(test)
if (
"secondary" in self.id()
and not async_client_context.is_mongos
and not async_client_context.has_secondaries
):
raise unittest.SkipTest("No secondaries")
class TestTransactions(AsyncTransactionsBase):
@async_client_context.require_transactions
def test_transaction_options_validation(self):
default_options = TransactionOptions()
self.assertIsNone(default_options.read_concern)
self.assertIsNone(default_options.write_concern)
self.assertIsNone(default_options.read_preference)
self.assertIsNone(default_options.max_commit_time_ms)
# No error when valid options are provided.
TransactionOptions(
read_concern=ReadConcern(),
write_concern=WriteConcern(),
read_preference=ReadPreference.PRIMARY,
max_commit_time_ms=10000,
)
with self.assertRaisesRegex(TypeError, "read_concern must be "):
TransactionOptions(read_concern={}) # type: ignore
with self.assertRaisesRegex(TypeError, "write_concern must be "):
TransactionOptions(write_concern={}) # type: ignore
with self.assertRaisesRegex(
ConfigurationError, "transactions do not support unacknowledged write concern"
):
TransactionOptions(write_concern=WriteConcern(w=0))
with self.assertRaisesRegex(TypeError, "is not valid for read_preference"):
TransactionOptions(read_preference={}) # type: ignore
with self.assertRaisesRegex(TypeError, "max_commit_time_ms must be an integer or None"):
TransactionOptions(max_commit_time_ms="10000") # type: ignore
@async_client_context.require_transactions
async def test_transaction_write_concern_override(self):
"""Test txn overrides Client/Database/Collection write_concern."""
client = await self.async_rs_client(w=0)
db = client.test
coll = db.test
await coll.insert_one({})
async with client.start_session() as s:
async with await s.start_transaction(write_concern=WriteConcern(w=1)):
self.assertTrue((await coll.insert_one({}, session=s)).acknowledged)
self.assertTrue((await coll.insert_many([{}, {}], session=s)).acknowledged)
self.assertTrue((await coll.bulk_write([InsertOne({})], session=s)).acknowledged)
self.assertTrue((await coll.replace_one({}, {}, session=s)).acknowledged)
self.assertTrue(
(await coll.update_one({}, {"$set": {"a": 1}}, session=s)).acknowledged
)
self.assertTrue(
(await coll.update_many({}, {"$set": {"a": 1}}, session=s)).acknowledged
)
self.assertTrue((await coll.delete_one({}, session=s)).acknowledged)
self.assertTrue((await coll.delete_many({}, session=s)).acknowledged)
await coll.find_one_and_delete({}, session=s)
await coll.find_one_and_replace({}, {}, session=s)
await coll.find_one_and_update({}, {"$set": {"a": 1}}, session=s)
unsupported_txn_writes: list = [
(client.drop_database, [db.name], {}),
(db.drop_collection, ["collection"], {}),
(coll.drop, [], {}),
(coll.rename, ["collection2"], {}),
# Drop collection2 between tests of "rename", above.
(coll.database.drop_collection, ["collection2"], {}),
(coll.create_indexes, [[IndexModel("a")]], {}),
(coll.create_index, ["a"], {}),
(coll.drop_index, ["a_1"], {}),
(coll.drop_indexes, [], {}),
(coll.aggregate, [[{"$out": "aggout"}]], {}),
]
# Creating a collection in a transaction requires MongoDB 4.4+.
if async_client_context.version < (4, 3, 4):
unsupported_txn_writes.extend(
[
(db.create_collection, ["collection"], {}),
]
)
for op in unsupported_txn_writes:
op, args, kwargs = op
async with client.start_session() as s:
kwargs["session"] = s
await s.start_transaction(write_concern=WriteConcern(w=1))
with self.assertRaises(OperationFailure):
await op(*args, **kwargs)
await s.abort_transaction()
@async_client_context.require_transactions
@async_client_context.require_multiple_mongoses
async def test_unpin_for_next_transaction(self):
# Increase localThresholdMS and wait until both nodes are discovered
# to avoid false positives.
client = await self.async_rs_client(
async_client_context.mongos_seeds(), localThresholdMS=1000
)
await async_wait_until(lambda: len(client.nodes) > 1, "discover both mongoses")
coll = client.test.test
# Create the collection.
await coll.insert_one({})
async with client.start_session() as s:
# Session is pinned to Mongos.
async with await s.start_transaction():
await coll.insert_one({}, session=s)
addresses = set()
for _ in range(UNPIN_TEST_MAX_ATTEMPTS):
async with await s.start_transaction():
cursor = coll.find({}, session=s)
self.assertTrue(await anext(cursor))
addresses.add(cursor.address)
# Break early if we can.
if len(addresses) > 1:
break
self.assertGreater(len(addresses), 1)
@async_client_context.require_transactions
@async_client_context.require_multiple_mongoses
async def test_unpin_for_non_transaction_operation(self):
# Increase localThresholdMS and wait until both nodes are discovered
# to avoid false positives.
client = await self.async_rs_client(
async_client_context.mongos_seeds(), localThresholdMS=1000
)
await async_wait_until(lambda: len(client.nodes) > 1, "discover both mongoses")
coll = client.test.test
# Create the collection.
await coll.insert_one({})
async with client.start_session() as s:
# Session is pinned to Mongos.
async with await s.start_transaction():
await coll.insert_one({}, session=s)
addresses = set()
for _ in range(UNPIN_TEST_MAX_ATTEMPTS):
cursor = coll.find({}, session=s)
self.assertTrue(await anext(cursor))
addresses.add(cursor.address)
# Break early if we can.
if len(addresses) > 1:
break
self.assertGreater(len(addresses), 1)
@async_client_context.require_transactions
@async_client_context.require_version_min(4, 3, 4)
async def test_create_collection(self):
client = async_client_context.client
db = client.pymongo_test
coll = db.test_create_collection
self.addAsyncCleanup(coll.drop)
# Use with_transaction to avoid StaleConfig errors on sharded clusters.
async def create_and_insert(session):
coll2 = await db.create_collection(coll.name, session=session)
self.assertEqual(coll, coll2)
await coll.insert_one({}, session=session)
async with client.start_session() as s:
await s.with_transaction(create_and_insert)
# Outside a transaction we raise CollectionInvalid on existing colls.
with self.assertRaises(CollectionInvalid):
await db.create_collection(coll.name)
# Inside a transaction we raise the OperationFailure from create.
async with client.start_session() as s:
await s.start_transaction()
with self.assertRaises(OperationFailure) as ctx:
await db.create_collection(coll.name, session=s)
self.assertEqual(ctx.exception.code, 48) # NamespaceExists
@async_client_context.require_transactions
async def test_gridfs_does_not_support_transactions(self):
client = async_client_context.client
db = client.pymongo_test
gfs = AsyncGridFS(db)
bucket = AsyncGridFSBucket(db)
async def gridfs_find(*args, **kwargs):
return await gfs.find(*args, **kwargs).next()
async def gridfs_open_upload_stream(*args, **kwargs):
await (await bucket.open_upload_stream(*args, **kwargs)).write(b"1")
gridfs_ops = [
(gfs.put, (b"123",)),
(gfs.get, (1,)),
(gfs.get_version, ("name",)),
(gfs.get_last_version, ("name",)),
(gfs.delete, (1,)),
(gfs.list, ()),
(gfs.find_one, ()),
(gridfs_find, ()),
(gfs.exists, ()),
(gridfs_open_upload_stream, ("name",)),
(
bucket.upload_from_stream,
(
"name",
b"data",
),
),
(
bucket.download_to_stream,
(
1,
BytesIO(),
),
),
(
bucket.download_to_stream_by_name,
(
"name",
BytesIO(),
),
),
(bucket.delete, (1,)),
(bucket.find, ()),
(bucket.open_download_stream, (1,)),
(bucket.open_download_stream_by_name, ("name",)),
(
bucket.rename,
(
1,
"new-name",
),
),
(
bucket.rename_by_name,
(
"new-name",
"new-name2",
),
),
(bucket.delete_by_name, ("new-name2",)),
]
async with client.start_session() as s, await s.start_transaction():
for op, args in gridfs_ops:
with self.assertRaisesRegex(
InvalidOperation,
"GridFS does not support multi-document transactions",
):
await op(*args, session=s) # type: ignore
# Require 4.2+ for large (16MB+) transactions.
@async_client_context.require_version_min(4, 2)
@async_client_context.require_transactions
@unittest.skipIf(sys.platform == "win32", "Our Windows machines are too slow to pass this test")
async def test_transaction_starts_with_batched_write(self):
if "PyPy" in sys.version and async_client_context.tls:
self.skipTest(
"PYTHON-2937 PyPy is so slow sending large "
"messages over TLS that this test fails"
)
# Start a transaction with a batch of operations that needs to be
# split.
listener = OvertCommandListener()
client = await self.async_rs_client(event_listeners=[listener])
coll = client[self.db.name].test
await coll.delete_many({})
listener.reset()
self.addAsyncCleanup(coll.drop)
large_str = "\0" * (1 * 1024 * 1024)
ops: List[InsertOne[RawBSONDocument]] = [
InsertOne(RawBSONDocument(encode({"a": large_str}))) for _ in range(48)
]
async with client.start_session() as session:
async with await session.start_transaction():
await coll.bulk_write(ops, session=session) # type: ignore[arg-type]
# Assert commands were constructed properly.
self.assertEqual(
["insert", "insert", "commitTransaction"], listener.started_command_names()
)
first_cmd = listener.started_events[0].command
self.assertTrue(first_cmd["startTransaction"])
lsid = first_cmd["lsid"]
txn_number = first_cmd["txnNumber"]
for event in listener.started_events[1:]:
self.assertNotIn("startTransaction", event.command)
self.assertEqual(lsid, event.command["lsid"])
self.assertEqual(txn_number, event.command["txnNumber"])
self.assertEqual(48, await coll.count_documents({}))
@async_client_context.require_transactions
async def test_transaction_direct_connection(self):
client = await self.async_single_client()
coll = client.pymongo_test.test
# Make sure the collection exists.
await coll.insert_one({})
self.assertEqual(client.topology_description.topology_type_name, "Single")
async def find(*args, **kwargs):
return coll.find(*args, **kwargs)
async def find_raw_batches(*args, **kwargs):
return coll.find_raw_batches(*args, **kwargs)
ops = [
(coll.bulk_write, [[InsertOne[dict]({})]]),
(coll.insert_one, [{}]),
(coll.insert_many, [[{}, {}]]),
(coll.replace_one, [{}, {}]),
(coll.update_one, [{}, {"$set": {"a": 1}}]),
(coll.update_many, [{}, {"$set": {"a": 1}}]),
(coll.delete_one, [{}]),
(coll.delete_many, [{}]),
(coll.find_one_and_replace, [{}, {}]),
(coll.find_one_and_update, [{}, {"$set": {"a": 1}}]),
(coll.find_one_and_delete, [{}, {}]),
(coll.find_one, [{}]),
(coll.count_documents, [{}]),
(coll.distinct, ["foo"]),
(coll.aggregate, [[]]),
(find, [{}]),
(coll.aggregate_raw_batches, [[]]),
(find_raw_batches, [{}]),
(coll.database.command, ["find", coll.name]),
]
for f, args in ops:
async with client.start_session() as s, await s.start_transaction():
res = await f(*args, session=s) # type:ignore[operator]
if isinstance(res, (AsyncCommandCursor, AsyncCursor)):
await res.to_list()
@async_client_context.require_transactions
async def test_transaction_pool_cleared_error_labelled_transient(self):
c = await self.async_single_client()
with self.assertRaises(AutoReconnect) as context:
async with c.start_session() as session:
async with await session.start_transaction():
server = await c._select_server(writable_server_selector, session, "test")
# Pause the server's pool, causing it to fail connection checkout.
server.pool.state = PoolState.PAUSED
async with c._checkout(server, session):
pass
# Verify that the TransientTransactionError label is present in the error.
self.assertTrue(context.exception.has_error_label("TransientTransactionError"))
class PatchSessionTimeout:
"""Patches the client_session's with_transaction timeout for testing."""
def __init__(self, mock_timeout):
self.real_timeout = client_session._WITH_TRANSACTION_RETRY_TIME_LIMIT
self.mock_timeout = mock_timeout
def __enter__(self):
client_session._WITH_TRANSACTION_RETRY_TIME_LIMIT = self.mock_timeout
return self
def __exit__(self, exc_type, exc_val, exc_tb):
client_session._WITH_TRANSACTION_RETRY_TIME_LIMIT = self.real_timeout
class TestTransactionsConvenientAPI(AsyncTransactionsBase):
async def asyncSetUp(self) -> None:
await super().asyncSetUp()
self.mongos_clients = []
if async_client_context.supports_transactions():
for address in async_client_context.mongoses:
self.mongos_clients.append(await self.async_single_client("{}:{}".format(*address)))
async def set_fail_point(self, command_args):
clients = self.mongos_clients if self.mongos_clients else [self.client]
for client in clients:
await self.configure_fail_point(client, command_args)
@async_client_context.require_transactions
async def test_callback_raises_custom_error(self):
class _MyException(Exception):
pass
async def raise_error(_):
raise _MyException
async with self.client.start_session() as s:
with self.assertRaises(_MyException):
await s.with_transaction(raise_error)
@async_client_context.require_transactions
async def test_callback_returns_value(self):
async def callback(_):
return "Foo"
async with self.client.start_session() as s:
self.assertEqual(await s.with_transaction(callback), "Foo")
await self.db.test.insert_one({})
async def callback2(session):
await self.db.test.insert_one({}, session=session)
return "Foo"
async with self.client.start_session() as s:
self.assertEqual(await s.with_transaction(callback2), "Foo")
@async_client_context.require_transactions
async def test_callback_not_retried_after_timeout(self):
listener = OvertCommandListener()
client = await self.async_rs_client(event_listeners=[listener])
coll = client[self.db.name].test
async def callback(session):
await coll.insert_one({}, session=session)
err: dict = {
"ok": 0,
"errmsg": "Transaction 7819 has been aborted.",
"code": 251,
"codeName": "NoSuchTransaction",
"errorLabels": ["TransientTransactionError"],
}
raise OperationFailure(err["errmsg"], err["code"], err)
# Create the collection.
await coll.insert_one({})
listener.reset()
async with client.start_session() as s:
with PatchSessionTimeout(0):
with self.assertRaises(OperationFailure):
await s.with_transaction(callback)
self.assertEqual(listener.started_command_names(), ["insert", "abortTransaction"])
@async_client_context.require_test_commands
@async_client_context.require_transactions
async def test_callback_not_retried_after_commit_timeout(self):
listener = OvertCommandListener()
client = await self.async_rs_client(event_listeners=[listener])
coll = client[self.db.name].test
async def callback(session):
await coll.insert_one({}, session=session)
# Create the collection.
await coll.insert_one({})
await self.set_fail_point(
{
"configureFailPoint": "failCommand",
"mode": {"times": 1},
"data": {
"failCommands": ["commitTransaction"],
"errorCode": 251, # NoSuchTransaction
},
}
)
self.addAsyncCleanup(
self.set_fail_point, {"configureFailPoint": "failCommand", "mode": "off"}
)
listener.reset()
async with client.start_session() as s:
with PatchSessionTimeout(0):
with self.assertRaises(OperationFailure):
await s.with_transaction(callback)
self.assertEqual(listener.started_command_names(), ["insert", "commitTransaction"])
@async_client_context.require_test_commands
@async_client_context.require_transactions
async def test_commit_not_retried_after_timeout(self):
listener = OvertCommandListener()
client = await self.async_rs_client(event_listeners=[listener])
coll = client[self.db.name].test
async def callback(session):
await coll.insert_one({}, session=session)
# Create the collection.
await coll.insert_one({})
await self.set_fail_point(
{
"configureFailPoint": "failCommand",
"mode": {"times": 2},
"data": {"failCommands": ["commitTransaction"], "closeConnection": True},
}
)
self.addAsyncCleanup(
self.set_fail_point, {"configureFailPoint": "failCommand", "mode": "off"}
)
listener.reset()
async with client.start_session() as s:
with PatchSessionTimeout(0):
with self.assertRaises(ConnectionFailure):
await s.with_transaction(callback)
# One insert for the callback and two commits (includes the automatic
# retry).
self.assertEqual(
listener.started_command_names(), ["insert", "commitTransaction", "commitTransaction"]
)
# Tested here because this supports Motor's convenient transactions API.
@async_client_context.require_transactions
async def test_in_transaction_property(self):
client = async_client_context.client
coll = client.test.testcollection
await coll.insert_one({})
self.addAsyncCleanup(coll.drop)
async with client.start_session() as s:
self.assertFalse(s.in_transaction)
await s.start_transaction()
self.assertTrue(s.in_transaction)
await coll.insert_one({}, session=s)
self.assertTrue(s.in_transaction)
await s.commit_transaction()
self.assertFalse(s.in_transaction)
async with client.start_session() as s:
await s.start_transaction()
# commit empty transaction
await s.commit_transaction()
self.assertFalse(s.in_transaction)
async with client.start_session() as s:
await s.start_transaction()
await s.abort_transaction()
self.assertFalse(s.in_transaction)
# Using a callback
async def callback(session):
self.assertTrue(session.in_transaction)
async with client.start_session() as s:
self.assertFalse(s.in_transaction)
await s.with_transaction(callback)
self.assertFalse(s.in_transaction)
class TestOptionsInsideTransactionProse(AsyncTransactionsBase):
@async_client_context.require_transactions
@async_client_context.require_no_standalone
async def test_case_1(self):
# Write concern not inherited from collection object inside transaction
# Create a MongoClient running against a configured sharded/replica set/load balanced cluster.
client = async_client_context.client
coll = client[self.db.name].test
await coll.delete_many({})
# Start a new session on the client.
async with client.start_session() as s:
# Start a transaction on the session.
await s.start_transaction()
# Instantiate a collection object in the driver with a default write concern of { w: 0 }.
inner_coll = coll.with_options(write_concern=WriteConcern(w=0))
# Insert the document { n: 1 } on the instantiated collection.
result = await inner_coll.insert_one({"n": 1}, session=s)
# Commit the transaction.
await s.commit_transaction()
# End the session.
# Ensure the document was inserted and no error was thrown from the transaction.
assert result.inserted_id is not None
if __name__ == "__main__":
unittest.main()
|