maleo-metadata-client 0.0.4__py3-none-any.whl → 0.0.6__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.

Potentially problematic release.


This version of maleo-metadata-client might be problematic. Click here for more details.

@@ -1,380 +0,0 @@
1
- import json
2
- from copy import deepcopy
3
- from Crypto.PublicKey.RSA import RsaKey
4
- from datetime import datetime, timezone
5
- from redis.asyncio.client import Redis
6
- from typing import Dict, List, Literal, Optional, Union, overload
7
- from uuid import UUID
8
- from maleo.soma.authorization import BearerAuth
9
- from maleo.soma.dtos.configurations.cache.redis import RedisCacheNamespaces
10
- from maleo.soma.enums.cardinality import Cardinality
11
- from maleo.soma.enums.environment import Environment
12
- from maleo.soma.enums.expiration import Expiration
13
- from maleo.soma.enums.logging import LogLevel
14
- from maleo.soma.enums.operation import OperationTarget
15
- from maleo.soma.managers.client.maleo import MaleoClientService
16
- from maleo.soma.managers.client.http import HTTPClientManager
17
- from maleo.soma.managers.credential import CredentialManager
18
- from maleo.soma.schemas.authentication import GeneralAuthentication
19
- from maleo.soma.schemas.data import DataPair
20
- from maleo.soma.schemas.operation.context import (
21
- OperationContextSchema,
22
- OperationOriginSchema,
23
- OperationLayerSchema,
24
- OperationTargetSchema,
25
- )
26
- from maleo.soma.schemas.operation.resource import (
27
- ReadSingleResourceOperationSchema,
28
- ReadMultipleResourceOperationSchema,
29
- )
30
- from maleo.soma.schemas.operation.resource.action import ReadResourceOperationAction
31
- from maleo.soma.schemas.operation.resource.result import (
32
- ReadSingleResourceOperationResult,
33
- ReadMultipleResourceOperationResult,
34
- )
35
- from maleo.soma.schemas.operation.timestamp import OperationTimestamp
36
- from maleo.soma.schemas.pagination import StrictPagination
37
- from maleo.soma.schemas.parameter.general import ReadSingleQueryParameterSchema
38
- from maleo.soma.schemas.request import RequestContext
39
- from maleo.soma.schemas.response import (
40
- SingleDataResponseSchema,
41
- MultipleDataResponseSchema,
42
- )
43
- from maleo.soma.schemas.service import ServiceContext
44
- from maleo.soma.utils.cache import build_key
45
- from maleo.soma.utils.logging import ClientLogger
46
- from maleo.soma.utils.merger import merge_dicts
47
- from maleo.soma.utils.token import reencode
48
- from maleo.metadata.constants.organization_type import RESOURCE
49
- from maleo.metadata.schemas.data.organization_type import OrganizationTypeDataSchema
50
- from maleo.metadata.schemas.parameter.client.organization_type import (
51
- ReadMultipleParameter,
52
- ReadMultipleQueryParameter,
53
- )
54
- from maleo.metadata.schemas.parameter.general.organization_type import (
55
- ReadSingleParameter,
56
- )
57
-
58
-
59
- class OrganizationTypeClientService(MaleoClientService):
60
- def __init__(
61
- self,
62
- environment: Environment,
63
- key: str,
64
- url: str,
65
- operation_origin: OperationOriginSchema,
66
- logger: ClientLogger,
67
- credential_manager: CredentialManager,
68
- http_client_manager: HTTPClientManager,
69
- private_key: RsaKey,
70
- redis: Redis,
71
- redis_namespaces: RedisCacheNamespaces,
72
- service_context: ServiceContext,
73
- ):
74
- super().__init__(
75
- environment,
76
- key,
77
- url,
78
- operation_origin,
79
- logger,
80
- credential_manager,
81
- http_client_manager,
82
- private_key,
83
- redis,
84
- redis_namespaces,
85
- service_context,
86
- )
87
- self._namespace = self._redis_namespaces.create(
88
- self._key,
89
- RESOURCE.aggregate(),
90
- origin=self._CACHE_ORIGIN,
91
- layer=self._CACHE_LAYER,
92
- )
93
- self._default_operation_context = OperationContextSchema(
94
- origin=self._operation_origin,
95
- layer=OperationLayerSchema(type=self._OPERATION_LAYER_TYPE, details=None),
96
- target=OperationTargetSchema(
97
- type=self._OPERATION_TARGET_TYPE, details=None
98
- ),
99
- )
100
-
101
- @overload
102
- async def read(
103
- self,
104
- cardinality: Literal[Cardinality.MULTIPLE],
105
- *,
106
- operation_id: UUID,
107
- request_context: RequestContext,
108
- authentication: GeneralAuthentication,
109
- parameters: ReadMultipleParameter,
110
- headers: Optional[Dict[str, str]] = None,
111
- ) -> ReadMultipleResourceOperationResult[
112
- OrganizationTypeDataSchema, StrictPagination, None
113
- ]: ...
114
- @overload
115
- async def read(
116
- self,
117
- cardinality: Literal[Cardinality.SINGLE],
118
- *,
119
- operation_id: UUID,
120
- request_context: RequestContext,
121
- authentication: GeneralAuthentication,
122
- parameters: ReadSingleParameter,
123
- headers: Optional[Dict[str, str]] = None,
124
- ) -> ReadSingleResourceOperationResult[OrganizationTypeDataSchema, None]: ...
125
- async def read(
126
- self,
127
- cardinality: Cardinality,
128
- *,
129
- operation_id: UUID,
130
- request_context: RequestContext,
131
- authentication: GeneralAuthentication,
132
- parameters: Union[ReadMultipleParameter, ReadSingleParameter],
133
- headers: Optional[Dict[str, str]] = None,
134
- ) -> Union[
135
- ReadMultipleResourceOperationResult[
136
- OrganizationTypeDataSchema, StrictPagination, None
137
- ],
138
- ReadSingleResourceOperationResult[OrganizationTypeDataSchema, None],
139
- ]:
140
- operation_action = ReadResourceOperationAction()
141
- executed_at = datetime.now(tz=timezone.utc)
142
-
143
- # Get function identifier
144
- func = self.__class__
145
- module, qualname = func.__module__, func.__qualname__
146
-
147
- # Define arguments being used in this function
148
- positional_arguments = [cardinality]
149
- keyword_arguments = {
150
- "authentication": authentication.model_dump(
151
- mode="json",
152
- exclude={
153
- "credentials": {
154
- "token": {
155
- "payload": {
156
- "iat_dt",
157
- "iat",
158
- "exp_dt",
159
- "exp",
160
- }
161
- }
162
- }
163
- },
164
- ),
165
- "parameters": parameters.model_dump(mode="json"),
166
- }
167
-
168
- # Define full function string
169
- function = f"{qualname}({json.dumps(positional_arguments)}|{json.dumps(keyword_arguments)})"
170
-
171
- # Define full cache key
172
- cache_key = build_key(module, function, namespace=self._namespace)
173
-
174
- if parameters.use_cache:
175
- operation_context = deepcopy(self._default_operation_context)
176
- operation_context.target.type = OperationTarget.CACHE
177
-
178
- # Check redis for data
179
- result_str = await self._redis.get(cache_key)
180
-
181
- if result_str is not None:
182
- completed_at = datetime.now(tz=timezone.utc)
183
-
184
- if isinstance(parameters, ReadMultipleParameter):
185
- result = ReadMultipleResourceOperationResult[
186
- OrganizationTypeDataSchema, StrictPagination, None
187
- ].model_validate(json.loads(result_str))
188
- ReadMultipleResourceOperationSchema[
189
- GeneralAuthentication,
190
- OrganizationTypeDataSchema,
191
- StrictPagination,
192
- None,
193
- ](
194
- service_context=self._service_context,
195
- id=operation_id,
196
- context=operation_context,
197
- timestamp=OperationTimestamp(
198
- executed_at=executed_at,
199
- completed_at=completed_at,
200
- duration=(completed_at - executed_at).total_seconds(),
201
- ),
202
- summary="Successfully retrieved multiple organization types from cache",
203
- request_context=request_context,
204
- authentication=authentication,
205
- action=operation_action,
206
- resource=RESOURCE,
207
- result=result,
208
- ).log(
209
- self._logger, LogLevel.INFO
210
- )
211
- elif isinstance(parameters, ReadSingleParameter):
212
- result = ReadSingleResourceOperationResult[
213
- OrganizationTypeDataSchema, None
214
- ].model_validate(json.loads(result_str))
215
- ReadSingleResourceOperationSchema[
216
- GeneralAuthentication, OrganizationTypeDataSchema, None
217
- ](
218
- service_context=self._service_context,
219
- id=operation_id,
220
- context=operation_context,
221
- timestamp=OperationTimestamp(
222
- executed_at=executed_at,
223
- completed_at=completed_at,
224
- duration=(completed_at - executed_at).total_seconds(),
225
- ),
226
- summary="Successfully retrieved single organization type from cache",
227
- request_context=request_context,
228
- authentication=authentication,
229
- action=operation_action,
230
- resource=RESOURCE,
231
- result=result,
232
- ).log(
233
- self._logger, LogLevel.INFO
234
- )
235
- return result
236
-
237
- operation_context = deepcopy(self._default_operation_context)
238
- async with self._http_client_manager.get() as http_client:
239
- # Create headers
240
- base_headers = {
241
- "content-type": "application/json",
242
- "x-operation-id": str(operation_id),
243
- }
244
- if headers is not None:
245
- headers = merge_dicts(base_headers, headers)
246
- else:
247
- headers = base_headers
248
-
249
- # Create auth
250
- token = None
251
- try:
252
- token = reencode(
253
- payload=authentication.credentials.token.payload,
254
- key=self._private_key,
255
- )
256
- except Exception:
257
- pass
258
-
259
- auth = BearerAuth(token) if token is not None else None
260
-
261
- if isinstance(parameters, ReadMultipleParameter):
262
- # Define URL
263
- url = f"{self._url}/v1/{RESOURCE.identifiers[0].url_slug}/"
264
-
265
- # Parse parameters to query params
266
- params = ReadMultipleQueryParameter.model_validate(
267
- parameters.model_dump()
268
- ).model_dump(
269
- exclude={"sort_columns", "date_filters"}, exclude_none=True
270
- )
271
- elif isinstance(parameters, ReadSingleParameter):
272
- # Define URL
273
- url = f"{self._url}/v1/{RESOURCE.identifiers[0].url_slug}/{parameters.identifier}/{parameters.value}"
274
-
275
- # Parse parameters to query params
276
- params = ReadSingleQueryParameterSchema.model_validate(
277
- parameters.model_dump()
278
- ).model_dump(exclude_none=True)
279
-
280
- # Send request and wait for response
281
- response = await http_client.get(
282
- url=url, params=params, headers=headers, auth=auth
283
- )
284
-
285
- if response.is_success:
286
- completed_at = datetime.now(tz=timezone.utc)
287
-
288
- if isinstance(parameters, ReadMultipleParameter):
289
- validated_response = MultipleDataResponseSchema[
290
- OrganizationTypeDataSchema, StrictPagination, None
291
- ].model_validate(response.json())
292
- data = DataPair[List[OrganizationTypeDataSchema], None](
293
- old=validated_response.data,
294
- new=None,
295
- )
296
- result = ReadMultipleResourceOperationResult[
297
- OrganizationTypeDataSchema, StrictPagination, None
298
- ](
299
- data=data,
300
- pagination=validated_response.pagination,
301
- metadata=None,
302
- other=None,
303
- )
304
- ReadMultipleResourceOperationSchema[
305
- GeneralAuthentication,
306
- OrganizationTypeDataSchema,
307
- StrictPagination,
308
- None,
309
- ](
310
- service_context=self._service_context,
311
- id=operation_id,
312
- context=operation_context,
313
- timestamp=OperationTimestamp(
314
- executed_at=executed_at,
315
- completed_at=completed_at,
316
- duration=(completed_at - executed_at).total_seconds(),
317
- ),
318
- summary="Successfully retrieved multiple organization types from http request",
319
- request_context=request_context,
320
- authentication=authentication,
321
- action=operation_action,
322
- resource=RESOURCE,
323
- result=result,
324
- ).log(
325
- self._logger, level=LogLevel.INFO
326
- )
327
- elif isinstance(parameters, ReadSingleParameter):
328
- validated_response = SingleDataResponseSchema[
329
- OrganizationTypeDataSchema, None
330
- ].model_validate(response.json())
331
- data = DataPair[OrganizationTypeDataSchema, None](
332
- old=validated_response.data,
333
- new=None,
334
- )
335
- result = ReadSingleResourceOperationResult[
336
- OrganizationTypeDataSchema, None
337
- ](
338
- data=data,
339
- pagination=validated_response.pagination,
340
- metadata=None,
341
- other=None,
342
- )
343
- ReadSingleResourceOperationSchema[
344
- GeneralAuthentication, OrganizationTypeDataSchema, None
345
- ](
346
- service_context=self._service_context,
347
- id=operation_id,
348
- context=operation_context,
349
- timestamp=OperationTimestamp(
350
- executed_at=executed_at,
351
- completed_at=completed_at,
352
- duration=(completed_at - executed_at).total_seconds(),
353
- ),
354
- summary="Successfully retrieved single organization type from http request",
355
- request_context=request_context,
356
- authentication=authentication,
357
- action=operation_action,
358
- resource=RESOURCE,
359
- result=result,
360
- ).log(
361
- self._logger, level=LogLevel.INFO
362
- )
363
-
364
- if parameters.use_cache:
365
- await self._redis.set(
366
- cache_key, result.model_dump_json(), Expiration.EXP_1MO.value
367
- )
368
-
369
- return result
370
-
371
- self._raise_resource_http_request_error(
372
- response=response,
373
- operation_id=operation_id,
374
- operation_context=operation_context,
375
- executed_at=executed_at,
376
- operation_action=operation_action,
377
- request_context=request_context,
378
- authentication=authentication,
379
- resource=RESOURCE,
380
- )