Skip to content

Conversation

@tmikula-dev
Copy link
Collaborator

@tmikula-dev tmikula-dev commented Jan 20, 2026

Overview

This pull request refactors the EventGate Lambda entrypoint and related handler classes to improve modularity, testability, and maintainability. The main changes include extracting the OpenAPI handler into its own class, refactoring the topic handler.

Release Notes

  • Refactoring lambda module to OOP

Related

Closes #105

Summary by CodeRabbit

  • New Features

    • Added an API specification endpoint and an explicit termination endpoint.
    • Centralized routing via a route map for simpler request dispatch.
    • Access configuration can be loaded from S3 or local files.
  • Bug Fixes

    • Expanded error handling to return 500 for unexpected server errors.
  • Tests

    • Added/updated tests covering API spec loading, access-config loading, topic-schema discovery, and local-access behavior.

✏️ Tip: You can customize this high-level summary in your review settings.

@tmikula-dev tmikula-dev self-assigned this Jan 20, 2026
@tmikula-dev tmikula-dev added enhancement New feature or request refactoring Improving code quality, paying off tech debt, aligning APIs labels Jan 20, 2026
@github-actions
Copy link

AquaSec has completed a full security repository scan ✅ You can find the analysis results for this PR branch on this overview.
Below is the summary of the findings:

AQUASEC CRITICAL HIGH MEDIUM LOW TOTAL
sast 0 4 2 0 6
vulnerabilities 0 0 0 0 0
iacMisconfigurations 1 2 2 10 15
secrets 0 0 0 0 0
pipelineMisconfigurations 0 0 0 16 16
license 0 0 0 0 0
➡️ Total 1 6 4 26 37

@coderabbitai
Copy link

coderabbitai bot commented Jan 20, 2026

Walkthrough

Reworks the Lambda entry to a ROUTE_MAP-driven dispatcher, adds HandlerApi to serve api.yaml, refactors HandlerTopic to load access config (S3 or local) and expose handle_request, renames token/public-key loader, and updates tests to match the new wiring and file paths.

Changes

Cohort / File(s) Summary
Main Lambda Entry Point
src/event_gate_lambda.py
Replaced inline routing with ROUTE_MAP dispatch; centralized initialization of HandlerToken, HandlerTopic, HandlerHealth, HandlerApi and AWS S3 client; removed old API string/get_api; added /terminate route and broader exception handling returning 500 on unexpected errors.
API Handler
src/handlers/handler_api.py
Added HandlerApi with with_api_definition_loaded() to read api.yaml and get_api() to return an HTTP-like YAML response (statusCode, headers, body).
Topic Handler
src/handlers/handler_topic.py
Constructor changed to accept config, aws_s3, handler_token, writers; added with_load_access_config() and with_load_topic_schemas() initializers; made topic operations private and added handle_request(event) to route GET/POST for /topics/{topic_name}.
Token Handler
src/handlers/handler_token.py
Renamed public key loader load_public_keys()with_public_keys_queried() and updated call sites to use the new builder-style method.
Tests — Handlers
tests/handlers/test_handler_api.py, tests/handlers/test_handler_topic.py, tests/handlers/test_handler_token.py
New tests for HandlerApi; updated HandlerTopic tests to validate access-config loading from local file and S3; tests adjusted to use renamed token method with_public_keys_queried.
Tests — Config & Local Lambda
tests/test_conf_validation.py, tests/test_event_gate_lambda_local_access.py
Updated topic schema discovery path to topic_schemas/*.json; assertions adjusted to reference handler_topic.access_config after reload.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Lambda
    participant ROUTE_MAP
    participant HandlerToken
    participant HandlerTopic
    participant S3

    Client->>Lambda: invoke (HTTP-like event)
    Lambda->>ROUTE_MAP: lookup handler by resource/method
    ROUTE_MAP-->>Lambda: handler reference
    Lambda->>HandlerToken: ensure keys loaded (with_public_keys_queried)
    Lambda->>HandlerTopic: call handle_request(event)
    HandlerTopic->>S3: with_load_access_config / with_load_topic_schemas (if needed)
    S3-->>HandlerTopic: return access config / schemas
    HandlerTopic->>HandlerToken: validate/extract token (via HandlerToken)
    HandlerTopic-->>Lambda: return response dict (statusCode, headers, body)
    Lambda-->>Client: return response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • lsulak
  • petr-pokorny-absa
  • oto-macenauer-absa

Poem

🐇
I hopped through routes and mapped each way,
I fetched api.yaml to brighten the day.
S3 whispers schemas while tokens take flight,
Handlers now bustle from morning to night.
A rabbit’s small cheer for tidy dispatch delight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 73.08% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'EventGate Lambda entrypoint OOP' clearly and concisely summarizes the main change: refactoring the Lambda entrypoint to use object-oriented programming.
Description check ✅ Passed The description includes the required Overview and Release Notes sections and mentions the related issue #105, aligning with the template structure.
Linked Issues check ✅ Passed The PR successfully implements the OOP refactoring of the Lambda module [#105]: extracted OpenAPI handler into HandlerApi, refactored topic handler, converted procedural code to method-based approach, and simplified main lambda_handler via ROUTE_MAP.
Out of Scope Changes check ✅ Passed All changes are scoped to the OOP refactoring objectives: handler classes, initialization methods, route mapping, and supporting test updates align with preparing the architecture for future stats endpoint implementation.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@src/event_gate_lambda.py`:
- Around line 79-87: The /terminate route in ROUTE_MAP currently maps to an
unprotected lambda that calls sys.exit("TERMINATING"); remove or guard this
endpoint: either delete the "/terminate" entry from ROUTE_MAP, or replace it
with a dedicated terminate handler that first checks an environment flag (e.g.,
ENABLE_TERMINATE or only allow in non-production) and validates a
secret/authorization token from the request before calling sys.exit; ensure the
new handler is the symbol referenced in ROUTE_MAP instead of the direct lambda
so authorization and env checks run prior to invoking sys.exit("TERMINATING").

In `@src/handlers/handler_topic.py`:
- Around line 114-125: The handler reads event["pathParameters"]["topic_name"],
event["body"], and calls json.loads without validating, which raises
KeyError/TypeError/JSONDecodeError; update the function handling this request to
validate inputs: check event is a dict, ensure pathParameters exists and
contains a non-empty topic_name (normalize with .lower()), verify httpMethod is
present and supported, and for POST ensure event["body"] is not None and is
valid JSON before calling json.loads; on any client-side issue return
build_error_response(400, "request", "<clear message>") and for unsupported
methods return 404 as before; keep references to topic_name, _get_topic_schema,
_post_topic_message, handler_token.extract_token, and build_error_response when
implementing these checks.

In `@tests/handlers/test_handler_api.py`:
- Around line 1-5: Add the standard 2026 copyright header to the top of the new
test file tests/handlers/test_handler_api.py so it includes the required project
header for new Python files created in 2026; modify the top of the file (above
the imports) to insert the exact project copyright block used across the repo
(year 2026) to satisfy header checks.
🧹 Nitpick comments (2)
tests/test_conf_validation.py (1)

62-64: Assertion is ineffective with @pytest.mark.parametrize.

When the glob returns an empty list, pytest.mark.parametrize will simply skip the test (0 test cases generated) rather than fail it. The assert topic_file on line 64 will never execute if there are no files, so it cannot catch missing schema files.

Consider using a separate test or fixture to validate that schema files exist:

💡 Suggested approach
def test_topic_schemas_directory_has_files():
    """Ensure at least one topic schema exists."""
    files = glob(os.path.join(CONF_DIR, "topic_schemas", "*.json"))
    assert files, "No *.json files found in topic_schemas/"


`@pytest.mark.parametrize`("topic_file", glob(os.path.join(CONF_DIR, "topic_schemas", "*.json")))
def test_topic_json_schemas_basic(topic_file):
    schema = load_json(topic_file)
    # ... rest of validation
src/handlers/handler_api.py (1)

51-63: Consider handling uninitialized state.

get_api() returns an empty body if load_api_definition() was never called. While the current initialization flow in event_gate_lambda.py chains these calls correctly, a defensive check could improve robustness.

💡 Optional defensive check
     def get_api(self) -> Dict[str, Any]:
         """
         Return the OpenAPI specification.

         Returns:
             Dict[str, Any]: API Gateway response with OpenAPI spec.
         """
         logger.debug("Handling GET API")
+        if not self.api_spec:
+            logger.warning("API spec not loaded; returning empty response")
         return {
             "statusCode": 200,
             "headers": {"Content-Type": "application/yaml"},
             "body": self.api_spec,
         }

Copy link
Collaborator

@oto-macenauer-absa oto-macenauer-absa left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd add some checks for the initialization and slightly change the names of the initializer methods

# Conflicts:
#	src/event_gate_lambda.py
#	src/handlers/handler_topic.py
#	tests/handlers/test_handler_topic.py
@tmikula-dev tmikula-dev merged commit 61e48bf into master Jan 30, 2026
9 checks passed
@tmikula-dev tmikula-dev deleted the feature/105-lambda-module-oop branch January 30, 2026 07:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request refactoring Improving code quality, paying off tech debt, aligning APIs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Lambda module OOP

3 participants