2
0

WebSocket.tsx 2.0 KB

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