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,400 +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.medical_role import RESOURCE
49
- from maleo.metadata.schemas.data.medical_role import MedicalRoleDataSchema
50
- from maleo.metadata.schemas.parameter.client.medical_role import (
51
- ReadMultipleParameter,
52
- ReadMultipleSpecializationsParameter,
53
- ReadMultipleQueryParameter,
54
- ReadMultipleSpecializationsQueryParameter,
55
- )
56
- from maleo.metadata.schemas.parameter.general.medical_role import ReadSingleParameter
57
-
58
-
59
- class MedicalRoleClientService(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: Union[ReadMultipleParameter, ReadMultipleSpecializationsParameter],
110
- headers: Optional[Dict[str, str]] = None,
111
- ) -> ReadMultipleResourceOperationResult[
112
- MedicalRoleDataSchema, 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[MedicalRoleDataSchema, 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[
133
- ReadMultipleParameter,
134
- ReadMultipleSpecializationsParameter,
135
- ReadSingleParameter,
136
- ],
137
- headers: Optional[Dict[str, str]] = None,
138
- ) -> Union[
139
- ReadMultipleResourceOperationResult[
140
- MedicalRoleDataSchema, StrictPagination, None
141
- ],
142
- ReadSingleResourceOperationResult[MedicalRoleDataSchema, None],
143
- ]:
144
- operation_action = ReadResourceOperationAction()
145
- executed_at = datetime.now(tz=timezone.utc)
146
-
147
- # Get function identifier
148
- func = self.__class__
149
- module, qualname = func.__module__, func.__qualname__
150
-
151
- # Define arguments being used in this function
152
- positional_arguments = [cardinality]
153
- keyword_arguments = {
154
- "authentication": authentication.model_dump(
155
- mode="json",
156
- exclude={
157
- "credentials": {
158
- "token": {
159
- "payload": {
160
- "iat_dt",
161
- "iat",
162
- "exp_dt",
163
- "exp",
164
- }
165
- }
166
- }
167
- },
168
- ),
169
- "parameters": parameters.model_dump(mode="json"),
170
- }
171
-
172
- # Define full function string
173
- function = f"{qualname}({json.dumps(positional_arguments)}|{json.dumps(keyword_arguments)})"
174
-
175
- # Define full cache key
176
- cache_key = build_key(module, function, namespace=self._namespace)
177
-
178
- if parameters.use_cache:
179
- operation_context = deepcopy(self._default_operation_context)
180
- operation_context.target.type = OperationTarget.CACHE
181
-
182
- # Check redis for data
183
- result_str = await self._redis.get(cache_key)
184
-
185
- if result_str is not None:
186
- completed_at = datetime.now(tz=timezone.utc)
187
-
188
- if isinstance(
189
- parameters,
190
- (ReadMultipleParameter, ReadMultipleSpecializationsParameter),
191
- ):
192
- result = ReadMultipleResourceOperationResult[
193
- MedicalRoleDataSchema, StrictPagination, None
194
- ].model_validate(json.loads(result_str))
195
- ReadMultipleResourceOperationSchema[
196
- GeneralAuthentication,
197
- MedicalRoleDataSchema,
198
- StrictPagination,
199
- None,
200
- ](
201
- service_context=self._service_context,
202
- id=operation_id,
203
- context=operation_context,
204
- timestamp=OperationTimestamp(
205
- executed_at=executed_at,
206
- completed_at=completed_at,
207
- duration=(completed_at - executed_at).total_seconds(),
208
- ),
209
- summary="Successfully retrieved multiple medical roles from cache",
210
- request_context=request_context,
211
- authentication=authentication,
212
- action=operation_action,
213
- resource=RESOURCE,
214
- result=result,
215
- ).log(
216
- self._logger, LogLevel.INFO
217
- )
218
- elif isinstance(parameters, ReadSingleParameter):
219
- result = ReadSingleResourceOperationResult[
220
- MedicalRoleDataSchema, None
221
- ].model_validate(json.loads(result_str))
222
- ReadSingleResourceOperationSchema[
223
- GeneralAuthentication, MedicalRoleDataSchema, None
224
- ](
225
- service_context=self._service_context,
226
- id=operation_id,
227
- context=operation_context,
228
- timestamp=OperationTimestamp(
229
- executed_at=executed_at,
230
- completed_at=completed_at,
231
- duration=(completed_at - executed_at).total_seconds(),
232
- ),
233
- summary="Successfully retrieved single medical role from cache",
234
- request_context=request_context,
235
- authentication=authentication,
236
- action=operation_action,
237
- resource=RESOURCE,
238
- result=result,
239
- ).log(
240
- self._logger, LogLevel.INFO
241
- )
242
- return result
243
-
244
- operation_context = deepcopy(self._default_operation_context)
245
- async with self._http_client_manager.get() as http_client:
246
- # Create headers
247
- base_headers = {
248
- "content-type": "application/json",
249
- "x-operation-id": str(operation_id),
250
- }
251
- if headers is not None:
252
- headers = merge_dicts(base_headers, headers)
253
- else:
254
- headers = base_headers
255
-
256
- # Create auth
257
- token = None
258
- try:
259
- token = reencode(
260
- payload=authentication.credentials.token.payload,
261
- key=self._private_key,
262
- )
263
- except Exception:
264
- pass
265
-
266
- auth = BearerAuth(token) if token is not None else None
267
-
268
- if isinstance(parameters, ReadMultipleParameter):
269
- # Define URL
270
- url = f"{self._url}/v1/{RESOURCE.identifiers[0].url_slug}/"
271
-
272
- # Parse parameters to query params
273
- params = ReadMultipleQueryParameter.model_validate(
274
- parameters.model_dump()
275
- ).model_dump(
276
- exclude={"sort_columns", "date_filters"}, exclude_none=True
277
- )
278
- elif isinstance(parameters, ReadMultipleSpecializationsParameter):
279
- # Define URL
280
- url = f"{self._url}/v1/{RESOURCE.identifiers[0].url_slug}/{parameters.medical_role_id}/specializations"
281
-
282
- # Parse parameters to query params
283
- params = ReadMultipleSpecializationsQueryParameter.model_validate(
284
- parameters.model_dump(exclude={"medical_role_id"})
285
- ).model_dump(
286
- exclude={"sort_columns", "date_filters"}, exclude_none=True
287
- )
288
- elif isinstance(parameters, ReadSingleParameter):
289
- # Define URL
290
- url = f"{self._url}/v1/{RESOURCE.identifiers[0].url_slug}/{parameters.identifier}/{parameters.value}"
291
-
292
- # Parse parameters to query params
293
- params = ReadSingleQueryParameterSchema.model_validate(
294
- parameters.model_dump()
295
- ).model_dump(exclude_none=True)
296
-
297
- # Send request and wait for response
298
- response = await http_client.get(
299
- url=url, params=params, headers=headers, auth=auth
300
- )
301
-
302
- if response.is_success:
303
- completed_at = datetime.now(tz=timezone.utc)
304
-
305
- if isinstance(
306
- parameters,
307
- (ReadMultipleParameter, ReadMultipleSpecializationsParameter),
308
- ):
309
- validated_response = MultipleDataResponseSchema[
310
- MedicalRoleDataSchema, StrictPagination, None
311
- ].model_validate(response.json())
312
- data = DataPair[List[MedicalRoleDataSchema], None](
313
- old=validated_response.data,
314
- new=None,
315
- )
316
- result = ReadMultipleResourceOperationResult[
317
- MedicalRoleDataSchema, StrictPagination, None
318
- ](
319
- data=data,
320
- pagination=validated_response.pagination,
321
- metadata=None,
322
- other=None,
323
- )
324
- ReadMultipleResourceOperationSchema[
325
- GeneralAuthentication,
326
- MedicalRoleDataSchema,
327
- StrictPagination,
328
- None,
329
- ](
330
- service_context=self._service_context,
331
- id=operation_id,
332
- context=operation_context,
333
- timestamp=OperationTimestamp(
334
- executed_at=executed_at,
335
- completed_at=completed_at,
336
- duration=(completed_at - executed_at).total_seconds(),
337
- ),
338
- summary="Successfully retrieved multiple medical roles from http request",
339
- request_context=request_context,
340
- authentication=authentication,
341
- action=operation_action,
342
- resource=RESOURCE,
343
- result=result,
344
- ).log(
345
- self._logger, level=LogLevel.INFO
346
- )
347
- elif isinstance(parameters, ReadSingleParameter):
348
- validated_response = SingleDataResponseSchema[
349
- MedicalRoleDataSchema, None
350
- ].model_validate(response.json())
351
- data = DataPair[MedicalRoleDataSchema, None](
352
- old=validated_response.data,
353
- new=None,
354
- )
355
- result = ReadSingleResourceOperationResult[
356
- MedicalRoleDataSchema, None
357
- ](
358
- data=data,
359
- pagination=validated_response.pagination,
360
- metadata=None,
361
- other=None,
362
- )
363
- ReadSingleResourceOperationSchema[
364
- GeneralAuthentication, MedicalRoleDataSchema, None
365
- ](
366
- service_context=self._service_context,
367
- id=operation_id,
368
- context=operation_context,
369
- timestamp=OperationTimestamp(
370
- executed_at=executed_at,
371
- completed_at=completed_at,
372
- duration=(completed_at - executed_at).total_seconds(),
373
- ),
374
- summary="Successfully retrieved single medical role from http request",
375
- request_context=request_context,
376
- authentication=authentication,
377
- action=operation_action,
378
- resource=RESOURCE,
379
- result=result,
380
- ).log(
381
- self._logger, level=LogLevel.INFO
382
- )
383
-
384
- if parameters.use_cache:
385
- await self._redis.set(
386
- cache_key, result.model_dump_json(), Expiration.EXP_1MO.value
387
- )
388
-
389
- return result
390
-
391
- self._raise_resource_http_request_error(
392
- response=response,
393
- operation_id=operation_id,
394
- operation_context=operation_context,
395
- executed_at=executed_at,
396
- operation_action=operation_action,
397
- request_context=request_context,
398
- authentication=authentication,
399
- resource=RESOURCE,
400
- )