forked from erp-dev/erp
feat: big version, added tasks for backup_database and stock change, added health check api, approve sse (support channel via merchant)
This commit is contained in:
74
sse/views.py
74
sse/views.py
@@ -2,16 +2,18 @@ from django.http import StreamingHttpResponse, HttpResponse
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.decorators.http import require_http_methods
|
||||
from rest_framework.decorators import api_view, permission_classes
|
||||
from rest_framework.permissions import AllowAny
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from rest_framework import status
|
||||
from . import services
|
||||
from .auth_utils import require_sse_authentication, get_user_merchant_id
|
||||
import queue
|
||||
import json
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
@require_http_methods(["GET", "OPTIONS"])
|
||||
@require_sse_authentication
|
||||
def create_sse_event(request):
|
||||
"""
|
||||
创建一个 SSE 事件流响应。
|
||||
@@ -24,6 +26,7 @@ def create_sse_event(request):
|
||||
注意:
|
||||
- 使用纯 Django 视图,不使用 DRF,避免内容协商导致的 406 错误
|
||||
- SSE 需要特殊的 CORS 配置
|
||||
- 需要JWT认证且用户必须有关联的商户
|
||||
"""
|
||||
# 处理 OPTIONS 预检请求
|
||||
if request.method == 'OPTIONS':
|
||||
@@ -38,13 +41,16 @@ def create_sse_event(request):
|
||||
return response
|
||||
|
||||
def event_stream():
|
||||
# 获取当前商户ID
|
||||
merchant_id = request.merchant_id
|
||||
|
||||
# 创建一个同步队列用于接收消息
|
||||
conn_queue = queue.Queue(maxsize=100)
|
||||
services.push_connection(conn_queue)
|
||||
services.push_connection(merchant_id, conn_queue)
|
||||
|
||||
try:
|
||||
# 发送初始连接成功消息
|
||||
yield f"data: {json.dumps({'type': 'connected', 'message': 'SSE connection established'})}\n\n"
|
||||
yield f"data: {json.dumps({'type': 'connected', 'message': 'SSE connection established', 'merchant_id': merchant_id})}\n\n"
|
||||
|
||||
# 持续从队列中获取消息并发送给客户端
|
||||
while True:
|
||||
@@ -60,7 +66,7 @@ def create_sse_event(request):
|
||||
break
|
||||
finally:
|
||||
# 清理:从连接集合中移除此队列
|
||||
services.remove_connection(conn_queue)
|
||||
services.remove_connection(merchant_id, conn_queue)
|
||||
|
||||
response = StreamingHttpResponse(
|
||||
event_stream(),
|
||||
@@ -82,50 +88,78 @@ def create_sse_event(request):
|
||||
|
||||
|
||||
@api_view(['POST'])
|
||||
@permission_classes([AllowAny])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def push_test_event(request):
|
||||
"""
|
||||
向所有连接的客户端广播一个 SSE 测试事件。
|
||||
向当前用户所属商户的所有连接客户端广播一个 SSE 测试事件。
|
||||
"""
|
||||
services.push_simple_message_with_object_id('order_paid', '订单已支付', 12345)
|
||||
# 获取当前用户的商户ID
|
||||
merchant_id = get_user_merchant_id(request)
|
||||
if not merchant_id:
|
||||
return Response({'error': 'User has no associated merchant'}, status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
services.push_simple_message_with_object_id_to_merchant(
|
||||
merchant_id, 'order_paid', '订单已支付', 12345
|
||||
)
|
||||
|
||||
merchant_connections = services.get_merchant_connections(merchant_id)
|
||||
return Response({
|
||||
'status': 'ok',
|
||||
'message': 'Test event broadcasted',
|
||||
'clients': len(services.get_active_connections())
|
||||
'message': 'Test event broadcasted to your merchant',
|
||||
'merchant_id': merchant_id,
|
||||
'clients': len(merchant_connections)
|
||||
})
|
||||
|
||||
|
||||
@api_view(['GET'])
|
||||
@permission_classes([AllowAny])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def get_sse_status(request):
|
||||
"""
|
||||
获取 SSE 连接状态信息。
|
||||
|
||||
返回:
|
||||
- clients: 当前连接的客户端数量
|
||||
- total_clients: 所有商户的客户端总数
|
||||
- merchant_clients: 当前商户的客户端数量
|
||||
- status: 服务状态
|
||||
"""
|
||||
active_connections = services.get_active_connections()
|
||||
merchant_id = get_user_merchant_id(request)
|
||||
if not merchant_id:
|
||||
return Response({'error': 'User has no associated merchant'}, status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
# 获取所有连接数
|
||||
all_connections = services.get_all_connections_count()
|
||||
|
||||
# 获取当前商户的连接数
|
||||
merchant_connections = services.get_merchant_connections(merchant_id)
|
||||
|
||||
return Response({
|
||||
'status': 'running',
|
||||
'clients': len(active_connections),
|
||||
'message': f'SSE server is running with {len(active_connections)} active connection(s)',
|
||||
'total_clients': all_connections,
|
||||
'merchant_clients': len(merchant_connections),
|
||||
'merchant_id': merchant_id,
|
||||
'message': f'SSE server is running with {all_connections} total connections, {len(merchant_connections)} for your merchant',
|
||||
})
|
||||
|
||||
|
||||
@api_view(['POST'])
|
||||
@permission_classes([AllowAny])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def shutdown_sse(request):
|
||||
"""
|
||||
优雅关闭所有SSE连接的端点
|
||||
关闭当前用户所属商户的所有SSE连接
|
||||
"""
|
||||
services.push_sse_event_to_all({
|
||||
merchant_id = get_user_merchant_id(request)
|
||||
if not merchant_id:
|
||||
return Response({'error': 'User has no associated merchant'}, status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
services.push_sse_event_to_merchant(merchant_id, {
|
||||
'type': 'server_shutdown',
|
||||
'message': 'Server is shutting down, please reconnect later'
|
||||
'message': 'Server shutting down your connections, please reconnect later'
|
||||
})
|
||||
|
||||
merchant_connections = services.get_merchant_connections(merchant_id)
|
||||
return Response({
|
||||
'status': 'ok',
|
||||
'message': 'Shutdown signal sent to all SSE connections',
|
||||
'clients': len(services.get_active_connections())
|
||||
'message': 'Shutdown signal sent to your merchant\'s SSE connections',
|
||||
'merchant_id': merchant_id,
|
||||
'clients': len(merchant_connections)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user