in Library/CorrelationIdManager.ts [19:100]
public static queryCorrelationId(config: Config, callback: (correlationId: string) => void) {
// GET request to `${this.endpointBase}/api/profiles/${this.instrumentationKey}/appId`
// If it 404s, the iKey is bad and we should give up
// If it fails otherwise, try again later
const appIdUrlString = `${config.profileQueryEndpoint}/api/profiles/${config.instrumentationKey}/appId`;
if (CorrelationIdManager.completedLookups.hasOwnProperty(appIdUrlString)) {
callback(CorrelationIdManager.completedLookups[appIdUrlString]);
return;
} else if (CorrelationIdManager.pendingLookups[appIdUrlString]) {
CorrelationIdManager.pendingLookups[appIdUrlString].push(callback);
return;
}
CorrelationIdManager.pendingLookups[appIdUrlString] = [callback];
const fetchAppId = () => {
if (!CorrelationIdManager.pendingLookups[appIdUrlString]) {
// This query has been cancelled.
return;
}
const requestOptions = {
method: 'GET',
// Ensure this request is not captured by auto-collection.
// Note: we don't refer to the property in HttpDependencyParser because that would cause a cyclical dependency
disableAppInsightsAutoCollection: true
};
Logging.info(CorrelationIdManager.TAG, requestOptions);
const req = Util.makeRequest(config, appIdUrlString, requestOptions, (res) => {
if (res.statusCode === 200) {
// Success; extract the appId from the body
let appId = "";
res.setEncoding("utf-8");
res.on('data', (data: any) => {
appId += data;
});
res.on('end', () => {
Logging.info(CorrelationIdManager.TAG, appId);
const result = CorrelationIdManager.correlationIdPrefix + appId;
CorrelationIdManager.completedLookups[appIdUrlString] = result;
if (CorrelationIdManager.pendingLookups[appIdUrlString]) {
CorrelationIdManager.pendingLookups[appIdUrlString].forEach((cb) => cb(result));
}
delete CorrelationIdManager.pendingLookups[appIdUrlString];
});
} else if (res.statusCode >= 400 && res.statusCode < 500) {
// Not found, probably a bad key. Do not try again.
CorrelationIdManager.completedLookups[appIdUrlString] = undefined;
delete CorrelationIdManager.pendingLookups[appIdUrlString];
}
else {
// Keep retrying
return;
}
// Do not retry
if (CorrelationIdManager._handle) {
clearTimeout(CorrelationIdManager._handle);
CorrelationIdManager._handle = undefined;
}
}, true, false);
if (req) {
req.on('error', (error: Error) => {
// Unable to contact endpoint.
// Do nothing for now.
Logging.warn(CorrelationIdManager.TAG, error);
if (this._handle) {
clearTimeout(CorrelationIdManager._handle);
CorrelationIdManager._handle = undefined;
}
});
req.end();
}
};
if (!CorrelationIdManager._handle) {
CorrelationIdManager._handle = <any>setTimeout(fetchAppId, config.correlationIdRetryIntervalMs);
CorrelationIdManager._handle.unref(); // Don't block apps from terminating
}
// Initial fetch
setImmediate(fetchAppId);
}