railyard/apps/ritgram/backend/ARCHITECTURE.md
caelum0x b2bf742a20 feat(ritgram): forge adapter — GitHub + Gitea (Rithub) side by side
- ForgeAdapter interface; existing Octokit code moved behind GitHubForgeAdapter (same behavior)
- GiteaForgeAdapter against /api/v1, paths checked against live Gitea 1.23.8 swagger
- One webhook ingestion for GitHub and Gitea (raw-body HMAC, X-Gitea-Signature detected first)
- Forge-agnostic activity feed (GitHub polled + Gitea webhook/polled, merged)
- Per-user ForgeConnection with legacy githubAccessToken backfill (migration 20261113000000)

Verified locally with a genuine delivery from a throwaway Gitea container and read-only probes of git.ereboslab.com; tsc clean, targeted jest 77/77.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-13 04:53:57 +03:00

196 lines
6.7 KiB
Markdown

# Gitgram Architecture
## System Overview
Gitgram is a social media platform for developers to showcase GitHub projects, built with:
- **Backend**: Node.js + Express + TypeScript
- **Database**: PostgreSQL with Prisma ORM
- **Mobile**: React Native with Expo
- **Real-time**: Socket.io
- **Storage**: AWS S3 (production) / Local (development)
## Architecture Diagram
```
┌─────────────┐
│ Mobile │
│ App │
│ (Expo) │
└──────┬──────┘
│
│ HTTPS/REST API
│ WebSocket
│
┌──────▼──────────────────┐
│ Load Balancer │
│ (Nginx/ALB) │
└──────┬──────────────────┘
│
├─────────────┬─────────────┐
│ │ │
┌──────▼──────┐ ┌───▼──────┐ ┌───▼──────┐
│ Backend │ │ Backend │ │ Backend │
│ Instance 1 │ │Instance 2│ │Instance 3│
└──────┬──────┘ └───┬──────┘ └───┬──────┘
│ │ │
└────────────┼─────────────┘
│
┌───────────┼───────────┐
│ │ │
┌───────▼──┐ ┌─────▼─────┐ ┌─▼──────┐
│PostgreSQL│ │ Redis │ │ S3 │
│ (Primary)│ │ (Cache) │ │(Media) │
└──────────┘ └───────────┘ └─────────┘
│
│
┌────▼──────┐
│PostgreSQL │
│ (Replica) │
└───────────┘
```
## Backend Structure
```
backend/
├── src/
│ ├── config/ # Configuration files
│ ├── controllers/ # Request handlers
│ ├── middleware/ # Express middleware
│ ├── models/ # Data models (Prisma)
│ ├── routes/ # API routes
│ ├── services/ # Business logic
│ ├── utils/ # Utilities
│ ├── validators/ # Input validation
│ └── websocket/ # Socket.io handlers
├── prisma/ # Database schema
├── tests/ # Test files
└── dist/ # Compiled JavaScript
```
## API Architecture
### RESTful API
- **Base URL**: `/api/v1`
- **Authentication**: JWT Bearer tokens
- **Response Format**: JSON
- **Error Handling**: Standardized error responses
### Endpoints
- `/api/v1/auth` - Authentication
- `/api/v1/posts` - Posts management
- `/api/v1/reels` - Reels (videos)
- `/api/v1/stories` - Stories (24h)
- `/api/v1/messages` - Direct messages
- `/api/v1/users` - User management
- `/api/v1/github` - GitHub integration
## Forge Layer (GitHub + Gitea/Rithub)
All git-host access goes through `src/forge/` (added 2026-11-13, Rithub plan §5.4):
- `types.ts` — `ForgeAdapter` interface + normalized `ForgeRepo`, `ForgeUser`, `ForgeCommit`,
`ForgeActivityItem`, ... shared by every forge.
- `GitHubForgeAdapter.ts` — the former Octokit code, moved behind the interface (same mapping, same
output). `.raw` exposes Octokit for GitHub-only features (GraphQL contributions, git trees).
- `GiteaForgeAdapter.ts` — plain `fetch` against Gitea `/api/v1` (verified on Gitea 1.23.8 at
git.ereboslab.com). Field differences are handled here (`stars_count`, `compare_url`,
`activities/feeds` instead of the Events API, no `star` webhook).
- `index.ts` — `createForgeAdapter({ forge, token })`, `forgeAdapterForUser(userId, forge)`.
- `webhook/` — `detect.ts` (header detection + HMAC over the raw body), `normalize.ts`
(GitHub/Gitea payload -> one `ForgeWebhookEvent`, plus a GitHub-compat bridge for the legacy
activity extractor / auto-post pipeline).
Gitea webhook facts (from `services/webhook/deliver.go`, release/v1.23, and a captured real delivery):
`X-Gitea-Event`, `X-Gitea-Delivery`, `X-Gitea-Event-Type`, `X-Gitea-Signature` = raw hex
HMAC-SHA256 (no `sha256=` prefix); Gitea also sends `X-GitHub-*`, `X-Gogs-*`, `X-Hub-Signature-256`
compat headers, so Gitea must be detected first. Bodies are pretty-printed JSON, so the signature
only verifies over the raw request bytes — `/api/v1/{github,forge}/webhooks/incoming` are mounted
with `express.raw()` ahead of the JSON parser.
Per-user credentials live in `ForgeConnection` (`services/forgeConnectionService.ts`); the legacy
`User.githubAccessToken` column is still read as a fallback and dual-written on GitHub OAuth.
`services/forgeActivityService.ts` merges GitHub (polled) with Gitea (webhook rows + polled) into one
feed, served by `/api/v1/forge-activity/*`. Connections: `/api/v1/forges/*`.
## Database Schema
### Key Models
- **User**: User accounts and profiles
- **Post**: Text, image, code posts
- **Reel**: Video content
- **Story**: Ephemeral content (24h)
- **Message**: Direct messages
- **Notification**: User notifications
- **GitHubProject**: Synced GitHub repositories
### Relationships
- User → Posts (1:N)
- User → Reels (1:N)
- User → Stories (1:N)
- User → Followers (N:M)
- Post → Comments (1:N)
- Post → Likes (N:M)
## Security
### Authentication Flow
1. User registers/logs in
2. Server generates access token (15min) + refresh token (7 days)
3. Client stores tokens securely
4. Client sends access token in Authorization header
5. On expiration, client uses refresh token to get new access token
### Authorization
- Role-based access control (user, admin, moderator)
- Resource ownership validation
- Rate limiting per endpoint
## Storage
### Media Storage
- **Development**: Local filesystem
- **Production**: AWS S3 with CDN
- **File Types**: Images, videos, code snippets
- **Max Size**: 50MB per file
## Real-time Features
### Socket.io
- Real-time messaging
- Typing indicators
- Live notifications
- Connection management
## Performance Optimizations
- Database indexes on frequently queried fields
- Response compression (gzip)
- API response caching (Redis - planned)
- Connection pooling
- Pagination for large datasets
## Monitoring
- Winston logging with daily rotation
- Request logging middleware
- Error tracking (Sentry - planned)
- Health check endpoints
## Deployment
- Docker containerization
- Kubernetes/ECS for orchestration
- CI/CD with GitHub Actions
- Automated testing on PR
- Staging and production environments