api-foundry 0.1.7__tar.gz → 0.1.9__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.

Potentially problematic release.


This version of api-foundry might be problematic. Click here for more details.

Files changed (72) hide show
  1. {api_foundry-0.1.7 → api_foundry-0.1.9}/PKG-INFO +1 -1
  2. api_foundry-0.1.9/api_foundry/iac/pulumi/api_foundry.py +98 -0
  3. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/__init__.py +0 -0
  4. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/adapters/adapter.py +67 -0
  5. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/adapters/case_change_adapter.py +79 -0
  6. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/adapters/gateway_adapter.py +112 -0
  7. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/cloudprints/archive_builder.py +6 -0
  8. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/cloudprints/hash_comparator.py +90 -0
  9. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/cloudprints/pulumi/lambda_.py +106 -0
  10. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/cloudprints/pulumi/log_group.pv +18 -0
  11. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/cloudprints/pulumi/rest_api.py +16 -0
  12. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/cloudprints/python_archive_builder.py +207 -0
  13. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/connectors/connection.py +32 -0
  14. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/connectors/connection_factory.py +110 -0
  15. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/connectors/oracle_connector.py +29 -0
  16. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/connectors/postgres_connection.py +105 -0
  17. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/dao.py +18 -0
  18. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/operation_dao.py +139 -0
  19. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/sql_custom_query_handler.py +66 -0
  20. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/sql_delete_query_handler.py +36 -0
  21. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/sql_insert_query_handler.py +102 -0
  22. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/sql_query_handler.py +378 -0
  23. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/sql_select_query_handler.py +303 -0
  24. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/sql_subselect_query_handler.py +61 -0
  25. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/dao/sql_update_query_handler.py +59 -0
  26. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/iac/gateway_spec.py +632 -0
  27. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/iac/handler.py +42 -0
  28. {api_foundry-0.1.7 → api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging}/api_foundry/iac/pulumi/api_foundry.py +1 -0
  29. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/operation.py +15 -0
  30. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/scripts/postgres_to_openapi.py +216 -0
  31. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/services/service.py +60 -0
  32. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/services/transactional_service.py +35 -0
  33. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/utils/app_exception.py +22 -0
  34. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/utils/logger.py +60 -0
  35. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/utils/model_factory.py +448 -0
  36. api_foundry-0.1.9/examples/chinook-postgres-pulumi/temp/chinook_postgres-archive-builder-lambda/staging/api_foundry/utils/spec_handler.py +74 -0
  37. {api_foundry-0.1.7 → api_foundry-0.1.9}/pyproject.toml +1 -1
  38. {api_foundry-0.1.7 → api_foundry-0.1.9}/.gitignore +0 -0
  39. {api_foundry-0.1.7 → api_foundry-0.1.9}/LICENSE +0 -0
  40. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/__init__.py +0 -0
  41. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/adapters/adapter.py +0 -0
  42. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/adapters/case_change_adapter.py +0 -0
  43. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/adapters/gateway_adapter.py +0 -0
  44. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/cloudprints/archive_builder.py +0 -0
  45. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/cloudprints/hash_comparator.py +0 -0
  46. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/cloudprints/pulumi/lambda_.py +0 -0
  47. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/cloudprints/pulumi/log_group.pv +0 -0
  48. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/cloudprints/pulumi/rest_api.py +0 -0
  49. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/cloudprints/python_archive_builder.py +0 -0
  50. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/connectors/connection.py +0 -0
  51. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/connectors/connection_factory.py +0 -0
  52. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/connectors/oracle_connector.py +0 -0
  53. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/connectors/postgres_connection.py +0 -0
  54. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/dao/dao.py +0 -0
  55. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/dao/operation_dao.py +0 -0
  56. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/dao/sql_custom_query_handler.py +0 -0
  57. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/dao/sql_delete_query_handler.py +0 -0
  58. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/dao/sql_insert_query_handler.py +0 -0
  59. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/dao/sql_query_handler.py +0 -0
  60. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/dao/sql_select_query_handler.py +0 -0
  61. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/dao/sql_subselect_query_handler.py +0 -0
  62. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/dao/sql_update_query_handler.py +0 -0
  63. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/iac/gateway_spec.py +0 -0
  64. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/iac/handler.py +0 -0
  65. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/operation.py +0 -0
  66. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/scripts/postgres_to_openapi.py +0 -0
  67. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/services/service.py +0 -0
  68. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/services/transactional_service.py +0 -0
  69. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/utils/app_exception.py +0 -0
  70. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/utils/logger.py +0 -0
  71. {api_foundry-0.1.7 → api_foundry-0.1.9}/api_foundry/utils/model_factory.py +0 -0
  72. {api_foundry-0.1.7 → api_foundry-0.1.9}/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.7
3
+ Version: 0.1.9
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
@@ -0,0 +1,98 @@
1
+ import pkgutil
2
+ import importlib.resources as pkg_resources
3
+ from pathlib import Path
4
+ from pulumi import ComponentResource, Output, ResourceOptions, export
5
+ import pulumi_aws as aws
6
+ from typing import Any, Awaitable, Mapping
7
+
8
+ from api_foundry.iac.gateway_spec import GatewaySpec
9
+ from api_foundry.cloudprints.python_archive_builder import PythonArchiveBuilder
10
+ from api_foundry.cloudprints.pulumi.lambda_ import PythonFunctionCloudprint
11
+ from api_foundry.utils.logger import logger, DEBUG, write_logging_file
12
+ from api_foundry.utils.model_factory import ModelFactory
13
+
14
+ log = logger(__name__)
15
+
16
+
17
+ class APIFoundry(ComponentResource):
18
+ def __init__(
19
+ self,
20
+ name: str,
21
+ props: Mapping[str, Any | Awaitable[Any] | Output[Any]],
22
+ opts: ResourceOptions | None = None,
23
+ remote: bool = False,
24
+ ) -> None:
25
+ super().__init__("api_foundry", name, props, opts, remote)
26
+
27
+ api_spec = str(props.get("api_spec", None))
28
+ assert api_spec, "api_spec is not set, a location must be provided."
29
+ assert "secrets" in props, "Missing secrets map"
30
+
31
+ # Dynamically obtain the path to the `api_foundry` package
32
+ with pkg_resources.path("api_foundry", "__init__.py") as p:
33
+ api_foundry_source = str(Path(p).parent)
34
+
35
+ self.archive_builder = PythonArchiveBuilder(
36
+ name=f"{name}-archive-builder",
37
+ sources={
38
+ "api_foundry": api_foundry_source,
39
+ "api_spec.yaml": api_spec,
40
+ "app.py": pkgutil.get_data("api_foundry", "iac/handler.py").decode("utf-8"), # type: ignore
41
+ },
42
+ requirements=[
43
+ "psycopg2-binary",
44
+ "pyyaml",
45
+ ],
46
+ working_dir="temp",
47
+ )
48
+
49
+ lambda_function = PythonFunctionCloudprint(
50
+ name=f"{name}-api-maker",
51
+ hash=self.archive_builder.hash(),
52
+ handler="app.lambda_handler",
53
+ 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
+ },
60
+ )
61
+
62
+ ModelFactory.load_yaml(api_spec)
63
+
64
+ body = lambda_function.invoke_arn().apply(
65
+ lambda invoke_arn: (
66
+ GatewaySpec(
67
+ function_name=lambda_function.name,
68
+ function_invoke_arn=invoke_arn,
69
+ enable_cors=True,
70
+ ).as_yaml()
71
+ )
72
+ )
73
+
74
+ if log.isEnabledFor(DEBUG):
75
+ body.apply(
76
+ lambda body_str: (
77
+ write_logging_file(f"{name}-gateway-doc.yaml", body_str)
78
+ )
79
+ )
80
+
81
+ gateway = aws.apigateway.RestApi(
82
+ f"{name}-http-api",
83
+ name=f"{name}-http-api",
84
+ body=body,
85
+ )
86
+
87
+ deployment = aws.apigateway.Deployment(
88
+ f"{name}-deployment", rest_api=gateway.id
89
+ )
90
+
91
+ aws.apigateway.Stage(
92
+ f"{name}-stage",
93
+ rest_api=gateway.id,
94
+ deployment=deployment.id,
95
+ stage_name=name,
96
+ )
97
+
98
+ export("gateway-api", gateway.id)
@@ -0,0 +1,67 @@
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)
@@ -0,0 +1,79 @@
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
@@ -0,0 +1,112 @@
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
@@ -0,0 +1,6 @@
1
+ class ArchiveBuilder:
2
+ def hash(self) -> str:
3
+ raise NotImplementedError
4
+
5
+ def location(self) -> str:
6
+ raise NotImplementedError
@@ -0,0 +1,90 @@
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
@@ -0,0 +1,106 @@
1
+ import pulumi
2
+ import pulumi_aws as aws
3
+ from api_foundry.utils.logger import logger
4
+
5
+ log = logger(__name__)
6
+
7
+
8
+ class PythonFunctionCloudprint(pulumi.ComponentResource):
9
+ name: str
10
+ handler: str
11
+ lambda_: aws.lambda_.Function
12
+
13
+ def __init__(
14
+ self,
15
+ name,
16
+ hash: str,
17
+ archive_location: str,
18
+ handler: str,
19
+ environment=None,
20
+ opts=None,
21
+ ):
22
+ super().__init__("custom:resource:PythonFunctionCloudprint", name, {}, opts)
23
+ self.name = name
24
+ self.handler = handler
25
+ self.environment = environment or {}
26
+ self.create_lambda_function(hash, archive_location)
27
+ self.register_outputs({})
28
+
29
+ def create_execution_role(self) -> aws.iam.Role:
30
+ log.debug("creating execution role")
31
+ assume_role_policy = aws.iam.get_policy_document(
32
+ statements=[
33
+ aws.iam.GetPolicyDocumentStatementArgs(
34
+ effect="Allow",
35
+ principals=[
36
+ aws.iam.GetPolicyDocumentStatementPrincipalArgs(
37
+ type="Service",
38
+ identifiers=["lambda.amazonaws.com"],
39
+ )
40
+ ],
41
+ actions=["sts:AssumeRole"],
42
+ )
43
+ ]
44
+ )
45
+
46
+ role = aws.iam.Role(
47
+ f"{self.name}-lambda-execution",
48
+ assume_role_policy=assume_role_policy.json,
49
+ )
50
+
51
+ aws.iam.get_policy_document(
52
+ statements=[
53
+ aws.iam.GetPolicyDocumentStatementArgs(
54
+ effect="Allow",
55
+ actions=[
56
+ "secretsmanager:GetSecretValue",
57
+ "secretsmanager:DescribeSecret",
58
+ "logs:CreateLogGroup",
59
+ "logs:CreateLogStream",
60
+ "logs:PutLogEvents",
61
+ ],
62
+ resources=["*"], # Allow access to all secrets and logs
63
+ )
64
+ ]
65
+ )
66
+
67
+ """
68
+ aws.iam.RolePolicy(
69
+ f"{self.name}-lambda-policy",
70
+ role=role.id,
71
+ policy=policy_document.json,
72
+ opts=pulumi.ResourceOptions(depends_on=[role])
73
+ )
74
+ """
75
+
76
+ return role
77
+
78
+ def create_log_group(self) -> aws.cloudwatch.LogGroup:
79
+ log_group = aws.cloudwatch.LogGroup(
80
+ f"{self.name}-log-group",
81
+ name=f"/aws/lambda/{pulumi.get_project()}-{self.name}",
82
+ retention_in_days=3,
83
+ )
84
+ return log_group
85
+
86
+ def invoke_arn(self) -> pulumi.Output[str]:
87
+ return self.lambda_.invoke_arn
88
+
89
+ def create_lambda_function(self, hash: str, archive_location: str):
90
+ log.debug("creating lambda function")
91
+
92
+ log_group = self.create_log_group()
93
+
94
+ execution_role = self.create_execution_role()
95
+
96
+ self.lambda_ = aws.lambda_.Function(
97
+ f"{self.name}-lambda",
98
+ code=pulumi.FileArchive(archive_location),
99
+ name=f"{pulumi.get_project()}-{self.name}",
100
+ role=execution_role.arn,
101
+ handler=self.handler,
102
+ source_code_hash=hash,
103
+ runtime=aws.lambda_.Runtime.PYTHON3D9,
104
+ environment=aws.lambda_.FunctionEnvironmentArgs(variables=self.environment),
105
+ opts=pulumi.ResourceOptions(depends_on=[execution_role, log_group]),
106
+ )
@@ -0,0 +1,18 @@
1
+ def log_group(scope: Construct, name: str, retention_in_days: int = 3) -> CloudwatchLogGroup:
2
+ """
3
+ Creates a CloudWatch log group.
4
+
5
+ Args:
6
+ name (str): The name of the log group.
7
+ retention_in_days (int, optional): Default retention period in days. Defaults to 3 days.
8
+
9
+ Returns:
10
+ CloudwatchLogGroup: The created CloudWatch log group.
11
+ """
12
+ return CloudwatchLogGroup(
13
+ scope,
14
+ make_id(scope, name),
15
+ name=f"{scope.config.get('environment')}/{scope.config.get('product')}/{scope.config.get('domain')}/{name}",
16
+ retention_in_days=retention_in_days,
17
+ tags=make_tags(scope, name)
18
+ )
@@ -0,0 +1,16 @@
1
+ import pulumi
2
+ import pulumi_aws as aws
3
+
4
+
5
+ class GatewayAPICloudprint(pulumi.ComponentResource):
6
+ rest_api: aws.apigateway.RestApi
7
+
8
+ def __init__(self, name, body: str, opts=None):
9
+ super().__init__("cloudprints:apigw:OpenAPIGateway", name, None, opts)
10
+
11
+ self.rest_api = aws.apigateway.RestApi(
12
+ f"{name}-http-api", name=f"{name}-http-api", body=body
13
+ )
14
+
15
+ def id(self) -> pulumi.Output[str]:
16
+ return self.rest_api.id