FOCUSCurrently working on ScheduleSomething and LayerdEvents algorithmsLearn More
FOCUSCurrently working on ScheduleSomething and LayerdEvents algorithmsLearn More
FOCUSCurrently working on ScheduleSomething and LayerdEvents algorithmsLearn More
FOCUSCurrently working on ScheduleSomething and LayerdEvents algorithmsLearn More
CONTRIBUTING.MdArchitecture
Request Lifecycle Specs
DocsCONTRIBUTING.mdArchitectureRequest Lifecycle Specs
GitHub Live Sync

Request Lifecycle Specs

Live technical documentation fetched from GitHub repository omghante/metapilot/docs/architecture/request-lifecycle.md

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

  1. TCP Socket Ingestion: Daphne listens on
    0.0.0.0:8000
    via Twisted event loop.
  2. 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

  1. CorsMiddleware
    : Evaluates
    Origin
    header against
    CORS_ALLOWED_ORIGINS
    (
    http://localhost:3000
    ). If preflight
    OPTIONS
    request, returns
    200 OK
    immediately with CORS response headers.
  2. SecurityMiddleware
    &
    WhiteNoiseMiddleware
    : Applies strict transport security, content-type nosniff rules, and static asset routing.
  3. TenantMiddleware
    (
    tenants.middleware
    )
    :
    • Inspects
      X-Tenant-ID
      HTTP header.
    • 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
      .
  4. AuthenticationMiddleware
    & SimpleJWT (
    rest_framework_simplejwt.authentication.JWTAuthentication
    )
    :
    • Extracts Bearer token from
      Authorization
      header.
    • Decodes token using
      settings.SECRET_KEY
      and algorithm
      HS256
      .
    • Verifies signature, expiration timestamp (
      exp
      ), and ensures token type is
      access
      .
    • Fetches active user and attaches
      request.user
      .

Phase C: ViewSet & Permission Execution

  1. DRF Permission Layer: Evaluates
    permission_classes = [IsAuthenticated, IsSuperAdmin]
    . If user role fails RBAC check, raises
    PermissionDenied
    (
    403 Forbidden
    ).
  2. Serializer Field & Business Validation:
    • TenantSerializer.is_valid(raise_exception=True)
      runs validations on
      name
      ,
      slug
      , and
      wa_access_token
      .
    • Verifies slug uniqueness in database.
  3. Cryptographic Encryption & Model Persistence:
    • Inside
      TenantSerializer.create()
      , calls
      config.set_value(wa_access_token)
      .
    • TenantConfig.set_value()
      encrypts plaintext access token using
      Fernet(settings.FERNET_KEY)
      .
    • Executes SQL
      INSERT
      inside atomic transaction (
      transaction.atomic()
      ).

Phase D: Response Serialization

  1. DTO Construction: Serializer maps model attributes to JSON representation (omitting sensitive decrypted values).
  2. HTTP Output Dispatch: Returns
    Response(data, status=status.HTTP_201_CREATED)
    back through middleware stack to client.

2. WebSocket Request & Connection Lifecycle

Rendering diagram...

Detailed Pipeline Traversal Breakdown

  1. Protocol Protocol Routing:
    core/asgi.py
    routes
    websocket
    connections through
    ProtocolTypeRouter
    to
    URLRouter
    .
  2. Channel Group Registration:
    InboxConsumer.connect()
    extracts
    tenant_id
    from URL keyword arguments, verifies agent membership, and calls
    async_to_sync(self.channel_layer.group_add)(f"inbox_{tenant_id}", self.channel_name)
    .
  3. Redis Subscription: The connection is registered under Redis Pub/Sub channel
    inbox_<tenant_id>
    in Redis DB 1.
  4. 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.
    • InboxConsumer
      encodes payload as JSON string and pushes frame over WebSocket connection.