Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

10.1 KB
Raw Blame
import type { Page } from 'puppeteer'

import {
    PLAYER_CONFIG_KEY,
    PLAYER_EMIT_FN,
    PLAYER_FRAME_TIMELINE_KEY,
    PLAYER_NAVIGATION_KEY,
    PLAYER_START_EVENT,
} from '@posthog/replay-headless/protocol'
import type { InactivityPeriod, NavigationSample, PlayerConfig, PlayerMessage } from '@posthog/replay-headless/protocol'

import { RasterizationError, toRasterizationErrorCode } from '~/session-replay/recording-rasterizer/errors'
import { type Logger, createLogger } from '~/session-replay/recording-rasterizer/logger'

import { BlockSource } from './block-proxy'
import { CapturePage } from './capture-page'
import { RequestInterceptor } from './request-interceptor'

/**
 * Controls communication with the in-browser replay player.
 *
 * The player sends messages via {@link PLAYER_EMIT_FN} and receives
 * commands via custom DOM events. This class accumulates player state
 * so the capture loop can poll it without touching browser globals.
 */
export class PlayerController {
    private capturePage: CapturePage
    private log: Logger
    private interceptor: RequestInterceptor
    private onProgress: () => void

    private state = {
        ended: false,
        inactivityPeriods: [] as InactivityPeriod[],
        frameSessionMs: [] as number[],
    }

    private startedResolve: (() => void) | null = null
    private errorReject: ((err: RasterizationError) => void) | null = null
    private playbackError: RasterizationError | null = null
    private resetStaleTimer: (() => void) | null = null

    constructor(
        capturePage: CapturePage,
        blockProxy: BlockSource,
        teamId: number,
        onProgress: () => void,
        log: Logger = createLogger()
    ) {
        this.capturePage = capturePage
        this.log = log
        this.onProgress = onProgress
        this.interceptor = new RequestInterceptor(capturePage, blockProxy, teamId, this.log)
    }

    get page(): Page {
        return this.capturePage.page
    }

    get fatalError(): RasterizationError | null {
        return this.capturePage.fatalError
    }

    private toError(err: { code: string; message: string; retryable: boolean }): RasterizationError {
        // The code is browser-supplied — clamp it to the known set so downstream labels stay bounded.
        return new RasterizationError(`[${err.code}] ${err.message}`, err.retryable, toRasterizationErrorCode(err.code))
    }

    private rejectWithError(err: { code: string; message: string; retryable: boolean }): void {
        const rasterErr = this.toError(err)
        if (this.errorReject) {
            this.errorReject(rasterErr)
            this.errorReject = null
        } else {
            // No active promise to reject — store for polling during capture.
            this.playbackError = rasterErr
        }
    }

    private handleMessage(msg: PlayerMessage): void {
        switch (msg.type) {
            case 'loading_progress':
                this.resetStaleTimer?.()
                this.onProgress()
                this.log.info({ loaded: msg.loaded, total: msg.total }, 'loading blocks')
                break
            case 'started':
                this.startedResolve?.()
                this.startedResolve = null
                break
            case 'ended':
                this.state.ended = true
                break
            case 'error':
                this.rejectWithError(msg)
                break
            case 'inactivity_periods':
                this.state.inactivityPeriods = msg.periods
                break
            case 'frame_timeline':
                this.state.frameSessionMs = msg.frameSessionMs
                break
        }
    }

    /**
     * Wait for `promise` to resolve, but reject if `ms` elapses or the
     * player sends an error. When `resetOnProgress` is true the timer
     * resets on each loading_progress message — so we only time out when
     * progress stalls, not when loading takes a long time overall.
     */
    private awaitWithTimeout(
        promise: Promise<void>,
        ms: number,
        timeoutMsg: string,
        resetOnProgress = false
    ): Promise<void> {
        // An error emitted before this registers errorReject (e.g. NO_SNAPSHOTS arriving between
        // load() and waitForStart()) was shelved in playbackError; without this check it would sit
        // there while we idle out and misreport a retryable TIMEOUT over the real, possibly
        // terminal, code.
        if (this.playbackError) {
            return Promise.reject(this.playbackError)
        }
        return new Promise<void>((resolve, reject) => {
            const onTimeout = (): void => {
                this.startedResolve = null
                this.errorReject = null
                this.resetStaleTimer = null
                reject(new RasterizationError(timeoutMsg, true, 'TIMEOUT'))
            }

            const cleanup = (): void => {
                clearTimeout(timer)
                this.startedResolve = null
                this.errorReject = null
                this.resetStaleTimer = null
            }

            let timer = setTimeout(onTimeout, ms)
            this.errorReject = (err) => {
                cleanup()
                reject(err)
            }

            if (resetOnProgress) {
                this.resetStaleTimer = () => {
                    clearTimeout(timer)
                    timer = setTimeout(onTimeout, ms)
                }
            }

            void promise
                .then(() => {
                    cleanup()
                    resolve()
                })
                .catch((err) => {
                    // Outer promise already settled (timeout or error). Log for debugging.
                    this.log.debug({ error: (err as Error)?.message }, 'secondary rejection after settlement')
                })
        })
    }

    /** Wrap timer/rAF callbacks in try/catch so player JS errors don't kill capture. */
    async installCallbackErrorGuards(): Promise<void> {
        await this.capturePage.installCallbackErrorGuards()
    }

    /** Resolves when all tracked stylesheet requests have a response. */
    waitForSettled(): Promise<void> {
        return this.interceptor.waitForSettled()
    }

    /**
     * Install CDP guards that override screenshot format and gate
     * beginFrame on pending stylesheet requests. Must be called
     * after the player is loaded and before captureVideo().
     */
    prepareBrowserForCapture(screenshotFormat: 'jpeg' | 'png', screenshotQuality: number | undefined): void {
        this.capturePage.installCDPGuards(screenshotFormat, screenshotQuality, () => this.waitForSettled(), this.log)
    }

    /** Install request interception, set up the message bridge, and navigate. */
    async load(playerConfig: PlayerConfig): Promise<void> {
        const page = this.capturePage.page
        await this.interceptor.install()

        await page.exposeFunction(PLAYER_EMIT_FN, (msg: PlayerMessage) => {
            this.handleMessage(msg)
        })

        // Inject config as a window global before the page loads — the
        // browser-side HostBridge reads it synchronously on startup.
        await page.evaluateOnNewDocument(
            (key, config) => {
                ;(window as any)[key] = config
            },
            PLAYER_CONFIG_KEY,
            playerConfig
        )

        try {
            await page.goto(this.capturePage.playerUrl, { waitUntil: 'load', timeout: 30000 })
        } catch (err) {
            // Puppeteer's TimeoutError would classify as UNKNOWN downstream; it is the same failure
            // mode as every other load stall, so give it the same retryable TIMEOUT code.
            if ((err as Error)?.name === 'TimeoutError') {
                throw new RasterizationError('player page load timed out', true, 'TIMEOUT', err)
            }
            throw err
        }
        this.log.info({ origin: this.capturePage.playerUrl }, 'player loaded')
    }

    /**
     * Wait for the player to finish loading and signal started.
     * Times out if no loading_progress arrives within `staleMs`.
     */
    async waitForStart(playerConfig: PlayerConfig, staleMs = 15000): Promise<void> {
        const startedPromise = new Promise<void>((resolve) => {
            this.startedResolve = resolve
        })
        await this.awaitWithTimeout(
            startedPromise,
            staleMs,
            `Recording did not start for session ${playerConfig.sessionId} (no progress for ${staleMs / 1000}s)`,
            true
        )

        this.log.info('loading complete')
    }

    async startPlayback(): Promise<void> {
        const startEvent = PLAYER_START_EVENT
        await this.capturePage.page.evaluate((evt) => {
            window.dispatchEvent(new Event(evt))
        }, startEvent)
    }

    isEnded(): boolean {
        return this.state.ended
    }

    getError(): RasterizationError | null {
        return this.playbackError
    }

    getInactivityPeriods(): InactivityPeriod[] {
        return this.state.inactivityPeriods
    }

    getFrameSessionMs(): number[] {
        return this.state.frameSessionMs
    }

    /** Read the frame timeline off the page. Works for a capture that was trimmed or timed out, where
     * the replayer never finished and so never pushed it. Falls back to whatever was pushed. */
    async readFrameTimeline(): Promise<number[]> {
        const samples = await this.readPageArray<number>(PLAYER_FRAME_TIMELINE_KEY)
        // Empty when the page is already gone: use whatever the player managed to push before teardown.
        return samples.length > 0 ? samples : this.state.frameSessionMs
    }

    async readNavigation(): Promise<NavigationSample[]> {
        return this.readPageArray<NavigationSample>(PLAYER_NAVIGATION_KEY)
    }

    private async readPageArray<T>(key: string): Promise<T[]> {
        try {
            return await this.capturePage.page.evaluate(
                (windowKey: string) => (window as unknown as Record<string, T[]>)[windowKey] ?? [],
                key
            )
        } catch {
            return []
        }
    }

    dispose(): void {
        this.startedResolve = null
        this.errorReject = null
        this.playbackError = null
        this.resetStaleTimer = null
    }
}