railyard/apps/ritgram/backend/ARCHITECTURE.md
caelum0x 6801c08af9
Some checks failed
ci / cargo test (abacus) (push) Has been cancelled
ci / cargo test (agent-runtime) (push) Has been cancelled
ci / cargo test (context-passport) (push) Has been cancelled
ci / cargo test (game-economy) (push) Has been cancelled
ci / cargo test (ledgerline) (push) Has been cancelled
ci / cargo test (mint) (push) Has been cancelled
ci / cargo test (rago) (push) Has been cancelled
ci / cargo test (relay) (push) Has been cancelled
ci / node suites (push) Has been cancelled
ci / cargo test (toolgate) (push) Has been cancelled
ci / cargo test (turnstile) (push) Has been cancelled
ci / cargo test (vend) (push) Has been cancelled
feat(RIT-OPS,RIT-BRD): rename gitea -> rit everywhere we control, deployed + live-verified
apps/gitea -> apps/rithub-server; compose services/containers renamed
(rithub-server-app/postgres/act-runner) with explicit project name and
volume names pinned to the exact existing Docker volumes (no data loss);
our own GITEA_* compose/env var names -> RIT_*; new rit-admin CLI wrapper
on railyard-box; giteaSession.mjs/giteaOAuth.mjs/giteaInfo.mjs ->
ritSession/ritOAuth/ritInfo across 6 apps; GiteaForgeAdapter -> RitForgeAdapter
+ giteaSyncService/importGiteaRepos/syncGiteaRepos -> rit* in ritgram
(tsc clean); apps/console/lib/gitea.ts -> lib/ritProvision.ts; Go
internal/giteaclient -> internal/ritclient in rithub-async-import (go
build/test clean); new /auth/rit + /forges/rit/connect routes with
/gitea back-compat aliases; locale/swagger/footer/captcha template text
scrubbed of remaining "Gitea" strings.

Deployed to railyard-box: old containers stopped/removed, /srv/railyard-gitea
renamed to /srv/rithub-server with a symlink kept, docker compose up -d from
the new path, act_runner network-alias fix for its persisted instance URL.
Live-verified: docker compose config diff showed zero unintended value
changes, DB row counts unchanged (19 users, 635 repos), full route
regression 200/expected, 0 "gitea" in headers/bodies on every checked page,
real git clone+push over HTTPS and SSH with a disposable account (deleted
after). Deferred on purpose (documented in plans/railyard.md): the forge
discriminator / DB column names / Postgres role+volume names (data
migrations, not a naming change) and the upstream GITEA__ env-to-ini keys
and X-Gitea-* wire headers (hardcoded in the vendored engine binary).

See plans/railyard.md RIT-OPS/RIT-BRD entry for the full old->new map and
live evidence.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-12-01 16:34:39 +03:00

198 lines
6.9 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 + 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).
- `RitForgeAdapter.ts` — plain `fetch` against Rithub's `/api/v1` (verified on the underlying engine
1.23.8 at rithub.dev). 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/Rithub payload -> one `ForgeWebhookEvent`, plus a GitHub-compat bridge for the legacy
activity extractor / auto-post pipeline).
Rithub webhook facts (from the underlying engine's `services/webhook/deliver.go`, release/v1.23, and
a captured real delivery — these are the wire header names the running engine itself sends; `detect.ts`
must match them literally and cannot rename them):
`X-Gitea-Event`, `X-Gitea-Delivery`, `X-Gitea-Event-Type`, `X-Gitea-Signature` = raw hex
HMAC-SHA256 (no `sha256=` prefix); Rithub also sends `X-GitHub-*`, `X-Gogs-*`, `X-Hub-Signature-256`
compat headers, so the Rithub case 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 Rithub (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