# ============================================================
# Nginx WebSocket 代理配置示例
# ============================================================
#
# 功能说明:
# - WebSocket 连接升级处理
# - 长连接超时配置
# - 负载均衡支持
#
# Lolly 对应配置:
# server:
#   proxy:
#     - path: "/ws"
#       targets:
#         - url: "http://websocket-server:8080"
#       # WebSocket 协议升级自动处理
#       timeout:
#         read: 3600s  # WebSocket 长连接超时
# ============================================================

upstream websocket_backend {
    server ws1:8080;
    server ws2:8080;
    keepalive 32;
}

server {
    listen 80;
    server_name ws.example.com;

    # WebSocket 代理
    location /ws {
        proxy_pass http://websocket_backend;

        # WebSocket 协议升级
        # HTTP/1.1 必需
        proxy_http_version 1.1;

        # Upgrade 和 Connection 头处理
        # Lolly 自动处理 WebSocket 协议升级
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        # 其他头部
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        # WebSocket 长连接超时
        # Lolly 对应: timeout.read: 3600s
        proxy_read_timeout 3600s;
        proxy_send_timeout 3600s;
        proxy_connect_timeout 60s;

        # 禁用缓冲（实时传输）
        proxy_buffering off;
    }

    # Socket.IO WebSocket 代理
    location /socket.io {
        proxy_pass http://websocket_backend;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;

        # Socket.IO 长轮询 fallback 支持
        proxy_read_timeout 3600s;
        proxy_send_timeout 3600s;

        # 禁用缓冲
        proxy_buffering off;
    }
}

# WebSocket 说明:
#
# 1. 协议升级流程:
#    客户端发送:
#    GET /ws HTTP/1.1
#    Upgrade: websocket
#    Connection: Upgrade
#    Sec-WebSocket-Key: <base64-key>
#    Sec-WebSocket-Version: 13
#
#    服务端响应:
#    HTTP/1.1 101 Switching Protocols
#    Upgrade: websocket
#    Connection: Upgrade
#    Sec-WebSocket-Accept: <accept-hash>
#
# 2. 超时配置:
#    - proxy_read_timeout: 等待 WebSocket 消息的超时
#    - 较短超时会导致长连接被断开
#    - 建议设置为最大预期空闲时间
#
# 3. 缓冲配置:
#    - proxy_buffering off: 实时传输消息
#    - 避免消息延迟
#
# 4. 负载均衡:
#    - WebSocket 连接需要会话保持
#    - 建议使用 ip_hash 或 sticky session