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.

1.5 KB
Raw Blame
import { Counter } from 'prom-client'

import { QuotaResource } from '../../common/services/quota-limiting.service'
import { HogFunctionMonitoringService } from '../services/monitoring/hog-function-monitoring.service'
import { CyclotronJobInvocationHogFunction } from '../types'

const counterQuotaLimited = new Counter({
    name: 'cdp_function_quota_limited',
    help: 'A function invocation was quota limited',
    labelNames: ['team_id'],
})

export interface QuotaLimitingContext {
    quotaLimiting: {
        isTeamQuotaLimited: (teamId: number, resource: QuotaResource) => Promise<boolean>
    }
    hogFunctionMonitoringService: HogFunctionMonitoringService
}

/**
 * Checks if an invocation should be quota limited and handles the appropriate metrics.
 * Returns true if the invocation should be blocked, false otherwise.
 */
export async function shouldBlockInvocationDueToQuota(
    item: CyclotronJobInvocationHogFunction,
    context: QuotaLimitingContext
): Promise<boolean> {
    const isQuotaLimited = await context.quotaLimiting.isTeamQuotaLimited(item.teamId, 'cdp_trigger_events')

    if (isQuotaLimited) {
        counterQuotaLimited.labels({ team_id: item.teamId }).inc()

        context.hogFunctionMonitoringService.queueAppMetric(
            {
                team_id: item.teamId,
                app_source_id: item.functionId,
                metric_kind: 'failure',
                metric_name: 'quota_limited',
                count: 1,
            },
            'hog_function'
        )
        return true
    }

    return false
}