Skip to content

Commit b752632

Browse files
committed
fix: update transaction handling in AccountingPolicy to ensure proper cancellation on failure
- Added transaction cancellation logic in case of failure during transaction creation and confirmation. - Introduced a new private method _cancel_transaction to handle transaction cancellations with the accounting service.
1 parent e7a691e commit b752632

2 files changed

Lines changed: 40 additions & 22 deletions

File tree

backend/syftai_space/components/policy_types/accounting/accounting_type.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ def pre_hook(
182182
credentials = AccountingCredentials.from_context(context)
183183
amount = config.price
184184

185+
transaction = None
185186
try:
186187
transaction = self._create_transaction(
187188
credentials,
@@ -193,6 +194,9 @@ def pre_hook(
193194
transactions.append({"id": transaction.id, "amount": amount})
194195
total_amount += amount
195196
except Exception as e:
197+
if transaction:
198+
self._cancel_transaction(credentials, transaction.id)
199+
196200
raise PolicyViolationError(
197201
message=f"Failed to create accounting transaction: {e}",
198202
policy_type=self.NAME,
@@ -221,7 +225,7 @@ def _create_transaction(
221225
return accounting_client.create_delegated_transaction(
222226
senderEmail=sender_email,
223227
amount=amount,
224-
transaction_token=transaction_token,
228+
token=transaction_token,
225229
appEpPath=endpoint_slug,
226230
)
227231

@@ -259,6 +263,9 @@ def post_hook(
259263
try:
260264
self._confirm_transaction(credentials, transaction["id"])
261265
except Exception as e:
266+
if transaction.get("id"):
267+
self._cancel_transaction(credentials, transaction["id"])
268+
262269
raise PolicyViolationError(
263270
message=f"Failed to confirm accounting transaction: {e}",
264271
policy_type=self.NAME,
@@ -277,6 +284,17 @@ def post_hook(
277284

278285
return context
279286

287+
def _cancel_transaction(
288+
self, credentials: AccountingCredentials, transaction_id: str
289+
) -> None:
290+
"""Cancel a transaction with the accounting service."""
291+
accounting_client = UserClient(
292+
url=str(credentials.url),
293+
email=str(credentials.email),
294+
password=credentials.password,
295+
)
296+
accounting_client.cancel_transaction(id=transaction_id)
297+
280298
def _confirm_transaction(
281299
self, credentials: AccountingCredentials, transaction_id: str
282300
) -> None:

backend/uv.lock

Lines changed: 21 additions & 21 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)