modular-sdk 8.1.0__tar.gz → 8.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. modular_sdk-8.2.0/PKG-INFO +221 -0
  2. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/README.md +38 -0
  3. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/commons/__init__.py +7 -1
  4. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/commons/constants.py +0 -1
  5. modular_sdk-8.2.0/modular_sdk/commons/exception.py +52 -0
  6. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/commons/helpers.py +11 -0
  7. modular_sdk-8.2.0/modular_sdk/commons/transaction_helper.py +129 -0
  8. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/pynamongo/__init__.py +13 -2
  9. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/pynamongo/adapter.py +112 -20
  10. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/pynamongo/models.py +4 -1
  11. modular_sdk-8.2.0/modular_sdk/models/pynamongo/transaction.py +289 -0
  12. modular_sdk-8.2.0/modular_sdk.egg-info/PKG-INFO +221 -0
  13. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk.egg-info/SOURCES.txt +2 -0
  14. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk.egg-info/requires.txt +1 -1
  15. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/pyproject.toml +4 -5
  16. modular_sdk-8.1.0/PKG-INFO +0 -386
  17. modular_sdk-8.1.0/modular_sdk/commons/exception.py +0 -8
  18. modular_sdk-8.1.0/modular_sdk.egg-info/PKG-INFO +0 -386
  19. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/LICENSE +0 -0
  20. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/MANIFEST.in +0 -0
  21. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/__init__.py +0 -0
  22. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/commons/log_helper.py +0 -0
  23. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/commons/time_helper.py +0 -0
  24. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/commons/trace_helper.py +0 -0
  25. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/connections/__init__.py +0 -0
  26. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/connections/rabbit_connection.py +0 -0
  27. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/__init__.py +0 -0
  28. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/application.py +0 -0
  29. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/base_meta.py +0 -0
  30. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/customer.py +0 -0
  31. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/customer_settings.py +0 -0
  32. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/execution_trace.py +0 -0
  33. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/heartbeat.py +0 -0
  34. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/job.py +0 -0
  35. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/operation_mode.py +0 -0
  36. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/parent.py +0 -0
  37. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/pynamongo/attributes.py +0 -0
  38. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/pynamongo/convertors.py +0 -0
  39. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/pynamongo/indexes_creator.py +0 -0
  40. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/pynamongo/patch.py +0 -0
  41. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/region.py +0 -0
  42. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/setting.py +0 -0
  43. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/tenant.py +0 -0
  44. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/models/tenant_settings.py +0 -0
  45. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/modular.py +0 -0
  46. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/__init__.py +0 -0
  47. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/application_service.py +0 -0
  48. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/aws_creds_provider.py +0 -0
  49. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/customer_service.py +0 -0
  50. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/customer_settings_service.py +0 -0
  51. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/environment_service.py +0 -0
  52. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/events_service.py +0 -0
  53. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/impl/__init__.py +0 -0
  54. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/impl/maestro_credentials_service.py +0 -0
  55. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/impl/maestro_http_transport_service.py +0 -0
  56. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/impl/maestro_rabbit_transport_service.py +0 -0
  57. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/impl/maestro_signature_builder.py +0 -0
  58. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/job_service.py +0 -0
  59. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/jwt_token_service.py +0 -0
  60. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/lambda_service.py +0 -0
  61. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/parent_service.py +0 -0
  62. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/rabbit_transport_service.py +0 -0
  63. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/region_service.py +0 -0
  64. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/settings_management_service.py +0 -0
  65. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/sqs_service.py +0 -0
  66. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/ssm_service.py +0 -0
  67. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/sts_service.py +0 -0
  68. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/tenant_service.py +0 -0
  69. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/tenant_settings_service.py +0 -0
  70. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/services/thread_local_storage_service.py +0 -0
  71. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/utils/__init__.py +0 -0
  72. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/utils/job_tracer/__init__.py +0 -0
  73. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/utils/job_tracer/abstract.py +0 -0
  74. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/utils/job_tracer/generic.py +0 -0
  75. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/utils/operation_mode/__init__.py +0 -0
  76. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/utils/operation_mode/abstract.py +0 -0
  77. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/utils/operation_mode/generic.py +0 -0
  78. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/utils/runtime_tracer/__init__.py +0 -0
  79. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/utils/runtime_tracer/abstract.py +0 -0
  80. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk/utils/runtime_tracer/generic.py +0 -0
  81. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk.egg-info/dependency_links.txt +0 -0
  82. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/modular_sdk.egg-info/top_level.txt +0 -0
  83. {modular_sdk-8.1.0 → modular_sdk-8.2.0}/setup.cfg +0 -0
@@ -0,0 +1,221 @@
1
+ Metadata-Version: 2.4
2
+ Name: modular_sdk
3
+ Version: 8.2.0
4
+ Summary: Data level integration for services built atop of Modular Framework
5
+ Author-email: EPAM Systems <support@syndicate.team>
6
+ Project-URL: Homepage, https://github.com/epam/modular-sdk
7
+ Project-URL: Documentation, https://github.com/epam/modular-sdk/blob/main/README.md
8
+ Project-URL: Repository, https://github.com/me/spam.git
9
+ Project-URL: Changelog, https://github.com/epam/modular-sdk/blob/main/CHANGELOG.md
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Classifier: Operating System :: OS Independent
14
+ Requires-Python: <4,>=3.14
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: pika==1.3.2
18
+ Requires-Dist: boto3<2,>=1.36.11
19
+ Requires-Dist: botocore<2,>=1.36.11
20
+ Requires-Dist: pymongo~=4.11.2
21
+ Requires-Dist: python-dateutil<3,>=2.9
22
+ Requires-Dist: cachetools<8,>=5.5.1
23
+ Requires-Dist: pynamodb==6.1.0
24
+ Provides-Extra: cryptography
25
+ Requires-Dist: cryptography~=50.0.2; extra == "cryptography"
26
+ Provides-Extra: jwt
27
+ Requires-Dist: PyJWT<3,>=2.8.0; extra == "jwt"
28
+ Provides-Extra: hvac
29
+ Requires-Dist: hvac~=2.1.0; extra == "hvac"
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest>=9.0.2; extra == "test"
32
+ Requires-Dist: mongomock>=4.3.0; extra == "test"
33
+ Requires-Dist: pytest-xdist>=3.8.0; extra == "test"
34
+ Requires-Dist: pytest-cov>=7.0.0; extra == "test"
35
+ Provides-Extra: all
36
+ Requires-Dist: modular-sdk[cryptography,hvac,jwt,test]; extra == "all"
37
+ Dynamic: license-file
38
+
39
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](http://www.apache.org/licenses/LICENSE-2.0.txt)
40
+
41
+ [![PyPI - Version](https://img.shields.io/pypi/v/modular-sdk.svg)](https://pypi.org/project/modular-sdk)
42
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/modular-sdk.svg)](https://pypi.org/project/modular-sdk)
43
+
44
+
45
+ # Modular SDK
46
+
47
+ You use Modular SDK to create, configure, and manage common entities, such as:
48
+ - Customers;
49
+ - Tenants;
50
+ - TenantSettings;
51
+ - Regions;
52
+ - Applications;
53
+ - Parents;
54
+
55
+ ### Prerequisites
56
+ - Python 3.14 required
57
+
58
+ ### [Building distribution archives](https://packaging.python.org/en/latest/tutorials/packaging-projects/#generating-distribution-archives)
59
+ - Make sure you have the latest version of PyPA’s build installed: `python3 -m pip install --upgrade build`
60
+ - Run the command form the same directory where `pyptoject.toml` is located: `python3 -m build`
61
+ - This command should output a lot of text and once completed should generate two files in the dist directory:
62
+ ```
63
+ dist/
64
+ modular_sdk-{version}.tar.gz
65
+ modular_sdk-{version}-py3-none-any.whl
66
+ ```
67
+
68
+ ### Installation
69
+ - `pip install modular-sdk`
70
+
71
+ ### Usage
72
+
73
+ To use Modular SDK, you must import, configure and indicate which service or
74
+ services you're going to use:
75
+
76
+ ```python
77
+ from modular_sdk.modular import Modular
78
+
79
+ modular_sdk = Modular()
80
+
81
+ parent_service = modular_sdk.parent_service()
82
+ tenant_service = modular_sdk.tenant_service()
83
+ ```
84
+
85
+ For services that aren't tied to the `service_mode` configuration, you can use
86
+ `ModularServiceProvider`:
87
+
88
+ ```python
89
+ from modular_sdk.modular import ModularServiceProvider
90
+
91
+ modular_sdk = ModularServiceProvider()
92
+
93
+ thread_local_storage_service = modular_sdk.thread_local_storage_service()
94
+ ```
95
+
96
+ For now, Modular provides 3 ways of DB access. Depends on the way of database
97
+ connection, different sets of env variables must be set:
98
+ 1. Onprem, Mongodb:
99
+ `modular_service_mode`: `docker`,
100
+ `modular_mongo_user`: `$MONGO_USER`,
101
+ `modular_mongo_password`: `$MONGO_PASSWORD`,
102
+ `modular_mongo_url`: `$MONGO_URL`,
103
+ `modular_mongo_db_name`: `$MONGO_DB_NAME`,
104
+ `modular_mongo_srv`: `True`, # Optional
105
+ Alternatively, instead of specifying `modular_mongo_user`, `modular_mongo_password`,
106
+ `modular_mongo_url`, and `modular_mongo_srv`, you can use:
107
+ `modular_mongo_uri`: `$MONGO_URI` # Format: `mongodb+srv://<USER>:<PASSWORD>@<URL>/`
108
+ 2. SaaS, DynamoDB (cross-account access):
109
+ `modular_service_mode`: `saas` # Optional
110
+ `modular_assume_role_arn`: `$ASSUME_ROLE_ARN`
111
+ 3. SAAS, DynamoDB (same AWS account):
112
+ `modular_service_mode`: `saas` # Optional
113
+
114
+ Alternatively, you can pass these parameters (fully or partially) on
115
+ initialization:
116
+
117
+ ```python
118
+ from modular_sdk.modular import Modular
119
+
120
+ modular_sdk = Modular(modular_service_mode='docker',
121
+ modular_mongo_user='MONGO_USER',
122
+ modular_mongo_password='MONGO_PASSWORD',
123
+ modular_mongo_url='MONGO_URL',
124
+ modular_mongo_db_name='DB_NAME')
125
+
126
+ # initialize some services
127
+ application_service = modular_sdk.application_service()
128
+ parent_service = modular_sdk.parent_service()
129
+ ```
130
+
131
+ #### More examples
132
+ Example 1: List Maestro Customers
133
+
134
+ ```python
135
+ from modular_sdk.modular import Modular
136
+
137
+ # initializing application service
138
+ customer_service = Modular().customer_service()
139
+
140
+ # listing available customers
141
+ customers = customer_service.list()
142
+
143
+ # printing customer names
144
+ for customer in customers:
145
+ print(customer.name)
146
+ ```
147
+
148
+
149
+ Example 2: Update Maestro Application
150
+
151
+ ```python
152
+ from modular_sdk.modular import Modular
153
+
154
+ # initializing application service
155
+ application_service = Modular().application_service()
156
+
157
+ # extracting application by id
158
+ application = application_service.get_application_by_id(
159
+ application_id="$APP_ID")
160
+
161
+ # updating application description
162
+ description_to_set = 'Updated application description'
163
+ application_service.update(application=application,
164
+ description=description_to_set)
165
+
166
+ # saving updated application
167
+ application_service.save(application=application)
168
+ ```
169
+
170
+ Example 3: Delete Maestro Parent
171
+
172
+ ```python
173
+ from modular_sdk.modular import Modular
174
+
175
+ # initializing parent service
176
+ parent_service = Modular().parent_service()
177
+
178
+ # extracting parent by id
179
+ parent = parent_service.get_parent_by_id(parent_id="$PARENT_ID")
180
+
181
+ # deleting parent
182
+ parent_service.mark_deleted(parent=parent)
183
+ ```
184
+
185
+ ### Transactions
186
+
187
+ Repositories can accept an optional transaction session and use it for all database writes:
188
+
189
+ ```python
190
+ from modular_sdk.models.pynamongo import TransactionAdapter
191
+
192
+ # The backend is selected from the model configuration.
193
+ adapter = TransactionAdapter(model=Quota)
194
+
195
+ with adapter.transaction() as session:
196
+ quota_repository.reserve(quota_id, session=session)
197
+ job_repository.create(job, session=session)
198
+ ```
199
+
200
+ Inside a repository, write through the session when one is provided:
201
+ ```python
202
+ # job_repository.py
203
+
204
+ def create(self, job, session=None):
205
+ if session is None:
206
+ return job.save()
207
+ return session.save(job)
208
+ ```
209
+
210
+ Always pass the session to every write that belongs to the transaction.
211
+ Calling `job.save()` directly inside the `with` block bypasses the
212
+ transaction.
213
+
214
+ The DynamoDB transaction is committed when the context exits successfully and
215
+ is rolled back when an exception is raised. DynamoDB transactions support up
216
+ to 100 actions, allow only one action per item, and all items must be in the
217
+ same region. An empty DynamoDB transaction fails on commit.
218
+
219
+ MongoDB transactions require a replica set or sharded cluster. MongoDB allows
220
+ multiple writes to the same document, and an empty MongoDB transaction
221
+ commits successfully.
@@ -143,3 +143,41 @@ parent = parent_service.get_parent_by_id(parent_id="$PARENT_ID")
143
143
  # deleting parent
144
144
  parent_service.mark_deleted(parent=parent)
145
145
  ```
146
+
147
+ ### Transactions
148
+
149
+ Repositories can accept an optional transaction session and use it for all database writes:
150
+
151
+ ```python
152
+ from modular_sdk.models.pynamongo import TransactionAdapter
153
+
154
+ # The backend is selected from the model configuration.
155
+ adapter = TransactionAdapter(model=Quota)
156
+
157
+ with adapter.transaction() as session:
158
+ quota_repository.reserve(quota_id, session=session)
159
+ job_repository.create(job, session=session)
160
+ ```
161
+
162
+ Inside a repository, write through the session when one is provided:
163
+ ```python
164
+ # job_repository.py
165
+
166
+ def create(self, job, session=None):
167
+ if session is None:
168
+ return job.save()
169
+ return session.save(job)
170
+ ```
171
+
172
+ Always pass the session to every write that belongs to the transaction.
173
+ Calling `job.save()` directly inside the `with` block bypasses the
174
+ transaction.
175
+
176
+ The DynamoDB transaction is committed when the context exits successfully and
177
+ is rolled back when an exception is raised. DynamoDB transactions support up
178
+ to 100 actions, allow only one action per item, and all items must be in the
179
+ same region. An empty DynamoDB transaction fails on commit.
180
+
181
+ MongoDB transactions require a replica set or sharded cluster. MongoDB allows
182
+ multiple writes to the same document, and an empty MongoDB transaction
183
+ commits successfully.
@@ -7,7 +7,13 @@ from functools import partial
7
7
  from uuid import uuid4
8
8
  from typing import Generator, TypeVar
9
9
 
10
- from modular_sdk.commons.exception import ModularException
10
+ from modular_sdk.commons.exception import (
11
+ ConditionalWriteFailed,
12
+ DuplicateKeyError,
13
+ ModularException,
14
+ TransactionError,
15
+ TransientTransactionError,
16
+ )
11
17
  from modular_sdk.commons.log_helper import get_logger
12
18
 
13
19
  _LOG = get_logger(__name__)
@@ -316,7 +316,6 @@ class Cloud(str, Enum):
316
316
  VSPHERE = 'VSPHERE'
317
317
  VMWARE = 'VMWARE' # VCloudDirector group
318
318
  NUTANIX = 'NUTANIX'
319
- KUBERNETES = 'KUBERNETES'
320
319
 
321
320
  @classmethod
322
321
  def iter(cls):
@@ -0,0 +1,52 @@
1
+ from typing import Any
2
+
3
+
4
+ class ModularException(Exception):
5
+
6
+ def __init__(self, code, content):
7
+ self.code = code
8
+ self.content = content
9
+
10
+ def __str__(self):
11
+ return f'{self.code}:{self.content}'
12
+
13
+
14
+ class TransactionError(Exception):
15
+ """
16
+ Base class for errors raised by the transaction adapter.
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ message: str,
22
+ *,
23
+ model: type[Any] | None = None,
24
+ collection=None,
25
+ ):
26
+ super().__init__(message)
27
+ self.model = model
28
+ self.collection = collection
29
+ self.collection_name = (
30
+ getattr(collection, 'name', collection)
31
+ if collection is not None
32
+ else None
33
+ )
34
+ self.model_name = model.__name__ if model is not None else None
35
+
36
+
37
+ class ConditionalWriteFailed(TransactionError):
38
+ """
39
+ Raised when a transaction condition is not satisfied.
40
+ """
41
+
42
+
43
+ class DuplicateKeyError(TransactionError):
44
+ """
45
+ Raised when a transaction attempts to write a duplicate key.
46
+ """
47
+
48
+
49
+ class TransientTransactionError(TransactionError):
50
+ """
51
+ Raised when a transaction fails for a potentially retryable reason.
52
+ """
@@ -1,3 +1,6 @@
1
+ from typing import Any
2
+
3
+
1
4
  class classproperty:
2
5
  """
3
6
  Decorator that converts a method with a single cls argument into a property
@@ -14,3 +17,11 @@ class classproperty:
14
17
  def getter(self, method):
15
18
  self.fget = method
16
19
  return self
20
+
21
+
22
+ def model_collection(model: type[Any] | None, adapter=None):
23
+ if model is None:
24
+ return None
25
+ if adapter is not None:
26
+ return adapter.get_collection(model)
27
+ return getattr(getattr(model, 'Meta', None), 'table_name', None)
@@ -0,0 +1,129 @@
1
+ from typing import Any
2
+
3
+ from botocore.exceptions import ClientError
4
+ from pynamodb.exceptions import (
5
+ DeleteError,
6
+ PutError,
7
+ TransactWriteError as PynamoDBTransactWriteError,
8
+ UpdateError,
9
+ )
10
+ from pymongo.errors import (
11
+ AutoReconnect,
12
+ ConnectionFailure,
13
+ DuplicateKeyError as MongoDuplicateKeyError,
14
+ WTimeoutError,
15
+ )
16
+
17
+ from modular_sdk.commons.exception import (
18
+ ConditionalWriteFailed,
19
+ DuplicateKeyError,
20
+ TransactionError,
21
+ TransientTransactionError,
22
+ )
23
+
24
+
25
+ def error_chain(error: BaseException):
26
+ seen = set()
27
+ current = error
28
+ while current is not None and id(current) not in seen:
29
+ seen.add(id(current))
30
+ yield current
31
+ current = getattr(current, 'cause', None) or current.__cause__
32
+
33
+
34
+ def error_code(error: BaseException) -> str | None:
35
+ response = getattr(error, 'response', None)
36
+ if isinstance(response, dict):
37
+ return response.get('Error', {}).get('Code')
38
+ details = getattr(error, 'details', None)
39
+ if isinstance(details, dict):
40
+ return details.get('codeName') or details.get('code')
41
+ return None
42
+
43
+
44
+ def cancellation_codes(error: BaseException) -> set[str]:
45
+ response = getattr(error, 'response', None)
46
+ reasons = response.get('CancellationReasons', []) if isinstance(
47
+ response, dict
48
+ ) else []
49
+ return {
50
+ reason.get('Code')
51
+ for reason in reasons
52
+ if isinstance(reason, dict) and reason.get('Code')
53
+ }
54
+
55
+
56
+ def is_transient(error: BaseException) -> bool:
57
+ transient_codes = {
58
+ 'TransactionConflict',
59
+ 'ProvisionedThroughputExceeded',
60
+ 'ThrottlingError',
61
+ 'RequestLimitExceeded',
62
+ 'InternalServerError',
63
+ 'TransactionInProgress',
64
+ }
65
+ for cause in error_chain(error):
66
+ if isinstance(cause, (AutoReconnect, ConnectionFailure, WTimeoutError)):
67
+ return True
68
+ has_error_label = getattr(cause, 'has_error_label', None)
69
+ if callable(has_error_label) and (
70
+ has_error_label('TransientTransactionError')
71
+ or has_error_label('UnknownTransactionCommitResult')
72
+ ):
73
+ return True
74
+ codes = {error_code(cause)} | cancellation_codes(cause)
75
+ if codes & transient_codes:
76
+ return True
77
+ return False
78
+
79
+
80
+ def is_duplicate(error: BaseException) -> bool:
81
+ for cause in error_chain(error):
82
+ codes = {error_code(cause)} | cancellation_codes(cause)
83
+ if isinstance(cause, MongoDuplicateKeyError) or codes & {
84
+ 'DuplicateKey',
85
+ 'DuplicateItem',
86
+ }:
87
+ return True
88
+ return False
89
+
90
+
91
+ def is_conditional(error: BaseException) -> bool:
92
+ conditional_codes = {
93
+ 'ConditionalCheckFailed',
94
+ 'ConditionalCheckFailedException',
95
+ 'TransactionCanceledException',
96
+ }
97
+ for cause in error_chain(error):
98
+ if isinstance(cause, (PutError, UpdateError, DeleteError)):
99
+ return True
100
+ codes = {error_code(cause)} | cancellation_codes(cause)
101
+ if isinstance(cause, (PynamoDBTransactWriteError, ClientError)):
102
+ if codes & conditional_codes:
103
+ return True
104
+ return False
105
+
106
+
107
+ def translate_error(
108
+ error: BaseException,
109
+ *,
110
+ model: type[Any] | None,
111
+ collection=None,
112
+ ) -> None:
113
+ if isinstance(error, TransactionError):
114
+ raise error
115
+ if is_transient(error):
116
+ error_type = TransientTransactionError
117
+ elif is_duplicate(error):
118
+ error_type = DuplicateKeyError
119
+ elif is_conditional(error):
120
+ error_type = ConditionalWriteFailed
121
+ else:
122
+ raise error
123
+
124
+ message = str(error) or error_type.__name__
125
+ raise error_type(
126
+ message,
127
+ model=model,
128
+ collection=collection,
129
+ ) from error
@@ -261,7 +261,6 @@ Almost all public methods of Model are supported. Those are:
261
261
 
262
262
  What PynamoDB features are not supported:
263
263
  - Polymorphism through the use of discriminators (https://pynamodb.readthedocs.io/en/stable/polymorphism.html)
264
- - Transaction Operations (https://pynamodb.readthedocs.io/en/stable/transaction.html)
265
264
  """
266
265
  from .adapter import PynamoDBToPymongoAdapter, ResultIterator
267
266
  from .attributes import (
@@ -279,6 +278,13 @@ from .attributes import (
279
278
  from .convertors import PynamoDBModelToMongoDictSerializer
280
279
  from .patch import patch_attributes
281
280
  from .indexes_creator import IndexesCreator
281
+ from modular_sdk.commons import (
282
+ ConditionalWriteFailed,
283
+ DuplicateKeyError,
284
+ TransactionError,
285
+ TransientTransactionError,
286
+ )
287
+ from .transaction import TransactionAdapter
282
288
 
283
289
  __all__ = (
284
290
  'PynamoDBToPymongoAdapter',
@@ -295,5 +301,10 @@ __all__ = (
295
301
  'UUIDAttribute',
296
302
  'PynamoDBModelToMongoDictSerializer',
297
303
  'patch_attributes',
298
- 'IndexesCreator'
304
+ 'IndexesCreator',
305
+ 'TransactionAdapter',
306
+ 'TransactionError',
307
+ 'ConditionalWriteFailed',
308
+ 'DuplicateKeyError',
309
+ 'TransientTransactionError',
299
310
  )