|
| 1 | +/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 | + |
| 5 | +import { Page, Route } from '@playwright/test'; |
| 6 | +import { gunzipSync } from 'zlib'; |
| 7 | + |
| 8 | +export interface GleanPing { |
| 9 | + eventName: string; |
| 10 | + extras: Record<string, string>; |
| 11 | + payload: Record<string, any>; |
| 12 | + url: string; |
| 13 | + timestamp: number; |
| 14 | +} |
| 15 | + |
| 16 | +/** |
| 17 | + * Intercepts Glean HTTP pings via page.route() and exposes captured events |
| 18 | + * for assertions in functional tests. |
| 19 | + * |
| 20 | + * Must be started (via start()) BEFORE any page.goto() calls, since |
| 21 | + * page.route() only intercepts requests registered before navigation. |
| 22 | + */ |
| 23 | +export class GleanEventsHelper { |
| 24 | + private pings: GleanPing[] = []; |
| 25 | + private page: Page; |
| 26 | + private started = false; |
| 27 | + private readonly ROUTE_PATTERN = '**/submit/accounts*frontend*/**'; |
| 28 | + |
| 29 | + constructor(page: Page) { |
| 30 | + this.page = page; |
| 31 | + } |
| 32 | + |
| 33 | + async start(): Promise<void> { |
| 34 | + if (this.started) return; |
| 35 | + this.started = true; |
| 36 | + |
| 37 | + // Glean.js uses navigator.sendBeacon() which Playwright's page.route() |
| 38 | + // cannot intercept. Monkey-patch sendBeacon to use fetch() instead. |
| 39 | + await this.page.addInitScript(() => { |
| 40 | + // eslint-disable-next-line no-undef |
| 41 | + navigator.sendBeacon = function (url: string, data?: BodyInit | null) { |
| 42 | + fetch(url, { |
| 43 | + method: 'POST', |
| 44 | + body: data, |
| 45 | + keepalive: true, |
| 46 | + mode: 'no-cors', |
| 47 | + }).catch(() => {}); |
| 48 | + return true; |
| 49 | + }; |
| 50 | + }); |
| 51 | + |
| 52 | + await this.page.route(this.ROUTE_PATTERN, async (route: Route) => { |
| 53 | + const request = route.request(); |
| 54 | + |
| 55 | + if (request.method() !== 'POST') { |
| 56 | + await route.fulfill({ status: 200 }); |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + try { |
| 61 | + const body = this.parseRequestBody(request); |
| 62 | + const eventName = body?.metrics?.string?.['event.name']; |
| 63 | + |
| 64 | + if (eventName) { |
| 65 | + // FxA stores event metadata as string metrics (event.reason, etc.) |
| 66 | + const stringMetrics = body?.metrics?.string ?? {}; |
| 67 | + const extras: Record<string, string> = {}; |
| 68 | + for (const [key, value] of Object.entries(stringMetrics)) { |
| 69 | + if (key.startsWith('event.') && key !== 'event.name') { |
| 70 | + extras[key.replace('event.', '')] = value as string; |
| 71 | + } |
| 72 | + } |
| 73 | + this.pings.push({ |
| 74 | + eventName, |
| 75 | + extras, |
| 76 | + payload: body, |
| 77 | + url: request.url(), |
| 78 | + timestamp: Date.now(), |
| 79 | + }); |
| 80 | + } |
| 81 | + } catch { |
| 82 | + // Silently ignore parse errors — non-event pings are expected |
| 83 | + } |
| 84 | + |
| 85 | + await route.fulfill({ status: 200 }); |
| 86 | + }); |
| 87 | + } |
| 88 | + |
| 89 | + async stop(): Promise<void> { |
| 90 | + if (!this.started) return; |
| 91 | + await this.page.unroute(this.ROUTE_PATTERN); |
| 92 | + this.started = false; |
| 93 | + } |
| 94 | + |
| 95 | + private parseRequestBody( |
| 96 | + request: ReturnType<Route['request']> |
| 97 | + ): Record<string, any> { |
| 98 | + const contentEncoding = request.headers()['content-encoding']; |
| 99 | + const rawBody = request.postDataBuffer(); |
| 100 | + |
| 101 | + if (!rawBody) return {}; |
| 102 | + |
| 103 | + if (contentEncoding === 'gzip') { |
| 104 | + const decompressed = gunzipSync(rawBody); |
| 105 | + return JSON.parse(decompressed.toString('utf-8')); |
| 106 | + } |
| 107 | + |
| 108 | + return JSON.parse(rawBody.toString('utf-8')); |
| 109 | + } |
| 110 | + |
| 111 | + getEventNames(): string[] { |
| 112 | + return this.pings.map((p) => p.eventName); |
| 113 | + } |
| 114 | + |
| 115 | + hasEvent(name: string): boolean { |
| 116 | + return this.pings.some((p) => p.eventName === name); |
| 117 | + } |
| 118 | + |
| 119 | + getEventsByName(name: string): GleanPing[] { |
| 120 | + return this.pings.filter((p) => p.eventName === name); |
| 121 | + } |
| 122 | + |
| 123 | + getPings(): GleanPing[] { |
| 124 | + return [...this.pings]; |
| 125 | + } |
| 126 | + |
| 127 | + clear(): void { |
| 128 | + this.pings = []; |
| 129 | + } |
| 130 | + |
| 131 | + /** |
| 132 | + * Polls until an event with the given name appears. |
| 133 | + * @param name The event name to wait for. |
| 134 | + * @param timeout Maximum wait time in ms (default 5000). |
| 135 | + * @param interval Poll interval in ms (default 100). |
| 136 | + */ |
| 137 | + async waitForEvent( |
| 138 | + name: string, |
| 139 | + timeout = 5000, |
| 140 | + interval = 100 |
| 141 | + ): Promise<GleanPing> { |
| 142 | + const start = Date.now(); |
| 143 | + while (Date.now() - start < timeout) { |
| 144 | + const ping = this.pings.find((p) => p.eventName === name); |
| 145 | + if (ping) return ping; |
| 146 | + await new Promise((resolve) => setTimeout(resolve, interval)); |
| 147 | + } |
| 148 | + throw new Error( |
| 149 | + `Timed out waiting for Glean event "${name}" after ${timeout}ms.\n` + |
| 150 | + `Captured events: [${this.getEventNames().join(', ')}]` |
| 151 | + ); |
| 152 | + } |
| 153 | + |
| 154 | + /** |
| 155 | + * Asserts that the given events appeared in order (not necessarily |
| 156 | + * contiguous — other events may appear between them). |
| 157 | + * |
| 158 | + * Filters captured events to only those in the expected list, then |
| 159 | + * checks sequential order. |
| 160 | + * |
| 161 | + * @param expectedSequence Event names in the expected order. |
| 162 | + */ |
| 163 | + assertEventOrder(expectedSequence: string[]): void { |
| 164 | + const captured = this.getEventNames(); |
| 165 | + const expectedSet = new Set(expectedSequence); |
| 166 | + |
| 167 | + const relevant = captured.filter((name) => expectedSet.has(name)); |
| 168 | + |
| 169 | + let expectedIdx = 0; |
| 170 | + for (const eventName of relevant) { |
| 171 | + if ( |
| 172 | + expectedIdx < expectedSequence.length && |
| 173 | + eventName === expectedSequence[expectedIdx] |
| 174 | + ) { |
| 175 | + expectedIdx++; |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + if (expectedIdx !== expectedSequence.length) { |
| 180 | + throw new Error( |
| 181 | + `Glean event order mismatch.\n` + |
| 182 | + `Expected sequence: [${expectedSequence.join(', ')}]\n` + |
| 183 | + `Relevant captured: [${relevant.join(', ')}]\n` + |
| 184 | + `All captured: [${captured.join(', ')}]` |
| 185 | + ); |
| 186 | + } |
| 187 | + } |
| 188 | +} |
0 commit comments