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.2 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    afterMount,
    kea,
    listeners,
    path,
    reducers,
    selectors,
    useMountedLogic,
    useSelector,
} from 'kea'
import { loaders } from 'kea-loaders'

import { teamLogic } from 'scenes/teamLogic'

import { signalsReportsPrCiStatuses } from 'products/signals/frontend/generated/api'
import type { PullRequestCiStatusEnumApi } from 'products/signals/frontend/generated/api.schemas'

/** CI state per report id. A report GitHub has not answered for is simply absent. */
export type PrCiStatusMap = Record<string, PullRequestCiStatusEnumApi>

/** How often the tracked pull requests are re-read while the inbox is open. */
export const PR_CI_STATUS_POLL_INTERVAL_MS = 60_000
/**
 * How long a state GitHub has stopped answering for is still shown. Two polls of slack ride out a
 * rate limit, and past that the glyph goes: a pill that keeps claiming a CI state nothing confirms
 * is worse than a pill with no glyph.
 */
export const PR_CI_STATUS_MAX_AGE_MS = 2 * PR_CI_STATUS_POLL_INTERVAL_MS
/** Reports one request may ask about, above which the endpoint rejects the list. */
export const PR_CI_STATUS_MAX_REPORTS = 100
/** Sections load independently, so their bursts coalesce into one load. */
const PR_CI_STATUS_DEBOUNCE_MS = 50

/** A resolved CI state and when GitHub last confirmed it, so a held state can age out. */
interface ConfirmedCiStatus {
    ciStatus: PullRequestCiStatusEnumApi
    confirmedAt: number
}

/** The announced rows, in requests no longer than the endpoint will answer for. */
function chunkReportIds(reportIds: string[]): string[][] {
    const chunks: string[][] = []
    for (let start = 0; start < reportIds.length; start += PR_CI_STATUS_MAX_REPORTS) {
        chunks.push(reportIds.slice(start, start + PR_CI_STATUS_MAX_REPORTS))
    }
    return chunks
}

/**
 * Whether two announcements cover the same rows. Both lists are deduplicated, so length and
 * membership are enough, and neither list's order carries meaning.
 */
function coversSameReports(reportIds: string[], other: string[]): boolean {
    return reportIds.length === other.length && reportIds.every((reportId) => other.includes(reportId))
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface prCiStatusLogicValues {
    ciStatusByReportId: PrCiStatusMap
    ciStatusByReportIdLoading: boolean
    requestedReportIds: string[]
    trackedReportIds: string[]
    trackedReportIdsBySource: Record<string, string[]>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface prCiStatusLogicActions {
    loadCiStatuses: ({ reportIds }: { reportIds: string[] }) => {
        reportIds: string[]
    }
    loadCiStatusesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadCiStatusesSuccess: (
        ciStatusByReportId: {
            [k: string]: PullRequestCiStatusEnumApi
        },
        payload?: {
            reportIds: string[]
        }
    ) => {
        ciStatusByReportId: {
            [k: string]: PullRequestCiStatusEnumApi
        }
        payload?: {
            reportIds: string[]
        }
    }
    trackReports: (
        source: string,
        reportIds: string[]
    ) => {
        reportIds: string[]
        source: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface prCiStatusLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        trackedReportIds: (trackedReportIdsBySource: Record<string, string[]>) => string[]
    }
}

export type prCiStatusLogicType = MakeLogicType<
    prCiStatusLogicValues,
    prCiStatusLogicActions,
    Record<string, any>,
    prCiStatusLogicMeta
>

/**
 * CI state of the implementation pull requests the report lists show, so a reader scanning the inbox
 * can see which pull requests are red without opening each report in turn.
 *
 * Shared rather than keyed: every report section paints the same pill, and the flat list merges
 * several sections, so one map serves them all and a report listed twice costs one lookup. Sections
 * announce the reports they show through `trackReports`; the backend resolves each request's set in
 * one batched GitHub read, and a poll keeps a running build's glyph moving while the inbox stays
 * open.
 */
export const prCiStatusLogic = kea<prCiStatusLogicType>([
    path(['scenes', 'inbox', 'logics', 'prCiStatusLogic']),

    actions({
        trackReports: (source: string, reportIds: string[]) => ({ source, reportIds }),
    }),

    loaders(({ cache }) => ({
        ciStatusByReportId: [
            {} as PrCiStatusMap,
            {
                loadCiStatuses: async ({ reportIds }: { reportIds: string[] }, breakpoint) => {
                    const teamId = teamLogic.values.currentTeamId
                    if (!teamId || reportIds.length === 0) {
                        cache.confirmedCiStatuses = {}
                        return {}
                    }
                    // The endpoint rejects a list longer than it will answer for, so a longer set is
                    // asked for in several requests instead of being cut short: a row on the third
                    // page a reader loaded needs its glyph as much as a row on the first.
                    const responses = await Promise.all(
                        chunkReportIds(reportIds).map((chunk) =>
                            signalsReportsPrCiStatuses(String(teamId), { report_ids: chunk.join(',') })
                        )
                    )
                    breakpoint()
                    const now = Date.now()
                    const confirmed: Record<string, ConfirmedCiStatus> = { ...cache.confirmedCiStatuses }
                    for (const entry of responses.flatMap((response) => response.statuses)) {
                        confirmed[entry.report_id] = { ciStatus: entry.ci_status, confirmedAt: now }
                    }
                    // Merge forward, then keep only the reports still on screen whose state is young
                    // enough: a pull request GitHub could not answer for this time holds the state it
                    // last had instead of losing its glyph for a poll, and a report that scrolled out
                    // is forgotten. A rate limit or revoked access leaves the same report out of every
                    // answer, so the state also expires, rather than claim a CI state for as long as
                    // the reader keeps the inbox open.
                    const kept = reportIds.filter(
                        (reportId) =>
                            reportId in confirmed && now - confirmed[reportId].confirmedAt <= PR_CI_STATUS_MAX_AGE_MS
                    )
                    cache.confirmedCiStatuses = Object.fromEntries(
                        kept.map((reportId) => [reportId, confirmed[reportId]])
                    )
                    return Object.fromEntries(kept.map((reportId) => [reportId, confirmed[reportId].ciStatus]))
                },
            },
        ],
    })),

    reducers({
        // Kept per announcing section, so a section that narrows its filter stops asking about rows it
        // no longer shows. Accumulating one flat set instead would keep every row a reader ever
        // scrolled past in the poll for as long as the inbox stayed open.
        trackedReportIdsBySource: [
            {} as Record<string, string[]>,
            {
                trackReports: (
                    state: Record<string, string[]>,
                    { source, reportIds }: { source: string; reportIds: string[] }
                ) => ({ ...state, [source]: reportIds }),
            },
        ],
        // What the last request covered, so a section re-rendering the same rows doesn't re-ask.
        requestedReportIds: [
            [] as string[],
            {
                loadCiStatuses: (_: string[], { reportIds }: { reportIds: string[] }) => reportIds,
            },
        ],
    }),

    selectors({
        // Every row the sections announce, deduplicated. Not capped to what one request carries: the
        // loader splits a longer set, so a reader who pages past the first hundred rows still gets
        // a glyph on the rest.
        trackedReportIds: [
            (s) => [s.trackedReportIdsBySource],
            (trackedReportIdsBySource: Record<string, string[]>): string[] =>
                Array.from(new Set(Object.values(trackedReportIdsBySource).flat())),
        ],
    }),

    listeners(({ actions, values }) => ({
        trackReports: async (_, breakpoint) => {
            // A section re-rendering the same rows must not re-ask. Any other set has to: a new row
            // has no state yet, and a row that left and came back may have gone stale while the poll
            // was not covering it. An empty set costs no request and clears the rows that left.
            if (coversSameReports(values.trackedReportIds, values.requestedReportIds)) {
                return
            }
            await breakpoint(PR_CI_STATUS_DEBOUNCE_MS)
            actions.loadCiStatuses({ reportIds: values.trackedReportIds })
        },
    })),

    afterMount(({ actions, values, cache }) => {
        // A build that goes red while someone is reading the list should show it. Auto-disposed on
        // unmount and paused on a hidden tab, so a backgrounded inbox costs GitHub nothing.
        cache.disposables.add(() => {
            const interval = setInterval(() => {
                if (values.trackedReportIds.length > 0) {
                    actions.loadCiStatuses({ reportIds: values.trackedReportIds })
                }
            }, PR_CI_STATUS_POLL_INTERVAL_MS)
            return () => clearInterval(interval)
        }, 'prCiStatusPoll')
    }),
])

/**
 * One row's CI state. A row must read only its own entry: subscribing to the whole map made every
 * card in the list repaint each time the minute poll answered, which is a few hundred cards of
 * React work for a glyph on one of them.
 */
export function useReportCiStatus(reportId: string | null): PullRequestCiStatusEnumApi | undefined {
    useMountedLogic(prCiStatusLogic)
    return useSelector((state) =>
        reportId ? prCiStatusLogic.selectors.ciStatusByReportId(state)[reportId] : undefined
    )
}