@amplitude/analytics-core 2.24.1 → 2.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/diagnostics/diagnostics-client.d.ts +156 -0
- package/lib/cjs/diagnostics/diagnostics-client.d.ts.map +1 -0
- package/lib/cjs/diagnostics/diagnostics-client.js +305 -0
- package/lib/cjs/diagnostics/diagnostics-client.js.map +1 -0
- package/lib/cjs/diagnostics/diagnostics-storage.d.ts +123 -0
- package/lib/cjs/diagnostics/diagnostics-storage.d.ts.map +1 -0
- package/lib/cjs/diagnostics/diagnostics-storage.js +492 -0
- package/lib/cjs/diagnostics/diagnostics-storage.js.map +1 -0
- package/lib/cjs/index.d.ts.map +1 -1
- package/lib/cjs/index.js +1 -0
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/types/config/core-config.d.ts +5 -0
- package/lib/cjs/types/config/core-config.d.ts.map +1 -1
- package/lib/cjs/types/config/core-config.js.map +1 -1
- package/lib/esm/diagnostics/diagnostics-client.d.ts +156 -0
- package/lib/esm/diagnostics/diagnostics-client.d.ts.map +1 -0
- package/lib/esm/diagnostics/diagnostics-client.js +302 -0
- package/lib/esm/diagnostics/diagnostics-client.js.map +1 -0
- package/lib/esm/diagnostics/diagnostics-storage.d.ts +123 -0
- package/lib/esm/diagnostics/diagnostics-storage.d.ts.map +1 -0
- package/lib/esm/diagnostics/diagnostics-storage.js +489 -0
- package/lib/esm/diagnostics/diagnostics-storage.js.map +1 -0
- package/lib/esm/index.d.ts.map +1 -1
- package/lib/esm/index.js +1 -0
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/types/config/core-config.d.ts +5 -0
- package/lib/esm/types/config/core-config.d.ts.map +1 -1
- package/lib/esm/types/config/core-config.js.map +1 -1
- package/package.json +2 -2
|
@@ -7,6 +7,7 @@ import { ServerZoneType } from '../server-zone';
|
|
|
7
7
|
import { Transport } from '../transport';
|
|
8
8
|
import { Storage } from '../storage';
|
|
9
9
|
import { Event } from '../event/event';
|
|
10
|
+
import { IIdentify } from '../../identify';
|
|
10
11
|
export interface IConfig {
|
|
11
12
|
/**
|
|
12
13
|
* Your Amplitude Project API key.
|
|
@@ -85,6 +86,10 @@ export interface IConfig {
|
|
|
85
86
|
* Metrics of the SDK.
|
|
86
87
|
*/
|
|
87
88
|
requestMetadata?: IRequestMetadata;
|
|
89
|
+
/**
|
|
90
|
+
* Invokes identify on this Identify object prior to initializing the SDK.
|
|
91
|
+
*/
|
|
92
|
+
identify?: IIdentify;
|
|
88
93
|
}
|
|
89
94
|
export interface IRequestMetadata {
|
|
90
95
|
sdk: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core-config.d.ts","sourceRoot":"","sources":["../../../../src/types/config/core-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"core-config.d.ts","sourceRoot":"","sources":["../../../../src/types/config/core-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AACr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,EAAE,SAAS,CAAC;CACtB;AAED,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE;QACH,OAAO,EAAE;YACP,SAAS,EAAE,iBAAiB,CAAC;SAC9B,CAAC;KACH,CAAC;IAEF,eAAe,CAAC,CAAC,SAAS,YAAY,EAAE,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;CACpF;AAED,MAAM,WAAW,iBAAiB;IAChC,4BAA4B,CAAC,EAAE,MAAM,CAAC;IACtC,oCAAoC,CAAC,EAAE,MAAM,CAAC;IAC9C,iCAAiC,CAAC,EAAE,MAAM,CAAC;CAC5C;AAED,MAAM,MAAM,YAAY,GAAG,MAAM,iBAAiB,CAAC;AAEnD,MAAM,WAAW,aAAc,SAAQ,OAAO,CAAC,OAAO,CAAC;IACrD,MAAM,EAAE,MAAM,CAAC;IACf,iBAAiB,EAAE,SAAS,CAAC;CAC9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core-config.js","sourceRoot":"","sources":["../../../../src/types/config/core-config.ts"],"names":[],"mappings":"","sourcesContent":["import { LogLevel } from '../loglevel';\nimport { ILogger } from '../../logger';\nimport { OfflineDisabled } from '../offline';\nimport { Plan } from '../event/plan';\nimport { IngestionMetadata } from '../event/ingestion-metadata';\nimport { ServerZoneType } from '../server-zone';\nimport { Transport } from '../transport';\nimport { Storage } from '../storage';\nimport { Event } from '../event/event';\n\nexport interface IConfig {\n /**\n * Your Amplitude Project API key.\n */\n apiKey: string;\n /**\n * The interval of uploading events to Amplitude in milliseconds.\n */\n flushIntervalMillis: number;\n /**\n * The maximum number of retries for failed upload attempts. This is only applicable to retryable errors.\n */\n flushMaxRetries: number;\n /**\n * The maximum number of events that are batched in a single upload attempt.\n */\n flushQueueSize: number;\n /**\n * The instance name. For tracking events to multiple Amplitude projects in your application.\n */\n instanceName?: string;\n /**\n * Level of logs to be printed in the developer console.\n * Valid values are `LogLevel.None`, `LogLevel.Error`, `LogLevel.Warn`, `LogLevel.Verbose`, `LogLevel.Debug`\n */\n logLevel: LogLevel;\n /**\n * A custom Logger class to emit log messages to desired destination.\n */\n loggerProvider: ILogger;\n /**\n * The minimum length for the value of userId and deviceId properties.\n */\n minIdLength?: number;\n /**\n * Whether the SDK is connected to network.\n */\n offline?: boolean | typeof OfflineDisabled;\n /**\n * The flag to opt this device out of Amplitude tracking.\n * If this flag is set, no additional information will be stored for the user.\n */\n optOut: boolean;\n /**\n * Tracking plan properties.\n * Amplitude internal use.\n */\n plan?: Plan;\n /**\n * Ingestion metadata.\n * Amplitude internal use.\n */\n ingestionMetadata?: IngestionMetadata;\n /**\n * The URL where events are upload to.\n */\n serverUrl?: string;\n /**\n * The Amplitude server zone.\n * Set this to EU for Amplitude projects created in EU data center.\n */\n serverZone?: ServerZoneType;\n /**\n * The storage provider to persist unsent events.\n */\n storageProvider?: Storage<Event[]>;\n /**\n * A customer Transport Class for sending data to a server.\n */\n transportProvider: Transport;\n /**\n * The flag of whether to upload events to Batch API instead of the default HTTP V2 API.\n */\n useBatch: boolean;\n /**\n * Metrics of the SDK.\n */\n requestMetadata?: IRequestMetadata;\n}\n\nexport interface IRequestMetadata {\n sdk: {\n metrics: {\n histogram: IHistogramOptions;\n };\n };\n\n recordHistogram<T extends HistogramKey>(key: T, value: IHistogramOptions[T]): void;\n}\n\nexport interface IHistogramOptions {\n remote_config_fetch_time_IDB?: number;\n remote_config_fetch_time_API_success?: number;\n remote_config_fetch_time_API_fail?: number;\n}\n\nexport type HistogramKey = keyof IHistogramOptions;\n\nexport interface ConfigOptions extends Partial<IConfig> {\n apiKey: string;\n transportProvider: Transport;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"core-config.js","sourceRoot":"","sources":["../../../../src/types/config/core-config.ts"],"names":[],"mappings":"","sourcesContent":["import { LogLevel } from '../loglevel';\nimport { ILogger } from '../../logger';\nimport { OfflineDisabled } from '../offline';\nimport { Plan } from '../event/plan';\nimport { IngestionMetadata } from '../event/ingestion-metadata';\nimport { ServerZoneType } from '../server-zone';\nimport { Transport } from '../transport';\nimport { Storage } from '../storage';\nimport { Event } from '../event/event';\nimport { IIdentify } from '../../identify';\n\nexport interface IConfig {\n /**\n * Your Amplitude Project API key.\n */\n apiKey: string;\n /**\n * The interval of uploading events to Amplitude in milliseconds.\n */\n flushIntervalMillis: number;\n /**\n * The maximum number of retries for failed upload attempts. This is only applicable to retryable errors.\n */\n flushMaxRetries: number;\n /**\n * The maximum number of events that are batched in a single upload attempt.\n */\n flushQueueSize: number;\n /**\n * The instance name. For tracking events to multiple Amplitude projects in your application.\n */\n instanceName?: string;\n /**\n * Level of logs to be printed in the developer console.\n * Valid values are `LogLevel.None`, `LogLevel.Error`, `LogLevel.Warn`, `LogLevel.Verbose`, `LogLevel.Debug`\n */\n logLevel: LogLevel;\n /**\n * A custom Logger class to emit log messages to desired destination.\n */\n loggerProvider: ILogger;\n /**\n * The minimum length for the value of userId and deviceId properties.\n */\n minIdLength?: number;\n /**\n * Whether the SDK is connected to network.\n */\n offline?: boolean | typeof OfflineDisabled;\n /**\n * The flag to opt this device out of Amplitude tracking.\n * If this flag is set, no additional information will be stored for the user.\n */\n optOut: boolean;\n /**\n * Tracking plan properties.\n * Amplitude internal use.\n */\n plan?: Plan;\n /**\n * Ingestion metadata.\n * Amplitude internal use.\n */\n ingestionMetadata?: IngestionMetadata;\n /**\n * The URL where events are upload to.\n */\n serverUrl?: string;\n /**\n * The Amplitude server zone.\n * Set this to EU for Amplitude projects created in EU data center.\n */\n serverZone?: ServerZoneType;\n /**\n * The storage provider to persist unsent events.\n */\n storageProvider?: Storage<Event[]>;\n /**\n * A customer Transport Class for sending data to a server.\n */\n transportProvider: Transport;\n /**\n * The flag of whether to upload events to Batch API instead of the default HTTP V2 API.\n */\n useBatch: boolean;\n /**\n * Metrics of the SDK.\n */\n requestMetadata?: IRequestMetadata;\n /**\n * Invokes identify on this Identify object prior to initializing the SDK.\n */\n identify?: IIdentify;\n}\n\nexport interface IRequestMetadata {\n sdk: {\n metrics: {\n histogram: IHistogramOptions;\n };\n };\n\n recordHistogram<T extends HistogramKey>(key: T, value: IHistogramOptions[T]): void;\n}\n\nexport interface IHistogramOptions {\n remote_config_fetch_time_IDB?: number;\n remote_config_fetch_time_API_success?: number;\n remote_config_fetch_time_API_fail?: number;\n}\n\nexport type HistogramKey = keyof IHistogramOptions;\n\nexport interface ConfigOptions extends Partial<IConfig> {\n apiKey: string;\n transportProvider: Transport;\n}\n"]}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { ILogger } from '../logger';
|
|
2
|
+
import { IDiagnosticsStorage } from './diagnostics-storage';
|
|
3
|
+
import { ServerZoneType } from '../types/server-zone';
|
|
4
|
+
export declare const SAVE_INTERVAL_MS = 1000;
|
|
5
|
+
export declare const FLUSH_INTERVAL_MS: number;
|
|
6
|
+
export declare const DIAGNOSTICS_US_SERVER_URL = "https://diagnostics.prod.us-west-2.amplitude.com/v1/capture";
|
|
7
|
+
export declare const DIAGNOSTICS_EU_SERVER_URL = "https://diagnostics.prod.eu-central-1.amplitude.com/v1/capture";
|
|
8
|
+
export declare const MAX_MEMORY_STORAGE_COUNT = 10000;
|
|
9
|
+
export declare const MAX_MEMORY_STORAGE_EVENTS_COUNT = 10;
|
|
10
|
+
/**
|
|
11
|
+
* Key-value pairs for environment/context information
|
|
12
|
+
*/
|
|
13
|
+
type DiagnosticsTags = Record<string, string>;
|
|
14
|
+
/**
|
|
15
|
+
* Numeric counters that can be incremented
|
|
16
|
+
*/
|
|
17
|
+
type DiagnosticsCounters = Record<string, number>;
|
|
18
|
+
/**
|
|
19
|
+
* Properties for diagnostic events
|
|
20
|
+
*/
|
|
21
|
+
type EventProperties = Record<string, any>;
|
|
22
|
+
/**
|
|
23
|
+
* Individual diagnostic event
|
|
24
|
+
*/
|
|
25
|
+
interface DiagnosticsEvent {
|
|
26
|
+
readonly event_name: string;
|
|
27
|
+
readonly time: number;
|
|
28
|
+
readonly event_properties: EventProperties;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Computed histogram statistics for final payload
|
|
32
|
+
*/
|
|
33
|
+
interface HistogramResult {
|
|
34
|
+
readonly count: number;
|
|
35
|
+
readonly min: number;
|
|
36
|
+
readonly max: number;
|
|
37
|
+
readonly avg: number;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Internal histogram statistics with sum for efficient incremental updates
|
|
41
|
+
*/
|
|
42
|
+
export interface HistogramStats {
|
|
43
|
+
count: number;
|
|
44
|
+
min: number;
|
|
45
|
+
max: number;
|
|
46
|
+
sum: number;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Collection of histogram results keyed by histogram name
|
|
50
|
+
*/
|
|
51
|
+
type DiagnosticsHistograms = Record<string, HistogramResult>;
|
|
52
|
+
/**
|
|
53
|
+
* Collection of histogram stats keyed by histogram name (internal use for memory + persistence storage)
|
|
54
|
+
*/
|
|
55
|
+
type DiagnosticsHistogramStats = Record<string, HistogramStats>;
|
|
56
|
+
/**
|
|
57
|
+
* Complete diagnostics payload sent to backend
|
|
58
|
+
*/
|
|
59
|
+
interface FlushPayload {
|
|
60
|
+
readonly tags: DiagnosticsTags;
|
|
61
|
+
readonly histogram: DiagnosticsHistograms;
|
|
62
|
+
readonly counters: DiagnosticsCounters;
|
|
63
|
+
readonly events: readonly DiagnosticsEvent[];
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Amplitude Diagnostics Client
|
|
67
|
+
*
|
|
68
|
+
* A client for collecting and managing diagnostics data including tags, counters,
|
|
69
|
+
* histograms, and events. Data is stored persistently using IndexedDB to survive browser restarts and offline scenarios.
|
|
70
|
+
*
|
|
71
|
+
* Key Features:
|
|
72
|
+
* - IndexedDB storage
|
|
73
|
+
* - Time-based persistent storage flush interval (5 minutes since last flush)
|
|
74
|
+
* - 1 second time-based memory storage flush to persistent storage
|
|
75
|
+
* - Histogram statistics calculation (min, max, avg)
|
|
76
|
+
*/
|
|
77
|
+
export interface IDiagnosticsClient {
|
|
78
|
+
/**
|
|
79
|
+
* Set or update a tag
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* ```typescript
|
|
83
|
+
* // Set environment tags
|
|
84
|
+
* diagnostics.setTag('library', 'amplitude-typescript/2.0.0');
|
|
85
|
+
* diagnostics.setTag('user_agent', navigator.userAgent);
|
|
86
|
+
* ```
|
|
87
|
+
*/
|
|
88
|
+
setTag(name: string, value: string): void;
|
|
89
|
+
/**
|
|
90
|
+
* Increment a counter. If doesn't exist, create a counter and set value to 1
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```typescript
|
|
94
|
+
* // Track counters
|
|
95
|
+
* diagnostics.increment('analytics.fileNotFound');
|
|
96
|
+
* diagnostics.increment('network.retry', 3);
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
increment(name: string, size?: number): void;
|
|
100
|
+
/**
|
|
101
|
+
* Record a histogram value
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* ```typescript
|
|
105
|
+
* // Record performance metrics
|
|
106
|
+
* diagnostics.recordHistogram('sr.time', 5.2);
|
|
107
|
+
* diagnostics.recordHistogram('network.latency', 150);
|
|
108
|
+
* ```
|
|
109
|
+
*/
|
|
110
|
+
recordHistogram(name: string, value: number): void;
|
|
111
|
+
/**
|
|
112
|
+
* Record an event
|
|
113
|
+
*
|
|
114
|
+
* @example
|
|
115
|
+
* ```typescript
|
|
116
|
+
* // Record diagnostic events
|
|
117
|
+
* diagnostics.recordEvent('error', {
|
|
118
|
+
* stack_trace: '...',
|
|
119
|
+
* });
|
|
120
|
+
* ```
|
|
121
|
+
*/
|
|
122
|
+
recordEvent(name: string, properties: EventProperties): void;
|
|
123
|
+
_flush(): void;
|
|
124
|
+
}
|
|
125
|
+
export declare class DiagnosticsClient implements IDiagnosticsClient {
|
|
126
|
+
storage?: IDiagnosticsStorage;
|
|
127
|
+
logger: ILogger;
|
|
128
|
+
serverUrl: string;
|
|
129
|
+
apiKey: string;
|
|
130
|
+
inMemoryTags: DiagnosticsTags;
|
|
131
|
+
inMemoryCounters: DiagnosticsCounters;
|
|
132
|
+
inMemoryHistograms: DiagnosticsHistogramStats;
|
|
133
|
+
inMemoryEvents: DiagnosticsEvent[];
|
|
134
|
+
saveTimer: ReturnType<typeof setTimeout> | null;
|
|
135
|
+
flushTimer: ReturnType<typeof setTimeout> | null;
|
|
136
|
+
constructor(apiKey: string, logger: ILogger, serverZone?: ServerZoneType);
|
|
137
|
+
setTag(name: string, value: string): void;
|
|
138
|
+
increment(name: string, size?: number): void;
|
|
139
|
+
recordHistogram(name: string, value: number): void;
|
|
140
|
+
recordEvent(name: string, properties: EventProperties): void;
|
|
141
|
+
startTimersIfNeeded(): void;
|
|
142
|
+
saveAllDataToStorage(): Promise<void>;
|
|
143
|
+
_flush(): Promise<void>;
|
|
144
|
+
/**
|
|
145
|
+
* Send diagnostics data to the server
|
|
146
|
+
*/
|
|
147
|
+
fetch(payload: FlushPayload): Promise<void>;
|
|
148
|
+
/**
|
|
149
|
+
* Initialize flush interval logic.
|
|
150
|
+
* Check if 5 minutes has passed since last flush, if so flush immediately.
|
|
151
|
+
* Otherwise set a timer to flush when the interval is reached.
|
|
152
|
+
*/
|
|
153
|
+
initializeFlushInterval(): Promise<void>;
|
|
154
|
+
}
|
|
155
|
+
export {};
|
|
156
|
+
//# sourceMappingURL=diagnostics-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"diagnostics-client.d.ts","sourceRoot":"","sources":["../../../src/diagnostics/diagnostics-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAsB,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAChF,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAGtD,eAAO,MAAM,gBAAgB,OAAO,CAAC;AACrC,eAAO,MAA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AAM,EAAE,IAAI,SAAI;IAchC,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM;IA6B3C,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,eAAe;IAkBrD,mBAAmB;IA0Bb,oBAAoB;IAsBpB,MAAM;IAqEZ;;OAEG;IACG,KAAK,CAAC,OAAO,EAAE,YAAY;IA0BjC;;;;OAIG;IACG,uBAAuB;CA6B9B"}
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import { __assign, __awaiter, __generator, __read, __spreadArray } from "tslib";
|
|
2
|
+
import { DiagnosticsStorage } from './diagnostics-storage';
|
|
3
|
+
import { getGlobalScope } from '../global-scope';
|
|
4
|
+
export var SAVE_INTERVAL_MS = 1000; // 1 second
|
|
5
|
+
export var FLUSH_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
|
|
6
|
+
export var DIAGNOSTICS_US_SERVER_URL = 'https://diagnostics.prod.us-west-2.amplitude.com/v1/capture';
|
|
7
|
+
export var DIAGNOSTICS_EU_SERVER_URL = 'https://diagnostics.prod.eu-central-1.amplitude.com/v1/capture';
|
|
8
|
+
// In-memory storage limits
|
|
9
|
+
export var MAX_MEMORY_STORAGE_COUNT = 10000; // for tags, counters, histograms separately
|
|
10
|
+
export var MAX_MEMORY_STORAGE_EVENTS_COUNT = 10;
|
|
11
|
+
var DiagnosticsClient = /** @class */ (function () {
|
|
12
|
+
function DiagnosticsClient(apiKey, logger, serverZone) {
|
|
13
|
+
if (serverZone === void 0) { serverZone = 'US'; }
|
|
14
|
+
// In-memory storages
|
|
15
|
+
this.inMemoryTags = {};
|
|
16
|
+
this.inMemoryCounters = {};
|
|
17
|
+
this.inMemoryHistograms = {};
|
|
18
|
+
this.inMemoryEvents = [];
|
|
19
|
+
// Timer for 1-second persistence
|
|
20
|
+
this.saveTimer = null;
|
|
21
|
+
// Timer for flush interval
|
|
22
|
+
this.flushTimer = null;
|
|
23
|
+
this.apiKey = apiKey;
|
|
24
|
+
this.logger = logger;
|
|
25
|
+
this.serverUrl = serverZone === 'US' ? DIAGNOSTICS_US_SERVER_URL : DIAGNOSTICS_EU_SERVER_URL;
|
|
26
|
+
if (DiagnosticsStorage.isSupported()) {
|
|
27
|
+
this.storage = new DiagnosticsStorage(apiKey, logger);
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
this.logger.debug('DiagnosticsClient: IndexedDB is not supported');
|
|
31
|
+
}
|
|
32
|
+
void this.initializeFlushInterval();
|
|
33
|
+
}
|
|
34
|
+
DiagnosticsClient.prototype.setTag = function (name, value) {
|
|
35
|
+
if (!this.storage) {
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (Object.keys(this.inMemoryTags).length >= MAX_MEMORY_STORAGE_COUNT) {
|
|
39
|
+
this.logger.debug('DiagnosticsClient: Early return setTags as reaching memory limit');
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
this.inMemoryTags[name] = value;
|
|
43
|
+
this.startTimersIfNeeded();
|
|
44
|
+
};
|
|
45
|
+
DiagnosticsClient.prototype.increment = function (name, size) {
|
|
46
|
+
if (size === void 0) { size = 1; }
|
|
47
|
+
if (!this.storage) {
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (Object.keys(this.inMemoryCounters).length >= MAX_MEMORY_STORAGE_COUNT) {
|
|
51
|
+
this.logger.debug('DiagnosticsClient: Early return increment as reaching memory limit');
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
this.inMemoryCounters[name] = (this.inMemoryCounters[name] || 0) + size;
|
|
55
|
+
this.startTimersIfNeeded();
|
|
56
|
+
};
|
|
57
|
+
DiagnosticsClient.prototype.recordHistogram = function (name, value) {
|
|
58
|
+
if (!this.storage) {
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (Object.keys(this.inMemoryHistograms).length >= MAX_MEMORY_STORAGE_COUNT) {
|
|
62
|
+
this.logger.debug('DiagnosticsClient: Early return recordHistogram as reaching memory limit');
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
var existing = this.inMemoryHistograms[name];
|
|
66
|
+
if (existing) {
|
|
67
|
+
// Update existing stats incrementally
|
|
68
|
+
existing.count += 1;
|
|
69
|
+
existing.min = Math.min(existing.min, value);
|
|
70
|
+
existing.max = Math.max(existing.max, value);
|
|
71
|
+
existing.sum += value;
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
// Create new stats
|
|
75
|
+
this.inMemoryHistograms[name] = {
|
|
76
|
+
count: 1,
|
|
77
|
+
min: value,
|
|
78
|
+
max: value,
|
|
79
|
+
sum: value,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
this.startTimersIfNeeded();
|
|
83
|
+
};
|
|
84
|
+
DiagnosticsClient.prototype.recordEvent = function (name, properties) {
|
|
85
|
+
if (!this.storage) {
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (this.inMemoryEvents.length >= MAX_MEMORY_STORAGE_EVENTS_COUNT) {
|
|
89
|
+
this.logger.debug('DiagnosticsClient: Early return recordEvent as reaching memory limit');
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
this.inMemoryEvents.push({
|
|
93
|
+
event_name: name,
|
|
94
|
+
time: Date.now(),
|
|
95
|
+
event_properties: properties,
|
|
96
|
+
});
|
|
97
|
+
this.startTimersIfNeeded();
|
|
98
|
+
};
|
|
99
|
+
DiagnosticsClient.prototype.startTimersIfNeeded = function () {
|
|
100
|
+
var _this = this;
|
|
101
|
+
if (!this.saveTimer) {
|
|
102
|
+
this.saveTimer = setTimeout(function () {
|
|
103
|
+
_this.saveAllDataToStorage()
|
|
104
|
+
.catch(function (error) {
|
|
105
|
+
_this.logger.debug('DiagnosticsClient: Failed to save all data to storage', error);
|
|
106
|
+
})
|
|
107
|
+
.finally(function () {
|
|
108
|
+
_this.saveTimer = null;
|
|
109
|
+
});
|
|
110
|
+
}, SAVE_INTERVAL_MS);
|
|
111
|
+
}
|
|
112
|
+
if (!this.flushTimer) {
|
|
113
|
+
this.flushTimer = setTimeout(function () {
|
|
114
|
+
_this._flush()
|
|
115
|
+
.catch(function (error) {
|
|
116
|
+
_this.logger.debug('DiagnosticsClient: Failed to flush', error);
|
|
117
|
+
})
|
|
118
|
+
.finally(function () {
|
|
119
|
+
_this.flushTimer = null;
|
|
120
|
+
});
|
|
121
|
+
}, FLUSH_INTERVAL_MS);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
DiagnosticsClient.prototype.saveAllDataToStorage = function () {
|
|
125
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
126
|
+
var tagsToSave, countersToSave, histogramsToSave, eventsToSave;
|
|
127
|
+
return __generator(this, function (_a) {
|
|
128
|
+
switch (_a.label) {
|
|
129
|
+
case 0:
|
|
130
|
+
if (!this.storage) {
|
|
131
|
+
return [2 /*return*/];
|
|
132
|
+
}
|
|
133
|
+
tagsToSave = __assign({}, this.inMemoryTags);
|
|
134
|
+
countersToSave = __assign({}, this.inMemoryCounters);
|
|
135
|
+
histogramsToSave = __assign({}, this.inMemoryHistograms);
|
|
136
|
+
eventsToSave = __spreadArray([], __read(this.inMemoryEvents), false);
|
|
137
|
+
this.inMemoryEvents = [];
|
|
138
|
+
this.inMemoryTags = {};
|
|
139
|
+
this.inMemoryCounters = {};
|
|
140
|
+
this.inMemoryHistograms = {};
|
|
141
|
+
return [4 /*yield*/, Promise.all([
|
|
142
|
+
this.storage.setTags(tagsToSave),
|
|
143
|
+
this.storage.incrementCounters(countersToSave),
|
|
144
|
+
this.storage.setHistogramStats(histogramsToSave),
|
|
145
|
+
this.storage.addEventRecords(eventsToSave),
|
|
146
|
+
])];
|
|
147
|
+
case 1:
|
|
148
|
+
_a.sent();
|
|
149
|
+
return [2 /*return*/];
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
};
|
|
154
|
+
DiagnosticsClient.prototype._flush = function () {
|
|
155
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
156
|
+
var _a, tagRecords, counterRecords, histogramStatsRecords, eventRecords, tags, counters, histogram, events, payload;
|
|
157
|
+
return __generator(this, function (_b) {
|
|
158
|
+
switch (_b.label) {
|
|
159
|
+
case 0:
|
|
160
|
+
if (!this.storage) {
|
|
161
|
+
return [2 /*return*/];
|
|
162
|
+
}
|
|
163
|
+
return [4 /*yield*/, this.saveAllDataToStorage()];
|
|
164
|
+
case 1:
|
|
165
|
+
_b.sent();
|
|
166
|
+
this.saveTimer = null;
|
|
167
|
+
this.flushTimer = null;
|
|
168
|
+
return [4 /*yield*/, this.storage.getAllAndClear()];
|
|
169
|
+
case 2:
|
|
170
|
+
_a = _b.sent(), tagRecords = _a.tags, counterRecords = _a.counters, histogramStatsRecords = _a.histogramStats, eventRecords = _a.events;
|
|
171
|
+
// Update the last flush timestamp
|
|
172
|
+
void this.storage.setLastFlushTimestamp(Date.now());
|
|
173
|
+
tags = {};
|
|
174
|
+
tagRecords.forEach(function (record) {
|
|
175
|
+
tags[record.key] = record.value;
|
|
176
|
+
});
|
|
177
|
+
counters = {};
|
|
178
|
+
counterRecords.forEach(function (record) {
|
|
179
|
+
counters[record.key] = record.value;
|
|
180
|
+
});
|
|
181
|
+
histogram = {};
|
|
182
|
+
histogramStatsRecords.forEach(function (stats) {
|
|
183
|
+
histogram[stats.key] = {
|
|
184
|
+
count: stats.count,
|
|
185
|
+
min: stats.min,
|
|
186
|
+
max: stats.max,
|
|
187
|
+
avg: Math.round((stats.sum / stats.count) * 100) / 100, // round the average to 2 decimal places.
|
|
188
|
+
};
|
|
189
|
+
});
|
|
190
|
+
events = eventRecords.map(function (record) { return ({
|
|
191
|
+
event_name: record.event_name,
|
|
192
|
+
time: record.time,
|
|
193
|
+
event_properties: record.event_properties,
|
|
194
|
+
}); });
|
|
195
|
+
// Early return if all data collections are empty
|
|
196
|
+
if (Object.keys(tags).length === 0 &&
|
|
197
|
+
Object.keys(counters).length === 0 &&
|
|
198
|
+
Object.keys(histogram).length === 0 &&
|
|
199
|
+
events.length === 0) {
|
|
200
|
+
return [2 /*return*/];
|
|
201
|
+
}
|
|
202
|
+
payload = {
|
|
203
|
+
tags: tags,
|
|
204
|
+
histogram: histogram,
|
|
205
|
+
counters: counters,
|
|
206
|
+
events: events,
|
|
207
|
+
};
|
|
208
|
+
// Send payload to diagnostics server
|
|
209
|
+
void this.fetch(payload);
|
|
210
|
+
return [2 /*return*/];
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
};
|
|
215
|
+
/**
|
|
216
|
+
* Send diagnostics data to the server
|
|
217
|
+
*/
|
|
218
|
+
DiagnosticsClient.prototype.fetch = function (payload) {
|
|
219
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
220
|
+
var response, error_1;
|
|
221
|
+
return __generator(this, function (_a) {
|
|
222
|
+
switch (_a.label) {
|
|
223
|
+
case 0:
|
|
224
|
+
_a.trys.push([0, 2, , 3]);
|
|
225
|
+
if (!getGlobalScope()) {
|
|
226
|
+
throw new Error('DiagnosticsClient: Fetch is not supported');
|
|
227
|
+
}
|
|
228
|
+
return [4 /*yield*/, fetch(this.serverUrl, {
|
|
229
|
+
method: 'POST',
|
|
230
|
+
headers: {
|
|
231
|
+
'X-ApiKey': this.apiKey,
|
|
232
|
+
'Content-Type': 'application/json',
|
|
233
|
+
},
|
|
234
|
+
body: JSON.stringify(payload),
|
|
235
|
+
})];
|
|
236
|
+
case 1:
|
|
237
|
+
response = _a.sent();
|
|
238
|
+
if (!response.ok) {
|
|
239
|
+
this.logger.debug('DiagnosticsClient: Failed to send diagnostics data.');
|
|
240
|
+
return [2 /*return*/];
|
|
241
|
+
}
|
|
242
|
+
this.logger.debug('DiagnosticsClient: Successfully sent diagnostics data');
|
|
243
|
+
return [3 /*break*/, 3];
|
|
244
|
+
case 2:
|
|
245
|
+
error_1 = _a.sent();
|
|
246
|
+
this.logger.debug('DiagnosticsClient: Failed to send diagnostics data. ', error_1);
|
|
247
|
+
return [3 /*break*/, 3];
|
|
248
|
+
case 3: return [2 /*return*/];
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
});
|
|
252
|
+
};
|
|
253
|
+
/**
|
|
254
|
+
* Initialize flush interval logic.
|
|
255
|
+
* Check if 5 minutes has passed since last flush, if so flush immediately.
|
|
256
|
+
* Otherwise set a timer to flush when the interval is reached.
|
|
257
|
+
*/
|
|
258
|
+
DiagnosticsClient.prototype.initializeFlushInterval = function () {
|
|
259
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
260
|
+
var now, lastFlushTimestamp, timeSinceLastFlush, remainingTime;
|
|
261
|
+
var _this = this;
|
|
262
|
+
return __generator(this, function (_a) {
|
|
263
|
+
switch (_a.label) {
|
|
264
|
+
case 0:
|
|
265
|
+
if (!this.storage) {
|
|
266
|
+
return [2 /*return*/];
|
|
267
|
+
}
|
|
268
|
+
now = Date.now();
|
|
269
|
+
return [4 /*yield*/, this.storage.getLastFlushTimestamp()];
|
|
270
|
+
case 1:
|
|
271
|
+
lastFlushTimestamp = (_a.sent()) || -1;
|
|
272
|
+
timeSinceLastFlush = now - lastFlushTimestamp;
|
|
273
|
+
// If last flush timestamp is -1, it means this is a new client
|
|
274
|
+
if (lastFlushTimestamp === -1) {
|
|
275
|
+
return [2 /*return*/];
|
|
276
|
+
}
|
|
277
|
+
else if (timeSinceLastFlush >= FLUSH_INTERVAL_MS) {
|
|
278
|
+
// More than 5 minutes has passed, flush immediately
|
|
279
|
+
void this._flush();
|
|
280
|
+
return [2 /*return*/];
|
|
281
|
+
}
|
|
282
|
+
else {
|
|
283
|
+
remainingTime = FLUSH_INTERVAL_MS - timeSinceLastFlush;
|
|
284
|
+
this.flushTimer = setTimeout(function () {
|
|
285
|
+
_this._flush()
|
|
286
|
+
.catch(function (error) {
|
|
287
|
+
_this.logger.debug('DiagnosticsClient: Failed to flush', error);
|
|
288
|
+
})
|
|
289
|
+
.finally(function () {
|
|
290
|
+
_this.flushTimer = null;
|
|
291
|
+
});
|
|
292
|
+
}, remainingTime);
|
|
293
|
+
}
|
|
294
|
+
return [2 /*return*/];
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
};
|
|
299
|
+
return DiagnosticsClient;
|
|
300
|
+
}());
|
|
301
|
+
export { DiagnosticsClient };
|
|
302
|
+
//# sourceMappingURL=diagnostics-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"diagnostics-client.js","sourceRoot":"","sources":["../../../src/diagnostics/diagnostics-client.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,kBAAkB,EAAuB,MAAM,uBAAuB,CAAC;AAEhF,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEjD,MAAM,CAAC,IAAM,gBAAgB,GAAG,IAAI,CAAC,CAAC,WAAW;AACjD,MAAM,CAAC,IAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,YAAY;AAC5D,MAAM,CAAC,IAAM,yBAAyB,GAAG,6DAA6D,CAAC;AACvG,MAAM,CAAC,IAAM,yBAAyB,GAAG,gEAAgE,CAAC;AAE1G,2BAA2B;AAC3B,MAAM,CAAC,IAAM,wBAAwB,GAAG,KAAK,CAAC,CAAC,4CAA4C;AAC3F,MAAM,CAAC,IAAM,+BAA+B,GAAG,EAAE,CAAC;AAwIlD;IAiBE,2BAAY,MAAc,EAAE,MAAe,EAAE,UAAiC;QAAjC,2BAAA,EAAA,iBAAiC;QAX9E,qBAAqB;QACrB,iBAAY,GAAoB,EAAE,CAAC;QACnC,qBAAgB,GAAwB,EAAE,CAAC;QAC3C,uBAAkB,GAA8B,EAAE,CAAC;QACnD,mBAAc,GAAuB,EAAE,CAAC;QAExC,iCAAiC;QACjC,cAAS,GAAyC,IAAI,CAAC;QACvD,2BAA2B;QAC3B,eAAU,GAAyC,IAAI,CAAC;QAGtD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM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AC,MAAM,EAAE,CAAC;4BACnB,sBAAO;yBACR;6BAAM;4BAEC,aAAa,GAAG,iBAAiB,GAAG,kBAAkB,CAAC;4BAC7D,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;gCAC3B,KAAI,CAAC,MAAM,EAAE;qCACV,KAAK,CAAC,UAAC,KAAK;oCACX,KAAI,CAAC,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,KAAK,CAAC,CAAC;gCACjE,CAAC,CAAC;qCACD,OAAO,CAAC;oCACP,KAAI,CAAC,UAAU,GAAG,IAAI,CAAC;gCACzB,CAAC,CAAC,CAAC;4BACP,CAAC,EAAE,aAAa,CAAC,CAAC;yBACnB;;;;;KACF;IACH,wBAAC;AAAD,CAAC,AA9RD,IA8RC","sourcesContent":["import { ILogger } from '../logger';\nimport { DiagnosticsStorage, IDiagnosticsStorage } from './diagnostics-storage';\nimport { ServerZoneType } from '../types/server-zone';\nimport { getGlobalScope } from '../global-scope';\n\nexport const SAVE_INTERVAL_MS = 1000; // 1 second\nexport const FLUSH_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\nexport const DIAGNOSTICS_US_SERVER_URL = 'https://diagnostics.prod.us-west-2.amplitude.com/v1/capture';\nexport const DIAGNOSTICS_EU_SERVER_URL = 'https://diagnostics.prod.eu-central-1.amplitude.com/v1/capture';\n\n// In-memory storage limits\nexport const MAX_MEMORY_STORAGE_COUNT = 10000; // for tags, counters, histograms separately\nexport const MAX_MEMORY_STORAGE_EVENTS_COUNT = 10;\n\n// === Core Data Types ===\n\n/**\n * Key-value pairs for environment/context information\n */\ntype DiagnosticsTags = Record<string, string>;\n\n/**\n * Numeric counters that can be incremented\n */\ntype DiagnosticsCounters = Record<string, number>;\n\n/**\n * Properties for diagnostic events\n */\ntype EventProperties = Record<string, any>;\n\n/**\n * Individual diagnostic event\n */\ninterface DiagnosticsEvent {\n readonly event_name: string;\n readonly time: number;\n readonly event_properties: EventProperties;\n}\n\n/**\n * Computed histogram statistics for final payload\n */\ninterface HistogramResult {\n readonly count: number;\n readonly min: number;\n readonly max: number;\n readonly avg: number;\n}\n\n/**\n * Internal histogram statistics with sum for efficient incremental updates\n */\nexport interface HistogramStats {\n count: number;\n min: number;\n max: number;\n sum: number; // Used for avg calculation\n}\n\n/**\n * Collection of histogram results keyed by histogram name\n */\ntype DiagnosticsHistograms = Record<string, HistogramResult>;\n\n/**\n * Collection of histogram stats keyed by histogram name (internal use for memory + persistence storage)\n */\ntype DiagnosticsHistogramStats = Record<string, HistogramStats>;\n\n// === Payload Types ===\n\n/**\n * Complete diagnostics payload sent to backend\n */\ninterface FlushPayload {\n readonly tags: DiagnosticsTags;\n readonly histogram: DiagnosticsHistograms;\n readonly counters: DiagnosticsCounters;\n readonly events: readonly DiagnosticsEvent[];\n}\n\n/**\n * Amplitude Diagnostics Client\n *\n * A client for collecting and managing diagnostics data including tags, counters,\n * histograms, and events. Data is stored persistently using IndexedDB to survive browser restarts and offline scenarios.\n *\n * Key Features:\n * - IndexedDB storage\n * - Time-based persistent storage flush interval (5 minutes since last flush)\n * - 1 second time-based memory storage flush to persistent storage\n * - Histogram statistics calculation (min, max, avg)\n */\nexport interface IDiagnosticsClient {\n /**\n * Set or update a tag\n *\n * @example\n * ```typescript\n * // Set environment tags\n * diagnostics.setTag('library', 'amplitude-typescript/2.0.0');\n * diagnostics.setTag('user_agent', navigator.userAgent);\n * ```\n */\n setTag(name: string, value: string): void;\n\n /**\n * Increment a counter. If doesn't exist, create a counter and set value to 1\n *\n * @example\n * ```typescript\n * // Track counters\n * diagnostics.increment('analytics.fileNotFound');\n * diagnostics.increment('network.retry', 3);\n * ```\n */\n increment(name: string, size?: number): void;\n\n /**\n * Record a histogram value\n *\n * @example\n * ```typescript\n * // Record performance metrics\n * diagnostics.recordHistogram('sr.time', 5.2);\n * diagnostics.recordHistogram('network.latency', 150);\n * ```\n */\n recordHistogram(name: string, value: number): void;\n\n /**\n * Record an event\n *\n * @example\n * ```typescript\n * // Record diagnostic events\n * diagnostics.recordEvent('error', {\n * stack_trace: '...',\n * });\n * ```\n */\n recordEvent(name: string, properties: EventProperties): void;\n\n // Flush storage\n _flush(): void;\n}\n\nexport class DiagnosticsClient implements IDiagnosticsClient {\n storage?: IDiagnosticsStorage;\n logger: ILogger;\n serverUrl: string;\n apiKey: string;\n\n // In-memory storages\n inMemoryTags: DiagnosticsTags = {};\n inMemoryCounters: DiagnosticsCounters = {};\n inMemoryHistograms: DiagnosticsHistogramStats = {};\n inMemoryEvents: DiagnosticsEvent[] = [];\n\n // Timer for 1-second persistence\n saveTimer: ReturnType<typeof setTimeout> | null = null;\n // Timer for flush interval\n flushTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(apiKey: string, logger: ILogger, serverZone: ServerZoneType = 'US') {\n this.apiKey = apiKey;\n this.logger = logger;\n this.serverUrl = serverZone === 'US' ? DIAGNOSTICS_US_SERVER_URL : DIAGNOSTICS_EU_SERVER_URL;\n\n if (DiagnosticsStorage.isSupported()) {\n this.storage = new DiagnosticsStorage(apiKey, logger);\n } else {\n this.logger.debug('DiagnosticsClient: IndexedDB is not supported');\n }\n\n void this.initializeFlushInterval();\n }\n\n setTag(name: string, value: string) {\n if (!this.storage) {\n return;\n }\n\n if (Object.keys(this.inMemoryTags).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return setTags as reaching memory limit');\n return;\n }\n\n this.inMemoryTags[name] = value;\n this.startTimersIfNeeded();\n }\n\n increment(name: string, size = 1) {\n if (!this.storage) {\n return;\n }\n\n if (Object.keys(this.inMemoryCounters).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return increment as reaching memory limit');\n return;\n }\n\n this.inMemoryCounters[name] = (this.inMemoryCounters[name] || 0) + size;\n this.startTimersIfNeeded();\n }\n\n recordHistogram(name: string, value: number) {\n if (!this.storage) {\n return;\n }\n\n if (Object.keys(this.inMemoryHistograms).length >= MAX_MEMORY_STORAGE_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return recordHistogram as reaching memory limit');\n return;\n }\n\n const existing = this.inMemoryHistograms[name];\n if (existing) {\n // Update existing stats incrementally\n existing.count += 1;\n existing.min = Math.min(existing.min, value);\n existing.max = Math.max(existing.max, value);\n existing.sum += value;\n } else {\n // Create new stats\n this.inMemoryHistograms[name] = {\n count: 1,\n min: value,\n max: value,\n sum: value,\n };\n }\n this.startTimersIfNeeded();\n }\n\n recordEvent(name: string, properties: EventProperties) {\n if (!this.storage) {\n return;\n }\n\n if (this.inMemoryEvents.length >= MAX_MEMORY_STORAGE_EVENTS_COUNT) {\n this.logger.debug('DiagnosticsClient: Early return recordEvent as reaching memory limit');\n return;\n }\n\n this.inMemoryEvents.push({\n event_name: name,\n time: Date.now(),\n event_properties: properties,\n });\n this.startTimersIfNeeded();\n }\n\n startTimersIfNeeded() {\n if (!this.saveTimer) {\n this.saveTimer = setTimeout(() => {\n this.saveAllDataToStorage()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to save all data to storage', error);\n })\n .finally(() => {\n this.saveTimer = null;\n });\n }, SAVE_INTERVAL_MS);\n }\n\n if (!this.flushTimer) {\n this.flushTimer = setTimeout(() => {\n this._flush()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to flush', error);\n })\n .finally(() => {\n this.flushTimer = null;\n });\n }, FLUSH_INTERVAL_MS);\n }\n }\n\n async saveAllDataToStorage() {\n if (!this.storage) {\n return;\n }\n const tagsToSave = { ...this.inMemoryTags };\n const countersToSave = { ...this.inMemoryCounters };\n const histogramsToSave = { ...this.inMemoryHistograms };\n const eventsToSave = [...this.inMemoryEvents];\n\n this.inMemoryEvents = [];\n this.inMemoryTags = {};\n this.inMemoryCounters = {};\n this.inMemoryHistograms = {};\n\n await Promise.all([\n this.storage.setTags(tagsToSave),\n this.storage.incrementCounters(countersToSave),\n this.storage.setHistogramStats(histogramsToSave),\n this.storage.addEventRecords(eventsToSave),\n ]);\n }\n\n async _flush() {\n if (!this.storage) {\n return;\n }\n\n await this.saveAllDataToStorage();\n this.saveTimer = null;\n this.flushTimer = null;\n\n // Get all data from storage and clear it\n const {\n tags: tagRecords,\n counters: counterRecords,\n histogramStats: histogramStatsRecords,\n events: eventRecords,\n } = await this.storage.getAllAndClear();\n\n // Update the last flush timestamp\n void this.storage.setLastFlushTimestamp(Date.now());\n\n // Convert metrics to the expected format\n const tags: DiagnosticsTags = {};\n tagRecords.forEach((record) => {\n tags[record.key] = record.value;\n });\n\n const counters: DiagnosticsCounters = {};\n counterRecords.forEach((record) => {\n counters[record.key] = record.value;\n });\n\n const histogram: DiagnosticsHistograms = {};\n histogramStatsRecords.forEach((stats) => {\n histogram[stats.key] = {\n count: stats.count,\n min: stats.min,\n max: stats.max,\n avg: Math.round((stats.sum / stats.count) * 100) / 100, // round the average to 2 decimal places.\n };\n });\n\n const events: DiagnosticsEvent[] = eventRecords.map((record) => ({\n event_name: record.event_name,\n time: record.time,\n event_properties: record.event_properties,\n }));\n\n // Early return if all data collections are empty\n if (\n Object.keys(tags).length === 0 &&\n Object.keys(counters).length === 0 &&\n Object.keys(histogram).length === 0 &&\n events.length === 0\n ) {\n return;\n }\n\n // Create flush payload\n const payload: FlushPayload = {\n tags,\n histogram,\n counters,\n events,\n };\n\n // Send payload to diagnostics server\n void this.fetch(payload);\n }\n\n /**\n * Send diagnostics data to the server\n */\n async fetch(payload: FlushPayload) {\n try {\n if (!getGlobalScope()) {\n throw new Error('DiagnosticsClient: Fetch is not supported');\n }\n\n const response = await fetch(this.serverUrl, {\n method: 'POST',\n headers: {\n 'X-ApiKey': this.apiKey,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n this.logger.debug('DiagnosticsClient: Failed to send diagnostics data.');\n return;\n }\n\n this.logger.debug('DiagnosticsClient: Successfully sent diagnostics data');\n } catch (error) {\n this.logger.debug('DiagnosticsClient: Failed to send diagnostics data. ', error);\n }\n }\n\n /**\n * Initialize flush interval logic.\n * Check if 5 minutes has passed since last flush, if so flush immediately.\n * Otherwise set a timer to flush when the interval is reached.\n */\n async initializeFlushInterval() {\n if (!this.storage) {\n return;\n }\n const now = Date.now();\n const lastFlushTimestamp = (await this.storage.getLastFlushTimestamp()) || -1;\n const timeSinceLastFlush = now - lastFlushTimestamp;\n\n // If last flush timestamp is -1, it means this is a new client\n if (lastFlushTimestamp === -1) {\n return;\n } else if (timeSinceLastFlush >= FLUSH_INTERVAL_MS) {\n // More than 5 minutes has passed, flush immediately\n void this._flush();\n return;\n } else {\n // Set timer for remaining time\n const remainingTime = FLUSH_INTERVAL_MS - timeSinceLastFlush;\n this.flushTimer = setTimeout(() => {\n this._flush()\n .catch((error) => {\n this.logger.debug('DiagnosticsClient: Failed to flush', error);\n })\n .finally(() => {\n this.flushTimer = null;\n });\n }, remainingTime);\n }\n }\n}\n"]}
|