# agri-mitra/bff architecture

> Architecture diagram of the GitHub repository agri-mitra/bff, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-04-22). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/agri-mitra/bff
- Repository: https://github.com/agri-mitra/bff

## Overview

##### Project type and purpose
- This is a Backend‑For‑Frontend (BFF) built with NestJS. It exposes a unified API for frontend apps, orchestrating calls to language services (translation, ASR, TTS) and domain APIs (PM Kisan Aadhaar status, OTP).
- It uses Prisma for database access, XState for flow control of conversations, and provides telemetry/metrics and logging.

##### File structure
- Top‑level NestJS project layout under src/ with module directories: aiTools, conversation, health, monitoring, metrics, user, plus a global‐services folder for Prisma.
- A src/xstate/prompt subfolder defining state‑machine logic in prompt.machine.ts, actions, guards, utils.
- prisma/ folder holds migrations and schema.prisma, implying a relational DB.
- Dockerfile and docker‑compose.*.yaml for local, CI, production.
- Tests under test/ and *.spec.ts files.
- Config files for linting, CI workflows, TypeScript, GitHub actions.

##### README insights
- Describes key features: API orchestration, XState flows, telemetry for metrics (consumable by Grafana), comprehensive logging.
- Mentions Hasura and database migration with Prisma.
- Supports additional “scheme_name” parameter for chatbot UI.

a. Frontend Application
- Calls BFF via HTTP/REST or GraphQL (if Hasura is in play).
b. BFF (NestJS backend)
- API Gateway / Controllers (conversation.controller, metrics.controller, user.controller, health.controller, monitoring.controller)
- Business Logic / Services (conversation.service, ai-tools.service, metrics.service, monitoring.service, user.service, health.service)
- XState engine (prompt.machine, prompt.service) for conversation flows
- Rate‑limiter guard (rate-limiter.guard.ts)
- Prisma Service (global-services/prisma.service.ts) → RDBMS
- Logging module (NestJS built‑in logger or custom)
- Telemetry/metrics pipeline (metrics.module → expose Prometheus metrics endpoint)
c. Database
- PostgreSQL (or MySQL) managed by Prisma
- Tables for users, messages, metrics, telemetry, feedback
d. External APIs
- Bhashini translation, ASR, TTS endpoints
- PM Kisan Aadhaar/OTP endpoints
- Any other 3rd‑party AI tools or caching layer (cache.provider.ts)
e. Observability
- Prometheus scraping metrics endpoint
- Grafana dashboards
- Logs shipped to ELK or similar

##### Relationships and interactions
- Frontend → BFF Controllers (HTTP requests)
- Controller → Services → External APIs or DB (via Prisma)
- Conversation.Service uses XState engine to drive multi‑step flows, invoking aiTools.service and/or user.service as needed.
- Metrics.Service collects counts/timings; Monitoring.Service monitors health; Health.controller for readiness/liveness.
- Prisma.Service executes SQL on the RDBMS.
- Telemetry endpoint scraped by Prometheus → Grafana visualizes.
- Logs written to console/files and collected by centralized logging system.

##### Architectural patterns and design principles
- Modular Monolith: distinct NestJS modules encapsulate functionality.
- State Machine for flow control (XState).
- Controller‑Service‑Repository pattern (NestJS + Prisma).
- Separation of concerns: orchestration, persistence, external API clients, observability.
- Infrastructure as Code with Docker & docker-compose for dev/CI/prod.

##### Final advice
- Be very detailed: include all modules and data stores.

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% Frontend Layer
    subgraph "Frontend Layer"
        UI["Frontend UI"]:::external
    end

    %% BFF Backend Layer
    subgraph "BFF (NestJS Backend)"
        subgraph "Controllers"
            ConvCtrl["ConversationController"]:::internal
            MetricsCtrl["MetricsController"]:::internal
            UserCtrl["UserController"]:::internal
            HealthCtrl["HealthController"]:::internal
            MonCtrl["MonitoringController"]:::internal
        end
        subgraph "Services & XState Engine"
            ConvSvc["ConversationService"]:::internal
            AiSvc["AiToolsService"]:::internal
            MetricsSvc["MetricsService"]:::internal
            MonSvc["MonitoringService"]:::internal
            UserSvc["UserService"]:::internal
            HealthSvc["HealthService"]:::internal
            subgraph "XState Engine"
                PromptMod["PromptModule"]:::internal
                PromptMach["prompt.machine.ts"]:::internal
                PromptAct["prompt.actions.ts"]:::internal
                PromptGd["prompt.gaurds.ts"]:::internal
                PromptUtil["prompt.utils.ts"]:::internal
                PromptSvc["PromptService"]:::internal
            end
        end
        RateGuard["RateLimiterGuard"]:::internal
        Prisma["PrismaService"]:::internal
        CacheProv["CacheProvider"]:::internal
        TelemetryEP["/metrics Endpoint"]:::internal
        Logger["NestJS Logger"]:::internal
    end

    %% Persistence Layer
    subgraph "Database Layer"
        DB["PostgreSQL (Prisma)"]:::db
    end

    %% External Services
    subgraph "External APIs"
        Bhashini["Bhashini (Translation/ASR/TTS)"]:::external
        PMKisan["PM Kisan API"]:::external
        OTP["OTP Service"]:::external
    end

    %% Observability Layer
    subgraph "Observability"
        Prom["Prometheus"]:::obs
        Graf["Grafana"]:::obs
        Logs["Log Aggregator"]:::obs
    end

    %% Connections
    UI -->|HTTP| ConvCtrl
    UI -->|HTTP| MetricsCtrl
    UI -->|HTTP| UserCtrl
    UI -->|HTTP| HealthCtrl
    UI -->|HTTP| MonCtrl

    ConvCtrl -->|uses| ConvSvc
    MetricsCtrl -->|uses| MetricsSvc
    UserCtrl -->|uses| UserSvc
    HealthCtrl -->|uses| HealthSvc
    MonCtrl -->|uses| MonSvc

    ConvSvc -->|orchestrates| PromptMod
    PromptMod --> PromptMach
    PromptMod --> PromptAct
    PromptMod --> PromptGd
    PromptMod --> PromptUtil
    PromptMod --> PromptSvc

    ConvSvc --> AiSvc
    ConvSvc --> UserSvc
    ConvSvc -->|reads/writes| Prisma
    AiSvc --> Bhashini
    MetricsSvc -->|exports metrics| TelemetryEP
    MonSvc -->|health checks| HealthSvc
    UserSvc -->|reads/writes| Prisma
    HealthSvc -->|reads| Prisma

    Prisma --> DB

    CacheProv -->|cache| ConvSvc
    RateGuard -->|guards| ConvCtrl

    TelemetryEP -->|scrape| Prom
    Prom -->|visualize| Graf
    Logger -->|logs| Logs

    %% Click Events - Controllers
    click ConvCtrl "https://github.com/agri-mitra/bff/blob/main/src/modules/conversation/conversation.controller.ts"
    click MetricsCtrl "https://github.com/agri-mitra/bff/blob/main/src/metrics/metrics.controller.ts"
    click UserCtrl "https://github.com/agri-mitra/bff/blob/main/src/modules/user/user.controller.ts"
    click HealthCtrl "https://github.com/agri-mitra/bff/blob/main/src/modules/health/health.controller.ts"
    click MonCtrl "https://github.com/agri-mitra/bff/blob/main/src/modules/monitoring/monitoring.controller.ts"

    %% Click Events - Services
    click ConvSvc "https://github.com/agri-mitra/bff/blob/main/src/modules/conversation/conversation.service.ts"
    click AiSvc "https://github.com/agri-mitra/bff/blob/main/src/modules/aiTools/ai-tools.service.ts"
    click MetricsSvc "https://github.com/agri-mitra/bff/blob/main/src/metrics/metrics.service.ts"
    click MonSvc "https://github.com/agri-mitra/bff/blob/main/src/modules/monitoring/monitoring.service.ts"
    click UserSvc "https://github.com/agri-mitra/bff/blob/main/src/modules/user/user.service.ts"
    click HealthSvc "https://github.com/agri-mitra/bff/blob/main/src/modules/health/health.service.ts"

    %% Click Events - XState
    click PromptMach "https://github.com/agri-mitra/bff/blob/main/src/xstate/prompt/prompt.machine.ts"
    click PromptAct "https://github.com/agri-mitra/bff/blob/main/src/xstate/prompt/prompt.actions.ts"
    click PromptGd "https://github.com/agri-mitra/bff/blob/main/src/xstate/prompt/prompt.gaurds.ts"
    click PromptUtil "https://github.com/agri-mitra/bff/blob/main/src/xstate/prompt/prompt.utils.ts"
    click PromptMod "https://github.com/agri-mitra/bff/blob/main/src/xstate/prompt/prompt.module.ts"
    click PromptSvc "https://github.com/agri-mitra/bff/blob/main/src/xstate/prompt/prompt.service.ts"

    %% Click Events - Rate Limiter & Persistence
    click RateGuard "https://github.com/agri-mitra/bff/blob/main/src/rate-limiter.guard.ts"
    click Prisma "https://github.com/agri-mitra/bff/blob/main/src/global-services/prisma.service.ts"
    click DB "https://github.com/agri-mitra/bff/blob/main/prisma/schema.prisma"
    click DB "https://github.com/agri-mitra/bff/tree/main/prisma/migrations/*"

    click CacheProv "https://github.com/agri-mitra/bff/blob/main/src/modules/cache/cache.provider.ts"

    %% Click Events - Telemetry
    click TelemetryEP "https://github.com/agri-mitra/bff/blob/main/src/metrics/metrics.module.ts"

    %% Styles
    classDef internal fill:#D6EFFF,stroke:#0366d6,color:#000
    classDef external fill:#FFE0B2,stroke:#e65100,color:#000
    classDef db fill:#C8E6C9,stroke:#2e7d32,color:#000
    classDef obs fill:#E1BEE7,stroke:#6a1b9a,color:#000
```
