summaryrefslogtreecommitdiff
path: root/shared/metrics-8/src/recorder/metricskit.ts
blob: 9d724c9509b16aa3b150bc847c452cdad8e27bc7 (plain)
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
import type { MetricsEventRecorder } from '@jet/engine';
import type { LintedMetricsEvent } from '@jet/environment/types/metrics';
import type { Opt } from '@jet/environment/types/optional';
import type { Logger, LoggerFactory } from '@amp/web-apps-logger';

import { METRICS_EVENT_TYPES } from '../constants';

import type { WebDelegates as WebDelegatesInstance } from '@amp-metrics/mt-metricskit-delegates-web';
import type { ClickstreamProcessor as ClickstreamProcessorInstance } from '@amp-metrics/mt-metricskit-processor-clickstream';
import type { Impressions } from '../impressions';
import { sendToMetricsDevConsole } from '../utils/metrics-dev-console/setup-metrics-dev';
import { getEventFieldsWithTopic } from '../utils/get-event-field-topic';
import { eventType } from '../utils/metrics-dev-console/constants';

interface DeferredEvent {
    event: LintedMetricsEvent;
    topic: Opt<string>;
}

type EventRecorder = WebDelegatesInstance['eventRecorder'];

type MetricEventType = (typeof METRICS_EVENT_TYPES)[number];

export interface MetricKitConfig {
    constraintProfiles: string[];
    topic: string;
}

export class MetricsKitRecorder implements MetricsEventRecorder {
    private readonly log: Logger;
    private eventRecorder: EventRecorder | undefined;
    private mtkit: ClickstreamProcessorInstance | undefined;
    private recordedEventsCount: number;
    private config: MetricKitConfig;
    private readonly impressions: InstanceType<typeof Impressions> | undefined;
    private enabled: boolean = true;

    /**
     * Queues events prior to the mt-event-queue recorder being available
     */
    private readonly deferredEvents: DeferredEvent[];

    constructor(
        loggerFactory: LoggerFactory,
        config: MetricKitConfig,
        impressions: InstanceType<typeof Impressions> | undefined,
    ) {
        this.log = loggerFactory.loggerFor('MetricsKitRecorder');
        this.deferredEvents = [];
        this.recordedEventsCount = 0;
        this.config = config;
        this.impressions = impressions;
    }

    record(event: LintedMetricsEvent, topic: Opt<string>): void {
        topic = topic ?? this.config.topic;
        if (this.isDisabled()) {
            this.log.info(
                `topic ${this.config.topic} is disabled following event not captured:`,
                event,
            );
            return;
        }

        if (this.eventRecorder) {
            const eventHandler = event.fields.eventType as MetricEventType;
            const { pageId, pageType, pageContext } = event.fields;
            if (!eventHandler) {
                this.log.warn('No `eventType` found on event', event, topic);
                return;
            } else if (!METRICS_EVENT_TYPES.includes(eventHandler)) {
                this.log.warn(
                    'Invalid `eventType` found on event',
                    event,
                    topic,
                );
                return;
            } else if (!this.impressions && eventHandler === 'impressions') {
                this.log.info(
                    'Supressing impression event. Impressions not enabled',
                );
                return;
            }

            // when the user leaves a page to report the accumulated impressions for that page
            if (
                (this.impressions?.isEnabled('exit') &&
                    eventHandler === 'exit') ||
                (this.impressions?.isEnabled('click') &&
                    event.fields.actionType === 'navigate')
            ) {
                // create + capture impressions
                const accumulatedImpressions =
                    this.impressions.consumeImpressions();

                const metricsData = this.mtkit?.eventHandlers[
                    'impressions'
                ]?.metricsData(pageId, pageType, pageContext, {
                    impressions: accumulatedImpressions,
                });

                metricsData
                    ?.recordEvent(topic)
                    .then((data) => {
                        this.log.info(
                            'impressions event captured',
                            data,
                            topic,
                        );
                        sendToMetricsDevConsole(
                            data as { [key: string]: unknown },
                            topic ?? '',
                        );
                    })
                    .catch((e) => {
                        this.log.warn(
                            'failed to capture impression metrics',
                            e,
                            topic,
                        );
                    });
            }

            let impressionsData = {};
            // snapshot impressions to include in click events
            if (
                (this.impressions?.isEnabled('click') &&
                    eventHandler === 'click') ||
                (this.impressions?.isEnabled('impressions') &&
                    eventHandler === 'impressions')
            ) {
                const snapshotImpressions =
                    this.impressions.captureSnapshotImpression();
                impressionsData = {
                    impressions: snapshotImpressions,
                };
            }

            const eventFields = getEventFieldsWithTopic(event, topic);
            // click events are the only ones with different method signature
            // https://github.pie.apple.com/amp-metrics/mt-metricskit/blob/7.3.5/src/metrics/event_handlers/click.js#L133
            const metricsDataArgs =
                eventHandler === 'click' // TODO rdar://102438307 (JMOTW Clickstream – Pass targetElement to click events)
                    ? [
                          pageId,
                          pageType,
                          pageContext,
                          null,
                          { ...eventFields, ...impressionsData },
                      ]
                    : [pageId, pageType, pageContext, eventFields];

            if (eventHandler === 'impressions') {
                metricsDataArgs.push(impressionsData);
            }

            let metricsData = this.mtkit?.eventHandlers[
                eventHandler
            ]?.metricsData(
                // @ts-expect-error TypeScript doesn't handle spreading the argument array well
                ...metricsDataArgs,
            );

            metricsData
                ?.recordEvent(topic)
                .then((data) => {
                    this.log.info('MetricsKit event data', data, topic);
                    sendToMetricsDevConsole(
                        data as { [key: string]: unknown },
                        topic ?? '',
                    );
                })
                .catch((e) => {
                    this.log.error(
                        'MetricsKit failed to capture metric',
                        e,
                        topic,
                    );
                });

            this.recordedEventsCount++;

            // on exit events we should flush all metrics
            if (eventHandler === 'exit') {
                this.eventRecorder?.flushUnreportedEvents?.(true);
                sendToMetricsDevConsole(
                    { metricsDevType: eventType.FLUSH, status: 'SUCCESS' },
                    topic,
                );
            }
        } else {
            this.deferredEvents.push({ event, topic });
        }
    }

    async flush(): Promise<number> {
        await this.eventRecorder?.flushUnreportedEvents?.(false);
        const count = this.recordedEventsCount;
        this.recordedEventsCount = 0;
        return count;
    }

    setupEventRecorder(
        eventRecorder: EventRecorder,
        mtkit: ClickstreamProcessorInstance,
    ): void {
        this.eventRecorder = eventRecorder;
        this.mtkit = mtkit;
        this.deferredEvents.forEach(({ event, topic }) =>
            this.record(event, topic),
        );
        this.deferredEvents.length = 0;
    }

    isDisabled(): boolean {
        return !this.enabled;
    }

    enable(): void {
        if (this.enabled) {
            this.log.info(
                `Clickstream topic ${this.config.topic} already enabled`,
            );
            return;
        }

        this.log.info(`Enabling clickstream topic ${this.config.topic}`);
        this.enabled = true;
    }

    disable(): void {
        if (this.isDisabled()) {
            return;
        }

        this.log.info(`Disabling clickstream topic ${this.config.topic}`);
        this.enabled = false;
    }
}