Request Lifecycle Specification
This document details the exact, step-by-step traversal of HTTP REST requests and WebSocket connections through the MetaPilot architecture stack.
1. HTTP REST Request Lifecycle
Rendering diagram...
Detailed Pipeline Traversal Breakdown
Phase A: Socket Ingestion & ASGI Processing
- TCP Socket Ingestion: Daphne listens on via Twisted event loop.
0.0.0.0:8000 - ASGI Scope Construction: Converts raw HTTP headers into an ASGI scope dictionary:
python
{ 'type': 'http', 'method': 'POST', 'path': '/api/clients/', 'headers': [(b'host', b'localhost:8000'), (b'authorization', b'Bearer eyJ...'), (b'x-tenant-id', b'96598ec0...')] }
Phase B: Django Middleware Pipeline Execution
- : Evaluates
CorsMiddlewareheader againstOrigin(CORS_ALLOWED_ORIGINS). If preflighthttp://localhost:3000request, returnsOPTIONSimmediately with CORS response headers.200 OK - &
SecurityMiddleware: Applies strict transport security, content-type nosniff rules, and static asset routing.WhiteNoiseMiddleware - (
TenantMiddleware):tenants.middleware- Inspects HTTP header.
X-Tenant-ID - If missing, decodes JWT access token claim .
tenant_id - Queries database: .
Tenant.objects.filter(id=tenant_id, is_active=True).first() - Attaches resolved instance to .
request.tenant
- Inspects
- & SimpleJWT (
AuthenticationMiddleware):rest_framework_simplejwt.authentication.JWTAuthentication- Extracts Bearer token from header.
Authorization - Decodes token using and algorithm
settings.SECRET_KEY.HS256 - Verifies signature, expiration timestamp (), and ensures token type is
exp.access - Fetches active user and attaches .
request.user
- Extracts Bearer token from
Phase C: ViewSet & Permission Execution
- DRF Permission Layer: Evaluates . If user role fails RBAC check, raises
permission_classes = [IsAuthenticated, IsSuperAdmin](PermissionDenied).403 Forbidden - Serializer Field & Business Validation:
- runs validations on
TenantSerializer.is_valid(raise_exception=True),name, andslug.wa_access_token - Verifies slug uniqueness in database.
- Cryptographic Encryption & Model Persistence:
- Inside , calls
TenantSerializer.create().config.set_value(wa_access_token) - encrypts plaintext access token using
TenantConfig.set_value().Fernet(settings.FERNET_KEY) - Executes SQL inside atomic transaction (
INSERT).transaction.atomic()
- Inside
Phase D: Response Serialization
- DTO Construction: Serializer maps model attributes to JSON representation (omitting sensitive decrypted values).
- HTTP Output Dispatch: Returns back through middleware stack to client.
Response(data, status=status.HTTP_201_CREATED)
2. WebSocket Request & Connection Lifecycle
Rendering diagram...
Detailed Pipeline Traversal Breakdown
- Protocol Protocol Routing: routes
core/asgi.pyconnections throughwebsockettoProtocolTypeRouter.URLRouter - Channel Group Registration: extracts
InboxConsumer.connect()from URL keyword arguments, verifies agent membership, and callstenant_id.async_to_sync(self.channel_layer.group_add)(f"inbox_{tenant_id}", self.channel_name) - Redis Subscription: The connection is registered under Redis Pub/Sub channel in Redis DB 1.
inbox_<tenant_id> - Realtime Broadcast Dispatch:
- Inbound webhook arrives or agent replies to conversation.
- Django publishes event: .
channel_layer.group_send(f"inbox_{tenant_id}", {"type": "new_message", "data": ...}) - Redis broadcasts event payload to all connected WebSocket worker processes.
- encodes payload as JSON string and pushes frame over WebSocket connection.
InboxConsumer