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.

8.7 KB
Raw Blame
import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'

import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { liveEventsHostOrigin } from 'lib/utils/apiHost'
import { hogql } from 'lib/utils/hogql'
import { teamLogic } from 'scenes/teamLogic'

import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { TeamPublicType, TeamType } from '../../../types'
import { LIVE_COUNT_REFRESH_MS, loadCachedLiveCount } from './liveCountCache'

const LIVE_USERS_COUNT_QUERY = hogql`
    SELECT uniq(distinct_id)
    FROM events
    WHERE timestamp > now() - INTERVAL 1 MINUTE
        AND timestamp < now() + INTERVAL 1 MINUTE`

export interface LiveUserCountStats {
    users_on_product?: number
}

export interface LiveUserCountLogicProps {
    pollIntervalMs?: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface liveUserCountLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    isHovering: boolean
    liveUserCount: number | null
    now: Date | null
    stats: LiveUserCountStats | null
    statsUpdatedSecondsAgo: number | null
    statsUpdatedTime: Date | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface liveUserCountLogicActions {
    setFeatureFlags: (
        flags: string[],
        variants: Record<string, boolean | string>
    ) => {
        flags: string[]
        variants: Record<string, boolean | string>
    } // featureFlagLogic
    loadCurrentTeamSuccess: (
        currentTeam: TeamPublicType | null,
        payload?: any
    ) => {
        currentTeam: TeamPublicType | null
        payload?: any
    } // teamLogic
    pauseStream: () => {
        value: true
    }
    pollStats: () => {
        value: true
    }
    resumeStream: () => {
        value: true
    }
    setIsHovering: (isHovering: boolean) => {
        isHovering: boolean
    }
    setNow: (now: Date) => {
        now: Date
    }
    setStats: (
        stats: LiveUserCountStats,
        now: Date
    ) => {
        now: Date
        stats: LiveUserCountStats
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface liveUserCountLogicMeta {
    key: number
    __keaTypeGenInternalSelectorTypes: {
        liveUserCount: (stats: LiveUserCountStats | null) => number | null
        statsUpdatedSecondsAgo: (statsUpdatedTime: Date | null, now: Date | null) => number | null
    }
}

export type liveUserCountLogicType = MakeLogicType<
    liveUserCountLogicValues,
    liveUserCountLogicActions,
    LiveUserCountLogicProps,
    liveUserCountLogicMeta
>

export const liveUserCountLogic = kea<liveUserCountLogicType>([
    path((key) => ['lib', 'components', 'LiveUserCount', 'liveUserCountLogic', key]),
    key((props) => props.pollIntervalMs ?? 30000),
    props({ pollIntervalMs: 30000 } as LiveUserCountLogicProps),
    connect(() => ({
        values: [teamLogic, ['currentTeam'], featureFlagLogic, ['featureFlags']],
        actions: [featureFlagLogic, ['setFeatureFlags'], teamLogic, ['loadCurrentTeamSuccess']],
    })),
    actions(() => ({
        pollStats: true,
        setStats: (stats: LiveUserCountStats, now: Date) => ({ stats, now }),
        setNow: (now: Date) => ({ now }),
        setIsHovering: (isHovering: boolean) => ({ isHovering }),
        pauseStream: true,
        resumeStream: true,
    })),
    reducers({
        stats: [
            null as LiveUserCountStats | null,
            {
                setStats: (_, { stats }) => stats,
            },
        ],
        statsUpdatedTime: [
            null as Date | null,
            {
                setStats: (_, { now }) => now,
            },
        ],
        now: [
            null as Date | null,
            {
                setNow: (_, { now }) => now,
                setStats: (_, { now }) => now,
            },
        ],
        isHovering: [
            false,
            {
                setIsHovering: (_, { isHovering }) => isHovering,
            },
        ],
    }),
    selectors({
        liveUserCount: [(s) => [s.stats], (stats: LiveUserCountStats | null) => stats?.users_on_product ?? null],
        statsUpdatedSecondsAgo: [
            (s) => [s.statsUpdatedTime, s.now],
            (statsUpdatedTime: Date | null, now: Date | null) => {
                if (!statsUpdatedTime || !now) {
                    return null
                }
                const seconds = Math.ceil((now.getTime() - statsUpdatedTime.getTime()) / 1000)
                if (seconds < 0 || seconds >= 300) {
                    return null
                }
                return seconds
            },
        ],
    }),
    listeners(({ actions, values, cache, props }) => ({
        pollStats: async () => {
            try {
                if (!values.currentTeam) {
                    return
                }

                if (values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL]) {
                    let nextPollMs = LIVE_COUNT_REFRESH_MS
                    try {
                        const { value, fetchedAt } = await loadCachedLiveCount(
                            'users',
                            values.currentTeam.id,
                            LIVE_USERS_COUNT_QUERY,
                            { productKey: 'product_analytics', name: 'live_users_count' }
                        )
                        if (cache.disposables.isDisposed) {
                            return
                        }
                        actions.setStats({ users_on_product: value }, new Date(fetchedAt))
                        nextPollMs = Math.max(0, fetchedAt + LIVE_COUNT_REFRESH_MS - Date.now())
                    } finally {
                        if (!cache.statsPaused && cache.usesHogql) {
                            cache.disposables.add(() => {
                                const timeoutId = setTimeout(() => actions.pollStats(), nextPollMs)
                                return () => clearTimeout(timeoutId)
                            }, 'statsInterval')
                        }
                    }
                    return
                }

                const response = await fetch(`${liveEventsHostOrigin()}/stats`, {
                    headers: {
                        Authorization: `Bearer ${values.currentTeam.live_events_token}`,
                    },
                })
                const data: LiveUserCountStats = await response.json()
                actions.setStats(data, new Date())
            } catch (error) {
                console.error('Failed to poll stats:', error)
            }
        },
        setIsHovering: ({ isHovering }) => {
            if (isHovering) {
                actions.setNow(new Date())
                cache.disposables.add(() => {
                    const intervalId = setInterval(() => {
                        actions.setNow(new Date())
                    }, 500)
                    return () => clearInterval(intervalId)
                }, 'nowInterval')
            } else {
                cache.disposables.dispose('nowInterval')
            }
        },
        pauseStream: () => {
            cache.statsPaused = true
            cache.disposables.dispose('statsInterval')
        },
        loadCurrentTeamSuccess: () => {
            // pollStats returns early without a team, so in HogQL mode no next poll is scheduled until the team loads.
            if (!cache.statsPaused && values.stats === null) {
                actions.pollStats()
            }
        },
        setFeatureFlags: () => {
            // Each mode schedules its polls differently, so a mode change needs a fresh scheduler.
            if (!cache.statsPaused && !!values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL] !== cache.usesHogql) {
                actions.resumeStream()
            }
        },
        resumeStream: () => {
            cache.statsPaused = false
            cache.usesHogql = !!values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL]
            actions.pollStats()
            if (cache.usesHogql) {
                // pollStats schedules its own next run from the cached fetch time.
                return
            }
            cache.disposables.add(() => {
                const intervalId = setInterval(() => {
                    actions.pollStats()
                }, props.pollIntervalMs ?? 30000)
                return () => clearInterval(intervalId)
            }, 'statsInterval')
        },
    })),
    events(({ actions }) => ({
        afterMount: () => {
            actions.setNow(new Date())
            actions.resumeStream()
        },
    })),
])