Skip to content
This repository has been archived by the owner on Dec 20, 2024. It is now read-only.

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

Open
linuslofgren opened this issue Jul 19, 2022 · 0 comments

Comments

@linuslofgren
Copy link

linuslofgren commented Jul 19, 2022

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)
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

1 participant