main.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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. # TODO: Implement Yjs document management with Redis
  94. DOCUMENTS = {}
  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. aquire_func = release_func = renew_func = lambda: True
  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_user_ids_from_room(room):
  175. active_session_ids = sio.manager.get_participants(
  176. namespace="/",
  177. room=room,
  178. )
  179. active_user_ids = list(
  180. set(
  181. [SESSION_POOL.get(session_id[0])["id"] for session_id in active_session_ids]
  182. )
  183. )
  184. return active_user_ids
  185. def get_active_status_by_user_id(user_id):
  186. if user_id in USER_POOL:
  187. return True
  188. return False
  189. @sio.on("usage")
  190. async def usage(sid, data):
  191. if sid in SESSION_POOL:
  192. model_id = data["model"]
  193. # Record the timestamp for the last update
  194. current_time = int(time.time())
  195. # Store the new usage data and task
  196. USAGE_POOL[model_id] = {
  197. **(USAGE_POOL[model_id] if model_id in USAGE_POOL else {}),
  198. sid: {"updated_at": current_time},
  199. }
  200. @sio.event
  201. async def connect(sid, environ, auth):
  202. user = None
  203. if auth and "token" in auth:
  204. data = decode_token(auth["token"])
  205. if data is not None and "id" in data:
  206. user = Users.get_user_by_id(data["id"])
  207. if user:
  208. SESSION_POOL[sid] = user.model_dump()
  209. if user.id in USER_POOL:
  210. USER_POOL[user.id] = USER_POOL[user.id] + [sid]
  211. else:
  212. USER_POOL[user.id] = [sid]
  213. @sio.on("user-join")
  214. async def user_join(sid, data):
  215. auth = data["auth"] if "auth" in data else None
  216. if not auth or "token" not in auth:
  217. return
  218. data = decode_token(auth["token"])
  219. if data is None or "id" not in data:
  220. return
  221. user = Users.get_user_by_id(data["id"])
  222. if not user:
  223. return
  224. SESSION_POOL[sid] = user.model_dump()
  225. if user.id in USER_POOL:
  226. USER_POOL[user.id] = USER_POOL[user.id] + [sid]
  227. else:
  228. USER_POOL[user.id] = [sid]
  229. # Join all the channels
  230. channels = Channels.get_channels_by_user_id(user.id)
  231. log.debug(f"{channels=}")
  232. for channel in channels:
  233. await sio.enter_room(sid, f"channel:{channel.id}")
  234. return {"id": user.id, "name": user.name}
  235. @sio.on("join-channels")
  236. async def join_channel(sid, data):
  237. auth = data["auth"] if "auth" in data else None
  238. if not auth or "token" not in auth:
  239. return
  240. data = decode_token(auth["token"])
  241. if data is None or "id" not in data:
  242. return
  243. user = Users.get_user_by_id(data["id"])
  244. if not user:
  245. return
  246. # Join all the channels
  247. channels = Channels.get_channels_by_user_id(user.id)
  248. log.debug(f"{channels=}")
  249. for channel in channels:
  250. await sio.enter_room(sid, f"channel:{channel.id}")
  251. @sio.on("channel-events")
  252. async def channel_events(sid, data):
  253. room = f"channel:{data['channel_id']}"
  254. participants = sio.manager.get_participants(
  255. namespace="/",
  256. room=room,
  257. )
  258. sids = [sid for sid, _ in participants]
  259. if sid not in sids:
  260. return
  261. event_data = data["data"]
  262. event_type = event_data["type"]
  263. if event_type == "typing":
  264. await sio.emit(
  265. "channel-events",
  266. {
  267. "channel_id": data["channel_id"],
  268. "message_id": data.get("message_id", None),
  269. "data": event_data,
  270. "user": UserNameResponse(**SESSION_POOL[sid]).model_dump(),
  271. },
  272. room=room,
  273. )
  274. @sio.on("yjs:document:join")
  275. async def yjs_document_join(sid, data):
  276. """Handle user joining a document"""
  277. user = SESSION_POOL.get(sid)
  278. try:
  279. document_id = data["document_id"]
  280. if document_id.startswith("note:"):
  281. note_id = document_id.split(":")[1]
  282. note = Notes.get_note_by_id(note_id)
  283. if not note:
  284. log.error(f"Note {note_id} not found")
  285. return
  286. if (
  287. user.get("role") != "admin"
  288. and user.get("id") != note.user_id
  289. and not has_access(
  290. user.get("id"), type="read", access_control=note.access_control
  291. )
  292. ):
  293. log.error(
  294. f"User {user.get('id')} does not have access to note {note_id}"
  295. )
  296. return
  297. user_id = data.get("user_id", sid)
  298. user_name = data.get("user_name", "Anonymous")
  299. user_color = data.get("user_color", "#000000")
  300. log.info(f"User {user_id} joining document {document_id}")
  301. # Initialize document if it doesn't exist
  302. if document_id not in DOCUMENTS:
  303. DOCUMENTS[document_id] = {
  304. "ydoc": Y.Doc(), # Create actual Yjs document
  305. "users": set(),
  306. }
  307. # Add user to document
  308. DOCUMENTS[document_id]["users"].add(sid)
  309. # Join Socket.IO room
  310. await sio.enter_room(sid, f"doc_{document_id}")
  311. # Send current document state as a proper Yjs update
  312. ydoc = DOCUMENTS[document_id]["ydoc"]
  313. # Encode the entire document state as an update
  314. state_update = ydoc.get_update()
  315. await sio.emit(
  316. "yjs:document:state",
  317. {
  318. "document_id": document_id,
  319. "state": list(state_update), # Convert bytes to list for JSON
  320. },
  321. room=sid,
  322. )
  323. # Notify other users about the new user
  324. await sio.emit(
  325. "yjs:user:joined",
  326. {
  327. "document_id": document_id,
  328. "user_id": user_id,
  329. "user_name": user_name,
  330. "user_color": user_color,
  331. },
  332. room=f"doc_{document_id}",
  333. skip_sid=sid,
  334. )
  335. log.info(f"User {user_id} successfully joined document {document_id}")
  336. except Exception as e:
  337. log.error(f"Error in yjs_document_join: {e}")
  338. await sio.emit("error", {"message": "Failed to join document"}, room=sid)
  339. async def document_save_handler(document_id, data, user):
  340. if document_id.startswith("note:"):
  341. note_id = document_id.split(":")[1]
  342. note = Notes.get_note_by_id(note_id)
  343. if not note:
  344. log.error(f"Note {note_id} not found")
  345. return
  346. if (
  347. user.get("role") != "admin"
  348. and user.get("id") != note.user_id
  349. and not has_access(
  350. user.get("id"), type="read", access_control=note.access_control
  351. )
  352. ):
  353. log.error(f"User {user.get('id')} does not have access to note {note_id}")
  354. return
  355. Notes.update_note_by_id(note_id, NoteUpdateForm(data=data))
  356. @sio.on("yjs:document:update")
  357. async def yjs_document_update(sid, data):
  358. """Handle Yjs document updates"""
  359. try:
  360. document_id = data["document_id"]
  361. try:
  362. await stop_item_tasks(REDIS, document_id)
  363. except:
  364. pass
  365. user_id = data.get("user_id", sid)
  366. update = data["update"] # List of bytes from frontend
  367. if document_id not in DOCUMENTS:
  368. log.warning(f"Document {document_id} not found")
  369. return
  370. # Apply the update to the server's Yjs document
  371. ydoc = DOCUMENTS[document_id]["ydoc"]
  372. update_bytes = bytes(update)
  373. try:
  374. ydoc.apply_update(update_bytes)
  375. except Exception as e:
  376. log.error(f"Failed to apply Yjs update: {e}")
  377. return
  378. # Broadcast update to all other users in the document
  379. await sio.emit(
  380. "yjs:document:update",
  381. {
  382. "document_id": document_id,
  383. "user_id": user_id,
  384. "update": update,
  385. "socket_id": sid, # Add socket_id to match frontend filtering
  386. },
  387. room=f"doc_{document_id}",
  388. skip_sid=sid,
  389. )
  390. async def debounced_save():
  391. await asyncio.sleep(0.5)
  392. await document_save_handler(
  393. document_id, data.get("data", {}), SESSION_POOL.get(sid)
  394. )
  395. await create_task(REDIS, debounced_save(), document_id)
  396. except Exception as e:
  397. log.error(f"Error in yjs_document_update: {e}")
  398. @sio.on("yjs:document:leave")
  399. async def yjs_document_leave(sid, data):
  400. """Handle user leaving a document"""
  401. try:
  402. document_id = data["document_id"]
  403. user_id = data.get("user_id", sid)
  404. log.info(f"User {user_id} leaving document {document_id}")
  405. if document_id in DOCUMENTS:
  406. DOCUMENTS[document_id]["users"].discard(sid)
  407. # Leave Socket.IO room
  408. await sio.leave_room(sid, f"doc_{document_id}")
  409. # Notify other users
  410. await sio.emit(
  411. "yjs:user:left",
  412. {"document_id": document_id, "user_id": user_id},
  413. room=f"doc_{document_id}",
  414. )
  415. if document_id in DOCUMENTS and not DOCUMENTS[document_id]["users"]:
  416. # If no users left, clean up the document
  417. log.info(f"Cleaning up document {document_id} as no users are left")
  418. del DOCUMENTS[document_id]
  419. except Exception as e:
  420. log.error(f"Error in yjs_document_leave: {e}")
  421. @sio.on("yjs:awareness:update")
  422. async def yjs_awareness_update(sid, data):
  423. """Handle awareness updates (cursors, selections, etc.)"""
  424. try:
  425. document_id = data["document_id"]
  426. user_id = data.get("user_id", sid)
  427. update = data["update"]
  428. # Broadcast awareness update to all other users in the document
  429. await sio.emit(
  430. "yjs:awareness:update",
  431. {"document_id": document_id, "user_id": user_id, "update": update},
  432. room=f"doc_{document_id}",
  433. skip_sid=sid,
  434. )
  435. except Exception as e:
  436. log.error(f"Error in yjs_awareness_update: {e}")
  437. @sio.event
  438. async def disconnect(sid):
  439. if sid in SESSION_POOL:
  440. user = SESSION_POOL[sid]
  441. del SESSION_POOL[sid]
  442. user_id = user["id"]
  443. USER_POOL[user_id] = [_sid for _sid in USER_POOL[user_id] if _sid != sid]
  444. if len(USER_POOL[user_id]) == 0:
  445. del USER_POOL[user_id]
  446. else:
  447. pass
  448. # print(f"Unknown session ID {sid} disconnected")
  449. def get_event_emitter(request_info, update_db=True):
  450. async def __event_emitter__(event_data):
  451. user_id = request_info["user_id"]
  452. session_ids = list(
  453. set(
  454. USER_POOL.get(user_id, [])
  455. + (
  456. [request_info.get("session_id")]
  457. if request_info.get("session_id")
  458. else []
  459. )
  460. )
  461. )
  462. emit_tasks = [
  463. sio.emit(
  464. "chat-events",
  465. {
  466. "chat_id": request_info.get("chat_id", None),
  467. "message_id": request_info.get("message_id", None),
  468. "data": event_data,
  469. },
  470. to=session_id,
  471. )
  472. for session_id in session_ids
  473. ]
  474. await asyncio.gather(*emit_tasks)
  475. if update_db:
  476. if "type" in event_data and event_data["type"] == "status":
  477. Chats.add_message_status_to_chat_by_id_and_message_id(
  478. request_info["chat_id"],
  479. request_info["message_id"],
  480. event_data.get("data", {}),
  481. )
  482. if "type" in event_data and event_data["type"] == "message":
  483. message = Chats.get_message_by_id_and_message_id(
  484. request_info["chat_id"],
  485. request_info["message_id"],
  486. )
  487. if message:
  488. content = message.get("content", "")
  489. content += event_data.get("data", {}).get("content", "")
  490. Chats.upsert_message_to_chat_by_id_and_message_id(
  491. request_info["chat_id"],
  492. request_info["message_id"],
  493. {
  494. "content": content,
  495. },
  496. )
  497. if "type" in event_data and event_data["type"] == "replace":
  498. content = event_data.get("data", {}).get("content", "")
  499. Chats.upsert_message_to_chat_by_id_and_message_id(
  500. request_info["chat_id"],
  501. request_info["message_id"],
  502. {
  503. "content": content,
  504. },
  505. )
  506. return __event_emitter__
  507. def get_event_call(request_info):
  508. async def __event_caller__(event_data):
  509. response = await sio.call(
  510. "chat-events",
  511. {
  512. "chat_id": request_info.get("chat_id", None),
  513. "message_id": request_info.get("message_id", None),
  514. "data": event_data,
  515. },
  516. to=request_info["session_id"],
  517. )
  518. return response
  519. return __event_caller__
  520. get_event_caller = get_event_call