summaryrefslogtreecommitdiff
path: root/shared/metrics-8/src/recorder/funnelkit.ts
blob: 7f3fa84b4d56ec15f329471101d28611e641ef81 (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
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 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>;
}

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

/**
 * These fields are considered PII and should be ignored by FunnelKit.
 * `consumerId` is added via the `processEvent` based on when it is available (see jet/metrics/index.ts)
 * However it should be ignored when sent to the FunnelKit topic.
 */
const IGNORED_FIELDS = ['consumerId'];

export class FunnelKitRecorder implements MetricsEventRecorder {
    private readonly log: Logger;
    private funnelKit: ClickstreamProcessorInstance | undefined;
    private funnelKitEnabled: boolean = false;
    private recordedEventsCount: number;
    private config: FunnelKitConfig;
    private readonly impressions: InstanceType<typeof Impressions> | undefined;

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

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

    async record(
        event: LintedMetricsEvent,
        eventTopic: Opt<string>,
    ): Promise<void> {
        let topic = eventTopic ?? this.config.topic;

        // TV always uses the config topic
        // TODO: rdar://151772731 (Align funnel metrics between Music + TV)
        if (this.config.topic === 'xp_amp_tv_unidentified') {
            topic = this.config.topic;
        }

        if (!this.funnelKitEnabled) {
            this.log.info('FunnelKit not enabled', event, topic);
            return;
        }

        if (this.funnelKit) {
            const eventHandler = event.fields.eventType as string;
            const { pageId, pageType, pageContext } = event.fields;
            if (!eventHandler) {
                this.log.warn('No `eventType` found on event', event, topic);
            } 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.funnelKit?.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: Record<string, unknown> = {};
            // 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 = snapshotImpressions
                    ? {
                          impressions: snapshotImpressions,
                      }
                    : {};
            }

            const eventFields = getEventFieldsWithTopic(event, topic);
            // Handle transaction events differently per Ember implementation
            // https://github.pie.apple.com/amp-ui/ember-metrics/blob/7eb762601db5e37cb428d7a4e6f24e22d0529515/addon/services/metrics.js#L347-L349
            const metricsDataArgs =
                eventHandler === 'transaction'
                    ? [eventFields]
                    : [pageId, pageType, pageContext, eventFields];

            try {
                const baseFields = await this.funnelKit.eventHandlers[
                    eventHandler
                ]
                    ?.metricsData(
                        // @ts-expect-error TypeScript doesn't handle spreading the argument array well
                        ...metricsDataArgs,
                    )
                    .toJSON();

                const metricsData = {
                    ...baseFields,
                    ...eventFields,
                    ...impressionsData,
                };
                IGNORED_FIELDS.forEach(
                    (ignoredField) => delete metricsData[ignoredField],
                );
                this.log.info('FunnelKit event data', metricsData, topic);

                try {
                    const data =
                        await this.funnelKit.system.eventRecorder.recordEvent(
                            topic,
                            metricsData,
                        );
                    sendToMetricsDevConsole(data, topic);
                } catch (e) {
                    this.log.info(
                        'FunnelKit failed to capture',
                        metricsData,
                        topic,
                    );
                }

                // on exit events we should flush all metrics
                if (eventHandler === 'exit') {
                    this.funnelKit?.system.eventRecorder.flushUnreportedEvents?.(
                        true,
                    );

                    sendToMetricsDevConsole(
                        { metricsDevType: eventType.FLUSH, status: 'SUCCESS' },
                        topic,
                    );
                }

                this.recordedEventsCount++;
            } catch (e) {
                this.log.error('FunnelKit failed to capture metric', e, topic);
            }
        } else {
            this.deferredEvents.push({ event, topic });
        }
    }

    async flush(): Promise<number> {
        if (!this.funnelKitEnabled) {
            return 0;
        }

        await this.funnelKit?.system.eventRecorder.flushUnreportedEvents(false);
        const count = this.recordedEventsCount;
        this.recordedEventsCount = 0;
        return count;
    }

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

    enableFunnelKit(): void {
        if (this.funnelKitEnabled) {
            return;
        }

        this.log.info('Enabling FunnelKit');
        this.funnelKitEnabled = true;
    }

    disableFunnelKit(): void {
        if (!this.funnelKitEnabled) {
            return;
        }

        this.log.info('Disabling FunnelKit');
        this.funnelKitEnabled = false;
    }
}