# System Overview

> A comprehensive look at how Izri works from a 10,000-foot view

## 🎯 What is Izri?

**Izri** is a modern test management and repository analysis platform built as a monorepo application. It provides:

- **Repository Analysis**: Automatic scanning and analysis of codebases
- **Test Management**: Track test runs, results, and coverage
- **Organization Support**: Multi-tenant architecture for teams
- **AI Integration**: Intelligent test generation and analysis
- **Privacy-First**: Metadata-focused analysis with optional hashing

## 🏗️ High-Level Architecture

Izri follows a modern, type-safe, full-stack architecture with clear separation of concerns:

```
┌─────────────────────────────────────────────────────────┐
│                    User Interface Layer                 │
│        React Router v7 + shadcn/ui + Tailwind          │
│              (Server-Side Rendering Ready)              │
└────────────────────┬────────────────────────────────────┘
                     │
                     │ tRPC (Type-Safe RPC)
                     │
┌────────────────────▼────────────────────────────────────┐
│                   Application Layer                      │
│             Hono + tRPC + Middleware Stack              │
│         (Authentication, Logging, Validation)            │
└─────┬──────────────────────────────────────────┬────────┘
      │                                          │
      │ Drizzle ORM                             │ HTTP/REST
      │                                          │
┌─────▼──────────────────┐         ┌────────────▼─────────┐
│   Data Layer           │         │   External Services  │
│                        │         │                      │
│  PostgreSQL 15         │         │  Python AI Service   │
│  (Primary Database)    │         │  (FastAPI + Models)  │
│                        │         │                      │
│  Redis 7               │         │  GitHub API          │
│  (Cache & Sessions)    │         │  (OAuth & Webhooks)  │
└────────────────────────┘         └──────────────────────┘
```

## 🔄 Request Flow

### Typical User Request

```mermaid
sequenceDiagram
    participant Browser
    participant WebApp as React Router App
    participant API as Hono + tRPC API
    participant DB as PostgreSQL
    participant Cache as Redis
    
    Browser->>WebApp: Navigate to /projects
    WebApp->>API: tRPC: projects.list()
    API->>Cache: Check cache
    alt Cache Hit
        Cache-->>API: Return cached data
    else Cache Miss
        API->>DB: Query projects
        DB-->>API: Return results
        API->>Cache: Store in cache
    end
    API-->>WebApp: Type-safe response
    WebApp-->>Browser: Render UI
```

### Data Write Flow

```mermaid
sequenceDiagram
    participant Browser
    participant WebApp
    participant API
    participant DB
    participant Cache
    participant Webhook as GitHub Webhook
    
    Browser->>WebApp: Create project
    WebApp->>API: tRPC: projects.create()
    API->>API: Validate with Zod
    API->>DB: INSERT transaction
    DB-->>API: Confirm
    API->>Cache: Invalidate cache
    API-->>WebApp: Success response
    WebApp-->>Browser: Update UI
    
    Note over Webhook: Asynchronously...
    Webhook->>API: POST /webhooks/github
    API->>API: Verify signature
    API->>DB: Store webhook event
    API->>API: Trigger analysis job
```

## 🧩 Core Components

### 1. Frontend Application (`apps/web`)

**Technology**: React Router v7, React 19, TypeScript, Tailwind CSS

**Responsibilities**:

- User interface rendering
- Client-side routing
- Form validation
- State management
- tRPC client integration
- Authentication flows

**Key Features**:

- Server-side rendering ready
- Type-safe API calls via tRPC
- Responsive design with Tailwind
- Component library (shadcn/ui)
- Hot module replacement (HMR)

### 2. API Server (`apps/api`)

**Technology**: Hono, tRPC, TypeScript, Node.js 18+

**Responsibilities**:

- HTTP request handling
- Business logic execution
- Data validation (Zod schemas)
- Authentication & authorization
- Rate limiting (planned)
- Logging and observability

**Key Features**:

- Fast and lightweight (Hono)
- Type-safe procedures (tRPC)
- Middleware chain pattern
- Comprehensive logging (Pino)
- OpenTelemetry support

### 3. Database Layer (`packages/database`)

**Technology**: PostgreSQL 15, Drizzle ORM, TypeScript

**Responsibilities**:

- Data persistence
- Schema management
- Migrations
- Seeding
- Query optimization

**Key Features**:

- Type-safe schema definitions
- Migration versioning
- Connection pooling
- ACID transactions
- Referential integrity

### 4. AI Service (`packages/ai-service`)

**Technology**: Python 3.12, FastAPI, LangChain

**Responsibilities**:

- Repository analysis
- Code scanning
- Test generation (planned)
- AI-powered insights

**Key Features**:

- Async processing
- Language detection
- Framework detection
- Dependency analysis
- Privacy-focused (metadata only)

### 5. Shared Packages

**`@izri/trpc`**: tRPC routers, procedures, and context
**`@izri/auth`**: Lucia authentication, session management
**`@izri/shared`**: Common utilities, types, schemas
**`@izri/crypto`**: Encryption utilities (libsodium)

## 🔐 Security Architecture

### Authentication Flow

```mermaid
graph LR
    A[User] --> B{Login Method}
    B -->|GitHub OAuth| C[GitHub Auth]
    B -->|Email/Password| D[Credentials Auth]
    C --> E[Lucia Session]
    D --> E
    E --> F[Session Cookie]
    F --> G[Authenticated Requests]
```

**Approach**: Lucia-based session management with multiple providers

**Features**:

- OAuth 2.0 (GitHub primary)
- Credentials fallback
- Secure session cookies
- API token support
- CSRF protection

### Data Protection

**Database Security**:

- Encrypted connections (SSL/TLS)
- Parameterized queries (SQL injection prevention)
- Row-level security (planned)
- Connection pooling limits

**Application Security**:

- Input validation (Zod)
- XSS protection (React escaping)
- CORS configuration
- Environment variable management
- Secret rotation support

**Encryption**:

- End-to-end message encryption
- libsodium sealed boxes
- Public key infrastructure
- No server-side key storage

## 📊 Data Model

### Core Entities

```
users
├── id (primary key)
├── email (unique)
├── password_hash
├── created_at
└── updated_at

organizations
├── id (primary key)
├── name
├── slug (unique)
├── owner_id (→ users.id)
├── settings (JSONB)
└── timestamps

organization_members
├── id (primary key)
├── organization_id (→ organizations.id)
├── user_id (→ users.id)
├── role (enum: owner, admin, member)
└── timestamps

projects
├── id (primary key)
├── organization_id (→ organizations.id)
├── name
├── repository_url
├── settings (JSONB)
└── timestamps

test_runs
├── id (primary key)
├── project_id (→ projects.id)
├── commit_sha
├── status (enum: pending, running, passed, failed)
├── summary (JSONB)
└── timestamps

project_analyses
├── id (primary key)
├── project_id (→ projects.id)
├── commit_sha
├── analysis_data (JSONB)
└── timestamps
```

**Relationships**:

- Users belong to many Organizations (via organization_members)
- Organizations have many Projects
- Projects have many TestRuns
- Projects have many Analyses (one per commit)

### Data Access Patterns

**Read-Heavy Operations**:

- Project listings (cached)
- Test run history (paginated)
- Organization dashboard (cached)

**Write-Heavy Operations**:

- Webhook events (queued)
- Analysis results (bulk insert)
- Test run updates (transactional)

## 🔄 Communication Patterns

### Frontend ↔ Backend

**Protocol**: tRPC over HTTP

**Benefits**:

- End-to-end type safety
- No code generation
- Request/response validation
- Automatic serialization
- Built-in error handling

**Example**:

```typescript
// Frontend
const projects = await trpc.projects.list.query()

// Backend
export const projectRouter = router({
  list: publicProcedure.query(async ({ ctx }) => {
    return ctx.db.select().from(projects)
  })
})
```

### Backend ↔ Database

**Protocol**: Drizzle ORM (SQL builder)

**Benefits**:

- Type-safe queries
- SQL-like syntax
- No runtime overhead
- Migration system
- Full TypeScript support

### Backend ↔ AI Service

**Protocol**: HTTP REST

**Approach**: Async job-based processing

**Flow**:

1. API queues analysis job
2. AI service polls for jobs
3. Processes repository
4. Returns results via callback
5. API stores in database

## 🚀 Deployment Model

### Development

```
Host Machine
├── apps/web (Vite dev server, port 5173)
├── apps/api (tsx watch, port 4000)
└── Docker Compose
    ├── PostgreSQL (port 5433)
    ├── Redis (port 6379)
    └── AI Service (port 8000)
```

### Production (Planned)

```
Load Balancer
├── Web App (N instances, containerized)
├── API Server (N instances, containerized)
└── Managed Services
    ├── PostgreSQL (managed DB)
    ├── Redis (managed cache)
    └── AI Service (containerized workers)
```

## 📈 Scalability Considerations

### Horizontal Scaling

**What scales horizontally**:

- ✅ Web app (stateless)
- ✅ API server (stateless)
- ✅ AI service (worker pool)

**What requires coordination**:

- ❌ PostgreSQL (read replicas possible)
- ❌ Redis (clustering recommended)

### Performance Targets

| Metric | Target | Current |
|--------|--------|---------|
| API Response (cached) | <50ms | ~30ms |
| API Response (DB query) | <200ms | ~150ms |
| Page Load (initial) | <2s | ~1.5s |
| Page Load (cached) | <500ms | ~300ms |
| Database Query | <10ms | ~8ms |
| Concurrent Users | 1000+ | TBD |

## 🔍 Observability

### Logging

**Approach**: Structured JSON logging with Pino

**Levels**: trace, debug, info, warn, error, fatal

**Context**: Request ID, user ID, tenant ID, trace ID

### Metrics (Planned)

- Request latency (p50, p95, p99)
- Error rates
- Database connection pool usage
- Cache hit rates
- Background job queue depth

### Tracing (Planned)

**Technology**: OpenTelemetry

**Coverage**: Full request lifecycle from browser to database

## 🎯 Design Principles

### 1. Type Safety First

Everything is typed end-to-end:

- Database schema → TypeScript types
- API contracts → tRPC procedures
- Frontend state → TypeScript interfaces

### 2. Convention Over Configuration

- Standardized project structure
- Consistent naming conventions
- Shared tooling configuration

### 3. Developer Experience

- Fast feedback loops (HMR, watch mode)
- Comprehensive error messages
- Extensive documentation
- Local development environment

### 4. Modularity

- Clear package boundaries
- Minimal coupling
- Dependency injection
- Testable units

### 5. Performance

- Turbo caching
- Database indexing
- Redis caching layer
- Lazy loading
- Code splitting

## 🔗 Next Steps

Now that you understand the system overview, explore these topics:

- **[Technology Stack](./technology-stack.md)**: Deep dive into each technology choice
- **[Monorepo Structure](./monorepo-structure.md)**: Navigate the codebase effectively
- **[Data Flow](./data-flow.md)**: Understand request/response lifecycles
- **[Design Decisions](./design-decisions.md)**: Learn why things are built this way

---

*Questions? Check [Design Decisions](./design-decisions.md) for rationale behind key choices.*
