Files
pos-system/services/chat-service-net/docs/en

Chat Service

Real-time chat service for GoodGo platform, built on ASP.NET Core SignalR.

Overview

Chat Service provides real-time communication capabilities in the microservices system with:

  • Real-time Communication - ASP.NET Core SignalR with WebSockets/SSE/Long Polling
  • Scalability - Redis Backplane or Azure SignalR Service
  • User & Group Management - Chat rooms, cross-device user mapping
  • AI Integration - Smart chatbot with streaming response
  • High Performance - MessagePack protocol
  • Resiliency - Auto reconnect, Stateful Reconnect

Requirements

Requirement Version
.NET SDK 10.0.101+
Docker 24.0+
PostgreSQL 16+
Redis 7+

Quick Start

1. Configure Environment

# Copy environment template
cp .env.example .env

# Edit configuration
nano .env

2. Run with Docker

# Start all services
docker-compose up -d

# View logs
docker-compose logs -f chatservice-api

3. Run Locally

dotnet restore
dotnet build
dotnet run --project src/ChatService.API

Feature Details

A. Real-time Communication

Feature Description
SignalR Hub Central hub handling all real-time connections
Multi-Transport Auto-select WebSockets → SSE → Long Polling
Streaming IAsyncEnumerable support for streaming AI responses
// Send message to group
await Clients.Group(roomId).SendAsync("ReceiveMessage", message);

// Streaming AI response
public async IAsyncEnumerable<string> StreamAIResponse(string prompt)
{
    await foreach (var chunk in _aiService.StreamAsync(prompt))
        yield return chunk;
}

B. Scalability

Solution Use Case
Redis Backplane On-premise, multi-instance deployment
Azure SignalR Service Azure cloud, serverless scenarios
Sticky Sessions Fallback when not using Azure SignalR
// Configure Redis Backplane
builder.Services.AddSignalR()
    .AddStackExchangeRedis(connectionString, options => {
        options.Configuration.ChannelPrefix = RedisChannel.Literal("ChatService");
    });

C. User & Group Management

Feature Description
Groups Group connections by chat room
User Mapping Map ConnectionId → UserId via Claims
Persistent State Save group state to database
// Custom User ID Provider
public class CustomUserIdProvider : IUserIdProvider
{
    public string? GetUserId(HubConnectionContext connection)
        => connection.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
}

D. AI Integration

Feature Description
AI Assistant In-group chatbot (trigger: @gpt)
Streaming Response Push response chunks in real-time
Context History Save chat history for AI context

E. MessagePack Protocol

// Server configuration
builder.Services.AddSignalR()
    .AddMessagePackProtocol();

// Client configuration (JavaScript)
const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub")
    .withHubProtocol(new signalR.protocols.msgpack.MessagePackHubProtocol())
    .build();

F. Resiliency

Feature Description
Auto Reconnect Client auto-reconnects
Stateful Reconnect Buffer data during interruption (.NET 8+)
// Server: Enable Stateful Reconnect
builder.Services.AddSignalR(options => {
    options.EnableDetailedErrors = true;
    options.StatefulReconnectBufferSize = 32 * 1024; // 32KB buffer
});

// Client: Configure reconnect
connection.WithAutomaticReconnect([0, 2000, 10000, 30000]);

API Endpoints

HTTP REST APIs

Method Endpoint Description
GET /api/v1/rooms Get chat room list
POST /api/v1/rooms Create new chat room
GET /api/v1/rooms/{id}/messages Get message history
POST /api/v1/rooms/{id}/participants Add participant

SignalR Hub Methods

Method Direction Description
SendMessage Client → Server Send message
JoinRoom Client → Server Join room
LeaveRoom Client → Server Leave room
ReceiveMessage Server → Client Receive message
UserJoined Server → Client New user notification

Health Endpoints

Endpoint Purpose
/health Full status
/health/live Liveness probe
/health/ready Readiness probe

Configuration

Environment Variables

Variable Description Default
ASPNETCORE_ENVIRONMENT Environment Development
DATABASE_URL PostgreSQL connection -
REDIS_URL Redis connection -
AZURE_SIGNALR_CONNECTION Azure SignalR (optional) -
OPENAI_API_KEY OpenAI API key (optional) -

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Host=localhost;Database=chatservice;Username=postgres;Password=postgres",
    "Redis": "localhost:6379"
  },
  "SignalR": {
    "EnableMessagePack": true,
    "StatefulReconnectBufferSize": 32768
  },
  "AI": {
    "Provider": "OpenAI",
    "Model": "gpt-4",
    "MaxHistoryMessages": 20
  }
}

Deployment

Docker Build

docker build -t chatservice:latest .
docker run -p 5000:8080 --env-file .env chatservice:latest

Kubernetes

See ARCHITECTURE.md for detailed Kubernetes configuration with Sticky Sessions.

References

License

Proprietary - GoodGo Platform