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.

2.6 KB
Raw Blame
import api from 'lib/api'
import { HogQLQueryString } from 'lib/utils/hogql'

import { QueryLogTags } from '~/queries/schema/schema-general'

export const LIVE_COUNT_REFRESH_MS = 30000
// pinned: localStorage key prefix, renaming it drops every user's cached counts
const STORAGE_KEY_PREFIX = 'live-count-hogql-'

export interface CachedLiveCount {
    value: number
    fetchedAt: number
}

// Several counters can mount at once, so they share one in-flight query per key.
const inflightByKey = new Map<string, Promise<CachedLiveCount>>()
// Fallback for when localStorage is disabled or full.
const memoryCacheByKey = new Map<string, CachedLiveCount>()

function isCachedLiveCount(value: unknown): value is CachedLiveCount {
    const candidate = value as Partial<CachedLiveCount> | null
    return Number.isFinite(candidate?.value) && Number.isFinite(candidate?.fetchedAt)
}

function readCachedLiveCount(storageKey: string): CachedLiveCount | null {
    try {
        const raw = localStorage.getItem(storageKey)
        const parsed: unknown = raw ? JSON.parse(raw) : null
        if (isCachedLiveCount(parsed)) {
            return parsed
        }
    } catch {
        // Fall through to the in-memory copy.
    }
    return memoryCacheByKey.get(storageKey) ?? null
}

/** Runs a single-value HogQL count, reusing a result younger than LIVE_COUNT_REFRESH_MS across mounts and reloads. */
export async function loadCachedLiveCount(
    name: string,
    teamId: number,
    query: HogQLQueryString,
    tags: QueryLogTags
): Promise<CachedLiveCount> {
    const storageKey = `${STORAGE_KEY_PREFIX}${name}-${teamId}`
    const cached = readCachedLiveCount(storageKey)
    if (cached && Date.now() - cached.fetchedAt < LIVE_COUNT_REFRESH_MS) {
        return cached
    }
    let request = inflightByKey.get(storageKey)
    if (!request) {
        request = queryLiveCount(storageKey, query, tags).finally(() => inflightByKey.delete(storageKey))
        inflightByKey.set(storageKey, request)
    }
    return request
}

async function queryLiveCount(
    storageKey: string,
    query: HogQLQueryString,
    tags: QueryLogTags
): Promise<CachedLiveCount> {
    // The default refresh mode can serve a server-cached count that is older than the whole live window.
    const response = await api.queryHogQL<[number][]>(query, tags, { refresh: 'force_blocking' })
    const result: CachedLiveCount = { value: response.results?.[0]?.[0] ?? 0, fetchedAt: Date.now() }
    memoryCacheByKey.set(storageKey, result)
    try {
        localStorage.setItem(storageKey, JSON.stringify(result))
    } catch {
        // Storage can be full or disabled. The in-memory copy still serves reads.
    }
    return result
}