Skip to content
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

[wip] Full Query Caching #1570

Closed
wants to merge 5 commits into from
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
29 changes: 28 additions & 1 deletion packages/apollo-engine-reporting/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,34 @@ export class EngineReportingExtension<TContext = any>
};
}

public willSendResponse(o: { graphqlResponse: GraphQLResponse }) {
public willSendResponse(o: {
graphqlResponse: GraphQLResponse;
cacheHit: boolean;
cachePolicy: string;
maxAgeMs: number;
}) {
this.trace.fullQueryCacheHit = o.cacheHit;
if (o.cacheHit) {
switch (o.cachePolicy) {
case 'public':
this.trace.cachePolicy = {
scope: Trace.CachePolicy.Scope.PUBLIC,
maxAgeNs: o.maxAgeMs * 1000,
};
break;
case 'private':
this.trace.cachePolicy = {
scope: Trace.CachePolicy.Scope.PRIVATE,
maxAgeNs: o.maxAgeMs * 1000,
};
break;
default:
this.trace.cachePolicy = {
scope: Trace.CachePolicy.Scope.UNKNOWN,
maxAgeNs: o.maxAgeMs,
};
}
}
const { errors } = o.graphqlResponse;
if (errors) {
errors.forEach((error: GraphQLError) => {
Expand Down
38 changes: 19 additions & 19 deletions packages/apollo-server-core/src/__tests__/runQuery.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* tslint:disable:no-unused-expression */
import MockReq = require('mock-req');
import { Request } from 'apollo-server-env';

import {
GraphQLSchema,
Expand Down Expand Up @@ -85,7 +85,7 @@ describe('runQuery', () => {
return runQuery({
schema,
queryString: query,
request: new MockReq(),
request: new Request('local'),
}).then(res => {
expect(res.data).toEqual(expected);
});
Expand All @@ -97,7 +97,7 @@ describe('runQuery', () => {
return runQuery({
schema,
parsedQuery: query,
request: new MockReq(),
request: new Request('local'),
}).then(res => {
expect(res.data).toEqual(expected);
});
Expand All @@ -110,7 +110,7 @@ describe('runQuery', () => {
schema,
queryString: query,
variables: { base: 1 },
request: new MockReq(),
request: new Request('local'),
}).then(res => {
expect(res.data).toBeUndefined();
expect(res.errors!.length).toEqual(1);
Expand All @@ -125,7 +125,7 @@ describe('runQuery', () => {
schema,
queryString: query,
debug: true,
request: new MockReq(),
request: new Request('local'),
}).then(() => {
logStub.mockRestore();
expect(logStub.mock.calls.length).toEqual(0);
Expand All @@ -139,7 +139,7 @@ describe('runQuery', () => {
schema,
queryString: query,
debug: false,
request: new MockReq(),
request: new Request('local'),
}).then(() => {
logStub.mockRestore();
expect(logStub.mock.calls.length).toEqual(0);
Expand All @@ -154,7 +154,7 @@ describe('runQuery', () => {
schema,
queryString: query,
variables: { base: 1 },
request: new MockReq(),
request: new Request('local'),
}).then(res => {
expect(res.data).toBeUndefined();
expect(res.errors!.length).toEqual(1);
Expand All @@ -169,7 +169,7 @@ describe('runQuery', () => {
schema,
queryString: query,
rootValue: 'it also',
request: new MockReq(),
request: new Request('local'),
}).then(res => {
expect(res.data).toEqual(expected);
});
Expand All @@ -182,7 +182,7 @@ describe('runQuery', () => {
schema,
queryString: query,
context: { s: 'it still' },
request: new MockReq(),
request: new Request('local'),
}).then(res => {
expect(res.data).toEqual(expected);
});
Expand All @@ -199,7 +199,7 @@ describe('runQuery', () => {
response['extensions'] = context.s;
return response;
},
request: new MockReq(),
request: new Request('local'),
}).then(res => {
expect(res.data).toEqual(expected);
expect(res['extensions']).toEqual('it still');
Expand All @@ -213,7 +213,7 @@ describe('runQuery', () => {
schema,
queryString: query,
variables: { base: 1 },
request: new MockReq(),
request: new Request('local'),
}).then(res => {
expect(res.data).toEqual(expected);
});
Expand All @@ -226,7 +226,7 @@ describe('runQuery', () => {
return runQuery({
schema,
queryString: query,
request: new MockReq(),
request: new Request('local'),
}).then(res => {
expect(res.errors![0].message).toEqual(expected);
});
Expand All @@ -236,7 +236,7 @@ describe('runQuery', () => {
return runQuery({
schema,
queryString: `{ testAwaitedValue }`,
request: new MockReq(),
request: new Request('local'),
}).then(res => {
expect(res.data).toEqual({
testAwaitedValue: 'it works',
Expand All @@ -259,7 +259,7 @@ describe('runQuery', () => {
schema,
queryString: query,
operationName: 'Q1',
request: new MockReq(),
request: new Request('local'),
}).then(res => {
expect(res.data).toEqual(expected);
});
Expand All @@ -278,7 +278,7 @@ describe('runQuery', () => {
schema,
queryString: query,
operationName: 'Q1',
request: new MockReq(),
request: new Request('local'),
});

expect(result1.data).toEqual({
Expand All @@ -292,7 +292,7 @@ describe('runQuery', () => {
queryString: query,
operationName: 'Q1',
fieldResolver: () => 'a very testful field resolver string',
request: new MockReq(),
request: new Request('local'),
});

expect(result2.data).toEqual({
Expand Down Expand Up @@ -333,7 +333,7 @@ describe('runQuery', () => {
}),
queryString,
extensions,
request: new MockReq(),
request: new Request('local'),
});
});

Expand All @@ -345,7 +345,7 @@ describe('runQuery', () => {
schema,
queryString,
extensions,
request: new MockReq(),
request: new Request('local'),
}).then(res => {
expect(res.data).toEqual(expected);
expect(res.extensions).toEqual({
Expand Down Expand Up @@ -390,7 +390,7 @@ describe('runQuery', () => {
schema,
queryString: query,
operationName: 'Q1',
request: new MockReq(),
request: new Request('local'),
});

// Expect there to be several async ids provided
Expand Down
8 changes: 7 additions & 1 deletion packages/apollo-server-core/src/caching.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import { CacheControlFormat } from 'apollo-cache-control';

export function calculateCacheControlHeaders(
responses: Array<ExecutionResult & { extensions?: Record<string, any> }>,
): Record<string, string> {
): Partial<{
'Cache-Control': string;
lowestMaxAge: number;
publicOrPrivate: string;
}> {
let lowestMaxAge = Number.MAX_VALUE;
let publicOrPrivate = 'public';

Expand Down Expand Up @@ -62,5 +66,7 @@ export function calculateCacheControlHeaders(

return {
'Cache-Control': `max-age=${lowestMaxAge}, ${publicOrPrivate}`,
lowestMaxAge,
publicOrPrivate,
};
}
2 changes: 2 additions & 0 deletions packages/apollo-server-core/src/graphqlOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ export interface GraphQLServerOptions<
| (CacheControlExtensionOptions & {
calculateHttpHeaders?: boolean;
stripFormattedExtensions?: boolean;
cache?: KeyValueCache;
privateCache?: KeyValueCache;
});
extensions?: Array<() => GraphQLExtension>;
dataSources?: () => DataSources<TContext>;
Expand Down
25 changes: 20 additions & 5 deletions packages/apollo-server-core/src/runHttpQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
PersistedQueryNotSupportedError,
PersistedQueryNotFoundError,
} from 'apollo-server-errors';
import { KeyValueCache } from 'apollo-server-caching';
import { calculateCacheControlHeaders } from './caching';

export interface HttpQueryRequest {
Expand Down Expand Up @@ -105,6 +106,8 @@ export async function runHttpQuery(
| CacheControlExtensionOptions & {
calculateHttpHeaders: boolean;
stripFormattedExtensions: boolean;
privateCache: KeyValueCache;
cache: KeyValueCache;
}
| undefined;

Expand Down Expand Up @@ -186,6 +189,10 @@ export async function runHttpQuery(
}
}

// Used for calculating cache key
const calculatedSha: string = sha256()
.update(queryString)
.digest('hex');
if (extensions && extensions.persistedQuery) {
// It looks like we've received an Apollo Persisted Query. Check if we
// support them. In an ideal world, we always would, however since the
Expand Down Expand Up @@ -233,9 +240,6 @@ export async function runHttpQuery(
);
}
} else {
const calculatedSha = sha256()
.update(queryString)
.digest('hex');
if (sha !== calculatedSha) {
throw new HttpQueryError(400, 'provided sha does not match query');
}
Expand Down Expand Up @@ -366,15 +370,22 @@ export async function runHttpQuery(
cacheControl = {
stripFormattedExtensions: false,
calculateHttpHeaders: false,
privateCache: optionsObject.cache!,
cache: optionsObject.cache!,
defaultMaxAge: 0,
};
} else {
const privateCache =
(optionsObject.cacheControl && optionsObject.cacheControl.cache) ||
optionsObject.cache!;
// Default behavior is to run default header calculation and return
// no cacheControl extensions
cacheControl = {
stripFormattedExtensions: true,
calculateHttpHeaders: true,
defaultMaxAge: 0,
privateCache,
cache: optionsObject.cache!,
...optionsObject.cacheControl,
};
}
Expand All @@ -393,7 +404,7 @@ export async function runHttpQuery(
formatResponse: optionsObject.formatResponse,
fieldResolver: optionsObject.fieldResolver,
debug: optionsObject.debug,
tracing: optionsObject.tracing,
tracing: optionsObject.tracing || false,
cacheControl: cacheControl
? omit(cacheControl, [
'calculateHttpHeaders',
Expand All @@ -404,6 +415,7 @@ export async function runHttpQuery(
extensions: optionsObject.extensions,
persistedQueryHit,
persistedQueryRegister,
queryHash: calculatedSha,
};

return runQuery(params);
Expand Down Expand Up @@ -445,7 +457,10 @@ export async function runHttpQuery(

responseInit.headers = {
...responseInit.headers,
...calculatedHeaders,
...(omit(calculatedHeaders, [
'lowestMaxAge',
'publicOrPrivate',
]) as Record<string, string>),
};
}

Expand Down
Loading