Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement consistent handling of TransactionCanceled errors. #171

Merged
merged 1 commit into from
Jan 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 13 additions & 13 deletions src/aiodynamo/errors.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import json
from typing import Any, Dict
from typing import Any, Dict, List, Optional, TypedDict


class CancellationReason(TypedDict):
Code: Optional[str]
Message: Optional[str]
aclemons marked this conversation as resolved.
Show resolved Hide resolved


class AIODynamoError(Exception):
Expand Down Expand Up @@ -110,7 +115,12 @@ class PointInTimeRecoveryUnavailable(AIODynamoError):


class TransactionCanceled(AIODynamoError):
pass
def __init__(self, body: Dict[str, Any]):
aclemons marked this conversation as resolved.
Show resolved Hide resolved
self.body = body
self.cancellation_reasons: List[CancellationReason] = self.body[
"CancellationReasons"
]
super().__init__(body)


class TransactionEmpty(AIODynamoError):
Expand Down Expand Up @@ -207,17 +217,7 @@ def exception_from_response(status: int, body: bytes) -> Exception:
return ServiceUnavailable()
try:
data = json.loads(body)
error = ERRORS[data["__type"].split("#", 1)[-1]](data)
if isinstance(error, TransactionCanceled):
error = extract_error_from_transaction_canceled(data)
error: Exception = ERRORS[data["__type"].split("#", 1)[-1]](data)
return error
except Exception:
return UnknownError(status, body)


def extract_error_from_transaction_canceled(data: Dict[str, Any]) -> AIODynamoError:
try:
error = data["CancellationReasons"][0]
return ERRORS[f"{error['Code']}Exception"](error["Message"])
except Exception:
return ERRORS[data["__type"].split("#", 1)[-1]](data)
38 changes: 34 additions & 4 deletions tests/integration/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,14 +624,34 @@ async def test_transact_write_items_put(client: Client, table: TableName) -> Non
await client.transact_write_items(items=puts)
assert len([item async for item in client.query(table, HashKey("h", "h"))]) == 2

with pytest.raises(errors.ConditionalCheckFailed):
with pytest.raises(errors.TransactionCanceled) as excinfo:
put = Put(
table=table,
item={"h": "h", "r": "0", "s": "initial"},
condition=F("h").does_not_exist(),
)
await client.transact_write_items(items=[put])

assert len(excinfo.value.cancellation_reasons) == 1
assert excinfo.value.cancellation_reasons[0]["Code"] == "ConditionalCheckFailed"

with pytest.raises(errors.TransactionCanceled) as excinfo:
put = Put(
table=table,
item={"h": "h", "r": "3", "s": "initial"},
condition=F("h").does_not_exist(),
)
put_fail = Put(
table=table,
item={"h": "h", "r": "0", "s": "initial"},
condition=F("h").does_not_exist(),
)
await client.transact_write_items(items=[put, put_fail])

assert len(excinfo.value.cancellation_reasons) == 2
assert excinfo.value.cancellation_reasons[0]["Code"] == "None"
assert excinfo.value.cancellation_reasons[1]["Code"] == "ConditionalCheckFailed"


@pytest.mark.usefixtures("supports_transactions")
async def test_transact_write_items_update(client: Client, table: TableName) -> None:
Expand All @@ -647,7 +667,7 @@ async def test_transact_write_items_update(client: Client, table: TableName) ->
query = await client.query_single_page(table, HashKey("h", "h"))
assert query.items[0]["s"] == "changed"

with pytest.raises(errors.ConditionalCheckFailed):
with pytest.raises(errors.TransactionCanceled) as excinfo:
update = Update(
table=table,
key={"h": "h", "r": "1"},
Expand All @@ -656,6 +676,9 @@ async def test_transact_write_items_update(client: Client, table: TableName) ->
)
await client.transact_write_items(items=[update])

assert len(excinfo.value.cancellation_reasons) == 1
assert excinfo.value.cancellation_reasons[0]["Code"] == "ConditionalCheckFailed"


@pytest.mark.usefixtures("supports_transactions")
async def test_transact_write_items_delete(client: Client, table: TableName) -> None:
Expand All @@ -670,14 +693,18 @@ async def test_transact_write_items_delete(client: Client, table: TableName) ->
assert len([item async for item in client.query(table, HashKey("h", "h"))]) == 0

await client.put_item(table=table, item={"h": "h", "r": "1", "s": "initial"})
with pytest.raises(errors.ConditionalCheckFailed):

with pytest.raises(errors.TransactionCanceled) as excinfo:
delete = Delete(
table=table,
key={"h": "h", "r": "1"},
condition=F("s").not_equals("initial"),
)
await client.transact_write_items(items=[delete])

assert len(excinfo.value.cancellation_reasons) == 1
assert excinfo.value.cancellation_reasons[0]["Code"] == "ConditionalCheckFailed"


@pytest.mark.usefixtures("supports_transactions")
async def test_transact_write_items_condition_check(
Expand All @@ -687,9 +714,12 @@ async def test_transact_write_items_condition_check(
condition = ConditionCheck(
table=table, key={"h": "h", "r": "1"}, condition=F("s").not_equals("initial")
)
with pytest.raises(errors.ConditionalCheckFailed):
with pytest.raises(errors.TransactionCanceled) as excinfo:
await client.transact_write_items(items=[condition])

assert len(excinfo.value.cancellation_reasons) == 1
assert excinfo.value.cancellation_reasons[0]["Code"] == "ConditionalCheckFailed"

condition = ConditionCheck(
table=table, key={"h": "h", "r": "1"}, condition=F("s").equals("initial")
)
Expand Down