main.py 20 KB

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