diff --git a/.changeset/cache-control-directive-check.md b/.changeset/cache-control-directive-check.md new file mode 100644 index 00000000000..95838b4d373 --- /dev/null +++ b/.changeset/cache-control-directive-check.md @@ -0,0 +1,5 @@ +--- +'@apollo/server': major +--- + +The cache control plugin now checks on startup that a schema's `@cacheControl` directive definition matches the documented one, and the documented definition declares `scope` as non-null (`scope: CacheControlScope!`), so every `@cacheControl` usage must specify `scope: PUBLIC` or `scope: PRIVATE`. A schema with the previous nullable `scope` fails to start with an error that prints the expected definition. Pass `validateDirectiveDefinition: false` to `ApolloServerPluginCacheControl` to keep a different definition. diff --git a/docs/source/api/plugin/cache-control.mdx b/docs/source/api/plugin/cache-control.mdx index e2652da85ea..b516d79444d 100644 --- a/docs/source/api/plugin/cache-control.mdx +++ b/docs/source/api/plugin/cache-control.mdx @@ -89,6 +89,22 @@ This option was popular in Apollo Server 2 as a workaround for the problem solve +###### `validateDirectiveDefinition` + +`boolean` + + + +By default, the plugin checks on startup that any `@cacheControl` directive your schema defines matches the [documented definition](../../performance/caching/#in-your-schema-static): `maxAge: Int`, a non-null `scope` argument whose enum has exactly the values `PUBLIC` and `PRIVATE`, `inheritMaxAge: Boolean`, no other arguments, and only the `FIELD_DEFINITION`, `OBJECT`, `INTERFACE`, and `UNION` locations. If the definition differs, the server fails to start with an error that prints the expected definition. The most common difference is a nullable `scope`, which Apollo Server 4 and 5 documented; Apollo Server 6 requires every `@cacheControl` usage to choose a scope so that no field is cached publicly by accident. + +Set this to `false` to skip the check and keep a different definition. Note that the plugin only understands the arguments listed above, whatever the definition says. + + + + + + + ###### `calculateHttpHeaders` `boolean | 'if-cacheable'` diff --git a/docs/source/migration.mdx b/docs/source/migration.mdx index 82da700a785..710eb993da4 100644 --- a/docs/source/migration.mdx +++ b/docs/source/migration.mdx @@ -57,3 +57,24 @@ Apollo Server 4 had a regression where operations with invalid variables (for ex ## New: request cancellation signal `HTTPGraphQLRequest` has a new optional `signal` field. Integrations that provide an `AbortSignal` and abort it when the client disconnects let Apollo Server stop execution early: GraphQL.js exposes the signal to resolvers via `info.getAbortSignal()`, and an operation whose signal fires before execution completes ends with a `REQUEST_ABORTED` error instead of running to completion. The standalone server (`startStandaloneServer`) does this automatically. This is optional for integrations; nothing changes for integrations that don't set it. + +## `@cacheControl` definition is checked, and `scope` is required + +If your schema defines the `@cacheControl` directive (which you need in order to use it in your SDL), the cache control plugin now checks on startup that the definition matches the documented one, and the documented definition now declares `scope` as non-null: + +```graphql +enum CacheControlScope { + PUBLIC + PRIVATE +} + +directive @cacheControl( + maxAge: Int + scope: CacheControlScope! + inheritMaxAge: Boolean +) on FIELD_DEFINITION | OBJECT | INTERFACE | UNION +``` + +Previously, `scope` was nullable and defaulted to `PUBLIC`, so a field annotated with just `@cacheControl(maxAge: 60)` was cacheable by shared caches and CDNs, which is easy to do by accident. With a non-null `scope`, GraphQL.js's own SDL validation rejects every `@cacheControl` usage that doesn't say `scope: PUBLIC` or `scope: PRIVATE`, including `@cacheControl(inheritMaxAge: true)`. + +To migrate, change `scope: CacheControlScope` to `scope: CacheControlScope!` in your definition, and add `scope: PUBLIC` (or `PRIVATE`) to every `@cacheControl` usage. The startup error prints the expected definition. If you want to keep the old definition for now, pass `validateDirectiveDefinition: false` to `ApolloServerPluginCacheControl`. Cache hints set from code (`info.cacheControl.setCacheHint({ maxAge })`, `defaultMaxAge`) still default to `PUBLIC`. diff --git a/docs/source/performance/apq.mdx b/docs/source/performance/apq.mdx index 743f7d3ab66..f010f8070f7 100644 --- a/docs/source/performance/apq.mdx +++ b/docs/source/performance/apq.mdx @@ -124,11 +124,11 @@ Apollo Server works well with a Content Distribution Network (CDN) to cache full Add cache hints as [directives](../schema/directives/) to GraphQL schema so that Apollo Server knows which fields and types are cacheable and for how long. For example, this schema indicates that all fields that return an `Author` should be cached for 60 seconds, and that the `posts` field should itself be cached for 180 seconds: ```graphql -type Author @cacheControl(maxAge: 60) { +type Author @cacheControl(maxAge: 60, scope: PUBLIC) { id: Int firstName: String lastName: String - posts: [Post] @cacheControl(maxAge: 180) + posts: [Post] @cacheControl(maxAge: 180, scope: PUBLIC) } ``` diff --git a/docs/source/performance/caching.md b/docs/source/performance/caching.md index ecc506cfeba..ee129efc77c 100644 --- a/docs/source/performance/caching.md +++ b/docs/source/performance/caching.md @@ -10,7 +10,7 @@ type Post { id: ID! title: String author: Author - votes: Int @cacheControl(maxAge: 30) + votes: Int @cacheControl(maxAge: 30, scope: PUBLIC) comments: [Comment] readByCurrentUser: Boolean! @cacheControl(maxAge: 10, scope: PRIVATE) } @@ -44,19 +44,19 @@ enum CacheControlScope { directive @cacheControl( maxAge: Int - scope: CacheControlScope + scope: CacheControlScope! inheritMaxAge: Boolean ) on FIELD_DEFINITION | OBJECT | INTERFACE | UNION ``` -If you don't add these definitions, Apollo Server throws an `Unknown directive "@cacheControl"` error on startup. +If you don't add these definitions, Apollo Server throws an `Unknown directive "@cacheControl"` error on startup. If your schema defines `@cacheControl` differently (for example, with a nullable `scope`, as Apollo Server 4 and 5 documented), the cache control plugin throws an error describing the expected definition on startup; see the [`validateDirectiveDefinition`](../api/plugin/cache-control/#validatedirectivedefinition) option if you need to keep a different definition. The `@cacheControl` directive accepts the following arguments: | Name | Description | |------|-------------| | `maxAge` | The maximum amount of time the field's cached value is valid, in seconds. The default value is `0`, but you can [set a different default](#setting-a-different-default-maxage). | -| `scope` | If `PRIVATE`, the field's value is specific to a single user. The default value is `PUBLIC`. See also [Identifying users for `PRIVATE` responses](#identifying-users-for-private-responses). | +| `scope` | **Required.** `PUBLIC` if the field's value can be shared between users, or `PRIVATE` if it is specific to a single user. See also [Identifying users for `PRIVATE` responses](#identifying-users-for-private-responses). | | `inheritMaxAge` | If `true`, this field inherits the `maxAge` of its parent field instead of using the [default `maxAge`](#setting-a-different-default-maxage). Do not provide `maxAge` if you provide this argument. | Use `@cacheControl` for fields that should usually be cached with the same settings. If caching settings might change at runtime, you can use the [dynamic method](#in-your-resolvers-dynamic). @@ -74,7 +74,7 @@ type Post { id: ID! title: String author: Author - votes: Int @cacheControl(maxAge: 30) + votes: Int @cacheControl(maxAge: 30, scope: PUBLIC) comments: [Comment] readByCurrentUser: Boolean! @cacheControl(maxAge: 10, scope: PRIVATE) } @@ -90,7 +90,7 @@ In this example: This example defines cache control settings for _all_ schema fields that return a `Post` object: ```graphql {1} title="schema.graphql" -type Post @cacheControl(maxAge: 240) { +type Post @cacheControl(maxAge: 240, scope: PUBLIC) { id: Int! title: String author: Author @@ -113,7 +113,7 @@ type Comment { ```graphql title="schema.graphql" type Comment { - post: Post! @cacheControl(maxAge: 120) + post: Post! @cacheControl(maxAge: 120, scope: PUBLIC) body: String! } ``` @@ -240,17 +240,17 @@ Consider the following schema: ```graphql type Query { book: Book - cachedBook: Book @cacheControl(maxAge: 60) - reader: Reader @cacheControl(maxAge: 40) + cachedBook: Book @cacheControl(maxAge: 60, scope: PUBLIC) + reader: Reader @cacheControl(maxAge: 40, scope: PUBLIC) } type Book { title: String - cachedTitle: String @cacheControl(maxAge: 30) + cachedTitle: String @cacheControl(maxAge: 30, scope: PUBLIC) } type Reader { - book: Book @cacheControl(inheritMaxAge: true) + book: Book @cacheControl(inheritMaxAge: true, scope: PUBLIC) } ``` @@ -307,7 +307,7 @@ When using [Apollo Federation](/federation), the `@cacheControl` directive and ` Subgraph schemas contain an `_entities` root field on the `Query` type, so all query plans that require entity resolution will have a [`maxAge` of `0` set by default](#default-maxage). To override this default behavior, you can add a `@cacheControl` directive to an entity's definition: ```graphql -type Book @key(fields: "isbn") @cacheControl(maxAge: 30) { +type Book @key(fields: "isbn") @cacheControl(maxAge: 30, scope: PUBLIC) { isbn: String! title: String } diff --git a/packages/integration-testsuite/src/apolloServerTests.ts b/packages/integration-testsuite/src/apolloServerTests.ts index 48feec428bb..8141510cf59 100644 --- a/packages/integration-testsuite/src/apolloServerTests.ts +++ b/packages/integration-testsuite/src/apolloServerTests.ts @@ -994,7 +994,7 @@ export function defineIntegrationTestSuiteApolloServerTests( directive @cacheControl( maxAge: Int - scope: CacheControlScope + scope: CacheControlScope! ) on FIELD_DEFINITION | OBJECT | INTERFACE type Query { diff --git a/packages/integration-testsuite/src/httpServerTests.ts b/packages/integration-testsuite/src/httpServerTests.ts index 1f21e9e1649..32f7fdfdcb4 100644 --- a/packages/integration-testsuite/src/httpServerTests.ts +++ b/packages/integration-testsuite/src/httpServerTests.ts @@ -999,12 +999,12 @@ export function defineIntegrationTestSuiteHttpServerTests( author: String } - type Cook @cacheControl(maxAge: 200) { + type Cook @cacheControl(maxAge: 200, scope: PUBLIC) { title: String author: String } - type Pook @cacheControl(maxAge: 200) { + type Pook @cacheControl(maxAge: 200, scope: PUBLIC) { title: String books: [Book] @cacheControl(maxAge: 20, scope: PRIVATE) } @@ -1014,7 +1014,7 @@ export function defineIntegrationTestSuiteHttpServerTests( cooks: [Cook] pooks: [Pook] uncached: ID - ten: ID @cacheControl(maxAge: 10) + ten: ID @cacheControl(maxAge: 10, scope: PUBLIC) twenty: ID @cacheControl(maxAge: 20, scope: PRIVATE) } @@ -1025,7 +1025,7 @@ export function defineIntegrationTestSuiteHttpServerTests( directive @cacheControl( maxAge: Int - scope: CacheControlScope + scope: CacheControlScope! ) on FIELD_DEFINITION | OBJECT | INTERFACE `; diff --git a/packages/plugin-response-cache/src/__tests__/integration.test.ts b/packages/plugin-response-cache/src/__tests__/integration.test.ts index 576a07237e9..6bbc853a572 100644 --- a/packages/plugin-response-cache/src/__tests__/integration.test.ts +++ b/packages/plugin-response-cache/src/__tests__/integration.test.ts @@ -42,10 +42,10 @@ describe('Response caching', () => { it('basic caching', async () => { const typeDefs = `#graphql type Query { - cached: String @cacheControl(maxAge: 10) - asyncCached: String @cacheControl(maxAge: 10) - asyncUncached: String @cacheControl(maxAge: 10) - asyncNoWrite: String @cacheControl(maxAge: 10) + cached: String @cacheControl(maxAge: 10, scope: PUBLIC) + asyncCached: String @cacheControl(maxAge: 10, scope: PUBLIC) + asyncUncached: String @cacheControl(maxAge: 10, scope: PUBLIC) + asyncNoWrite: String @cacheControl(maxAge: 10, scope: PUBLIC) uncached: String private: String @cacheControl(maxAge: 9, scope: PRIVATE) } @@ -55,7 +55,7 @@ describe('Response caching', () => { } directive @cacheControl( maxAge: Int - scope: CacheControlScope + scope: CacheControlScope! ) on FIELD_DEFINITION | OBJECT | INTERFACE `; diff --git a/packages/server/src/__tests__/plugin/cacheControl/cacheControlDirective.test.ts b/packages/server/src/__tests__/plugin/cacheControl/cacheControlDirective.test.ts index a834d76663c..1f08c56d293 100644 --- a/packages/server/src/__tests__/plugin/cacheControl/cacheControlDirective.test.ts +++ b/packages/server/src/__tests__/plugin/cacheControl/cacheControlDirective.test.ts @@ -85,7 +85,7 @@ describe('@cacheControl directives', () => { it('should set the specified maxAge from a cache hint on the field', async () => { const schema = buildSchemaWithCacheControlSupport(` type Query { - droid(id: ID!): Droid @cacheControl(maxAge: 60) + droid(id: ID!): Droid @cacheControl(maxAge: 60, scope: PUBLIC) } type Droid { @@ -106,7 +106,9 @@ describe('@cacheControl directives', () => { { defaultMaxAge: 10 }, ); - expect(hints).toStrictEqual(new Map([['droid', { maxAge: 60 }]])); + expect(hints).toStrictEqual( + new Map([['droid', { maxAge: 60, scope: 'PUBLIC' }]]), + ); }); it('should set the specified maxAge for a field from a cache hint on the target type', async () => { @@ -115,7 +117,7 @@ describe('@cacheControl directives', () => { droid(id: ID!): Droid } - type Droid @cacheControl(maxAge: 60) { + type Droid @cacheControl(maxAge: 60, scope: PUBLIC) { id: ID! name: String! } @@ -133,7 +135,9 @@ describe('@cacheControl directives', () => { { defaultMaxAge: 10 }, ); - expect(hints).toStrictEqual(new Map([['droid', { maxAge: 60 }]])); + expect(hints).toStrictEqual( + new Map([['droid', { maxAge: 60, scope: 'PUBLIC' }]]), + ); }); it('should set the specified maxAge for a field from a cache hint on the target type extension', async () => { @@ -147,7 +151,7 @@ describe('@cacheControl directives', () => { name: String! } - extend type Droid @cacheControl(maxAge: 60) + extend type Droid @cacheControl(maxAge: 60, scope: PUBLIC) `); const hints = await collectCacheControlHints( @@ -162,7 +166,9 @@ describe('@cacheControl directives', () => { { defaultMaxAge: 10 }, ); - expect(hints).toStrictEqual(new Map([['droid', { maxAge: 60 }]])); + expect(hints).toStrictEqual( + new Map([['droid', { maxAge: 60, scope: 'PUBLIC' }]]), + ); }); it('should overwrite the default maxAge when maxAge=0 is specified on the type', async () => { @@ -171,7 +177,7 @@ describe('@cacheControl directives', () => { droid(id: ID!): Droid } - type Droid @cacheControl(maxAge: 0) { + type Droid @cacheControl(maxAge: 0, scope: PUBLIC) { id: ID! name: String! } @@ -189,16 +195,18 @@ describe('@cacheControl directives', () => { { defaultMaxAge: 10 }, ); - expect(hints).toStrictEqual(new Map([['droid', { maxAge: 0 }]])); + expect(hints).toStrictEqual( + new Map([['droid', { maxAge: 0, scope: 'PUBLIC' }]]), + ); }); it('should override the maxAge from the target type with that specified on a field', async () => { const schema = buildSchemaWithCacheControlSupport(` type Query { - droid(id: ID!): Droid @cacheControl(maxAge: 120) + droid(id: ID!): Droid @cacheControl(maxAge: 120, scope: PUBLIC) } - type Droid @cacheControl(maxAge: 60) { + type Droid @cacheControl(maxAge: 60, scope: PUBLIC) { id: ID! name: String! } @@ -216,13 +224,15 @@ describe('@cacheControl directives', () => { { defaultMaxAge: 10 }, ); - expect(hints).toStrictEqual(new Map([['droid', { maxAge: 120 }]])); + expect(hints).toStrictEqual( + new Map([['droid', { maxAge: 120, scope: 'PUBLIC' }]]), + ); }); it('should override the maxAge from the target type with that specified on a field, keeping the scope', async () => { const schema = buildSchemaWithCacheControlSupport(` type Query { - droid(id: ID!): Droid @cacheControl(maxAge: 120) + droid(id: ID!): Droid @cacheControl(maxAge: 120, scope: PRIVATE) } type Droid @cacheControl(maxAge: 60, scope: PRIVATE) { @@ -285,11 +295,11 @@ describe('@cacheControl directives', () => { alien(id: ID!): Alien } - interface Named @cacheControl(maxAge: 60) { + interface Named @cacheControl(maxAge: 60, scope: PUBLIC) { name: String! } - type Droid implements Named @cacheControl(maxAge: 30) { + type Droid implements Named @cacheControl(maxAge: 30, scope: PUBLIC) { id: ID! name: String! } @@ -315,7 +325,7 @@ describe('@cacheControl directives', () => { ); expect(hintsNamed).toStrictEqual( - new Map([['named', { maxAge: 60, scope: undefined }]]), + new Map([['named', { maxAge: 60, scope: 'PUBLIC' }]]), ); const hintsDroid = await collectCacheControlHints( @@ -331,7 +341,7 @@ describe('@cacheControl directives', () => { ); expect(hintsDroid).toStrictEqual( - new Map([['droid', { maxAge: 30, scope: undefined }]]), + new Map([['droid', { maxAge: 30, scope: 'PUBLIC' }]]), ); const hintsAlien = await collectCacheControlHints( @@ -356,18 +366,18 @@ describe('@cacheControl directives', () => { const schema = makeExecutableSchemaWithCacheControlSupport({ typeDefs: `#graphql type Query { - topLevel: DroidQuery @cacheControl(maxAge: 1000) + topLevel: DroidQuery @cacheControl(maxAge: 1000, scope: PUBLIC) } type DroidQuery { - droid: Droid @cacheControl(inheritMaxAge: true) - droids: [Droid] @cacheControl(inheritMaxAge: true) + droid: Droid @cacheControl(inheritMaxAge: true, scope: PUBLIC) + droids: [Droid] @cacheControl(inheritMaxAge: true, scope: PUBLIC) } type Droid { uncachedField: Droid scalarField: String - cachedField: String @cacheControl(maxAge: 30) + cachedField: String @cacheControl(maxAge: 30, scope: PUBLIC) } `, }); @@ -382,8 +392,9 @@ describe('@cacheControl directives', () => { expect(hints).toStrictEqual( new Map([ - ['topLevel', { maxAge: 1000 }], - ['topLevel.droid.cachedField', { maxAge: 30 }], + ['topLevel', { maxAge: 1000, scope: 'PUBLIC' }], + ['topLevel.droid', { maxAge: undefined, scope: 'PUBLIC' }], + ['topLevel.droid.cachedField', { maxAge: 30, scope: 'PUBLIC' }], ]), ); expect(policyIfCacheable).toStrictEqual({ @@ -402,10 +413,14 @@ describe('@cacheControl directives', () => { expect(hints).toStrictEqual( new Map([ - ['topLevel', { maxAge: 1000 }], - ['topLevel.droid.cachedField', { maxAge: 30 }], + ['topLevel', { maxAge: 1000, scope: 'PUBLIC' }], + ['topLevel.droid', { maxAge: undefined, scope: 'PUBLIC' }], + ['topLevel.droid.cachedField', { maxAge: 30, scope: 'PUBLIC' }], ['topLevel.droid.uncachedField', { maxAge: 0 }], - ['topLevel.droid.uncachedField.cachedField', { maxAge: 30 }], + [ + 'topLevel.droid.uncachedField.cachedField', + { maxAge: 30, scope: 'PUBLIC' }, + ], ]), ); expect(policyIfCacheable).toBeNull(); @@ -421,13 +436,20 @@ describe('@cacheControl directives', () => { expect(hints).toStrictEqual( new Map([ - ['topLevel', { maxAge: 1000 }], - ['topLevel.droids.0.cachedField', { maxAge: 30 }], + ['topLevel', { maxAge: 1000, scope: 'PUBLIC' }], + ['topLevel.droids', { maxAge: undefined, scope: 'PUBLIC' }], + ['topLevel.droids.0.cachedField', { maxAge: 30, scope: 'PUBLIC' }], ['topLevel.droids.0.uncachedField', { maxAge: 0 }], - ['topLevel.droids.0.uncachedField.cachedField', { maxAge: 30 }], - ['topLevel.droids.1.cachedField', { maxAge: 30 }], + [ + 'topLevel.droids.0.uncachedField.cachedField', + { maxAge: 30, scope: 'PUBLIC' }, + ], + ['topLevel.droids.1.cachedField', { maxAge: 30, scope: 'PUBLIC' }], ['topLevel.droids.1.uncachedField', { maxAge: 0 }], - ['topLevel.droids.1.uncachedField.cachedField', { maxAge: 30 }], + [ + 'topLevel.droids.1.uncachedField.cachedField', + { maxAge: 30, scope: 'PUBLIC' }, + ], ]), ); expect(policyIfCacheable).toBeNull(); @@ -439,15 +461,15 @@ describe('@cacheControl directives', () => { typeDefs: `#graphql type Query { book: Book - cachedBook: Book @cacheControl(maxAge: 60) - reader: Reader @cacheControl(maxAge: 40) + cachedBook: Book @cacheControl(maxAge: 60, scope: PUBLIC) + reader: Reader @cacheControl(maxAge: 40, scope: PUBLIC) } type Book { title: String - cachedTitle: String @cacheControl(maxAge: 30) + cachedTitle: String @cacheControl(maxAge: 30, scope: PUBLIC) } type Reader { - book: Book @cacheControl(inheritMaxAge: true) + book: Book @cacheControl(inheritMaxAge: true, scope: PUBLIC) } `, }); @@ -474,13 +496,13 @@ describe('@cacheControl directives', () => { const schema = makeExecutableSchemaWithCacheControlSupport({ typeDefs: `#graphql type Query { - topLevel: TopLevel @cacheControl(maxAge: 500) + topLevel: TopLevel @cacheControl(maxAge: 500, scope: PUBLIC) } type TopLevel { foo: Foo @cacheControl(inheritMaxAge: true, scope: PRIVATE) } type Foo { - bar: String @cacheControl(maxAge: 5) + bar: String @cacheControl(maxAge: 5, scope: PUBLIC) } `, }); @@ -494,9 +516,9 @@ describe('@cacheControl directives', () => { expect(hints).toStrictEqual( new Map([ - ['topLevel', { maxAge: 500 }], - ['topLevel.foo', { scope: 'PRIVATE' }], - ['topLevel.foo.bar', { maxAge: 5 }], + ['topLevel', { maxAge: 500, scope: 'PUBLIC' }], + ['topLevel.foo', { maxAge: undefined, scope: 'PRIVATE' }], + ['topLevel.foo.bar', { maxAge: 5, scope: 'PUBLIC' }], ]), ); expect(policyIfCacheable).toStrictEqual({ @@ -509,12 +531,12 @@ describe('@cacheControl directives', () => { const schema = makeExecutableSchemaWithCacheControlSupport({ typeDefs: `#graphql type Query { - topLevel: TopLevel @cacheControl(maxAge: 500) + topLevel: TopLevel @cacheControl(maxAge: 500, scope: PUBLIC) } type TopLevel { foo: Foo } - type Foo @cacheControl(inheritMaxAge: true) { + type Foo @cacheControl(inheritMaxAge: true, scope: PUBLIC) { bar: String } `, @@ -527,7 +549,12 @@ describe('@cacheControl directives', () => { {}, ); - expect(hints).toStrictEqual(new Map([['topLevel', { maxAge: 500 }]])); + expect(hints).toStrictEqual( + new Map([ + ['topLevel', { maxAge: 500, scope: 'PUBLIC' }], + ['topLevel.foo', { maxAge: undefined, scope: 'PUBLIC' }], + ]), + ); expect(policyIfCacheable).toStrictEqual({ maxAge: 500, scope: 'PUBLIC', @@ -538,15 +565,15 @@ describe('@cacheControl directives', () => { const schema = makeExecutableSchemaWithCacheControlSupport({ typeDefs: `#graphql type Query { - foo: Foo @cacheControl(maxAge: 5) + foo: Foo @cacheControl(maxAge: 5, scope: PUBLIC) } type Foo { - bar: Bar @cacheControl(inheritMaxAge: true) + bar: Bar @cacheControl(inheritMaxAge: true, scope: PUBLIC) defaultBar: Bar } type Bar { scalar: String - cachedScalar: String @cacheControl(maxAge: 2) + cachedScalar: String @cacheControl(maxAge: 2, scope: PUBLIC) } `, }); diff --git a/packages/server/src/__tests__/plugin/cacheControl/cacheControlSupport.ts b/packages/server/src/__tests__/plugin/cacheControl/cacheControlSupport.ts index b9c49430ea6..a2ba983a037 100644 --- a/packages/server/src/__tests__/plugin/cacheControl/cacheControlSupport.ts +++ b/packages/server/src/__tests__/plugin/cacheControl/cacheControlSupport.ts @@ -15,7 +15,7 @@ export function augmentTypeDefsWithCacheControlSupport(typeDefs: string) { directive @cacheControl( maxAge: Int - scope: CacheControlScope + scope: CacheControlScope! inheritMaxAge: Boolean ) on FIELD_DEFINITION | OBJECT | INTERFACE | UNION ` + typeDefs diff --git a/packages/server/src/__tests__/plugin/cacheControl/directiveDefinition.test.ts b/packages/server/src/__tests__/plugin/cacheControl/directiveDefinition.test.ts new file mode 100644 index 00000000000..deb0de162f1 --- /dev/null +++ b/packages/server/src/__tests__/plugin/cacheControl/directiveDefinition.test.ts @@ -0,0 +1,114 @@ +import { ApolloServer } from '../../..'; +import { ApolloServerPluginCacheControl } from '../../../plugin/cacheControl'; +import { describe, it, expect } from '@jest/globals'; + +const goodDefinition = `#graphql + enum CacheControlScope { + PUBLIC + PRIVATE + } + directive @cacheControl( + maxAge: Int + scope: CacheControlScope! + inheritMaxAge: Boolean + ) on FIELD_DEFINITION | OBJECT | INTERFACE | UNION +`; + +const queryType = `#graphql + type Query { + hello: String @cacheControl(maxAge: 10, scope: PUBLIC) + } +`; + +async function startAndStop( + typeDefs: string, + options?: Parameters[0], +) { + const server = new ApolloServer({ + typeDefs, + plugins: options ? [ApolloServerPluginCacheControl(options)] : [], + }); + await server.start(); + await server.stop(); +} + +describe('@cacheControl directive definition check', () => { + it('accepts the documented definition', async () => { + await startAndStop(goodDefinition + queryType); + }); + + it('accepts a differently named scope enum and a subset of locations', async () => { + await startAndStop(`#graphql + enum Scope { + PRIVATE + PUBLIC + } + directive @cacheControl(maxAge: Int, scope: Scope!) on FIELD_DEFINITION + ${queryType} + `); + }); + + it('accepts schemas that do not define the directive', async () => { + await startAndStop('type Query { hello: String }'); + }); + + it('rejects a nullable scope', async () => { + await expect( + startAndStop( + goodDefinition.replace( + 'scope: CacheControlScope!', + 'scope: CacheControlScope', + ) + queryType, + ), + ).rejects.toThrow( + /its `scope` argument has nullable type `CacheControlScope`[\s\S]*scope: CacheControlScope!/, + ); + }); + + it('rejects a missing scope', async () => { + await expect( + startAndStop(`#graphql + directive @cacheControl(maxAge: Int) on FIELD_DEFINITION + type Query { + hello: String @cacheControl(maxAge: 10) + } + `), + ).rejects.toThrow('it has no `scope` argument'); + }); + + it('rejects an enum with other values', async () => { + await expect( + startAndStop( + goodDefinition.replace('PRIVATE\n', 'PRIVATE\n SECRET\n') + + queryType, + ), + ).rejects.toThrow('has values PRIVATE, PUBLIC, SECRET rather than exactly'); + }); + + it('rejects unexpected arguments and locations', async () => { + await expect( + startAndStop( + goodDefinition.replace( + 'inheritMaxAge: Boolean', + 'inheritMaxAge: Boolean\n ttl: Int', + ) + queryType, + ), + ).rejects.toThrow('it has an unexpected `ttl` argument'); + await expect( + startAndStop( + goodDefinition.replace('| UNION', '| UNION | ARGUMENT_DEFINITION') + + queryType, + ), + ).rejects.toThrow('it is defined on the ARGUMENT_DEFINITION location'); + }); + + it('can be disabled', async () => { + await startAndStop( + goodDefinition.replace( + 'scope: CacheControlScope!', + 'scope: CacheControlScope', + ) + queryType, + { validateDirectiveDefinition: false }, + ); + }); +}); diff --git a/packages/server/src/__tests__/plugin/cacheControl/dynamicCacheControl.test.ts b/packages/server/src/__tests__/plugin/cacheControl/dynamicCacheControl.test.ts index dce512f437a..7956b740084 100644 --- a/packages/server/src/__tests__/plugin/cacheControl/dynamicCacheControl.test.ts +++ b/packages/server/src/__tests__/plugin/cacheControl/dynamicCacheControl.test.ts @@ -117,7 +117,7 @@ describe('dynamic cache control', () => { it('should set the scope for a field from a dynamic cache hint', async () => { const typeDefs = ` type Query { - droid(id: ID!): Droid @cacheControl(maxAge: 60) + droid(id: ID!): Droid @cacheControl(maxAge: 60, scope: PUBLIC) } type Droid { @@ -163,7 +163,7 @@ describe('dynamic cache control', () => { it('should override the maxAge set for a field from a dynamic cache hint', async () => { const typeDefs = ` type Query { - droid(id: ID!): Droid @cacheControl(maxAge: 60) + droid(id: ID!): Droid @cacheControl(maxAge: 60, scope: PUBLIC) } type Droid { @@ -201,6 +201,8 @@ describe('dynamic cache control', () => { { defaultMaxAge: 10 }, ); - expect(hints).toStrictEqual(new Map([['droid', { maxAge: 120 }]])); + expect(hints).toStrictEqual( + new Map([['droid', { maxAge: 120, scope: 'PUBLIC' }]]), + ); }); }); diff --git a/packages/server/src/plugin/cacheControl/index.ts b/packages/server/src/plugin/cacheControl/index.ts index bf611689357..16d4cbbda37 100644 --- a/packages/server/src/plugin/cacheControl/index.ts +++ b/packages/server/src/plugin/cacheControl/index.ts @@ -1,12 +1,17 @@ import type { ApolloServerPlugin } from '../../externalTypes/index.js'; import { type DirectiveNode, + DirectiveLocation, getNamedType, type GraphQLCompositeType, + type GraphQLDirective, type GraphQLField, isCompositeType, + isEnumType, isInterfaceType, + isNonNullType, isObjectType, + isScalarType, responsePathAsArray, } from 'graphql'; import { newCachePolicy } from '../../cachePolicy.js'; @@ -48,10 +53,95 @@ export interface ApolloServerPluginCacheControlOptions { * delivery response, and the body contains no errors. */ calculateHttpHeaders?: boolean | 'if-cacheable'; + /** + * If true (the default), the plugin checks at startup that any + * `@cacheControl` directive defined in your schema has the documented + * definition (in particular, that its `scope` argument is non-null, so that + * every `@cacheControl` usage says whether it is `PUBLIC` or `PRIVATE`), and + * throws an error describing the expected definition if it does not. Set + * this to false to keep using a different definition, such as the one with a + * nullable `scope` that Apollo Server 4 and 5 documented. + */ + validateDirectiveDefinition?: boolean; // For testing only. __testing__cacheHints?: Map; } +// The definition of `@cacheControl` that we document and expect schemas to use. +export const CACHE_CONTROL_DIRECTIVE_DEFINITION = `enum CacheControlScope { + PUBLIC + PRIVATE +} + +directive @cacheControl( + maxAge: Int + scope: CacheControlScope! + inheritMaxAge: Boolean +) on FIELD_DEFINITION | OBJECT | INTERFACE | UNION`; + +const ALLOWED_LOCATIONS = new Set([ + DirectiveLocation.FIELD_DEFINITION, + DirectiveLocation.OBJECT, + DirectiveLocation.INTERFACE, + DirectiveLocation.UNION, +]); + +// Checks that a schema's `@cacheControl` directive matches the documented +// definition closely enough for the plugin to interpret its usages correctly: +// `maxAge: Int`, `inheritMaxAge: Boolean`, a non-null `scope` whose enum has +// exactly the values PUBLIC and PRIVATE (the enum's name doesn't matter), no +// other arguments, and only the documented locations. Returns a description of +// the first problem found, or null. +export function cacheControlDirectiveDefinitionProblem( + directive: GraphQLDirective, +): string | null { + for (const location of directive.locations) { + if (!ALLOWED_LOCATIONS.has(location)) { + return `it is defined on the ${location} location`; + } + } + const seen = new Set(); + for (const arg of directive.args) { + seen.add(arg.name); + const type = arg.type; + switch (arg.name) { + case 'maxAge': + if (!(isScalarType(type) && type.name === 'Int')) { + return `its \`maxAge\` argument has type \`${type}\` rather than \`Int\``; + } + break; + case 'inheritMaxAge': + if (!(isScalarType(type) && type.name === 'Boolean')) { + return `its \`inheritMaxAge\` argument has type \`${type}\` rather than \`Boolean\``; + } + break; + case 'scope': { + if (!isNonNullType(type)) { + return `its \`scope\` argument has nullable type \`${type}\`; Apollo Server 6 requires every \`@cacheControl\` to specify a scope, so define it as \`${type}!\``; + } + const enumType = type.ofType; + if (!isEnumType(enumType)) { + return `its \`scope\` argument has type \`${type}\` rather than a non-null enum`; + } + const values = enumType + .getValues() + .map((v) => v.name) + .sort(); + if (values.join(',') !== 'PRIVATE,PUBLIC') { + return `its \`scope\` argument's enum \`${enumType.name}\` has values ${values.join(', ')} rather than exactly PUBLIC and PRIVATE`; + } + break; + } + default: + return `it has an unexpected \`${arg.name}\` argument`; + } + } + if (!seen.has('scope')) { + return 'it has no `scope` argument'; + } + return null; +} + export function ApolloServerPluginCacheControl( options: ApolloServerPluginCacheControlOptions = Object.create(null), ): ApolloServerPlugin { @@ -67,6 +157,18 @@ export function ApolloServerPluginCacheControl( __is_disabled_plugin__: false, async serverWillStart({ schema }) { + if (options.validateDirectiveDefinition !== false) { + const directive = schema.getDirective('cacheControl'); + const problem = directive + ? cacheControlDirectiveDefinitionProblem(directive) + : null; + if (problem) { + throw new Error( + `The schema's \`@cacheControl\` directive definition does not match the one Apollo Server expects: ${problem}. The expected definition is:\n\n${CACHE_CONTROL_DIRECTIVE_DEFINITION}\n\nTo use a different definition, pass \`validateDirectiveDefinition: false\` to ApolloServerPluginCacheControl.`, + ); + } + } + // Set the size of the caches to be equal to the number of composite types // and fields in the schema respectively. This generally means that the // cache will always have room for all the cache hints in the active