Skip to content

Commit

Permalink
Add a simple interface to enable custom buffer storage solutions micr…
Browse files Browse the repository at this point in the history
…osoft#1419

This can be used like:

```
const appInsights = new ApplicationInsights({
  config: {
    enableSessionStorageBuffer: true,
    bufferOverride: {
      getItem: (logger, key) => localStorage.getItem(key),
      setItem: (logger, key, value) => localStorage.setItem(key, value),
    }
  }
});
```
  • Loading branch information
peitschie committed Apr 7, 2023
1 parent 4361915 commit d92af76
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 5 deletions.
7 changes: 7 additions & 0 deletions channels/applicationinsights-channel-js/src/Interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { IStorageBuffer } from "@microsoft/applicationinsights-common";

export interface ISenderConfig {
/**
* The url to which payloads will be sent
Expand Down Expand Up @@ -29,6 +31,11 @@ export interface ISenderConfig {
*/
enableSessionStorageBuffer: () => boolean;

/**
* Specify the storage buffer type implementation.
*/
bufferOverride: () => IStorageBuffer | false;

/**
* Is retry handler disabled.
* If enabled, retry on 206 (partial success), 408 (timeout), 429 (too many requests), 500 (internal server error) and 503 (service unavailable).
Expand Down
7 changes: 4 additions & 3 deletions channels/applicationinsights-channel-js/src/SendBuffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ export class SessionStorageSendBuffer extends BaseSendBuffer implements ISendBuf
constructor(logger: IDiagnosticLogger, config: ISenderConfig) {
super(logger, config);
let _bufferFullMessageSent = false;
const { getItem, setItem } = config.bufferOverride() || { getItem: utlGetSessionStorage, setItem: utlSetSessionStorage };

dynamicProto(SessionStorageSendBuffer, this, (_self, _base) => {
const bufferItems = _getBuffer(SessionStorageSendBuffer.BUFFER_KEY);
Expand Down Expand Up @@ -287,7 +288,7 @@ export class SessionStorageSendBuffer extends BaseSendBuffer implements ISendBuf
let prefixedKey = key;
try {
prefixedKey = config.namePrefix && config.namePrefix() ? config.namePrefix() + "_" + prefixedKey : prefixedKey;
const bufferJson = utlGetSessionStorage(logger, prefixedKey);
const bufferJson = getItem(logger, prefixedKey);
if (bufferJson) {
let buffer: string[] = getJSON().parse(bufferJson);
if (isString(buffer)) {
Expand All @@ -314,11 +315,11 @@ export class SessionStorageSendBuffer extends BaseSendBuffer implements ISendBuf
try {
prefixedKey = config.namePrefix && config.namePrefix() ? config.namePrefix() + "_" + prefixedKey : prefixedKey;
const bufferJson = JSON.stringify(buffer);
utlSetSessionStorage(logger, prefixedKey, bufferJson);
setItem(logger, prefixedKey, bufferJson);
} catch (e) {
// if there was an error, clear the buffer
// telemetry is stored in the _buffer array so we won't loose any items
utlSetSessionStorage(logger, prefixedKey, JSON.stringify([]));
setItem(logger, prefixedKey, JSON.stringify([]));

_throwInternal(logger, eLoggingSeverity.WARNING,
_eInternalMessageId.FailedToSetStorageBuffer,
Expand Down
8 changes: 6 additions & 2 deletions channels/applicationinsights-channel-js/src/Sender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ function _getDefaultAppInsightsChannelConfig(): ISenderConfig {
maxBatchSizeInBytes: () => 102400, // 100kb
disableTelemetry: () => false,
enableSessionStorageBuffer: () => true,
bufferOverride: () => false,
isRetryDisabled: () => false,
isBeaconApiDisabled: () => true,
disableXhr: () => false,
Expand Down Expand Up @@ -231,8 +232,11 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
}
});

_self._buffer = (_self._senderConfig.enableSessionStorageBuffer() && utlCanUseSessionStorage())
? new SessionStorageSendBuffer(diagLog, _self._senderConfig) : new ArraySendBuffer(diagLog, _self._senderConfig);
const useSessionStorage = _self._senderConfig.enableSessionStorageBuffer() &&
(_self._senderConfig.bufferOverride() || utlCanUseSessionStorage())
_self._buffer = useSessionStorage
? new SessionStorageSendBuffer(diagLog, _self._senderConfig)
: new ArraySendBuffer(diagLog, _self._senderConfig);
_self._sample = new Sample(_self._senderConfig.samplingPercentage(), diagLog);

if(!_validateInstrumentationKey(config)) {
Expand Down
6 changes: 6 additions & 0 deletions shared/AppInsightsCommon/src/Interfaces/IConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { IConfiguration, ICustomProperties, isNullOrUndefined } from "@microsoft/applicationinsights-core-js";
import { DistributedTracingModes } from "../Enums";
import { IRequestContext } from "./IRequestContext";
import { IStorageBuffer } from "./IStorageBuffer";

/**
* Configuration settings for how telemetry is sent
Expand Down Expand Up @@ -170,6 +171,11 @@ export interface IConfig {
*/
enableSessionStorageBuffer?: boolean;

/**
* If specified, overrides the storage & retrieval mechanism that is used to manage unsent telemetry.
*/
bufferOverride?: IStorageBuffer;

/**
* @deprecated Use either disableCookiesUsage or specify a cookieCfg with the enabled value set.
* If true, the SDK will not store or read any data from cookies. Default is false. As this field is being deprecated, when both
Expand Down
13 changes: 13 additions & 0 deletions shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { IDiagnosticLogger } from "@microsoft/applicationinsights-core-js";

export interface IStorageBuffer {
/**
* Retrieves the stored value for a given key
*/
getItem(logger: IDiagnosticLogger, name: string): string;

/**
* Sets the stored value for a given key
*/
setItem(logger: IDiagnosticLogger, name: string, data: string): boolean;
}
1 change: 1 addition & 0 deletions shared/AppInsightsCommon/src/applicationinsights-common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export { PageViewPerformance } from "./Telemetry/PageViewPerformance";
export { Data } from "./Telemetry/Common/Data";
export { eSeverityLevel, SeverityLevel } from "./Interfaces/Contracts/SeverityLevel";
export { IConfig, ConfigurationManager } from "./Interfaces/IConfig";
export { IStorageBuffer } from "./Interfaces/IStorageBuffer";
export { IChannelControlsAI } from "./Interfaces/IChannelControlsAI";
export { IContextTagKeys, ContextTagKeys } from "./Interfaces/Contracts/ContextTagKeys";
export {
Expand Down

0 comments on commit d92af76

Please sign in to comment.