Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove App ID exchange functionality #1079

Merged
merged 6 commits into from
Feb 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AutoCollection/HttpDependencies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import Util = require("../Library/Util");
import RequestResponseHeaders = require("../Library/RequestResponseHeaders");
import HttpDependencyParser = require("./HttpDependencyParser");
import { CorrelationContextManager, PrivateCustomProperties } from "./CorrelationContextManager";
import CorrelationIdManager = require("../Library/CorrelationIdManager");
import Traceparent = require("../Library/Traceparent");
import * as DiagChannel from "./diagnostic-channel/initialization";
import CorrelationIdManager = require("../Library/CorrelationIdManager");

class AutoCollectHttpDependencies {
public static disableCollectionRequestOption = "disableAppInsightsAutoCollection";
Expand Down
2 changes: 1 addition & 1 deletion AutoCollection/Statsbeat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,7 @@ class Statsbeat {
}

private _shutdownStatsbeat() {
this.enable(false);// Disable Statsbeat as is it failed 3 times cosnecutively during initialization, is possible SDK is running in private or restricted network
this.enable(false);// Disable Statsbeat as is it failed 3 times cosnecutively during initialization, is possible SDK is running in private or restricted network
}

private _getConnectionString(config: Config): string {
Expand Down
2 changes: 1 addition & 1 deletion Bootstrap/DataModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const DiagnosticMessageId = {
"setupAlreadyCalled": "3003",
"prefixFailed": "3004",
"aadEnabled": "3005",
"unknownError": "3006",
"unknownError": "3006"
}

export const enum SeverityLevel {
Expand Down
2 changes: 1 addition & 1 deletion Library/AzureVirtualMachine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export class AzureVirtualMachine {
[AutoCollectHttpDependencies.disableCollectionRequestOption]: true,
headers: {
"Metadata": "True"
},
}
};

const req = Util.makeRequest(config, metadataRequestUrl, requestOptions, (res) => {
Expand Down
6 changes: 1 addition & 5 deletions Library/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ class Config implements IConfig {
public correlationId: string; // TODO: Should be private
private _connectionString: string;
private _endpointBase: string = Constants.DEFAULT_BREEZE_ENDPOINT;
private _setCorrelationId: (v: string) => void;
private _profileQueryEndpoint: string;
private _instrumentationKey: string;
public _webInstrumentationConnectionString: string;
Expand Down Expand Up @@ -108,7 +107,6 @@ class Config implements IConfig {
"*.core.eaglex.ic.gov"
];

this._setCorrelationId = (correlationId) => this.correlationId = correlationId;
this.ignoreLegacyHeaders = this.ignoreLegacyHeaders || false;
this.profileQueryEndpoint = csCode.ingestionendpoint || csEnv.ingestionendpoint || process.env[Config.ENV_profileQueryEndpoint] || this._endpointBase;
this.quickPulseHost = this.quickPulseHost || csCode.liveendpoint || csEnv.liveendpoint || process.env[Config.ENV_quickPulseHost] || Constants.DEFAULT_LIVEMETRICS_HOST;
Expand All @@ -121,10 +119,8 @@ class Config implements IConfig {
}

public set profileQueryEndpoint(endpoint: string) {
CorrelationIdManager.cancelCorrelationIdQuery(this, this._setCorrelationId);
this._profileQueryEndpoint = endpoint;
this.correlationId = CorrelationIdManager.correlationIdPrefix; // Reset the correlationId while we wait for the new query
CorrelationIdManager.queryCorrelationId(this, this._setCorrelationId);
this.correlationId = CorrelationIdManager.correlationIdPrefix;
}

public get profileQueryEndpoint() {
Expand Down
106 changes: 2 additions & 104 deletions Library/CorrelationIdManager.ts
Original file line number Diff line number Diff line change
@@ -1,123 +1,21 @@
import Util = require("./Util");
import Config = require("./Config");
import Logging = require("./Logging");

class CorrelationIdManager {
private static TAG = "CorrelationIdManager";
private static _handle: NodeJS.Timer;
public static correlationIdPrefix = "cid-v1:";
public static w3cEnabled = true;
public static HTTP_TIMEOUT: number = 2500; // 2.5 seconds

// To avoid extraneous HTTP requests, we maintain a queue of callbacks waiting on a particular appId lookup,
// as well as a cache of completed lookups so future requests can be resolved immediately.
private static pendingLookups: { [key: string]: Function[] } = {};
private static completedLookups: { [key: string]: string } = {};

private static requestIdMaxLength = 1024;
private static currentRootId = Util.randomu32();
private static _requestTimedOut: boolean;

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.setTimeout(CorrelationIdManager.HTTP_TIMEOUT, () => {
this._requestTimedOut = true;
req.abort();
});
req.on("error", (error: Error) => {
// Unable to contact endpoint.
// Do nothing for now.
if (this._requestTimedOut) {
error.name = "telemetry timeout";
error.message = "telemetry request timed out";
}
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);
// No Op, App ID Exchange not required in SDK anymore
}

public static cancelCorrelationIdQuery(config: Config, callback: (correlationId: string) => void) {
const appIdUrlString = `${config.profileQueryEndpoint}/api/profiles/${config.instrumentationKey}/appId`;
const pendingLookups = CorrelationIdManager.pendingLookups[appIdUrlString];
if (pendingLookups) {
CorrelationIdManager.pendingLookups[appIdUrlString] = pendingLookups.filter((cb) => cb != callback);
if (CorrelationIdManager.pendingLookups[appIdUrlString].length == 0) {
delete CorrelationIdManager.pendingLookups[appIdUrlString];
}
}
// No Op, App ID Exchange not required in SDK anymore
}

/**
Expand Down
2 changes: 1 addition & 1 deletion Library/SnippetInjectionHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export const insertSnippetByIndex = (index: number, html: string, snippet: strin
let newHtml = null;
let subStart = html.substring(0, index);
let subEnd = html.substring(index);
newHtml = subStart + '<script type="text/javascript">' + snippet + "</script>" + subEnd;
newHtml = subStart + "<script type=\"text/javascript\">" + snippet + "</script>" + subEnd;
return newHtml;
}

Expand Down
1 change: 0 additions & 1 deletion Tests/EndToEnd.tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,6 @@ describe("EndToEnd", () => {
beforeEach(() => {
nockScope = interceptor.reply(503, { "errors": [{ "index": 0, "statusCode": 503 }] });
AppInsights.defaultClient = undefined;
sandbox.stub(CorrelationIdManager, 'queryCorrelationId'); // TODO: Fix method of stubbing requests to allow CID to be part of E2E tests
writeFile = sandbox.stub(FileSystemHelper, 'writeFileAsync');
writeFileSync = sandbox.stub(fs, 'writeFileSync');
existsSync = sandbox.stub(fs, 'existsSync').returns(true);
Expand Down
46 changes: 0 additions & 46 deletions Tests/Library/CorrelationIdManager.tests.ts

This file was deleted.

Loading