-
Notifications
You must be signed in to change notification settings - Fork 237
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: optimize gateway by batching queries #667
Merged
mcollina
merged 8 commits into
mercurius-js:master
from
giacomorebonato:batch_gateway_queries
Nov 27, 2021
Merged
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
8a96260
feat: gateway batching queries
giacomorebonato 4f3d038
feat: batching queries with gateway
giacomorebonato 4f6d184
Merge branch 'master' into batch_gateway_queries
giacomorebonato ed26498
feat: gateway query batching
giacomorebonato 4419f58
doc: gateway with batching
giacomorebonato 6fba68e
feat: batched queries to services
giacomorebonato 144ae99
feat: batch gateway requests
giacomorebonato 5d0644d
doc: batched queries for services
giacomorebonato File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,17 @@ | ||
# mercurius | ||
|
||
- [Federation metadata support](#federation-metadata-support) | ||
- [Federation with \_\_resolveReference caching](#federation-with-__resolvereference-caching) | ||
- [Use GraphQL server as a Gateway for federated schemas](#use-graphql-server-as-a-gateway-for-federated-schemas) | ||
- [Periodically refresh federated schemas in Gateway mode](#periodically-refresh-federated-schemas-in-gateway-mode) | ||
- [Programmatically refresh federated schemas in Gateway mode](#programmatically-refresh-federated-schemas-in-gateway-mode) | ||
- [Using Gateway mode with a schema registry](#using-gateway-mode-with-a-schema-registry) | ||
- [Flag service as mandatory in Gateway mode](#flag-service-as-mandatory-in-gateway-mode) | ||
- [Using a custom errorHandler for handling downstream service errors in Gateway mode](#using-a-custom-errorhandler-for-handling-downstream-service-errors-in-gateway-mode) | ||
- [mercurius](#mercurius) | ||
- [Federation](#federation) | ||
- [Federation metadata support](#federation-metadata-support) | ||
- [Federation with \_\_resolveReference caching](#federation-with-__resolvereference-caching) | ||
- [Use GraphQL server as a Gateway for federated schemas](#use-graphql-server-as-a-gateway-for-federated-schemas) | ||
- [Periodically refresh federated schemas in Gateway mode](#periodically-refresh-federated-schemas-in-gateway-mode) | ||
- [Programmatically refresh federated schemas in Gateway mode](#programmatically-refresh-federated-schemas-in-gateway-mode) | ||
- [Using Gateway mode with a schema registry](#using-gateway-mode-with-a-schema-registry) | ||
- [Flag service as mandatory in Gateway mode](#flag-service-as-mandatory-in-gateway-mode) | ||
- [Batched Queries to services](#batched-queries-to-services) | ||
- [Using a custom errorHandler for handling downstream service errors in Gateway mode](#using-a-custom-errorhandler-for-handling-downstream-service-errors-in-gateway-mode) | ||
- [Securely parse service responses in Gateway mode](#securely-parse-service-responses-in-gateway-mode) | ||
|
||
## Federation | ||
|
||
|
@@ -351,6 +355,40 @@ server.register(mercurius, { | |
server.listen(3002) | ||
``` | ||
|
||
#### Batched Queries to services | ||
|
||
To fully leverage the DataLoader pattern a Gateway assumes that can send a request with batched queries to its services. | ||
This configuration can be disabled if the service doesn't support batched queries instead. | ||
|
||
|
||
```js | ||
const Fastify = require('fastify') | ||
const mercurius = require('mercurius') | ||
|
||
const server = Fastify() | ||
|
||
server.register(mercurius, { | ||
graphiql: true, | ||
gateway: { | ||
services: [ | ||
{ | ||
name: 'user', | ||
url: 'http://localhost:3000/graphql' // queries will be batched into one request | ||
// same as setting allowBatchedQueries: true | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. please uncomment this |
||
}, | ||
{ | ||
name: 'company', | ||
url: 'http://localhost:3001/graphql', // one request for each of the queries | ||
allowBatchedQueries: false | ||
} | ||
] | ||
}, | ||
pollingInterval: 2000 | ||
}) | ||
|
||
server.listen(3002) | ||
``` | ||
|
||
#### Using a custom errorHandler for handling downstream service errors in Gateway mode | ||
|
||
Service which uses Gateway mode can process different types of issues that can be obtained from remote services (for example, Network Error, Downstream Error, etc.). A developer can provide a function (`gateway.errorHandler`) that can process these errors. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
const defaultServiceDefinition = { | ||
allowBatchedQueries: true | ||
} | ||
|
||
module.exports = defaultServiceDefinition |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,140 @@ | ||
'use strict' | ||
|
||
const { preGatewayExecutionHandler } = require('../handlers') | ||
|
||
const mergeQueries = (queries) => { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would add some comments on the code to understand the context/logic |
||
const q = [...new Set(queries.map(q => q.query))] | ||
const resultIndexes = [] | ||
const mergedQueries = queries.reduce((acc, curr, queryIndex) => { | ||
if (!acc[curr.query]) { | ||
acc[curr.query] = { | ||
document: curr.document, | ||
variables: curr.variables | ||
} | ||
resultIndexes[q.indexOf(curr.query)] = [] | ||
} else { | ||
acc[curr.query].variables.representations = [ | ||
...acc[curr.query].variables.representations, | ||
...curr.variables.representations | ||
] | ||
} | ||
|
||
for (let i = 0; i < curr.variables.representations.length; i++) { | ||
resultIndexes[q.indexOf(curr.query)].push(queryIndex) | ||
} | ||
|
||
return acc | ||
}, {}) | ||
|
||
return { mergedQueries, resultIndexes } | ||
} | ||
|
||
const getBactchedResult = async ({ mergeQueriesResult, context, serviceDefinition, service }) => { | ||
const { mergedQueries, resultIndexes } = mergeQueriesResult | ||
const batchedQueries = [] | ||
|
||
for (const [query, { document, variables }] of Object.entries(mergedQueries)) { | ||
let modifiedQuery | ||
|
||
if (context.preGatewayExecution !== null) { | ||
({ modifiedQuery } = await preGatewayExecutionHandler({ | ||
schema: serviceDefinition.schema, | ||
document, | ||
context, | ||
service: { name: service } | ||
})) | ||
} | ||
|
||
batchedQueries.push({ | ||
operationName: document.definitions.find(d => d.kind === 'OperationDefinition').name.value, | ||
query: modifiedQuery || query, | ||
variables | ||
}) | ||
} | ||
|
||
const response = await serviceDefinition.sendRequest({ | ||
originalRequestHeaders: context.reply.request.headers, | ||
body: JSON.stringify(batchedQueries), | ||
context | ||
}) | ||
|
||
return buildResult({ resultIndexes, data: response.json }) | ||
} | ||
|
||
const buildResult = ({ resultIndexes, data }) => { | ||
const result = [] | ||
|
||
for (const [queryIndex, queryResponse] of data.entries()) { | ||
let entityIndex = 0 | ||
|
||
for (const entity of queryResponse.data._entities) { | ||
if (!result[resultIndexes[queryIndex][entityIndex]]) { | ||
result[resultIndexes[queryIndex][entityIndex]] = { | ||
...queryResponse, | ||
json: { | ||
data: { | ||
_entities: [entity] | ||
} | ||
} | ||
} | ||
} else { | ||
result[resultIndexes[queryIndex][entityIndex]].json.data._entities.push(entity) | ||
} | ||
|
||
entityIndex++ | ||
} | ||
} | ||
|
||
return result | ||
} | ||
|
||
const getResult = async ({ mergeQueriesResult, serviceDefinition, context, service }) => { | ||
giacomorebonato marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const { mergedQueries, resultIndexes } = mergeQueriesResult | ||
const queriesEntries = Object.entries(mergedQueries) | ||
const data = await Promise.all( | ||
queriesEntries.map(async ([query, { document, variables }]) => { | ||
let modifiedQuery | ||
|
||
if (context.preGatewayExecution !== null) { | ||
({ modifiedQuery } = await preGatewayExecutionHandler({ | ||
schema: serviceDefinition.schema, | ||
document, | ||
context, | ||
service: { name: service } | ||
})) | ||
} | ||
|
||
const response = await serviceDefinition.sendRequest({ | ||
originalRequestHeaders: context.reply.request.headers, | ||
body: JSON.stringify({ | ||
query: modifiedQuery || query, | ||
variables | ||
}), | ||
context | ||
}) | ||
|
||
return response.json | ||
}) | ||
) | ||
|
||
return buildResult({ data, resultIndexes }) | ||
} | ||
|
||
const getQueryResult = async ({ context, queries, serviceDefinition, service }) => { | ||
const mergeQueriesResult = mergeQueries(queries) | ||
const params = { | ||
mergeQueriesResult, | ||
service, | ||
serviceDefinition, | ||
queries, | ||
context | ||
} | ||
|
||
if (serviceDefinition.allowBatchedQueries) { | ||
return getBactchedResult({ ...params }) | ||
} | ||
|
||
return getResult({ ...params }) | ||
} | ||
|
||
module.exports = getQueryResult |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This does not match the implementation anymore.