Skip to content

Fixes on Demand Control #1027

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/cold-monkeys-approve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphql-tools/batch-execute': patch
---

Spread sync errors into an array with the same size of the requests to satisfy underlying DataLoader implementation to throw the error correctly
5 changes: 5 additions & 0 deletions .changeset/giant-paws-battle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphql-hive/gateway-runtime': patch
---

If metadata is included the result with `includeExtensionMetadata`, `cost.estimated` should always be added to the result extensions even if no cost is calculated.
5 changes: 3 additions & 2 deletions packages/batch-execute/src/createBatchingExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ function createLoadFn(
): PromiseLike<Array<ExecutionResult>> {
if (requests.length === 1 && requests[0]) {
const request = requests[0];
return fakePromise<any>(
return fakePromise(
handleMaybePromise(
() => executor(request),
(result) => [result],
Expand All @@ -58,7 +58,7 @@ function createLoadFn(
);
}
const mergedRequests = mergeRequests(requests, extensionsReducer);
return fakePromise<any>(
return fakePromise(
handleMaybePromise(
() => executor(mergedRequests),
(resultBatches) => {
Expand All @@ -69,6 +69,7 @@ function createLoadFn(
}
return splitResult(resultBatches, requests.length);
},
(err) => requests.map(() => err),
),
);
};
Expand Down
40 changes: 19 additions & 21 deletions packages/runtime/src/plugins/useDemandControl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,33 +104,31 @@ export function useDemandControl<TContext extends Record<string, any>>({
},
onExecutionResult({ result, setResult, context }) {
if (includeExtensionMetadata) {
const costByContext = costByContextMap.get(context);
if (costByContext) {
if (isAsyncIterable(result)) {
setResult(
mapAsyncIterator(result, (value) => ({
...value,
extensions: {
...(value.extensions || {}),
cost: {
estimated: costByContext,
max: maxCost,
},
},
})),
);
} else {
setResult({
...(result || {}),
const costByContext = costByContextMap.get(context) || 0;
if (isAsyncIterable(result)) {
setResult(
mapAsyncIterator(result, (value) => ({
...value,
extensions: {
...(result?.extensions || {}),
...(value.extensions || {}),
cost: {
estimated: costByContext,
max: maxCost,
},
},
});
}
})),
);
} else {
setResult({
...(result || {}),
extensions: {
...(result?.extensions || {}),
cost: {
estimated: costByContext,
max: maxCost,
},
},
});
}
}
},
Expand Down
170 changes: 170 additions & 0 deletions packages/runtime/tests/demand-control.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,11 @@ describe('Demand Control', () => {
path: ['items'],
},
],
extensions: {
cost: {
estimated: 0,
},
},
});
});
it('@listSize(slicingArguments:, requireOneSlicingArgument:false)', async () => {
Expand Down Expand Up @@ -1016,4 +1021,169 @@ describe('Demand Control', () => {
},
});
});

it('returns cost even if it does not hit the subgraph', async () => {
const subgraph = buildSubgraphSchema({
typeDefs: parse(/* GraphQL */ `
type Query {
foo: String
}
`),
});
await using subgraphServer = createYoga({
schema: subgraph,
});
await using gateway = createGatewayRuntime({
supergraph: await composeLocalSchemasWithApollo([
{
name: 'subgraph',
schema: subgraph,
url: 'http://subgraph/graphql',
},
]),
plugins: () => [
// @ts-expect-error TODO: MeshFetch is not compatible with @whatwg-node/server fetch
useCustomFetch(subgraphServer.fetch),
useDemandControl({
includeExtensionMetadata: true,
}),
],
});
const query = /* GraphQL */ `
query EmptyQuery {
__typename
a: __typename
}
`;
const response = await gateway.fetch('http://localhost:4000/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query }),
});
const result = await response.json();
expect(result).toEqual({
data: {
__typename: 'Query',
a: 'Query',
},
extensions: {
cost: {
estimated: 0,
},
},
});
});

it('handles batched requests', async () => {
const subgraph = buildSubgraphSchema({
typeDefs: parse(/* GraphQL */ `
type Query {
foo: Foo
bar: Bar
}

type Foo {
id: ID
}

type Bar {
id: ID
}
`),
resolvers: {
Query: {
foo: async () => ({ id: 'foo' }),
bar: async () => ({ id: 'bar' }),
},
},
});
await using subgraphServer = createYoga({
schema: subgraph,
});
await using gateway = createGatewayRuntime({
supergraph: await composeLocalSchemasWithApollo([
{
name: 'subgraph',
schema: subgraph,
url: 'http://subgraph/graphql',
},
]),
plugins: () => [
// @ts-expect-error TODO: MeshFetch is not compatible with @whatwg-node/server fetch
useCustomFetch(subgraphServer.fetch),
useDemandControl({
includeExtensionMetadata: true,
maxCost: 1,
}),
],
});
const query = /* GraphQL */ `
query FooQuery {
foo {
id
}
bar {
id
}
}
`;
const response = await gateway.fetch('http://localhost:4000/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query }),
});
const result = await response.json();
expect(result).toEqual({
data: {
foo: null,
bar: null,
},
errors: [
{
extensions: {
code: 'COST_ESTIMATED_TOO_EXPENSIVE',
cost: {
estimated: 2,
max: 1,
},
},
locations: [
{
column: 9,
line: 3,
},
],
message: 'Operation estimated cost 2 exceeded configured maximum 1',
path: ['foo'],
},
{
extensions: {
code: 'COST_ESTIMATED_TOO_EXPENSIVE',
cost: {
estimated: 2,
max: 1,
},
},
locations: [
{
column: 9,
line: 6,
},
],
message: 'Operation estimated cost 2 exceeded configured maximum 1',
path: ['bar'],
},
],
extensions: {
cost: {
estimated: 2,
max: 1,
},
},
});
});
});
Loading