contra/graphql-helix

Infinite loop when using defer and async iterators (`JavaScript heap out of memory`)

linuslofgren opened this issue · 0 comments

Using the @defer directive when returning an array of async functions causes helix to go into an infinite loop and crash. This happens when the request is cancelled before all async resolvers have returned. I have isolated the problem to this for await loop in process-request.ts. It probably has something to do with the async iterator not stopping correctly (see this comment on the async iterator proposal).

Here is a minimal project which reproduces the issue. (Reproduced with 16.1.0-experimental-stream-defer.6)

In GraphQLi starting and stoping this query before the timeout has completed causes the application to increase memory usage until it crashes with JavaScript heap out of memory.

 query DeferTestQuery {
    deferTest {
      name
      ... on GraphQLDeferTest @defer(label:"d") {
        deferThisField
      }
    }
  }
const express = require('express')
const { getGraphQLParameters, processRequest, renderGraphiQL, shouldRenderGraphiQL, sendResult } = require("graphql-helix")

const app = express()

const {
  GraphQLBoolean,
  GraphQLList,
  GraphQLObjectType,
  GraphQLSchema,
  GraphQLString,
} = require("graphql")

const sleep = (t = 1000) => new Promise((res) => setTimeout(res, t));
const GraphQLDeferTest = new GraphQLObjectType({
  name: "GraphQLDeferTest",
  fields: {
    name: {
      type: GraphQLString,
      resolve: () => "This should resolve instantly",
    },
    deferThisField: {
      type: GraphQLString,
      resolve: async () => {
        console.log("Resolver")
        await sleep(Math.random() * 3000);
        return "Should resolve after some time";
      }
    },
  },
});

const Query = new GraphQLObjectType({
  name: "Query",
  fields: {
    ping: {
      type: GraphQLBoolean,
      resolve: () => true,
    },
    deferTest: {
      type: new GraphQLList(GraphQLDeferTest),
      resolve: () => ([{}, {}]),
    }
  },
});

const schema = new GraphQLSchema({
  query: Query,
  enableDeferStream: true
});

app.use(express.json());
app.use('/graphql', async (req, res) => {
  const request = {
    body: req.body,
    headers: req.headers,
    method: req.method,
    query: req.query,
  };


  if (shouldRenderGraphiQL(request)) {
    res.send(renderGraphiQL());
  } else {

    const { operationName, query, variables } = getGraphQLParameters(request);

    const result = await processRequest({
      operationName,
      query,
      variables,
      request,
      schema,
    });

    sendResult(result, res);
  }
})

app.listen(4001)