Skip to content

Commit

Permalink
Add parser support for string literal aliases
Browse files Browse the repository at this point in the history
Summary: These are the graphql-js changes for a proposed spec change that changes the definition of an alias from:
```
Alias : Name :
```
...to:
```
Alias :
 - Name :
 - StringValue :
```

At Meta, our GraphQL clients for both web and mobile care a lot about local data consistency. Local data consistency is when the client is able to reconcile data from multiple GraphQL responses in a local client-side cache which can be subscribed to. When data changes, we issue updates to these subscribers — which allows us to keep various screens "in-sync" and show the same view of the data.

The canonical example of this on Facebook is if you navigate to the Groups page from a Feed post and join the group, then when you navigate back to Feed we should update the "Join Group" button in the post to "Joined".

Local data consistency is supported today by Relay for JS clients (widely adopted within industry) and by Meta's internal mobile GraphQL client for Android/iOS clients.

To support consistency, we need to be able to remap aliases/field names into their "canonical names". The canonical name is what we use to keep two fields consistent, as it represents the true definition of a field.

Given a field selection:
```
alias: field(arg: "foo")
```
the canonical name would be:
```
field(arg:"foo")
```

Internally, we've explored various ways of doing this. We currently need to embed a lot of information about the schema and query in our clients; for example Relay creates a "normalization AST" with this information, and our internal mobile client requires all the information to be pre-compiled into the app binary. This leads to additional costs, e.g. binary size bloat or wire size costs.

We've found that we can more efficiently deliver the canonical name information by embedding it into our response instead, which removes the need for pre-compiled metadata. We run a transform on our queries to add aliases for each field, and use the canonical name as the alias. However since the canonical name may contain non-supported characters (e.g. `(`, `)`, `$`), we are proposing a spec change to allow `StringValue` tokens as the alias.

This would allow syntax such as:
```
"field(arg:\"foo\")": field(arg: "foo")
```

We've attempted alternative ways of implementing this, such as doing this transform during server-side execution (a spec violation, and high server overhead!) or delivering encoded aliases to abide by the `NameValue` specification (client parsing overhead for decoding!).

Potential side effects / outcomes of this change:
1. Selection set conflict validation should still work out of the box, even if one selection is a string literal and the other is a normal `NameValue`.
2. Here we parse the `StringValue` into a `NameNode` (same as when parsing a `NaveValue`), which doesn't have any requirements on the name itself as far as I can tell.
3. We allow string literal aliases here but not number literals, which abides by the JSON specification. According to the JSON spec, map/object keys must be strings.


Test Plan: `npm test`
  • Loading branch information
Curtis Li committed Feb 26, 2024
1 parent 9c90a23 commit c6e90eb
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 13 deletions.
12 changes: 10 additions & 2 deletions src/language/__tests__/parser-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { kitchenSinkQuery } from '../../__testUtils__/kitchenSinkQuery.js';
import { inspect } from '../../jsutils/inspect.js';

import { Kind } from '../kinds.js';
import type { ParseOptions } from '../parser.js';
import { parse, parseConstValue, parseType, parseValue } from '../parser.js';
import { Source } from '../source.js';
import { TokenKind } from '../tokenKind.js';
Expand All @@ -19,8 +20,8 @@ function parseCCN(source: string) {
return parse(source, { experimentalClientControlledNullability: true });
}

function expectSyntaxError(text: string) {
return expectToThrowJSON(() => parse(text));
function expectSyntaxError(text: string, options?: ParseOptions | undefined) {
return expectToThrowJSON(() => parse(text, options));
}

describe('Parser', () => {
Expand Down Expand Up @@ -73,6 +74,13 @@ describe('Parser', () => {
message: 'Syntax Error: Expected Name, found String "".',
locations: [{ line: 1, column: 3 }],
});

expectSyntaxError('{ ""', {
experimentalParseStringLiteralAliases: true,
}).to.deep.include({
message: 'Syntax Error: Expected ":", found <EOF>.',
locations: [{ line: 1, column: 5 }],
});
});

it('parse provides useful error when using source', () => {
Expand Down
45 changes: 41 additions & 4 deletions src/language/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,23 @@ export interface ParseOptions {
* future.
*/
experimentalClientControlledNullability?: boolean | undefined;

/**
* EXPERIMENTAL:
*
* If enabled, the parser will understand and parse StringValues as aliases.
*
* The syntax looks like the following:
*
* ```graphql
* {
* "alias": field
* }
* ```
* Note: this feature is experimental and may change or be removed in the
* future.
*/
experimentalParseStringLiteralAliases?: boolean | undefined;
}

/**
Expand Down Expand Up @@ -236,6 +253,17 @@ export class Parser {
});
}

/**
* Converts a string lex token into a name parse node.
*/
parseStringLiteralAlias(): NameNode {
const token = this.expectToken(TokenKind.STRING);
return this.node<NameNode>(token, {
kind: Kind.NAME,
value: token.value,
});
}

// Implements the parsing rules in the Document section.

/**
Expand Down Expand Up @@ -454,14 +482,23 @@ export class Parser {
parseField(): FieldNode {
const start = this._lexer.token;

const nameOrAlias = this.parseName();
let alias;
let name;
if (this.expectOptionalToken(TokenKind.COLON)) {
alias = nameOrAlias;
if (
this._options.experimentalParseStringLiteralAliases &&
this.peek(TokenKind.STRING)
) {
alias = this.parseStringLiteralAlias();
this.expectToken(TokenKind.COLON);
name = this.parseName();
} else {
name = nameOrAlias;
const nameOrAlias = this.parseName();
if (this.expectOptionalToken(TokenKind.COLON)) {
alias = nameOrAlias;
name = this.parseName();
} else {
name = nameOrAlias;
}
}

return this.node<FieldNode>(start, {
Expand Down
47 changes: 43 additions & 4 deletions src/validation/__tests__/OverlappingFieldsCanBeMergedRule-test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { describe, it } from 'mocha';

import type { ParseOptions } from '../../language/parser.js';

import type { GraphQLSchema } from '../../type/schema.js';

import { buildSchema } from '../../utilities/buildASTSchema.js';
Expand All @@ -11,12 +13,16 @@ import {
expectValidationErrorsWithSchema,
} from './harness.js';

function expectErrors(queryStr: string) {
return expectValidationErrors(OverlappingFieldsCanBeMergedRule, queryStr);
function expectErrors(queryStr: string, options?: ParseOptions | undefined) {
return expectValidationErrors(
OverlappingFieldsCanBeMergedRule,
queryStr,
options,
);
}

function expectValid(queryStr: string) {
expectErrors(queryStr).toDeepEqual([]);
function expectValid(queryStr: string, options?: ParseOptions | undefined) {
expectErrors(queryStr, options).toDeepEqual([]);
}

function expectErrorsWithSchema(schema: GraphQLSchema, queryStr: string) {
Expand Down Expand Up @@ -242,6 +248,39 @@ describe('Validate: Overlapping fields can be merged', () => {
]);
});

it('Same literal aliases allowed on same field targets', () => {
expectValid(
`
fragment sameLiteralAliasesWithSameFieldTargets on Dog {
"fido": name
fido: name
}
`,
{ experimentalParseStringLiteralAliases: true },
);
});

it('Same literal aliases with different field targets', () => {
expectErrors(
`
fragment sameLiteralAliasesWithDifferentFieldTargets on Dog {
"fido": name
fido: nickname
}
`,
{ experimentalParseStringLiteralAliases: true },
).toDeepEqual([
{
message:
'Fields "fido" conflict because "name" and "nickname" are different fields. Use different aliases on the fields to fetch both if this was intentional.',
locations: [
{ line: 3, column: 9 },
{ line: 4, column: 9 },
],
},
]);
});

it('Same aliases allowed on non-overlapping fields', () => {
// This is valid since no object can be both a "Dog" and a "Cat", thus
// these fields can never overlap.
Expand Down
8 changes: 5 additions & 3 deletions src/validation/__tests__/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { expectJSON } from '../../__testUtils__/expectJSON.js';

import type { Maybe } from '../../jsutils/Maybe.js';

import type { ParseOptions } from '../../language/parser.js';
import { parse } from '../../language/parser.js';

import type { GraphQLSchema } from '../../type/schema.js';
Expand Down Expand Up @@ -128,17 +129,18 @@ export function expectValidationErrorsWithSchema(
schema: GraphQLSchema,
rule: ValidationRule,
queryStr: string,
options?: ParseOptions | undefined,
): any {
const doc = parse(queryStr);
const doc = parse(queryStr, options);
const errors = validate(schema, doc, [rule]);
return expectJSON(errors);
}

export function expectValidationErrors(
rule: ValidationRule,
queryStr: string,
queryStr: string, options?: ParseOptions | undefined,
): any {
return expectValidationErrorsWithSchema(testSchema, rule, queryStr);
return expectValidationErrorsWithSchema(testSchema, rule, queryStr, options);
}

export function expectSDLValidationErrors(
Expand Down

0 comments on commit c6e90eb

Please sign in to comment.