-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathConfigurationClientManager.ts
More file actions
297 lines (260 loc) · 11.7 KB
/
ConfigurationClientManager.ts
File metadata and controls
297 lines (260 loc) · 11.7 KB
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { AppConfigurationClient, AppConfigurationClientOptions } from "@azure/app-configuration";
import { ConfigurationClientWrapper } from "./ConfigurationClientWrapper.js";
import { TokenCredential } from "@azure/identity";
import { AzureAppConfigurationOptions, MaxRetries, MaxRetryDelayInMs } from "./AzureAppConfigurationOptions.js";
import { isBrowser, isWebWorker } from "./requestTracing/utils.js";
import * as RequestTracing from "./requestTracing/constants.js";
import { shuffleList } from "./common/utils.js";
const TCP_ORIGIN_KEY_NAME = "_origin._tcp";
const ALT_KEY_NAME = "_alt";
const TCP_KEY_NAME = "_tcp";
const ENDPOINT_KEY_NAME = "Endpoint";
const ID_KEY_NAME = "Id";
const SECRET_KEY_NAME = "Secret";
const TRUSTED_DOMAIN_LABELS = [".azconfig.", ".appconfig."];
const FALLBACK_CLIENT_REFRESH_EXPIRE_INTERVAL = 60 * 60 * 1000; // 1 hour in milliseconds
const MINIMAL_CLIENT_REFRESH_INTERVAL = 30 * 1000; // 30 seconds in milliseconds
const SRV_QUERY_TIMEOUT = 30 * 1000; // 30 seconds in milliseconds
export class ConfigurationClientManager {
#isFailoverable: boolean;
#dns: any;
endpoint: URL;
#secret : string;
#id : string;
#credential: TokenCredential;
#clientOptions: AppConfigurationClientOptions | undefined;
#appConfigOptions: AzureAppConfigurationOptions | undefined;
#validDomain: string;
#staticClients: ConfigurationClientWrapper[]; // there should always be only one static client
#dynamicClients: ConfigurationClientWrapper[];
#replicaCount: number = 0;
#lastFallbackClientRefreshTime: number = 0;
#lastFallbackClientRefreshAttempt: number = 0;
constructor (
connectionStringOrEndpoint?: string | URL,
credentialOrOptions?: TokenCredential | AzureAppConfigurationOptions,
appConfigOptions?: AzureAppConfigurationOptions
) {
let staticClient: AppConfigurationClient;
const credentialPassed = instanceOfTokenCredential(credentialOrOptions);
if (typeof connectionStringOrEndpoint === "string" && !credentialPassed) {
const connectionString = connectionStringOrEndpoint;
this.#appConfigOptions = credentialOrOptions as AzureAppConfigurationOptions;
this.#clientOptions = getClientOptions(this.#appConfigOptions);
const ConnectionStringRegex = /Endpoint=(.*);Id=(.*);Secret=(.*)/;
const regexMatch = connectionString.match(ConnectionStringRegex);
if (regexMatch) {
const endpointFromConnectionStr = regexMatch[1];
this.endpoint = getValidUrl(endpointFromConnectionStr);
this.#id = regexMatch[2];
this.#secret = regexMatch[3];
} else {
throw new Error(`Invalid connection string. Valid connection strings should match the regex '${ConnectionStringRegex.source}'.`);
}
staticClient = new AppConfigurationClient(connectionString, this.#clientOptions);
} else if ((connectionStringOrEndpoint instanceof URL || typeof connectionStringOrEndpoint === "string") && credentialPassed) {
let endpoint = connectionStringOrEndpoint;
// ensure string is a valid URL.
if (typeof endpoint === "string") {
endpoint = getValidUrl(endpoint);
}
const credential = credentialOrOptions as TokenCredential;
this.#appConfigOptions = appConfigOptions as AzureAppConfigurationOptions;
this.#clientOptions = getClientOptions(this.#appConfigOptions);
this.endpoint = endpoint;
this.#credential = credential;
staticClient = new AppConfigurationClient(this.endpoint.origin, this.#credential, this.#clientOptions);
} else {
throw new Error("A connection string or an endpoint with credential must be specified to create a client.");
}
this.#staticClients = [new ConfigurationClientWrapper(this.endpoint.origin, staticClient)];
this.#validDomain = getValidDomain(this.endpoint.hostname.toLowerCase());
}
async init() {
if (this.#appConfigOptions?.replicaDiscoveryEnabled === false || isBrowser() || isWebWorker()) {
this.#isFailoverable = false;
return;
}
try {
this.#dns = await import("dns/promises");
} catch (error) {
this.#isFailoverable = false;
console.warn("Failed to load the dns module:", error.message);
return;
}
this.#isFailoverable = true;
}
getReplicaCount(): number {
return this.#replicaCount;
}
async getClients(): Promise<ConfigurationClientWrapper[]> {
if (!this.#isFailoverable) {
return this.#staticClients;
}
const currentTime = Date.now();
// Filter static clients whose backoff time has ended
let availableClients = this.#staticClients.filter(client => client.backoffEndTime <= currentTime);
if (currentTime >= this.#lastFallbackClientRefreshAttempt + MINIMAL_CLIENT_REFRESH_INTERVAL &&
(!this.#dynamicClients ||
// All dynamic clients are in backoff means no client is available
this.#dynamicClients.every(client => currentTime < client.backoffEndTime) ||
currentTime >= this.#lastFallbackClientRefreshTime + FALLBACK_CLIENT_REFRESH_EXPIRE_INTERVAL)) {
this.#lastFallbackClientRefreshAttempt = currentTime;
await this.#discoverFallbackClients(this.endpoint.hostname);
return availableClients.concat(this.#dynamicClients);
}
// If there are dynamic clients, filter and concatenate them
if (this.#dynamicClients && this.#dynamicClients.length > 0) {
availableClients = availableClients.concat(
this.#dynamicClients
.filter(client => client.backoffEndTime <= currentTime));
}
return availableClients;
}
async refreshClients() {
const currentTime = Date.now();
if (this.#isFailoverable &&
currentTime >= new Date(this.#lastFallbackClientRefreshAttempt + MINIMAL_CLIENT_REFRESH_INTERVAL).getTime()) {
this.#lastFallbackClientRefreshAttempt = currentTime;
await this.#discoverFallbackClients(this.endpoint.hostname);
}
}
async #discoverFallbackClients(host: string) {
let result;
let timeout;
try {
result = await Promise.race([
new Promise((_, reject) => timeout = setTimeout(() => reject(new Error("SRV record query timed out.")), SRV_QUERY_TIMEOUT)),
this.#querySrvTargetHost(host)
]);
} catch (error) {
throw new Error(`Failed to build fallback clients, ${error.message}`);
} finally {
clearTimeout(timeout);
}
const srvTargetHosts = shuffleList(result) as string[];
const newDynamicClients: ConfigurationClientWrapper[] = [];
for (const host of srvTargetHosts) {
if (isValidEndpoint(host, this.#validDomain)) {
const targetEndpoint = `https://${host}`;
if (host.toLowerCase() === this.endpoint.hostname.toLowerCase()) {
continue;
}
const client = this.#credential ?
new AppConfigurationClient(targetEndpoint, this.#credential, this.#clientOptions) :
new AppConfigurationClient(buildConnectionString(targetEndpoint, this.#secret, this.#id), this.#clientOptions);
newDynamicClients.push(new ConfigurationClientWrapper(targetEndpoint, client));
}
}
this.#dynamicClients = newDynamicClients;
this.#lastFallbackClientRefreshTime = Date.now();
this.#replicaCount = this.#dynamicClients.length;
}
/**
* Query SRV records and return target hosts.
*/
async #querySrvTargetHost(host: string): Promise<string[]> {
const results: string[] = [];
try {
// Look up SRV records for the origin host
const originRecords = await this.#dns.resolveSrv(`${TCP_ORIGIN_KEY_NAME}.${host}`);
if (originRecords.length === 0) {
return results;
}
// Add the first origin record to results
const originHost = originRecords[0].name;
results.push(originHost);
// Look up SRV records for alternate hosts
let index = 0;
// eslint-disable-next-line no-constant-condition
while (true) {
const currentAlt = `${ALT_KEY_NAME}${index}`;
const altRecords = await this.#dns.resolveSrv(`${currentAlt}.${TCP_KEY_NAME}.${originHost}`);
if (altRecords.length === 0) {
break; // No more alternate records, exit loop
}
altRecords.forEach(record => {
const altHost = record.name;
if (altHost) {
results.push(altHost);
}
});
index++;
}
} catch (err) {
if (err.code === "ENOTFOUND") {
return results; // No more SRV records found, return results
} else {
throw new Error(`Failed to lookup SRV records: ${err.message}`);
}
}
return results;
}
}
/**
* Builds a connection string from the given endpoint, secret, and id.
* Returns an empty string if either secret or id is empty.
*/
function buildConnectionString(endpoint, secret, id: string): string {
if (!secret || !id) {
return "";
}
return `${ENDPOINT_KEY_NAME}=${endpoint};${ID_KEY_NAME}=${id};${SECRET_KEY_NAME}=${secret}`;
}
/**
* Extracts a valid domain from the given endpoint URL based on trusted domain labels.
*/
export function getValidDomain(host: string): string {
for (const label of TRUSTED_DOMAIN_LABELS) {
const index = host.lastIndexOf(label);
if (index !== -1) {
return host.substring(index);
}
}
return "";
}
/**
* Checks if the given host ends with the valid domain.
*/
export function isValidEndpoint(host: string, validDomain: string): boolean {
if (!validDomain) {
return false;
}
return host.toLowerCase().endsWith(validDomain.toLowerCase());
}
function getClientOptions(options?: AzureAppConfigurationOptions): AppConfigurationClientOptions | undefined {
// user-agent
let userAgentPrefix = RequestTracing.USER_AGENT_PREFIX; // Default UA for JavaScript Provider
const userAgentOptions = options?.clientOptions?.userAgentOptions;
if (userAgentOptions?.userAgentPrefix) {
userAgentPrefix = `${userAgentOptions.userAgentPrefix} ${userAgentPrefix}`; // Prepend if UA prefix specified by user
}
// retry options
const defaultRetryOptions = {
maxRetries: MaxRetries,
maxRetryDelayInMs: MaxRetryDelayInMs,
};
const retryOptions = Object.assign({}, defaultRetryOptions, options?.clientOptions?.retryOptions);
return Object.assign({}, options?.clientOptions, {
retryOptions,
userAgentOptions: {
userAgentPrefix
}
});
}
function getValidUrl(endpoint: string): URL {
try {
return new URL(endpoint);
} catch (error) {
if (error.code === "ERR_INVALID_URL") {
throw new Error("Invalid endpoint URL.", { cause: error });
} else {
throw error;
}
}
}
export function instanceOfTokenCredential(obj: unknown) {
return obj && typeof obj === "object" && "getToken" in obj && typeof obj.getToken === "function";
}