main.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. import asyncio
  2. import random
  3. import socketio
  4. import logging
  5. import sys
  6. import time
  7. from typing import Dict, Set
  8. from redis import asyncio as aioredis
  9. import pycrdt as Y
  10. from open_webui.models.users import Users, UserNameResponse
  11. from open_webui.models.channels import Channels
  12. from open_webui.models.chats import Chats
  13. from open_webui.models.notes import Notes, NoteUpdateForm
  14. from open_webui.utils.redis import (
  15. get_sentinels_from_env,
  16. get_sentinel_url_from_env,
  17. )
  18. from open_webui.env import (
  19. ENABLE_WEBSOCKET_SUPPORT,
  20. WEBSOCKET_MANAGER,
  21. WEBSOCKET_REDIS_URL,
  22. WEBSOCKET_REDIS_LOCK_TIMEOUT,
  23. WEBSOCKET_SENTINEL_PORT,
  24. WEBSOCKET_SENTINEL_HOSTS,
  25. )
  26. from open_webui.utils.auth import decode_token
  27. from open_webui.socket.utils import RedisDict, RedisLock
  28. from open_webui.tasks import create_task, stop_item_tasks
  29. from open_webui.utils.redis import get_redis_connection
  30. from open_webui.utils.access_control import has_access, get_users_with_access
  31. from open_webui.env import (
  32. GLOBAL_LOG_LEVEL,
  33. SRC_LOG_LEVELS,
  34. )
  35. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  36. log = logging.getLogger(__name__)
  37. log.setLevel(SRC_LOG_LEVELS["SOCKET"])
  38. REDIS = get_redis_connection(
  39. redis_url=WEBSOCKET_REDIS_URL,
  40. redis_sentinels=get_sentinels_from_env(
  41. WEBSOCKET_SENTINEL_HOSTS, WEBSOCKET_SENTINEL_PORT
  42. ),
  43. async_mode=True,
  44. )
  45. if WEBSOCKET_MANAGER == "redis":
  46. if WEBSOCKET_SENTINEL_HOSTS:
  47. mgr = socketio.AsyncRedisManager(
  48. get_sentinel_url_from_env(
  49. WEBSOCKET_REDIS_URL, WEBSOCKET_SENTINEL_HOSTS, WEBSOCKET_SENTINEL_PORT
  50. )
  51. )
  52. else:
  53. mgr = socketio.AsyncRedisManager(WEBSOCKET_REDIS_URL)
  54. sio = socketio.AsyncServer(
  55. cors_allowed_origins=[],
  56. async_mode="asgi",
  57. transports=(["websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]),
  58. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  59. always_connect=True,
  60. client_manager=mgr,
  61. )
  62. else:
  63. sio = socketio.AsyncServer(
  64. cors_allowed_origins=[],
  65. async_mode="asgi",
  66. transports=(["websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]),
  67. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  68. always_connect=True,
  69. )
  70. # Timeout duration in seconds
  71. TIMEOUT_DURATION = 3
  72. # Dictionary to maintain the user pool
  73. if WEBSOCKET_MANAGER == "redis":
  74. log.debug("Using Redis to manage websockets.")
  75. redis_sentinels = get_sentinels_from_env(
  76. WEBSOCKET_SENTINEL_HOSTS, WEBSOCKET_SENTINEL_PORT
  77. )
  78. SESSION_POOL = RedisDict(
  79. "open-webui:session_pool",
  80. redis_url=WEBSOCKET_REDIS_URL,
  81. redis_sentinels=redis_sentinels,
  82. )
  83. USER_POOL = RedisDict(
  84. "open-webui:user_pool",
  85. redis_url=WEBSOCKET_REDIS_URL,
  86. redis_sentinels=redis_sentinels,
  87. )
  88. USAGE_POOL = RedisDict(
  89. "open-webui:usage_pool",
  90. redis_url=WEBSOCKET_REDIS_URL,
  91. redis_sentinels=redis_sentinels,
  92. )
  93. DOCUMENTS = {}
  94. DOCUMENT_USERS = {}
  95. clean_up_lock = RedisLock(
  96. redis_url=WEBSOCKET_REDIS_URL,
  97. lock_name="usage_cleanup_lock",
  98. timeout_secs=WEBSOCKET_REDIS_LOCK_TIMEOUT,
  99. redis_sentinels=redis_sentinels,
  100. )
  101. aquire_func = clean_up_lock.aquire_lock
  102. renew_func = clean_up_lock.renew_lock
  103. release_func = clean_up_lock.release_lock
  104. else:
  105. SESSION_POOL = {}
  106. USER_POOL = {}
  107. USAGE_POOL = {}
  108. DOCUMENTS = {} # document_id -> Y.YDoc instance
  109. DOCUMENT_USERS = {} # document_id -> set of user sids
  110. aquire_func = release_func = renew_func = lambda: True
  111. async def periodic_usage_pool_cleanup():
  112. max_retries = 2
  113. retry_delay = random.uniform(
  114. WEBSOCKET_REDIS_LOCK_TIMEOUT / 2, WEBSOCKET_REDIS_LOCK_TIMEOUT
  115. )
  116. for attempt in range(max_retries + 1):
  117. if aquire_func():
  118. break
  119. else:
  120. if attempt < max_retries:
  121. log.debug(
  122. f"Cleanup lock already exists. Retry {attempt + 1} after {retry_delay}s..."
  123. )
  124. await asyncio.sleep(retry_delay)
  125. else:
  126. log.warning(
  127. "Failed to acquire cleanup lock after retries. Skipping cleanup."
  128. )
  129. return
  130. log.debug("Running periodic_cleanup")
  131. try:
  132. while True:
  133. if not renew_func():
  134. log.error(f"Unable to renew cleanup lock. Exiting usage pool cleanup.")
  135. raise Exception("Unable to renew usage pool cleanup lock.")
  136. now = int(time.time())
  137. send_usage = False
  138. for model_id, connections in list(USAGE_POOL.items()):
  139. # Creating a list of sids to remove if they have timed out
  140. expired_sids = [
  141. sid
  142. for sid, details in connections.items()
  143. if now - details["updated_at"] > TIMEOUT_DURATION
  144. ]
  145. for sid in expired_sids:
  146. del connections[sid]
  147. if not connections:
  148. log.debug(f"Cleaning up model {model_id} from usage pool")
  149. del USAGE_POOL[model_id]
  150. else:
  151. USAGE_POOL[model_id] = connections
  152. send_usage = True
  153. await asyncio.sleep(TIMEOUT_DURATION)
  154. finally:
  155. release_func()
  156. app = socketio.ASGIApp(
  157. sio,
  158. socketio_path="/ws/socket.io",
  159. )
  160. def get_models_in_use():
  161. # List models that are currently in use
  162. models_in_use = list(USAGE_POOL.keys())
  163. return models_in_use
  164. def get_active_user_ids():
  165. """Get the list of active user IDs."""
  166. return list(USER_POOL.keys())
  167. def get_user_active_status(user_id):
  168. """Check if a user is currently active."""
  169. return user_id in USER_POOL
  170. def get_user_id_from_session_pool(sid):
  171. user = SESSION_POOL.get(sid)
  172. if user:
  173. return user["id"]
  174. return None
  175. def get_user_ids_from_room(room):
  176. active_session_ids = sio.manager.get_participants(
  177. namespace="/",
  178. room=room,
  179. )
  180. active_user_ids = list(
  181. set(
  182. [SESSION_POOL.get(session_id[0])["id"] for session_id in active_session_ids]
  183. )
  184. )
  185. return active_user_ids
  186. def get_active_status_by_user_id(user_id):
  187. if user_id in USER_POOL:
  188. return True
  189. return False
  190. @sio.on("usage")
  191. async def usage(sid, data):
  192. if sid in SESSION_POOL:
  193. model_id = data["model"]
  194. # Record the timestamp for the last update
  195. current_time = int(time.time())
  196. # Store the new usage data and task
  197. USAGE_POOL[model_id] = {
  198. **(USAGE_POOL[model_id] if model_id in USAGE_POOL else {}),
  199. sid: {"updated_at": current_time},
  200. }
  201. @sio.event
  202. async def connect(sid, environ, auth):
  203. user = None
  204. if auth and "token" in auth:
  205. data = decode_token(auth["token"])
  206. if data is not None and "id" in data:
  207. user = Users.get_user_by_id(data["id"])
  208. if user:
  209. SESSION_POOL[sid] = user.model_dump()
  210. if user.id in USER_POOL:
  211. USER_POOL[user.id] = USER_POOL[user.id] + [sid]
  212. else:
  213. USER_POOL[user.id] = [sid]
  214. @sio.on("user-join")
  215. async def user_join(sid, data):
  216. auth = data["auth"] if "auth" in data else None
  217. if not auth or "token" not in auth:
  218. return
  219. data = decode_token(auth["token"])
  220. if data is None or "id" not in data:
  221. return
  222. user = Users.get_user_by_id(data["id"])
  223. if not user:
  224. return
  225. SESSION_POOL[sid] = user.model_dump()
  226. if user.id in USER_POOL:
  227. USER_POOL[user.id] = USER_POOL[user.id] + [sid]
  228. else:
  229. USER_POOL[user.id] = [sid]
  230. # Join all the channels
  231. channels = Channels.get_channels_by_user_id(user.id)
  232. log.debug(f"{channels=}")
  233. for channel in channels:
  234. await sio.enter_room(sid, f"channel:{channel.id}")
  235. return {"id": user.id, "name": user.name}
  236. @sio.on("join-channels")
  237. async def join_channel(sid, data):
  238. auth = data["auth"] if "auth" in data else None
  239. if not auth or "token" not in auth:
  240. return
  241. data = decode_token(auth["token"])
  242. if data is None or "id" not in data:
  243. return
  244. user = Users.get_user_by_id(data["id"])
  245. if not user:
  246. return
  247. # Join all the channels
  248. channels = Channels.get_channels_by_user_id(user.id)
  249. log.debug(f"{channels=}")
  250. for channel in channels:
  251. await sio.enter_room(sid, f"channel:{channel.id}")
  252. @sio.on("channel-events")
  253. async def channel_events(sid, data):
  254. room = f"channel:{data['channel_id']}"
  255. participants = sio.manager.get_participants(
  256. namespace="/",
  257. room=room,
  258. )
  259. sids = [sid for sid, _ in participants]
  260. if sid not in sids:
  261. return
  262. event_data = data["data"]
  263. event_type = event_data["type"]
  264. if event_type == "typing":
  265. await sio.emit(
  266. "channel-events",
  267. {
  268. "channel_id": data["channel_id"],
  269. "message_id": data.get("message_id", None),
  270. "data": event_data,
  271. "user": UserNameResponse(**SESSION_POOL[sid]).model_dump(),
  272. },
  273. room=room,
  274. )
  275. @sio.on("yjs:document:join")
  276. async def yjs_document_join(sid, data):
  277. """Handle user joining a document"""
  278. user = SESSION_POOL.get(sid)
  279. try:
  280. document_id = data["document_id"]
  281. if document_id.startswith("note:"):
  282. note_id = document_id.split(":")[1]
  283. note = Notes.get_note_by_id(note_id)
  284. if not note:
  285. log.error(f"Note {note_id} not found")
  286. return
  287. if user.get("role") != "admin" and has_access(
  288. user.get("id"), type="read", access_control=note.access_control
  289. ):
  290. log.error(
  291. f"User {user.get('id')} does not have access to note {note_id}"
  292. )
  293. return
  294. user_id = data.get("user_id", sid)
  295. user_name = data.get("user_name", "Anonymous")
  296. user_color = data.get("user_color", "#000000")
  297. log.info(f"User {user_id} joining document {document_id}")
  298. # Initialize document if it doesn't exist
  299. if document_id not in DOCUMENTS:
  300. DOCUMENTS[document_id] = {
  301. "ydoc": Y.Doc(), # Create actual Yjs document
  302. "users": set(),
  303. }
  304. DOCUMENT_USERS[document_id] = set()
  305. # Add user to document
  306. DOCUMENTS[document_id]["users"].add(sid)
  307. DOCUMENT_USERS[document_id].add(sid)
  308. # Join Socket.IO room
  309. await sio.enter_room(sid, f"doc_{document_id}")
  310. # Send current document state as a proper Yjs update
  311. ydoc = DOCUMENTS[document_id]["ydoc"]
  312. # Encode the entire document state as an update
  313. state_update = ydoc.get_update()
  314. await sio.emit(
  315. "yjs:document:state",
  316. {
  317. "document_id": document_id,
  318. "state": list(state_update), # Convert bytes to list for JSON
  319. },
  320. room=sid,
  321. )
  322. # Notify other users about the new user
  323. await sio.emit(
  324. "yjs:user:joined",
  325. {
  326. "document_id": document_id,
  327. "user_id": user_id,
  328. "user_name": user_name,
  329. "user_color": user_color,
  330. },
  331. room=f"doc_{document_id}",
  332. skip_sid=sid,
  333. )
  334. log.info(f"User {user_id} successfully joined document {document_id}")
  335. except Exception as e:
  336. log.error(f"Error in yjs_document_join: {e}")
  337. await sio.emit("error", {"message": "Failed to join document"}, room=sid)
  338. async def document_save_handler(document_id, data, user):
  339. if document_id.startswith("note:"):
  340. note_id = document_id.split(":")[1]
  341. note = Notes.get_note_by_id(note_id)
  342. if not note:
  343. log.error(f"Note {note_id} not found")
  344. return
  345. if user.get("role") != "admin" and has_access(
  346. user.get("id"), type="read", access_control=note.access_control
  347. ):
  348. log.error(f"User {user.get('id')} does not have access to note {note_id}")
  349. return
  350. Notes.update_note_by_id(note_id, NoteUpdateForm(data=data))
  351. @sio.on("yjs:document:update")
  352. async def yjs_document_update(sid, data):
  353. """Handle Yjs document updates"""
  354. try:
  355. document_id = data["document_id"]
  356. await stop_item_tasks(REDIS, document_id)
  357. user_id = data.get("user_id", sid)
  358. update = data["update"] # List of bytes from frontend
  359. if document_id not in DOCUMENTS:
  360. log.warning(f"Document {document_id} not found")
  361. return
  362. # Apply the update to the server's Yjs document
  363. ydoc = DOCUMENTS[document_id]["ydoc"]
  364. update_bytes = bytes(update)
  365. try:
  366. ydoc.apply_update(update_bytes)
  367. except Exception as e:
  368. log.error(f"Failed to apply Yjs update: {e}")
  369. return
  370. # Broadcast update to all other users in the document
  371. await sio.emit(
  372. "yjs:document:update",
  373. {
  374. "document_id": document_id,
  375. "user_id": user_id,
  376. "update": update,
  377. "socket_id": sid, # Add socket_id to match frontend filtering
  378. },
  379. room=f"doc_{document_id}",
  380. skip_sid=sid,
  381. )
  382. async def debounced_save():
  383. await asyncio.sleep(0.5)
  384. await document_save_handler(
  385. document_id, data.get("data", {}), SESSION_POOL.get(sid)
  386. )
  387. await stop_item_tasks(REDIS, document_id) # Cancel previous in-flight save
  388. await create_task(REDIS, debounced_save(), document_id)
  389. except Exception as e:
  390. log.error(f"Error in yjs_document_update: {e}")
  391. @sio.on("yjs:document:leave")
  392. async def yjs_document_leave(sid, data):
  393. """Handle user leaving a document"""
  394. try:
  395. document_id = data["document_id"]
  396. user_id = data.get("user_id", sid)
  397. log.info(f"User {user_id} leaving document {document_id}")
  398. if document_id in DOCUMENTS:
  399. DOCUMENTS[document_id]["users"].discard(sid)
  400. if document_id in DOCUMENT_USERS:
  401. DOCUMENT_USERS[document_id].discard(sid)
  402. # Leave Socket.IO room
  403. await sio.leave_room(sid, f"doc_{document_id}")
  404. # Notify other users
  405. await sio.emit(
  406. "yjs:user:left",
  407. {"document_id": document_id, "user_id": user_id},
  408. room=f"doc_{document_id}",
  409. )
  410. if document_id in DOCUMENTS and not DOCUMENTS[document_id]["users"]:
  411. # If no users left, clean up the document
  412. log.info(f"Cleaning up document {document_id} as no users are left")
  413. del DOCUMENTS[document_id]
  414. del DOCUMENT_USERS[document_id]
  415. except Exception as e:
  416. log.error(f"Error in yjs_document_leave: {e}")
  417. @sio.on("yjs:awareness:update")
  418. async def yjs_awareness_update(sid, data):
  419. """Handle awareness updates (cursors, selections, etc.)"""
  420. try:
  421. document_id = data["document_id"]
  422. user_id = data.get("user_id", sid)
  423. update = data["update"]
  424. # Broadcast awareness update to all other users in the document
  425. await sio.emit(
  426. "yjs:awareness:update",
  427. {"document_id": document_id, "user_id": user_id, "update": update},
  428. room=f"doc_{document_id}",
  429. skip_sid=sid,
  430. )
  431. except Exception as e:
  432. log.error(f"Error in yjs_awareness_update: {e}")
  433. @sio.event
  434. async def disconnect(sid):
  435. if sid in SESSION_POOL:
  436. user = SESSION_POOL[sid]
  437. del SESSION_POOL[sid]
  438. user_id = user["id"]
  439. USER_POOL[user_id] = [_sid for _sid in USER_POOL[user_id] if _sid != sid]
  440. if len(USER_POOL[user_id]) == 0:
  441. del USER_POOL[user_id]
  442. else:
  443. pass
  444. # print(f"Unknown session ID {sid} disconnected")
  445. def get_event_emitter(request_info, update_db=True):
  446. async def __event_emitter__(event_data):
  447. user_id = request_info["user_id"]
  448. session_ids = list(
  449. set(
  450. USER_POOL.get(user_id, [])
  451. + (
  452. [request_info.get("session_id")]
  453. if request_info.get("session_id")
  454. else []
  455. )
  456. )
  457. )
  458. emit_tasks = [
  459. sio.emit(
  460. "chat-events",
  461. {
  462. "chat_id": request_info.get("chat_id", None),
  463. "message_id": request_info.get("message_id", None),
  464. "data": event_data,
  465. },
  466. to=session_id,
  467. )
  468. for session_id in session_ids
  469. ]
  470. await asyncio.gather(*emit_tasks)
  471. if update_db:
  472. if "type" in event_data and event_data["type"] == "status":
  473. Chats.add_message_status_to_chat_by_id_and_message_id(
  474. request_info["chat_id"],
  475. request_info["message_id"],
  476. event_data.get("data", {}),
  477. )
  478. if "type" in event_data and event_data["type"] == "message":
  479. message = Chats.get_message_by_id_and_message_id(
  480. request_info["chat_id"],
  481. request_info["message_id"],
  482. )
  483. if message:
  484. content = message.get("content", "")
  485. content += event_data.get("data", {}).get("content", "")
  486. Chats.upsert_message_to_chat_by_id_and_message_id(
  487. request_info["chat_id"],
  488. request_info["message_id"],
  489. {
  490. "content": content,
  491. },
  492. )
  493. if "type" in event_data and event_data["type"] == "replace":
  494. content = event_data.get("data", {}).get("content", "")
  495. Chats.upsert_message_to_chat_by_id_and_message_id(
  496. request_info["chat_id"],
  497. request_info["message_id"],
  498. {
  499. "content": content,
  500. },
  501. )
  502. return __event_emitter__
  503. def get_event_call(request_info):
  504. async def __event_caller__(event_data):
  505. response = await sio.call(
  506. "chat-events",
  507. {
  508. "chat_id": request_info.get("chat_id", None),
  509. "message_id": request_info.get("message_id", None),
  510. "data": event_data,
  511. },
  512. to=request_info["session_id"],
  513. )
  514. return response
  515. return __event_caller__
  516. get_event_caller = get_event_call