# maharshi0143/algoryn architecture

> Architecture diagram of the GitHub repository maharshi0143/algoryn, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-06-25). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/maharshi0143/algoryn
- Repository: https://github.com/maharshi0143/algoryn

## Overview

1. **What this repository is**
   - This is a single backend service for “DevTrack AI,” a developer analytics platform.
   - It exposes an Express API, connects to PostgreSQL, polls external coding platforms, generates AI-driven reports/insights, and pushes realtime notifications via Socket.IO.

2. **Top-level runtime and startup boundary**
   - The entrypoint is `src/server.js`.
   - Startup sequence is: load env → wait for PostgreSQL → initialize cron jobs → create HTTP server → attach Socket.IO → listen on port → register graceful shutdown.
   - Shutdown stops cron tasks, closes Socket.IO, and ends the DB pool, so background work is part of the same process boundary as the API.

3. **Request path inside the API**
   - Requests flow through `src/app.js` middleware first: security headers, CORS, JSON/urlencoded parsing, compression, logging, cookies, and global rate limiting.
   - Route handlers then apply route-specific auth, validation, and tighter rate limits before reaching controllers.
   - Controllers are thin: they read request inputs, call services, and return a standard JSON envelope.

4. **Layered application structure**
   - The code is organized into clear layers: routes → controllers → services → repositories.
   - Services contain the business rules and orchestration.
   - Repositories are the data-access boundary and are the only layer that talks to PostgreSQL.
   - This makes the diagram easy to draw as a strict vertical flow with external integrations hanging off the service layer.

5. **Database and persistence**
   - PostgreSQL is the primary system of record.
   - The schema includes users, refresh tokens, coding profiles, problem stats, GitHub stats, daily stats, contest history, achievements, notifications, goals, friends, activity logs, email preferences, contest reminders, and weekly reports.
   - Most repositories use raw `pg` queries; only analytics and leaderboard use Knex, so the data-access boundary is mixed but still centralized.
   - All user-owned data cascades on user deletion.

6. **Authentication and session model**
   - Auth is JWT-based with short-lived access tokens and longer-lived refresh tokens.
   - Refresh tokens are stored hashed in PostgreSQL and also issued as httpOnly cookies.
   - `authMiddleware` verifies Bearer access tokens, loads the user from the database, and blocks inactive accounts.
   - This is a stateless API externally, but session revocation is backed by the `refresh_tokens` table.

7. **Core product domain**
   - The main domain revolves around coding profiles per platform, then syncing platform stats into normalized tables.
   - Supported platforms are GitHub, LeetCode, Codeforces, CodeChef, GFG, and HackerRank.
   - Dashboard, analytics, leaderboard, achievements, goals, friends, public profile, and export features all read from the same shared profile/stats model rather than duplicating data.

8. **External integration layer**
   - External platform adapters live in `src/integrations/*`.
   - Each platform has its own service file that knows how to call that platform’s API and normalize its response.
   - GitHub is the most complex integration because it uses both REST and GraphQL, including optional token-based contribution data.
   - Groq is the AI integration used for insights and reports.

9. **Background jobs and scheduled synchronization**
   - The app runs nine cron jobs from `src/jobs`.
   - Five jobs sync platform data every six hours; others generate achievements, daily snapshots, weekly reports, and contest reminders.
   - Jobs are wrapped in an in-memory lock so overlapping runs are skipped.
   - This means the platform is not only request-driven; it also has a significant scheduled processing subsystem.

10. **Realtime notifications**
   - Socket.IO is initialized on the same Node server and authenticated with JWT during the handshake.
   - Users join a room for their own user ID only.
   - Notification creation writes to the database first, then emits `notification:new` to the user’s room.
   - Realtime delivery is therefore an async side effect of persisted notification records, not the source of truth.

11. **AI, reports, and exports**
   - AI features build prompts from current user stats and send them to Groq.
   - Weekly reports combine stats, achievements, goals, and recent activity, then store the generated summary in PostgreSQL.
   - Export endpoints read from multiple repositories and produce JSON, PDF, or PNG representations.
   - These are read-heavy orchestration features rather than separate services.

12. **Security, validation, and reliability boundaries**
   - Security and control points include Helmet, CORS, rate limiting, validation, bcrypt password hashing, and refresh-token rotation.
   - Validation is handled by express-validator rules plus a shared validation middleware.
   - Logging goes through Winston, request logs are piped through Morgan, and Sentry captures unhandled errors and performance traces in production.
   - Health checks include database connectivity, so the API can report partial or full outage conditions.

13. **Operational shape of the system**
   - The app expects a single frontend origin and a single PostgreSQL database.
   - Redis appears only in Docker Compose and is not wired into the application code, so it is not part of the runtime architecture.
   - The service can be deployed as a standalone Node process behind a platform like Render or Railway, with cron jobs running inside that same process.

14. **How to draw the main data flows**
   - User request flow: client → Express middleware → route/controller → service → repository → PostgreSQL → response.
   - Sync flow: cron job or manual sync endpoint → integration client → service normalization → repository updates → PostgreSQL → notification side effect.
   - AI/report flow: service reads internal stats from PostgreSQL → Groq API call → parsed result → database/email/export output.
   - Realtime flow: database write for notification → Socket.IO emit to user room.

Main entry points: [`server/src/repositories`](https://github.com/maharshi0143/algoryn/tree/main/server/src/repositories) (Repositories), [`server/src/jobs`](https://github.com/maharshi0143/algoryn/tree/main/server/src/jobs) (Cron Jobs), [`server/src/app.js`](https://github.com/maharshi0143/algoryn/blob/main/server/src/app.js) (Express App), [`server/src/server.js`](https://github.com/maharshi0143/algoryn/blob/main/server/src/server.js) (Server)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_runtime["Runtime"]
  node_client(("Client<br/>consumer"))
  node_server["Server<br/>bootstrap<br/>[server.js]"]
  node_socket(("Socket.IO<br/>realtime<br/>[socket.js]"))
end

subgraph group_app["API Layer"]
  node_app["Express App<br/>http app<br/>[app.js]"]
  node_middleware["Middleware<br/>policy chain"]
  node_routes["Routes<br/>routing"]
  node_controllers["Controllers<br/>http handlers"]
end

subgraph group_domain["Domain"]
  node_services["Services<br/>business logic"]
  node_sync["Sync Service<br/>orchestrator<br/>[syncService.js]"]
  node_ai["AI Service<br/>reporting<br/>[aiService.js]"]
  node_report["Report Service<br/>reporting"]
  node_export["Export Service<br/>output<br/>[exportService.js]"]
  node_notification["Notifications<br/>side effect"]
  node_auth["Auth<br/>security<br/>[authService.js]"]
end

subgraph group_data["Data"]
  node_repositories[("Repositories<br/>data access")]
  node_db[("PostgreSQL<br/>database<br/>[schema.sql]")]
end

subgraph group_integrations["Integrations"]
  node_integrations["Platform APIs<br/>adapters"]
end

subgraph group_background["Background"]
  node_jobs["Cron Jobs<br/>scheduler"]
end

node_client -->|"HTTP requests"| node_app
node_server -->|"mounts"| node_app
node_server -->|"starts"| node_jobs
node_server -->|"attaches"| node_socket
node_app -->|"uses"| node_middleware
node_app -->|"mounts"| node_routes
node_routes -->|"dispatches"| node_controllers
node_controllers -->|"calls"| node_services
node_services -->|"reads/writes"| node_repositories
node_repositories -->|"queries"| node_db
node_auth -->|"loads users"| node_repositories
node_sync -->|"polls"| node_integrations
node_sync -->|"updates"| node_repositories
node_jobs -->|"runs"| node_sync
node_jobs -->|"generates"| node_report
node_jobs -->|"reminds"| node_notification
node_ai -->|"calls Groq"| node_integrations
node_report -->|"reads stats"| node_repositories
node_export -->|"reads data"| node_repositories
node_notification -->|"emits"| node_socket
node_notification -->|"persists"| node_repositories

click node_server "https://github.com/maharshi0143/algoryn/blob/main/server/src/server.js"
click node_app "https://github.com/maharshi0143/algoryn/blob/main/server/src/app.js"
click node_middleware "https://github.com/maharshi0143/algoryn/tree/main/server/src/middlewares"
click node_routes "https://github.com/maharshi0143/algoryn/tree/main/server/src/routes"
click node_controllers "https://github.com/maharshi0143/algoryn/tree/main/server/src/controllers"
click node_services "https://github.com/maharshi0143/algoryn/tree/main/server/src/services"
click node_sync "https://github.com/maharshi0143/algoryn/blob/main/server/src/services/syncService.js"
click node_ai "https://github.com/maharshi0143/algoryn/blob/main/server/src/services/aiService.js"
click node_report "https://github.com/maharshi0143/algoryn/blob/main/server/src/services/weeklyReportService.js"
click node_export "https://github.com/maharshi0143/algoryn/blob/main/server/src/services/exportService.js"
click node_notification "https://github.com/maharshi0143/algoryn/blob/main/server/src/services/notificationService.js"
click node_repositories "https://github.com/maharshi0143/algoryn/tree/main/server/src/repositories"
click node_db "https://github.com/maharshi0143/algoryn/blob/main/server/database/schema.sql"
click node_socket "https://github.com/maharshi0143/algoryn/blob/main/server/src/config/socket.js"
click node_jobs "https://github.com/maharshi0143/algoryn/tree/main/server/src/jobs"
click node_integrations "https://github.com/maharshi0143/algoryn/tree/main/server/src/integrations"
click node_auth "https://github.com/maharshi0143/algoryn/blob/main/server/src/services/authService.js"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_client,node_server,node_socket toneBlue
class node_app,node_middleware,node_routes,node_controllers toneAmber
class node_services,node_sync,node_ai,node_report,node_export,node_notification,node_auth toneMint
class node_repositories,node_db toneRose
class node_integrations toneIndigo
class node_jobs toneTeal
```

## Components

### Runtime

Single Node process boundary for API, jobs, and realtime

- **Client**: consumer · Frontend or API consumer
- [Server](https://github.com/maharshi0143/algoryn/blob/main/server/src/server.js): bootstrap · Process entrypoint and startup orchestration · `server/src/server.js`
- [Socket.IO](https://github.com/maharshi0143/algoryn/blob/main/server/src/config/socket.js): realtime · Authenticated realtime delivery on the same server · `server/src/config/socket.js`

### API Layer

Express request pipeline and route handling

- [Express App](https://github.com/maharshi0143/algoryn/blob/main/server/src/app.js): http app · Middleware stack and route mounting · `server/src/app.js`
- [Middleware](https://github.com/maharshi0143/algoryn/tree/main/server/src/middlewares): policy chain · Security, parsing, logging, auth, validation, and rate limits · `server/src/middlewares`
- [Routes](https://github.com/maharshi0143/algoryn/tree/main/server/src/routes): routing · HTTP endpoints grouped by feature · `server/src/routes`
- [Controllers](https://github.com/maharshi0143/algoryn/tree/main/server/src/controllers): http handlers · Thin request handlers that call services · `server/src/controllers`

### Domain

Core business services and orchestration

- [Services](https://github.com/maharshi0143/algoryn/tree/main/server/src/services): business logic · Core orchestration and domain rules · `server/src/services`
- [Sync Service](https://github.com/maharshi0143/algoryn/blob/main/server/src/services/syncService.js): orchestrator · Coordinates platform polling and normalization · `server/src/services/syncService.js`
- [AI Service](https://github.com/maharshi0143/algoryn/blob/main/server/src/services/aiService.js): reporting · Builds prompts and calls Groq for insights · `server/src/services/aiService.js`
- [Report Service](https://github.com/maharshi0143/algoryn/blob/main/server/src/services/weeklyReportService.js): reporting · Generates weekly summaries from stored stats · `server/src/services/weeklyReportService.js`
- [Export Service](https://github.com/maharshi0143/algoryn/blob/main/server/src/services/exportService.js): output · Assembles JSON, PDF, and PNG exports · `server/src/services/exportService.js`
- [Notifications](https://github.com/maharshi0143/algoryn/blob/main/server/src/services/notificationService.js): side effect · Persists and emits realtime user notifications · `server/src/services/notificationService.js`
- [Auth](https://github.com/maharshi0143/algoryn/blob/main/server/src/services/authService.js): security · JWT access, refresh-token rotation, bcrypt, and account checks · `server/src/services/authService.js`

### Data

Persistence boundary and database access

- [Repositories](https://github.com/maharshi0143/algoryn/tree/main/server/src/repositories): data access · PostgreSQL boundary for users, stats, tokens, and reports · `server/src/repositories`
- [PostgreSQL](https://github.com/maharshi0143/algoryn/blob/main/server/database/schema.sql): database · Primary system of record · `server/database/schema.sql`

### Integrations

External platform and AI adapters

- [Platform APIs](https://github.com/maharshi0143/algoryn/tree/main/server/src/integrations): adapters · GitHub, LeetCode, Codeforces, CodeChef, GFG, HackerRank, Groq · `server/src/integrations`

### Background

Scheduled synchronization and reporting jobs

- [Cron Jobs](https://github.com/maharshi0143/algoryn/tree/main/server/src/jobs): scheduler · In-process scheduled sync, snapshots, reminders, and reports · `server/src/jobs`

## Connections

- Client → Express App: HTTP requests · API traffic enters the Express app
- Server → Express App: mounts · Bootstrap creates and configures the app
- Server → Cron Jobs: starts · Scheduled tasks begin in the same process
- Server → Socket.IO: attaches · Realtime server is attached to the HTTP server
- Express App → Middleware: uses · Shared middleware runs before routes
- Express App → Routes: mounts · Feature routes are registered on the app
- Routes → Controllers: dispatches · Routes hand requests to controllers
- Controllers → Services: calls · Controllers delegate business work to services
- Services → Repositories: reads/writes · Services use repositories for persistence
- Repositories → PostgreSQL: queries · Repositories are the only database access layer
- Auth → Repositories: loads users · Auth middleware and service depend on token and user storage
- Sync Service → Platform APIs: polls · Platform adapters fetch and normalize remote stats
- Sync Service → Repositories: updates · Normalized stats are stored after sync
- Cron Jobs → Sync Service: runs · Cron sync jobs invoke the sync pipeline
- Cron Jobs → Report Service: generates · Weekly report job builds persisted summaries
- Cron Jobs → Notifications: reminds · Reminder and achievement jobs create notifications
- AI Service → Platform APIs: calls Groq · AI prompts are sent to the Groq service
- Report Service → Repositories: reads stats · Reports combine stored stats, goals, and activity
- Export Service → Repositories: reads data · Exports aggregate multiple data sources
- Notifications → Socket.IO: emits · Persisted notifications are pushed to user rooms
- Notifications → Repositories: persists · Notification records are stored before delivery
