Skip to content

Commit

Permalink
[main] update the way to generate ajax perforamance mark prefix (#2367)
Browse files Browse the repository at this point in the history
  • Loading branch information
siyuniu-ms committed Jun 27, 2024
1 parent db5e084 commit 806051a
Show file tree
Hide file tree
Showing 9 changed files with 77 additions and 24 deletions.
3 changes: 1 addition & 2 deletions channels/offline-channel-js/src/Helpers/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@
import { EventPersistence } from "@microsoft/applicationinsights-common";
import { INotificationManager, ITelemetryItem, NotificationManager, generateW3CId } from "@microsoft/applicationinsights-core-js";
import { isString, objKeys, strSubstr } from "@nevware21/ts-utils";
import { isValidPersistenceLevel } from "../Providers/IndexDbProvider";
import { IPostTransmissionTelemetryItem } from "../Interfaces/IInMemoryBatch";

import { isValidPersistenceLevel } from "../Providers/IndexDbProvider";

// Endpoint schema
// <prefix>.<suffix>
Expand Down
3 changes: 1 addition & 2 deletions channels/offline-channel-js/src/Interfaces/IOfflineBatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@

import { IOfflineListener } from "@microsoft/applicationinsights-common";
import {
IPayloadData, IProcessTelemetryUnloadContext, ITelemetryUnloadState, IXHROverride,
createEnumStyle
IPayloadData, IProcessTelemetryUnloadContext, ITelemetryUnloadState, IXHROverride, createEnumStyle
} from "@microsoft/applicationinsights-core-js";
import { IPromise } from "@nevware21/ts-async";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
// Licensed under the MIT License.

import { EventPersistence } from "@microsoft/applicationinsights-common";
import { INotificationManager, IPayloadData, IProcessTelemetryContext, IXHROverride, createEnumStyle } from "@microsoft/applicationinsights-core-js";
import {
INotificationManager, IPayloadData, IProcessTelemetryContext, IXHROverride, createEnumStyle
} from "@microsoft/applicationinsights-core-js";
import { IPromise } from "@nevware21/ts-async";

/**
Expand Down
8 changes: 7 additions & 1 deletion examples/dependency/src/appinsights-init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,13 @@ export function changeConfig() {
return false;
}


export function enableAjaxPerfTrackingConfig() {
if (_appInsights && _appInsights.config.extensionConfig) {
_appInsights.config.extensionConfig["AjaxDependencyPlugin"].enableAjaxPerfTracking = true;
return true;
}
return false;
}

// // ******************************************************************************************************************************
// // Snippet Initialization
Expand Down
14 changes: 11 additions & 3 deletions examples/dependency/src/dependencies-example-index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
// Licensed under the MIT License.

import { arrForEach } from "@microsoft/applicationinsights-core-js";
import { addDependencyListener, addDependencyInitializer, stopDependencyEvent, changeConfig, initApplicationInsights, getConfig } from "./appinsights-init";
import { addHandlersButtonId, buttonSectionId, changeConfigButtonId, clearDetailsButtonId, clearDetailsList, clearEle, configContainerId, configDetails, createButton, createContainers, createDetailList, createFetchRequest, createUnTrackRequest, createXhrRequest, dependencyInitializerDetails, dependencyInitializerDetailsContainerId, dependencyListenerButtonId, dependencyListenerDetails, dependencyListenerDetailsContainerId, fetchCallId, fetchXhrId, removeAllHandlersId, stopDependencyEventButtonId, untrackFetchRequestId } from "./utils";
import { addDependencyListener, addDependencyInitializer, stopDependencyEvent, changeConfig, initApplicationInsights, getConfig, enableAjaxPerfTrackingConfig } from "./appinsights-init";
import { addHandlersButtonId, ajaxCallId, buttonSectionId, changeConfigButtonId, clearDetailsButtonId, clearDetailsList, clearEle, configContainerId, configDetails, createButton, createContainers, createDetailList, createFetchRequest, createUnTrackRequest, createXhrRequest, dependencyInitializerDetails, dependencyInitializerDetailsContainerId, dependencyListenerButtonId, dependencyListenerDetails, dependencyListenerDetailsContainerId, fetchCallId, fetchXhrId, removeAllHandlersId, stopDependencyEventButtonId, untrackFetchRequestId } from "./utils";

let dependencyListenerHandler: any = null;
let dependencyInitializerHandler: any = null;
Expand Down Expand Up @@ -72,17 +72,25 @@ function onAddHandlersClick() {
addDependencyInitializerOnClick();
}

function createAjaxPerformRequest() {
console.log("turn on perf tracking for ajax calls");
enableAjaxPerfTrackingConfig();
createConfigDetails();
createXhrRequest();
}

function createButtonSection() {
let container = document.getElementById(buttonSectionId);
let changeConfigBtn = createButton(changeConfigButtonId, changeConfigOnClick, changeConfigButtonId);
let handlersBtn = createButton(addHandlersButtonId, onAddHandlersClick, dependencyListenerButtonId);
let fetchButton = createButton(fetchCallId, createFetchRequest);
let ajaxPerfButton = createButton(ajaxCallId, createAjaxPerformRequest);
let xhrButton = createButton(fetchXhrId, createXhrRequest);
let untrackRequestButton = createButton(untrackFetchRequestId, createUnTrackRequest);
let stopEventButton = createButton(stopDependencyEventButtonId, stopDependencyEvent);
let removeHandlersButton = createButton(removeAllHandlersId, removeAllHandlers);
let clearBtn = createButton(clearDetailsButtonId, clearDetailsList);
let buttons = [changeConfigBtn, handlersBtn, fetchButton, xhrButton, untrackRequestButton, stopEventButton, removeHandlersButton, clearBtn];
let buttons = [changeConfigBtn, handlersBtn, fetchButton, xhrButton, ajaxPerfButton, untrackRequestButton, stopEventButton, removeHandlersButton, clearBtn];
arrForEach(buttons, ele => {
container?.appendChild(ele);
});
Expand Down
1 change: 1 addition & 0 deletions examples/dependency/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const stopDependencyEventButtonId = "stop-dependency-events";
export const changeConfigButtonId = "change-config";
export const fetchCallId = "create-fetch-request";
export const fetchXhrId = "create-xhr-request";
export const ajaxCallId = "create-ajaxPerf-request";
export const untrackFetchRequestId = "create-untrack-fetch-request";
export const removeAllHandlersId = "remove-all-handlers";
export const buttonSectionId = "button-section";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3378,6 +3378,52 @@ export class AjaxPerfTrackTests extends AITestClass {
}, 'response received', 600, 1000) as any)
});

this.testCaseAsync({
name: "AjaxPerf: check perf mark prefix is correctly set for multiple xhr requests",
stepDelay: 10,
steps: [ (testContext) => {
let performance = getPerformance();
let markSpy = this.sandbox.spy(performance, "mark");

this._ajax = new AjaxMonitor();
let appInsightsCore = new AppInsightsCore();
let coreConfig = {
instrumentationKey: "instrumentationKey",
extensionConfig: {
"AjaxDependencyPlugin": {
appId: "appId",
enableAjaxPerfTracking: true
}
}
};
appInsightsCore.initialize(coreConfig, [this._ajax, new TestChannelPlugin()]);
this._ajax["_currentWindowHost"] = "httpbin.org";
// Used to "wait" for App Insights to finish initializing which should complete after the XHR request
this._context["trackStub"] = this.sandbox.stub(appInsightsCore, "track");
// Act
var xhr = new XMLHttpRequest();

// trigger the request that should cause a track event once the xhr request is complete
xhr.open("GET", "https://httpbin.org/status/200");
xhr.send();

var xhr2 = new XMLHttpRequest();
xhr2.open("GET", "https://httpbin.org/anything");
xhr2.send();

Assert.equal(true, markSpy.called, "The code should have called been mark()");
let spyDetails = markSpy.args;
let prefix1 = spyDetails[0][0];
let prefix2 = spyDetails[1][0];
Assert.equal(prefix1.indexOf("ajaxData"), 0, "Prefix1 should start with 'ajaxData'");
Assert.equal(prefix2.indexOf("ajaxData"), 0, "Prefix2 should start with 'ajaxData'");

let ajaxCountOne = parseInt(prefix1.substring(prefix1.indexOf('#') + 1), 10);
let ajaxCountTwo = parseInt(prefix2.substring(prefix1.indexOf('#') + 1), 10);
Assert.equal(1, ajaxCountTwo-ajaxCountOne, "the count should increase by 1");
}]
});

this.testCaseAsync({
name: "AjaxPerf: check that performance tracking is reported, even if the entry is missing when enabled for xhr requests",
stepDelay: 10,
Expand Down
12 changes: 2 additions & 10 deletions extensions/applicationinsights-dependencies-js/src/ajax.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
dumpObj, eLoggingSeverity, eventOn, generateW3CId, getExceptionName, getGlobal, getIEVersion, getLocation, getPerformance, isFunction,
isNullOrUndefined, isString, isXhrSupported, mergeEvtNamespace, onConfigChange, strPrototype, strTrim
} from "@microsoft/applicationinsights-core-js";
import { isWebWorker, objFreeze, scheduleTimeout, strIndexOf, strSplit, strSubstr, strSubstring } from "@nevware21/ts-utils";
import { isWebWorker, objFreeze, scheduleTimeout, strIndexOf, strSplit, strSubstr } from "@nevware21/ts-utils";
import { DependencyInitializerFunction, IDependencyInitializerDetails, IDependencyInitializerHandler } from "./DependencyInitializer";
import {
DependencyListenerFunction, IDependencyHandler, IDependencyListenerContainer, IDependencyListenerDetails, IDependencyListenerHandler
Expand Down Expand Up @@ -597,14 +597,7 @@ export class AjaxMonitor extends BaseTelemetryPlugin implements IDependenciesPlu
_isUsingW3CHeaders = _distributedTracingMode === eDistributedTracingModes.AI_AND_W3C || _distributedTracingMode === eDistributedTracingModes.W3C;

if (_enableAjaxPerfTracking) {
let iKey = (config.instrumentationKey as string) || "unkwn";
// TODO: handle ikey promise
if (iKey.length > 5) {
_markPrefix = AJAX_MONITOR_PREFIX + strSubstring(iKey, iKey.length - 5) + ".";
} else {
_markPrefix = AJAX_MONITOR_PREFIX + iKey + ".";
}

_markPrefix = _ajaxDataId;
}

_disableAjaxTracking = !!_extensionConfig.disableAjaxTracking;
Expand Down Expand Up @@ -1220,7 +1213,6 @@ export class AjaxMonitor extends BaseTelemetryPlugin implements IDependenciesPlu
}

ajaxData.requestHeaders = requestHeaders;

_createMarkId(STR_FETCH, ajaxData);

return ajaxData;
Expand Down
10 changes: 5 additions & 5 deletions shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,16 @@ export interface ICorrelationConfig {

/**
* [Optional] Response and request headers to be excluded from AJAX & Fetch tracking data.
* To override or discard the default, add an array with all headers to be excluded or
* an empty array to the configuration.
*
* To override or discard the default, add an array with all headers to be excluded or
* an empty array to the configuration.
*
* For example: `["Authorization", "X-API-Key", "WWW-Authenticate"]`
*
*
* @example
* ```js
* import { ApplicationInsights } from '@microsoft/applicationinsights-web';
* import { AjaxPlugin } from '@microsoft/applicationinsights-dependencies-js';
*
*
* const dependencyPlugin = new AjaxPlugin();
* const appInsights = new ApplicationInsights({
* config: {
Expand Down

0 comments on commit 806051a

Please sign in to comment.