api-foundry 0.1.14__tar.gz → 0.1.16__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 (73) hide show
  1. {api_foundry-0.1.14 → api_foundry-0.1.16}/PKG-INFO +1 -1
  2. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/iac/pulumi/api_foundry.py +37 -8
  3. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/utils/model_factory.py +48 -14
  4. {api_foundry-0.1.14 → api_foundry-0.1.16}/pyproject.toml +1 -1
  5. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/__init__.py +0 -0
  6. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/adapters/adapter.py +0 -67
  7. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/adapters/case_change_adapter.py +0 -79
  8. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/adapters/gateway_adapter.py +0 -112
  9. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/cloudprints/archive_builder.py +0 -6
  10. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/cloudprints/hash_comparator.py +0 -90
  11. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/cloudprints/pulumi/lambda_.py +0 -106
  12. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/cloudprints/pulumi/log_group.pv +0 -18
  13. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/cloudprints/pulumi/rest_api.py +0 -16
  14. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/cloudprints/python_archive_builder.py +0 -207
  15. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/connectors/connection.py +0 -32
  16. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/connectors/connection_factory.py +0 -110
  17. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/connectors/oracle_connector.py +0 -29
  18. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/connectors/postgres_connection.py +0 -105
  19. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/dao.py +0 -23
  20. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/operation_dao.py +0 -141
  21. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/sql_custom_query_handler.py +0 -66
  22. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/sql_delete_query_handler.py +0 -36
  23. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/sql_insert_query_handler.py +0 -102
  24. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/sql_query_handler.py +0 -378
  25. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/sql_select_query_handler.py +0 -303
  26. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/sql_subselect_query_handler.py +0 -63
  27. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/sql_update_query_handler.py +0 -59
  28. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/iac/gateway_spec.py +0 -632
  29. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/iac/handler.py +0 -42
  30. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/iac/pulumi/api_foundry.py +0 -98
  31. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/operation.py +0 -15
  32. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/scripts/postgres_to_openapi.py +0 -216
  33. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/services/service.py +0 -60
  34. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/services/transactional_service.py +0 -35
  35. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/utils/app_exception.py +0 -22
  36. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/utils/logger.py +0 -60
  37. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/utils/model_factory.py +0 -448
  38. api_foundry-0.1.14/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/utils/spec_handler.py +0 -74
  39. {api_foundry-0.1.14 → api_foundry-0.1.16}/.gitignore +0 -0
  40. {api_foundry-0.1.14 → api_foundry-0.1.16}/LICENSE +0 -0
  41. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/__init__.py +0 -0
  42. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/adapters/adapter.py +0 -0
  43. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/adapters/case_change_adapter.py +0 -0
  44. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/adapters/gateway_adapter.py +0 -0
  45. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/cloudprints/archive_builder.py +0 -0
  46. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/cloudprints/hash_comparator.py +0 -0
  47. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/cloudprints/pulumi/lambda_.py +0 -0
  48. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/cloudprints/pulumi/log_group.pv +0 -0
  49. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/cloudprints/pulumi/rest_api.py +0 -0
  50. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/cloudprints/python_archive_builder.py +0 -0
  51. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/connectors/connection.py +0 -0
  52. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/connectors/connection_factory.py +0 -0
  53. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/connectors/oracle_connector.py +0 -0
  54. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/connectors/postgres_connection.py +0 -0
  55. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/dao/dao.py +0 -0
  56. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/dao/operation_dao.py +0 -0
  57. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/dao/sql_custom_query_handler.py +0 -0
  58. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/dao/sql_delete_query_handler.py +0 -0
  59. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/dao/sql_insert_query_handler.py +0 -0
  60. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/dao/sql_query_handler.py +0 -0
  61. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/dao/sql_select_query_handler.py +0 -0
  62. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/dao/sql_subselect_query_handler.py +0 -0
  63. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/dao/sql_update_query_handler.py +0 -0
  64. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/iac/gateway_spec.py +0 -0
  65. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/iac/handler.py +0 -0
  66. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/operation.py +0 -0
  67. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/scripts/install_secret.py +0 -0
  68. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/scripts/postgres_to_openapi.py +0 -0
  69. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/services/service.py +0 -0
  70. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/services/transactional_service.py +0 -0
  71. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/utils/app_exception.py +0 -0
  72. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/utils/logger.py +0 -0
  73. {api_foundry-0.1.14 → api_foundry-0.1.16}/api_foundry/utils/spec_handler.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: api-foundry
3
- Version: 0.1.14
3
+ Version: 0.1.16
4
4
  Summary: The `api_foundry` project is a powerful tool designed to automate the deployment of REST APIs on AWS using Lambda services to access and interact with relational databases (RDBMS). This project leverages the OpenAPI specification to define and manage the APIs
5
5
  Project-URL: Documentation, https://github.com/DanRepik/api-foundry
6
6
  Project-URL: Source, https://github.com/DanRepik/api-foundry
@@ -1,9 +1,10 @@
1
1
  import pkgutil
2
+ import json
2
3
  import importlib.resources as pkg_resources
3
4
  from pathlib import Path
4
- from pulumi import ComponentResource, Output, ResourceOptions, export
5
+ from pulumi import ComponentResource, Output, ResourceOptions, export, Config
5
6
  import pulumi_aws as aws
6
- from typing import Any, Awaitable, Mapping
7
+ from typing import Any, Awaitable, Mapping, Dict
7
8
 
8
9
  from api_foundry.iac.gateway_spec import GatewaySpec
9
10
  from api_foundry.cloudprints.python_archive_builder import PythonArchiveBuilder
@@ -46,17 +47,25 @@ class APIFoundry(ComponentResource):
46
47
  working_dir="temp",
47
48
  )
48
49
 
50
+ environment = props.get("environment") if isinstance(props.get("environment"), dict) else {} # type: ignore
51
+ # Check if we are deploying to LocalStack
52
+ if self.is_deploying_to_localstack():
53
+ # Add LocalStack-specific environment variables
54
+ localstack_env = {
55
+ "AWS_ACCESS_KEY_ID": "test",
56
+ "AWS_SECRET_ACCESS_KEY": "test",
57
+ "AWS_ENDPOINT_URL": "http://localstack:4566",
58
+ }
59
+ environment = {**localstack_env, **environment}
60
+
61
+ environment['secrets'] = props["secrets"]
62
+
49
63
  lambda_function = PythonFunctionCloudprint(
50
64
  name=f"{name}-api-maker",
51
65
  hash=self.archive_builder.hash(),
52
66
  handler="app.lambda_handler",
53
67
  archive_location=self.archive_builder.location(),
54
- environment={
55
- "AWS_ACCESS_KEY_ID": "test",
56
- "AWS_SECRET_ACCESS_KEY": "test",
57
- "AWS_ENDPOINT_URL": "http://localstack:4566",
58
- "SECRETS": props["secrets"],
59
- },
68
+ environment=environment
60
69
  )
61
70
 
62
71
  ModelFactory.load_yaml(api_spec)
@@ -96,3 +105,23 @@ class APIFoundry(ComponentResource):
96
105
  )
97
106
 
98
107
  export("gateway-api", gateway.id)
108
+
109
+ def is_deploying_to_localstack(self) -> bool:
110
+ # Create a Pulumi Config instance
111
+ config = Config("aws")
112
+
113
+ # Check if the 'endpoints' configuration is set, which usually indicates LocalStack
114
+ endpoints = config.get("endpoints")
115
+
116
+ if endpoints:
117
+ try:
118
+ # Parse the endpoints configuration and check for LocalStack URL
119
+ endpoints_list = json.loads(endpoints)
120
+ for endpoint in endpoints_list:
121
+ if "localhost" in endpoint.get("url", ""):
122
+ return True
123
+ except json.JSONDecodeError:
124
+ pass
125
+
126
+ return False
127
+
@@ -1,6 +1,6 @@
1
1
  import re
2
2
  import yaml
3
- from typing import Any, Dict, Optional, List, Union
3
+ from typing import Any, Dict, Optional, List, Union, cast
4
4
  from datetime import datetime
5
5
  from api_foundry.utils.app_exception import ApplicationException
6
6
  from api_foundry.utils.spec_handler import SpecificationHandler
@@ -111,6 +111,8 @@ class SchemaObjectKey(SchemaObjectProperty):
111
111
  spec: Dict[str, Any],
112
112
  ):
113
113
  super().__init__(operation_id, name, properties, spec)
114
+ log.info(f"properties: {properties}")
115
+ log.info(f"key_type: {self.get('x-af-primary-key')}")
114
116
  self.key_type = self.get("x-af-primary-key", default="auto")
115
117
  if self.key_type not in ["manual", "uuid", "auto", "sequence"]:
116
118
  raise ApplicationException(
@@ -146,9 +148,15 @@ class SchemaObjectAssociation(OpenAPIElement):
146
148
  @property
147
149
  def child_property(self) -> "SchemaObjectProperty":
148
150
  child_property = self.get("x-af-child-property", None)
149
- if not child_property:
150
- return self.child_schema_object.primary_key
151
- return self.child_schema_object.get_property(child_property)
151
+
152
+ return cast(
153
+ SchemaObjectProperty,
154
+ (
155
+ self.child_schema_object.get_property(child_property)
156
+ if child_property
157
+ else self.child_schema_object.primary_key
158
+ ),
159
+ )
152
160
 
153
161
  @property
154
162
  def parent_property(self) -> "SchemaObjectProperty":
@@ -163,9 +171,14 @@ class SchemaObjectAssociation(OpenAPIElement):
163
171
  ),
164
172
  )
165
173
  parent = self.get("x-af-parent-property")
166
- if parent:
167
- return parent_schema_object.get_property(parent)
168
- return parent_schema_object.primary_key
174
+ return cast(
175
+ SchemaObjectProperty,
176
+ (
177
+ parent_schema_object.get_property(parent)
178
+ if parent
179
+ else parent_schema_object.primary_key
180
+ ),
181
+ )
169
182
 
170
183
  @property
171
184
  def child_schema_object(self) -> "SchemaObject":
@@ -190,29 +203,40 @@ class SchemaObject(OpenAPIElement):
190
203
  self, operation_id: str, schema_object: Dict[str, Any], spec: Dict[str, Any]
191
204
  ):
192
205
  super().__init__(schema_object, spec)
206
+ log.info(f"schema_object init: {schema_object}")
193
207
  self.operation_id = operation_id
194
208
  self.schema_object = schema_object
195
209
  database = schema_object.get("x-af-database")
196
210
  if database:
197
211
  self.database = database.lower()
198
- self.primary_key = None
199
212
 
200
213
  @property
201
214
  def properties(self) -> Dict[str, SchemaObjectProperty]:
215
+ log.info("properties")
202
216
  if not hasattr(self, "_properties"):
203
217
  self._resolve_properties()
204
218
  return self._properties
205
219
 
206
220
  @property
207
221
  def relations(self) -> Dict[str, SchemaObjectAssociation]:
222
+ log.info("relations")
208
223
  if not hasattr(self, "_relations"):
209
224
  self._resolve_properties()
210
225
  return self._relations
211
226
 
227
+ @property
228
+ def primary_key(self) -> SchemaObjectKey:
229
+ log.info("primary_key")
230
+ if not hasattr(self, "_primary_key"):
231
+ self._resolve_properties()
232
+ return self._primary_key
233
+
212
234
  def _resolve_properties(self):
235
+ log.info("resolve_properties")
213
236
  self._properties = dict()
214
237
  self._relations = dict()
215
- for property_name, prop in self.get("properties").items():
238
+ for property_name, prop in cast(dict, self.get("properties")).items():
239
+ log.info(f"name: {property_name}, prop: {prop}")
216
240
  assert prop is not None, (
217
241
  f"Property is none operation_id: {self.operation_id}, "
218
242
  + f"property: {property_name}"
@@ -222,6 +246,7 @@ class SchemaObject(OpenAPIElement):
222
246
  self._properties[property_name] = object_property
223
247
 
224
248
  def _resolve_property(self, property_name: str, prop: Dict[str, Any]):
249
+ log.info("resolve property")
225
250
  type = self.get("type", prop, None)
226
251
 
227
252
  if not type:
@@ -231,11 +256,16 @@ class SchemaObject(OpenAPIElement):
231
256
  )
232
257
 
233
258
  if type in ["object", "array"]:
259
+ log.info(f"relations: {property_name}")
234
260
  self._relations[property_name] = SchemaObjectAssociation(
235
261
  self.operation_id,
236
262
  property_name,
237
263
  {
238
- **(prop if type == "object" else self.get("items", prop)),
264
+ **(
265
+ prop
266
+ if type == "object"
267
+ else cast(dict, self.get("items", prop))
268
+ ),
239
269
  "type": type,
240
270
  },
241
271
  self.spec,
@@ -245,7 +275,7 @@ class SchemaObject(OpenAPIElement):
245
275
  self.operation_id, property_name, prop, self.spec
246
276
  )
247
277
  if object_property.is_primary_key:
248
- self.primary_key = SchemaObjectKey(
278
+ self._primary_key = SchemaObjectKey(
249
279
  self.operation_id, property_name, prop, self.spec
250
280
  )
251
281
  return object_property
@@ -375,7 +405,7 @@ class PathOperation(OpenAPIElement):
375
405
  return properties
376
406
 
377
407
  def _get_schema_properties(
378
- self, schema: Dict[str, Any], param_name: str = None
408
+ self, schema: Dict[str, Any], param_name: Optional[str] = None
379
409
  ) -> Dict[str, SchemaObjectProperty]:
380
410
  properties = {}
381
411
  schema_ref = schema.get("$ref")
@@ -387,14 +417,16 @@ class PathOperation(OpenAPIElement):
387
417
  self.path, prop_name, prop_spec, self.spec
388
418
  )
389
419
  elif param_name:
390
- properties[param_name] = SchemaObjectProperty(self.path, param_name, schema)
420
+ properties[param_name] = SchemaObjectProperty(
421
+ self.path, param_name, schema, self.spec
422
+ )
391
423
  return properties
392
424
 
393
425
 
394
426
  class ModelFactory:
395
427
  spec: dict
396
428
  schema_objects: Dict[str, SchemaObject] = {}
397
- path_operations: Dict[str, PathOperation] = []
429
+ path_operations: Dict[str, PathOperation] = {}
398
430
 
399
431
  @classmethod
400
432
  def load_yaml(cls, api_spec_path: str):
@@ -405,12 +437,14 @@ class ModelFactory:
405
437
 
406
438
  @classmethod
407
439
  def set_spec(cls, spec: dict):
440
+ log.info("set_spec")
408
441
  cls.spec = spec
409
442
  cls.schema_objects = {}
410
443
 
411
444
  schemas = cls.spec.get("components", {}).get("schemas", {})
412
445
  for name, schema in schemas.items():
413
446
  if "x-af-database" in schema:
447
+ log.info(f"schema_object: {name}")
414
448
  cls.schema_objects[name] = SchemaObject(name, schema, cls.spec)
415
449
 
416
450
  paths = cls.spec.get("paths", {})
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "api-foundry"
7
- version = "0.1.14"
7
+ version = "0.1.16"
8
8
  authors = [
9
9
  { name="Daniel Repik", email="danrepik@icloud.com" },
10
10
  ]
@@ -1,67 +0,0 @@
1
- import abc
2
- from typing import Optional
3
-
4
- from api_foundry.operation import Operation
5
- from api_foundry.services.transactional_service import TransactionalService
6
- from api_foundry.utils.logger import logger
7
- from api_foundry.services.service import Service
8
-
9
- log = logger(__name__)
10
-
11
-
12
- class Adapter(metaclass=abc.ABCMeta):
13
- service: Service
14
-
15
- @classmethod
16
- def __subclasshook__(cls, __subclass: type) -> bool:
17
- return (
18
- hasattr(__subclass, "marshal")
19
- and callable(__subclass.marshal)
20
- and hasattr(__subclass, "umarshal")
21
- and callable(__subclass.unmarshal)
22
- )
23
-
24
- def __init__(self, service: Optional[Service] = None) -> None:
25
- self.service = service if service is not None else TransactionalService()
26
-
27
- def unmarshal(self, event) -> Operation:
28
- """
29
- Unmarshal the event in a tuple for processing
30
-
31
- Parameters:
32
- - event (dict): Lambda event object.
33
-
34
- Returns:
35
- - Operation containing the entity, action, and parameters
36
- """
37
- raise NotImplementedError
38
-
39
- def marshal(self, result: list[dict]):
40
- """
41
- Marshal the result into a event response
42
-
43
- Parameters:
44
- - result (list): the data set to return in the response
45
-
46
- Returns:
47
- - the event response
48
- """
49
- return result
50
-
51
- def process_event(self, event):
52
- """
53
- Process Lambda event using a domain function.
54
-
55
- Parameters:
56
- - service_function (callable): The service function to be executed.
57
- - event (dict): Lambda event object.
58
-
59
- Returns:
60
- - any: Result of the domain function.
61
- """
62
- operation = self.unmarshal(event)
63
-
64
- result = self.service.execute(operation)
65
- log.debug(f"adapter result: {result}")
66
-
67
- return self.marshal(result)
@@ -1,79 +0,0 @@
1
- from humps import camelize, decamelize
2
-
3
- from api_foundry.adapters.adapter import Adapter
4
- from api_foundry.utils.logger import logger
5
- from api_foundry.operation import Operation
6
-
7
- log = logger(__name__)
8
-
9
-
10
- class CaseChangeAdapter(Adapter):
11
- """
12
- Handles changing case from snake to camel and back
13
- """
14
-
15
- def unmarshal(self, event) -> Operation:
16
- """
17
- Unmarshal the event in a tuple for processing
18
-
19
- Parameters:
20
- - event (dict): Lambda event object.
21
-
22
- Returns:
23
- - tuple: Tuple containing entity operation, store_params, query_params and metadata params.
24
- """
25
- operation = super().unmarshal(event)
26
-
27
- # determine case
28
- self.camel_case = (
29
- operation.metadata_params.get("_case", "snake") == "camel"
30
- or self.__check_camel_case(operation.store_params)
31
- or self.__check_camel_case(operation.query_params)
32
- )
33
- log.info(f"camel_case: {self.camel_case}")
34
-
35
- if self.camel_case:
36
- return Operation(
37
- operation_id=operation.operation_id,
38
- action=operation.action,
39
- store_params=decamelize(operation.store_params),
40
- query_params=decamelize(operation.query_params),
41
- metadata_params=operation.metadata_params,
42
- )
43
-
44
- return operation
45
-
46
- def marshal(self, result: list[dict]):
47
- """
48
- Marshal the result into a event response
49
-
50
- Parameters:
51
- - result (list): the data set to return in the response
52
-
53
- Returns:
54
- - the event response
55
- """
56
- super().marshal(result)
57
-
58
- if not self.camel_case:
59
- return result
60
-
61
- converted_result = []
62
- for item in result:
63
- converted_result.append(camelize(item))
64
-
65
- # convert back to camel case if needed
66
- return converted_result
67
-
68
- def __check_camel_case(self, params: dict) -> bool:
69
- if params is not None:
70
- # check the keys for an upper case character
71
- for param in params:
72
- if (
73
- param != param.lower()
74
- and param != param.upper()
75
- and "_" not in param
76
- ):
77
- return True
78
-
79
- return False
@@ -1,112 +0,0 @@
1
- import json
2
-
3
- from api_foundry.adapters.adapter import Adapter
4
- from api_foundry.operation import Operation
5
-
6
- actions_map = {
7
- "GET": "read",
8
- "POST": "create",
9
- "PUT": "update",
10
- "DELETE": "delete",
11
- }
12
-
13
-
14
- class GatewayAdapter(Adapter):
15
- def marshal(self, result: list[dict]):
16
- """
17
- Marshal the result into a event response
18
-
19
- Parameters:
20
- - result (list): the data set to return in the response
21
-
22
- Returns:
23
- - the event response
24
- """
25
- return super().marshal(result)
26
-
27
- def unmarshal(self, event):
28
- """
29
- Get parameters from the Lambda event.
30
-
31
- Parameters:
32
- - event (dict): Lambda event object.
33
-
34
- Returns:
35
- - tuple: Tuple containing data, query and metadata parameters.
36
- """
37
- entity = event.get("resource").split("/")[1]
38
- action = actions_map.get(event.get("httpMethod").upper(), "read")
39
-
40
- event_params = {}
41
-
42
- path_parameters = self._convert_parameters(event.get("pathParameters"))
43
- if path_parameters is not None:
44
- event_params.update(path_parameters)
45
-
46
- queryStringParameters = self._convert_parameters(
47
- event.get("queryStringParameters")
48
- )
49
- if queryStringParameters is not None:
50
- event_params.update(queryStringParameters)
51
-
52
- query_params, metadata_params = self.split_params(event_params)
53
-
54
- store_params = {}
55
- body = event.get("body")
56
- if body is not None and len(body) > 0:
57
- store_params = json.loads(body)
58
-
59
- return Operation(
60
- operation_id=entity,
61
- action=action,
62
- store_params=store_params,
63
- query_params=query_params,
64
- metadata_params=metadata_params,
65
- )
66
-
67
- def _convert_parameters(self, parameters):
68
- """
69
- Convert parameters to appropriate types.
70
-
71
- Parameters:
72
- - parameters (dict): Dictionary of parameters.
73
-
74
- Returns:
75
- - dict: Dictionary with parameters converted to appropriate types.
76
- """
77
- if parameters is None:
78
- return None
79
-
80
- result = {}
81
- for parameter, value in parameters.items():
82
- try:
83
- result[parameter] = int(value)
84
- except ValueError:
85
- try:
86
- result[parameter] = float(value)
87
- except ValueError:
88
- result[parameter] = value
89
- return result
90
-
91
- def split_params(self, parameters: dict):
92
- """
93
- Split a dictionary into two dictionaries based on keys.
94
-
95
- Parameters:
96
- - dictionary (dict): Input dictionary.
97
-
98
- Returns:
99
- - tuple: A tuple containing two dictionaries.
100
- The first dictionary contains metadata_params,
101
- and the second dictionary query_params.
102
- """
103
- query_params = {}
104
- metadata_params = {}
105
-
106
- for key, value in parameters.items():
107
- if key.startswith("__"):
108
- metadata_params[key] = value
109
- else:
110
- query_params[key] = value
111
-
112
- return query_params, metadata_params
@@ -1,6 +0,0 @@
1
- class ArchiveBuilder:
2
- def hash(self) -> str:
3
- raise NotImplementedError
4
-
5
- def location(self) -> str:
6
- raise NotImplementedError
@@ -1,90 +0,0 @@
1
- import hashlib
2
- import os
3
- import re
4
-
5
- from api_foundry.utils.logger import logger, DEBUG
6
-
7
- log = logger(__name__)
8
-
9
-
10
- class HashComparator:
11
- def __init__(self, hash_algorithm="sha256"):
12
- self.hash_algorithm = hash_algorithm
13
-
14
- def check_folder(self, hash_file: str, hash_dir: str):
15
- old_hash = self.read(hash_file)
16
- log.info(f"old_hash: {old_hash}")
17
- if old_hash is None:
18
- return False
19
-
20
- new_hash = self.hash_folder(hash_dir)
21
- log.info(f"new_hash: {new_hash}")
22
- return self.compare(old_hash, new_hash)
23
-
24
- def hash_file(self, file_path):
25
- """
26
- Calculate the hash value of a file.
27
- """
28
- hasher = hashlib.new(self.hash_algorithm)
29
- with open(file_path, "rb") as f:
30
- for chunk in iter(lambda: f.read(4096), b""):
31
- hasher.update(chunk)
32
- return hasher.hexdigest()
33
-
34
- def hash_folder(self, folder_path, include_regex=None, exclude_regex=None):
35
- hasher = hashlib.new(self.hash_algorithm)
36
-
37
- include_pattern = re.compile(include_regex) if include_regex else None
38
- exclude_pattern = re.compile(exclude_regex) if exclude_regex else None
39
-
40
- for root, dirs, files in os.walk(folder_path):
41
- for file in sorted(files):
42
- file_path = os.path.join(root, file)
43
-
44
- # Check if the file should be included
45
- if include_pattern and not include_pattern.match(file):
46
- continue
47
-
48
- # Check if the file should be excluded
49
- if exclude_pattern and exclude_pattern.match(file):
50
- continue
51
-
52
- with open(file_path, "rb") as f:
53
- # Update the folder hash with the hash of the file contents
54
- file_hash = hashlib.sha256()
55
- file_hash.update(f.read())
56
- hasher.update(file_hash.digest())
57
-
58
- return hasher.hexdigest()
59
-
60
- def read(self, file_path):
61
- """
62
- Read the hash value from a file.
63
- """
64
- if log.isEnabledFor(DEBUG):
65
- log.debug(f"reading hash: {file_path}")
66
-
67
- if not os.path.exists(file_path):
68
- return None
69
- try:
70
- with open(os.path.join(file_path, ".hash"), "r") as f:
71
- return f.read().strip()
72
- except FileNotFoundError:
73
- log.debug(f"hash file not found: {file_path}")
74
- return None
75
-
76
- def write(self, hash_value, file_path):
77
- """
78
- Write the hash value to a file.
79
- """
80
- if log.isEnabledFor(DEBUG):
81
- log.debug(f"writing hash: {file_path}")
82
-
83
- with open(os.path.join(file_path, ".hash"), "w") as f:
84
- f.write(hash_value)
85
-
86
- def compare(self, hash_value1, hash_value2):
87
- """
88
- Compare two hash values.
89
- """
90
- return False if hash_value1 is None else hash_value1 == hash_value2