main.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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_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("ydoc:document:join")
  275. async def ydoc_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. "updates": [], # Store updates for the 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 = Y.Doc()
  313. if document_id in DOCUMENTS:
  314. # If the document already exists, apply its updates
  315. for update in DOCUMENTS[document_id]["updates"]:
  316. ydoc.apply_update(bytes(update))
  317. # Encode the entire document state as an update
  318. state_update = ydoc.get_update()
  319. await sio.emit(
  320. "ydoc:document:state",
  321. {
  322. "document_id": document_id,
  323. "state": list(state_update), # Convert bytes to list for JSON
  324. },
  325. room=sid,
  326. )
  327. # Notify other users about the new user
  328. await sio.emit(
  329. "ydoc:user:joined",
  330. {
  331. "document_id": document_id,
  332. "user_id": user_id,
  333. "user_name": user_name,
  334. "user_color": user_color,
  335. },
  336. room=f"doc_{document_id}",
  337. skip_sid=sid,
  338. )
  339. log.info(f"User {user_id} successfully joined document {document_id}")
  340. except Exception as e:
  341. log.error(f"Error in yjs_document_join: {e}")
  342. await sio.emit("error", {"message": "Failed to join document"}, room=sid)
  343. async def document_save_handler(document_id, data, user):
  344. if document_id.startswith("note:"):
  345. note_id = document_id.split(":")[1]
  346. note = Notes.get_note_by_id(note_id)
  347. if not note:
  348. log.error(f"Note {note_id} not found")
  349. return
  350. if (
  351. user.get("role") != "admin"
  352. and user.get("id") != note.user_id
  353. and not has_access(
  354. user.get("id"), type="read", access_control=note.access_control
  355. )
  356. ):
  357. log.error(f"User {user.get('id')} does not have access to note {note_id}")
  358. return
  359. Notes.update_note_by_id(note_id, NoteUpdateForm(data=data))
  360. @sio.on("ydoc:document:update")
  361. async def yjs_document_update(sid, data):
  362. """Handle Yjs document updates"""
  363. try:
  364. document_id = data["document_id"]
  365. try:
  366. await stop_item_tasks(REDIS, document_id)
  367. except:
  368. pass
  369. user_id = data.get("user_id", sid)
  370. update = data["update"] # List of bytes from frontend
  371. if document_id not in DOCUMENTS:
  372. log.warning(f"Document {document_id} not found")
  373. return
  374. updates = DOCUMENTS[document_id]["updates"]
  375. updates.append(update)
  376. # Broadcast update to all other users in the document
  377. await sio.emit(
  378. "ydoc:document:update",
  379. {
  380. "document_id": document_id,
  381. "user_id": user_id,
  382. "update": update,
  383. "socket_id": sid, # Add socket_id to match frontend filtering
  384. },
  385. room=f"doc_{document_id}",
  386. skip_sid=sid,
  387. )
  388. async def debounced_save():
  389. await asyncio.sleep(0.5)
  390. await document_save_handler(
  391. document_id, data.get("data", {}), SESSION_POOL.get(sid)
  392. )
  393. await create_task(REDIS, debounced_save(), document_id)
  394. except Exception as e:
  395. log.error(f"Error in yjs_document_update: {e}")
  396. @sio.on("ydoc:document:leave")
  397. async def yjs_document_leave(sid, data):
  398. """Handle user leaving a document"""
  399. try:
  400. document_id = data["document_id"]
  401. user_id = data.get("user_id", sid)
  402. log.info(f"User {user_id} leaving document {document_id}")
  403. if document_id in DOCUMENTS:
  404. DOCUMENTS[document_id]["users"].discard(sid)
  405. # Leave Socket.IO room
  406. await sio.leave_room(sid, f"doc_{document_id}")
  407. # Notify other users
  408. await sio.emit(
  409. "ydoc:user:left",
  410. {"document_id": document_id, "user_id": user_id},
  411. room=f"doc_{document_id}",
  412. )
  413. if document_id in DOCUMENTS and not DOCUMENTS[document_id]["users"]:
  414. # If no users left, clean up the document
  415. log.info(f"Cleaning up document {document_id} as no users are left")
  416. del DOCUMENTS[document_id]
  417. except Exception as e:
  418. log.error(f"Error in yjs_document_leave: {e}")
  419. @sio.on("ydoc:awareness:update")
  420. async def yjs_awareness_update(sid, data):
  421. """Handle awareness updates (cursors, selections, etc.)"""
  422. try:
  423. document_id = data["document_id"]
  424. user_id = data.get("user_id", sid)
  425. update = data["update"]
  426. # Broadcast awareness update to all other users in the document
  427. await sio.emit(
  428. "ydoc:awareness:update",
  429. {"document_id": document_id, "user_id": user_id, "update": update},
  430. room=f"doc_{document_id}",
  431. skip_sid=sid,
  432. )
  433. except Exception as e:
  434. log.error(f"Error in yjs_awareness_update: {e}")
  435. @sio.event
  436. async def disconnect(sid):
  437. if sid in SESSION_POOL:
  438. user = SESSION_POOL[sid]
  439. del SESSION_POOL[sid]
  440. user_id = user["id"]
  441. USER_POOL[user_id] = [_sid for _sid in USER_POOL[user_id] if _sid != sid]
  442. if len(USER_POOL[user_id]) == 0:
  443. del USER_POOL[user_id]
  444. else:
  445. pass
  446. # print(f"Unknown session ID {sid} disconnected")
  447. def get_event_emitter(request_info, update_db=True):
  448. async def __event_emitter__(event_data):
  449. user_id = request_info["user_id"]
  450. session_ids = list(
  451. set(
  452. USER_POOL.get(user_id, [])
  453. + (
  454. [request_info.get("session_id")]
  455. if request_info.get("session_id")
  456. else []
  457. )
  458. )
  459. )
  460. emit_tasks = [
  461. sio.emit(
  462. "chat-events",
  463. {
  464. "chat_id": request_info.get("chat_id", None),
  465. "message_id": request_info.get("message_id", None),
  466. "data": event_data,
  467. },
  468. to=session_id,
  469. )
  470. for session_id in session_ids
  471. ]
  472. await asyncio.gather(*emit_tasks)
  473. if update_db:
  474. if "type" in event_data and event_data["type"] == "status":
  475. Chats.add_message_status_to_chat_by_id_and_message_id(
  476. request_info["chat_id"],
  477. request_info["message_id"],
  478. event_data.get("data", {}),
  479. )
  480. if "type" in event_data and event_data["type"] == "message":
  481. message = Chats.get_message_by_id_and_message_id(
  482. request_info["chat_id"],
  483. request_info["message_id"],
  484. )
  485. if message:
  486. content = message.get("content", "")
  487. content += event_data.get("data", {}).get("content", "")
  488. Chats.upsert_message_to_chat_by_id_and_message_id(
  489. request_info["chat_id"],
  490. request_info["message_id"],
  491. {
  492. "content": content,
  493. },
  494. )
  495. if "type" in event_data and event_data["type"] == "replace":
  496. content = event_data.get("data", {}).get("content", "")
  497. Chats.upsert_message_to_chat_by_id_and_message_id(
  498. request_info["chat_id"],
  499. request_info["message_id"],
  500. {
  501. "content": content,
  502. },
  503. )
  504. return __event_emitter__
  505. def get_event_call(request_info):
  506. async def __event_caller__(event_data):
  507. response = await sio.call(
  508. "chat-events",
  509. {
  510. "chat_id": request_info.get("chat_id", None),
  511. "message_id": request_info.get("message_id", None),
  512. "data": event_data,
  513. },
  514. to=request_info["session_id"],
  515. )
  516. return response
  517. return __event_caller__
  518. get_event_caller = get_event_call