api-foundry 0.1.16__tar.gz → 0.1.19__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 (45) hide show
  1. {api_foundry-0.1.16 → api_foundry-0.1.19}/PKG-INFO +4 -2
  2. api_foundry-0.1.19/api_foundry/__init__.py +6 -0
  3. api_foundry-0.1.19/api_foundry/iac/gateway_spec.py +545 -0
  4. api_foundry-0.1.19/api_foundry/iac/pulumi/api_foundry.py +119 -0
  5. api_foundry-0.1.19/api_foundry/utils/model_factory.py +386 -0
  6. api_foundry-0.1.19/api_foundry/utils/schema_processor.py.x +211 -0
  7. api_foundry-0.1.19/api_foundry/utils/schema_validator.py +56 -0
  8. {api_foundry-0.1.16 → api_foundry-0.1.19}/pyproject.toml +3 -1
  9. api_foundry-0.1.16/api_foundry/__init__.py +0 -0
  10. api_foundry-0.1.16/api_foundry/adapters/adapter.py +0 -67
  11. api_foundry-0.1.16/api_foundry/adapters/case_change_adapter.py +0 -79
  12. api_foundry-0.1.16/api_foundry/adapters/gateway_adapter.py +0 -112
  13. api_foundry-0.1.16/api_foundry/cloudprints/archive_builder.py +0 -6
  14. api_foundry-0.1.16/api_foundry/cloudprints/hash_comparator.py +0 -90
  15. api_foundry-0.1.16/api_foundry/cloudprints/pulumi/lambda_.py +0 -106
  16. api_foundry-0.1.16/api_foundry/cloudprints/pulumi/log_group.pv +0 -18
  17. api_foundry-0.1.16/api_foundry/cloudprints/pulumi/rest_api.py +0 -16
  18. api_foundry-0.1.16/api_foundry/cloudprints/python_archive_builder.py +0 -207
  19. api_foundry-0.1.16/api_foundry/connectors/connection.py +0 -32
  20. api_foundry-0.1.16/api_foundry/connectors/connection_factory.py +0 -110
  21. api_foundry-0.1.16/api_foundry/connectors/oracle_connector.py +0 -29
  22. api_foundry-0.1.16/api_foundry/connectors/postgres_connection.py +0 -105
  23. api_foundry-0.1.16/api_foundry/dao/dao.py +0 -23
  24. api_foundry-0.1.16/api_foundry/dao/operation_dao.py +0 -141
  25. api_foundry-0.1.16/api_foundry/dao/sql_custom_query_handler.py +0 -66
  26. api_foundry-0.1.16/api_foundry/dao/sql_delete_query_handler.py +0 -36
  27. api_foundry-0.1.16/api_foundry/dao/sql_insert_query_handler.py +0 -102
  28. api_foundry-0.1.16/api_foundry/dao/sql_query_handler.py +0 -378
  29. api_foundry-0.1.16/api_foundry/dao/sql_select_query_handler.py +0 -303
  30. api_foundry-0.1.16/api_foundry/dao/sql_subselect_query_handler.py +0 -63
  31. api_foundry-0.1.16/api_foundry/dao/sql_update_query_handler.py +0 -59
  32. api_foundry-0.1.16/api_foundry/iac/gateway_spec.py +0 -632
  33. api_foundry-0.1.16/api_foundry/iac/handler.py +0 -42
  34. api_foundry-0.1.16/api_foundry/iac/pulumi/api_foundry.py +0 -127
  35. api_foundry-0.1.16/api_foundry/operation.py +0 -15
  36. api_foundry-0.1.16/api_foundry/services/service.py +0 -60
  37. api_foundry-0.1.16/api_foundry/services/transactional_service.py +0 -35
  38. api_foundry-0.1.16/api_foundry/utils/model_factory.py +0 -482
  39. {api_foundry-0.1.16 → api_foundry-0.1.19}/.gitignore +0 -0
  40. {api_foundry-0.1.16 → api_foundry-0.1.19}/LICENSE +0 -0
  41. {api_foundry-0.1.16 → api_foundry-0.1.19}/api_foundry/scripts/install_secret.py +0 -0
  42. {api_foundry-0.1.16 → api_foundry-0.1.19}/api_foundry/scripts/postgres_to_openapi.py +0 -0
  43. {api_foundry-0.1.16 → api_foundry-0.1.19}/api_foundry/utils/app_exception.py +0 -0
  44. {api_foundry-0.1.16 → api_foundry-0.1.19}/api_foundry/utils/logger.py +0 -0
  45. {api_foundry-0.1.16 → api_foundry-0.1.19}/api_foundry/utils/spec_handler.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.3
1
+ Metadata-Version: 2.4
2
2
  Name: api-foundry
3
- Version: 0.1.16
3
+ Version: 0.1.19
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
@@ -9,7 +9,9 @@ License-File: LICENSE
9
9
  Classifier: Operating System :: OS Independent
10
10
  Classifier: Programming Language :: Python :: 3.9
11
11
  Requires-Python: >=3.9
12
+ Requires-Dist: api-foundry-query-engine
12
13
  Requires-Dist: boto3
14
+ Requires-Dist: cloud-foundry
13
15
  Requires-Dist: cryptography
14
16
  Requires-Dist: pulumi
15
17
  Requires-Dist: pulumi-aws
@@ -0,0 +1,6 @@
1
+ # __init__.py
2
+
3
+ from api_foundry.iac.pulumi.api_foundry import APIFoundry
4
+ from cloud_foundry import logger
5
+
6
+ __all__ = ["APIFoundry", "logger"]
@@ -0,0 +1,545 @@
1
+ # gatway_spec.py
2
+
3
+ import copy
4
+ from typing import Any, Optional
5
+
6
+ from cloud_foundry import Function
7
+ from cloud_foundry.utils.aws_openapi_editor import AWSOpenAPISpecEditor
8
+
9
+ from cloud_foundry import logger
10
+
11
+
12
+ log = logger(__name__)
13
+
14
+
15
+ class APISpecEditor:
16
+ api_spec: dict
17
+ function: Function
18
+ integrations: list[dict]
19
+
20
+ def __init__(self, *, open_api_spec: dict, function_name: str, function: Function):
21
+ self.function = function
22
+ self.integrations = []
23
+ self.editor = AWSOpenAPISpecEditor(copy.deepcopy(open_api_spec))
24
+
25
+ def rest_api_spec(self) -> str:
26
+ schemas = self.editor.get_spec_part(["components", "schemas"], create=False)
27
+ if schemas:
28
+ for schema_name, schema_object in schemas.items():
29
+ self.generate_crud_operations(schema_name, schema_object)
30
+
31
+ self.editor.remove_attributes_by_pattern("^x-af-.*$")
32
+
33
+ self.editor.correct_schema_names()
34
+ return self.editor.to_yaml()
35
+
36
+ def add_operation(
37
+ self,
38
+ path: str,
39
+ method: str,
40
+ operation: dict,
41
+ schema_object: Optional[dict] = None,
42
+ ):
43
+ self.integrations.append(
44
+ {"path": path, "method": method, "function": self.function}
45
+ )
46
+ self.editor.add_operation(path, method, operation, schema_object)
47
+
48
+ def generate_regex(self, property: dict[str, Any]) -> str:
49
+ regex_pattern = ""
50
+
51
+ if property["type"] == "string" and property.get("format", None) == "date":
52
+ # Assuming ISO 8601 date format (YYYY-MM-DD)
53
+ regex_pattern = r"\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])" # Date part: YYYY-MM-DD
54
+
55
+ elif (
56
+ property["type"] == "string" and property.get("format", None) == "date-time"
57
+ ):
58
+ regex_pattern = (
59
+ r"\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])" # Date part: YYYY-MM-DD
60
+ r"T" # Separator: T
61
+ r"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])" # Time part: HH:MM:SS
62
+ r"(?:\.\d+)?(?:Z|[+-](?:0[0-9]|1[0-4]):[0-5][0-9])?" # Optional: fractional seconds and timezone
63
+ )
64
+
65
+ elif property["type"] == "string":
66
+ if "pattern" in property:
67
+ regex_pattern = f"{property.get('pattern')}" + regex_pattern
68
+ else:
69
+ max_length = property.get("max_length", 200)
70
+ min_length = property.get("min_length", 0)
71
+ regex_pattern = rf"[\w\s]{min_length},{max_length}" # Allows letters, numbers, and underscores
72
+
73
+ elif property["type"] == "integer":
74
+ signed = property.get("signed", True)
75
+ regex_pattern = r"[\-\+]?\d+" if signed else r"\d+"
76
+
77
+ elif property["type"] == "number":
78
+ regex_pattern = r"[+-]?\d+(\.\d+)?"
79
+
80
+ if len(regex_pattern) == 0:
81
+ regex_pattern = ".*"
82
+
83
+ return (
84
+ rf"^{regex_pattern}$"
85
+ + rf"|^(?:lt::|le::|eq::|ne::|ge::|gt::)?{regex_pattern}$"
86
+ + rf"|^between::{regex_pattern},{regex_pattern}$"
87
+ + rf"|^not-between::{regex_pattern},{regex_pattern},"
88
+ + rf"|^in::{regex_pattern}(,{regex_pattern})*$"
89
+ + rf"|^not-in::{regex_pattern}(,{regex_pattern})*$"
90
+ )
91
+
92
+ def generate_query_parameters(self, schema_object: dict[str, Any]):
93
+ parameters = []
94
+ for (
95
+ property_name,
96
+ property_details,
97
+ ) in self.get_input_properties(schema_object, include_primary_key=True).items():
98
+ parameter = {
99
+ "in": "query",
100
+ "name": property_name,
101
+ "required": False,
102
+ "schema": {
103
+ "type": property_details["type"],
104
+ "pattern": self.generate_regex(property_details),
105
+ }, # Assuming default type is string
106
+ "description": f"Filter by {property_name}",
107
+ }
108
+ parameters.append(parameter)
109
+ return parameters
110
+
111
+ def __list_of_schema(self, schema_name: str):
112
+ return {
113
+ "application/json": {
114
+ "schema": {
115
+ "type": "array",
116
+ "items": {"$ref": f"#/components/schemas/{schema_name}"},
117
+ }
118
+ }
119
+ }
120
+
121
+ def get_primary_key(
122
+ self, schema_object: dict[str, Any]
123
+ ) -> Optional[tuple[str, dict[str, Any]]]:
124
+ for name, property in schema_object["properties"].items():
125
+ if "x-af-primary-key" in property:
126
+ return (name, property)
127
+ return None
128
+
129
+ def get_concurrency_property(
130
+ self, schema_object: dict[str, Any]
131
+ ) -> Optional[tuple[str, dict[str, Any]]]:
132
+ concurrency_property = schema_object.get("x-af-concurrency-control", None)
133
+ if concurrency_property:
134
+ return (
135
+ concurrency_property,
136
+ schema_object["properties"][concurrency_property],
137
+ )
138
+ return None
139
+
140
+ def get_input_properties(
141
+ self, schema_object: dict[str, Any], include_primary_key: bool = False
142
+ ) -> dict[str, Any]:
143
+ # Retrieve primary key and concurrency property if they exist
144
+ primary_key = (
145
+ self.get_primary_key(schema_object) if not include_primary_key else None
146
+ )
147
+ concurrency_property = self.get_concurrency_property(schema_object)
148
+
149
+ result = dict()
150
+ for name, prop in schema_object["properties"].items():
151
+ if "$ref" in prop:
152
+ ref_parts = prop["$ref"].lstrip("#/").split("/")
153
+ referenced_schema = self.editor.get_spec_part(ref_parts)
154
+ if referenced_schema:
155
+ prop = {**prop, **referenced_schema}
156
+ prop.pop("$ref")
157
+
158
+ if (
159
+ "x-af-parent-property" not in prop
160
+ and "x-af-child-property" not in prop
161
+ and (
162
+ include_primary_key
163
+ or name != (primary_key[0] if primary_key else None)
164
+ )
165
+ and name != (concurrency_property[0] if concurrency_property else None)
166
+ ):
167
+ result[name] = prop
168
+ return result
169
+
170
+ def get_required_input_properties(
171
+ self,
172
+ schema_object: dict[str, Any],
173
+ input_properties: dict[str, Any],
174
+ ) -> list[str]:
175
+ # Filter the required properties from input properties
176
+ required_properties = schema_object.get("required", [])
177
+ return [name for name in input_properties if name in required_properties]
178
+
179
+ def generate_crud_operations(self, schema_name, schema_object: dict):
180
+ path = f"/{schema_name.lower()}"
181
+ self.generate_create_operation(path, schema_name, schema_object)
182
+ self.generate_get_by_id_operation(path, schema_name, schema_object)
183
+ self.generate_get_many_operation(path, schema_name, schema_object)
184
+ self.generate_update_by_id_operation(path, schema_name, schema_object)
185
+ self.generate_update_with_cc_operation(path, schema_name, schema_object)
186
+ self.generate_update_many_operation(path, schema_name, schema_object)
187
+ self.generate_delete_by_id_operation(path, schema_name, schema_object)
188
+ self.generate_delete_with_cc_operation(path, schema_name, schema_object)
189
+ self.generate_delete_many_operation(path, schema_name, schema_object)
190
+
191
+ def generate_create_operation(
192
+ self, path: str, schema_name: str, schema_object: dict[str, Any]
193
+ ):
194
+ primary_key = self.get_primary_key(schema_object)
195
+ include_primary_key = primary_key and primary_key[1].get("key_type") == "manual"
196
+ input_properties = self.get_input_properties(
197
+ schema_object, include_primary_key=include_primary_key or False
198
+ )
199
+ self.add_operation(
200
+ path,
201
+ "post",
202
+ operation={
203
+ "summary": f"Create a new {schema_name}",
204
+ "requestBody": {
205
+ "required": True,
206
+ "content": {
207
+ "application/json": {
208
+ "schema": {
209
+ "type": "object",
210
+ "properties": input_properties,
211
+ "required": self.get_required_input_properties(
212
+ schema_object, input_properties
213
+ ),
214
+ }
215
+ }
216
+ },
217
+ },
218
+ "responses": {
219
+ "201": {
220
+ "description": f"{schema_name} created successfully",
221
+ "content": self.__list_of_schema(schema_name),
222
+ }
223
+ },
224
+ },
225
+ schema_object=schema_object,
226
+ )
227
+
228
+ def generate_get_many_operation(
229
+ self, path: str, schema_name: str, schema_object: dict[str, Any]
230
+ ):
231
+ self.add_operation(
232
+ path,
233
+ "get",
234
+ {
235
+ "summary": f"Retrieve all {schema_name}",
236
+ "parameters": self.generate_query_parameters(schema_object),
237
+ "responses": {
238
+ "200": {
239
+ "description": f"A list of {schema_name}.",
240
+ "content": self.__list_of_schema(schema_name),
241
+ }
242
+ },
243
+ },
244
+ )
245
+
246
+ def generate_get_by_id_operation(
247
+ self, path: str, schema_name: str, schema_object: dict[str, Any]
248
+ ):
249
+ key = self.get_primary_key(schema_object)
250
+ if not key:
251
+ return
252
+
253
+ key_name = key[0]
254
+ key_properties = key[1]
255
+
256
+ self.add_operation(
257
+ f"{path}/{{{key_name}}}",
258
+ "get",
259
+ {
260
+ "summary": f"Retrieve {schema_name} by {key_name}",
261
+ "parameters": [
262
+ {
263
+ "name": "id",
264
+ "in": "path",
265
+ "description": f"ID of the {schema_name} to get",
266
+ "required": True,
267
+ "schema": {"type": key_properties},
268
+ }
269
+ ],
270
+ "responses": {
271
+ "200": {
272
+ "description": f"A list of {schema_name}.",
273
+ "content": self.__list_of_schema(schema_name),
274
+ }
275
+ },
276
+ },
277
+ )
278
+
279
+ def generate_update_by_id_operation(
280
+ self, path: str, schema_name: str, schema_object: dict[str, Any]
281
+ ):
282
+ concurrency = self.get_concurrency_property(schema_object)
283
+ if concurrency:
284
+ return
285
+
286
+ key = self.get_primary_key(schema_object)
287
+ if not key:
288
+ return
289
+
290
+ key_name = key[0]
291
+ key_properties = key[1]
292
+
293
+ # Update operation
294
+ self.add_operation(
295
+ f"{path}/{{{key_name}}}",
296
+ "put",
297
+ {
298
+ "summary": f"Update an existing {schema_name} by {key_name}",
299
+ "parameters": [
300
+ {
301
+ "name": key_name,
302
+ "in": "path",
303
+ "description": f"ID of the {schema_name} to update",
304
+ "required": True,
305
+ "schema": key_properties,
306
+ }
307
+ ],
308
+ "requestBody": {
309
+ "required": True,
310
+ "content": {
311
+ "application/json": {
312
+ "schema": {
313
+ "type": "object",
314
+ "properties": self.get_input_properties(schema_object),
315
+ "required": [], # No properties are marked as required
316
+ }
317
+ }
318
+ },
319
+ },
320
+ "responses": {
321
+ "200": {
322
+ "description": f"{schema_name} updated successfully",
323
+ "content": self.__list_of_schema(schema_name),
324
+ }
325
+ },
326
+ },
327
+ )
328
+
329
+ def generate_update_with_cc_operation(
330
+ self, path: str, schema_name: str, schema_object: dict[str, Any]
331
+ ):
332
+ # Update operation
333
+ key = self.get_primary_key(schema_object)
334
+ if not key:
335
+ return
336
+
337
+ key_name = key[0]
338
+ key_properties = key[1]
339
+
340
+ cc_tuple = self.get_concurrency_property(schema_object)
341
+ if not cc_tuple:
342
+ return
343
+
344
+ cc_property_name = cc_tuple[0]
345
+ cc_property = cc_tuple[1]
346
+
347
+ self.add_operation(
348
+ f"{path}/{{{key_name}}}/{cc_property_name}/{{{cc_property_name}}}",
349
+ "put",
350
+ {
351
+ "summary": f"Update an existing {schema_name} by ID",
352
+ "parameters": [
353
+ {
354
+ "name": key_name,
355
+ "in": "path",
356
+ "description": f"ID of the {schema_name} to update",
357
+ "required": True,
358
+ "schema": key_properties,
359
+ },
360
+ {
361
+ "name": cc_property_name,
362
+ "in": "path",
363
+ "description": (
364
+ cc_property_name + " of the " + schema_name + " to update"
365
+ ),
366
+ "required": True,
367
+ "schema": cc_property,
368
+ },
369
+ ],
370
+ "requestBody": {
371
+ "required": False,
372
+ "content": {
373
+ "application/json": {
374
+ "schema": {
375
+ "type": "object",
376
+ "properties": self.get_input_properties(schema_object),
377
+ "required": [],
378
+ }
379
+ }
380
+ },
381
+ },
382
+ "responses": {
383
+ "200": {
384
+ "description": f"{schema_name} updated successfully",
385
+ "content": self.__list_of_schema(schema_name),
386
+ }
387
+ },
388
+ },
389
+ )
390
+
391
+ def generate_update_many_operation(
392
+ self, path: str, schema_name: str, schema_object: dict[str, Any]
393
+ ):
394
+ cc_tuple = self.get_concurrency_property(schema_object)
395
+ if cc_tuple:
396
+ return
397
+
398
+ # Update operation
399
+ self.add_operation(
400
+ path,
401
+ "put",
402
+ {
403
+ "summary": f"Update an existing {schema_name} by ID",
404
+ "parameters": self.generate_query_parameters(schema_object),
405
+ "requestBody": {
406
+ "required": False,
407
+ "content": {
408
+ "application/json": {
409
+ "schema": {
410
+ "type": "object",
411
+ "properties": schema_object["properties"],
412
+ "required": [],
413
+ }
414
+ }
415
+ },
416
+ },
417
+ "responses": {
418
+ "200": {
419
+ "description": f"{schema_name} updated successfully",
420
+ "content": self.__list_of_schema(schema_name),
421
+ }
422
+ },
423
+ },
424
+ )
425
+
426
+ # Delete operation
427
+
428
+ def generate_delete_with_cc_operation(
429
+ self, path: str, schema_name: str, schema_object: dict[str, Any]
430
+ ):
431
+ cc_tuple = self.get_concurrency_property(schema_object)
432
+ if not cc_tuple:
433
+ return
434
+
435
+ cc_property_name = cc_tuple[0]
436
+ cc_property = cc_tuple[1]
437
+
438
+ key = self.get_primary_key(schema_object)
439
+ if not key:
440
+ return
441
+
442
+ key_name = key[0]
443
+ key_properties = key[1]
444
+
445
+ self.add_operation(
446
+ f"{path}/{{{key_name}}}/{cc_property_name}/{{{cc_property_name}}}",
447
+ "delete",
448
+ {
449
+ "summary": f"Delete an existing {schema_name} by ID",
450
+ "parameters": [
451
+ {
452
+ "name": key_name,
453
+ "in": "path",
454
+ "description": f"ID of the {schema_name} to update",
455
+ "required": True,
456
+ "schema": {"type": key_properties},
457
+ },
458
+ {
459
+ "name": cc_property_name,
460
+ "in": "path",
461
+ "description": (
462
+ f"{cc_property_name} of the {schema_name} to update"
463
+ ),
464
+ "required": True,
465
+ "schema": cc_property,
466
+ },
467
+ ],
468
+ "responses": {
469
+ "204": {
470
+ "description": f"{schema_name} deleted successfully",
471
+ "content": self.__list_of_schema(schema_name),
472
+ }
473
+ },
474
+ },
475
+ )
476
+
477
+ def generate_delete_by_id_operation(
478
+ self, path: str, schema_name: str, schema_object: dict[str, Any]
479
+ ):
480
+ if self.get_concurrency_property(schema_object):
481
+ return
482
+
483
+ key = self.get_primary_key(schema_object)
484
+ if not key:
485
+ return
486
+
487
+ key_name = key[0]
488
+ key_properties = key[1]
489
+
490
+ self.add_operation(
491
+ f"{path}/{{{key_name}}}",
492
+ "delete",
493
+ {
494
+ "summary": f"Delete an existing {schema_name} by {key_name}",
495
+ "parameters": [
496
+ {
497
+ "name": key_name,
498
+ "in": "path",
499
+ "description": f"ID of the {schema_name} to update",
500
+ "required": True,
501
+ "schema": {"type": key_properties},
502
+ }
503
+ ],
504
+ "responses": {
505
+ "204": {
506
+ "description": f"{schema_name} deleted successfully",
507
+ "content": self.__list_of_schema(schema_name),
508
+ }
509
+ },
510
+ },
511
+ )
512
+
513
+ def generate_delete_many_operation(
514
+ self, path: str, schema_name: str, schema_object: dict[str, Any]
515
+ ):
516
+ if self.get_concurrency_property(schema_object):
517
+ return
518
+
519
+ self.add_operation(
520
+ path,
521
+ "delete",
522
+ {
523
+ "summary": f"Delete many existing {schema_name} using query",
524
+ "parameters": self.generate_query_parameters(schema_object),
525
+ "responses": {
526
+ "204": {
527
+ "description": f"{schema_name} deleted successfully",
528
+ "content": self.__list_of_schema(schema_name),
529
+ }
530
+ },
531
+ },
532
+ )
533
+
534
+ def transform_schemas(self, spec_dict):
535
+ for component_name, component_data in (
536
+ spec_dict.get("components", {}).get("schemas", {}).items()
537
+ ):
538
+ # Remove attributes that start with 'x-af'
539
+ attributes_to_remove = [
540
+ key for key in component_data if key.startswith("x-af")
541
+ ]
542
+ for attribute in attributes_to_remove:
543
+ component_data.pop(attribute)
544
+
545
+ return spec_dict
@@ -0,0 +1,119 @@
1
+ import pkgutil
2
+ import os
3
+ import json
4
+ import yaml
5
+ from typing import Union
6
+ from pulumi import ComponentResource, Config
7
+
8
+ # from pulumi_aws import get_caller_identity, get_region
9
+
10
+ import cloud_foundry
11
+
12
+ from api_foundry.iac.gateway_spec import APISpecEditor
13
+ from api_foundry.utils.model_factory import ModelFactory
14
+ from cloud_foundry import logger
15
+
16
+ log = logger(__name__)
17
+
18
+
19
+ class APIFoundry(ComponentResource):
20
+ api_spec_editor: APISpecEditor
21
+
22
+ def __init__(
23
+ self,
24
+ name,
25
+ *,
26
+ api_spec: str,
27
+ secrets: str,
28
+ environment: dict[str, str] = {},
29
+ body: Union[str, list[str]] = [],
30
+ integrations: list[dict] = [],
31
+ token_validators: list[dict] = [],
32
+ policy_statements: list = [],
33
+ vpc_config: dict = {},
34
+ opts=None,
35
+ ):
36
+ super().__init__("cloud_foundry:apigw:APIFoundry", name, None, opts)
37
+
38
+ if os.path.exists(api_spec):
39
+ with open(api_spec, "r") as yaml_file:
40
+ api_spec_dict = yaml.safe_load(yaml_file)
41
+ else:
42
+ api_spec_dict = yaml.safe_load(api_spec)
43
+
44
+ if isinstance(body, str):
45
+ body = [body]
46
+
47
+ # Check if we are deploying to LocalStack
48
+ if self.is_deploying_to_localstack():
49
+ # Add LocalStack-specific environment variables
50
+ localstack_env = {
51
+ "AWS_ACCESS_KEY_ID": "test",
52
+ "AWS_SECRET_ACCESS_KEY": "test",
53
+ "AWS_ENDPOINT_URL": "http://localstack:4566",
54
+ }
55
+ environment = {**localstack_env, **environment}
56
+ environment["SECRETS"] = secrets
57
+
58
+ # account_id = get_caller_identity().account_id
59
+ # region = get_region().name
60
+ for database, secret_name in json.loads(secrets).items():
61
+ policy_statements.append(
62
+ {
63
+ "Effect": "Allow",
64
+ "Actions": ["secretsmanager:GetSecretValue"],
65
+ "Resources": ["*"],
66
+ # "Resources": [f"arn:aws:secretsmanager:{region}:{account_id}:secret:{secret_name}"],
67
+ }
68
+ )
69
+
70
+ self.api_function = cloud_foundry.python_function(
71
+ name=name,
72
+ environment=environment,
73
+ sources={
74
+ "api_spec.yaml": yaml.safe_dump(
75
+ ModelFactory(api_spec_dict).get_config_output()
76
+ ),
77
+ "app.py": pkgutil.get_data(
78
+ "api_foundry_query_engine", "lambda_handler.py"
79
+ ).decode(), # type: ignore
80
+ },
81
+ requirements=["psycopg2-binary", "pyyaml", "api_foundry_query_engine"],
82
+ policy_statements=policy_statements,
83
+ vpc_config=vpc_config,
84
+ )
85
+
86
+ gateway_spec = APISpecEditor(
87
+ open_api_spec=api_spec_dict,
88
+ function=self.api_function,
89
+ function_name=name,
90
+ )
91
+ # log.info(f"integrations: {gateway_spec.integrations}")
92
+ self.rest_api = cloud_foundry.rest_api(
93
+ name,
94
+ body=[*body, gateway_spec.rest_api_spec()],
95
+ integrations=[*integrations, *gateway_spec.integrations],
96
+ token_validators=token_validators,
97
+ )
98
+
99
+ def integrations(self) -> list[dict]:
100
+ return self.api_spec_editor.integrations
101
+
102
+ def is_deploying_to_localstack(self) -> bool:
103
+ # Create a Pulumi Config instance
104
+ config = Config("aws")
105
+
106
+ # Check if the 'endpoints' configuration is set, which usually indicates LocalStack
107
+ endpoints = config.get("endpoints")
108
+
109
+ if endpoints:
110
+ try:
111
+ # Parse the endpoints configuration and check for LocalStack URL
112
+ endpoints_list = json.loads(endpoints)
113
+ for endpoint in endpoints_list:
114
+ if "localhost" in endpoint.get("url", ""):
115
+ return True
116
+ except json.JSONDecodeError:
117
+ pass
118
+
119
+ return False