Skip to content

Commit db8a51f

Browse files
authored
Set User Agent and Correlation Context for requests (#6)
1 parent 571065e commit db8a51f

File tree

8 files changed

+303
-10
lines changed

8 files changed

+303
-10
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,7 @@ trademarks or logos is subject to and must follow
2323
[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general).
2424
Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.
2525
Any use of third-party trademarks or logos are subject to those third-party's policies.
26+
27+
# Data Collection
28+
29+
The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry by setting the environment variable `AZURE_APP_CONFIGURATION_TRACING_DISABLED` to `TRUE`. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft’s privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.

src/AzureAppConfigurationImpl.ts

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
// Copyright (c) Microsoft Corporation.
22
// Licensed under the MIT license.
33

4-
import { AppConfigurationClient, ConfigurationSetting } from "@azure/app-configuration";
4+
import { AppConfigurationClient, ConfigurationSetting, ListConfigurationSettingsOptions } from "@azure/app-configuration";
55
import { AzureAppConfiguration } from "./AzureAppConfiguration";
66
import { AzureAppConfigurationOptions } from "./AzureAppConfigurationOptions";
77
import { IKeyValueAdapter } from "./IKeyValueAdapter";
8+
import { JsonKeyValueAdapter } from "./JsonKeyValueAdapter";
89
import { KeyFilter } from "./KeyFilter";
910
import { LabelFilter } from "./LabelFilter";
1011
import { AzureKeyVaultKeyValueAdapter } from "./keyvault/AzureKeyVaultKeyValueAdapter";
11-
import { JsonKeyValueAdapter } from "./JsonKeyValueAdapter";
12+
import { CorrelationContextHeaderName, RequestTracingDisabledEnvironmentVariable } from "./requestTracing/constants";
13+
import { createCorrelationContextHeader } from "./requestTracing/utils";
1214

1315
export class AzureAppConfigurationImpl extends Map<string, unknown> implements AzureAppConfiguration {
1416
private adapters: IKeyValueAdapter[] = [];
@@ -17,12 +19,23 @@ export class AzureAppConfigurationImpl extends Map<string, unknown> implements A
1719
* Since multiple prefixes could start with the same characters, we need to trim the longest prefix first.
1820
*/
1921
private sortedTrimKeyPrefixes: string[] | undefined;
22+
private readonly requestTracingEnabled: boolean;
23+
private correlationContextHeader: string | undefined;
2024

2125
constructor(
2226
private client: AppConfigurationClient,
2327
private options: AzureAppConfigurationOptions | undefined
2428
) {
2529
super();
30+
// Enable request tracing if not opt-out
31+
const requestTracingDisabledEnv = process.env[RequestTracingDisabledEnvironmentVariable];
32+
if (requestTracingDisabledEnv && requestTracingDisabledEnv.toLowerCase() === "true") {
33+
this.requestTracingEnabled = false;
34+
} else {
35+
this.requestTracingEnabled = true;
36+
this.enableRequestTracing();
37+
}
38+
2639
if (options?.trimKeyPrefixes) {
2740
this.sortedTrimKeyPrefixes = [...options.trimKeyPrefixes].sort((a, b) => b.localeCompare(a));
2841
}
@@ -36,10 +49,17 @@ export class AzureAppConfigurationImpl extends Map<string, unknown> implements A
3649
const keyValues: [key: string, value: unknown][] = [];
3750
const selectors = this.options?.selectors ?? [{ keyFilter: KeyFilter.Any, labelFilter: LabelFilter.Null }];
3851
for (const selector of selectors) {
39-
const settings = this.client.listConfigurationSettings({
52+
const listOptions: ListConfigurationSettingsOptions = {
4053
keyFilter: selector.keyFilter,
4154
labelFilter: selector.labelFilter
42-
});
55+
};
56+
if (this.requestTracingEnabled) {
57+
listOptions.requestOptions = {
58+
customHeaders: this.customHeaders()
59+
}
60+
}
61+
62+
const settings = this.client.listConfigurationSettings(listOptions);
4363

4464
for await (const setting of settings) {
4565
if (setting.key) {
@@ -55,7 +75,7 @@ export class AzureAppConfigurationImpl extends Map<string, unknown> implements A
5575
}
5676

5777
private async processAdapters(setting: ConfigurationSetting<string>): Promise<[string, unknown]> {
58-
for(const adapter of this.adapters) {
78+
for (const adapter of this.adapters) {
5979
if (adapter.canProcess(setting)) {
6080
return adapter.processKeyValue(setting);
6181
}
@@ -73,4 +93,18 @@ export class AzureAppConfigurationImpl extends Map<string, unknown> implements A
7393
}
7494
return key;
7595
}
96+
97+
private enableRequestTracing() {
98+
this.correlationContextHeader = createCorrelationContextHeader(this.options);
99+
}
100+
101+
private customHeaders() {
102+
if (!this.requestTracingEnabled) {
103+
return undefined;
104+
}
105+
106+
const headers = {};
107+
headers[CorrelationContextHeaderName] = this.correlationContextHeader;
108+
return headers;
109+
}
76110
}

src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Copyright (c) Microsoft Corporation.
22
// Licensed under the MIT license.
33

4-
export { load } from "./Load";
4+
export { load } from "./load";
55
export { AzureAppConfiguration } from "./AzureAppConfiguration";
66
export { KeyFilter } from "./KeyFilter";
77
export { LabelFilter } from "./LabelFilter";

src/Load.ts renamed to src/load.ts

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { TokenCredential } from "@azure/identity";
66
import { AzureAppConfiguration } from "./AzureAppConfiguration";
77
import { AzureAppConfigurationImpl } from "./AzureAppConfigurationImpl";
88
import { AzureAppConfigurationOptions, MaxRetries, MaxRetryDelayInMs } from "./AzureAppConfigurationOptions";
9+
import * as RequestTracing from "./requestTracing/constants";
910

1011
export async function load(connectionString: string, options?: AzureAppConfigurationOptions): Promise<AzureAppConfiguration>;
1112
export async function load(endpoint: URL | string, credential: TokenCredential, options?: AzureAppConfigurationOptions): Promise<AzureAppConfiguration>;
@@ -38,7 +39,7 @@ export async function load(
3839
const credential = credentialOrOptions as TokenCredential;
3940
options = appConfigOptions;
4041
const clientOptions = getClientOptions(options);
41-
client = new AppConfigurationClient(endpoint.toString(), credential, clientOptions)
42+
client = new AppConfigurationClient(endpoint.toString(), credential, clientOptions);
4243
} else {
4344
throw new Error("A connection string or an endpoint with credential must be specified to create a client.");
4445
}
@@ -53,15 +54,24 @@ function instanceOfTokenCredential(obj: unknown) {
5354
}
5455

5556
function getClientOptions(options?: AzureAppConfigurationOptions): AppConfigurationClientOptions | undefined {
56-
// TODO: user-agent
57-
// TODO: set correlation context using additional policies
57+
// user-agent
58+
let userAgentPrefix = RequestTracing.UserAgentPrefix; // Default UA for JavaScript Provider
59+
const userAgentOptions = options?.clientOptions?.userAgentOptions;
60+
if (userAgentOptions?.userAgentPrefix) {
61+
userAgentPrefix = `${userAgentOptions.userAgentPrefix} ${userAgentPrefix}`; // Prepend if UA prefix specified by user
62+
}
63+
5864
// retry options
5965
const defaultRetryOptions = {
6066
maxRetries: MaxRetries,
6167
maxRetryDelayInMs: MaxRetryDelayInMs,
6268
}
6369
const retryOptions = Object.assign({}, defaultRetryOptions, options?.clientOptions?.retryOptions);
70+
6471
return Object.assign({}, options?.clientOptions, {
65-
retryOptions
72+
retryOptions,
73+
userAgentOptions: {
74+
userAgentPrefix
75+
}
6676
});
6777
}

src/requestTracing/constants.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT license.
3+
4+
import { Version } from "../version";
5+
6+
export const RequestTracingDisabledEnvironmentVariable = "AZURE_APP_CONFIGURATION_TRACING_DISABLED";
7+
8+
// User Agent
9+
export const UserAgentPrefix = `javascript-appconfiguration-provider/${Version}`;
10+
11+
// Correlation Context
12+
export const CorrelationContextHeaderName = "Correlation-Context";
13+
14+
// Env
15+
export const NodeJSEnvironmentVariable = "NODE_ENV";
16+
export const NodeJSDevEnvironmentVariableValue = "development";
17+
export const EnvironmentKey = "Env";
18+
export const DevEnvironmentValue = "Dev";
19+
20+
// Host Type
21+
export const HostTypeKey = "Host";
22+
export enum HostType {
23+
AzureFunction = "AzureFunction",
24+
AzureWebApp = "AzureWebApp",
25+
ContainerApp = "ContainerApp",
26+
Kubernetes = "Kubernetes",
27+
ServiceFabric = "ServiceFabric"
28+
}
29+
30+
// Environment variables to identify Host type.
31+
export const AzureFunctionEnvironmentVariable = "FUNCTIONS_EXTENSION_VERSION";
32+
export const AzureWebAppEnvironmentVariable = "WEBSITE_SITE_NAME";
33+
export const ContainerAppEnvironmentVariable = "CONTAINER_APP_NAME";
34+
export const KubernetesEnvironmentVariable = "KUBERNETES_PORT";
35+
export const ServiceFabricEnvironmentVariable = "Fabric_NodeName"; // See: https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-environment-variables-reference
36+
37+
// Request Type
38+
export const RequestTypeKey = "RequestType";
39+
export enum RequestType {
40+
Startup = "Startup",
41+
Watch = "Watch"
42+
}
43+
44+
// Tag names
45+
export const KeyVaultConfiguredTag = "UsesKeyVault";

src/requestTracing/utils.ts

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT license.
3+
4+
import { AzureAppConfigurationOptions } from "../AzureAppConfigurationOptions";
5+
import {
6+
AzureFunctionEnvironmentVariable,
7+
AzureWebAppEnvironmentVariable,
8+
ContainerAppEnvironmentVariable,
9+
DevEnvironmentValue,
10+
EnvironmentKey,
11+
HostType,
12+
HostTypeKey,
13+
KeyVaultConfiguredTag,
14+
KubernetesEnvironmentVariable,
15+
NodeJSDevEnvironmentVariableValue,
16+
NodeJSEnvironmentVariable,
17+
RequestType,
18+
RequestTypeKey,
19+
ServiceFabricEnvironmentVariable
20+
} from "./constants";
21+
22+
// Utils
23+
export function createCorrelationContextHeader(options: AzureAppConfigurationOptions | undefined): string {
24+
/*
25+
RequestType: 'Startup' during application starting up, 'Watch' after startup completed.
26+
Host: identify with defined envs
27+
Env: identify by env `NODE_ENV` which is a popular but not standard.usually the value can be "development", "production".
28+
UsersKeyVault
29+
*/
30+
const keyValues = new Map<string, string | undefined>();
31+
keyValues.set(RequestTypeKey, RequestType.Startup); // TODO: now always "Startup", until refresh is supported.
32+
keyValues.set(HostTypeKey, getHostType());
33+
keyValues.set(EnvironmentKey, isDevEnvironment() ? DevEnvironmentValue : undefined);
34+
35+
const tags: string[] = [];
36+
if (options?.keyVaultOptions) {
37+
const { credential, secretClients, secretResolver } = options.keyVaultOptions;
38+
if (credential !== undefined || secretClients?.length || secretResolver !== undefined) {
39+
tags.push(KeyVaultConfiguredTag);
40+
}
41+
}
42+
43+
const contextParts: string[] = [];
44+
for (const [k, v] of keyValues) {
45+
if (v !== undefined) {
46+
contextParts.push(`${k}=${v}`);
47+
}
48+
}
49+
for (const tag of tags) {
50+
contextParts.push(tag);
51+
}
52+
53+
return contextParts.join(",");
54+
}
55+
56+
function getHostType(): string | undefined {
57+
let hostType: string | undefined;
58+
if (process.env[AzureFunctionEnvironmentVariable]) {
59+
hostType = HostType.AzureFunction;
60+
} else if (process.env[AzureWebAppEnvironmentVariable]) {
61+
hostType = HostType.AzureWebApp;
62+
} else if (process.env[ContainerAppEnvironmentVariable]) {
63+
hostType = HostType.ContainerApp;
64+
} else if (process.env[KubernetesEnvironmentVariable]) {
65+
hostType = HostType.Kubernetes;
66+
} else if (process.env[ServiceFabricEnvironmentVariable]) {
67+
hostType = HostType.ServiceFabric;
68+
}
69+
return hostType;
70+
}
71+
72+
function isDevEnvironment(): boolean {
73+
const envType = process.env[NodeJSEnvironmentVariable];
74+
if (NodeJSDevEnvironmentVariableValue === envType?.toLowerCase()) {
75+
return true;
76+
}
77+
return false;
78+
}

src/version.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT license.
3+
4+
export const Version = "0.1.0-preview";

0 commit comments

Comments
 (0)