WebSocket.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { createContext, useContext, useEffect, useState, useRef } from 'react';
  2. import { io, Socket } from 'socket.io-client';
  3. import { WS_EVENTS, WS_EVENTS_TYPE } from '../consts/Http';
  4. import { authContext } from '../context/Auth';
  5. import { url } from '../http/Axios';
  6. import { CollectionHttp } from '../http/Collection';
  7. import { MilvusHttp } from '../http/Milvus';
  8. import { CollectionView } from '../pages/collections/Types';
  9. import { checkIndexBuilding, checkLoading } from '../utils/Validation';
  10. import { WebSocketType } from './Types';
  11. export const webSokcetContext = createContext<WebSocketType>({
  12. collections: [],
  13. setCollections: data => {},
  14. });
  15. const { Provider } = webSokcetContext;
  16. export const WebSocketProvider = (props: { children: React.ReactNode }) => {
  17. const [collections, setCollections] = useState<CollectionView[]>([]);
  18. const { isAuth } = useContext(authContext);
  19. const socket = useRef<Socket | null>(null);
  20. useEffect(() => {
  21. if (isAuth) {
  22. socket.current = io(url);
  23. socket.current.on('connect', function () {
  24. console.log('--- ws connected ---');
  25. });
  26. /**
  27. * Because of collections data may be big, so we still use ajax to fetch data.
  28. * Only when collection list includes index building or loading collection,
  29. * server will keep push collections data from milvus every seconds.
  30. * After all collections are not loading or building index, tell server stop pulling data.
  31. */
  32. socket.current.on(WS_EVENTS.COLLECTION, (data: any) => {
  33. const collections: CollectionHttp[] = data.map(
  34. (v: any) => new CollectionHttp(v)
  35. );
  36. const hasLoadingOrBuildingCollection = collections.some(
  37. v => checkLoading(v) || checkIndexBuilding(v)
  38. );
  39. setCollections(collections);
  40. // If no collection is building index or loading collection
  41. // stop server cron job
  42. if (!hasLoadingOrBuildingCollection) {
  43. MilvusHttp.triggerCron({
  44. name: WS_EVENTS.COLLECTION,
  45. type: WS_EVENTS_TYPE.STOP,
  46. });
  47. }
  48. });
  49. } else {
  50. socket.current?.disconnect();
  51. }
  52. }, [isAuth]);
  53. return (
  54. <Provider
  55. value={{
  56. collections,
  57. setCollections,
  58. }}
  59. >
  60. {props.children}
  61. </Provider>
  62. );
  63. };