main.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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. REDIS_KEY_PREFIX,
  26. )
  27. from open_webui.utils.auth import decode_token
  28. from open_webui.socket.utils import RedisDict, RedisLock, YdocManager
  29. from open_webui.tasks import create_task, stop_item_tasks
  30. from open_webui.utils.redis import get_redis_connection
  31. from open_webui.utils.access_control import has_access, get_users_with_access
  32. from open_webui.env import (
  33. GLOBAL_LOG_LEVEL,
  34. SRC_LOG_LEVELS,
  35. )
  36. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  37. log = logging.getLogger(__name__)
  38. log.setLevel(SRC_LOG_LEVELS["SOCKET"])
  39. REDIS = None
  40. if WEBSOCKET_MANAGER == "redis":
  41. if WEBSOCKET_SENTINEL_HOSTS:
  42. mgr = socketio.AsyncRedisManager(
  43. get_sentinel_url_from_env(
  44. WEBSOCKET_REDIS_URL, WEBSOCKET_SENTINEL_HOSTS, WEBSOCKET_SENTINEL_PORT
  45. )
  46. )
  47. else:
  48. mgr = socketio.AsyncRedisManager(WEBSOCKET_REDIS_URL)
  49. sio = socketio.AsyncServer(
  50. cors_allowed_origins=[],
  51. async_mode="asgi",
  52. transports=(["websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]),
  53. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  54. always_connect=True,
  55. client_manager=mgr,
  56. )
  57. else:
  58. sio = socketio.AsyncServer(
  59. cors_allowed_origins=[],
  60. async_mode="asgi",
  61. transports=(["websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]),
  62. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  63. always_connect=True,
  64. )
  65. # Timeout duration in seconds
  66. TIMEOUT_DURATION = 3
  67. # Dictionary to maintain the user pool
  68. if WEBSOCKET_MANAGER == "redis":
  69. log.debug("Using Redis to manage websockets.")
  70. REDIS = get_redis_connection(
  71. redis_url=WEBSOCKET_REDIS_URL,
  72. redis_sentinels=get_sentinels_from_env(
  73. WEBSOCKET_SENTINEL_HOSTS, WEBSOCKET_SENTINEL_PORT
  74. ),
  75. async_mode=True,
  76. )
  77. redis_sentinels = get_sentinels_from_env(
  78. WEBSOCKET_SENTINEL_HOSTS, WEBSOCKET_SENTINEL_PORT
  79. )
  80. SESSION_POOL = RedisDict(
  81. f"{REDIS_KEY_PREFIX}:session_pool",
  82. redis_url=WEBSOCKET_REDIS_URL,
  83. redis_sentinels=redis_sentinels,
  84. )
  85. USER_POOL = RedisDict(
  86. f"{REDIS_KEY_PREFIX}:user_pool",
  87. redis_url=WEBSOCKET_REDIS_URL,
  88. redis_sentinels=redis_sentinels,
  89. )
  90. USAGE_POOL = RedisDict(
  91. f"{REDIS_KEY_PREFIX}:usage_pool",
  92. redis_url=WEBSOCKET_REDIS_URL,
  93. redis_sentinels=redis_sentinels,
  94. )
  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. aquire_func = release_func = renew_func = lambda: True
  109. YDOC_MANAGER = YdocManager(
  110. redis=REDIS,
  111. redis_key_prefix=f"{REDIS_KEY_PREFIX}: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("join-note")
  257. async def join_note(sid, data):
  258. auth = data["auth"] if "auth" in data else None
  259. if not auth or "token" not in auth:
  260. return
  261. token_data = decode_token(auth["token"])
  262. if token_data is None or "id" not in token_data:
  263. return
  264. user = Users.get_user_by_id(token_data["id"])
  265. if not user:
  266. return
  267. note = Notes.get_note_by_id(data["note_id"])
  268. if not note:
  269. log.error(f"Note {data['note_id']} not found for user {user.id}")
  270. return
  271. if (
  272. user.role != "admin"
  273. and user.id != note.user_id
  274. and not has_access(user.id, type="read", access_control=note.access_control)
  275. ):
  276. log.error(f"User {user.id} does not have access to note {data['note_id']}")
  277. return
  278. log.debug(f"Joining note {note.id} for user {user.id}")
  279. await sio.enter_room(sid, f"note:{note.id}")
  280. @sio.on("channel-events")
  281. async def channel_events(sid, data):
  282. room = f"channel:{data['channel_id']}"
  283. participants = sio.manager.get_participants(
  284. namespace="/",
  285. room=room,
  286. )
  287. sids = [sid for sid, _ in participants]
  288. if sid not in sids:
  289. return
  290. event_data = data["data"]
  291. event_type = event_data["type"]
  292. if event_type == "typing":
  293. await sio.emit(
  294. "channel-events",
  295. {
  296. "channel_id": data["channel_id"],
  297. "message_id": data.get("message_id", None),
  298. "data": event_data,
  299. "user": UserNameResponse(**SESSION_POOL[sid]).model_dump(),
  300. },
  301. room=room,
  302. )
  303. @sio.on("ydoc:document:join")
  304. async def ydoc_document_join(sid, data):
  305. """Handle user joining a document"""
  306. user = SESSION_POOL.get(sid)
  307. try:
  308. document_id = data["document_id"]
  309. if document_id.startswith("note:"):
  310. note_id = document_id.split(":")[1]
  311. note = Notes.get_note_by_id(note_id)
  312. if not note:
  313. log.error(f"Note {note_id} not found")
  314. return
  315. if (
  316. user.get("role") != "admin"
  317. and user.get("id") != note.user_id
  318. and not has_access(
  319. user.get("id"), type="read", access_control=note.access_control
  320. )
  321. ):
  322. log.error(
  323. f"User {user.get('id')} does not have access to note {note_id}"
  324. )
  325. return
  326. user_id = data.get("user_id", sid)
  327. user_name = data.get("user_name", "Anonymous")
  328. user_color = data.get("user_color", "#000000")
  329. log.info(f"User {user_id} joining document {document_id}")
  330. await YDOC_MANAGER.add_user(document_id=document_id, user_id=sid)
  331. # Join Socket.IO room
  332. await sio.enter_room(sid, f"doc_{document_id}")
  333. active_session_ids = get_session_ids_from_room(f"doc_{document_id}")
  334. # Get the Yjs document state
  335. ydoc = Y.Doc()
  336. updates = await YDOC_MANAGER.get_updates(document_id)
  337. for update in updates:
  338. ydoc.apply_update(bytes(update))
  339. # Encode the entire document state as an update
  340. state_update = ydoc.get_update()
  341. await sio.emit(
  342. "ydoc:document:state",
  343. {
  344. "document_id": document_id,
  345. "state": list(state_update), # Convert bytes to list for JSON
  346. "sessions": active_session_ids,
  347. },
  348. room=sid,
  349. )
  350. # Notify other users about the new user
  351. await sio.emit(
  352. "ydoc:user:joined",
  353. {
  354. "document_id": document_id,
  355. "user_id": user_id,
  356. "user_name": user_name,
  357. "user_color": user_color,
  358. },
  359. room=f"doc_{document_id}",
  360. skip_sid=sid,
  361. )
  362. log.info(f"User {user_id} successfully joined document {document_id}")
  363. except Exception as e:
  364. log.error(f"Error in yjs_document_join: {e}")
  365. await sio.emit("error", {"message": "Failed to join document"}, room=sid)
  366. async def document_save_handler(document_id, data, user):
  367. if document_id.startswith("note:"):
  368. note_id = document_id.split(":")[1]
  369. note = Notes.get_note_by_id(note_id)
  370. if not note:
  371. log.error(f"Note {note_id} not found")
  372. return
  373. if (
  374. user.get("role") != "admin"
  375. and user.get("id") != note.user_id
  376. and not has_access(
  377. user.get("id"), type="read", access_control=note.access_control
  378. )
  379. ):
  380. log.error(f"User {user.get('id')} does not have access to note {note_id}")
  381. return
  382. Notes.update_note_by_id(note_id, NoteUpdateForm(data=data))
  383. @sio.on("ydoc:document:state")
  384. async def yjs_document_state(sid, data):
  385. """Send the current state of the Yjs document to the user"""
  386. try:
  387. document_id = data["document_id"]
  388. room = f"doc_{document_id}"
  389. active_session_ids = get_session_ids_from_room(room)
  390. if sid not in active_session_ids:
  391. log.warning(f"Session {sid} not in room {room}. Cannot send state.")
  392. return
  393. if not await YDOC_MANAGER.document_exists(document_id):
  394. log.warning(f"Document {document_id} not found")
  395. return
  396. # Get the Yjs document state
  397. ydoc = Y.Doc()
  398. updates = await YDOC_MANAGER.get_updates(document_id)
  399. for update in updates:
  400. ydoc.apply_update(bytes(update))
  401. # Encode the entire document state as an update
  402. state_update = ydoc.get_update()
  403. await sio.emit(
  404. "ydoc:document:state",
  405. {
  406. "document_id": document_id,
  407. "state": list(state_update), # Convert bytes to list for JSON
  408. "sessions": active_session_ids,
  409. },
  410. room=sid,
  411. )
  412. except Exception as e:
  413. log.error(f"Error in yjs_document_state: {e}")
  414. @sio.on("ydoc:document:update")
  415. async def yjs_document_update(sid, data):
  416. """Handle Yjs document updates"""
  417. try:
  418. document_id = data["document_id"]
  419. try:
  420. await stop_item_tasks(REDIS, document_id)
  421. except:
  422. pass
  423. user_id = data.get("user_id", sid)
  424. update = data["update"] # List of bytes from frontend
  425. await YDOC_MANAGER.append_to_updates(
  426. document_id=document_id,
  427. update=update, # Convert list of bytes to bytes
  428. )
  429. # Broadcast update to all other users in the document
  430. await sio.emit(
  431. "ydoc:document:update",
  432. {
  433. "document_id": document_id,
  434. "user_id": user_id,
  435. "update": update,
  436. "socket_id": sid, # Add socket_id to match frontend filtering
  437. },
  438. room=f"doc_{document_id}",
  439. skip_sid=sid,
  440. )
  441. async def debounced_save():
  442. await asyncio.sleep(0.5)
  443. await document_save_handler(
  444. document_id, data.get("data", {}), SESSION_POOL.get(sid)
  445. )
  446. if data.get("data"):
  447. await create_task(REDIS, debounced_save(), document_id)
  448. except Exception as e:
  449. log.error(f"Error in yjs_document_update: {e}")
  450. @sio.on("ydoc:document:leave")
  451. async def yjs_document_leave(sid, data):
  452. """Handle user leaving a document"""
  453. try:
  454. document_id = data["document_id"]
  455. user_id = data.get("user_id", sid)
  456. log.info(f"User {user_id} leaving document {document_id}")
  457. # Remove user from the document
  458. await YDOC_MANAGER.remove_user(document_id=document_id, user_id=sid)
  459. # Leave Socket.IO room
  460. await sio.leave_room(sid, f"doc_{document_id}")
  461. # Notify other users
  462. await sio.emit(
  463. "ydoc:user:left",
  464. {"document_id": document_id, "user_id": user_id},
  465. room=f"doc_{document_id}",
  466. )
  467. if (
  468. await YDOC_MANAGER.document_exists(document_id)
  469. and len(await YDOC_MANAGER.get_users(document_id)) == 0
  470. ):
  471. log.info(f"Cleaning up document {document_id} as no users are left")
  472. await YDOC_MANAGER.clear_document(document_id)
  473. except Exception as e:
  474. log.error(f"Error in yjs_document_leave: {e}")
  475. @sio.on("ydoc:awareness:update")
  476. async def yjs_awareness_update(sid, data):
  477. """Handle awareness updates (cursors, selections, etc.)"""
  478. try:
  479. document_id = data["document_id"]
  480. user_id = data.get("user_id", sid)
  481. update = data["update"]
  482. # Broadcast awareness update to all other users in the document
  483. await sio.emit(
  484. "ydoc:awareness:update",
  485. {"document_id": document_id, "user_id": user_id, "update": update},
  486. room=f"doc_{document_id}",
  487. skip_sid=sid,
  488. )
  489. except Exception as e:
  490. log.error(f"Error in yjs_awareness_update: {e}")
  491. @sio.event
  492. async def disconnect(sid):
  493. if sid in SESSION_POOL:
  494. user = SESSION_POOL[sid]
  495. del SESSION_POOL[sid]
  496. user_id = user["id"]
  497. USER_POOL[user_id] = [_sid for _sid in USER_POOL[user_id] if _sid != sid]
  498. if len(USER_POOL[user_id]) == 0:
  499. del USER_POOL[user_id]
  500. await YDOC_MANAGER.remove_user_from_all_documents(sid)
  501. else:
  502. pass
  503. # print(f"Unknown session ID {sid} disconnected")
  504. def get_event_emitter(request_info, update_db=True):
  505. async def __event_emitter__(event_data):
  506. user_id = request_info["user_id"]
  507. session_ids = list(
  508. set(
  509. USER_POOL.get(user_id, [])
  510. + (
  511. [request_info.get("session_id")]
  512. if request_info.get("session_id")
  513. else []
  514. )
  515. )
  516. )
  517. emit_tasks = [
  518. sio.emit(
  519. "chat-events",
  520. {
  521. "chat_id": request_info.get("chat_id", None),
  522. "message_id": request_info.get("message_id", None),
  523. "data": event_data,
  524. },
  525. to=session_id,
  526. )
  527. for session_id in session_ids
  528. ]
  529. await asyncio.gather(*emit_tasks)
  530. if update_db:
  531. if "type" in event_data and event_data["type"] == "status":
  532. Chats.add_message_status_to_chat_by_id_and_message_id(
  533. request_info["chat_id"],
  534. request_info["message_id"],
  535. event_data.get("data", {}),
  536. )
  537. if "type" in event_data and event_data["type"] == "message":
  538. message = Chats.get_message_by_id_and_message_id(
  539. request_info["chat_id"],
  540. request_info["message_id"],
  541. )
  542. if message:
  543. content = message.get("content", "")
  544. content += event_data.get("data", {}).get("content", "")
  545. Chats.upsert_message_to_chat_by_id_and_message_id(
  546. request_info["chat_id"],
  547. request_info["message_id"],
  548. {
  549. "content": content,
  550. },
  551. )
  552. if "type" in event_data and event_data["type"] == "replace":
  553. content = event_data.get("data", {}).get("content", "")
  554. Chats.upsert_message_to_chat_by_id_and_message_id(
  555. request_info["chat_id"],
  556. request_info["message_id"],
  557. {
  558. "content": content,
  559. },
  560. )
  561. return __event_emitter__
  562. def get_event_call(request_info):
  563. async def __event_caller__(event_data):
  564. response = await sio.call(
  565. "chat-events",
  566. {
  567. "chat_id": request_info.get("chat_id", None),
  568. "message_id": request_info.get("message_id", None),
  569. "data": event_data,
  570. },
  571. to=request_info["session_id"],
  572. )
  573. return response
  574. return __event_caller__
  575. get_event_caller = get_event_call