main.py 20 KB

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