1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | import { isCustomHost, isGraphURL } from "../GraphRequestUtil";
|
12 | import { Context } from "../IContext";
|
13 | import { PACKAGE_VERSION } from "../Version";
|
14 | import { Middleware } from "./IMiddleware";
|
15 | import { MiddlewareControl } from "./MiddlewareControl";
|
16 | import { appendRequestHeader, generateUUID, getRequestHeader, setRequestHeader } from "./MiddlewareUtil";
|
17 | import { TelemetryHandlerOptions } from "./options/TelemetryHandlerOptions";
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 | export class TelemetryHandler implements Middleware {
|
25 | |
26 |
|
27 |
|
28 |
|
29 |
|
30 | private static CLIENT_REQUEST_ID_HEADER = "client-request-id";
|
31 |
|
32 | |
33 |
|
34 |
|
35 |
|
36 |
|
37 | private static SDK_VERSION_HEADER = "SdkVersion";
|
38 |
|
39 | |
40 |
|
41 |
|
42 |
|
43 |
|
44 | private static PRODUCT_NAME = "graph-js";
|
45 |
|
46 | |
47 |
|
48 |
|
49 |
|
50 |
|
51 | private static FEATURE_USAGE_STRING = "featureUsage";
|
52 |
|
53 | |
54 |
|
55 |
|
56 |
|
57 | private nextMiddleware: Middleware;
|
58 |
|
59 | |
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 | public async execute(context: Context): Promise<void> {
|
67 | const url = typeof context.request === "string" ? context.request : context.request.url;
|
68 | if (isGraphURL(url) || (context.customHosts && isCustomHost(url, context.customHosts))) {
|
69 |
|
70 |
|
71 | let clientRequestId: string = getRequestHeader(context.request, context.options, TelemetryHandler.CLIENT_REQUEST_ID_HEADER);
|
72 | if (!clientRequestId) {
|
73 | clientRequestId = generateUUID();
|
74 | setRequestHeader(context.request, context.options, TelemetryHandler.CLIENT_REQUEST_ID_HEADER, clientRequestId);
|
75 | }
|
76 | let sdkVersionValue = `${TelemetryHandler.PRODUCT_NAME}/${PACKAGE_VERSION}`;
|
77 | let options: TelemetryHandlerOptions;
|
78 | if (context.middlewareControl instanceof MiddlewareControl) {
|
79 | options = context.middlewareControl.getMiddlewareOptions(TelemetryHandlerOptions) as TelemetryHandlerOptions;
|
80 | }
|
81 | if (options) {
|
82 | const featureUsage: string = options.getFeatureUsage();
|
83 | sdkVersionValue += ` (${TelemetryHandler.FEATURE_USAGE_STRING}=${featureUsage})`;
|
84 | }
|
85 | appendRequestHeader(context.request, context.options, TelemetryHandler.SDK_VERSION_HEADER, sdkVersionValue);
|
86 | } else {
|
87 |
|
88 | delete context.options.headers[TelemetryHandler.CLIENT_REQUEST_ID_HEADER];
|
89 | delete context.options.headers[TelemetryHandler.SDK_VERSION_HEADER];
|
90 | }
|
91 | return await this.nextMiddleware.execute(context);
|
92 | }
|
93 |
|
94 | |
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 | public setNext(next: Middleware): void {
|
101 | this.nextMiddleware = next;
|
102 | }
|
103 | }
|