Ring Platform Logo

    Завантаження документації...

    Підготовка контенту платформи Ring

    Documentation

    Welcome — mission & audiences

    Welcome to Ring Platform - Gateway Between Humanity and the Quantum World

    Library hub

    Welcome to Ring Platform - Gateway Between Humanity and the Quantum World

    Getting Started

    Index
    Prerequisites
    Installation
    Database migrations
    First Success Validation
    Troubleshooting
    Next Steps

    Architecture

    Index
    Backend modes and databases
    Data Model
    Authentication Architecture
    Email AI-CRM Architecture
    PaymentConductor architecture
    News Kingdom architecture
    Proxy and internationalization
    Real Time
    Security

    Features

    Platform Features
    Authentication
    Email AI-CRM System
    Entities
    Opportunities
    Notifications
    Push Notifications with FCM (Ring-Powered)
    Web3 Wallet
    Multi-Vendor Store
    Payment Integration
    PaymentConductor
    WayForPay Payment Integration
    News Module - Digital Newspaper Experience

    API

    Index
    Authentication
    Email AI-CRM API
    Entities
    Opportunities
    Messaging API
    Notifications API
    Wallet
    Store API

    CLI

    Ring CLI (enterprise only)

    Customization

    Index
    Branding
    Features
    Localization
    Themes
    Components

    Deployment

    Index
    Self-hosted deployment
    Vercel
    Docker
    Environment Configuration
    Monitoring & Analytics
    Performance Optimization
    Backup & Recovery

    Development

    Index
    Local Setup
    Code Structure
    Community tooling
    Ring MCP Server
    OSS vs enterprise
    Whitelabel Navigation
    Best Practices

    Examples

    Index
    Quick Start
    Authentication
    Email AI-CRM Tutorial
    Api Integration
    Web3 Integration
    White Label
    Real World

    Integrations

    Ethereum wallets (Wagmi v3)

    Quick entry (CTOs · auditors · agents)

    Library hub
    Welcome — mission & audiences
    Getting started
    Architecture & Auth.js
    Backend modes & databases (DB_BACKEND_MODE)
    Self-hosted
    Ring MCP
    Deploy (Docker · k8s)
    Security & compliance reads
    Ring Platform Logo

    Завантаження документації...

    Підготовка контенту платформи Ring

    Documentation

    Welcome — mission & audiences

    Welcome to Ring Platform - Gateway Between Humanity and the Quantum World

    Library hub

    Welcome to Ring Platform - Gateway Between Humanity and the Quantum World

    Getting Started

    Index
    Prerequisites
    Installation
    Database migrations
    First Success Validation
    Troubleshooting
    Next Steps

    Architecture

    Index
    Backend modes and databases
    Data Model
    Authentication Architecture
    Email AI-CRM Architecture
    PaymentConductor architecture
    News Kingdom architecture
    Proxy and internationalization

    Features

    Platform Features
    Authentication
    Email AI-CRM System
    Entities
    Opportunities
    Notifications
    Push Notifications with FCM (Ring-Powered)
    Web3 Wallet

    API

    Index
    Authentication
    Email AI-CRM API
    Entities
    Opportunities
    Messaging API
    Notifications API
    Wallet
    Store API

    CLI

    Ring CLI (enterprise only)

    Customization

    Index
    Branding
    Features
    Localization
    Themes
    Components

    Deployment

    Index
    Self-hosted deployment
    Vercel
    Docker
    Environment Configuration
    Monitoring & Analytics
    Performance Optimization
    Backup & Recovery

    Development

    Index
    Local Setup
    Code Structure
    Community tooling
    Ring MCP Server
    OSS vs enterprise
    Whitelabel Navigation
    Best Practices

    Examples

    Index
    Quick Start
    Authentication
    Email AI-CRM Tutorial
    Api Integration
    Web3 Integration
    White Label
    Real World

    Integrations

    Ethereum wallets (Wagmi v3)

    Quick entry (CTOs · auditors · agents)

    Library hub
    Welcome — mission & audiences
    Getting started
    Architecture & Auth.js
    Backend modes & databases (DB_BACKEND_MODE)
    Self-hosted
    Ring MCP
    Deploy (Docker · k8s)
    Security & compliance reads
    Ring Platform Logo

    Завантаження документації...

    Підготовка контенту платформи Ring

    Documentation

    Welcome — mission & audiences

    Welcome to Ring Platform - Gateway Between Humanity and the Quantum World

    Library hub

    Welcome to Ring Platform - Gateway Between Humanity and the Quantum World

    Getting Started

    Index
    Prerequisites
    Installation
    Database migrations
    First Success Validation
    Troubleshooting
    Next Steps

    Architecture

    Index
    Backend modes and databases
    Data Model
    Authentication Architecture
    Email AI-CRM Architecture
    PaymentConductor architecture
    News Kingdom architecture
    Proxy and internationalization

    Features

    Platform Features
    Authentication
    Email AI-CRM System
    Entities
    Opportunities
    Notifications
    Push Notifications with FCM (Ring-Powered)
    Web3 Wallet

    API

    Index
    Authentication
    Email AI-CRM API
    Entities
    Opportunities
    Messaging API
    Notifications API
    Wallet
    Store API

    CLI

    Ring CLI (enterprise only)

    Customization

    Index
    Branding
    Features
    Localization
    Themes
    Components

    Deployment

    Index
    Self-hosted deployment
    Vercel
    Docker
    Environment Configuration
    Monitoring & Analytics
    Performance Optimization
    Backup & Recovery

    Development

    Index
    Local Setup
    Code Structure
    Community tooling
    Ring MCP Server
    OSS vs enterprise
    Whitelabel Navigation
    Best Practices

    Examples

    Index
    Quick Start
    Authentication
    Email AI-CRM Tutorial
    Api Integration
    Web3 Integration
    White Label
    Real World

    Integrations

    Ethereum wallets (Wagmi v3)

    Quick entry (CTOs · auditors · agents)

    Library hub
    Welcome — mission & audiences
    Getting started
    Architecture & Auth.js
    Backend modes & databases (DB_BACKEND_MODE)
    Self-hosted
    Ring MCP
    Deploy (Docker · k8s)
    Security & compliance reads
    Member Blogs
    Scientific Editor
    Locale System
    Security & Compliance
    NFT Marketplace
    Token Staking System
    Performance Optimization Patterns
    Mobile Experience
    Admin API
    Workflow
    Code Style
    Performance
    Testing
    Deployment
    Debugging
    Contributing
    Api Examples
    ringdom.org — LegioX homebase
    Source — MIT license (GitHub)
    Real Time
    Security
    Multi-Vendor Store
    Payment Integration
    PaymentConductor
    WayForPay Payment Integration
    News Module - Digital Newspaper Experience
    Member Blogs
    Scientific Editor
    Locale System
    Security & Compliance
    NFT Marketplace
    Token Staking System
    Performance Optimization Patterns
    Mobile Experience
    Admin API
    Workflow
    Code Style
    Performance
    Testing
    Deployment
    Debugging
    Contributing
    Api Examples
    ringdom.org — LegioX homebase
    Source — MIT license (GitHub)
    Real Time
    Security
    Multi-Vendor Store
    Payment Integration
    PaymentConductor
    WayForPay Payment Integration
    News Module - Digital Newspaper Experience
    Member Blogs
    Scientific Editor
    Locale System
    Security & Compliance
    NFT Marketplace
    Token Staking System
    Performance Optimization Patterns
    Mobile Experience
    Admin API
    Workflow
    Code Style
    Performance
    Testing
    Deployment
    Debugging
    Contributing
    Api Examples
    ringdom.org — LegioX homebase
    Source — MIT license (GitHub)

    🚇 Tunnel Protocol

    Ring's Multi-Transport Real-Time Communication

    Tunnel Protocol is Ring Platform's intelligent real-time communication system - the Ring analog to Firebase Realtime Database. It provides unified real-time messaging across WebSocket, Server-Sent Events (SSE), Supabase Realtime, and Long-Polling transports with automatic fallback and Edge Runtime compatibility.

    v1.6.0: lib/tunnel/disconnected-tunnel-context.ts preserves UX when the tunnel is offline; pair with Push notifications FCM for mobile alerts.

    🎯 Why Tunnel Protocol?

    The Problem with Firebase RTDB

    Firebase Realtime Database provides excellent real-time features but creates vendor lock-in:

    • ❌ Vendor Lock-in: Tied to Firebase infrastructure
    • ❌ Edge Runtime Incompatible: Cannot run on Vercel Edge
    • ❌ Cost Scaling: Pay-per-operation pricing
    • ❌ Limited Control: Cannot optimize for specific use cases
    • ❌ Single Transport: WebSocket only

    The Ring Solution: Tunnel Protocol

    ✅ Transport Abstraction: Unified API across 5+ transports
    ✅ Edge Runtime Compatible: SSE support for Vercel Edge
    ✅ Zero Vendor Lock-in: Use any backend (PostgreSQL, Supabase, Firebase)
    ✅ Intelligent Fallback: Automatic cascade on transport failures ✅ : Self-hosted options, pay only for infrastructure ✅ : Real-time features for unauthenticated users

    🚇 Tunnel Protocol

    Ring's Multi-Transport Real-Time Communication

    Tunnel Protocol is Ring Platform's intelligent real-time communication system - the Ring analog to Firebase Realtime Database. It provides unified real-time messaging across WebSocket, Server-Sent Events (SSE), Supabase Realtime, and Long-Polling transports with automatic fallback and Edge Runtime compatibility.

    v1.6.0: lib/tunnel/disconnected-tunnel-context.ts preserves UX when the tunnel is offline; pair with Push notifications FCM for mobile alerts.

    🎯 Why Tunnel Protocol?

    The Problem with Firebase RTDB

    Firebase Realtime Database provides excellent real-time features but creates vendor lock-in:

    • ❌ Vendor Lock-in: Tied to Firebase infrastructure
    • ❌ Edge Runtime Incompatible: Cannot run on Vercel Edge
    • ❌ Cost Scaling: Pay-per-operation pricing
    • ❌ Limited Control: Cannot optimize for specific use cases
    • ❌ Single Transport: WebSocket only

    The Ring Solution: Tunnel Protocol

    ✅ Transport Abstraction: Unified API across 5+ transports
    ✅ Edge Runtime Compatible: SSE support for Vercel Edge
    ✅ Zero Vendor Lock-in: Use any backend (PostgreSQL, Supabase, Firebase)
    ✅ Intelligent Fallback: Automatic cascade on transport failures ✅ : Self-hosted options, pay only for infrastructure ✅ : Real-time features for unauthenticated users

    🚇 Tunnel Protocol

    Ring's Multi-Transport Real-Time Communication

    Tunnel Protocol is Ring Platform's intelligent real-time communication system - the Ring analog to Firebase Realtime Database. It provides unified real-time messaging across WebSocket, Server-Sent Events (SSE), Supabase Realtime, and Long-Polling transports with automatic fallback and Edge Runtime compatibility.

    v1.6.0: lib/tunnel/disconnected-tunnel-context.ts preserves UX when the tunnel is offline; pair with Push notifications FCM for mobile alerts.

    🎯 Why Tunnel Protocol?

    The Problem with Firebase RTDB

    Firebase Realtime Database provides excellent real-time features but creates vendor lock-in:

    • ❌ Vendor Lock-in: Tied to Firebase infrastructure
    • ❌ Edge Runtime Incompatible: Cannot run on Vercel Edge
    • ❌ Cost Scaling: Pay-per-operation pricing
    • ❌ Limited Control: Cannot optimize for specific use cases
    • ❌ Single Transport: WebSocket only

    The Ring Solution: Tunnel Protocol

    ✅ Transport Abstraction: Unified API across 5+ transports
    ✅ Edge Runtime Compatible: SSE support for Vercel Edge
    ✅ Zero Vendor Lock-in: Use any backend (PostgreSQL, Supabase, Firebase)
    ✅ Intelligent Fallback: Automatic cascade on transport failures ✅ : Self-hosted options, pay only for infrastructure ✅ : Real-time features for unauthenticated users


    Cost Optimized

    Anonymous Support

    🏗️ Architecture Overview

    Ring Analog to Firebase RTDB

    Tunnel Protocol is Ring's equivalent to Firebase Realtime Database, providing the same real-time capabilities with multi-transport flexibility and zero vendor lock-in.

    Unified Transport API


    Cost Optimized

    Anonymous Support

    🏗️ Architecture Overview

    Ring Analog to Firebase RTDB

    Tunnel Protocol is Ring's equivalent to Firebase Realtime Database, providing the same real-time capabilities with multi-transport flexibility and zero vendor lock-in.

    Unified Transport API


    Cost Optimized

    Anonymous Support

    🏗️ Architecture Overview

    Ring Analog to Firebase RTDB

    Tunnel Protocol is Ring's equivalent to Firebase Realtime Database, providing the same real-time capabilities with multi-transport flexibility and zero vendor lock-in.

    Unified Transport API

    // Single API works across ALL transports
    import { publishToTunnel, subscribeToTunnel } from '@/lib/tunnel/publisher'
    
    // Publish message (works on any transport)
    await publishToTunnel(channel, eventType, data)
    
    // Subscribe to updates (works on any transport)
    const unsubscribe = subscribeToTunnel(channel, (message) => {
      console
    
    // Single API works across ALL transports
    import { publishToTunnel, subscribeToTunnel } from '@/lib/tunnel/publisher'
    
    // Publish message (works on any transport)
    await publishToTunnel(channel, eventType, data)
    
    // Subscribe to updates (works on any transport)
    const unsubscribe = subscribeToTunnel(channel, (message) => {
      console
    
    // Single API works across ALL transports
    import { publishToTunnel, subscribeToTunnel } from '@/lib/tunnel/publisher'
    
    // Publish message (works on any transport)
    await publishToTunnel(channel, eventType, data)
    
    // Subscribe to updates (works on any transport)
    const unsubscribe = subscribeToTunnel(channel, (message) => {
      console
    

    Supported Transports

    Supported Transports

    Supported Transports

    TransportLatencyThroughputUse Case
    WebSocket<50ms10K msg/sSelf-hosted, K8s clusters
    SSE<100ms1K msg/sVercel Edge Runtime
    Supabase Realtime<50ms5K msg/sSupabase deployments
    Firebase Realtime<200ms1K msg/sFirebase-full mode
    Long-Polling500ms-2s100 msg/sUltimate fallback
    TransportLatencyThroughputUse Case
    WebSocket<50ms10K msg/sSelf-hosted, K8s clusters
    SSE<100ms1K msg/sVercel Edge Runtime
    Supabase Realtime<50ms5K msg/sSupabase deployments
    Firebase Realtime<200ms1K msg/sFirebase-full mode
    Long-Polling500ms-2s100 msg/sUltimate fallback
    TransportLatencyThroughputUse Case
    WebSocket<50ms10K msg/sSelf-hosted, K8s clusters
    SSE<100ms1K msg/sVercel Edge Runtime
    Supabase Realtime<50ms5K msg/sSupabase deployments
    Firebase Realtime<200ms1K msg/sFirebase-full mode
    Long-Polling500ms-2s100 msg/sUltimate fallback

    🚀 Quick Start

    Publishing Real-Time Updates

    Replace Firebase RTDB calls with Tunnel:

    Before (Firebase RTDB):


    🚀 Quick Start

    Publishing Real-Time Updates

    Replace Firebase RTDB calls with Tunnel:

    Before (Firebase RTDB):


    🚀 Quick Start

    Publishing Real-Time Updates

    Replace Firebase RTDB calls with Tunnel:

    Before (Firebase RTDB):

    import { getAdminRtdb } from '@/lib/firebase-admin.server'
    
    const rtdb = getAdminRtdb()
    await rtdb.ref(`messages/${messageId}`).set(messageData)
    import { getAdminRtdb } from '@/lib/firebase-admin.server'
    
    const rtdb = getAdminRtdb()
    await rtdb.ref(`messages/${messageId}`).set(messageData)
    import { getAdminRtdb } from '@/lib/firebase-admin.server'
    
    const rtdb = getAdminRtdb()
    await rtdb.ref(`messages/${messageId}`).set(messageData)

    After (Tunnel Protocol):

    After (Tunnel Protocol):

    After (Tunnel Protocol):

    import { publishToTunnel } from '@/lib/tunnel/publisher'
    
    await publishToTunnel(`conversation:${conversationId}`, 'message:new', messageData)
    import { publishToTunnel } from '@/lib/tunnel/publisher'
    
    await publishToTunnel(`conversation:${conversationId}`, 'message:new', messageData)
    import { publishToTunnel } from '@/lib/tunnel/publisher'
    
    await publishToTunnel(`conversation:${conversationId}`, 'message:new', messageData)

    Subscribing to Updates

    Before (Firebase RTDB):

    Subscribing to Updates

    Before (Firebase RTDB):

    Subscribing to Updates

    Before (Firebase RTDB):

    const ref = rtdb.ref(`messages/${messageId}`)
    ref.on('value', (snapshot) => {
      const data = snapshot.val()
      handleUpdate(data)
    })
    const ref = rtdb.ref(`messages/${messageId}`)
    ref.on('value', (snapshot) => {
      const data = snapshot.val()
      handleUpdate(data)
    })
    const ref = rtdb.ref(`messages/${messageId}`)
    ref.on('value', (snapshot) => {
      const data = snapshot.val()
      handleUpdate(data)
    })

    After (Tunnel Protocol):

    After (Tunnel Protocol):

    After (Tunnel Protocol):

    import { subscribeToTunnel } from '@/lib/tunnel/client'
    
    const unsubscribe = subscribeToTunnel(`conversation:${conversationId}`, (message) => {
      if (message.type === 'message:new') {
        handleUpdate(message.payload)
    
    
    
    
    
    import { subscribeToTunnel } from '@/lib/tunnel/client'
    
    const unsubscribe = subscribeToTunnel(`conversation:${conversationId}`, (message) => {
      if (message.type === 'message:new') {
        handleUpdate(message.payload)
    
    
    
    
    
    import { subscribeToTunnel } from '@/lib/tunnel/client'
    
    const unsubscribe = subscribeToTunnel(`conversation:${conversationId}`, (message) => {
      if (message.type === 'message:new') {
        handleUpdate(message.payload)
    
    
    
    
    

    💡 Real-World Examples

    Example 1: Chat Messages

    Server-side (publish):


    💡 Real-World Examples

    Example 1: Chat Messages

    Server-side (publish):


    💡 Real-World Examples

    Example 1: Chat Messages

    Server-side (publish):

    'use server'
    
    import { initializeDatabase, getDatabaseService } from '@/lib/database/DatabaseService'
    import { publishToTunnel } from '@/lib/tunnel/publisher'
    import { revalidatePath } from 'next/cache'
    
    export async function sendMessage(conversationId: string, content: string
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    'use server'
    
    import { initializeDatabase, getDatabaseService } from '@/lib/database/DatabaseService'
    import { publishToTunnel } from '@/lib/tunnel/publisher'
    import { revalidatePath } from 'next/cache'
    
    export async function sendMessage(conversationId: string, content: string
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    'use server'
    
    import { initializeDatabase, getDatabaseService } from '@/lib/database/DatabaseService'
    import { publishToTunnel } from '@/lib/tunnel/publisher'
    import { revalidatePath } from 'next/cache'
    
    export async function sendMessage(conversationId: string, content: string
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    Client-side (subscribe):

    Client-side (subscribe):

    Client-side (subscribe):

    'use client'
    
    import { useEffect, useState } from 'react'
    import { subscribeToTunnel } from '@/lib/tunnel/client'
    
    export function ChatMessages({ conversationId }) {
      const [messages, setMessages] = useState([])
      
      useEffect
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    'use client'
    
    import { useEffect, useState } from 'react'
    import { subscribeToTunnel } from '@/lib/tunnel/client'
    
    export function ChatMessages({ conversationId }) {
      const [messages, setMessages] = useState([])
      
      useEffect
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    'use client'
    
    import { useEffect, useState } from 'react'
    import { subscribeToTunnel } from '@/lib/tunnel/client'
    
    export function ChatMessages({ conversationId }) {
      const [messages, setMessages] = useState([])
      
      useEffect
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    Example 2: Typing Indicators

    Publish typing status:

    Example 2: Typing Indicators

    Publish typing status:

    Example 2: Typing Indicators

    Publish typing status:

    await publishToTunnel(`conversation:${conversationId}`, 'typing:start', {
      userId,
      userName,
      timestamp: Date.now()
    })
    await publishToTunnel(`conversation:${conversationId}`, 'typing:start', {
      userId,
      userName,
      timestamp: Date.now()
    })
    await publishToTunnel(`conversation:${conversationId}`, 'typing:start', {
      userId,
      userName,
      timestamp: Date.now()
    })

    Subscribe to typing:

    Subscribe to typing:

    Subscribe to typing:

    subscribeToTunnel(`conversation:${conversationId}`, (message) => {
      if (message.type === 'typing:start') {
        showTypingIndicator(message.payload.userName)
      }
    })
    subscribeToTunnel(`conversation:${conversationId}`, (message) => {
      if (message.type === 'typing:start') {
        showTypingIndicator(message.payload.userName)
      }
    })
    subscribeToTunnel(`conversation:${conversationId}`, (message) => {
      if (message.type === 'typing:start') {
        showTypingIndicator(message.payload.userName)
      }
    })

    Example 3: Like/Unlike Updates

    Publish like update:

    Example 3: Like/Unlike Updates

    Publish like update:

    Example 3: Like/Unlike Updates

    Publish like update:

    await publishToTunnel(`entity:${entityId}`, 'like:toggled', {
      likeCount: newCount,
      liked: true,
      userId
    })
    await publishToTunnel(`entity:${entityId}`, 'like:toggled', {
      likeCount: newCount,
      liked: true,
      userId
    })
    await publishToTunnel(`entity:${entityId}`, 'like:toggled', {
      likeCount: newCount,
      liked: true,
      userId
    })

    🎛️ Transport Selection

    Tunnel automatically selects optimal transport based on deployment:

    Kubernetes + PostgreSQL

    // Detected: postgres.*.svc.cluster.local
    // Selected: WebSocket (wss://)
    // Fallback: Long-Polling

    Vercel Edge Runtime

    // Detected: VERCEL=1
    // Selected: SSE (Edge compatible)
    // Fallback: Long-Polling

    Supabase Deployment

    // Detected: SUPABASE_URL configured
    // Selected: Supabase Realtime
    // Fallback: SSE → Long-Polling

    Firebase Mode


    🎛️ Transport Selection

    Tunnel automatically selects optimal transport based on deployment:

    Kubernetes + PostgreSQL

    // Detected: postgres.*.svc.cluster.local
    // Selected: WebSocket (wss://)
    // Fallback: Long-Polling

    Vercel Edge Runtime

    // Detected: VERCEL=1
    // Selected: SSE (Edge compatible)
    // Fallback: Long-Polling

    Supabase Deployment

    // Detected: SUPABASE_URL configured
    // Selected: Supabase Realtime
    // Fallback: SSE → Long-Polling

    Firebase Mode


    🎛️ Transport Selection

    Tunnel automatically selects optimal transport based on deployment:

    Kubernetes + PostgreSQL

    // Detected: postgres.*.svc.cluster.local
    // Selected: WebSocket (wss://)
    // Fallback: Long-Polling

    Vercel Edge Runtime

    // Detected: VERCEL=1
    // Selected: SSE (Edge compatible)
    // Fallback: Long-Polling

    Supabase Deployment

    // Detected: SUPABASE_URL configured
    // Selected: Supabase Realtime
    // Fallback: SSE → Long-Polling

    Firebase Mode

    // Detected: DB_BACKEND_MODE=firebase-full
    // Selected: Firebase Realtime
    // Fallback: SSE → Long-Polling

    🔧 Configuration

    Environment Variables

    // Detected: DB_BACKEND_MODE=firebase-full
    // Selected: Firebase Realtime
    // Fallback: SSE → Long-Polling

    🔧 Configuration

    Environment Variables

    // Detected: DB_BACKEND_MODE=firebase-full
    // Selected: Firebase Realtime
    // Fallback: SSE → Long-Polling

    🔧 Configuration

    Environment Variables

    # Transport selection (optional - auto-detected)
    NEXT_PUBLIC_TUNNEL_TRANSPORT=websocket # or sse, supabase, firebase
    
    # WebSocket configuration
    TUNNEL_WEBSOCKET_URL=wss://your-domain.com/api/tunnel/ws
    
    # SSE configuration (Edge Runtime)
    TUNNEL_SSE_URL=https://your-domain.com/api/tunnel/sse
    
    # Fallback settings
    TUNNEL_ENABLE_FALLBACK=true
    TUNNEL_FALLBACK_TIMEOUT=5000 # 5 seconds
    # Transport selection (optional - auto-detected)
    NEXT_PUBLIC_TUNNEL_TRANSPORT=websocket # or sse, supabase, firebase
    
    # WebSocket configuration
    TUNNEL_WEBSOCKET_URL=wss://your-domain.com/api/tunnel/ws
    
    # SSE configuration (Edge Runtime)
    TUNNEL_SSE_URL=https://your-domain.com/api/tunnel/sse
    
    # Fallback settings
    TUNNEL_ENABLE_FALLBACK=true
    TUNNEL_FALLBACK_TIMEOUT=5000 # 5 seconds
    # Transport selection (optional - auto-detected)
    NEXT_PUBLIC_TUNNEL_TRANSPORT=websocket # or sse, supabase, firebase
    
    # WebSocket configuration
    TUNNEL_WEBSOCKET_URL=wss://your-domain.com/api/tunnel/ws
    
    # SSE configuration (Edge Runtime)
    TUNNEL_SSE_URL=https://your-domain.com/api/tunnel/sse
    
    # Fallback settings
    TUNNEL_ENABLE_FALLBACK=true
    TUNNEL_FALLBACK_TIMEOUT=5000 # 5 seconds

    Backend Mode Integration

    Tunnel respects your database backend mode:

    Backend Mode Integration

    Tunnel respects your database backend mode:

    Backend Mode Integration

    Tunnel respects your database backend mode:

    // lib/database/backend-mode-config.ts
    export const BACKEND_MODES = {
      'k8s-postgres-fcm': {
        tunnel: 'websocket' // Primary transport
      },
      'firebase-full': {
        tunnel: 'firebase' // Use Firebase Realtime
      },
      'supabase-fcm': {
    
    
    
    // lib/database/backend-mode-config.ts
    export const BACKEND_MODES = {
      'k8s-postgres-fcm': {
        tunnel: 'websocket' // Primary transport
      },
      'firebase-full': {
        tunnel: 'firebase' // Use Firebase Realtime
      },
      'supabase-fcm': {
    
    
    
    // lib/database/backend-mode-config.ts
    export const BACKEND_MODES = {
      'k8s-postgres-fcm': {
        tunnel: 'websocket' // Primary transport
      },
      'firebase-full': {
        tunnel: 'firebase' // Use Firebase Realtime
      },
      'supabase-fcm': {
    
    
    

    📊 Performance Characteristics

    Latency Comparison


    📊 Performance Characteristics

    Latency Comparison


    📊 Performance Characteristics

    Latency Comparison

    WebSocket:          <50ms   // Best for self-hosted
    SSE:                <100ms  // Best for Edge Runtime
    Supabase Realtime:  <50ms   // Best for Supabase deployments
    Firebase Realtime:  <200ms  // When using Firebase mode
    Long-Polling:       500ms-2s // Universal fallback
    WebSocket:          <50ms   // Best for self-hosted
    SSE:                <100ms  // Best for Edge Runtime
    Supabase Realtime:  <50ms   // Best for Supabase deployments
    Firebase Realtime:  <200ms  // When using Firebase mode
    Long-Polling:       500ms-2s // Universal fallback
    WebSocket:          <50ms   // Best for self-hosted
    SSE:                <100ms  // Best for Edge Runtime
    Supabase Realtime:  <50ms   // Best for Supabase deployments
    Firebase Realtime:  <200ms  // When using Firebase mode
    Long-Polling:       500ms-2s // Universal fallback

    Throughput Comparison

    Throughput Comparison

    Throughput Comparison

    WebSocket:          10,000 messages/second
    SSE:                1,000 messages/second
    Supabase Realtime:  5,000 messages/second
    Firebase Realtime:  1,000 messages/second
    Long-Polling:       100 messages/second
    WebSocket:          10,000 messages/second
    SSE:                1,000 messages/second
    Supabase Realtime:  5,000 messages/second
    Firebase Realtime:  1,000 messages/second
    Long-Polling:       100 messages/second
    WebSocket:          10,000 messages/second
    SSE:                1,000 messages/second
    Supabase Realtime:  5,000 messages/second
    Firebase Realtime:  1,000 messages/second
    Long-Polling:       100 messages/second

    🛡️ Security Features

    Encrypted Channels

    All transports support encryption:


    🛡️ Security Features

    Encrypted Channels

    All transports support encryption:


    🛡️ Security Features

    Encrypted Channels

    All transports support encryption:

    await publishToTunnel(`secure:${userId}`, 'sensitive:data', {
      encrypted: true,
      data: encryptedPayload
    })
    await publishToTunnel(`secure:${userId}`, 'sensitive:data', {
      encrypted: true,
      data: encryptedPayload
    })
    await publishToTunnel(`secure:${userId}`, 'sensitive:data', {
      encrypted: true,
      data: encryptedPayload
    })

    Rate Limiting

    Built-in protection against abuse:

    Rate Limiting

    Built-in protection against abuse:

    Rate Limiting

    Built-in protection against abuse:

    // Automatic rate limiting per user/IP
    Max 100 messages/minute per user
    Max 1000 messages/minute per IP
    // Automatic rate limiting per user/IP
    Max 100 messages/minute per user
    Max 1000 messages/minute per IP
    // Automatic rate limiting per user/IP
    Max 100 messages/minute per user
    Max 1000 messages/minute per IP

    DDoS Protection

    Transport-level protection:

    • Connection limits per IP
    • Message size limits
    • Automatic ban for abusive patterns

    🎯 Migration Guide

    From Firebase RTDB

    DDoS Protection

    Transport-level protection:

    • Connection limits per IP
    • Message size limits
    • Automatic ban for abusive patterns

    🎯 Migration Guide

    From Firebase RTDB

    DDoS Protection

    Transport-level protection:

    • Connection limits per IP
    • Message size limits
    • Automatic ban for abusive patterns

    🎯 Migration Guide

    From Firebase RTDB

    Firebase RTDBTunnel Protocol
    rtdb.ref(path).set(data)publishToTunnel(channel, type, data)
    rtdb.ref(path).on('value', cb)subscribeToTunnel(channel, cb)
    rtdb.ref(path).off()unsubscribe()
    rtdb.ref(path).onDisconnect()Handled by transport layer
    Firebase RTDBTunnel Protocol
    rtdb.ref(path).set(data)publishToTunnel(channel, type, data)
    rtdb.ref(path).on('value', cb)subscribeToTunnel(channel, cb)
    rtdb.ref(path).off()unsubscribe()
    rtdb.ref(path).onDisconnect()Handled by transport layer
    Firebase RTDBTunnel Protocol
    rtdb.ref(path).set(data)publishToTunnel(channel, type, data)
    rtdb.ref(path).on('value', cb)subscribeToTunnel(channel, cb)
    rtdb.ref(path).off()unsubscribe()
    rtdb.ref(path).onDisconnect()Handled by transport layer

    Code Example

    Before:

    Code Example

    Before:

    Code Example

    Before:

    const rtdb = getAdminRtdb()
    await rtdb.ref(`typing/${conversationId}/${userId}`).set(typingData)
    await rtdb.ref(`typing/${conversationId}/${userId}`).
    const rtdb = getAdminRtdb()
    await rtdb.ref(`typing/${conversationId}/${userId}`).set(typingData)
    await rtdb.ref(`typing/${conversationId}/${userId}`).
    const rtdb = getAdminRtdb()
    await rtdb.ref(`typing/${conversationId}/${userId}`).set(typingData)
    await rtdb.ref(`typing/${conversationId}/${userId}`).

    After:

    After:

    After:

    await publishToTunnel(`conversation:${conversationId}`, 'typing:start', {
      userId,
      userName,
      timestamp: Date.now()
    })
    // Disconnect handling automatic in Tunnel transport layer
    await publishToTunnel(`conversation:${conversationId}`, 'typing:start', {
      userId,
      userName,
      timestamp: Date.now()
    })
    // Disconnect handling automatic in Tunnel transport layer
    await publishToTunnel(`conversation:${conversationId}`, 'typing:start', {
      userId,
      userName,
      timestamp: Date.now()
    })
    // Disconnect handling automatic in Tunnel transport layer

    🔥 Advanced Features

    Message Types

    Tunnel supports typed messages:


    🔥 Advanced Features

    Message Types

    Tunnel supports typed messages:


    🔥 Advanced Features

    Message Types

    Tunnel supports typed messages:

    type TunnelMessageType = 
      | 'DATA'          // Generic data
      | 'NOTIFICATION'  // Push notifications
      | 'MESSAGE'       // Chat messages
      | 'PRESENCE'      // User presence/typing
      | 'HEARTBEAT'     // Keep-alive
      | 'ACK'           // Acknowledgments
      | '
    
    
    
    
    type TunnelMessageType = 
      | 'DATA'          // Generic data
      | 'NOTIFICATION'  // Push notifications
      | 'MESSAGE'       // Chat messages
      | 'PRESENCE'      // User presence/typing
      | 'HEARTBEAT'     // Keep-alive
      | 'ACK'           // Acknowledgments
      | '
    
    
    
    
    type TunnelMessageType = 
      | 'DATA'          // Generic data
      | 'NOTIFICATION'  // Push notifications
      | 'MESSAGE'       // Chat messages
      | 'PRESENCE'      // User presence/typing
      | 'HEARTBEAT'     // Keep-alive
      | 'ACK'           // Acknowledgments
      | '
    
    
    
    

    Channel Patterns

    Organize channels by feature:

    Channel Patterns

    Organize channels by feature:

    Channel Patterns

    Organize channels by feature:

    `conversation:${id}`     // Chat conversations
    `entity:${id}`           // Entity updates
    `opportunity:${id}`      // Opportunity updates
    `user:${id}`             // User-specific channel
    `typing:${conversationId}` // Typing indicators
    `presence:${
    
    `conversation:${id}`     // Chat conversations
    `entity:${id}`           // Entity updates
    `opportunity:${id}`      // Opportunity updates
    `user:${id}`             // User-specific channel
    `typing:${conversationId}` // Typing indicators
    `presence:${
    
    `conversation:${id}`     // Chat conversations
    `entity:${id}`           // Entity updates
    `opportunity:${id}`      // Opportunity updates
    `user:${id}`             // User-specific channel
    `typing:${conversationId}` // Typing indicators
    `presence:${
    

    🎖️ Best Practices Summary


    🎖️ Best Practices Summary


    🎖️ Best Practices Summary

    Tunnel Protocol Best Practices
    1. Use Tunnel for real-time, DatabaseService for persistence
    2. Channel naming: Use feature:id pattern
    3. Message types: Use semantic types (message:new, typing:start, etc.)
    4. Error handling: Tunnel failures should not break core functionality
    5. React 19: Combine with revalidatePath() for cache updates
    6. Performance: Tunnel is async, don't await unless critical
    7. Cleanup: Always unsubscribe in useEffect cleanup
    Tunnel Protocol Best Practices
    1. Use Tunnel for real-time, DatabaseService for persistence
    2. Channel naming: Use feature:id pattern
    3. Message types: Use semantic types (message:new, typing:start, etc.)
    4. Error handling: Tunnel failures should not break core functionality
    5. React 19: Combine with revalidatePath() for cache updates
    6. Performance: Tunnel is async, don't await unless critical
    7. Cleanup: Always unsubscribe in useEffect cleanup
    Tunnel Protocol Best Practices
    1. Use Tunnel for real-time, DatabaseService for persistence
    2. Channel naming: Use feature:id pattern
    3. Message types: Use semantic types (message:new, typing:start, etc.)
    4. Error handling: Tunnel failures should not break core functionality
    5. React 19: Combine with revalidatePath() for cache updates
    6. Performance: Tunnel is async, don't await unless critical
    7. Cleanup: Always unsubscribe in useEffect cleanup

    Built by Legiox Commander for Emperor Ray
    Ring analog to Firebase RTDB - Zero vendor lock-in - Maximum flexibility
    🔥⚔️👑

    .
    log
    (
    '
    Received:
    '
    ,
    message
    )
    })
    }
    })
    // Cleanup
    unsubscribe()
    )
    {
    await initializeDatabase()

    Built by Legiox Commander for Emperor Ray
    Ring analog to Firebase RTDB - Zero vendor lock-in - Maximum flexibility
    🔥⚔️👑

    .
    log
    (
    '
    Received:
    '
    ,
    message
    )
    })
    }
    })
    // Cleanup
    unsubscribe()
    )
    {
    await initializeDatabase()

    Built by Legiox Commander for Emperor Ray
    Ring analog to Firebase RTDB - Zero vendor lock-in - Maximum flexibility
    🔥⚔️👑

    .
    log
    (
    '
    Received:
    '
    ,
    message
    )
    })
    }
    })
    // Cleanup
    unsubscribe()
    )
    {
    await initializeDatabase()
    const db = getDatabaseService()
    // Save to database (persistence)
    const db = getDatabaseService()
    // Save to database (persistence)
    const db = getDatabaseService()
    // Save to database (persistence)
    const result = await db.create('messages', {
    const result = await db.create('messages', {
    const result = await db.create('messages', {
    conversationId,
    content,
    timestamp: new Date()
    })
    if (!result.success) throw result.error
    // Publish real-time update (Tunnel replaces Firebase RTDB)
    conversationId,
    content,
    timestamp: new Date()
    })
    if (!result.success) throw result.error
    // Publish real-time update (Tunnel replaces Firebase RTDB)
    conversationId,
    content,
    timestamp: new Date()
    })
    if (!result.success) throw result.error
    // Publish real-time update (Tunnel replaces Firebase RTDB)
    await publishToTunnel(`conversation:${conversationId}`, 'message:new', {
    await publishToTunnel(`conversation:${conversationId}`, 'message:new', {
    await publishToTunnel(`conversation:${conversationId}`, 'message:new', {
    id: result.data.id,
    content,
    timestamp: Date.now()
    })
    // Revalidate (React 19 pattern)
    revalidatePath(`/[locale]/chat/${conversationId}`)
    return result.data
    id: result.data.id,
    content,
    timestamp: Date.now()
    })
    // Revalidate (React 19 pattern)
    revalidatePath(`/[locale]/chat/${conversationId}`)
    return result.data
    id: result.data.id,
    content,
    timestamp: Date.now()
    })
    // Revalidate (React 19 pattern)
    revalidatePath(`/[locale]/chat/${conversationId}`)
    return result.data
    }
    (
    ()
    =>
    {
    // Subscribe to real-time updates
    const unsubscribe = subscribeToTunnel(
    `conversation:${conversationId}`,
    (message) => {
    if (message.type === 'message:new') {
    }
    (
    ()
    =>
    {
    // Subscribe to real-time updates
    const unsubscribe = subscribeToTunnel(
    `conversation:${conversationId}`,
    (message) => {
    if (message.type === 'message:new') {
    }
    (
    ()
    =>
    {
    // Subscribe to real-time updates
    const unsubscribe = subscribeToTunnel(
    `conversation:${conversationId}`,
    (message) => {
    if (message.type === 'message:new') {
    setMessages(prev => [...prev, message.payload])
    }
    }
    )
    return () => unsubscribe()
    }, [conversationId])
    setMessages(prev => [...prev, message.payload])
    }
    }
    )
    return () => unsubscribe()
    }, [conversationId])
    setMessages(prev => [...prev, message.payload])
    }
    }
    )
    return () => unsubscribe()
    }, [conversationId])
    return <div>{messages.map(msg => <Message key={msg.id} {...msg} />)}</div>
    return <div>{messages.map(msg => <Message key={msg.id} {...msg} />)}</div>
    return <div>{messages.map(msg => <Message key={msg.id} {...msg} />)}</div>
    }
    tunnel
    :
    '
    supabase
    '
    // Use Supabase Realtime
    }
    }
    onDisconnect
    ()
    .
    remove
    ()
    ERROR
    '
    // Error messages
    | 'AUTH' // Authentication
    | 'DB_INSERT' // Database insert event
    | 'DB_UPDATE' // Database update event
    }
    tunnel
    :
    '
    supabase
    '
    // Use Supabase Realtime
    }
    }
    onDisconnect
    ()
    .
    remove
    ()
    ERROR
    '
    // Error messages
    | 'AUTH' // Authentication
    | 'DB_INSERT' // Database insert event
    | 'DB_UPDATE' // Database update event
    }
    tunnel
    :
    '
    supabase
    '
    // Use Supabase Realtime
    }
    }
    onDisconnect
    ()
    .
    remove
    ()
    ERROR
    '
    // Error messages
    | 'AUTH' // Authentication
    | 'DB_INSERT' // Database insert event
    | 'DB_UPDATE' // Database update event
    | 'DB_DELETE' // Database delete event
    userId
    }
    `
    // User presence
    `global:announcements` // Broadcast channel
    | 'DB_DELETE' // Database delete event
    userId
    }
    `
    // User presence
    `global:announcements` // Broadcast channel
    | 'DB_DELETE' // Database delete event
    userId
    }
    `
    // User presence
    `global:announcements` // Broadcast channel