SSE - Smart-Cart-System/backend-fastapi GitHub Wiki

Server-Sent Events (SSE) Module Documentation for Frontend

Endpoints

1. Subscribe to SSE Events

  • URL: /sse/{cart_id}
  • Method: GET
  • Description: Establishes a Server-Sent Events connection for real-time cart updates.
  • Path Parameters:
    • cart_id (str): The unique identifier of the cart to monitor.
  • Response:
    • 200 OK: Streaming connection established with text/event-stream media type.
    • Connection Headers:
      Cache-Control: no-cache
      Connection: keep-alive
      X-Accel-Buffering: no
      

SSE Message Schemas

1. SSEMessage

  • Fields:
    • event (str): The type of event that occurred.
    • data (Dict[str, Any]): Event-specific data payload.

2. SSEAuthMessage

  • Fields:
    • session_id (int): The ID of the customer session.
    • token (str): Bearer authentication token.
    • event_type (str): Type of authentication event.

SSE Event Types

Connection Events

  1. Initial Connection
    • Event: connection
    • Message: "Connected {cart_id}"
    • Trigger: When client first connects to SSE endpoint
    • Example:
      {
        "type": "connection",
        "message": "Connected cart_123"
      }
      

Authentication Events

  1. Session Started
    • Event: session-started
    • Trigger: When QR code is successfully scanned and session is created
    • Data: SSEAuthMessage with session details
    • Example:
      {
        "session_id": 456,
        "token": "Bearer eyJ0eXAiOiJKV1QiLCJhbGc...",
        "event_type": "session-started"
      }
      

QR Token to SSE Pipeline Documentation

Complete Flow from QR Generation to SSE Notification

Step 1: QR Code Generation

GET /customer-session/qr/{cart_id}
  • Frontend cart requests QR code for specific cart_id
  • Server generates time-limited JWT token containing cart information
  • QR code is created containing the token
  • QR code displayed on cart screen

Step 2: Mobile App SSE Connection

GET /sse/{cart_id}
  • Frontend establishes SSE connection using the same cart_id
  • Server creates asyncio queue for the cart
  • Initial connection message sent:
    {"type": "connection", "message": "Connected cart_123"}
    

Step 3: QR Code Scanning

POST /customer-session/scan-qr
  • User scans QR code with mobile app
  • Request body contains:
    {
      "token": "scanned_jwt_token_from_qr"
    }
    
  • Server validates JWT token and extracts cart_id
  • New customer session created linking user to cart

Step 4: SSE Authentication Event

  • Immediately after successful QR scan, SSE event is triggered:
    await send_authenticated_message(
        cart_id=new_session.cart_id,
        auth_message=SSEAuthMessage(
            session_id=new_session.session_id,
            token=user_bearer_token,
            event_type="session-started"
        )
    )
    

Frontend Implementation Guide

Establishing SSE Connection

// Connect to SSE endpoint
const cartId = "cart_123";
const eventSource = new EventSource(`/sse/${cartId}`);

// Handle incoming messages
eventSource.onmessage = function(event) {
    const data = JSON.parse(event.data);
    
    switch(data.type || data.event_type) {
        case 'connection':
            console.log('Connected to cart:', data.message);
            break;
            
        case 'session-started':
            // Store session details
            localStorage.setItem('session_id', data.session_id);
            localStorage.setItem('auth_token', data.token);
            // Navigate to shopping interface
            navigateToShopping();
            break;
            
        case 'checkout-completed':
            // Show receipt or success page
            showReceipt(data);
            break;
    }
};

// Handle connection errors
eventSource.onerror = function(event) {
    console.error('SSE connection error:', event);
};

QR Code Scanning Integration

// After scanning QR code
async function processQRScan(qrToken) {
    try {
        const response = await fetch('/customer-session/scan-qr', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${userToken}`
            },
            body: JSON.stringify({ token: qrToken })
        });
        
        // Session creation response
        const sessionData = await response.json();
        
        // SSE will automatically receive session-started event
        // No need to manually handle - SSE listener will trigger
        
    } catch (error) {
        console.error('QR scan failed:', error);
    }
}

Error Handling

Common Scenarios

  1. Invalid QR Token: HTTP 401 - "Invalid or expired QR code"
  2. Connection Lost: SSE onerror event - implement reconnection logic
  3. Session Creation Failed: HTTP 400 - Handle gracefully in QR scan response

Best Practices

  • Implement SSE reconnection logic for network interruptions
  • Store session_id and token from SSE events for subsequent API calls
  • Handle multiple event types in single SSE message handler
  • Close SSE connection when user leaves cart context
  • Validate cart_id matches expected cart before processing events

Security Considerations

  • SSE connection uses cart_id (public identifier)
  • Sensitive data (user tokens, session details) only sent after authentication
  • JWT tokens in QR codes have short expiration times
  • Bearer tokens for API access transmitted securely through SSE