Skip to content
Closed
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
11 changes: 11 additions & 0 deletions .changeset/defer-stream-validation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"grafast": patch
"grafserv": patch
"postgraphile": patch
---

When the installed `graphql` doesn't natively support `@defer`/`@stream` (e.g.
`graphql@^16`), Gra*fast* and Grafserv now apply polyfilled versions of the
incremental delivery validation rules from GraphQL.js v17 (exported as
`incrementalValidationRules`), so `@defer`/`@stream` usage is properly validated
without needing an experimental `graphql` version.
296 changes: 296 additions & 0 deletions grafast/grafast/__tests__/incrementalValidation-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,296 @@
/* eslint-disable graphile-export/exhaustive-deps, graphile-export/export-methods, graphile-export/export-plans, graphile-export/export-instances, graphile-export/export-subclasses, graphile-export/no-nested */
import { expect } from "chai";
import { resolvePreset } from "graphile-config";
import type { ExecutionResult } from "graphql";
import { parse, specifiedRules, validate } from "graphql";
import { describe, it } from "mocha";

import {
constant,
grafast,
graphqlHasStreamDefer,
incrementalValidationRules,
makeGrafastSchema,
} from "../dist/index.js";

const schema = makeGrafastSchema({
typeDefs: /* GraphQL */ `
type Thing {
id: Int
things: [Thing!]
}
type Query {
thing: Thing
things: [Thing!]
}
type Mutation {
things: [Thing!]
}
type Subscription {
things: [Thing!]
}
`,
objects: {
Query: {
plans: {
thing() {
return constant(1);
},
things() {
return constant([1, 2]);
},
},
},
},
enableDeferStream: true,
});

const rules = [...specifiedRules, ...incrementalValidationRules];

function errorsFor(source: string): string[] {
return validate(schema, parse(source), rules).map((e) => e.message);
}

describe("incremental delivery validation", () => {
if (graphqlHasStreamDefer) {
it("defers to GraphQL.js's own rules", () => {
expect(incrementalValidationRules).to.have.length(0);
});
return;
}

it("accepts valid @defer and @stream usage", () => {
expect(
errorsFor(/* GraphQL */ `
query Q($if: Boolean) {
things @stream(initialCount: 1, label: "a") {
id
}
... @defer(label: "b") {
thing {
id
}
}
...F @defer(if: $if)
}
fragment F on Query {
thing {
things @stream {
id
}
}
}
`),
).to.deep.equal([]);
});

it("rejects @stream on a non-list field", () => {
expect(
errorsFor(/* GraphQL */ `
{
thing @stream {
id
}
}
`),
).to.deep.equal([
'Directive "@stream" cannot be used on non-list field "Query.thing".',
]);
});

it("rejects non-static and duplicate labels", () => {
expect(
errorsFor(/* GraphQL */ `
query Q($label: String) {
things @stream(label: "a") {
id
}
... @defer(label: "a") {
thing {
id
}
}
... @defer(label: $label) {
thing {
id
}
}
}
`),
).to.deep.equal([
'Value for arguments "defer(label:)" and "stream(label:)" must be unique across all Defer/Stream directive usages.',
'Argument "@defer(label:)" must be a static string.',
]);
});

it("rejects @defer/@stream on root mutation fields", () => {
expect(
errorsFor(/* GraphQL */ `
mutation {
things @stream {
id
}
... @defer {
__typename
}
...M @defer
}
fragment M on Mutation {
__typename
}
`),
).to.deep.equal([
'Stream directive cannot be used on root mutation type "Mutation".',
'Defer directive cannot be used on root mutation type "Mutation".',
'Defer directive cannot be used on root mutation type "Mutation".',
]);
});

it("rejects enabled @defer/@stream in subscriptions", () => {
expect(
errorsFor(/* GraphQL */ `
subscription S($if: Boolean!) {
things {
things @stream {
id
}
a: things @stream(if: false) {
id
}
b: things @stream(if: $if) {
id
}
...T @defer
...T @defer(if: false) @skip(if: true)
}
}
fragment T on Thing {
id
}
`),
).to.deep.equal([
"Stream directive not supported on subscription operations. Disable `@stream` by setting the `if` argument to `false`.",
"Defer directive not supported on subscription operations. Disable `@defer` by setting the `if` argument to `false`.",
]);
});

it("rejects @stream on overlapping fields", () => {
const message =
'Fields "things" conflict because they have overlapping stream directives. Use different aliases on the fields to fetch both if this was intentional.';
expect(
errorsFor(/* GraphQL */ `
{
things @stream {
id
}
...F
}
fragment F on Query {
things {
id
}
}
`),
).to.deep.equal([message]);
expect(
errorsFor(/* GraphQL */ `
{
thing {
things @stream(initialCount: 1) {
id
}
}
thing {
things @stream(initialCount: 1) {
id
}
}
}
`),
).to.deep.equal([message]);
});

it("handles fragment cycles alongside @stream", () => {
expect(
errorsFor(/* GraphQL */ `
{
things @stream {
id
}
...F
}
fragment F on Query {
thing {
...T
}
thing {
id
}
}
fragment T on Thing {
things {
...T
}
things {
id
}
}
`),
).to.deep.equal(['Cannot spread fragment "T" within itself.']);
});

it("checks fragment fan-out in polynomial time", () => {
const depth = 30;
let source = `{ things @stream { id } ...F${depth} }\nfragment F0 on Thing { id }\n`;
for (let i = 1; i <= depth; i++) {
const on = i === depth ? "Query" : "Thing";
source += `fragment F${i} on ${on} { a: things { ...F${i - 1} } a: things { ...F${i - 1} } b: things { ...F${i - 1} } b: things { ...F${i - 1} } }\n`;
}
expect(errorsFor(source)).to.deep.equal([]);
});

it("reports each overlapping pair once", () => {
expect(
errorsFor(/* GraphQL */ `
{
thing {
...A
...B
}
thing {
...B
...A
}
}
fragment A on Thing {
things @stream {
id
}
}
fragment B on Thing {
things {
id
}
}
`),
).to.have.length(1);
});

it("is applied by grafast()", async () => {
const result = (await grafast({
schema,
source: /* GraphQL */ `
{
thing @stream {
id
}
}
`,
resolvedPreset: resolvePreset({}),
requestContext: {},
})) as ExecutionResult;
expect(result.errors?.map((e) => e.message)).to.deep.equal([
'Directive "@stream" cannot be used on non-list field "Query.thing".',
]);
});
});
18 changes: 16 additions & 2 deletions grafast/grafast/src/grafastGraphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type { PromiseOrValue } from "graphql/jsutils/PromiseOrValue.js";
import { $$queryCache } from "./constants.ts";
import { SafeError } from "./error.ts";
import { execute } from "./execute.ts";
import { incrementalValidationRules } from "./incrementalValidation.ts";
import { hookArgs } from "./index.ts";
import type {
GrafastArgs,
Expand All @@ -21,7 +22,16 @@ import type {
import { establishMiddleware } from "./middleware.ts";
import { isPromiseLike } from "./utils.ts";

const { GraphQLError, parse, Source, validate, validateSchema } = graphql;
const {
GraphQLError,
parse,
Source,
specifiedRules,
validate,
validateSchema,
} = graphql;

const validationRules = [...specifiedRules, ...incrementalValidationRules];

/** Rough average size per query */
const CACHE_MULTIPLIER = 100000;
Expand Down Expand Up @@ -94,7 +104,11 @@ const parseAndValidate = (
try {
queryDocumentAst = parse(source);
// Validate our GraphQL query using given rules.
const validationErrors = validate(gqlSchema, queryDocumentAst);
const validationErrors = validate(
gqlSchema,
queryDocumentAst,
validationRules,
);
const cacheResult =
validationErrors.length > 0 ? validationErrors : queryDocumentAst;
queryCache.set(hash, cacheResult);
Expand Down
Loading
Loading