-
Notifications
You must be signed in to change notification settings - Fork 2k
/
agent.ts
1046 lines (957 loc) 路 37.5 KB
/
agent.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os from 'os';
import { gzip } from 'zlib';
import {
DocumentNode,
GraphQLError,
GraphQLSchema,
printSchema,
} from 'graphql';
import {
ReportHeader,
Trace,
Report,
TracesAndStats,
} from 'apollo-engine-reporting-protobuf';
import { fetch, RequestAgent, Response } from 'apollo-server-env';
import retry from 'async-retry';
import { plugin } from './plugin';
import {
GraphQLRequestContext,
GraphQLRequestContextDidEncounterErrors,
GraphQLRequestContextDidResolveOperation,
Logger,
} from 'apollo-server-types';
import { InMemoryLRUCache } from 'apollo-server-caching';
import { defaultEngineReportingSignature } from 'apollo-graphql';
import { ApolloServerPlugin } from 'apollo-server-plugin-base';
import { reportingLoop, SchemaReporter } from './schemaReporter';
import { v4 as uuidv4 } from 'uuid';
import { createHash } from 'crypto';
let warnedOnDeprecatedApiKey = false;
export interface ClientInfo {
clientName?: string;
clientVersion?: string;
clientReferenceId?: string;
}
export type SendValuesBaseOptions =
| { onlyNames: Array<String> }
| { exceptNames: Array<String> }
| { all: true }
| { none: true };
type VariableValueTransformOptions = {
variables: Record<string, any>;
operationString?: string;
};
export type VariableValueOptions =
| {
transform: (
options: VariableValueTransformOptions,
) => Record<string, any>;
}
| SendValuesBaseOptions;
export type ReportTimingOptions<TContext> =
| ((
request:
| GraphQLRequestContextDidResolveOperation<TContext>
| GraphQLRequestContextDidEncounterErrors<TContext>,
) => Promise<boolean>)
| boolean;
export type GenerateClientInfo<TContext> = (
requestContext: GraphQLRequestContext<TContext>,
) => ClientInfo;
// AS3: Drop support for deprecated `ENGINE_API_KEY`.
export function getEngineApiKey({
engine,
skipWarn = false,
logger = console,
}: {
engine: EngineReportingOptions<any> | boolean | undefined;
skipWarn?: boolean;
logger?: Logger;
}) {
if (typeof engine === 'object') {
if (engine.apiKey) {
return engine.apiKey;
}
}
const legacyApiKeyFromEnv = process.env.ENGINE_API_KEY;
const apiKeyFromEnv = process.env.APOLLO_KEY;
if (legacyApiKeyFromEnv && apiKeyFromEnv && !skipWarn) {
logger.warn(
'Using `APOLLO_KEY` since `ENGINE_API_KEY` (deprecated) is also set in the environment.',
);
}
if (legacyApiKeyFromEnv && !warnedOnDeprecatedApiKey && !skipWarn) {
logger.warn(
'[deprecated] The `ENGINE_API_KEY` environment variable has been renamed to `APOLLO_KEY`.',
);
warnedOnDeprecatedApiKey = true;
}
return apiKeyFromEnv || legacyApiKeyFromEnv || '';
}
// AS3: Drop support for deprecated `ENGINE_SCHEMA_TAG`.
export function getEngineGraphVariant(
engine: EngineReportingOptions<any> | boolean | undefined,
logger: Logger = console,
): string | undefined {
if (engine === false) {
return;
} else if (
typeof engine === 'object' &&
(engine.graphVariant || engine.schemaTag)
) {
if (engine.graphVariant && engine.schemaTag) {
throw new Error(
'Cannot set both engine.graphVariant and engine.schemaTag. Please use engine.graphVariant.',
);
}
if (engine.schemaTag) {
logger.warn(
'[deprecated] The `schemaTag` property within `engine` configuration has been renamed to `graphVariant`.',
);
}
return engine.graphVariant || engine.schemaTag;
} else {
if (process.env.ENGINE_SCHEMA_TAG) {
logger.warn(
'[deprecated] The `ENGINE_SCHEMA_TAG` environment variable has been renamed to `APOLLO_GRAPH_VARIANT`.',
);
}
if (process.env.ENGINE_SCHEMA_TAG && process.env.APOLLO_GRAPH_VARIANT) {
throw new Error(
'`APOLLO_GRAPH_VARIANT` and `ENGINE_SCHEMA_TAG` (deprecated) environment variables must not both be set.',
);
}
return process.env.APOLLO_GRAPH_VARIANT || process.env.ENGINE_SCHEMA_TAG;
}
}
export interface EngineReportingOptions<TContext> {
/**
* API key for the service. Get this from
* [Engine](https://engine.apollographql.com) by logging in and creating
* a service. You may also specify this with the `ENGINE_API_KEY`
* environment variable; the option takes precedence. __Required__.
*/
apiKey?: string;
/**
* Specify the function for creating a signature for a query. See signature.ts
* for details.
*/
calculateSignature?: (ast: DocumentNode, operationName: string) => string;
/**
* How often to send reports to the Engine server. We'll also send reports
* when the report gets big; see maxUncompressedReportSize.
*/
reportIntervalMs?: number;
/**
* We send a report when the report size will become bigger than this size in
* bytes (default: 4MB). (This is a rough limit --- we ignore the size of the
* report header and some other top level bytes. We just add up the lengths of
* the serialized traces and signatures.)
*/
maxUncompressedReportSize?: number;
/**
* [DEPRECATED] this option was replaced by tracesEndpointUrl
* The URL of the Engine report ingress server.
*/
endpointUrl?: string;
/**
* The URL to the Apollo Graph Manager ingress endpoint.
* (Previously, this was `endpointUrl`, which will be removed in AS3).
*/
tracesEndpointUrl?: string;
/**
* If set, prints all reports as JSON when they are sent.
*/
debugPrintReports?: boolean;
/**
* HTTP(s) agent to be used on the fetch call to apollo-engine metrics endpoint
*/
requestAgent?: RequestAgent | false;
/**
* Reporting is retried with exponential backoff up to this many times
* (including the original request). Defaults to 5.
*/
maxAttempts?: number;
/**
* Minimum back-off for retries. Defaults to 100ms.
*/
minimumRetryDelayMs?: number;
/**
* By default, errors that occur when sending trace reports to Engine servers
* will be logged to standard error. Specify this function to process errors
* in a different way.
*/
reportErrorFunction?: (err: Error) => void;
/**
* By default, Apollo Server does not send the values of any GraphQL variables to Apollo's servers, because variable
* values often contain the private data of your app's users. If you'd like variable values to be included in traces, set this option.
* This option can take several forms:
* - { none: true }: don't send any variable values (DEFAULT)
* - { all: true}: send all variable values
* - { transform: ... }: a custom function for modifying variable values. Keys added by the custom function will
* be removed, and keys removed will be added back with an empty value. For security reasons, if an error occurs within this function, all variable values will be replaced with `[PREDICATE_FUNCTION_ERROR]`.
* - { exceptNames: ... }: a case-sensitive list of names of variables whose values should not be sent to Apollo servers
* - { onlyNames: ... }: A case-sensitive list of names of variables whose values will be sent to Apollo servers
*
* Defaults to not sending any variable values if both this parameter and
* the deprecated `privateVariables` are not set. The report will
* indicate each private variable key whose value was redacted by { none: true } or { exceptNames: [...] }.
*
* TODO(helen): Add new flag to the trace details (and modify the protobuf message structure) to indicate the type of modification. Then, add the following description to the docs:
* "The report will indicate that variable values were modified by a custom function, or will list all private variables redacted."
* TODO(helen): LINK TO EXAMPLE FUNCTION? e.g. a function recursively search for keys to be blocklisted
*/
sendVariableValues?: VariableValueOptions;
/**
* This option allows configuring the behavior of request tracing and
* reporting to [Apollo Graph Manager](https://engine.apollographql.com/).
*
* By default, this is set to `true`, which results in *all* requests being
* traced and reported. This behavior can be _disabled_ by setting this option
* to `false`. Alternatively, it can be selectively enabled or disabled on a
* per-request basis using a predicate function.
*
* When specified as a predicate function, the _return value_ of its
* invocation (per request) will determine whether or not that request is
* traced and reported. The predicate function will receive the request
* context. If validation and parsing of the request succeeds the function will
* receive the request context in the
* [`GraphQLRequestContextDidResolveOperation`](https://www.apollographql.com/docs/apollo-server/integrations/plugins/#didresolveoperation)
* phase, which permits tracing based on dynamic properties, e.g., HTTP
* headers or the `operationName` (when available),
* otherwise it will receive the request context in the [`GraphQLRequestContextDidEncounterError`](https://www.apollographql.com/docs/apollo-server/integrations/plugins/#didencountererrors)
* phase:
*
* **Example:**
*
* ```js
* reportTiming(requestContext) {
* // Always trace `query HomeQuery { ... }`.
* if (requestContext.operationName === "HomeQuery") return true;
*
* // Also trace if the "trace" header is set to "true".
* if (requestContext.request.http?.headers?.get("trace") === "true") {
* return true;
* }
*
* // Otherwise, do not trace!
* return false;
* },
* ```
*
*/
reportTiming?: ReportTimingOptions<TContext>;
/**
* [DEPRECATED] Use sendVariableValues
* Passing an array into privateVariables is equivalent to passing { exceptNames: array } into
* sendVariableValues, and passing in `true` or `false` is equivalent to passing { none: true } or
* { all: true }, respectively.
*
* An error will be thrown if both this deprecated option and its replacement, sendVariableValues are defined.
*/
privateVariables?: Array<String> | boolean;
/**
* By default, Apollo Server does not send the list of HTTP headers and values to
* Apollo's servers, to protect private data of your app's users. If you'd like this information included in traces,
* set this option. This option can take several forms:
*
* - { none: true } to drop all HTTP request headers (DEFAULT)
* - { all: true } to send the values of all HTTP request headers
* - { exceptNames: Array<String> } A case-insensitive list of names of HTTP headers whose values should not be
* sent to Apollo servers
* - { onlyNames: Array<String> }: A case-insensitive list of names of HTTP headers whose values will be sent to Apollo servers
*
* Defaults to not sending any request header names and values if both this parameter and
* the deprecated `privateHeaders` are not set.
* Unlike with sendVariableValues, names of dropped headers are not reported.
* The headers 'authorization', 'cookie', and 'set-cookie' are never reported.
*/
sendHeaders?: SendValuesBaseOptions;
/**
* [DEPRECATED] Use sendHeaders
* Passing an array into privateHeaders is equivalent to passing { exceptNames: array } into sendHeaders, and
* passing `true` or `false` is equivalent to passing in { none: true } and { all: true }, respectively.
*
* An error will be thrown if both this deprecated option and its replacement, sendHeaders are defined.
*/
privateHeaders?: Array<String> | boolean;
/**
* For backwards compatibility only; specifying `new ApolloServer({engine: {handleSignals: false}})` is
* equivalent to specifying `new ApolloServer({stopOnTerminationSignals: false})`.
*/
handleSignals?: boolean;
/**
* Sends the trace report immediately. This options is useful for stateless environments
*/
sendReportsImmediately?: boolean;
/**
* @deprecated Use `rewriteError` instead.
* @default false
*
* To remove the error message from traces, set this to true.
*/
maskErrorDetails?: boolean;
/**
* By default, all errors get reported to Engine servers. You can specify a
* a filter function to exclude specific errors from being reported by
* returning an explicit `null`, or you can mask certain details of the error
* by modifying it and returning the modified error.
*/
rewriteError?: (err: GraphQLError) => GraphQLError | null;
/**
* [DEPRECATED: use graphVariant] A human readable name to tag this variant of a schema (i.e. staging, EU)
*/
schemaTag?: string;
/**
* A human readable name to refer to the variant of the graph for which metrics are reported
*/
graphVariant?: string;
/**
* Creates the client information for operation traces.
*/
generateClientInfo?: GenerateClientInfo<TContext>;
/**
* Enable schema reporting from this server with Apollo Graph Manager.
*
* The use of this option avoids the need to register schemas manually within
* CI deployment pipelines using `apollo schema:push` by periodically
* reporting this server's schema (when changes are detected) along with
* additional details about its runtime environment to Apollo Graph Manager.
*
* See [our _preview
* documentation_](https://github.com/apollographql/apollo-schema-reporting-preview-docs)
* for more information.
*/
reportSchema?: boolean;
/**
* Override the reported schema that is reported to AGM.
* This schema does not go through any normalizations and the string is directly sent to Apollo Graph Manager.
* This would be useful for comments or other ordering and whitespace changes that get stripped when generating a `GraphQLSchema`
*/
overrideReportedSchema?: string;
/**
* The schema reporter waits before starting reporting.
* By default, the report waits some random amount of time between 0 and 10 seconds.
* A longer interval leads to more staggered starts which means it is less likely
* multiple servers will get asked to upload the same schema.
*
* If this server runs in lambda or in other constrained environments it would be useful
* to decrease the schema reporting max wait time to be less than default.
*
* This number will be the max for the range in ms that the schema reporter will
* wait before starting to report.
*/
schemaReportingInitialDelayMaxMs?: number;
/**
* The URL to use for reporting schemas.
*/
schemaReportingUrl?: string;
/**
* A logger interface to be used for output and errors. When not provided
* it will default to the server's own `logger` implementation and use
* `console` when that is not available.
*/
logger?: Logger;
/**
* @deprecated use {@link reportSchema} instead
*/
experimental_schemaReporting?: boolean;
/**
* @deprecated use {@link overrideReportedSchema} instead
*/
experimental_overrideReportedSchema?: string;
/**
* @deprecated use {@link schemaReportingInitialDelayMaxMs} instead
*/
experimental_schemaReportingInitialDelayMaxMs?: number;
}
export interface AddTraceArgs {
trace: Trace;
operationName: string;
queryHash: string;
executableSchemaId: string;
source?: string;
document?: DocumentNode;
logger: Logger;
}
const serviceHeaderDefaults = {
hostname: os.hostname(),
agentVersion: `apollo-engine-reporting@${require('../package.json').version}`,
runtimeVersion: `node ${process.version}`,
// XXX not actually uname, but what node has easily.
uname: `${os.platform()}, ${os.type()}, ${os.release()}, ${os.arch()})`,
};
class ReportData {
report!: Report;
size!: number;
readonly header: ReportHeader;
constructor(executableSchemaId: string, graphVariant: string) {
this.header = new ReportHeader({
...serviceHeaderDefaults,
executableSchemaId,
schemaTag: graphVariant,
});
this.reset();
}
reset() {
this.report = new Report({ header: this.header });
this.size = 0;
}
}
// EngineReportingAgent is a persistent object which creates
// EngineReportingExtensions for each request and sends batches of trace reports
// to the Engine server.
export class EngineReportingAgent<TContext = any> {
private readonly options: EngineReportingOptions<TContext>;
private readonly apiKey: string;
private readonly logger: Logger = console;
private readonly graphVariant: string;
private readonly reportDataByExecutableSchemaId: {
[executableSchemaId: string]: ReportData | undefined;
} = Object.create(null);
private reportTimer: any; // timer typing is weird and node-specific
private readonly sendReportsImmediately?: boolean;
private stopped: boolean = false;
private signatureCache: InMemoryLRUCache<string>;
private currentSchemaReporter?: SchemaReporter;
private readonly bootId: string;
private lastSeenExecutableSchemaToId?: {
executableSchema: string | GraphQLSchema;
executableSchemaId: string;
};
private readonly tracesEndpointUrl: string;
readonly schemaReport: boolean;
public constructor(options: EngineReportingOptions<TContext> = {}) {
this.options = options;
this.apiKey = getEngineApiKey({
engine: this.options,
skipWarn: false,
logger: this.logger,
});
if (options.logger) this.logger = options.logger;
this.bootId = uuidv4();
this.graphVariant = getEngineGraphVariant(options, this.logger) || '';
if (!this.apiKey) {
throw new Error(
`To use EngineReportingAgent, you must specify an API key via the apiKey option or the APOLLO_KEY environment variable.`,
);
}
if (options.experimental_schemaReporting !== undefined) {
this.logger.warn(
[
'[deprecated] The "experimental_schemaReporting" option has been',
'renamed to "reportSchema"'
].join(' ')
);
if (options.reportSchema === undefined) {
options.reportSchema = options.experimental_schemaReporting;
}
}
if (options.experimental_overrideReportedSchema !== undefined) {
this.logger.warn(
[
'[deprecated] The "experimental_overrideReportedSchema" option has',
'been renamed to "overrideReportedSchema"'
].join(' ')
);
if (options.overrideReportedSchema === undefined) {
options.overrideReportedSchema = options.experimental_overrideReportedSchema;
}
}
if (options.experimental_schemaReportingInitialDelayMaxMs !== undefined) {
this.logger.warn(
[
'[deprecated] The "experimental_schemaReportingInitialDelayMaxMs"',
'option has been renamed to "schemaReportingInitialDelayMaxMs"'
].join(' ')
);
if (options.schemaReportingInitialDelayMaxMs === undefined) {
options.schemaReportingInitialDelayMaxMs = options.experimental_schemaReportingInitialDelayMaxMs;
}
}
if (options.reportSchema !== undefined) {
this.schemaReport = options.reportSchema;
} else {
this.schemaReport = process.env.APOLLO_SCHEMA_REPORTING === "true"
}
// Since calculating the signature for Engine reporting is potentially an
// expensive operation, we'll cache the signatures we generate and re-use
// them based on repeated traces for the same `queryHash`.
this.signatureCache = createSignatureCache({ logger: this.logger });
this.sendReportsImmediately = options.sendReportsImmediately;
if (!this.sendReportsImmediately) {
this.reportTimer = setInterval(
() => this.sendAllReportsAndReportErrors(),
this.options.reportIntervalMs || 10 * 1000,
);
}
if (this.options.endpointUrl) {
this.logger.warn(
'[deprecated] The `endpointUrl` option within `engine` has been renamed to `tracesEndpointUrl`.',
);
}
this.tracesEndpointUrl =
(this.options.endpointUrl ||
this.options.tracesEndpointUrl ||
'https://engine-report.apollodata.com') + '/api/ingress/traces';
// Handle the legacy options: privateVariables and privateHeaders
handleLegacyOptions(this.options);
}
private executableSchemaIdGenerator(schema: string | GraphQLSchema) {
if (this.lastSeenExecutableSchemaToId?.executableSchema === schema) {
return this.lastSeenExecutableSchemaToId.executableSchemaId;
}
const id = computeExecutableSchemaId(schema);
// We override this variable every time we get a new schema so we cache
// the last seen value. It mostly a cached pair.
this.lastSeenExecutableSchemaToId = {
executableSchema: schema,
executableSchemaId: id,
};
return id;
}
public newPlugin(): ApolloServerPlugin<TContext> {
return plugin(this.options, this.addTrace.bind(this), {
startSchemaReporting: this.startSchemaReporting.bind(this),
executableSchemaIdGenerator: this.executableSchemaIdGenerator.bind(this),
schemaReport: this.schemaReport,
});
}
private getReportData(executableSchemaId: string): ReportData {
const existing = this.reportDataByExecutableSchemaId[executableSchemaId];
if (existing) {
return existing;
}
const reportData = new ReportData(executableSchemaId, this.graphVariant);
this.reportDataByExecutableSchemaId[executableSchemaId] = reportData;
return reportData;
}
public async addTrace({
trace,
queryHash,
document,
operationName,
source,
executableSchemaId,
/**
* Since this agent instruments the plugin with its `options.logger`, but
* also passes off a reference to this `addTrace` method which is invoked
* with the availability of a per-request `logger`, this `logger` (in this
* destructuring) is already conditionally either:
*
* 1. The `logger` that was passed into the `options` for the agent.
* 2. The request-specific `logger`.
*/
logger,
}: AddTraceArgs): Promise<void> {
// Ignore traces that come in after stop().
if (this.stopped) {
return;
}
const reportData = this.getReportData(executableSchemaId);
const { report } = reportData;
const protobufError = Trace.verify(trace);
if (protobufError) {
throw new Error(`Error encoding trace: ${protobufError}`);
}
const encodedTrace = Trace.encode(trace).finish();
const signature = await this.getTraceSignature({
queryHash,
document,
source,
operationName,
logger,
});
const statsReportKey = `# ${operationName || '-'}\n${signature}`;
if (!report.tracesPerQuery.hasOwnProperty(statsReportKey)) {
report.tracesPerQuery[statsReportKey] = new TracesAndStats();
(report.tracesPerQuery[statsReportKey] as any).encodedTraces = [];
}
// See comment on our override of Traces.encode inside of
// apollo-engine-reporting-protobuf to learn more about this strategy.
(report.tracesPerQuery[statsReportKey] as any).encodedTraces.push(
encodedTrace,
);
reportData.size += encodedTrace.length + Buffer.byteLength(statsReportKey);
// If the buffer gets big (according to our estimate), send.
if (
this.sendReportsImmediately ||
reportData.size >=
(this.options.maxUncompressedReportSize || 4 * 1024 * 1024)
) {
await this.sendReportAndReportErrors(executableSchemaId);
}
}
public async sendAllReports(): Promise<void> {
await Promise.all(
Object.keys(this.reportDataByExecutableSchemaId).map(id =>
this.sendReport(id),
),
);
}
public async sendReport(executableSchemaId: string): Promise<void> {
const reportData = this.getReportData(executableSchemaId);
const { report } = reportData;
reportData.reset();
if (Object.keys(report.tracesPerQuery).length === 0) {
return;
}
// Send traces asynchronously, so that (eg) addTrace inside a resolver
// doesn't block on it.
await Promise.resolve();
if (this.options.debugPrintReports) {
// In terms of verbosity, and as the name of this option suggests, this
// message is either an "info" or a "debug" level message. However,
// we are using `warn` here for compatibility reasons since the
// `debugPrintReports` flag pre-dated the existence of log-levels and
// changing this to also require `debug: true` (in addition to
// `debugPrintReports`) just to reach the level of verbosity to produce
// the output would be a breaking change. The "warn" level is on by
// default. There is a similar theory and comment applied below.
this.logger.warn(
`Engine sending report: ${JSON.stringify(report.toJSON())}`,
);
}
const protobufError = Report.verify(report);
if (protobufError) {
throw new Error(`Error encoding report: ${protobufError}`);
}
const message = Report.encode(report).finish();
const compressed = await new Promise<Buffer>((resolve, reject) => {
// The protobuf library gives us a Uint8Array. Node 8's zlib lets us
// pass it directly; convert for the sake of Node 6. (No support right
// now for Node 4, which lacks Buffer.from.)
const messageBuffer = Buffer.from(
message.buffer as ArrayBuffer,
message.byteOffset,
message.byteLength,
);
gzip(messageBuffer, (err, gzipResult) => {
if (err) {
reject(err);
} else {
resolve(gzipResult);
}
});
});
// Wrap fetch with async-retry for automatic retrying
const response: Response = await retry(
// Retry on network errors and 5xx HTTP
// responses.
async () => {
const curResponse = await fetch(this.tracesEndpointUrl, {
method: 'POST',
headers: {
'user-agent': 'apollo-engine-reporting',
'x-api-key': this.apiKey,
'content-encoding': 'gzip',
},
body: compressed,
agent: this.options.requestAgent,
});
if (curResponse.status >= 500 && curResponse.status < 600) {
throw new Error(
`HTTP status ${curResponse.status}, ${(await curResponse.text()) ||
'(no body)'}`,
);
} else {
return curResponse;
}
},
{
retries: (this.options.maxAttempts || 5) - 1,
minTimeout: this.options.minimumRetryDelayMs || 100,
factor: 2,
},
).catch((err: Error) => {
throw new Error(
`Error sending report to Apollo Engine servers: ${err.message}`,
);
});
if (response.status < 200 || response.status >= 300) {
// Note that we don't expect to see a 3xx here because request follows
// redirects.
throw new Error(
`Error sending report to Apollo Engine servers: HTTP status ${
response.status
}, ${(await response.text()) || '(no body)'}`,
);
}
if (this.options.debugPrintReports) {
// In terms of verbosity, and as the name of this option suggests, this
// message is either an "info" or a "debug" level message. However,
// we are using `warn` here for compatibility reasons since the
// `debugPrintReports` flag pre-dated the existence of log-levels and
// changing this to also require `debug: true` (in addition to
// `debugPrintReports`) just to reach the level of verbosity to produce
// the output would be a breaking change. The "warn" level is on by
// default. There is a similar theory and comment applied above.
this.logger.warn(`Engine report: status ${response.status}`);
}
}
public startSchemaReporting({
executableSchemaId,
executableSchema,
}: {
executableSchemaId: string;
executableSchema: string;
}) {
this.logger.info('Starting schema reporter...');
if (this.options.overrideReportedSchema !== undefined) {
this.logger.info('Schema to report has been overridden');
}
if (this.options.schemaReportingInitialDelayMaxMs !== undefined) {
this.logger.info(`Schema reporting max initial delay override: ${
this.options.schemaReportingInitialDelayMaxMs
} ms`);
}
if (this.options.schemaReportingUrl !== undefined) {
this.logger.info(`Schema reporting URL override: ${
this.options.schemaReportingUrl
}`);
}
if (this.currentSchemaReporter) {
this.currentSchemaReporter.stop();
}
const serverInfo = {
bootId: this.bootId,
graphVariant: this.graphVariant,
// The infra environment in which this edge server is running, e.g. localhost, Kubernetes
// Length must be <= 256 characters.
platform: process.env.APOLLO_SERVER_PLATFORM || 'local',
runtimeVersion: `node ${process.version}`,
executableSchemaId: executableSchemaId,
// An identifier used to distinguish the version of the server code such as git or docker sha.
// Length must be <= 256 charecters
userVersion: process.env.APOLLO_SERVER_USER_VERSION,
// "An identifier for the server instance. Length must be <= 256 characters.
serverId:
process.env.APOLLO_SERVER_ID || process.env.HOSTNAME || os.hostname(),
libraryVersion: `apollo-engine-reporting@${
require('../package.json').version
}`,
};
this.logger.info(
`Schema reporting EdgeServerInfo: ${JSON.stringify(serverInfo)}`
)
// Jitter the startup between 0 and 10 seconds
const delay = Math.floor(
Math.random() *
(this.options.schemaReportingInitialDelayMaxMs || 10_000),
);
const schemaReporter = new SchemaReporter(
serverInfo,
executableSchema,
this.apiKey,
this.options.schemaReportingUrl,
this.logger
);
const fallbackReportingDelayInMs = 20_000;
this.currentSchemaReporter = schemaReporter;
const logger = this.logger;
setTimeout(function() {
reportingLoop(schemaReporter, logger, false, fallbackReportingDelayInMs);
}, delay);
}
// Stop prevents reports from being sent automatically due to time or buffer
// size, and stop buffering new traces. You may still manually send a last
// report by calling sendReport().
public stop() {
if (this.reportTimer) {
clearInterval(this.reportTimer);
this.reportTimer = undefined;
}
if (this.currentSchemaReporter) {
this.currentSchemaReporter.stop();
}
this.stopped = true;
}
private async getTraceSignature({
queryHash,
operationName,
document,
source,
logger,
}: {
queryHash: string;
operationName: string;
document?: DocumentNode;
source?: string;
logger: Logger;
}): Promise<string> {
if (!document && !source) {
// This shouldn't happen: one of those options must be passed to runQuery.
throw new Error('No document or source?');
}
const cacheKey = signatureCacheKey(queryHash, operationName);
// If we didn't have the signature in the cache, we'll resort to
// calculating it asynchronously. The `addTrace` method will
// `await` the `signature` if it's a Promise, prior to putting it
// on the stack of traces to deliver to the cloud.
const cachedSignature = await this.signatureCache.get(cacheKey);
if (cachedSignature) {
return cachedSignature;
}
if (!document) {
// We didn't get an AST, possibly because of a parse failure. Let's just
// use the full query string.
//
// XXX This does mean that even if you use a calculateSignature which
// hides literals, you might end up sending literals for queries
// that fail parsing or validation. Provide some way to mask them
// anyway?
return source as string;
}
const generatedSignature = (
this.options.calculateSignature || defaultEngineReportingSignature
)(document, operationName);
// Intentionally not awaited so the cache can be written to at leisure.
//
// As of the writing of this comment, this signature cache is exclusively
// backed by an `InMemoryLRUCache` which cannot do anything
// non-synchronously, though that will probably change in the future,
// and a distributed cache store, like Redis, doesn't seem unfathomable.
//
// Due in part to the plugin being separate from the `EngineReportingAgent`,
// the loggers are difficult to track down here. Errors will be logged to
// either the request-specific logger on the request context (if available)
// or to the `logger` that was passed into `EngineReportingOptions` which
// is provided in the `EngineReportingAgent` constructor options.
this.signatureCache.set(cacheKey, generatedSignature).catch(err => {
logger.warn(
'Could not store signature cache. ' + (err && err.message) || err,
);
});
return generatedSignature;
}
public async sendAllReportsAndReportErrors(): Promise<void> {
await Promise.all(
Object.keys(this.reportDataByExecutableSchemaId).map(executableSchemaId =>
this.sendReportAndReportErrors(executableSchemaId),
),
);
}
private sendReportAndReportErrors(executableSchemaId: string): Promise<void> {
return this.sendReport(executableSchemaId).catch(err => {
// This catch block is primarily intended to catch network errors from
// the retried request itself, which include network errors and non-2xx
// HTTP errors.
if (this.options.reportErrorFunction) {
this.options.reportErrorFunction(err);
} else {
this.logger.error(err.message);
}
});
}
}
function createSignatureCache({
logger,
}: {
logger: Logger;
}): InMemoryLRUCache<string> {
let lastSignatureCacheWarn: Date;
let lastSignatureCacheDisposals: number = 0;
return new InMemoryLRUCache<string>({
// Calculate the length of cache objects by the JSON.stringify byteLength.
sizeCalculator(obj) {
return Buffer.byteLength(JSON.stringify(obj), 'utf8');
},
// 3MiB limit, very much approximately since we can't be sure how V8 might
// be storing these strings internally. Though this should be enough to
// store a fair amount of operation signatures (~10000?), depending on their
// overall complexity. A future version of this might expose some
// configuration option to grow the cache, but ideally, we could do that
// dynamically based on the resources available to the server, and not add
// more configuration surface area. Hopefully the warning message will allow
// us to evaluate the need with more validated input from those that receive
// it.
maxSize: Math.pow(2, 20) * 3,
onDispose() {
// Count the number of disposals between warning messages.
lastSignatureCacheDisposals++;
// Only show a message warning about the high turnover every 60 seconds.
if (
!lastSignatureCacheWarn ||
new Date().getTime() - lastSignatureCacheWarn.getTime() > 60000
) {
// Log the time that we last displayed the message.
lastSignatureCacheWarn = new Date();
logger.warn(
[
'This server is processing a high number of unique operations. ',
`A total of ${lastSignatureCacheDisposals} records have been `,
'ejected from the Engine Reporting signature cache in the past ',
'interval. If you see this warning frequently, please open an ',
'issue on the Apollo Server repository.',
].join(''),
);
// Reset the disposal counter for the next message interval.
lastSignatureCacheDisposals = 0;
}
},
});
}
export function signatureCacheKey(queryHash: string, operationName: string) {
return `${queryHash}${operationName && ':' + operationName}`;
}
// Helper function to modify the EngineReportingOptions if the deprecated fields 'privateVariables' and 'privateHeaders'
// were set.
// - Throws an error if both the deprecated option and its replacement (e.g. 'privateVariables' and 'sendVariableValues') were set.
// - Otherwise, wraps the deprecated option into objects that can be passed to the new replacement field (see the helper
// function makeSendValuesBaseOptionsFromLegacy), and deletes the deprecated field from the options
export function handleLegacyOptions(
options: EngineReportingOptions<any>,
): void {
// Handle the legacy option: privateVariables
if (
typeof options.privateVariables !== 'undefined' &&
options.sendVariableValues
) {
throw new Error(
"You have set both the 'sendVariableValues' and the deprecated 'privateVariables' options. Please only set 'sendVariableValues'.",
);
} else if (typeof options.privateVariables !== 'undefined') {