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] Add support for Server Timing headers #1490

Closed
wants to merge 2 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
1 change: 1 addition & 0 deletions packages/apollo-server-core/src/graphqlOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export interface GraphQLServerOptions<
fieldResolver?: GraphQLFieldResolver<any, TContext>;
debug?: boolean;
tracing?: boolean;
serverTiming?: boolean;
cacheControl?:
| boolean
| (CacheControlExtensionOptions & {
Expand Down
42 changes: 42 additions & 0 deletions packages/apollo-server-core/src/runHttpQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,10 @@ export async function runHttpQuery(
}
}

if (optionsObject.serverTiming === true && !optionsObject.tracing) {
throw new Error('Tracing must be enabled for serverTiming to work.');
}

let params: QueryOptions = {
schema: optionsObject.schema,
queryString,
Expand Down Expand Up @@ -461,6 +465,44 @@ export async function runHttpQuery(
}
}

if (optionsObject.serverTiming) {
responses.forEach(response => {
if (response.extensions && response.extensions.tracing) {
const pathToKey = (path: any[]) =>
path.filter(k => typeof k === 'string').join('.');

const results = response.extensions.tracing.execution.resolvers.reduce(
(results: Map<string, any>, resolver: any) => {
const key = pathToKey(resolver.path);
if (
!results.has(key) ||
results.get(key).duration < resolver.duration
) {
return results.set(key, resolver);
}

return results;
},
new Map(),
);
const keyToIDs = new Map();
var timings: string[] = [];
results.forEach((value: any, key: string) => {
const [rootKey] = value.path;
if (!keyToIDs.has(rootKey)) {
keyToIDs.set(rootKey, keyToIDs.size + 1);
}
const durationInMS = (value.duration / 1000000).toFixed(2);

timings.push(
`gql-${keyToIDs.get(rootKey)};dur=${durationInMS};desc="${key}"`,
);
});
responseInit.headers!['Server-Timing'] = timings.join(',');
}
});
}

if (!isBatch) {
const graphqlResponse = responses[0];
// This code is run on parse/validation errors and any other error that
Expand Down