# Aphrodite Architecture

> **Canonical source:** the canonical architecture document for this domain is
> [`deep-dive/architecture.md`](./deep-dive/architecture.md), rendered in the
> docs center. This file is its operational companion (service topology, APIs,
> schemas, runtime detail) — reconciled by linking, not duplicated (§2, §13).

> System Architecture for the Live Streaming and Performance Platform

This document describes the technical architecture of the Aphrodite domain,
covering its microservice topology, real-time communication patterns, database
design, payment flows, device integration, and compliance infrastructure.

---

## Table of Contents

1. [System Overview](#system-overview)
2. [Service Architecture](#service-architecture)
3. [Application Layer](#application-layer)
4. [Library Layer](#library-layer)
5. [Communication Architecture](#communication-architecture)
6. [Database Architecture](#database-architecture)
7. [Streaming Pipeline](#streaming-pipeline)
8. [Payment Architecture](#payment-architecture)
9. [Device Integration Architecture](#device-integration-architecture)
10. [VR/AR Architecture](#vrar-architecture)
11. [Security and Compliance](#security-and-compliance)
12. [Data Flow](#data-flow)
13. [Cross-Domain Dependencies](#cross-domain-dependencies)
14. [Deployment Architecture](#deployment-architecture)
15. [Technology Stack](#technology-stack)

---

## System Overview

Aphrodite is a large-scale, real-time streaming platform with 22 backend
services and 74 libraries. The architecture is designed around five core
concerns:

1. **Real-time media delivery** -- Low-latency streaming via RTMP ingest, WebRTC
   signaling, and adaptive HLS/DASH distribution.
2. **Interactive experiences** -- Bidirectional device control, haptic feedback,
   chat, tipping, and VR/AR immersion.
3. **Payment processing** -- Multi-provider payment (CCBill, Epoch, Segpay),
   token economy, cryptocurrency support, and revenue sharing.
4. **Content safety** -- Age verification, 18 U.S.C. 2257 compliance, GDPR, DRM,
   watermarking, and AI-based content moderation.
5. **Scalable microservices** -- Each concern is an independent service with its
   own data store, communicating via REST, WebSocket, gRPC, and Kafka.

```
┌──────────────────────────────────────────────────────────────────────┐
│                            CLIENTS                                    │
│  Web App  │  Mobile (Viewer/Broadcaster)  │  VR  │  OBS  │  Devices │
└─────────────────────────────┬────────────────────────────────────────┘
                              │
              ┌───────────────┼───────────────┐
              ▼               ▼               ▼
         ┌─────────┐   ┌──────────┐   ┌─────────────┐
         │   API   │   │  Media   │   │  WebSocket  │
         │ Gateway │   │ Gateway  │   │   Gateway   │
         │ (REST)  │   │(WebRTC)  │   │ (Socket.io) │
         └────┬────┘   └────┬─────┘   └──────┬──────┘
              │              │                │
              └──────────────┼────────────────┘
                             │
         ┌───────────────────┼───────────────────┐
         ▼                   ▼                   ▼
   ┌───────────┐      ┌──────────┐       ┌───────────┐
   │  Auth     │      │ Streaming│       │   Chat    │
   │  :3003    │◄────►│  :3003   │◄─────►│   :5000   │
   └─────┬─────┘      └────┬─────┘       └─────┬─────┘
         │                  │                   │
   ┌─────┴─────┐     ┌─────┴─────┐      ┌─────┴─────┐
   ▼           ▼     ▼           ▼      ▼           ▼
┌────────┐ ┌─────┐ ┌───────┐ ┌──────┐ ┌────────┐ ┌──────┐
│Payment │ │CDN  │ │Viewer │ │Broad-│ │Devices │ │VR    │
│ :4000  │ │:3005│ │ :3002 │ │caster│ │ :4003  │ │:3008 │
│        │ │     │ │       │ │:3100 │ │        │ │      │
└────────┘ └─────┘ └───────┘ └──────┘ └────────┘ └──────┘
   │         │         │         │         │         │
   └─────────┴─────────┴─────────┴─────────┴─────────┘
                             │
     ┌───────────────────────┼───────────────────────┐
     ▼                       ▼                       ▼
┌──────────┐         ┌──────────┐            ┌──────────────┐
│PostgreSQL│         │  MongoDB │            │  ClickHouse  │
│(Users,   │         │(Chat,    │            │  (Analytics) │
│ Payments,│         │ Streams, │            │              │
│ Content) │         │ Notifs)  │            │              │
└──────────┘         └──────────┘            └──────────────┘
     │                    │                       │
     └────────────────────┴───────────────────────┘
                          │
              ┌───────────┴──────────────┐
              ▼                          ▼
         ┌─────────┐             ┌──────────┐
         │  Redis  │             │  Kafka   │
         │ (Cache, │             │ (Events) │
         │ Pub/Sub)│             │          │
         └─────────┘             └──────────┘
```

---

## Service Architecture

### Backend Services (22)

| Service                 | Directory                            | Port | Framework        | Protocol(s)     | Description                                 |
| ----------------------- | ------------------------------------ | ---- | ---------------- | --------------- | ------------------------------------------- |
| **Auth**                | `apps/aphrodite/auth`                | 3003 | Hono             | REST            | Authentication, JWT, OAuth, 2FA             |
| **Streaming**           | `apps/aphrodite/streaming`           | 3003 | Hono             | REST, gRPC      | Stream ingestion, transcoding, distribution |
| **Chat**                | `apps/aphrodite/chat`                | 5000 | Hono + Socket.io | REST, WebSocket | Real-time chat, DMs, moderation             |
| **Payment**             | `apps/aphrodite/payment`             | 4000 | Hono             | REST, Webhooks  | Tokens, tips, subscriptions, payouts        |
| **Viewer**              | `apps/aphrodite/viewer`              | 3002 | Hono             | REST            | Stream viewing, tipping, interactions       |
| **Broadcaster**         | `apps/aphrodite/broadcaster`         | 3100 | Hono             | REST            | Stream creation, management, earnings       |
| **CDN**                 | `apps/aphrodite/cdn`                 | 3005 | Hono             | REST            | CDN management, signed URLs, purging        |
| **Admin**               | `apps/aphrodite/admin`               | 3004 | Hono             | REST            | Platform administration, moderation         |
| **Admin BI Dashboard**  | `apps/aphrodite/admin-bi-dashboard`  | 3000 | Hono             | REST            | Business intelligence, revenue reports      |
| **Analytics**           | `apps/aphrodite/analytics`           | --   | Hono             | REST            | Event ingestion, pipeline, dashboards       |
| **Realtime Analytics**  | `apps/aphrodite/realtime-analytics`  | 3450 | Hono + WS        | REST, WebSocket | Live viewer counts, trending streams        |
| **Notifications**       | `apps/aphrodite/notifications`       | --   | Hono             | REST            | Multi-channel delivery (push, email, SMS)   |
| **Devices**             | `apps/aphrodite/devices`             | 4003 | Hono + WS        | REST, WebSocket | Device control, haptic patterns             |
| **VR**                  | `apps/aphrodite/vr`                  | 3008 | Hono + WS        | REST, WebSocket | VR capture, playback, spatial audio         |
| **Recommendation**      | `apps/aphrodite/recommendation`      | --   | --               | REST            | Content recommendations engine              |
| **Moderation**          | `apps/aphrodite/moderation`          | --   | --               | REST            | AI content moderation, reports              |
| **Mobile**              | `apps/aphrodite/mobile`              | --   | React Native     | --              | Mobile viewer application                   |
| **Mobile Broadcaster**  | `apps/aphrodite/mobile-broadcaster`  | --   | React Native     | --              | Mobile broadcasting application             |
| **Mobile Viewer**       | `apps/aphrodite/mobile-viewer`       | --   | React Native     | --              | Mobile viewer-focused application           |
| **Web**                 | `apps/aphrodite/web`                 | --   | --               | --              | Web application (SPA)                       |
| **Analytics Dashboard** | `apps/aphrodite/analytics-dashboard` | --   | --               | --              | Creator analytics dashboard                 |

### Service Communication Patterns

| Pattern           | Use Case                              | Services                              |
| ----------------- | ------------------------------------- | ------------------------------------- |
| **REST**          | Client-facing APIs, CRUD operations   | All services                          |
| **WebSocket**     | Real-time bidirectional communication | Chat, Devices, VR, Realtime Analytics |
| **gRPC**          | Service-to-service RPC (low latency)  | Streaming                             |
| **Kafka**         | Event streaming, fan-out              | Chat, Stream, Analytics               |
| **Redis Pub/Sub** | Socket.io horizontal scaling          | Chat, Notifications                   |
| **Webhooks**      | Payment provider callbacks            | Payment (CCBill, Epoch, Segpay)       |

---

## Application Layer

### Streaming Service (`apps/aphrodite/streaming`)

The central media infrastructure service handling the full stream lifecycle:

```
apps/aphrodite/streaming/src/
├── index.ts              # Server bootstrap (HTTP + gRPC)
├── app.ts                # Hono application
└── routes/
    ├── streams.ts        # POST /api/streams -- create session
    ├── ingest.ts         # POST /api/ingest/rtmp, /api/ingest/webrtc
    ├── transcoding.ts    # POST /api/transcoding -- start job
    ├── distribution.ts   # GET  /api/distribution -- playback URLs
    ├── recording.ts      # POST /api/recording -- start/stop
    ├── thumbnails.ts     # POST /api/thumbnails -- generate
    ├── quality.ts        # GET  /api/quality -- stream metrics
    ├── discovery.ts      # GET  /api/discovery -- live streams
    ├── health.ts         # GET  /health
    └── metrics.ts        # GET  /metrics (Prometheus)
```

**Ports:**

- HTTP API: 3003
- gRPC (service-to-service): 50051
- RTMP Ingest: 1935

### Chat Service (`apps/aphrodite/chat`)

Dual-protocol service combining Hono HTTP and Socket.io WebSocket:

- **REST API**: Room management, message history, moderation actions
- **WebSocket**: Real-time message delivery, typing indicators, presence

### Payment Service (`apps/aphrodite/payment`)

Handles the full financial lifecycle:

- Token purchases (credit card, crypto)
- Tips and donations
- Subscriptions (recurring billing)
- Pay-per-view (PPV) access
- Creator payouts
- Revenue sharing splits
- Webhook processing from payment providers

### Auth Service (`apps/aphrodite/auth`)

Authentication and identity:

- JWT access/refresh tokens
- OAuth2 providers (Google, Twitter, Discord)
- Two-factor authentication (TOTP)
- Age verification integration
- Session management
- API key generation

---

## Library Layer

### 74 Libraries Organized by Domain

#### Core Infrastructure (9)

| Library           | Package                      | Purpose                                 |
| ----------------- | ---------------------------- | --------------------------------------- |
| `core`            | `@aphrodite/core`            | Types, validation, utilities, constants |
| `database`        | `@aphrodite/database`        | Zod schemas, repositories, isolation    |
| `cache`           | `@aphrodite/cache`           | Redis-based caching layer               |
| `storage`         | `@aphrodite/storage`         | S3-compatible file/media storage        |
| `event-publisher` | `@aphrodite/event-publisher` | Event publishing and subscription       |
| `oauth-providers` | `@aphrodite/oauth-providers` | OAuth integration (Google, Twitter)     |
| `safety`          | `@aphrodite/safety`          | Emergency controls and safety features  |
| `sdk`             | `@aphrodite/sdk`             | Unified SDK for platform integration    |
| `payment`         | `@aphrodite/payment`         | Payment processing utilities            |
| `testing`         | `@aphrodite/testing`         | Mock factories and test utilities       |

#### Device Integration (12)

| Library                 | Purpose                                         |
| ----------------------- | ----------------------------------------------- |
| `device-protocols`      | Unified protocol layer (Lovense, Kiiroo, Handy) |
| `buttplug`              | Buttplug.io universal device protocol           |
| `haptics`               | Haptic feedback engine                          |
| `bidirectional-haptics` | Two-way haptic communication                    |
| `motion-haptics`        | Motion-based haptic patterns                    |
| `audio-haptics`         | Audio-reactive haptic responses                 |
| `wearables`             | Wearable device integration                     |
| `smart-home`            | Smart home device control (lights, locks)       |
| `eye-tracking`          | VR eye-tracking integration                     |
| `vr-quest`              | Meta Quest-specific integration                 |
| `vr-haptics`            | VR haptic feedback                              |
| `interactables`         | Interactive stream elements                     |

#### Streaming and Media (10)

| Library                   | Purpose                                     |
| ------------------------- | ------------------------------------------- |
| `streaming-core`          | Stream session management, ingest, playback |
| `cloud-recording`         | Cloud-based stream recording                |
| `multi-source`            | Multi-camera/source composition             |
| `video-effects`           | Real-time video filters and effects         |
| `stream-upscaling`        | AI-powered resolution upscaling             |
| `highlight-clipping`      | Automated highlight creation                |
| `vod-chaptering`          | VOD chapter markers and navigation          |
| `thumbnail-generation`    | Automatic thumbnail creation                |
| `content-tagging`         | AI content classification and tagging       |
| `stream-content-analysis` | Real-time stream content analysis           |

#### VR/AR and Avatar (13)

| Library                   | Purpose                                     |
| ------------------------- | ------------------------------------------- |
| `vr-core`                 | Core VR streaming (quality presets, stereo) |
| `vr-quest`                | Meta Quest platform integration             |
| `vr-haptics`              | VR-specific haptic feedback                 |
| `spatial-audio`           | 3D spatial audio processing                 |
| `virtual-rooms`           | Virtual room creation and management        |
| `ar-overlays`             | AR overlay rendering                        |
| `viewer-avatars`          | Viewer avatar representation                |
| `avatar-motion`           | Motion capture for avatars                  |
| `avatar-renderer`         | Avatar rendering pipeline                   |
| `avatar-physics`          | Avatar physics simulation                   |
| `avatar-customization-ui` | Avatar customization interface              |
| `animations`              | Animation system                            |
| `animation-blending`      | Animation blend trees                       |
| `animation-triggers`      | Event-triggered animations                  |

#### Chat and Social (8)

| Library               | Purpose                                       |
| --------------------- | --------------------------------------------- |
| `chat-core`           | Core chat protocol and message handling       |
| `chat-moderation`     | Automated chat moderation (profanity, spam)   |
| `chat-entertainment`  | Chat games, polls, quizzes                    |
| `chat`                | High-level chat integration layer             |
| `viewer-interactions` | Viewer interaction system (reactions, emotes) |
| `tip-acknowledgment`  | Tip notification and acknowledgment           |
| `tip-effects`         | Visual effects triggered by tips              |
| `vip-areas`           | VIP-only rooms and features                   |

#### Payment and Monetization (10)

| Library           | Purpose                                         |
| ----------------- | ----------------------------------------------- |
| `payments`        | Core payment processing (CCBill, Epoch, Segpay) |
| `crypto-payments` | Cryptocurrency payment (BTC, ETH)               |
| `privacy-coins`   | Privacy-focused crypto (Monero, Zcash)          |
| `ppv`             | Pay-per-view access control                     |
| `revenue-sharing` | Creator/platform revenue splits                 |
| `tip-goals`       | Tip goal tracking and milestones                |
| `virtual-gifts`   | Virtual gift marketplace                        |
| `gamification`    | Achievements, leaderboards, loyalty             |
| `nft-integration` | NFT minting and marketplace                     |
| `remote-guest`    | Remote guest appearance management              |

#### AI and Analytics (6)

| Library                     | Purpose                                 |
| --------------------------- | --------------------------------------- |
| `analytics`                 | Event pipeline, aggregation, dashboards |
| `recommendations`           | Content recommendation engine           |
| `ai-assistant`              | AI assistant for creators               |
| `notification-intelligence` | Smart notification timing and batching  |
| `stream-content-analysis`   | AI-based stream content moderation      |
| `content-tagging`           | Automatic content classification        |

#### Security and Compliance (8)

| Library                | Purpose                                            |
| ---------------------- | -------------------------------------------------- |
| `age-verification`     | Multi-provider age verification                    |
| `compliance-2257`      | 18 U.S.C. 2257 record-keeping compliance           |
| `gdpr-compliance`      | GDPR data export, deletion, consent tracking       |
| `drm`                  | Digital rights management for VOD                  |
| `e2e-encryption`       | End-to-end encrypted private messaging             |
| `stream-watermarking`  | Invisible watermarking for stream piracy detection |
| `recording-prevention` | Screen recording deterrence                        |
| `content-takedown`     | DMCA takedown request handling                     |

---

## Communication Architecture

### Protocol Distribution

```
                         CLIENTS
    ┌──────────────────────────────────────────────┐
    │  Web  │  Mobile  │  VR  │  OBS  │  Devices   │
    └──────────────────────┬───────────────────────┘
                           │
           ┌───────────────┼───────────────┐
           ▼               ▼               ▼
      ┌──────────┐   ┌──────────┐   ┌──────────────┐
      │   REST   │   │ Socket.io│   │   WebRTC     │
      │ (HTTPS)  │   │  (WSS)   │   │ (Signaling)  │
      └──────────┘   └──────────┘   └──────────────┘
           │               │               │
           ▼               ▼               ▼
      ┌──────────────────────────────────────────┐
      │            SERVICE MESH                    │
      │  (service discovery, load balancing)       │
      └───────────────────┬────────────────────────┘
                          │
      ┌───────────────────┼────────────────────────┐
      ▼                   ▼                        ▼
┌───────────┐      ┌───────────┐           ┌───────────┐
│   Kafka   │      │   Redis   │           │   gRPC    │
│ (Events)  │      │ (Pub/Sub) │           │  (RPC)    │
└───────────┘      └───────────┘           └───────────┘
```

### Kafka Event Topics

| Topic                  | Producer(s) | Consumer(s)                   |
| ---------------------- | ----------- | ----------------------------- |
| `stream.events`        | Streaming   | Analytics, Chat, Notification |
| `chat.messages`        | Chat        | Analytics, Moderation         |
| `payment.transactions` | Payment     | Analytics, Notification       |
| `user.events`          | Auth        | Analytics, Recommendation     |
| `moderation.actions`   | Moderation  | Chat, Streaming, Notification |
| `device.commands`      | Devices     | Analytics                     |

### Redis Pub/Sub Channels

| Channel                | Purpose                                       |
| ---------------------- | --------------------------------------------- |
| `stream:{id}:viewers`  | Real-time viewer count updates                |
| `stream:{id}:chat`     | Socket.io adapter for horizontal chat scaling |
| `user:{id}:presence`   | Online/offline presence                       |
| `device:{id}:commands` | Device command relay                          |

---

## Database Architecture

### Polyglot Persistence

| Database       | Engine        | Purpose                                 | Data Volume   |
| -------------- | ------------- | --------------------------------------- | ------------- |
| **PostgreSQL** | Prisma ORM    | Users, payments, subscriptions, content | ~10M records  |
| **MongoDB**    | Native driver | Chat messages, notifications, streams   | ~100M records |
| **ClickHouse** | Native        | Time-series analytics events            | ~1B events    |
| **Redis**      | ioredis       | Cache, sessions, pub/sub, leaderboards  | ~1GB          |

### PostgreSQL Schema (via Zod)

#### Users

| Field          | Type   | Description                        |
| -------------- | ------ | ---------------------------------- |
| `id`           | UUID   | Primary key                        |
| `email`        | string | Unique email                       |
| `username`     | string | Display username (3-30 chars)      |
| `role`         | enum   | viewer, creator, admin, moderator  |
| `status`       | enum   | active, suspended, banned, deleted |
| `tokenBalance` | int    | Current token balance              |
| `isCreator`    | bool   | Has broadcasting privileges        |
| `isVerified`   | bool   | Identity verified                  |

#### Streams

| Field             | Type   | Description                                                                      |
| ----------------- | ------ | -------------------------------------------------------------------------------- |
| `id`              | UUID   | Primary key                                                                      |
| `creatorId`       | UUID   | FK to users                                                                      |
| `title`           | string | Stream title (max 200)                                                           |
| `status`          | enum   | offline, starting, live, paused, ending, ended                                   |
| `visibility`      | enum   | public, private, subscribers, unlisted                                           |
| `viewerCount`     | int    | Current viewers                                                                  |
| `peakViewerCount` | int    | Peak viewers this session                                                        |
| `isExplicit`      | bool   | True for `sensual` tier (music-video cap). Column name retained for back-compat. |

#### Transactions

| Field          | Type | Description                                                                  |
| -------------- | ---- | ---------------------------------------------------------------------------- |
| `id`           | UUID | Primary key                                                                  |
| `userId`       | UUID | Initiating user                                                              |
| `targetUserId` | UUID | Recipient (for tips)                                                         |
| `type`         | enum | deposit, withdrawal, tip, subscription, purchase, refund, payout, fee, bonus |
| `status`       | enum | pending, processing, completed, failed, cancelled, refunded                  |
| `amount`       | int  | Gross amount (tokens/cents)                                                  |
| `fee`          | int  | Platform fee                                                                 |
| `netAmount`    | int  | Net amount after fee                                                         |

#### Content Items

| Field       | Type   | Description                         |
| ----------- | ------ | ----------------------------------- |
| `id`        | UUID   | Primary key                         |
| `creatorId` | UUID   | Content creator                     |
| `type`      | enum   | photo, video, audio, bundle         |
| `status`    | enum   | draft, published, archived, deleted |
| `fileUrl`   | string | S3/CDN file URL                     |
| `price`     | int    | Price in tokens (0 = free)          |

---

## Streaming Pipeline

### Ingest to Playback Flow

```
Broadcaster (OBS/Browser)
         │
         ├──── RTMP (port 1935) ────►  RTMP Ingest Server
         │                                    │
         ├──── WebRTC (signaling) ──►  WebRTC Signaling
         │                                    │
         └────────────────────────────────────┘
                                              │
                                              ▼
                                    ┌──────────────────┐
                                    │   Transcoding    │
                                    │   (FFmpeg/GPU)   │
                                    │                  │
                                    │  Input: RTMP/RTP │
                                    │  Output:         │
                                    │   • HLS (ABR)    │
                                    │   • DASH         │
                                    │   • Low-latency  │
                                    │   • Thumbnails   │
                                    └────────┬─────────┘
                                             │
                              ┌──────────────┼──────────────┐
                              ▼              ▼              ▼
                         ┌─────────┐  ┌──────────┐  ┌──────────┐
                         │   CDN   │  │ Recording│  │ Analytics│
                         │(S3/CF)  │  │ (S3/VOD) │  │ (metrics)│
                         └────┬────┘  └──────────┘  └──────────┘
                              │
                              ▼
                    ┌──────────────────┐
                    │     Viewers      │
                    │  (HLS/DASH/LL)   │
                    └──────────────────┘
```

### Streaming Endpoints

| Method | Path                 | Purpose                               |
| ------ | -------------------- | ------------------------------------- |
| POST   | `/api/streams`       | Create a new stream session           |
| POST   | `/api/ingest/rtmp`   | RTMP ingest authentication callback   |
| POST   | `/api/ingest/webrtc` | WebRTC signaling                      |
| POST   | `/api/transcoding`   | Start a transcoding job               |
| GET    | `/api/distribution`  | Get playback URLs (HLS/DASH)          |
| POST   | `/api/recording`     | Start/stop stream recording           |
| POST   | `/api/thumbnails`    | Generate stream thumbnails            |
| GET    | `/api/quality`       | Stream quality metrics (bitrate, FPS) |
| GET    | `/api/discovery`     | Discover live streams (browse/search) |

---

## Payment Architecture

### Payment Flow

```
Viewer                        Platform                     Provider
  │                              │                            │
  ├── Purchase Tokens ──────────►│                            │
  │                              ├── Redirect to Checkout ───►│
  │                              │                            │
  │                              │◄── Webhook (success) ──────┤
  │                              │                            │
  │   ◄── Tokens Credited ──────┤                            │
  │                              │                            │
  ├── Send Tip (100 tokens) ───►│                            │
  │                              │                            │
  │                              ├── Debit viewer (100)       │
  │                              ├── Credit creator (80)      │
  │                              ├── Platform fee (20%)       │
  │                              ├── Emit tip event           │
  │                              │                            │
  │   ◄── Tip Confirmation ─────┤                            │
  │                              │                            │
```

### Payment Providers

| Provider   | Type                | Integration                               |
| ---------- | ------------------- | ----------------------------------------- |
| **CCBill** | Adult-specialized   | Redirect checkout, webhook callbacks      |
| **Epoch**  | Adult-specialized   | Redirect checkout, webhook callbacks      |
| **Segpay** | Adult-specialized   | Redirect checkout, webhook callbacks      |
| **Stripe** | General (non-adult) | Direct API, payment intents               |
| **Crypto** | Cryptocurrency      | BTC, ETH, Monero, Zcash via custom wallet |

### Revenue Sharing

Default platform fee: 20%. Creator receives 80% of tips and subscriptions.
Custom splits configurable per creator via `@aphrodite/revenue-sharing`.

---

## Device Integration Architecture

### Device Protocol Stack

```
┌──────────────────────────────────┐
│        Application Layer          │
│  @aphrodite/device-protocols      │
│  (Unified command interface)      │
└──────────────┬───────────────────┘
               │
    ┌──────────┼──────────────────────┐
    ▼          ▼          ▼           ▼
┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐
│Lovense │ │Kiiroo  │ │ Handy  │ │OhMiBod │
│Protocol│ │Protocol│ │Protocol│ │Protocol│
└───┬────┘ └───┬────┘ └───┬────┘ └───┬────┘
    │          │          │           │
    └──────────┴──────────┴───────────┘
               │
    ┌──────────┴──────────────────────┐
    ▼                                 ▼
┌──────────────┐            ┌──────────────┐
│  Bluetooth   │            │   HTTP/WS    │
│  (buttplug)  │            │  (cloud API) │
└──────────────┘            └──────────────┘
```

### Haptic Communication Layers

| Layer          | Library                            | Purpose                             |
| -------------- | ---------------------------------- | ----------------------------------- |
| Base haptics   | `@aphrodite/haptics`               | Pattern engine, intensity control   |
| Bidirectional  | `@aphrodite/bidirectional-haptics` | Two-way device sync                 |
| Motion-based   | `@aphrodite/motion-haptics`        | Accelerometer/gyro-driven patterns  |
| Audio-reactive | `@aphrodite/audio-haptics`         | Sound amplitude to haptic mapping   |
| VR-specific    | `@aphrodite/vr-haptics`            | Spatial haptics for VR environments |

### Device Service WebSocket Protocol

The Devices service (`apps/aphrodite/devices`, port 4003) uses WebSocket for
real-time device control:

```
Client                          Device Service
  │                                │
  ├── connect (device_id) ────────►│
  │                                │
  ◄── device_connected ───────────┤
  │                                │
  ├── command { vibrate: 50 } ───►│ ──► Device (Bluetooth/HTTP)
  │                                │
  ├── pattern { name: "wave" } ──►│ ──► Device
  │                                │
  ◄── device_status ──────────────┤
  │                                │
```

---

## VR/AR Architecture

### VR Streaming Pipeline

```
Broadcaster Camera (180/360 VR)
         │
         ▼
   ┌─────────────────┐
   │  VR Capture     │
   │  (Stereo encode)│
   └────────┬────────┘
            │
            ▼
   ┌─────────────────┐
   │  VR Transcoding │
   │  (SBS/TB/EAC)   │
   │  Quality Presets │
   └────────┬────────┘
            │
            ▼
   ┌─────────────────┐
   │  VR Distribution│
   │  (Adaptive ABR) │
   └────────┬────────┘
            │
    ┌───────┼───────┐
    ▼       ▼       ▼
 ┌──────┐ ┌────┐ ┌──────┐
 │Quest │ │Web │ │Other │
 │(native)│VR  │ │HMDs  │
 └──────┘ └────┘ └──────┘
```

### VR Quality Presets

| Preset | Resolution | Bitrate | FOV | Use Case              |
| ------ | ---------- | ------- | --- | --------------------- |
| Low    | 2048x1024  | 5 Mbps  | 180 | Mobile, low bandwidth |
| Medium | 3840x1920  | 15 Mbps | 180 | Desktop VR            |
| High   | 5760x2880  | 30 Mbps | 180 | High-end HMDs         |
| Ultra  | 7680x3840  | 50 Mbps | 360 | Professional capture  |

---

## Security and Compliance

### Age Verification Flow

```
User ──► Sign Up ──► Age Gate (DOB + document) ──► Verification Provider
                                                          │
                                                     ┌────┴────┐
                                                     │ Verified │  ──► Access Granted
                                                     │ Rejected │  ──► Access Denied
                                                     └─────────┘
```

### Compliance Stack

| Requirement          | Library                           | Description                    |
| -------------------- | --------------------------------- | ------------------------------ |
| Age verification     | `@aphrodite/age-verification`     | Multi-provider identity checks |
| 18 U.S.C. 2257       | `@aphrodite/compliance-2257`      | Performer record-keeping       |
| GDPR                 | `@aphrodite/gdpr-compliance`      | Data export, deletion, consent |
| DRM                  | `@aphrodite/drm`                  | Encrypted media delivery       |
| Watermarking         | `@aphrodite/stream-watermarking`  | Invisible forensic watermarks  |
| Recording prevention | `@aphrodite/recording-prevention` | Screen capture deterrence      |
| Content takedown     | `@aphrodite/content-takedown`     | DMCA notice processing         |
| E2E encryption       | `@aphrodite/e2e-encryption`       | Private message encryption     |

### Security Layers

1. **Transport**: TLS 1.3 for all connections
2. **Authentication**: JWT (short-lived access + refresh tokens)
3. **Authorization**: Role-based (viewer, creator, admin, moderator)
4. **Data**: AES-256 encryption at rest, E2E for DMs
5. **Media**: DRM, watermarking, recording prevention
6. **Compliance**: Age verification, 2257 records, GDPR consent tracking

---

## Data Flow

### Tip Flow (End-to-End)

```
1. Viewer clicks "Send Tip" (100 tokens)
2. Viewer Service validates balance → Payment Service
3. Payment Service:
   a. Debit viewer token balance (-100)
   b. Calculate fee (20% = 20 tokens)
   c. Credit creator balance (+80)
   d. Create transaction records
   e. Publish tip event → Kafka
4. Kafka consumers:
   a. Chat Service → show tip message in chat
   b. Analytics → record tip event in ClickHouse
   c. Notification → push notification to creator
   d. Device Service → trigger tip-linked device pattern
   e. Gamification → check tip achievements
5. Stream overlay shows tip animation
```

### Stream Lifecycle

```
1. Broadcaster creates stream → Streaming Service (POST /api/streams)
2. Broadcaster starts OBS → RTMP ingest (port 1935)
3. Streaming Service authenticates stream key
4. Transcoding starts → HLS/DASH segments generated
5. CDN distributes segments
6. Viewers connect → Viewer Service fetches playback URLs
7. Real-time analytics track viewer count
8. Chat Service opens room for stream
9. Stream ends → Recording finalized → VOD processed
```

---

## Cross-Domain Dependencies

### Outbound (Aphrodite using shared libraries)

| Library            | Purpose                          |
| ------------------ | -------------------------------- |
| `@oshun/database`  | Database connection utilities    |
| `@oshun/config`    | Configuration management         |
| `@oshun/logging`   | Structured logging               |
| `@oshun/event-bus` | Cross-domain event communication |

### External Integrations

| Category           | Providers                                    |
| ------------------ | -------------------------------------------- |
| Payment            | CCBill, Epoch, Segpay, Stripe                |
| Device protocols   | Lovense, Kiiroo, Handy, OhMiBod, Buttplug.io |
| Push notifications | Firebase FCM, APNs                           |
| Email              | SendGrid                                     |
| CDN                | AWS CloudFront, S3                           |
| VR platforms       | Meta Quest (native SDK)                      |
| Content moderation | Custom AI models                             |

---

## Deployment Architecture

### Container Layout

```
┌──────────────────────────────────────────────────────────────────┐
│                        Kubernetes Cluster                          │
├──────────────────────────────────────────────────────────────────┤
│                                                                    │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐            │
│  │  auth (x3)    │  │ streaming(x5)│  │  chat (x5)   │            │
│  │  :3003        │  │  :3003       │  │  :5000       │            │
│  └──────────────┘  └──────────────┘  └──────────────┘            │
│                                                                    │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐            │
│  │  payment(x3) │  │  viewer(x5)  │  │ broadcaster  │            │
│  │  :4000       │  │  :3002       │  │  (x3) :3100  │            │
│  └──────────────┘  └──────────────┘  └──────────────┘            │
│                                                                    │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐            │
│  │  devices(x3) │  │  cdn (x2)    │  │  admin (x2)  │            │
│  │  :4003       │  │  :3005       │  │  :3004       │            │
│  └──────────────┘  └──────────────┘  └──────────────┘            │
│                                                                    │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐            │
│  │  vr (x2)     │  │  analytics   │  │ rt-analytics │            │
│  │  :3008       │  │  (x3)       │  │  (x2) :3450  │            │
│  └──────────────┘  └──────────────┘  └──────────────┘            │
│                                                                    │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐            │
│  │  PostgreSQL  │  │  MongoDB     │  │  ClickHouse  │            │
│  │ (StatefulSet)│  │ (ReplicaSet) │  │ (Cluster)    │            │
│  └──────────────┘  └──────────────┘  └──────────────┘            │
│                                                                    │
│  ┌──────────────┐  ┌──────────────┐                              │
│  │  Redis       │  │  Kafka       │                              │
│  │  (Cluster)   │  │  (Cluster)   │                              │
│  └──────────────┘  └──────────────┘                              │
│                                                                    │
└──────────────────────────────────────────────────────────────────┘
```

### Environment Variables (Key Variables)

| Variable                    | Default | Description            |
| --------------------------- | ------- | ---------------------- |
| `APHRODITE_DATABASE_URL`    | --      | PostgreSQL connection  |
| `APHRODITE_REDIS_URL`       | --      | Redis connection       |
| `APHRODITE_MONGO_URL`       | --      | MongoDB connection     |
| `APHRODITE_KAFKA_BROKERS`   | --      | Kafka broker list      |
| `APHRODITE_S3_BUCKET`       | --      | Media storage bucket   |
| `APHRODITE_CDN_URL`         | --      | CDN base URL           |
| `APHRODITE_STRIPE_KEY`      | --      | Stripe API key         |
| `APHRODITE_CCBILL_ACCOUNT`  | --      | CCBill account number  |
| `APHRODITE_JWT_SECRET`      | --      | JWT signing secret     |
| `APHRODITE_ENCRYPTION_KEY`  | --      | Data encryption key    |
| `APHRODITE_LOVENSE_TOKEN`   | --      | Lovense API token      |
| `APHRODITE_BUTTPLUG_SERVER` | --      | Buttplug WebSocket URL |

---

## Technology Stack

| Component          | Technology                                    |
| ------------------ | --------------------------------------------- |
| Language           | TypeScript (Node.js)                          |
| API Framework      | Hono with `@hono/zod-openapi`                 |
| WebSocket          | Socket.io (chat), ws (devices, VR, analytics) |
| Build              | tsup (services), Nx orchestration             |
| Testing            | Vitest                                        |
| Databases          | PostgreSQL, MongoDB, ClickHouse, Redis        |
| Message Broker     | Apache Kafka                                  |
| Streaming          | RTMP (nginx-rtmp), WebRTC, HLS/DASH           |
| CDN                | AWS CloudFront + S3                           |
| VR                 | WebXR, Meta Quest SDK                         |
| Mobile             | React Native                                  |
| Monitoring         | Prometheus metrics, health probes             |
| Validation         | Zod schemas                                   |
| Authentication     | JWT, OAuth2, TOTP (2FA)                       |
| Service-to-Service | gRPC, Kafka, Redis Pub/Sub                    |
