Middleware API

Complete API reference for the RouteMQ Middleware interface and middleware development patterns.

Middleware Abstract Class

The Middleware class is an abstract base class that all middleware components must extend. It defines the interface for intercepting and processing MQTT messages before they reach controllers.

Import

from core.middleware import Middleware

Abstract Methods

handle(context, next_handler)

Process the request context and call the next handler in the middleware chain.

Signature:

async def handle(self, context: Dict[str, Any], next_handler: Callable[[Dict[str, Any]], Awaitable[Any]]) -> Any

Parameters:

  • context (Dict[str, Any]): Request context containing topic, payload, params, and client

  • next_handler (Callable): The next handler in the middleware chain

Returns: Any - The result of the request handling

Context Structure:

Properties

logger

Class-level logger instance for all middleware.

Type: logging.Logger Name: "RouteMQ.Middleware"

Example:

Creating Custom Middleware

Basic Middleware Pattern

Authentication Middleware

Rate Limiting Middleware

Validation Middleware

Monitoring Middleware

Middleware Execution Order

Middleware executes in the order specified in the middleware list:

Context Modification

Middleware can modify the context for downstream handlers:

Error Handling in Middleware

Graceful Error Handling

Circuit Breaker Pattern

Testing Middleware

Unit Testing

Best Practices

1. Single Responsibility

Each middleware should have one clear purpose:

2. Configurable Behavior

Make middleware configurable:

3. Graceful Degradation

Handle dependencies gracefully:

4. Performance Considerations

Keep middleware lightweight:

Last updated