From c6e90eb1553801fe1f52faabd6f71f9d227b6e29 Mon Sep 17 00:00:00 2001 From: Curtis Li Date: Mon, 26 Feb 2024 12:58:51 -0500 Subject: [PATCH 1/2] Add parser support for string literal aliases MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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` --- src/language/__tests__/parser-test.ts | 12 ++++- src/language/parser.ts | 45 ++++++++++++++++-- .../OverlappingFieldsCanBeMergedRule-test.ts | 47 +++++++++++++++++-- src/validation/__tests__/harness.ts | 8 ++-- 4 files changed, 99 insertions(+), 13 deletions(-) diff --git a/src/language/__tests__/parser-test.ts b/src/language/__tests__/parser-test.ts index 34e9dff4b9..b3c4a6a417 100644 --- a/src/language/__tests__/parser-test.ts +++ b/src/language/__tests__/parser-test.ts @@ -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'; @@ -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', () => { @@ -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 .', + locations: [{ line: 1, column: 5 }], + }); }); it('parse provides useful error when using source', () => { diff --git a/src/language/parser.ts b/src/language/parser.ts index cd9345f6dd..aaf9d03694 100644 --- a/src/language/parser.ts +++ b/src/language/parser.ts @@ -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; } /** @@ -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(token, { + kind: Kind.NAME, + value: token.value, + }); + } + // Implements the parsing rules in the Document section. /** @@ -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(start, { diff --git a/src/validation/__tests__/OverlappingFieldsCanBeMergedRule-test.ts b/src/validation/__tests__/OverlappingFieldsCanBeMergedRule-test.ts index ecb56a15cf..a795905916 100644 --- a/src/validation/__tests__/OverlappingFieldsCanBeMergedRule-test.ts +++ b/src/validation/__tests__/OverlappingFieldsCanBeMergedRule-test.ts @@ -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'; @@ -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) { @@ -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. diff --git a/src/validation/__tests__/harness.ts b/src/validation/__tests__/harness.ts index b7710ff9d9..00856ae3d0 100644 --- a/src/validation/__tests__/harness.ts +++ b/src/validation/__tests__/harness.ts @@ -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'; @@ -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( From 3fc725d87216602baa52138a3300d0b45c0bbfa5 Mon Sep 17 00:00:00 2001 From: Curtis Li Date: Mon, 26 Feb 2024 15:36:14 -0500 Subject: [PATCH 2/2] Prettier --- src/validation/__tests__/harness.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/validation/__tests__/harness.ts b/src/validation/__tests__/harness.ts index 00856ae3d0..b2c65a974f 100644 --- a/src/validation/__tests__/harness.ts +++ b/src/validation/__tests__/harness.ts @@ -138,7 +138,8 @@ export function expectValidationErrorsWithSchema( export function expectValidationErrors( rule: ValidationRule, - queryStr: string, options?: ParseOptions | undefined, + queryStr: string, + options?: ParseOptions | undefined, ): any { return expectValidationErrorsWithSchema(testSchema, rule, queryStr, options); }