# Architecture Document
Generated: Tuesday, September 16, 2025

## System Overview
The Angular Clarity Boilerplate is a frontend-only, single-page application (SPA) template. It is designed to serve as a foundational starting point for developing enterprise-grade web applications. The system provides a pre-configured, modular, and scalable architecture using the Angular framework and is visually styled with the VMware Clarity Design System. Its primary purpose is to accelerate development by providing a structured and feature-rich starting point.

## Architecture Pattern
The boilerplate is built upon a **Component-Based Architecture**, which is fundamental to the Angular framework. The UI is composed of a tree of reusable and encapsulated components.

The overall architectural pattern follows best practices for scalable Angular applications, emphasizing a **Modular Design**. The application is segregated into a `CoreModule`, a `SharedModule`, and is designed for the addition of multiple `FeatureModules`. This structure promotes separation of concerns, reusability, and maintainability.

## Component Design (Frontend)

- **AppModule:** The root module of the application, responsible for bootstrapping the `AppComponent` and importing essential modules like the `CoreModule` and `AppRoutingModule`.

- **AppComponent:** The main application shell component. It contains the primary layout, including the Clarity header, sidebar navigation, and the main content area where routed components are displayed via `<router-outlet>`.

- **CoreModule:** This module is designed to be imported only once by the `AppModule`. It contains singleton services, route guards, and other one-time setup logic (e.g., HTTP interceptors). This pattern prevents services from being provided multiple times across the application.

- **SharedModule:** This module contains commonly used components, directives, and pipes that can be reused across different feature modules. It is imported by feature modules whenever they need access to these shared elements. It primarily exports common Angular modules (like `CommonModule`, `FormsModule`) and Clarity UI modules.

- **Feature Modules (Conceptual):** The architecture is designed for developers to create new feature modules (e.g., `DashboardModule`, `AdminModule`). These modules encapsulate all the components, services, and routing related to a specific business domain. They are typically **lazy-loaded** to improve initial application load performance.

## Data Architecture

### Primary Database
- Not applicable. As a frontend-only boilerplate, this project does not include a database. It is designed to connect to any backend with a data persistence layer.

### Data Model (Client-Side)
- Data models will be defined using **TypeScript interfaces or classes** within feature modules. These models will represent the structure of data objects retrieved from or sent to the backend API.
- **Example `User` model:**
  ```typescript
  export interface User {
    id: number;
    name: string;
    email: string;
    role: 'admin' | 'user';
  }

  Of course. Here is the architecture_document.md for the Angular Clarity boilerplate project, presented in a single code block for easy copying.

Markdown

# Architecture Document
Generated: Tuesday, September 16, 2025

## System Overview
The Angular Clarity Boilerplate is a frontend-only, single-page application (SPA) template. It is designed to serve as a foundational starting point for developing enterprise-grade web applications. The system provides a pre-configured, modular, and scalable architecture using the Angular framework and is visually styled with the VMware Clarity Design System. Its primary purpose is to accelerate development by providing a structured and feature-rich starting point.

## Architecture Pattern
The boilerplate is built upon a **Component-Based Architecture**, which is fundamental to the Angular framework. The UI is composed of a tree of reusable and encapsulated components.

The overall architectural pattern follows best practices for scalable Angular applications, emphasizing a **Modular Design**. The application is segregated into a `CoreModule`, a `SharedModule`, and is designed for the addition of multiple `FeatureModules`. This structure promotes separation of concerns, reusability, and maintainability.

## Component Design (Frontend)

- **AppModule:** The root module of the application, responsible for bootstrapping the `AppComponent` and importing essential modules like the `CoreModule` and `AppRoutingModule`.

- **AppComponent:** The main application shell component. It contains the primary layout, including the Clarity header, sidebar navigation, and the main content area where routed components are displayed via `<router-outlet>`.

- **CoreModule:** This module is designed to be imported only once by the `AppModule`. It contains singleton services, route guards, and other one-time setup logic (e.g., HTTP interceptors). This pattern prevents services from being provided multiple times across the application.

- **SharedModule:** This module contains commonly used components, directives, and pipes that can be reused across different feature modules. It is imported by feature modules whenever they need access to these shared elements. It primarily exports common Angular modules (like `CommonModule`, `FormsModule`) and Clarity UI modules.

- **Feature Modules (Conceptual):** The architecture is designed for developers to create new feature modules (e.g., `DashboardModule`, `AdminModule`). These modules encapsulate all the components, services, and routing related to a specific business domain. They are typically **lazy-loaded** to improve initial application load performance.

## Data Architecture

### Primary Database
- Not applicable. As a frontend-only boilerplate, this project does not include a database. It is designed to connect to any backend with a data persistence layer.

### Data Model (Client-Side)
- Data models will be defined using **TypeScript interfaces or classes** within feature modules. These models will represent the structure of data objects retrieved from or sent to the backend API.
- **Example `User` model:**
  ```typescript
  export interface User {
    id: number;
    name: string;
    email: string;
    role: 'admin' | 'user';
  }
Data Flow
API Call: A component's method calls a function in its corresponding service (e.g., userService.getUsers()).

Service Layer: The service uses Angular's HttpClient to make an HTTP request to the backend API.

Data Retrieval: The service receives the HTTP response and typically returns an Observable of the data, typed with the appropriate TypeScript interface.

Component Update: The component subscribes to the Observable. Once the data is received, it updates its local state, triggering Angular's change detection to re-render the template and display the new data.

API Design (Backend Communication)
This boilerplate is backend-agnostic. It is designed to communicate with any backend that exposes a RESTful or GraphQL API.

Communication Protocol
HTTP/HTTPS: Communication is handled via standard HTTP requests using Angular's HttpClient service.

Example Service Implementation
An example of a service making API calls:
// in user.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from '../models/user.model';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private apiUrl = `${environment.apiBaseUrl}/users`;

  constructor(private http: HttpClient) { }

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(this.apiUrl);
  }

  getUserById(id: number): Observable<User> {
    return this.http.get<User>(`${this.apiUrl}/${id}`);
  }
}

Error Handling
HTTP interceptors can be provided in the CoreModule to handle API errors globally (e.g., logging errors, redirecting on 401 Unauthorized responses).

Security Architecture
Authentication: Authentication logic (e.g., handling JWTs, interacting with OAuth providers) should be encapsulated within an AuthService provided in the CoreModule.

Authorization (Route Guards): The architecture uses Angular's Route Guards to protect routes. An AuthGuard can be implemented to prevent unauthorized users from accessing certain parts of the application.

Client-Side Security: The boilerplate does not inherently protect against all client-side vulnerabilities. Developers should follow best practices for preventing XSS and CSRF attacks.

Scalability Considerations
Lazy Loading: The architecture strongly encourages the use of lazy-loaded feature modules. This ensures that the initial application bundle size remains small, leading to faster load times. As new features are added, they do not impact the initial load performance.

Modular Design: The strict separation of concerns into Core, Shared, and Feature modules makes the codebase easier to manage, test, and scale as the application grows in complexity.

State Management: For applications with complex state, a state management library like NgRx or Akita can be easily integrated into this architecture without requiring significant refactoring.

---

## ARCHITECTURE UPDATE - 2025-10-10 04:19:30


# Architecture Document
Generated: 2025-10-10T04:04:10.080488

## System Overview - 2025-10-10T04:04:10.080488
The Messaging App will operate as a distributed system, comprising a single-page application (SPA) frontend and a set of backend microservices. The frontend, built on the existing Angular Clarity boilerplate, will provide the user interface and interact with the backend services through both RESTful APIs for data management (e.g., user profiles, message history) and WebSocket connections for real-time communication (e.g., instant message delivery, user presence updates). The backend will handle user authentication, user management, real-time chat logic, message persistence, and potential future features like group chats and media sharing. This architecture ensures high availability, scalability, and responsiveness essential for a modern messaging platform, as per `analysis_document.md` and `requirements_document.md`.

## Architecture Pattern - 2025-10-10T04:04:10.080488

**Frontend:** The frontend will maintain its **Single-Page Application (SPA)** pattern using Angular and the Clarity Design System. It will consume data and real-time events from the backend.

**Backend:** A **Microservices Architecture** pattern will be adopted for the backend to address the scalability and modularity requirements of a real-time messaging application (`NFR-006`). This allows different functionalities (authentication, chat, user management) to be developed, deployed, and scaled independently. An **Event-Driven Architecture** will complement the microservices, leveraging a message broker for asynchronous communication between services and handling high-throughput real-time events. A dedicated **WebSocket Gateway** will abstract real-time complexity and provide a unified entry point for persistent client connections.

**Justification:**
-   **Scalability:** Microservices allow individual components, such as the Chat Service or WebSocket Gateway, to be scaled independently based on load, which is critical for handling a growing number of concurrent users and messages (`NFR-002`).
-   **Resilience:** Failure in one service (e.g., User Profile) does not necessarily bring down the entire messaging system.
-   **Maintainability:** Clear separation of concerns makes the codebase easier to understand, develop, and test.
-   **Real-time Capabilities:** The WebSocket Gateway and event-driven communication are specifically designed for low-latency message delivery (`NFR-001`).

## Component Design - 2025-10-10T04:04:10.080488

The system will consist of the following key components:

### Frontend (Angular Clarity SPA)
-   **Purpose:** User Interface, user interaction, data display, and real-time event handling.
-   **Modules:** Extends the existing `CoreModule`, `SharedModule`, and introduces feature modules for `Auth`, `Chat`, `User Profile`, etc., as per the base boilerplate's modularity (`FR-002` from base `requirements_document.md`).
-   **Communication:** Utilizes Angular `HttpClient` for REST API calls and a custom WebSocket service for real-time data exchange.

### Backend Microservices
1.  **API Gateway:**
    -   **Purpose:** Single entry point for all client REST requests. Routes requests to appropriate backend services, handles authentication token validation (`NFR-003`).
    -   **Responsibilities:** Request routing, load balancing, SSL termination (`NFR-005`).
2.  **Authentication Service:**
    -   **Purpose:** Handles user registration, login, token generation (JWT), and token validation (`FR-001`, `FR-002`).
    -   **Responsibilities:** Stores user credentials securely, issues and validates JWTs (`NFR-003`).
3.  **User Service:**
    -   **Purpose:** Manages user profiles, user search, and presence status (`FR-003`, `FR-004`, `FR-005`).
    -   **Responsibilities:** Stores user details, updates online/offline status, publishes status changes to the WebSocket Gateway/Message Broker.
4.  **Chat Service:**
    -   **Purpose:** Manages conversations (1:1 and group), message persistence, and message retrieval (`FR-006`, `FR-008`, `FR-010`, `FR-014`, `NFR-008`).
    -   **Responsibilities:** Stores message content, conversation metadata, and participant information. Handles message history pagination.
5.  **WebSocket Gateway:**
    -   **Purpose:** Manages persistent WebSocket connections with clients. Routes real-time messages and events to/from clients and the Chat/User/Notification services (`FR-009`).
    -   **Responsibilities:** Handles WebSocket handshake, connection management, user presence tracking, message broadcasting, and pushing notifications.
6.  **Notification Service (Future):**
    -   **Purpose:** Generates and delivers real-time notifications for new messages or events (`FR-015`, `FR-016`).
    -   **Responsibilities:** Subscribes to message broker events and pushes notifications via WebSocket Gateway or other channels.
7.  **File Storage Service (Future):**
    -   **Purpose:** Handles secure upload, storage, and retrieval of media files shared in chats (`FR-017`, `FR-018`).
    -   **Responsibilities:** Integrates with an object storage solution (e.g., S3-compatible).

### Infrastructure Components
-   **Database:** Primary data store for users, conversations, and messages.
-   **Cache/Real-time Store:** In-memory data store for user presence, session data, and pub/sub capabilities.
-   **Message Broker:** Facilitates asynchronous, reliable communication between backend services (e.g., message persistence acknowledgements, notification triggers, presence updates).

## Data Architecture - 2025-10-10T04:04:10.080488

### Database Design
Based on `requirements_document.md` Data Requirements:
-   **Primary Database:** A relational database (e.g., PostgreSQL) will store structured data for users, conversations, participants, and messages. This choice provides strong consistency, ACID properties, and flexibility for complex queries needed for chat history and user management.
    -   **User Table:** `id`, `username`, `email`, `password_hash`, `profile_picture_url`, `status`, `created_at`, `updated_at`.
    -   **Conversation Table:** `id`, `type` (one_to_one/group), `name` (for group), `created_at`, `updated_at`.
    -   **ConversationParticipant Table (Join Table):** `conversation_id`, `user_id`, `role` (member/admin), `joined_at`, `last_read_message_id`, `is_active`.
    -   **Message Table:** `id`, `conversation_id`, `sender_id`, `content`, `type`, `attachment_url`, `sent_at`, `edited_at`, `deleted_at`.

### Data Flow
1.  **User Authentication:** Frontend sends login credentials to API Gateway -> Authentication Service -> verifies against database. Returns JWT to frontend.
2.  **User/Conversation Management (REST):** Frontend sends HTTP requests (e.g., `GET /api/users/me`, `POST /api/conversations`) to API Gateway -> routed to User Service or Chat Service -> interacts with Primary Database. Responses returned to frontend.
3.  **Sending Real-time Messages (WebSocket):** Frontend sends `send_message` event via WebSocket Gateway -> Chat Service receives event -> persists message in Primary Database -> Chat Service publishes `new_message` event to Message Broker -> WebSocket Gateway subscribes to Message Broker and broadcasts `new_message` to relevant clients (`FR-009`).
4.  **Receiving Real-time Messages (WebSocket):** WebSocket Gateway receives `new_message` event from Message Broker -> pushes to subscribed clients.
5.  **Presence Updates (WebSocket/Cache):** User Service updates `status` in Primary Database and `Cache/Real-time Store`. User Service or WebSocket Gateway publishes `user_status_update` event to Message Broker for broadcasting.
6.  **Media Sharing (Future):** Frontend uploads file to File Storage Service (via API Gateway) -> File Storage Service saves to Object Storage and returns `attachment_url` -> `send_message` event then includes this URL.

## API Design - 2025-10-10T04:04:10.080488

Based on `requirements_document.md` Interface Requirements:

### RESTful API (HTTP/HTTPS)
-   **Base URL:** `/api/v1`
-   **Authentication Endpoints (`/api/v1/auth`):**
    -   `POST /register`: User registration (`FR-001`).
    -   `POST /login`: User login, returns JWT (`FR-002`).
-   **User Endpoints (`/api/v1/users`):**
    -   `GET /me`: Retrieve current user profile (`FR-003`).
    -   `PUT /me`: Update current user profile (`FR-003`).
    -   `GET /search?query=...`: Search for users (`FR-005`).
    -   `GET /{userId}/status`: Get specific user's online status (or included in user profile).
-   **Conversation Endpoints (`/api/v1/conversations`):**
    -   `GET /`: Retrieve list of user's conversations (`FR-008` for list context).
    -   `POST /one-to-one`: Create a 1:1 conversation (`FR-006` context).
    -   `POST /group`: Create a group conversation (`FR-010`).
    -   `GET /{conversationId}/messages?limit=...&offset=...`: Retrieve paginated messages for a conversation (`FR-008`, `FR-014`).
    -   `POST /{conversationId}/members`: Add members to a group chat (Admin only, `FR-011`).
    -   `DELETE /{conversationId}/members/{userId}`: Remove member from group chat (Admin only, `FR-011`).

### WebSocket API (WSS)
-   **Endpoint:** `wss://api.yourdomain.com/ws/chat`
-   **Authentication:** JWT token sent in WebSocket handshake (e.g., as a query parameter or header).
-   **Client to Server Events:**
    -   `send_message`: `{ conversationId: UUID, content: string, type: 'text'|'image'|'file', attachmentUrl?: string }` (`FR-006`, `FR-012`, `FR-017`).
    -   `user_typing`: `{ conversationId: UUID }` (for typing indicators).
    -   `read_message`: `{ messageId: UUID, conversationId: UUID }` (for read receipts).
    -   `update_status`: `{ status: 'online'|'offline'|'away' }` (`FR-004`).
-   **Server to Client Events:**
    -   `new_message`: `{ messageId: UUID, conversationId: UUID, senderId: UUID, content: string, type: 'text'|'image'|'file', attachmentUrl?: string, sentAt: Timestamp }` (`FR-007`, `FR-013`).
    -   `user_status_update`: `{ userId: UUID, status: 'online'|'offline'|'away' }` (`FR-004`, `FR-016`).
    -   `typing_indicator`: `{ userId: UUID, conversationId: UUID }`.
    -   `notification`: `{ type: 'new_message'|'user_online', data: {...} }` (`FR-015`, `FR-016`).
    -   `conversation_update`: `{ conversationId: UUID, type: 'member_added'|'member_removed'|'group_renamed', data: {...} }` (`FR-011`).

## Security Architecture - 2025-10-10T04:04:10.080488

-   **Authentication (NFR-003):**
    -   **JWT-based:** Users authenticate via the REST API, receiving a JSON Web Token (JWT). This token will be sent with subsequent HTTP requests (in `Authorization` header as `Bearer Token`) and for WebSocket connection (`WSS`).
    -   **Token Expiration & Refresh:** JWTs will have short expiration times, and a refresh token mechanism will be implemented to securely obtain new access tokens without re-authenticating repeatedly.
-   **Authorization (NFR-004):**
    -   **Role-Based Access Control (RBAC):** Backend services will implement RBAC to ensure users only access resources and perform actions for which they have explicit permissions (e.g., `member` vs. `admin` in group chats, access to own messages).
    -   **Resource Ownership Checks:** All API requests and WebSocket events will include checks to verify that the requesting user has rights to the specific `conversationId` or `userId` resource.
-   **Data Encryption (NFR-005):**
    -   **TLS/SSL (HTTPS/WSS):** All communication between frontend and backend services (both REST and WebSocket) will be encrypted using TLS/SSL to protect data in transit.
    -   **Password Hashing:** User passwords will be stored as securely hashed values (e.g., using bcrypt) in the database, never in plain text.
-   **Input Validation (NFR-006 from base `requirements_document.md`):** All user inputs on both frontend and backend (API layer) will be strictly validated to prevent common vulnerabilities like SQL injection, XSS, and buffer overflows.
-   **Rate Limiting:** Implement API rate limiting to prevent abuse and brute-force attacks on authentication endpoints.
-   **CORS:** Properly configure Cross-Origin Resource Sharing (CORS) policies to allow requests only from trusted frontend origins.

## Scalability Considerations - 2025-10-10T04:04:10.080488

-   **Horizontal Scaling (NFR-006):**
    -   **Stateless Services:** All backend microservices (Auth, User, Chat) will be designed to be stateless. This allows them to be scaled horizontally by adding more instances behind a load balancer, distributing the load effectively and supporting `NFR-002` (Concurrent Users).
    -   **WebSocket Gateway:** The WebSocket Gateway will also be horizontally scalable. Solutions like Redis Pub/Sub or a dedicated WebSocket scaling layer will be used to ensure messages are routed to the correct client, regardless of which gateway instance they are connected to.
-   **Database Scalability:**
    -   **PostgreSQL:** Will be configured for high availability with master-replica (read-only) setups to distribute read load. Sharding or partitioning strategies can be explored for extreme data volumes in the future. Connection pooling will optimize database access.
    -   **Redis:** Crucial for real-time data like user presence. Redis cluster mode will be used to scale Redis horizontally and ensure high availability.
-   **Message Broker:** A robust message broker (e.g., RabbitMQ, Kafka) will handle high message throughput and asynchronous processing, decoupling services and buffering spikes in traffic, essential for `NFR-001` (Message Latency).
-   **Caching:** Extensive caching (e.g., Redis) will be implemented for frequently accessed, less volatile data (e.g., user profiles, conversation metadata) to reduce database load and improve response times.
-   **Load Balancing:** An Nginx-based reverse proxy or cloud provider's load balancer will distribute incoming HTTP and WebSocket traffic across multiple instances of backend services and WebSocket Gateways.



---

## ARCHITECTURE UPDATE - 2025-10-10 04:20:49


# Architecture Document Update: Messaging App
Generated: 2025-10-10T[timestamp]

## System Overview
The Messaging App extends the existing Angular Clarity Boilerplate frontend with a new, dedicated backend. The architecture is a **Client-Server model** with a robust **Real-time Communication Layer**. The Angular frontend provides the user interface for authentication, user management, and interactive chat. The backend, composed of several specialized services, handles business logic, data persistence, and real-time message exchange via WebSockets. This separation ensures scalability, maintainability, and allows independent evolution of frontend and backend components. The system prioritizes low-latency message delivery, secure communication, and horizontal scalability to accommodate a growing user base, as derived from `analysis_document.md` and `requirements_document.md`.

## Architecture Pattern
The core architecture pattern for the Messaging App is a **Hybrid Client-Server / Layered Architecture** with a strong emphasis on a **Publish-Subscribe (Pub/Sub) pattern** for real-time messaging:

1.  **Client-Server:** The Angular frontend acts as the client, communicating with the backend API servers.
2.  **Layered Backend:** The backend is designed with distinct layers:
    *   **Presentation/API Gateway:** Handles incoming HTTP/WebSocket requests, routing, and potentially authentication pre-checks.
    *   **Application Services:** Implements core business logic for user management, conversations, and messages.
    *   **Real-time Communication Layer:** Dedicated WebSocket server(s) manage persistent connections and message broadcasting.
    *   **Data Access Layer:** Interfaces with the database for CRUD operations.
3.  **Publish-Subscribe (for Real-time):** A message broker (e.g., Redis Pub/Sub) will be used to facilitate real-time message exchange between backend services (e.g., a message service publishing new messages, and multiple WebSocket servers subscribing to these messages to fan-out to connected clients). This pattern is crucial for horizontal scaling of WebSocket servers, addressing NFR-003 (Scalability) from `requirements_document.md`.

## Component Design
The system is composed of the following key components, aligning with `analysis_document.md`'s architectural components and `requirements_document.md`'s data and interface requirements:

### 1. Frontend (Angular Clarity Application)
*   **Purpose:** User interface for interaction, leveraging the existing Angular Clarity boilerplate.
*   **Modules:**
    *   `AuthModule`: Handles user registration, login, and session management (communicates with Backend Auth Service).
    *   `UserModule`: Manages user profiles, search, and presence display (communicates with Backend User Service).
    *   `ChatModule`: Core messaging functionality, including conversation list, chat window, message input, and real-time message display. (Communicates with Backend Conversation, Message, and WebSocket Services).
    *   `CoreModule` & `SharedModule`: As per boilerplate, for singleton services (e.g., HTTP interceptors, WebSocket client) and reusable UI components.
*   **Key Features:** Responsive UI (NFR-007), Real-time message rendering, User presence display.

### 2. Backend Services
Designed as a set of loosely coupled services, potentially evolving into microservices, to manage core functionalities.

*   **2.1. Authentication Service (REST API):**
    *   **Purpose:** Manages user authentication and authorization (FR-001, FR-002, NFR-003, NFR-004).
    *   **Responsibilities:** User registration, login, JWT token issuance, validation, and refresh. Password hashing.
    *   **Interaction:** Exposes REST endpoints (`POST /api/auth/register`, `POST /api/auth/login`) as per `requirements_document.md`.

*   **2.2. User Service (REST API):**
    *   **Purpose:** Manages user profiles and provides user search capabilities (FR-003, FR-005).
    *   **Responsibilities:** Store and retrieve user profile information, handle profile updates, provide search functionality for other users.
    *   **Interaction:** Exposes REST endpoints (`GET /api/users/me`, `PUT /api/users/me`, `GET /api/users/search`).

*   **2.3. Conversation Service (REST API):**
    *   **Purpose:** Manages the creation and retrieval of 1:1 and group conversations (FR-009).
    *   **Responsibilities:** Create new conversations, manage participants (FR-010), retrieve lists of conversations a user is part of.
    *   **Interaction:** Exposes REST endpoints (`GET /api/conversations`, `POST /api/conversations/one-to-one`, `POST /api/conversations/group`).

*   **2.4. Message Service (Internal & REST API):**
    *   **Purpose:** Persists messages and retrieves chat history (FR-008).
    *   **Responsibilities:** Store incoming messages from the WebSocket Service, retrieve paginated message history for conversations.
    *   **Interaction:** Exposes REST endpoint (`GET /api/conversations/{id}/messages`) for history, and an internal API for the WebSocket Service to persist new messages.

*   **2.5. Real-time WebSocket Service:**
    *   **Purpose:** Manages persistent WebSocket connections, handles real-time message delivery, and user presence updates (FR-006, FR-007, FR-009, NFR-001, NFR-007).
    *   **Responsibilities:** Authenticate WebSocket connections using JWT, receive messages from clients, persist them via Message Service, broadcast messages to relevant recipients, manage user online/offline status, propagate status updates via Redis Pub/Sub.
    *   **Interaction:** Exposes a WSS endpoint (`wss://api.yourdomain.com/ws/chat`), integrates with Redis for Pub/Sub and presence, and with Message Service for persistence.

### 3. Database
*   **Purpose:** Persistent storage for all application data, adhering to `requirements_document.md`'s Data Requirements.
*   **Key Entities:** `User`, `Conversation`, `ConversationParticipant`, `Message` (as defined in `requirements_document.md`).
*   **Relationships:** One-to-many and many-to-many relationships modeled for users, conversations, and messages.

### 4. Caching / Message Broker (Redis)
*   **Purpose:** Enhances real-time performance, manages presence, and facilitates inter-service communication for WebSockets.
*   **Responsibilities:** Store user presence status (online/offline), act as a Pub/Sub broker for real-time message distribution across multiple WebSocket service instances, potentially caching frequently accessed data (e.g., user profiles).

### 5. Object Storage (e.g., AWS S3 - for Phase 2 Media Sharing)
*   **Purpose:** Store media files (images, documents) for sharing (FR-017, FR-018).
*   **Responsibilities:** Provides scalable and secure storage for user-uploaded content. The Message Service will store references (URLs) to these objects.

## Data Flow

1.  **User Authentication & Profile Management:**
    *   Frontend (Angular) sends `POST /api/auth/register` or `POST /api/auth/login` to Backend Auth Service.
    *   Auth Service interacts with Database to create/verify user credentials. Issues JWT.
    *   Frontend uses JWT for subsequent requests to Backend User Service (e.g., `GET /api/users/me`, `PUT /api/users/me`), which then interacts with Database.

2.  **Real-time Messaging (1:1 & Group Chat):**
    *   After authentication, Frontend (Angular) establishes a secure WebSocket connection (`wss://api.yourdomain.com/ws/chat`) to the Backend WebSocket Service, providing JWT for authorization.
    *   **Sending a Message:** Frontend sends `send_message` event over WebSocket to Backend WebSocket Service. WebSocket Service persists message via Message Service (to Database). WebSocket Service then publishes the new message to a Redis Pub/Sub channel.
    *   **Receiving a Message:** Other instances of Backend WebSocket Service (subscribed to Redis Pub/Sub) receive the published message. They identify relevant connected clients and fan out the `new_message` event over their respective WebSockets to the recipients' Frontends.
    *   **Message History:** Frontend retrieves older messages via `GET /api/conversations/{id}/messages` from Backend Message Service (REST API), which queries the Database.

3.  **User Presence:**
    *   Frontend sends `user_online`/`user_offline` events (or inferred from WebSocket connection status) to Backend WebSocket Service.
    *   WebSocket Service updates user status in Redis (for fast retrieval across instances) and potentially Database.
    *   Status changes are published via Redis Pub/Sub to inform other connected users.

## API Design
As detailed in `requirements_document.md` (Interface Requirements):

*   **RESTful API:** For stateless operations such as user registration, login, profile management, and fetching historical data (user lists, chat history).
    *   Endpoints like `/api/auth/register`, `/api/auth/login`, `/api/users/me`, `/api/conversations`, `/api/conversations/{id}/messages` will be implemented.
    *   Communication will be JSON over HTTPS.
*   **WebSocket API:** For real-time, bidirectional communication.
    *   A single `wss://api.yourdomain.com/ws/chat` endpoint will be used.
    *   Events like `send_message`, `new_message`, `user_status_update`, `typing_indicator` will be exchanged.
    *   Payloads will be JSON.

## Security Architecture
Addressing NFR-002 (Security) from `requirements_document.md`:

*   **Authentication:**
    *   **JWT (JSON Web Tokens):** Used for authenticating REST API requests and authorizing WebSocket connections. Tokens will have short lifespans with a refresh token mechanism.
    *   **Password Hashing:** User passwords will be hashed and salted using strong, industry-standard algorithms (e.g., bcrypt) before storage in the database.
*   **Authorization:**
    *   **Role-Based Access Control (RBAC):** Implemented at the backend for sensitive actions (e.g., group administration (FR-011), accessing message history (NFR-004)).
    *   **Scope-Based Authorization:** JWTs will contain claims to define the scope of a user's access.
*   **Data Encryption:**
    *   **In-transit:** All HTTP and WebSocket communication will be encrypted using **TLS/SSL (HTTPS/WSS)** (NFR-005).
    *   **At-rest:** Database encryption and secure storage practices will be applied, especially for media files (if applicable, using encrypted storage services).
*   **Input Validation:** Comprehensive input validation will be implemented on all backend API endpoints to prevent common vulnerabilities such as XSS, SQL injection, and buffer overflows (NFR-002).
*   **Session Management:** Secure session management for JWTs, including proper storage (e.g., HttpOnly cookies) and invalidation on logout.

## Scalability Considerations
Addressing NFR-003 (Scalability) from `requirements_document.md`:

*   **Horizontal Scaling:**
    *   **Stateless Services:** Backend API services will be designed as stateless entities, allowing them to be horizontally scaled by adding more instances behind a load balancer.
    *   **WebSocket Service Scaling:** Multiple instances of the WebSocket Service can run concurrently. Redis Pub/Sub acts as a backbone to distribute messages across these instances, ensuring all clients receive messages regardless of which WebSocket server they are connected to.
*   **Load Balancing:** A load balancer (e.g., Nginx, or cloud-native solutions) will distribute incoming HTTP and WebSocket traffic across multiple backend service instances.
*   **Database Scalability:**
    *   **Read Replicas:** PostgreSQL can be configured with read replicas to offload read-heavy operations (e.g., fetching chat history) from the primary database instance.
    *   **Connection Pooling:** Efficient database connection pooling will be used by backend services to manage database load.
    *   **Sharding (Future):** For extremely high message volumes, message data might be sharded across multiple database instances based on conversation ID or user ID.
*   **Caching:** Redis will be used for caching frequently accessed data (e.g., user profiles, online status) to reduce database load and improve response times.
*   **Asynchronous Processing:** Backend operations, especially for media sharing (Phase 2), will leverage asynchronous processing to avoid blocking the main request/response cycle, potentially using background task queues (e.g., Celery with Redis).



---

## ARCHITECTURE UPDATE - 2025-10-10 04:21:29



# Architecture Document Update
Generated: 2025-10-10T04:20:00.000000

## Data Architecture Refinement
Building upon the initial data architecture, a deeper dive into indexing and read strategies is essential to meet performance requirements (NFR-001) and efficient message history retrieval (FR-007):

*   **Message Indexing:** For the `Message` entity, robust indexing will be critical. Indices will be created on `conversation_id`, `sender_id`, and `sent_at` to facilitate rapid querying of messages within a conversation, retrieving messages by a specific sender, and efficient chronological sorting for chat history. A compound index on `(conversation_id, sent_at)` will be highly beneficial for paginated history retrieval, addressing `FR-008` (View Message History) and `FR-014` (View Group Message History).
*   **User/Conversation Lookups:** Indices on `User.username` and `User.email` will speed up login and user search operations (FR-001, FR-002, FR-005). For `ConversationParticipant`, indexes on `(user_id, conversation_id)` and `(conversation_id, user_id)` will optimize fetching all conversations for a user and all participants for a conversation.
*   **Read Status Tracking:** The `ConversationParticipant.last_read_message_id` will be actively updated by the frontend via the WebSocket Service whenever a user views a conversation, providing real-time read receipts (an implicit feature derived from data model, enhancing user experience).
*   **Database Partitioning (Future consideration):** For extreme scale and very high message volumes, tables like `Message` could be considered for partitioning by `conversation_id` or `sent_at` range to distribute load and improve query performance, directly supporting NFR-006 (Scalability).

## Message Queuing and Offline Delivery Strategy
While Redis Pub/Sub efficiently handles real-time message fan-out, a more robust strategy is needed for guaranteed message delivery, especially for offline users, addressing NFR-005 (Reliability).

*   **Redis Streams/Lists for Offline Messages:** Instead of solely relying on Pub/Sub, the WebSocket Service will leverage Redis Streams or Lists to temporarily store messages for users who are currently offline or disconnected. When a user reconnects, the WebSocket Service will first check for any pending messages in their dedicated Redis queue/stream before subscribing them to real-time updates. This ensures messages are delivered even if the recipient was not connected at the time of sending.
*   **Background Processing Queue (Future for Phase 2):** For computationally intensive tasks, particularly related to Phase 2 features like media processing (FR-017, FR-018) or complex notification logic, a dedicated background task queue (e.g., using Celery with Redis as a broker) could be introduced. This would decouple the main request/response flow, improving responsiveness and system resilience.

## Deployment and Operational Architecture
To ensure the system meets its Non-Functional Requirements, especially NFR-005 (Reliability), NFR-006 (Maintainability), and NFR-003 (Scalability), a robust deployment and operational strategy is critical.

*   **Container Orchestration:** Leveraging Docker Compose for local development and potentially Kubernetes (or AWS ECS/Fargate) for production ensures consistent environments and simplifies scaling. Backend services will be deployed as separate containers, managed by the orchestrator.
*   **Monitoring and Alerting:** Comprehensive monitoring will be implemented across all layers. Metrics (CPU, memory, network I/O, message delivery latency, API response times) will be collected from frontend (e.g., web vitals), backend services, databases, and the Redis instance. Alerts will be configured for critical thresholds and errors to ensure proactive issue resolution.
*   **Centralized Logging:** All application logs (frontend, backend, Nginx) will be aggregated into a centralized logging system (e.g., an ELK stack or Grafana Loki). This enables easy debugging, auditing, and performance analysis, crucial for maintaining system health (NFR-006).
*   **Automated Backups:** Regular automated backups of the PostgreSQL database will be implemented to ensure data durability and recovery capabilities.

## Security Architecture Enhancements
To further reinforce NFR-002 (Security), additional considerations will be implemented:

*   **Rate Limiting:** Implement rate limiting on authentication and registration endpoints at the Nginx level and within FastAPI to prevent brute-force attacks and abuse.
*   **Content Security Policy (CSP):** Configure a strict Content Security Policy for the Angular frontend to mitigate XSS attacks.
*   **Environment Variable Management:** Securely manage sensitive configurations (database credentials, API keys, JWT secrets) using environment variables or a secrets management service (e.g., AWS Secrets Manager, HashiCorp Vault) in production.
*   **Regular Security Audits:** Conduct periodic security audits and vulnerability assessments to identify and remediate potential weaknesses.

