Architecture Documentation

April 12, 2026 ยท View on GitHub

This document details the technical architecture, design decisions, and implementation details of 0trace.

๐Ÿ“ Overall Architecture

System Architecture Diagram

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Sender     โ”‚                                    โ”‚  Receiver   โ”‚
โ”‚  Browser    โ”‚                                    โ”‚  Browser    โ”‚
โ”‚             โ”‚                                    โ”‚             โ”‚
โ”‚  WebRTC     โ”‚                                    โ”‚  WebRTC     โ”‚
โ”‚  JavaScript โ”‚                                    โ”‚  JavaScript โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜                                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜
       โ”‚                                                  โ”‚
       โ”‚ WebSocket Signaling                             โ”‚ WebSocket Signaling
       โ”‚ (SDP/ICE)                                       โ”‚ (SDP/ICE)
       โ”‚                                                  โ”‚
       โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                          โ”‚
                    โ”Œโ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚ Rust      โ”‚
                    โ”‚ Backend   โ”‚
                    โ”‚           โ”‚
                    โ”‚ Axum      โ”‚
                    โ”‚ + Tokio   โ”‚
                    โ”‚ + WebSocketโ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                          โ”‚
                          โ”‚ Signaling relay
                          โ”‚ Room management
                          โ”‚
       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
       โ”‚                                     โ”‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”                      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Sender     โ”‚                      โ”‚  Receiver   โ”‚
โ”‚  DataChannelโ”‚โ—„โ”€โ”€โ”€โ”€P2P Directโ”€โ”€โ”€โ”€โ”€โ–บโ”‚  DataChannelโ”‚
โ”‚  (File Data)โ”‚    (DTLS encrypted) โ”‚  (File Data)โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Core Workflow

  1. Room Creation: Sender creates a room, gets an 8-digit pickup code
  2. Signaling Exchange: Both parties exchange SDP and ICE candidates via WebSocket
  3. P2P Connection: WebRTC establishes peer-to-peer connection with multiple STUN servers
  4. File Transfer: Transfer file data via DataChannel (streaming mode for large files)
  5. Auto Cleanup: Room automatically expires after 5 minutes of inactivity
  6. Keep-Alive: WebSocket heartbeat and auto-reconnect maintain connection stability

๐Ÿ—๏ธ Technology Stack

Backend

ComponentVersionPurpose
Rust1.75+Systems programming language
Axum0.7Web framework
Tokio1.35Async runtime
Tower0.4Middleware
Serde1.0Serialization/deserialization

Frontend

ComponentDescription
Vanilla JavaScriptNo framework, stays lightweight
WebRTC APIBrowser-native P2P
WebSocket APISignaling communication
Fetch APIHTTP requests

Protocols

  • Signaling Protocol: WebSocket + JSON
  • Transport Protocol: WebRTC DataChannel
  • Encryption: DTLS/SRTP (WebRTC built-in)

๐Ÿ“ Project Structure

0trace/
โ”œโ”€โ”€ shared/                      # Shared library
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”œโ”€โ”€ lib.rs               # Library entry point
โ”‚   โ”‚   โ”œโ”€โ”€ protocol.rs          # Protocol definitions
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ SignalMessage    # Signaling messages
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ TransferMessage  # Transfer messages
โ”‚   โ”‚   โ””โ”€โ”€ room.rs              # Room logic
โ”‚   โ”‚       โ”œโ”€โ”€ RoomStatus       # Room status
โ”‚   โ”‚       โ””โ”€โ”€ generate_code()  # Pickup code generation
โ”‚   โ””โ”€โ”€ Cargo.toml
โ”‚
โ”œโ”€โ”€ backend/                     # Backend service
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”œโ”€โ”€ main.rs              # Server entry point
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ HTTP routes
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ Static file service
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ CORS configuration
โ”‚   โ”‚   โ”œโ”€โ”€ room.rs              # Room manager
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ RoomManager      # Room management
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ create_room()    # Create room
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ join_room()      # Join room
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ cleanup_expired()# Cleanup expired rooms
โ”‚   โ”‚   โ””โ”€โ”€ ws.rs                # WebSocket handling
โ”‚   โ”‚       โ”œโ”€โ”€ handle_ws()      # Connection handling
โ”‚   โ”‚       โ””โ”€โ”€ forward_signal() # Signaling relay
โ”‚   โ”œโ”€โ”€ static/                  # Static files (production)
โ”‚   โ””โ”€โ”€ Cargo.toml
โ”‚
โ””โ”€โ”€ frontend/                    # Frontend development
    โ””โ”€โ”€ static/
        โ”œโ”€โ”€ index.html           # Main page
        โ”œโ”€โ”€ app.js               # Core logic
        โ”‚   โ”œโ”€โ”€ WebRTCConnection # WebRTC management
        โ”‚   โ””โ”€โ”€ App              # UI control
        โ”œโ”€โ”€ style.css            # Styles
        โ”œโ”€โ”€ i18n.js              # Multilingual system
        โ””โ”€โ”€ i18n/                # Translation files
            โ”œโ”€โ”€ zh-CN.json
            โ”œโ”€โ”€ en.json
            โ”œโ”€โ”€ ja.json
            โ”œโ”€โ”€ ko.json
            โ”œโ”€โ”€ es.json
            โ””โ”€โ”€ fr.json

๐Ÿ”Œ API Design

HTTP API

Create Room

POST /api/create-room
Response: {"success": true, "code": "ABC123"}

Query Room

GET /api/room-info?code=ABC123
Response: {"exists": true, "sender_connected": true, "receiver_connected": false}

WebSocket API

Connection

ws://localhost:2029/api/ws?code=ABC123&role=sender

Signaling Messages

// Offer
{"type": "offer", "sdp": "..."}

// Answer
{"type": "answer", "sdp": "..."}

// ICE Candidate
{"type": "ice-candidate", "candidate": "..."}

// Peer joined
{"type": "peer-joined", "role": "receiver"}

// Peer left
{"type": "peer-left"}

// Error
{"type": "error", "message": "..."}

๐Ÿ” Security Design

Transport Security

  1. WebRTC Encryption

    • DTLS (Datagram Transport Layer Security)
    • SRTP (Secure Real-time Transport Protocol)
    • End-to-end encryption, server cannot decrypt
  2. Signaling Security

    • WebSocket connection (WSS in production)
    • Pickup code verification
    • Room capacity limit (max 2 people)
  3. Data Privacy

    • Zero server storage
    • Only forwards signaling messages
    • No file content logging

Room Security

Pickup Code Design

const CHARS: &[u8] = b"123456789ABCDEFGHIJKLMNPQRSTUVWXYZ";
// Excludes 0 and O to avoid confusion
// $34^{6}$ โ‰ˆ 1.5 billion combinations

Expiration Mechanism

  • Creation timestamp recorded
  • Auto-cleanup after 1 hour
  • Periodic scan for expired rooms

๐Ÿ“ก Transfer Protocol

File Transfer Flow

1. Sender โ†’ Receiver: File metadata
   {"type": "file-meta", "name": "test.jpg", "size": 1024000, "mimeType": "image/jpeg"}

2. Sender โ†’ Receiver: Chunk info + data
   {"type": "chunk-info", "index": 0, "total": 4}
   [ArrayBuffer: 256KB data]

3. Repeat step 2 until all chunks transferred

4. Sender โ†’ Receiver: Transfer complete
   {"type": "complete"}

5. Receiver: Assemble file and trigger download

Chunking Strategy

const CHUNK_SIZE = 256 * 1024; // 256KB

// Advantages:
// - Reduces memory footprint
// - Real-time progress updates
// - Supports large files
// - Lowers transfer failure risk

๐ŸŽจ Frontend Design

WebRTC Connection Management

class WebRTCConnection {
    constructor() {
        this.pc = null;           // RTCPeerConnection
        this.dc = null;           // RTCDataChannel
        this.ws = null;           // WebSocket
        this.role = null;         // 'sender' | 'receiver'
    }

    // Core methods
    async createRoom()            // Create room
    async joinRoom(code)          // Join room
    setupPeerConnection()         // Setup PeerConnection
    setupDataChannel()            // Setup DataChannel
    async sendFile(file)          // Send file
    handleFileReceive()           // Receive file
}

UI Control

class App {
    constructor() {
        this.connection = null;
        this.selectedFiles = null;
    }

    // Core methods
    async init()                  // Initialize (i18n + events)
    initModals()                  // Initialize modals
    handleFilesSelect(files)      // Handle file selection
    async sendFiles()             // Send multiple files
    async joinRoom(code)          // Join room
    showToast(message, type)      // Show notification
}

Multilingual System

class I18n {
    async init()                  // Initialize (auto-detect language)
    async loadLanguage(lang)      // Load translation file
    t(key)                        // Translation function
    updateUI()                    // Update UI text
}

// Usage
i18n.t('send.copyLink')          // โ†’ "Copy Link"

๐Ÿ”„ State Management

Room State

pub struct Room {
    pub code: String,
    pub created_at: Instant,
    pub sender: Option<SplitSink<WebSocket, Message>>,
    pub receiver: Option<SplitSink<WebSocket, Message>>,
}

pub enum RoomStatus {
    WaitingSender,
    WaitingReceiver,
    Connected,
    Expired,
}

Connection State

// WebRTC connection state
'new' โ†’ 'connecting' โ†’ 'connected' โ†’ 'disconnected' | 'failed'

// DataChannel state
'connecting' โ†’ 'open' โ†’ 'closing' โ†’ 'closed'

โšก Performance Optimization

Backend Optimization

  1. Async I/O

    • Tokio async runtime
    • Non-blocking WebSocket
    • High concurrency support
  2. Memory Management

    • RwLock read-write lock
    • Periodic cleanup of expired rooms
    • Zero-copy message forwarding
  3. Compile Optimization

    [profile.release]
    opt-level = 3
    lto = true
    codegen-units = 1
    

Frontend Optimization

  1. Chunked Transfer

    • 256KB chunk size
    • Avoids memory overflow
    • Real-time progress updates
  2. Resource Optimization

    • No framework dependencies
    • Compressed icon resources
    • CSS variable reuse
  3. User Experience

    • Toast instead of alert
    • Smooth animations
    • Responsive design

๐Ÿ› Known Issues and Solutions

1. Connection Timing Issue

Problem: Sender creates offer too early, receiver not ready

Solution:

// Sender waits for peer-joined message
case 'peer-joined':
    if (this.role === 'sender') {
        this.createOffer();
    }
    break;

2. Room Premature Deletion

Problem: One party leaving causes room deletion, other cannot join

Solution:

// Remove is_empty() check, rely only on 1-hour expiration
pub async fn leave_room(&self, code: &str, role: Role) {
    let mut rooms = self.rooms.write().await;
    if let Some(room) = rooms.get_mut(code) {
        room.remove_client(role);
        // Do not delete room immediately
    }
}

3. NAT Traversal

Problem: Symmetric NAT cannot establish P2P connection

Solution:

  • Short-term: Use STUN server (already configured)
  • Long-term: Integrate TURN server (relay)

๐Ÿ“Š Performance Metrics

MetricValue
Backend binary size< 2MB (release)
Frontend asset size< 100KB (including icons)
Memory usage< 10MB (idle)
Startup time< 10ms
Concurrent rooms1000+ (depends on memory)
Transfer speed10-50 MB/s (LAN)

๐Ÿ”ฎ Future Optimizations

Short-term (1-3 months)

  • Add transfer speed display
  • Support resumable transfers
  • Add file preview
  • Optimize large file transfers (streaming)

Medium-term (3-6 months)

  • Integrate TURN server
  • Add file encryption option
  • Support batch transfer queue
  • Mobile PWA optimization

Long-term (6-12 months)

  • Text message transfer
  • QR code sharing
  • Transfer history (optional)
  • Custom STUN/TURN configuration

๐Ÿ“š References

๐Ÿค Design Principles

  1. Simplicity over complexity - Avoid over-engineering
  2. Performance over features - Keep it lightweight and efficient
  3. Security over convenience - Privacy first
  4. User experience over technical flair - Practicality-focused

Last updated: 2026-04-07