繁体   English   中英

Apollo Graphql 服务器:请求需要整整一分钟才能到达解析器

[英]Apollo Graphql Server: Request takes a full minute to reach resolver

我在 NodeJS 服务器上使用 Apollo Graphql。 我最近注意到我的请求花费了很多时间,因此决定解决这个问题。 我添加了日志时间戳并将控制台日志添加到服务器中的不同位置以找出瓶颈。 我的服务器代码如下:

(async function () {
  
  const app = express();
  const httpServer = createServer(app);

  const wsServer = new WebSocketServer({
    server: httpServer,
    path: "/graphql",
  });
  const serverCleanup = useServer({ schema }, wsServer);

  const server = new ApolloServer({
    schema,
    plugins: [
      ApolloServerPluginDrainHttpServer({ httpServer }),
      {
        async serverWillStart() {
          return {
            async drainServer() {
              await serverCleanup.dispose();
            },
          };
        },
      },
      myPlugin
    ],
    healthCheckPath: '/health',
    async onHealthCheck() {
      return
    },
  });


  await server.start();

  app.use(
    '/',
    cors(),
    // 50mb is the limit that `startStandaloneServer` uses, but you may configure this to suit your needs
    bodyParser.json({ limit: '50mb' }),
    // expressMiddleware accepts the same arguments:
    // an Apollo Server instance and optional configuration options
    expressMiddleware(server, {
      context: async ({ req }) => {
        let decodedToken
        try {
          if (env === 'development') {
            decodedToken = {
              uid: "test"
            }
          } else {
            decodedToken = await verifyIdToken(req.headers?.authorization?.replace('Bearer ', ''))
          }
        } catch (error) {
          decodedToken = null
        }
        return {
          decodedToken,
          jwt: decodedToken
        }
      }
    }),
  );

  await new Promise((resolve) => httpServer.listen({ port: 4000 }, resolve));
  console.log(`🚀 Server ready at http://localhost:4000/`);

})()

然后在我的 graphql 解析器中,我有与此类似的代码

const { AuthenticationError } = require('@apollo/server/express4');
const mutations = {
   createPost: async(_, { createPostInput }, context) => {
        console.log('In graphql mutation')
        if (!context.decodedToken || !Object.keys(context.decodedToken).length) {
            throw new AuthenticationError('Unauthenticated');
        }
        console.log('In graphql mutation 2')
        return await createPostApi(createPostInput);
   }
}

传递给 apollo 服务器的“我的插件”代码取自 apollo 文档。 它只打印各种事件的日志。

const myPlugin = {
    // Fires whenever a GraphQL request is received from a client.
    async requestDidStart(requestContext) {
      console.log('Request started!');

      return {
        // Fires whenever Apollo Server will parse a GraphQL
        // request to create its associated document AST.
        async parsingDidStart(requestContext) {
          console.log('Parsing started!');
        },

        // Fires whenever Apollo Server will validate a
        // request's document AST against your GraphQL schema.
        async validationDidStart(requestContext) {
          console.log('Validation started!');
        },

        async executionDidStart(requestContext) {
          console.log('Execution started!');
        },
      };
    },
  };

我已经安装了 log-timestamp package 来打印每个日志的时间戳,这里是 output

[2023-01-31T18:23:02.428Z] Request started!
[2023-01-31T18:23:02.430Z] Parsing started!
[2023-01-31T18:23:02.432Z] Validation started!
[2023-01-31T18:23:02.450Z] Execution started!
[2023-01-31T18:23:03.081Z] Request started!
[2023-01-31T18:23:03.081Z] Parsing started!
[2023-01-31T18:23:03.081Z] Validation started!
[2023-01-31T18:23:03.083Z] Execution started!
[2023-01-31T18:23:03.380Z] Request started!
[2023-01-31T18:23:03.381Z] Execution started!
[2023-01-31T18:23:18.290Z] Request started!
[2023-01-31T18:23:18.291Z] Execution started!
[2023-01-31T18:23:22.878Z] Request started!
[2023-01-31T18:23:22.878Z] Execution started!
[2023-01-31T18:23:23.878Z] Request started!
[2023-01-31T18:23:23.878Z] Execution started!
[2023-01-31T18:23:24.869Z] Request started!
[2023-01-31T18:23:24.869Z] Execution started!
[2023-01-31T18:23:30.389Z] Request started!
[2023-01-31T18:23:30.390Z] Execution started!
[2023-01-31T18:23:41.372Z] Request started!
[2023-01-31T18:23:41.373Z] Execution started!
[2023-01-31T18:24:01.046Z] Request started!
[2023-01-31T18:24:01.047Z] Execution started!
[2023-01-31T18:24:02.040Z] Request started!
[2023-01-31T18:24:02.041Z] Execution started!
[2023-01-31T18:24:03.180Z] In graphql mutation
[2023-01-31T18:24:03.180Z] In graphql mutation 2
// logs below this point are from my actual mutation. Actual log output has been redacted
[2023-01-31T18:24:03.180Z] Starting ...
[2023-01-31T18:24:03.181Z] Inside function
[2023-01-31T18:24:03.181Z] Sorting ...
[2023-01-31T18:24:03.181Z] Getting from db ...
[2023-01-31T18:24:03.311Z] Got ...
[2023-01-31T18:24:03.311Z] Creating ... input
[2023-01-31T18:24:03.312Z] Creating ... input
[2023-01-31T18:24:03.312Z] Creating ... Input
[2023-01-31T18:24:03.312Z] Creating in db
[2023-01-31T18:24:03.702Z] Fetching fetching from db
[2023-01-31T18:24:03.756Z] parsing
[2023-01-31T18:24:03.756Z] Starting another thing
[2023-01-31T18:24:03.756Z] In that other thing
[2023-01-31T18:24:03.756Z] Starting a third thing
[2023-01-31T18:24:03.760Z] Creating (db call) ...
[2023-01-31T18:24:03.803Z] Finding (db call) ...
[2023-01-31T18:24:03.836Z] Creating (another db call) ...
[2023-01-31T18:24:03.838Z] Creating (db call) ...
[2023-01-31T18:24:03.838Z] Creating (db call) ...
[2023-01-31T18:24:03.839Z] Creating (db call)...
[2023-01-31T18:24:03.840Z] Finishing ...

如您所见,请求从 18:23:02 开始,并在整整分钟后18:24:03到达解析器。 不涉及中间件,这是我的本地机器,因此不存在网络延迟问题或等待令牌验证。 实际业务逻辑在同一秒内执行,但总时间变为 1 分钟以上。 我怎样才能减少这种滞后?

奇怪的是,简单的机器重启就解决了这个问题。 尽管我仍然不明白最初是什么原因造成的。 可能是与 MacOS 或 Apollo 服务器相关的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM