Skip to content

Conversation

NFUChen
Copy link
Contributor

@NFUChen NFUChen commented Jul 18, 2025

Add Middleware Support to PySpring Framework

Overview

This PR introduces comprehensive middleware support to the PySpring framework, allowing developers to easily add custom request/response processing logic to their FastAPI applications. The implementation provides a clean, Spring-inspired middleware architecture with dependency injection support.

🚀 New Features

1. Middleware Base Class (Middleware)

  • Location: py_spring_core/core/entities/middlewares/middleware.py
  • Purpose: Provides a simplified base class for creating custom middlewares
  • Key Features:
    • Inherits from FastAPI's BaseHTTPMiddleware
    • Abstract process_request method for custom logic
    • Automatic request/response flow management
    • Support for early response returns

2. Middleware Registry (MiddlewareRegistry)

  • Location: py_spring_core/core/entities/middlewares/middleware_registry.py
  • Purpose: Centralized middleware management with single inheritance pattern
  • Key Features:
    • Abstract base class for middleware registration
    • Single inheritance enforcement via SingleInheritanceRequired
    • Automatic middleware application to FastAPI app
    • Dependency injection support for middleware classes

3. Single Inheritance Interface (SingleInheritanceRequired)

  • Location: py_spring_core/core/interfaces/single_inheritance_required.py
  • Purpose: Enforces single inheritance pattern for registry classes
  • Key Features:
    • Generic type support
    • Subclass validation
    • Automatic subclass retrieval

🔧 Core Framework Updates

PySpring Application Updates

  • File: py_spring_core/core/application/py_spring_application.py
  • Changes:
    • Replaced controller-level middleware registration with centralized approach
    • Added __init_middlewares() method for automatic middleware initialization
    • Enhanced logging for middleware initialization process
    • Automatic dependency injection for middleware classes and registry

RestController Simplification

  • File: py_spring_core/core/entities/controllers/rest_controller.py
  • Changes:
    • Removed register_middlewares() method (no longer needed)
    • Updated documentation to reflect new middleware approach
    • Cleaner controller implementation

📦 Package Updates

Version Bump

  • From: 0.0.180.0.19
  • Reason: New middleware functionality addition

Dependencies

  • Added: pytest-asyncio>=1.1.0 for async test support

Public API Exports

  • Added: Middleware and MiddlewareRegistry to __all__ list

🧪 Comprehensive Test Suite

Test Coverage

  • File: tests/test_middleware.py (389 lines)
  • Coverage Areas:
    • Middleware base class functionality
    • Middleware registry operations
    • Integration testing with FastAPI
    • Single inheritance enforcement
    • Type hint validation
    • Async middleware execution
    • Request/response flow testing

Test Categories

  1. Unit Tests: Individual component testing
  2. Integration Tests: FastAPI application integration
  3. Async Tests: Proper async/await handling
  4. Type Tests: Type hint and inheritance validation

💡 Usage Example

from py_spring_core import Middleware, MiddlewareRegistry
from fastapi import Request, Response

# Define custom middleware
class AuthMiddleware(Middleware):
    async def process_request(self, request: Request) -> Response | None:
        if not request.headers.get("Authorization"):
            return Response(content="Unauthorized", status_code=401)
        return None

# Create middleware registry
class AppMiddlewareRegistry(MiddlewareRegistry):
    def get_middleware_classes(self) -> list[type[Middleware]]:
        return [AuthMiddleware]

# PySpring automatically discovers and applies middlewares

🔄 Breaking Changes

For Existing Users

  • Removed: register_middlewares() method from RestController
  • Migration: Middleware registration now happens through MiddlewareRegistry subclass
  • Impact: Low - existing controllers without custom middleware remain unaffected

🎯 Benefits

  1. Simplified Development: Clean, Spring-inspired middleware API
  2. Dependency Injection: Automatic DI support for middleware classes
  3. Type Safety: Comprehensive type hints and validation
  4. Testability: Extensive test coverage with async support
  5. Flexibility: Support for early returns and complex middleware chains
  6. Maintainability: Centralized middleware management

📋 Checklist

  • ✅ New middleware base class implementation
  • ✅ Middleware registry with single inheritance
  • ✅ Application context integration
  • ✅ Automatic middleware discovery and application
  • ✅ Comprehensive test suite (389 lines)
  • ✅ Type hints and documentation
  • ✅ Version bump and dependency updates
  • ✅ Public API exports
  • ✅ Breaking changes documented

🔍 Testing

Run the test suite to verify all functionality:

pytest tests/test_middleware.py -v

All tests should pass, including async middleware execution and integration tests.


Note: This PR maintains backward compatibility while introducing powerful new middleware capabilities that align with Spring Framework patterns.

- Introduced ContainerManager, DependencyInjector, ComponentManager, BeanManager, and PropertiesManager to streamline the management of components, beans, and properties.
- Enhanced error handling and logging for dependency injection failures.
- Updated tests to reflect changes in the application context structure and ensure proper registration and retrieval of components, beans, and properties.
- Improved documentation for classes and methods to clarify their responsibilities and usage.
- Updated the _validate_bean_view method to include a type hint for the view parameter, specifying it as BeanView.
- This change improves code clarity and helps with static type checking.
- Introduced Middleware and MiddlewareRegistry classes to manage middleware application in the FastAPI application.
- Refactored PySpringApplication to initialize middlewares during application startup.
- Updated RestController documentation to clarify middleware registration process.
- Bumped version to 0.0.20 to reflect the addition of new features.
…iddleware and MiddlewareRegistry

- Added pytest-asyncio to the development dependencies for async testing support.
- Created a new test suite for Middleware and MiddlewareRegistry, covering various scenarios including abstract class enforcement, middleware execution order, and early returns.
- Ensured that middleware functionality is thoroughly validated through integration tests, enhancing overall test coverage.
- Included Middleware in the __all__ list to ensure it is accessible for import.
- Updated import statements to reflect the addition of Middleware, enhancing module functionality.
- Updated the subclass validation logic to use a dictionary for tracking unique subclass names, ensuring only one subclass is allowed.
- Enhanced the error message to include the count and names of found subclasses for better clarity.
- Added a method to ApplicationContext for injecting dependencies into external objects, improving flexibility in middleware initialization.
- Updated PySpringApplication to log the injection of dependencies and refactor middleware application logic for better clarity and structure.
- Added logging for the injection of dependencies into middleware classes during application initialization.
- Improved clarity in middleware setup by explicitly logging each middleware class being processed.
- Expanded the docstring for MiddlewareRegistry to clarify the automatic middleware registration and execution order.
- Explained the stacking behavior of middlewares during request and response paths, providing an example for better understanding.
@NFUChen NFUChen changed the title Feat/enforce single parent registration Add Middleware Support to PySpring Framework Jul 18, 2025
@NFUChen NFUChen merged commit 4ea85cd into main Jul 18, 2025
1 check passed
@NFUChen NFUChen deleted the feat/enforce-single-parent-registration branch July 18, 2025 08:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants