lambda-api-decorators-cdk 0.4.0__py3-none-any.whl → 0.4.4__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.
@@ -1,4 +1,5 @@
1
- from typing import Mapping, Optional, Sequence
1
+ from collections.abc import Mapping
2
+ from typing import Optional, Sequence
2
3
 
3
4
  from aws_cdk import Duration
4
5
  from aws_cdk import aws_ec2 as ec2
@@ -29,7 +30,29 @@ class LambdaApiConfig:
29
30
  s3_buckets: Optional[Mapping[str, s3.IBucket]] = None,
30
31
  authorizers: Optional[Mapping[str, object]] = None,
31
32
  default_authorizer: Optional[str] = None,
33
+ default_runtime: Optional[str] = None,
34
+ default_role: Optional[iam.IRole] = None,
35
+ common_environment: Optional[Mapping[str, str]] = None,
36
+ role_registry: Optional[Mapping[str, iam.IRole]] = None,
37
+ environment_registry: Optional[Mapping[str, Mapping[str, str]]] = None,
38
+ layer_registry: Optional[Mapping[str, lambda_.ILayerVersion]] = None,
39
+ security_group_registry: Optional[Mapping[str, ec2.ISecurityGroup]] = None,
40
+ vpc_registry: Optional[Mapping[str, ec2.IVpc]] = None,
41
+ dynamodb_table_registry: Optional[Mapping[str, dynamodb.ITable]] = None,
42
+ s3_bucket_registry: Optional[Mapping[str, s3.IBucket]] = None,
43
+ authorizer_registry: Optional[Mapping[str, object]] = None,
32
44
  ) -> None:
45
+ if default_runtime is not None:
46
+ self._validate_runtime_name(default_runtime)
47
+ if default_runtime is not None and runtime is not None:
48
+ raise ValueError("runtime and default_runtime cannot both be supplied")
49
+ if default_role is not None and role is not None:
50
+ raise ValueError("role and default_role cannot both be supplied")
51
+ if common_environment is not None and environment is not None:
52
+ raise ValueError(
53
+ "environment and common_environment cannot both be supplied"
54
+ )
55
+
33
56
  self._default_runtime = runtime
34
57
  self._default_timeout = timeout
35
58
  self._default_memory_size = memory_size
@@ -40,7 +63,13 @@ class LambdaApiConfig:
40
63
  self._common_security_groups = (
41
64
  list(security_groups) if security_groups is not None else []
42
65
  )
43
- self._common_environments = dict(environment) if environment is not None else {}
66
+ self._common_environments = dict(
67
+ common_environment if common_environment is not None else environment or {}
68
+ )
69
+ if default_runtime is not None:
70
+ self._default_runtime = default_runtime
71
+ if default_role is not None:
72
+ self._default_role = default_role
44
73
 
45
74
  self._custom_runtimes = {}
46
75
  self._custom_roles = {}
@@ -61,6 +90,49 @@ class LambdaApiConfig:
61
90
  self._default_authorizer = None
62
91
  self.set_default_authorizer(default_authorizer)
63
92
 
93
+ for key, value in (role_registry or {}).items():
94
+ self.register_role(key, value)
95
+ for key, value in (environment_registry or {}).items():
96
+ self.register_environment(key, value)
97
+ for key, value in (layer_registry or {}).items():
98
+ self.register_layer(key, value)
99
+ for key, value in (security_group_registry or {}).items():
100
+ self.register_security_group(key, value)
101
+ for key, value in (vpc_registry or {}).items():
102
+ self.register_vpc(key, value)
103
+ for key, value in (dynamodb_table_registry or {}).items():
104
+ self.register_dynamodb_table(key, value)
105
+ for key, value in (s3_bucket_registry or {}).items():
106
+ self.register_s3_bucket(key, value)
107
+ for key, value in (authorizer_registry or {}).items():
108
+ self.register_authorizer(key, value)
109
+
110
+ @staticmethod
111
+ def _validate_runtime_name(runtime: str) -> None:
112
+ supported = {
113
+ "python3.10", "python3.11", "python3.12", "python3.13", "python3.14"
114
+ }
115
+ if not isinstance(runtime, str):
116
+ raise TypeError("runtime must be a string")
117
+ if runtime not in supported:
118
+ raise ValueError(
119
+ "runtime must be one of {}".format(", ".join(sorted(supported)))
120
+ )
121
+
122
+ @staticmethod
123
+ def _validate_registry_key(key: str, registry_name: str) -> None:
124
+ if not isinstance(key, str):
125
+ raise TypeError(f"{registry_name} keys must be strings")
126
+ if not key.strip():
127
+ raise ValueError(f"{registry_name} keys must not be empty or whitespace")
128
+
129
+ @classmethod
130
+ def _register(cls, registry: dict, key: str, value, registry_name: str) -> None:
131
+ cls._validate_registry_key(key, registry_name)
132
+ if key in registry:
133
+ raise ValueError(f"{registry_name} key {key!r} is already registered")
134
+ registry[key] = value
135
+
64
136
  def set_default_runtime(self, runtime: Optional[lambda_.Runtime]) -> None:
65
137
  self._default_runtime = runtime
66
138
 
@@ -90,9 +162,6 @@ class LambdaApiConfig:
90
162
  if security_group not in self._common_security_groups:
91
163
  self._common_security_groups.append(security_group)
92
164
 
93
- def add_common_environment(self, key: str, value: str) -> None:
94
- self._common_environments[key] = value
95
-
96
165
  def add_custom_runtime(self, key: str, runtime: lambda_.Runtime) -> None:
97
166
  self._custom_runtimes[key] = runtime
98
167
 
@@ -141,6 +210,50 @@ class LambdaApiConfig:
141
210
  raise ValueError(f"Authorizer key {key!r} is already registered")
142
211
  self._authorizers[key] = authorizer
143
212
 
213
+ def register_role(self, key: str, role: iam.IRole) -> None:
214
+ self._register(self._custom_roles, key, role, "role registry")
215
+
216
+ def register_environment(self, key: str, value: Mapping[str, str]) -> None:
217
+ if not isinstance(value, Mapping):
218
+ raise TypeError("environment registry values must be mappings")
219
+ self._register(self._custom_environments, key, dict(value), "environment registry")
220
+
221
+ def register_layer(self, key: str, layer: lambda_.ILayerVersion) -> None:
222
+ self._register(self._custom_layers, key, layer, "layer registry")
223
+
224
+ def register_security_group(self, key: str, security_group: ec2.ISecurityGroup) -> None:
225
+ self._register(
226
+ self._custom_security_groups, key, security_group, "security group registry"
227
+ )
228
+
229
+ def register_vpc(
230
+ self,
231
+ key: str,
232
+ vpc: ec2.IVpc,
233
+ vpc_subnets: Optional[ec2.SubnetSelection] = None,
234
+ ) -> None:
235
+ self._register(self._custom_vpcs, key, (vpc, vpc_subnets), "vpc registry")
236
+
237
+ def register_dynamodb_table(self, key: str, table: dynamodb.ITable) -> None:
238
+ self._register(self._dynamodb_tables, key, table, "dynamodb table registry")
239
+
240
+ def register_s3_bucket(self, key: str, bucket: s3.IBucket) -> None:
241
+ self._register(self._s3_buckets, key, bucket, "s3 bucket registry")
242
+
243
+ def register_authorizer(self, key: str, authorizer: object) -> None:
244
+ self._validate_registry_key(key, "authorizer registry")
245
+ interfaces = getattr(authorizer, "__jsii_ifaces__", ()) if authorizer is not None else ()
246
+ supported = {
247
+ "aws_cdk.aws_apigateway.IAuthorizer",
248
+ "aws_cdk.aws_apigatewayv2.IHttpRouteAuthorizer",
249
+ }
250
+ if not any(
251
+ f"{interface.__module__}.{interface.__name__}" in supported
252
+ for interface in interfaces
253
+ ):
254
+ raise TypeError("authorizer registry values must be CDK authorizers")
255
+ self._register(self._authorizers, key, authorizer, "authorizer registry")
256
+
144
257
  def set_default_authorizer(self, key: Optional[str]) -> None:
145
258
  if key is None:
146
259
  self._default_authorizer = None
@@ -179,7 +292,10 @@ class LambdaApiConfig:
179
292
  custom_runtimes=dict(self._custom_runtimes),
180
293
  custom_roles=dict(self._custom_roles),
181
294
  custom_layers=dict(self._custom_layers),
182
- custom_environments=dict(self._custom_environments),
295
+ custom_environments={
296
+ key: dict(value) if isinstance(value, Mapping) else value
297
+ for key, value in self._custom_environments.items()
298
+ },
183
299
  custom_security_groups=dict(self._custom_security_groups),
184
300
  custom_vpcs=dict(self._custom_vpcs),
185
301
  dynamodb_tables=dict(self._dynamodb_tables),
@@ -50,7 +50,7 @@ class ResourceBuilder():
50
50
  ) -> 'ResourceBuilder':
51
51
 
52
52
  '''
53
- Creates base instance of a Resource Builder. By default, there are no predetermined custom, common nor default settings with the exception of the following custom runtimes: python3.8, python3.9, python3.10, python3.11, python3.12, python3.13, python3.14.
53
+ Creates base instance of a Resource Builder. By default, there are no predetermined custom, common nor default settings with the exception of the following custom runtimes: python3.10, python3.11, python3.12, python3.13, python3.14.
54
54
  You can optionally specify arguments (Keep in mind some of them are constructs of the aws_cdk toolkit) such as:
55
55
  @param default_runtime
56
56
  @param default_timeout
@@ -93,8 +93,6 @@ class ResourceBuilder():
93
93
  self._physical_dynamodb_tables = {}
94
94
  self._physical_s3_buckets = {}
95
95
 
96
- self.custom_runtimes.update({'python3.8':lambda_.Runtime.PYTHON_3_8})
97
- self.custom_runtimes.update({'python3.9':lambda_.Runtime.PYTHON_3_9})
98
96
  self.custom_runtimes.update({'python3.10':lambda_.Runtime.PYTHON_3_10})
99
97
  self.custom_runtimes.update({'python3.11':lambda_.Runtime.PYTHON_3_11})
100
98
  self.custom_runtimes.update({'python3.12':lambda_.Runtime.PYTHON_3_12})
@@ -132,10 +130,6 @@ class ResourceBuilder():
132
130
  '''Add a common security group for all your Lambda Functions.'''
133
131
  self.common_security_groups.append(security_group) if security_group not in self.common_security_groups else None
134
132
 
135
- def add_common_environment(self, key:str, value):
136
- '''Add a common environment variable and value for all your Lambda Functions.'''
137
- self.common_environments.update({key:value})
138
-
139
133
  def add_custom_vpc(self, key: str, vpc: ec2.Vpc, vpc_subnets: list):
140
134
  self.custom_vpcs.update({key:(vpc, vpc_subnets)})
141
135
 
@@ -197,7 +191,7 @@ class ResourceBuilder():
197
191
  def get_custom_layer(self, value: str) -> lambda_.LayerVersion | _lambda_python.PythonLayerVersion:
198
192
  if value in self.custom_layers:
199
193
  return self.custom_layers[value]
200
- else: raise KeyError(f'Value {value} not previously declared as custom layer')
194
+ else: raise KeyError(f'layer registry key {value!r} is not registered')
201
195
 
202
196
  def get_custom_roles(self):
203
197
  return self.custom_roles
@@ -205,26 +199,28 @@ class ResourceBuilder():
205
199
  def get_custom_role(self, value: str) -> iam.Role:
206
200
  if value in self.custom_roles:
207
201
  return self.custom_roles[value]
208
- else: raise KeyError(f'Value {value} not previously declared as custom role')
202
+ else: raise KeyError(f'role registry key {value!r} is not registered')
209
203
 
210
204
  def get_custom_security_group(self, value: str) -> ec2.SecurityGroup:
211
205
  if value in self.custom_security_groups:
212
206
  return self.custom_security_groups[value]
213
- else: raise KeyError(f'Value {value} not previously declared as custom security group')
207
+ else: raise KeyError(f'security group registry key {value!r} is not registered')
214
208
 
215
- def get_custom_environment(self, value: str) -> str:
209
+ def get_custom_environment(self, value: str):
216
210
  if value in self.custom_environments:
217
211
  return self.custom_environments[value]
218
- else: raise KeyError(f'Value {value} not previously declared as custom environment')
212
+ else: raise KeyError(f'environment registry key {value!r} is not registered')
219
213
 
220
214
  def get_custom_runtime(self, value: str) -> lambda_.Runtime:
221
215
  if value in self.custom_runtimes:
222
216
  return self.custom_runtimes[value]
223
- else: raise KeyError(f'Value {value} not previously declared as custom runtime')
217
+ else: raise KeyError(f'runtime alias {value!r} is not registered')
224
218
 
225
219
  def get_custom_vpc(self, value: str) -> tuple:
226
- #TODO
227
- return self.custom_vpcs[value]
220
+ try:
221
+ return self.custom_vpcs[value]
222
+ except KeyError:
223
+ raise KeyError(f'vpc registry key {value!r} is not registered') from None
228
224
 
229
225
  def build(self, construct, api_resource: apigateway.IResource, lambda_path:str,
230
226
  print_tree: bool = False,
@@ -245,9 +241,9 @@ class ResourceBuilder():
245
241
  if print_tree:
246
242
  ast_helper.dump_tree(graph)
247
243
  self._prepare_layers(construct, graph, layer_sources)
248
- self._emit_authorization_diagnostics(construct, graph)
249
244
  self.build_from_graph(
250
245
  construct, graph, api_resource, lambda_root, source_layout)
246
+ self._emit_configuration_diagnostics(construct, graph)
251
247
 
252
248
  def build_http(self, construct, http_api: apigateway2.HttpApi,
253
249
  lambda_path:str, print_tree: bool = False,
@@ -267,9 +263,9 @@ class ResourceBuilder():
267
263
  if print_tree:
268
264
  ast_helper.dump_tree(graph)
269
265
  self._prepare_layers(construct, graph, layer_sources)
270
- self._emit_authorization_diagnostics(construct, graph)
271
266
  self.build_http_from_graph(
272
267
  construct, graph, http_api, lambda_root, source_layout)
268
+ self._emit_configuration_diagnostics(construct, graph)
273
269
 
274
270
  @staticmethod
275
271
  def _discover_layer_sources(layers_path: Optional[str]):
@@ -312,6 +308,8 @@ class ResourceBuilder():
312
308
 
313
309
  def _resolve_runtime(self, decorators: dict):
314
310
  runtime = self.get_default_runtime()
311
+ if isinstance(runtime, str):
312
+ runtime = self.get_custom_runtime(runtime)
315
313
  if 'runtime' in decorators:
316
314
  runtime = self.get_custom_runtime(decorators['runtime'])
317
315
  return runtime
@@ -476,9 +474,17 @@ class ResourceBuilder():
476
474
  elif key == 'environment':
477
475
  if type(value) == list:
478
476
  for v in value:
479
- options[key][v] = self.get_custom_environment(v)
477
+ selected = self.get_custom_environment(v)
478
+ if isinstance(selected, dict):
479
+ options[key].update(selected)
480
+ else:
481
+ options[key][v] = selected
480
482
  else:
481
- options[key][value] = self.get_custom_environment(value)
483
+ selected = self.get_custom_environment(value)
484
+ if isinstance(selected, dict):
485
+ options[key].update(selected)
486
+ else:
487
+ options[key][value] = selected
482
488
  elif key == 'vpc':
483
489
  options[key] = self.get_custom_vpc(value)
484
490
  return options
@@ -520,6 +526,127 @@ class ResourceBuilder():
520
526
  return None
521
527
  return key if state == "authorizer" else self.default_authorizer
522
528
 
529
+ @staticmethod
530
+ def _diagnostic_rows(graph: ast_helper.Resource):
531
+ rows = []
532
+
533
+ def visit(resource):
534
+ for method in resource.get_methods():
535
+ rows.append((resource.get_path(), method))
536
+ for child in resource.get_connections():
537
+ visit(child)
538
+
539
+ visit(graph)
540
+ return sorted(rows, key=lambda item: (item[0], item[1].get_method()))
541
+
542
+ @staticmethod
543
+ def _diagnostic_table(title, default_label, columns, rows):
544
+ if not rows:
545
+ return None
546
+ lines = [title, default_label, "", " ".join(columns)]
547
+ lines.extend(" ".join(row) for row in rows)
548
+ return "\n".join(lines)
549
+
550
+ def _emit_configuration_diagnostics(self, construct, graph):
551
+ if not isinstance(construct, Construct):
552
+ return
553
+ self._emit_authorization_diagnostics(construct, graph)
554
+ self._emit_role_diagnostics(construct, graph)
555
+ self._emit_vpc_diagnostics(construct, graph)
556
+ self._emit_shared_role_warning(construct, graph)
557
+
558
+ def _emit_role_diagnostics(self, construct, graph):
559
+ if self.default_role is None:
560
+ return
561
+ rows = []
562
+ for path, method in self._diagnostic_rows(graph):
563
+ decorators = self._configuration_decorators(method)
564
+ selected = decorators.get("role")
565
+ if selected is None:
566
+ continue
567
+ effective = self.get_custom_role(selected)
568
+ if effective is self.default_role:
569
+ continue
570
+ rows.append((method.get_method(), path, str(selected)))
571
+ message = self._diagnostic_table(
572
+ "Execution role overrides",
573
+ "Default role: configured default",
574
+ ("METHOD", "PATH", "EFFECTIVE"),
575
+ rows,
576
+ )
577
+ if message:
578
+ Annotations.of(construct).add_info(message)
579
+
580
+ @staticmethod
581
+ def _subnet_selection_name(selection):
582
+ if selection is None:
583
+ return "NONE"
584
+ subnet_type = getattr(selection, "subnet_type", None)
585
+ if subnet_type is not None:
586
+ return getattr(subnet_type, "value", str(subnet_type))
587
+ if getattr(selection, "subnet_group_name", None):
588
+ return str(selection.subnet_group_name)
589
+ if getattr(selection, "one_per_az", False):
590
+ return "ONE_PER_AZ"
591
+ if getattr(selection, "subnets", None):
592
+ return "EXPLICIT_SUBNETS"
593
+ return "DEFAULT"
594
+
595
+ def _emit_vpc_diagnostics(self, construct, graph):
596
+ if self.default_vpc is None:
597
+ return
598
+ default_vpc, default_subnets = self.default_vpc
599
+ rows = []
600
+ for path, method in self._diagnostic_rows(graph):
601
+ decorators = self._configuration_decorators(method)
602
+ selected = decorators.get("vpc")
603
+ if selected is None:
604
+ continue
605
+ effective_vpc, effective_subnets = self.get_custom_vpc(selected)
606
+ if (
607
+ effective_vpc is default_vpc
608
+ and effective_subnets is default_subnets
609
+ ):
610
+ continue
611
+ rows.append((
612
+ method.get_method(),
613
+ path,
614
+ str(selected),
615
+ self._subnet_selection_name(effective_subnets),
616
+ ))
617
+ message = self._diagnostic_table(
618
+ "VPC overrides",
619
+ "Default VPC: configured default",
620
+ ("METHOD", "PATH", "EFFECTIVE", "SUBNETS"),
621
+ rows,
622
+ )
623
+ if message:
624
+ Annotations.of(construct).add_info(message)
625
+
626
+ def _emit_shared_role_warning(self, construct, graph):
627
+ roles = {}
628
+ for path, method in self._diagnostic_rows(graph):
629
+ decorators = self._configuration_decorators(method)
630
+ selected = decorators.get("role")
631
+ if selected is None:
632
+ continue
633
+ grants = {
634
+ invocation.name
635
+ for invocation in method.get_decorator_invocations()
636
+ if invocation.name in {"grant_dynamodb", "grant_s3"}
637
+ }
638
+ if not grants:
639
+ continue
640
+ effective = self.get_custom_role(selected)
641
+ roles.setdefault(id(effective), (effective, set()))[1].add(path)
642
+
643
+ if any(len(paths) > 1 for _, paths in roles.values()):
644
+ Annotations.of(construct).add_warning_v2(
645
+ "LAD_ROLE_SHARED_PERMISSIONS",
646
+ "LAD_ROLE_SHARED_PERMISSIONS: an explicit execution role with "
647
+ "derived permissions is shared by multiple Lambda handlers.",
648
+ )
649
+
523
650
  @staticmethod
524
651
  def _implements_interface(authorizer, interface) -> bool:
525
652
  return interface in getattr(authorizer, "__jsii_ifaces__", ())
@@ -603,14 +730,21 @@ class ResourceBuilder():
603
730
  return
604
731
  deviations.sort(key=lambda item: (item[0], item[1]))
605
732
  if self.default_authorizer is None:
606
- heading = "Default authorizer: PUBLIC\n\nProtected routes:"
733
+ default_label = "Default authorizer: PUBLIC"
607
734
  else:
608
- heading = f"Default authorizer: {self.default_authorizer}\n\nOverrides:"
609
- details = "\n".join(
610
- f" {method} {path} {value}"
735
+ default_label = f"Default authorizer: {self.default_authorizer}"
736
+ rows = [
737
+ (method, path, value)
611
738
  for path, method, value in deviations
739
+ ]
740
+ message = self._diagnostic_table(
741
+ "Authorization overrides",
742
+ default_label,
743
+ ("METHOD", "PATH", "EFFECTIVE"),
744
+ rows,
612
745
  )
613
- Annotations.of(construct).add_info(f"{heading}\n{details}")
746
+ if message:
747
+ Annotations.of(construct).add_info(message)
614
748
 
615
749
  @staticmethod
616
750
  def _physical_resource_id(resource_type: str, physical_name: str) -> str:
@@ -841,11 +975,38 @@ class ResourceBuilder():
841
975
  return self.build_lambda_function(
842
976
  construct, method, lambda_root, source_layout)
843
977
 
978
+ @staticmethod
979
+ def _validate_single_route_handlers(graph: ast_helper.Resource) -> None:
980
+ seen = {}
981
+
982
+ def visit(resource):
983
+ for method in resource.get_methods():
984
+ handler = (
985
+ method.get_path_to_file(),
986
+ method.get_file(),
987
+ method.get_handler(),
988
+ method.get_method(),
989
+ )
990
+ if handler in seen:
991
+ raise ValueError(
992
+ f"Handler {handler[2]!r} has multiple routes for "
993
+ f"HTTP method {handler[3]!r}: "
994
+ f"{seen[handler]!r} and {resource.get_path()!r}"
995
+ )
996
+ seen[handler] = resource.get_path()
997
+ for child in resource.get_connections():
998
+ visit(child)
999
+
1000
+ visit(graph)
1001
+
844
1002
  def build_from_graph(self, construct, graph: ast_helper.Resource,
845
1003
  api_resource: apigateway.IResource,
846
1004
  lambda_root: Optional[Path] = None,
847
1005
  source_layout: SourceLayout = SourceLayout.ROOT):
848
1006
 
1007
+ if isinstance(construct, Construct):
1008
+ self._validate_single_route_handlers(graph)
1009
+
849
1010
  path = graph.get_path()
850
1011
  level = path.count('/')
851
1012
  if level <= 1 and len(path) <= 1: #root '/'
@@ -877,6 +1038,9 @@ class ResourceBuilder():
877
1038
  http_api: apigateway2.HttpApi,
878
1039
  lambda_root: Optional[Path] = None,
879
1040
  source_layout: SourceLayout = SourceLayout.ROOT):
1041
+ if isinstance(construct, Construct):
1042
+ self._validate_single_route_handlers(graph)
1043
+
880
1044
  method_mapping = {
881
1045
  'GET': apigateway2.HttpMethod.GET,
882
1046
  'POST': apigateway2.HttpMethod.POST,
@@ -0,0 +1,197 @@
1
+ Metadata-Version: 2.4
2
+ Name: lambda-api-decorators-cdk
3
+ Version: 0.4.4
4
+ Summary: AWS CDK integration for Lambda API Decorators. Generate AWS Lambda and API Gateway infrastructure from decorated Python handlers.
5
+ Author: Mateo Marcos, Emanuel Arguinarena, Lucas Picchi
6
+ License: MIT License
7
+
8
+ Copyright (c) 2024 Lambda API Decorators CDK
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ Project-URL: Homepage, https://infrastructure-as-decorator.github.io/
28
+ Project-URL: Documentation, https://infrastructure-as-decorator.github.io/docs/api-reference/index
29
+ Project-URL: Repository, https://github.com/infrastructure-as-decorator/lambda-api-decorators-cdk
30
+ Project-URL: Bug Reports, https://github.com/infrastructure-as-decorator/lambda-api-decorators-cdk/issues
31
+ Keywords: cdk,lambda,aws,api gateway,ast
32
+ Classifier: Development Status :: 2 - Pre-Alpha
33
+ Classifier: Intended Audience :: Developers
34
+ Classifier: Framework :: AWS CDK :: 2
35
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
36
+ Classifier: Topic :: Software Development :: Build Tools
37
+ Classifier: License :: OSI Approved :: MIT License
38
+ Classifier: Programming Language :: Python :: 3.10
39
+ Classifier: Programming Language :: Python :: 3.11
40
+ Classifier: Programming Language :: Python :: 3.12
41
+ Classifier: Programming Language :: Python :: 3.13
42
+ Classifier: Programming Language :: Python :: 3.14
43
+ Requires-Python: >=3.10
44
+ Description-Content-Type: text/markdown
45
+ License-File: LICENSE
46
+ Requires-Dist: aws-cdk.aws-lambda-python-alpha
47
+ Dynamic: license-file
48
+
49
+ # Lambda API Decorators CDK
50
+
51
+ AWS CDK integration for [Lambda API Decorators](https://github.com/infrastructure-as-decorator/lambda-api-decorators). Define API routes with Python decorators and let CDK create the Lambda functions, integrations, routes, and related configuration.
52
+
53
+ The complete cross-package guides and architecture documentation are available at [infrastructure-as-decorator.github.io](https://infrastructure-as-decorator.github.io/).
54
+
55
+ ## Installation
56
+
57
+ ```bash
58
+ pip install lambda-api-decorators-cdk
59
+ ```
60
+
61
+ The package requires Python 3.10 or newer and AWS CDK v2. The `lambda-api-decorators` package provides the decorators used by the Lambda source files.
62
+
63
+ ## Quick start
64
+
65
+ `LambdaApi` is the recommended high-level construct. It creates a REST API by default and discovers decorated handlers below `lambda_path`.
66
+
67
+ ```python
68
+ from aws_cdk import Stack
69
+ from constructs import Construct
70
+
71
+ from lambda_api_decorators_cdk import LambdaApi
72
+
73
+
74
+ class ExampleStack(Stack):
75
+ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
76
+ super().__init__(scope, construct_id, **kwargs)
77
+
78
+ LambdaApi(self, "ExampleApi", lambda_path="lambdas")
79
+ ```
80
+
81
+ A handler must include an HTTP method decorator from `lambda-api-decorators`:
82
+
83
+ ```python
84
+ from lambda_api_decorators import GET
85
+
86
+
87
+ @GET("/hello")
88
+ def hello(event, context):
89
+ return {"statusCode": 200, "body": "Hello, world!"}
90
+ ```
91
+
92
+ `lambda_path` is resolved from the directory where CDK is run. Files without a supported route decorator are ignored.
93
+
94
+ ## API types and imported APIs
95
+
96
+ REST is the default. Select an HTTP API with `ApiType.HTTP`, or provide an existing supported API and let the construct infer its type.
97
+
98
+ ```python
99
+ from aws_cdk import aws_apigateway as apigateway
100
+ from lambda_api_decorators_cdk import ApiType, LambdaApi
101
+
102
+
103
+ LambdaApi(self, "HttpApi", lambda_path="lambdas", api_type=ApiType.HTTP)
104
+
105
+ existing_rest_api = apigateway.RestApi(self, "ExistingRestApi")
106
+ LambdaApi(self, "ExistingApiRoutes", lambda_path="lambdas", api=existing_rest_api)
107
+ ```
108
+
109
+ Created and imported REST APIs are supported. Concrete `aws_apigatewayv2.HttpApi` instances are supported for HTTP APIs.
110
+
111
+ ## Reusable configuration
112
+
113
+ Use `LambdaApiConfig` for defaults and named resources shared by one or more `LambdaApi` constructs. Configuration must be complete before constructing the API.
114
+
115
+ ```python
116
+ from aws_cdk import Duration, aws_lambda as lambda_
117
+ from lambda_api_decorators_cdk import LambdaApi, LambdaApiConfig
118
+
119
+
120
+ config = LambdaApiConfig(
121
+ runtime=lambda_.Runtime.PYTHON_3_12,
122
+ timeout=Duration.seconds(30),
123
+ memory_size=512,
124
+ environment={"ENVIRONMENT": "production"},
125
+ )
126
+ config.add_custom_environment("PAYMENTS_URL", "https://payments.example.com")
127
+
128
+ LambdaApi(self, "ConfiguredApi", lambda_path="lambdas", config=config)
129
+ ```
130
+
131
+ `LambdaApiConfig` supports default and custom runtimes, roles, VPCs, subnets, layers, security groups, and environment variables. It also supports registries for DynamoDB tables, S3 buckets, and REST or HTTP authorizers. A reused configuration creates an isolated builder snapshot for each API.
132
+
133
+ ## Source layout and layers
134
+
135
+ By default, each handler is packaged relative to the source root. For a service-oriented layout, use `SourceLayout.SERVICE`:
136
+
137
+ ```python
138
+ from lambda_api_decorators_cdk import LambdaApi, SourceLayout
139
+
140
+
141
+ LambdaApi(
142
+ self,
143
+ "ServiceApi",
144
+ lambda_path="services",
145
+ source_layout=SourceLayout.SERVICE,
146
+ layers_path="layers",
147
+ )
148
+ ```
149
+
150
+ When `layers_path` is provided, each visible child directory is treated as a discoverable layer source. Explicit layer configuration remains available through `LambdaApiConfig`.
151
+
152
+ ## Authorization and permissions
153
+
154
+ Register authorizers with a logical key and select the default authorizer for routes. A handler can override the default with `@authorizer("key")` or make itself public with `@public`.
155
+
156
+ ```python
157
+ from aws_cdk import aws_apigateway as apigateway
158
+ from lambda_api_decorators_cdk import LambdaApiConfig
159
+
160
+
161
+ authorizer = apigateway.TokenAuthorizer(self, "UsersAuthorizer", handler=authorizer_fn)
162
+ config = LambdaApiConfig(authorizers={"users": authorizer}, default_authorizer="users")
163
+ ```
164
+
165
+ The resource registries also allow decorated handlers to request least-privilege grants for registered DynamoDB tables and S3 buckets. See the [complete documentation](https://infrastructure-as-decorator.github.io/docs/api-reference/index) for decorator syntax and supported access levels.
166
+
167
+ ## Low-level builder
168
+
169
+ `ResourceBuilder` remains a supported lower-level API for callers that need direct control over the API root or build lifecycle:
170
+
171
+ ```python
172
+ from aws_cdk import Duration
173
+ from lambda_api_decorators_cdk import ResourceBuilder
174
+
175
+
176
+ builder = ResourceBuilder()
177
+ builder.set_default_timeout(Duration.seconds(30))
178
+ builder.add_common_environment("ENVIRONMENT", "production")
179
+ builder.build(self, rest_api.root, "lambdas")
180
+ ```
181
+
182
+ Prefer `LambdaApi` for new code. It owns API creation or reuse and delegates option resolution to isolated `ResourceBuilder` snapshots.
183
+
184
+ ## Releases
185
+
186
+ The Git tag is the single source of truth for this package's version. For example, `v0.3.0` produces Python package version `0.3.0`. This repository is versioned independently from `lambda-api-decorators`.
187
+
188
+ To release from `main`, push a semantic version tag:
189
+
190
+ ```bash
191
+ git checkout main
192
+ git pull
193
+ git tag v0.3.0
194
+ git push origin v0.3.0
195
+ ```
196
+
197
+ Pushing the tag triggers the release workflow, which tests, builds, verifies the version, and publishes to PyPI using trusted publishing. The PyPI project must have a trusted publisher configured for this repository, the `release.yml` workflow, and the `pypi` GitHub environment.
@@ -2,11 +2,11 @@ lambda_api_decorators_cdk/__init__.py,sha256=LkPu_ySBeRlGKVYbeLV86H78kYFrEQHBuzm
2
2
  lambda_api_decorators_cdk/api_type.py,sha256=UjhwP6KBwILl7NpL17e4mL-Bi5JdcfDs3oq2bxoESL0,146
3
3
  lambda_api_decorators_cdk/ast_helper.py,sha256=5aXh7dFjTKaBdEfO9Vd9l8HEOnO7WkgnXCQaUA-bmCU,15996
4
4
  lambda_api_decorators_cdk/lambda_api.py,sha256=wqiwe10-XOuPG8kxn2YGcpk4IHag1WG6mMHFENLgRhc,3148
5
- lambda_api_decorators_cdk/lambda_api_config.py,sha256=NWJPjAvFXhxjiFN0wCrWGyT3-UJ_jJJp12KDyQOzya4,7989
6
- lambda_api_decorators_cdk/resource_builder.py,sha256=z3m_Qzq-c_r69CVWgn1FdLcN_XxOj8q_o3SsTLC_p4Q,41791
5
+ lambda_api_decorators_cdk/lambda_api_config.py,sha256=Nbi-4kx9P5u0OUoQq2S-Ll8eFKc9fbanhJYs1nOvkmU,13542
6
+ lambda_api_decorators_cdk/resource_builder.py,sha256=G0Cs9x_pytUiL01iPo1_661G1SSzuuBamxPbS8Vn8b4,47774
7
7
  lambda_api_decorators_cdk/source_layout.py,sha256=rvw2D0UTOyhHmiCg_NTuxFf2wvsFCBugnwNKd3NLWLo,167
8
- lambda_api_decorators_cdk-0.4.0.dist-info/licenses/LICENSE,sha256=kABKIBEzZQqtNkBsAA9tA_Ume6OKdVUnChslMCL2Baw,1081
9
- lambda_api_decorators_cdk-0.4.0.dist-info/METADATA,sha256=EdDP2OfwWSTC1-gD1kyRY9rBqBuNFV6G8SyrsE1Vl5U,6487
10
- lambda_api_decorators_cdk-0.4.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
11
- lambda_api_decorators_cdk-0.4.0.dist-info/top_level.txt,sha256=1goCGc19BssxULn6ejZNLDYP0sQHEyqCMhivbGjxDCE,26
12
- lambda_api_decorators_cdk-0.4.0.dist-info/RECORD,,
8
+ lambda_api_decorators_cdk-0.4.4.dist-info/licenses/LICENSE,sha256=kABKIBEzZQqtNkBsAA9tA_Ume6OKdVUnChslMCL2Baw,1081
9
+ lambda_api_decorators_cdk-0.4.4.dist-info/METADATA,sha256=gA5V7i8tAZ4_VSP3YGkKcGL-b89sJqJ-275mHqjIhb8,8315
10
+ lambda_api_decorators_cdk-0.4.4.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
11
+ lambda_api_decorators_cdk-0.4.4.dist-info/top_level.txt,sha256=1goCGc19BssxULn6ejZNLDYP0sQHEyqCMhivbGjxDCE,26
12
+ lambda_api_decorators_cdk-0.4.4.dist-info/RECORD,,
@@ -1,145 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: lambda-api-decorators-cdk
3
- Version: 0.4.0
4
- Summary: AWS CDK integration for Lambda API Decorators. Generate AWS Lambda and API Gateway infrastructure from decorated Python handlers.
5
- Author: Mateo Marcos, Emanuel Arguinarena, Lucas Picchi
6
- License: MIT License
7
-
8
- Copyright (c) 2024 Lambda API Decorators CDK
9
-
10
- Permission is hereby granted, free of charge, to any person obtaining a copy
11
- of this software and associated documentation files (the "Software"), to deal
12
- in the Software without restriction, including without limitation the rights
13
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
- copies of the Software, and to permit persons to whom the Software is
15
- furnished to do so, subject to the following conditions:
16
-
17
- The above copyright notice and this permission notice shall be included in all
18
- copies or substantial portions of the Software.
19
-
20
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
- SOFTWARE.
27
- Project-URL: Homepage, https://github.com/lambda-api-decorators/lambda-api-decorators-cdk
28
- Project-URL: Repository, https://github.com/lambda-api-decorators/lambda-api-decorators-cdk
29
- Project-URL: Bug Reports, https://github.com/lambda-api-decorators/lambda-api-decorators-cdk
30
- Keywords: cdk,lambda,aws,api gateway,ast
31
- Classifier: Development Status :: 2 - Pre-Alpha
32
- Classifier: Intended Audience :: Developers
33
- Classifier: Framework :: AWS CDK :: 2
34
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
35
- Classifier: Topic :: Software Development :: Build Tools
36
- Classifier: License :: OSI Approved :: MIT License
37
- Classifier: Programming Language :: Python :: 3.10
38
- Classifier: Programming Language :: Python :: 3.11
39
- Classifier: Programming Language :: Python :: 3.12
40
- Classifier: Programming Language :: Python :: 3.13
41
- Classifier: Programming Language :: Python :: 3.14
42
- Requires-Python: >=3.10
43
- Description-Content-Type: text/markdown
44
- License-File: LICENSE
45
- Requires-Dist: aws-cdk.aws-lambda-python-alpha
46
- Dynamic: license-file
47
-
48
- # Lambda API Decorators CDK
49
-
50
- ## A library for AWS API Gateway/Lambda Proxy Integration
51
-
52
- Lambda API Decorators CDK allows simplified resource creation for AWS Lambda functions and Rest API resources by using decorators and setting a builder with default, common or custom values for IAM Roles, Runtimes, Timeouts, Layers, Environment values, etc. This project relies abstract syntactic trees (ast) to analyze the code of your lambda functions and generate infraestructure accordingly.
53
-
54
- ### Installation
55
-
56
- `lambda_api_decorators_cdk` is available from PyPI as `lambda-api-decorators-cdk`:
57
-
58
- pip install lambda-api-decorators-cdk
59
-
60
- Installation of [lambda-api-decorators](https://pypi.org/project/lambda-api-decorators/) is also required as a dependency for your lambda functions, since it provides the definition of decorators used within this module.
61
-
62
-
63
- ### Example
64
-
65
- ```python
66
- import lambda_api_decorators_cdk
67
- or
68
- from lambda_api_decorators_cdk import ResourceBuilder
69
- ```
70
-
71
- ### Builder instance
72
-
73
- You may define a builder using lambda_api_decorators_cdk's constructor `ResourceBuilder`. This method returns an instance of the class that will be used to configure and create your Lambda Functions. By default, no parameters are required to instantiate the object, but custom options may be passed in advanced use cases.
74
-
75
- ```python
76
- from lambda_api_decorators_cdk import ResourceBuilder
77
-
78
- builder = ResourceBuilder()
79
- ```
80
-
81
- ### Builder Configuration
82
-
83
- If opted to, you can set default values for IAM Roles, Memory Size, Timeout, Runtime and VPC.
84
-
85
- On the same note, support for common configuration that all the Lambda Functions will receive, such as Security Groups, Environment variables and Layers, is provided.
86
-
87
- Lastly you can setup custom environments, layers, security groups, vpcs a Lambda Function will receive ONLY if they have the decorators defined.
88
-
89
- ```python
90
- from lambda_api_decorators_cdk import ResourceBuilder
91
- from aws_cdk import Duration
92
-
93
- builder = ResourceBuilder()
94
- builder.set_default_timeout(Duration.seconds(30))
95
- builder.add_common_environment("DATABASE_URI", "something-db-related")
96
- builder.add_custom_environment("URL-PREFIX", "lambda-api-decorators-cdk-") #Lambda Function should have decorator @environment("URL-PREFIX")
97
- ```
98
-
99
- ### Building
100
-
101
- Assuming you have already instantiated a Builder, configured it and ready to deploy your stack, then simply define the directory of your Lambda Functions and build!
102
-
103
- Note: For a Lambda Function to be recognised and built, it has to have a decorator specifying the HTTP method it responds to. Decorators are defined in the [lambda-api-decorators](https://pypi.org/project/lambda-api-decorators/) package.
104
-
105
- ```python
106
- [...] # Imports
107
-
108
- class LambdaApiDecoratorsExampleStack(Stack):
109
-
110
- def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
111
- super().__init__(scope, construct_id, **kwargs)
112
-
113
- [...] # Instantiating builder, defining options and layers...
114
-
115
- lambda_path = 'lambdas'
116
-
117
- restapi = apigateway.RestApi(
118
- self, 'lambda-api-decorators-RestApi',
119
- rest_api_name= 'lambda-api-decorators-restApi')
120
- root_resource = restapi.root
121
-
122
- builder.build(self, root_resource, lambda_path, print_tree=True)
123
-
124
- ```
125
-
126
- ## Maintainer releases
127
-
128
- The Git tag is the single source of truth for this package's version. For
129
- example, `v0.3.0` produces Python package version `0.3.0`. This repository is
130
- versioned independently from `lambda-api-decorators`.
131
-
132
- To release from `main`, choose and push a semantic version tag:
133
-
134
- ```bash
135
- git checkout main
136
- git pull
137
-
138
- git tag v0.3.0
139
- git push origin v0.3.0
140
- ```
141
-
142
- Pushing the tag triggers the release workflow, which tests, builds, verifies
143
- the version, and publishes with PyPI trusted publishing. The PyPI project must
144
- have a trusted publisher configured for this repository, the `release.yml`
145
- workflow, and the `pypi` GitHub environment.