1414# limitations under the License.
1515#
1616
17- """Event Gate Lambda function implementation."""
17+ """
18+ This module contains the AWS Lambda entry point for the EventGate service.
19+ """
20+
1821import json
1922import logging
2023import os
2427import boto3
2528from botocore .exceptions import BotoCoreError , NoCredentialsError
2629
30+ from src .handlers .handler_api import HandlerApi
2731from src .handlers .handler_token import HandlerToken
2832from src .handlers .handler_topic import HandlerTopic
2933from src .handlers .handler_health import HandlerHealth
3438from src .writers .writer_postgres import WriterPostgres
3539from src .utils .conf_path import CONF_DIR , INVALID_CONF_ENV
3640
37- PROJECT_ROOT = os .path .abspath (os .path .join (os .path .dirname (__file__ ), ".." ))
3841
3942# Initialize logger
40- logger = logging .getLogger (__name__ )
43+ root_logger = logging .getLogger ()
44+ if not root_logger .handlers :
45+ root_logger .addHandler (logging .StreamHandler ())
46+
4147log_level = os .environ .get ("LOG_LEVEL" , "INFO" )
42- logger .setLevel (log_level )
43- if not logger .handlers :
44- logger .addHandler (logging .StreamHandler ())
48+ root_logger .setLevel (log_level )
49+ logger = logging .getLogger (__name__ )
4550logger .debug ("Initialized logger with level %s" , log_level )
4651
4752# Load main configuration
5257 config = json .load (file )
5358logger .debug ("Loaded main configuration" )
5459
55- # Load API definition
56- with open (os .path .join (PROJECT_ROOT , "api.yaml" ), "r" , encoding = "utf-8" ) as file :
57- API = file .read ()
58- logger .debug ("Loaded API definition" )
59-
6060# Initialize S3 client with SSL verification
6161try :
6262 ssl_verify = config .get (SSL_CA_BUNDLE_KEY , True )
6666 logger .exception ("Failed to initialize AWS S3 client" )
6767 raise RuntimeError ("AWS S3 client initialization failed" ) from exc
6868
69- # Load access configuration
70- ACCESS : Dict [str , list [str ]] = {}
71- if config ["access_config" ].startswith ("s3://" ):
72- name_parts = config ["access_config" ].split ("/" )
73- BUCKET_NAME = name_parts [2 ]
74- BUCKET_OBJECT_KEY = "/" .join (name_parts [3 :])
75- ACCESS = json .loads (aws_s3 .Bucket (BUCKET_NAME ).Object (BUCKET_OBJECT_KEY ).get ()["Body" ].read ().decode ("utf-8" ))
76- else :
77- with open (config ["access_config" ], "r" , encoding = "utf-8" ) as file :
78- ACCESS = json .load (file )
79- logger .debug ("Loaded access configuration" )
80-
81- # Initialize token handler and load token public keys
82- handler_token = HandlerToken (config ).load_public_keys ()
83-
8469# Initialize EventGate writers
8570writers = {
8671 "kafka" : WriterKafka (config ),
8772 "eventbridge" : WriterEventBridge (config ),
8873 "postgres" : WriterPostgres (config ),
8974}
9075
91- # Initialize topic handler and load topic schemas
92- handler_topic = HandlerTopic (CONF_DIR , ACCESS , handler_token , writers ).load_topic_schemas ()
93-
94- # Initialize health handler
76+ # Initialize EventGate handlers
77+ handler_token = HandlerToken (config ).with_public_keys_queried ()
78+ handler_topic = HandlerTopic (config , aws_s3 , handler_token , writers ).with_load_access_config ().with_load_topic_schemas ()
9579handler_health = HandlerHealth (writers )
80+ handler_api = HandlerApi ().with_api_definition_loaded ()
9681
9782
98- def get_api () -> Dict [str , Any ]:
99- """Return the OpenAPI specification text."""
100- return {"statusCode" : 200 , "body" : API }
83+ # Route to handler function mapping
84+ ROUTE_MAP : Dict [str , Any ] = {
85+ "/api" : lambda _ : handler_api .get_api (),
86+ "/token" : lambda _ : handler_token .get_token_provider_info (),
87+ "/health" : lambda _ : handler_health .get_health (),
88+ "/topics" : lambda _ : handler_topic .get_topics_list (),
89+ "/topics/{topic_name}" : handler_topic .handle_request ,
90+ "/terminate" : lambda _ : sys .exit ("TERMINATING" ),
91+ }
10192
10293
10394def lambda_handler (event : Dict [str , Any ], _context : Any = None ) -> Dict [str , Any ]:
10495 """
10596 AWS Lambda entry point. Dispatches based on API Gateway proxy 'resource' and 'httpMethod'.
97+
10698 Args:
10799 event: The event data from API Gateway.
108100 _context: The mandatory context argument for AWS Lambda invocation (unused).
@@ -113,26 +105,11 @@ def lambda_handler(event: Dict[str, Any], _context: Any = None) -> Dict[str, Any
113105 """
114106 try :
115107 resource = event .get ("resource" , "" ).lower ()
116- if resource == "/api" :
117- return get_api ()
118- if resource == "/token" :
119- return handler_token .get_token_provider_info ()
120- if resource == "/health" :
121- return handler_health .get_health ()
122- if resource == "/topics" :
123- return handler_topic .get_topics_list ()
124- if resource == "/topics/{topic_name}" :
125- method = event .get ("httpMethod" )
126- if method == "GET" :
127- return handler_topic .get_topic_schema (event ["pathParameters" ]["topic_name" ].lower ())
128- if method == "POST" :
129- return handler_topic .post_topic_message (
130- event ["pathParameters" ]["topic_name" ].lower (),
131- json .loads (event ["body" ]),
132- handler_token .extract_token (event .get ("headers" , {})),
133- )
134- if resource == "/terminate" :
135- sys .exit ("TERMINATING" )
108+ route_function = ROUTE_MAP .get (resource )
109+
110+ if route_function :
111+ return route_function (event )
112+
136113 return build_error_response (404 , "route" , "Resource not found" )
137114 except (KeyError , json .JSONDecodeError , ValueError , AttributeError , TypeError , RuntimeError ) as request_exc :
138115 logger .exception ("Request processing error: %s" , request_exc )
0 commit comments