main.py 21 KB

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