-
Notifications
You must be signed in to change notification settings - Fork 8.1k
/
analytics_client.ts
359 lines (323 loc) · 12.1 KB
/
analytics_client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { Mixed } from 'io-ts';
import type { Observable } from 'rxjs';
import { BehaviorSubject, Subject, combineLatest, from, merge } from 'rxjs';
import {
buffer,
bufferCount,
concatMap,
delay,
filter,
groupBy,
map,
mergeMap,
share,
shareReplay,
skipWhile,
takeUntil,
tap,
} from 'rxjs';
import type { LogMeta } from '@kbn/logging';
import type { IShipper } from '../shippers';
import type {
AnalyticsClientInitContext,
ContextProviderName,
ContextProviderOpts,
EventTypeOpts,
IAnalyticsClient,
OptInConfig,
RegisterShipperOpts,
ShipperClassConstructor,
} from './types';
import type { Event, EventContext, EventType, TelemetryCounter } from '../events';
import { ShippersRegistry } from './shippers_registry';
import { OptInConfigService } from './opt_in_config';
import { ContextService } from './context_service';
import { schemaToIoTs, validateSchema } from '../schema/validation';
interface EventDebugLogMeta extends LogMeta {
ebt_event: Event<unknown>;
}
export class AnalyticsClient implements IAnalyticsClient {
private readonly internalTelemetryCounter$ = new Subject<TelemetryCounter>();
public readonly telemetryCounter$: Observable<TelemetryCounter> =
this.internalTelemetryCounter$.pipe(share()); // Using `share` so we can have multiple subscribers
/**
* This queue holds all the events until both conditions occur:
* 1. We know the user's optIn decision.
* 2. We have, at least, one registered shipper.
* @private
*/
private readonly internalEventQueue$ = new Subject<Event>();
private readonly shippersRegistry = new ShippersRegistry();
/**
* Observable used to report when a shipper is registered.
* @private
*/
private readonly shipperRegistered$ = new Subject<void>();
private readonly eventTypeRegistry = new Map<
EventType,
EventTypeOpts<unknown> & { validator?: Mixed }
>();
private readonly contextService: ContextService;
private readonly context$ = new BehaviorSubject<Partial<EventContext>>({});
private readonly optInConfig$ = new BehaviorSubject<OptInConfigService | undefined>(undefined);
private readonly optInConfigWithReplay$ = this.optInConfig$.pipe(
filter((optInConfig): optInConfig is OptInConfigService => typeof optInConfig !== 'undefined'),
shareReplay(1)
);
private readonly contextWithReplay$ = this.context$.pipe(
skipWhile(() => !this.optInConfig$.value), // Do not forward the context events until we have an optInConfig value
shareReplay(1)
);
constructor(private readonly initContext: AnalyticsClientInitContext) {
this.contextService = new ContextService(
this.context$,
this.initContext.isDev,
this.initContext.logger.get('context-service')
);
this.reportEnqueuedEventsWhenClientIsReady();
}
public reportEvent = <EventTypeData extends object>(
eventType: EventType,
eventData: EventTypeData
) => {
// Fetch the timestamp as soon as we receive the event.
const timestamp = new Date().toISOString();
this.internalTelemetryCounter$.next({
type: 'enqueued',
source: 'client',
event_type: eventType,
code: 'enqueued',
count: 1,
});
const eventTypeOpts = this.eventTypeRegistry.get(eventType);
if (!eventTypeOpts) {
this.internalTelemetryCounter$.next({
type: 'dropped',
source: 'client',
event_type: eventType,
code: 'UnregisteredType',
count: 1,
});
throw new Error(
`Attempted to report event type "${eventType}", before registering it. Use the "registerEventType" API to register it.`
);
}
// If the validator is registered (dev-mode only), perform the validation.
if (eventTypeOpts.validator) {
validateSchema<EventTypeData>(
`Event Type '${eventType}'`,
eventTypeOpts.validator,
eventData
);
}
const event: Event = {
timestamp,
event_type: eventType,
context: this.context$.value,
properties: eventData as unknown as Record<string, unknown>,
};
this.initContext.logger.debug<EventDebugLogMeta>(`Report event "${eventType}"`, {
ebt_event: event,
});
const optInConfig = this.optInConfig$.value;
if (optInConfig?.isEventTypeOptedIn(eventType) === false) {
// If opted out, skip early
return;
}
if (typeof optInConfig === 'undefined') {
// If the opt-in config is not provided yet, we need to enqueue the event to an internal queue
this.internalEventQueue$.next(event);
} else {
this.sendToShipper(eventType, [event]);
}
};
public registerEventType = <EventTypeData>(eventTypeOps: EventTypeOpts<EventTypeData>) => {
if (this.eventTypeRegistry.get(eventTypeOps.eventType)) {
throw new Error(`Event Type "${eventTypeOps.eventType}" is already registered.`);
}
this.eventTypeRegistry.set(eventTypeOps.eventType, {
...eventTypeOps,
validator: this.initContext.isDev ? schemaToIoTs(eventTypeOps.schema) : undefined,
});
};
public optIn = (optInConfig: OptInConfig) => {
const optInConfigInstance = new OptInConfigService(optInConfig);
this.optInConfig$.next(optInConfigInstance);
};
public registerContextProvider = <Context>(contextProviderOpts: ContextProviderOpts<Context>) => {
this.contextService.registerContextProvider(contextProviderOpts);
};
public removeContextProvider = (name: ContextProviderName) => {
this.contextService.removeContextProvider(name);
};
public registerShipper = <Shipper extends IShipper, ShipperConfig>(
ShipperClass: ShipperClassConstructor<Shipper, ShipperConfig>,
shipperConfig: ShipperConfig,
{ exclusiveEventTypes = [] }: RegisterShipperOpts = {}
) => {
const shipperName = ShipperClass.shipperName;
const shipper = new ShipperClass(shipperConfig, {
...this.initContext,
logger: this.initContext.logger.get('shipper', shipperName),
});
if (exclusiveEventTypes.length) {
// This feature is not intended to be supported in the MVP.
// I can remove it if we think it causes more bad than good.
exclusiveEventTypes.forEach((eventType) => {
this.shippersRegistry.addEventExclusiveShipper(eventType, shipperName, shipper);
});
} else {
this.shippersRegistry.addGlobalShipper(shipperName, shipper);
}
// Subscribe to the shipper's telemetryCounter$ and pass it over to the client's-level observable
shipper.telemetryCounter$?.subscribe((counter) =>
this.internalTelemetryCounter$.next({
...counter,
source: shipperName, // Enforce the shipper's name in the `source`
})
);
// Spread the optIn configuration updates
this.optInConfigWithReplay$.subscribe((optInConfig) => {
const isOptedIn = optInConfig.isShipperOptedIn(shipperName);
try {
shipper.optIn(isOptedIn);
} catch (err) {
this.initContext.logger.warn(
`Failed to set isOptedIn:${isOptedIn} in shipper ${shipperName}`,
err
);
}
});
// Spread the global context if it has custom extendContext method
if (shipper.extendContext) {
this.contextWithReplay$.subscribe((context) => {
try {
shipper.extendContext!(context);
} catch (err) {
this.initContext.logger.warn(
`Shipper "${shipperName}" failed to extend the context`,
err
);
}
});
}
// Notify that a shipper is registered
this.shipperRegistered$.next();
};
public flush = async () => {
await Promise.all(
[...this.shippersRegistry.allShippers.entries()].map(async ([shipperName, shipper]) => {
try {
await shipper.flush();
} catch (err) {
this.initContext.logger.warn(`Failed to flush shipper "${shipperName}"`, err);
}
})
);
};
public shutdown = async () => {
await this.flush();
this.shippersRegistry.allShippers.forEach((shipper, shipperName) => {
try {
shipper.shutdown();
} catch (err) {
this.initContext.logger.warn(`Failed to shutdown shipper "${shipperName}"`, err);
}
});
this.internalEventQueue$.complete();
this.internalTelemetryCounter$.complete();
this.shipperRegistered$.complete();
this.optInConfig$.complete();
this.context$.complete();
};
/**
* Forwards the `events` to the registered shippers, bearing in mind if the shipper is opted-in for that eventType.
* @param eventType The event type's name
* @param events A bulk array of events matching the eventType.
* @private
*/
private sendToShipper(eventType: EventType, events: Event[]) {
let sentToShipper = false;
this.shippersRegistry.getShippersForEventType(eventType).forEach((shipper, shipperName) => {
const isShipperOptedIn = this.optInConfig$.value?.isShipperOptedIn(shipperName, eventType);
// Only send it to the non-explicitly opted-out shippers
if (isShipperOptedIn) {
sentToShipper = true;
try {
shipper.reportEvents(events);
} catch (err) {
this.initContext.logger.warn(
`Failed to report event "${eventType}" via shipper "${shipperName}"`,
err
);
}
}
});
if (sentToShipper) {
this.internalTelemetryCounter$.next({
type: 'sent_to_shipper',
source: 'client',
event_type: eventType,
code: 'OK',
count: events.length,
});
}
}
/**
* Once the client is ready (it has a valid optInConfig and at least one shipper),
* flush any early events and ship them or discard them based on the optInConfig.
* @private
*/
private reportEnqueuedEventsWhenClientIsReady() {
// Observer that will emit when both events occur: the OptInConfig is set + a shipper has been registered
const configReceivedAndShipperReceivedObserver$ = combineLatest([
this.optInConfigWithReplay$,
merge([
this.shipperRegistered$,
// Merging shipperRegistered$ with the optInConfigWithReplay$ when optedIn is false, so that we don't need to wait for the shipper if opted-in === false
this.optInConfigWithReplay$.pipe(filter((cfg) => cfg?.isOptedIn() === false)),
]),
]);
// Flush the internal queue when we get any optInConfig and, at least, 1 shipper
this.internalEventQueue$
.pipe(
// Take until will close the observer once we reach the condition below
takeUntil(configReceivedAndShipperReceivedObserver$),
// Accumulate the events until we can send them
buffer(configReceivedAndShipperReceivedObserver$),
// Minimal delay only to make this chain async and let the optIn operation to complete first.
delay(0),
// Re-emit the context to make sure all the shippers got it (only if opted-in)
tap(() => {
if (this.optInConfig$.value?.isOptedIn()) {
this.context$.next(this.context$.value);
}
}),
// Minimal delay only to make this chain async and let
// the context update operation to complete first.
delay(0),
// Flatten the array of events
concatMap((events) => from(events)),
// Discard opted-out events
filter((event) => this.optInConfig$.value?.isEventTypeOptedIn(event.event_type) === true),
// Let's group the requests per eventType for easier batching
groupBy((event) => event.event_type),
mergeMap((groupedObservable) =>
groupedObservable.pipe(
bufferCount(1000), // Batching up-to 1000 events per event type for backpressure reasons
map((events) => ({ eventType: groupedObservable.key, events }))
)
)
)
.subscribe(({ eventType, events }) => {
this.sendToShipper(eventType, events);
});
}
}