app.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. import express from 'express';
  2. import cors from 'cors';
  3. import helmet from 'helmet';
  4. import * as http from 'http';
  5. import { Server, Socket } from 'socket.io';
  6. import { router as connectRouter } from './milvus';
  7. import { router as collectionsRouter } from './collections';
  8. import { router as partitionsRouter } from './partitions';
  9. import { router as schemaRouter } from './schema';
  10. import { router as cronsRouter } from './crons';
  11. import { router as userRouter } from './users';
  12. import { pubSub } from './events';
  13. import {
  14. TransformResMiddlerware,
  15. LoggingMiddleware,
  16. ErrorMiddleware,
  17. ReqHeaderMiddleware,
  18. } from './middlewares';
  19. import { getDirectories, getDirectoriesSync, generateCfgs } from './utils';
  20. import * as path from 'path';
  21. import chalk from 'chalk';
  22. import { surveSwaggerSpecification } from './swagger';
  23. import swaggerUi from 'swagger-ui-express';
  24. import LruCache from 'lru-cache';
  25. import { EXPIRED_TIME, INSIGHT_CACHE } from './utils/Const';
  26. const PLUGIN_DEV = process.env?.PLUGIN_DEV;
  27. const SRC_PLUGIN_DIR = 'src/plugins';
  28. const DEV_PLUGIN_DIR = '../../src/*/server';
  29. const insightCache = new LruCache({
  30. maxAge: EXPIRED_TIME,
  31. updateAgeOnGet: true,
  32. });
  33. export const app = express();
  34. const PORT = 3000;
  35. // initialize a simple http server
  36. const server = http.createServer(app);
  37. // initialize the WebSocket server instance
  38. const io = new Server(server, {
  39. cors: {
  40. origin: '*',
  41. methods: ['GET', 'POST'],
  42. },
  43. });
  44. app.set(INSIGHT_CACHE, insightCache);
  45. // https://expressjs.com/en/resources/middleware/cors.html
  46. app.use(cors());
  47. // https://github.com/helmetjs/helmet
  48. app.use(
  49. helmet({
  50. contentSecurityPolicy: false,
  51. })
  52. );
  53. app.use(express.json({ limit: '150MB' }));
  54. // TransformResInterceptor
  55. app.use(TransformResMiddlerware);
  56. // LoggingInterceptor
  57. app.use(LoggingMiddleware);
  58. // All headers operations
  59. app.use(ReqHeaderMiddleware);
  60. const router = express.Router();
  61. const pluginsRouter = express.Router();
  62. // Init WebSocket server event listener
  63. io.on('connection', (socket: Socket) => {
  64. console.log('socket.io connected');
  65. socket.on('COLLECTION', (message: any) => {
  66. socket.emit('COLLECTION', { data: message });
  67. });
  68. pubSub.on('ws_pubsub', msg => {
  69. const { event, data } = msg;
  70. socket.emit(event, data);
  71. });
  72. });
  73. // Read plugin files and start express server
  74. // Import all plguins under "src/plugins"
  75. getDirectories(SRC_PLUGIN_DIR, async (dirErr: Error, dirRes: string[]) => {
  76. const cfgs: any[] = [];
  77. if (dirErr) {
  78. console.log('Reading plugin directory Error', dirErr);
  79. } else {
  80. generateCfgs(cfgs, dirRes);
  81. }
  82. // If under plugin dev mode, import all plugins under "../../src/*/server"
  83. if (PLUGIN_DEV) {
  84. getDirectoriesSync(
  85. DEV_PLUGIN_DIR,
  86. (devDirErr: Error, devDirRes: string[]) => {
  87. if (devDirErr) {
  88. console.log('Reading dev plugin directory Error', devDirErr);
  89. } else {
  90. generateCfgs(cfgs, devDirRes, false);
  91. }
  92. }
  93. );
  94. }
  95. console.log('======/api/plugins configs======', cfgs);
  96. cfgs.forEach(async (cfg: any) => {
  97. const { api: pluginPath, componentPath } = cfg;
  98. if (!pluginPath) return;
  99. const {
  100. default: { router: pluginRouter },
  101. } = await import(componentPath);
  102. pluginsRouter.use(`/${pluginPath}`, pluginRouter);
  103. });
  104. router.use('/milvus', connectRouter);
  105. router.use('/collections', collectionsRouter);
  106. router.use('/partitions', partitionsRouter);
  107. router.use('/schema', schemaRouter);
  108. router.use('/crons', cronsRouter);
  109. router.use('/users', userRouter);
  110. router.get('/healthy', (req, res, next) => {
  111. res.json({ status: 200 });
  112. next();
  113. });
  114. app.use('/api/v1', router);
  115. app.use('/api/plugins', pluginsRouter);
  116. // Return client build files
  117. app.use(express.static('build'));
  118. const data = surveSwaggerSpecification();
  119. app.use('/api/v1/swagger', swaggerUi.serve, swaggerUi.setup(data));
  120. // handle every other route with index.html, which will contain
  121. // a script tag to your application's JavaScript file(s).
  122. app.get('*', (request, response) => {
  123. response.sendFile(path.join(__dirname, '../build/index.html'));
  124. });
  125. // ErrorInterceptor
  126. app.use(ErrorMiddleware);
  127. // start server
  128. server.listen(PORT, () => {
  129. console.log(chalk.green.bold(`Attu Server started on port ${PORT} :)`));
  130. });
  131. });