- Introduce Rooms in chat-sessions, as different clients received the same messages.

This commit is contained in:
Josako
2024-08-19 07:22:06 +02:00
parent 688f2300b9
commit 733f115e92
9 changed files with 175 additions and 42 deletions

View File

@@ -1,7 +1,7 @@
import uuid
from flask_jwt_extended import create_access_token, get_jwt_identity, verify_jwt_in_request, decode_token
from flask_socketio import emit, disconnect
from flask_socketio import emit, disconnect, join_room, leave_room
from flask import current_app, request, session
from sqlalchemy.exc import SQLAlchemyError
from datetime import datetime, timedelta
@@ -32,17 +32,23 @@ def handle_connect():
token = create_access_token(identity={"tenant_id": tenant_id, "api_key": api_key})
current_app.logger.debug(f'SocketIO: Connection handling created token: {token} for tenant {tenant_id}')
# Create a unique room for this client
room = f"{tenant_id}_{request.sid}"
join_room(room)
current_app.logger.debug(f'SocketIO: Client joined room: {room}')
# Create a unique session ID
if 'session_id' not in session:
session['session_id'] = str(uuid.uuid4())
session['last_activity'] = datetime.now()
session['room'] = room
# Communicate connection to client
current_app.logger.debug(f'SocketIO: Connection handling sending status to client for tenant {tenant_id}')
emit('connect', {'status': 'Connected', 'tenant_id': tenant_id})
emit('connect', {'status': 'Connected', 'tenant_id': tenant_id, 'room': room})
current_app.logger.debug(f'SocketIO: Connection handling sending authentication token to client')
emit('authenticated', {'token': token}) # Emit custom event with the token
emit('authenticated', {'token': token, 'room': room}) # Emit custom event with the token
current_app.logger.debug(f'SocketIO: Connection handling sent token to client for tenant {tenant_id}')
except Exception as e:
current_app.logger.error(f'SocketIO: Connection failed: {e}')
@@ -53,6 +59,10 @@ def handle_connect():
@socketio.on('disconnect')
def handle_disconnect():
room = session.get('room')
if room:
leave_room(room)
current_app.logger.debug(f'SocketIO: Client left room: {room}')
current_app.logger.debug('SocketIO: Client disconnected')
@@ -73,6 +83,7 @@ def handle_message(data):
session['last_activity'] = datetime.now()
current_tenant_id = validate_incoming_data(data)
room = session.get('room')
# Offload actual processing of question
task = current_celery.send_task('ask_question', queue='llm_interactions', args=[
@@ -80,7 +91,8 @@ def handle_message(data):
data['message'],
data['language'],
session['session_id'],
data['timezone']
data['timezone'],
room
])
current_app.logger.debug(f'SocketIO: Message offloading for tenant {current_tenant_id}, '
f'Question: {task.id}')
@@ -90,7 +102,7 @@ def handle_message(data):
'taskId': task.id,
}
current_app.logger.debug(f"SocketIO: Message handling sent bot response: {response}")
emit('bot_response', response, broadcast=True)
emit('bot_response', response, room=room)
except Exception as e:
current_app.logger.error(f'SocketIO: Message handling failed: {e}')
disconnect()
@@ -99,15 +111,16 @@ def handle_message(data):
@socketio.on('check_task_status')
def check_task_status(data):
task_id = data.get('task_id')
room = session.get('room')
current_app.logger.debug(f'SocketIO: Check task status for task_id: {task_id}')
if not task_id:
emit('task_status', {'status': 'error', 'message': 'Missing task ID'})
emit('task_status', {'status': 'error', 'message': 'Missing task ID'}, room=room)
return
task_result = current_celery.AsyncResult(task_id)
if task_result.state == 'PENDING':
current_app.logger.debug(f'SocketIO: Task {task_id} is pending')
emit('task_status', {'status': 'pending', 'taskId': task_id})
emit('task_status', {'status': 'pending', 'taskId': task_id}, room=room)
elif task_result.state == 'SUCCESS':
current_app.logger.debug(f'SocketIO: Task {task_id} has finished. Status: {task_result.state}, '
f'Result: {task_result.result}')
@@ -120,10 +133,10 @@ def check_task_status(data):
'algorithm': result['algorithm'],
'interaction_id': result['interaction_id'],
}
emit('task_status', response)
emit('task_status', response, room=room)
else:
current_app.logger.error(f'SocketIO: Task {task_id} has failed. Error: {task_result.info}')
emit('task_status', {'status': task_result.state, 'message': str(task_result.info)})
emit('task_status', {'status': task_result.state, 'message': str(task_result.info)}, room=room)
@socketio.on('feedback')