Skip to content

Commit

Permalink
[Main][Task]27064983: Update post channel to use sender post common i…
Browse files Browse the repository at this point in the history
…nterfaces from core (#2295)

* update sender and post

* udpate

* update

* update
  • Loading branch information
Karlie-777 authored Mar 9, 2024
1 parent 724d520 commit aba7c9d
Show file tree
Hide file tree
Showing 24 changed files with 966 additions and 807 deletions.
4 changes: 2 additions & 2 deletions AISKU/Tests/Unit/src/AISKUSize.Tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { Snippet } from "../../../src/Snippet";
import { utlRemoveSessionStorage } from "@microsoft/applicationinsights-common";

export class AISKUSizeCheck extends AITestClass {
private readonly MAX_RAW_SIZE = 138;
private readonly MAX_BUNDLE_SIZE = 138;
private readonly MAX_RAW_SIZE = 139;
private readonly MAX_BUNDLE_SIZE = 139;
private readonly MAX_RAW_DEFLATE_SIZE = 56;
private readonly MAX_BUNDLE_DEFLATE_SIZE = 56;
private readonly rawFilePath = "../dist/es5/applicationinsights-web.min.js";
Expand Down
2 changes: 1 addition & 1 deletion AISKU/src/AISku.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ export class AppInsightsSku implements IApplicationInsights {
if (_config.connectionString) {
const cs = parseConnectionString(_config.connectionString);
const ingest = cs.ingestionendpoint;
_config.endpointUrl = _config.userOverrideEndpointUrl ? _config.userOverrideEndpointUrl : ingest + DEFAULT_BREEZE_PATH; // add /v2/track
_config.endpointUrl = _config.userOverrideEndpointUrl ? _config.userOverrideEndpointUrl : ingest + DEFAULT_BREEZE_PATH; // add /v2/track
_config.instrumentationKey = cs.instrumentationkey || _config.instrumentationKey;
}
// userOverrideEndpointUrl have the highest priority
Expand Down
4 changes: 2 additions & 2 deletions AISKULight/Tests/Unit/src/AISKULightSize.Tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { AITestClass, Assert } from "@microsoft/ai-test-framework";
import * as pako from "pako";

export class AISKULightSizeCheck extends AITestClass {
private readonly MAX_RAW_SIZE = 85;
private readonly MAX_BUNDLE_SIZE = 85;
private readonly MAX_RAW_SIZE = 86;
private readonly MAX_BUNDLE_SIZE = 86;
private readonly MAX_RAW_DEFLATE_SIZE = 35;
private readonly MAX_BUNDLE_DEFLATE_SIZE = 35;
private readonly rawFilePath = "../dist/es5/applicationinsights-web-basic.min.js";
Expand Down
442 changes: 133 additions & 309 deletions channels/1ds-post-js/src/HttpManager.ts

Large diffs are not rendered by default.

43 changes: 26 additions & 17 deletions channels/1ds-post-js/src/PostChannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,25 +234,34 @@ export class PostChannel extends BaseTelemetryPlugin implements IChannelControls
};

_self.getOfflineSupport = () => {
let details = _httpManager.getOfflineRequestDetails();
return {
getUrl: () => {
return details.url
},
serialize: _serialize,
batch: _batch,
shouldProcess: (evt) => {
return !_disableTelemetry;
},
createPayload: (evt) => {
try {
let details = _httpManager && _httpManager.getOfflineRequestDetails();
if (details) {
return {
urlString: details.url,
headers: details.hdrs,
data: evt
} as IPayloadData;
}
} as IInternalOfflineSupport;
getUrl: () => {
return details.url
},
serialize: _serialize,
batch: _batch,
shouldProcess: (evt) => {
return !_disableTelemetry;
},
createPayload: (evt) => {
return {
urlString: details.url,
headers: details.hdrs,
data: evt
} as IPayloadData;
}
} as IInternalOfflineSupport;

}

} catch (e) {
// eslint-disable-next-line no-empty
}
return null;

};

_self._doTeardown = (unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1912,6 +1912,7 @@ export class SenderTests extends AITestClass {
let fetchstub = this.sandbox.stub((window as any), "fetch");
let fakeXMLHttpRequest = (window as any).XMLHttpRequest;
let sessionStorage = window.sessionStorage;
let sessionSpy = this.sandbox.spy(sessionStorage,"setItem");
QUnit.assert.ok(sessionStorage, "sessionStorage API is supported");
sessionStorage.clear();

Expand Down Expand Up @@ -1974,8 +1975,23 @@ export class SenderTests extends AITestClass {
let bufferItems = JSON.parse(sessionStorage.getItem("AI_buffer") as any);
QUnit.assert.equal(bufferItems.length, 0, "sender buffer should be clear payload");
let sentItems = JSON.parse(sessionStorage.getItem("AI_sentBuffer") as any);
QUnit.assert.equal(1, sentItems.length, "sent buffer should have one payload");

QUnit.assert.equal(0, sentItems.length, "sent buffer should have one payload test1");

let setItemCalled = 0;
let args = sessionSpy.args;
let itemCount = 0;
args.forEach((arg) => {
if (arg && arg[0] === "AI_sentBuffer") {
let data = JSON.parse(arg[1]);
let cnt = data.length;
if(data && cnt) {
setItemCalled ++;
itemCount += cnt;
}
}
});
QUnit.assert.equal(1, setItemCalled, "sent buffer session should have be called once");
QUnit.assert.equal(1, itemCount, "sent buffer session should have be called once with one item");

(window as any).XMLHttpRequest = fakeXMLHttpRequest;
sessionStorage.clear();
Expand Down Expand Up @@ -2074,6 +2090,7 @@ export class SenderTests extends AITestClass {
let fetchstub = this.sandbox.stub((window as any), "fetch");
let fakeXMLHttpRequest = (window as any).XMLHttpRequest;
let sessionStorage = window.sessionStorage;
let sessionSpy = this.sandbox.spy(sessionStorage,"setItem");
QUnit.assert.ok(sessionStorage, "sessionStorage API is supported");
sessionStorage.clear();

Expand Down Expand Up @@ -2151,7 +2168,23 @@ export class SenderTests extends AITestClass {
let bufferItems = JSON.parse(sessionStorage.getItem("AI_buffer") as any);
QUnit.assert.equal(bufferItems.length, 0, "sender buffer should be clear payload");
let sentItems = JSON.parse(sessionStorage.getItem("AI_sentBuffer") as any);
QUnit.assert.equal(2, sentItems.length, "sent buffer should have two payload");
QUnit.assert.equal(0, sentItems.length, "sent buffer should have no payload left");

let setItemCalled = 0;
let itemCount = 0;
let args = sessionSpy.args;
args.forEach((arg) => {
if (arg && arg[0] === "AI_sentBuffer") {
let data = JSON.parse(arg[1]);
let cnt = data.length;
if(data && cnt) {
setItemCalled ++;
itemCount += cnt;
}
}
});
QUnit.assert.equal(1, setItemCalled, "sent buffer session should have be called once");
QUnit.assert.equal(2, itemCount, "sent buffer session should have be called once with two item");

(window as any).XMLHttpRequest = fakeXMLHttpRequest;
sessionStorage.clear();
Expand Down
52 changes: 32 additions & 20 deletions channels/applicationinsights-channel-js/src/Sender.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
import dynamicProto from "@microsoft/dynamicproto-js";
import {
BreezeChannelIdentifier, DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, Event, Exception, IConfig, IEnvelope, IOfflineListener, ISample,
IStorageBuffer, Metric, PageView, PageViewPerformance, ProcessLegacy, RemoteDependencyData, RequestHeaders, SampleRate,
SenderPostManager, Trace, _ISendPostMgrConfig, _ISenderOnComplete, createOfflineListener, eRequestHeaders, formatErrorMessageXdr,
formatErrorMessageXhr, isInternalApplicationInsightsEndpoint, parseResponse, prependTransports, utlCanUseSessionStorage,
utlSetStoragePrefix
IStorageBuffer, Metric, PageView, PageViewPerformance, ProcessLegacy, RemoteDependencyData, RequestHeaders, SampleRate, Trace,
createOfflineListener, eRequestHeaders, isInternalApplicationInsightsEndpoint, utlCanUseSessionStorage, utlSetStoragePrefix
} from "@microsoft/applicationinsights-common";
import {
BaseTelemetryPlugin, IAppInsightsCore, IChannelControls, IConfigDefaults, IConfiguration, IDiagnosticLogger, IInternalOfflineSupport,
INotificationManager, IPayloadData, IPlugin, IProcessTelemetryContext, IProcessTelemetryUnloadContext, ITelemetryItem,
ITelemetryPluginChain, ITelemetryUnloadState, IXHROverride, OnCompleteCallback, SendPOSTFunction, SendRequestReason, TransportType,
_eInternalMessageId, _throwInternal, _warnToConsole, arrForEach, cfgDfBoolean, cfgDfValidate, createProcessTelemetryContext,
createUniqueNamespace, dateNow, dumpObj, eLoggingSeverity, getExceptionName, getIEVersion, isArray, isBeaconsSupported, isFetchSupported,
isNullOrUndefined, mergeEvtNamespace, objExtend, onConfigChange, runTargetUnload
BaseTelemetryPlugin, IAppInsightsCore, IBackendResponse, IChannelControls, IConfigDefaults, IConfiguration, IDiagnosticLogger,
IInternalOfflineSupport, INotificationManager, IPayloadData, IPlugin, IProcessTelemetryContext, IProcessTelemetryUnloadContext,
ITelemetryItem, ITelemetryPluginChain, ITelemetryUnloadState, IXDomainRequest, IXHROverride, OnCompleteCallback, SendPOSTFunction,
SendRequestReason, SenderPostManager, TransportType, _ISendPostMgrConfig, _ISenderOnComplete, _eInternalMessageId, _throwInternal,
_warnToConsole, arrForEach, cfgDfBoolean, cfgDfValidate, createProcessTelemetryContext, createUniqueNamespace, dateNow, dumpObj,
eLoggingSeverity, formatErrorMessageXdr, formatErrorMessageXhr, getExceptionName, getIEVersion, isArray, isBeaconsSupported,
isFetchSupported, isNullOrUndefined, mergeEvtNamespace, objExtend, onConfigChange, parseResponse, prependTransports, runTargetUnload
} from "@microsoft/applicationinsights-core-js";
import { IPromise } from "@nevware21/ts-async";
import { ITimerHandler, isTruthy, objDeepFreeze, objDefine, scheduleTimeout } from "@nevware21/ts-utils";
import {
DependencyEnvelopeCreator, EventEnvelopeCreator, ExceptionEnvelopeCreator, MetricEnvelopeCreator, PageViewEnvelopeCreator,
PageViewPerformanceEnvelopeCreator, TraceEnvelopeCreator
} from "./EnvelopeCreator";
import { IBackendResponse, ISenderConfig, XDomainRequest as IXDomainRequest } from "./Interfaces";
import { ISenderConfig } from "./Interfaces";
import { ArraySendBuffer, ISendBuffer, SessionStorageSendBuffer } from "./SendBuffer";
import { Serializer } from "./Serializer";
import { Sample } from "./TelemetryProcessors/Sample";
Expand Down Expand Up @@ -370,7 +369,7 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControls {
// Beacon would be filtered out if user has set disableBeaconApi to true at _getSenderInterface
let theTransports: TransportType[] = prependTransports([TransportType.Beacon, TransportType.Xhr, TransportType.Fetch], senderConfig.transports);

httpInterface = _sendPostMgr && _sendPostMgr.getXhrInst(theTransports, false);
httpInterface = _sendPostMgr && _sendPostMgr.getSenderInst(theTransports, false);

let xhrInterface = _sendPostMgr && _sendPostMgr.getFallbackInst();
_xhrSend = (payload: string[], isAsync: boolean) => {
Expand All @@ -397,7 +396,7 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControls {
syncTransports = syncTransports.filter(transport => transport !== TransportType.Fetch);
}

syncInterface = _sendPostMgr && _sendPostMgr.getXhrInst(syncTransports, true);
syncInterface = _sendPostMgr && _sendPostMgr.getSenderInst(syncTransports, true);
syncInterface = _alwaysUseCustomSend? customInterface : (syncInterface || customInterface);

if ((_alwaysUseCustomSend || senderConfig.unloadTransports || !_syncUnloadSender) && syncInterface) {
Expand Down Expand Up @@ -809,10 +808,7 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControls {
}

function _createPayload(data: string |Uint8Array) {
let headers = _headers;
if (isInternalApplicationInsightsEndpoint(_endpointUrl)) {
headers[RequestHeaders[eRequestHeaders.sdkContextHeader]] = RequestHeaders[eRequestHeaders.sdkContextHeaderAppIdRequest];
}
let headers = _getHeaders();
return {
urlString: _endpointUrl,
data: data,
Expand Down Expand Up @@ -856,10 +852,11 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControls {
function _getPayload(payload: string[]): IInternalPayloadData {
if (isArray(payload) && payload.length > 0) {
let batch = _self._buffer.batchPayloads(payload);
let headers = _getHeaders();
let payloadData: IInternalPayloadData = {
data: batch,
urlString: _endpointUrl,
headers: _headers,
headers: headers,
disableXhrSync: _disableXhr,
disableFetchKeepAlive: !_fetchKeepAlive,
oriPayload: payload
Expand All @@ -870,6 +867,21 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControls {
return null;
}

function _getHeaders() {
try {
let headers = _headers || {};
if (isInternalApplicationInsightsEndpoint(_endpointUrl)) {
headers[RequestHeaders[eRequestHeaders.sdkContextHeader]] = RequestHeaders[eRequestHeaders.sdkContextHeaderAppIdRequest];
}
return headers;

} catch(e) {
// eslint-disable-next-line no-empty

}
return null;
}

function _checkMaxSize(incomingPayload?: string): boolean {
let incomingSize = incomingPayload? incomingPayload.length : 0;
if ((_self._buffer.size() + incomingSize) > _maxBatchSizeInBytes) {
Expand Down Expand Up @@ -968,7 +980,7 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControls {
} else {

// Fallback to the previous beacon Sender (which causes a CORB warning on chrome now)
let beaconInst = _sendPostMgr && _sendPostMgr.getXhrInst([TransportType.Beacon], true);
let beaconInst = _sendPostMgr && _sendPostMgr.getSenderInst([TransportType.Beacon], true);
return _doSend(beaconInst, payload, isAsync);
}
}
Expand Down Expand Up @@ -1024,7 +1036,7 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControls {
transport = TransportType.Xhr;
_throwInternal(_self.diagLog(), eLoggingSeverity.WARNING, _eInternalMessageId.TransmissionFailed, ". " + "Failed to send telemetry with Beacon API, retried with xhrSender.");
}
let inst = _sendPostMgr && _sendPostMgr.getXhrInst([transport], true);
let inst = _sendPostMgr && _sendPostMgr.getSenderInst([transport], true);
return _doSend(inst, payload, isAsync);
}
return null;
Expand Down
2 changes: 1 addition & 1 deletion channels/offline-channel-js/src/OfflineChannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -557,7 +557,7 @@ export class OfflineChannel extends BaseTelemetryPlugin implements IChannelContr
_primaryChannelId = id;
if (isFunction(channel.getOfflineSupport)) {
_offineSupport = channel.getOfflineSupport();
onlineUrl = isFunction(_offineSupport.getUrl) && _offineSupport.getUrl();
onlineUrl = isFunction(_offineSupport && _offineSupport.getUrl) && _offineSupport.getUrl();
}
return;
}
Expand Down
12 changes: 5 additions & 7 deletions channels/offline-channel-js/src/Sender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@
// Licensed under the MIT License.

import dynamicProto from "@microsoft/dynamicproto-js";
import {
BreezeChannelIdentifier, IConfig, IXDomainRequest, SenderPostManager, _ISendPostMgrConfig, _ISenderOnComplete, formatErrorMessageXdr,
getResponseText, parseResponse, prependTransports, utlSetStoragePrefix
} from "@microsoft/applicationinsights-common";
import { BreezeChannelIdentifier, IConfig, utlSetStoragePrefix } from "@microsoft/applicationinsights-common";
import {
IAppInsightsCore, IConfiguration, IDiagnosticLogger, IProcessTelemetryContext, IProcessTelemetryUnloadContext, ITelemetryUnloadState,
IUnloadHookContainer, IXHROverride, OnCompleteCallback, SendRequestReason, TransportType, _eInternalMessageId, _throwInternal,
createProcessTelemetryContext, eLoggingSeverity, onConfigChange
IUnloadHookContainer, IXDomainRequest, IXHROverride, OnCompleteCallback, SendRequestReason, SenderPostManager, TransportType,
_ISendPostMgrConfig, _ISenderOnComplete, _eInternalMessageId, _throwInternal, createProcessTelemetryContext, eLoggingSeverity,
formatErrorMessageXdr, getResponseText, onConfigChange, parseResponse, prependTransports
} from "@microsoft/applicationinsights-core-js";
import { IPromise } from "@nevware21/ts-async";
import { isFunction } from "@nevware21/ts-utils";
Expand Down Expand Up @@ -115,7 +113,7 @@ export class Sender {
let customTransPorts = offlineSenderCfg.transports || senderConfig.transports || [];

let theTransports: TransportType[] = prependTransports([TransportType.Xhr, TransportType.Fetch, TransportType.Beacon], customTransPorts);
httpInterface = _sendPostMgr.getXhrInst(theTransports, false);
httpInterface = _sendPostMgr.getSenderInst(theTransports, false);
let xhrInterface = _sendPostMgr.getFallbackInst();
httpInterface = _alwaysUseCustomSend? customInterface : (httpInterface || customInterface || xhrInterface);
_httpInterface = httpInterface || xhrInterface;
Expand Down
Loading

0 comments on commit aba7c9d

Please sign in to comment.