: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import posthog from 'posthog-js'
import type { GuardAvailableFeatureFn } from 'lib/components/UpgradeModal/upgradeModalLogic'
import { dayjs, Dayjs } from 'lib/dayjs'
import { AlertCalculationInterval } from '~/queries/schema/schema-general'
import { AvailableFeature, IntervalType } from '~/types'
export function evaluationDelayPreview(
interval: IntervalType,
delay: number,
timezone: string,
weekStartDay: number = 0,
now: Dayjs = dayjs()
): string {
const local = now.tz(timezone)
let start: Dayjs
let end: Dayjs
if (interval === 'hour' || interval === 'minute' || interval === 'second') {
const boundary = local
.utc()
.subtract(interval === 'hour' ? local.minute() : 0, 'minute')
.subtract(interval !== 'second' ? local.second() : 0, 'second')
.millisecond(0)
end = boundary.subtract(delay, interval).tz(timezone)
start = boundary.subtract(delay + 1, interval).tz(timezone)
} else {
const wallClock = dayjs.utc(local.format('YYYY-MM-DDTHH:mm:ss'))
const boundary =
interval === 'week'
? wallClock.startOf('day').subtract((wallClock.day() - weekStartDay + 7) % 7, 'day')
: wallClock.startOf(interval)
start = dayjs.tz(boundary.subtract(delay + 1, interval).format('YYYY-MM-DDTHH:mm:ss'), timezone)
end = dayjs.tz(boundary.subtract(delay, interval).format('YYYY-MM-DDTHH:mm:ss'), timezone)
}
return `${start.format('MMM D, YYYY HH:mm Z')} to ${end.format('MMM D, YYYY HH:mm Z')}`
}
export function getDefaultSimulationRange(interval: AlertCalculationInterval): string {
switch (interval) {
case AlertCalculationInterval.REAL_TIME:
return '-1h'
case AlertCalculationInterval.EVERY_15_MINUTES:
return '-12h'
case AlertCalculationInterval.HOURLY:
return '-48h'
case AlertCalculationInterval.DAILY:
return '-30d'
case AlertCalculationInterval.WEEKLY:
return '-12w'
case AlertCalculationInterval.MONTHLY:
return '-12m'
}
}
export const HIGH_FREQUENCY_ALERTS_REQUIRED_MESSAGE =
'15-minute alert intervals require a Boost, Scale, or Enterprise platform add-on.'
const SUB_DAILY_INTERVALS = [
AlertCalculationInterval.HOURLY,
AlertCalculationInterval.EVERY_15_MINUTES,
AlertCalculationInterval.REAL_TIME,
]
export function isSubDailyAlertInterval(interval: AlertCalculationInterval): boolean {
return SUB_DAILY_INTERVALS.includes(interval)
}
export function canSetAlertScheduleStartTime(interval: AlertCalculationInterval): boolean {
return interval === AlertCalculationInterval.HOURLY
}
export function scheduleStartTimeForInterval(
interval: AlertCalculationInterval,
scheduleStartTime: string | null | undefined
): string | null {
return canSetAlertScheduleStartTime(interval) ? (scheduleStartTime ?? null) : null
}
export function getAlertScheduleStartMinute(scheduleStartTime: string | null | undefined): number | undefined {
if (!scheduleStartTime) {
return undefined
}
return Number(scheduleStartTime.split(':')[1])
}
export function scheduleStartTimeForMinute(minute: number | null | undefined): string | null {
if (minute === null || minute === undefined || !Number.isInteger(minute) || minute < 0 || minute > 59) {
return null
}
return `00:${String(minute).padStart(2, '0')}`
}
const INTERVAL_DISPLAY_LABELS: Record<AlertCalculationInterval, string> = {
[AlertCalculationInterval.REAL_TIME]: 'Real time',
[AlertCalculationInterval.EVERY_15_MINUTES]: 'Every 15 minutes',
[AlertCalculationInterval.HOURLY]: 'Hourly',
[AlertCalculationInterval.DAILY]: 'Daily',
[AlertCalculationInterval.WEEKLY]: 'Weekly',
[AlertCalculationInterval.MONTHLY]: 'Monthly',
}
export function alertIntervalDisplayLabel(interval: AlertCalculationInterval): string {
return INTERVAL_DISPLAY_LABELS[interval]
}
// Twin of _CADENCE_DURATION_MINUTES / _INTERVAL_DURATION_MINUTES in
// products/alerts/backend/evaluation/validation.py — keep the two in sync.
const CADENCE_DURATION_MINUTES: Record<AlertCalculationInterval, number> = {
[AlertCalculationInterval.REAL_TIME]: 2,
[AlertCalculationInterval.EVERY_15_MINUTES]: 15,
[AlertCalculationInterval.HOURLY]: 60,
[AlertCalculationInterval.DAILY]: 60 * 24,
[AlertCalculationInterval.WEEKLY]: 60 * 24 * 7,
[AlertCalculationInterval.MONTHLY]: 60 * 24 * 30,
}
export function alertCadenceMinutes(interval: AlertCalculationInterval): number {
return CADENCE_DURATION_MINUTES[interval]
}
const INSIGHT_INTERVAL_DURATION_MINUTES: Record<IntervalType, number> = {
second: 1 / 60,
minute: 1,
hour: 60,
day: 60 * 24,
week: 60 * 24 * 7,
month: 60 * 24 * 30,
quarter: 60 * 24 * 30 * 3,
year: 60 * 24 * 365,
}
/** An alert re-checks the insight's last completed bucket, whose size is the insight's grouping
* interval. A cadence finer than that bucket re-reads the same frozen value until the bucket closes,
* so evaluating the ongoing (incomplete) bucket is what makes the faster cadence meaningful. */
export function cadenceFinerThanInsightInterval(
cadence: AlertCalculationInterval,
insightInterval: string | null | undefined
): boolean {
const insightMinutes =
INSIGHT_INTERVAL_DURATION_MINUTES[(insightInterval as IntervalType | null) ?? 'day'] ??
INSIGHT_INTERVAL_DURATION_MINUTES.day
return alertCadenceMinutes(cadence) < insightMinutes
}
type EntitlementResult =
| { blocked: true; message: string; feature: AvailableFeature }
| { blocked: false; message: null; feature: null }
export function blockSubmitWithoutEntitlement(
interval: AlertCalculationInterval,
{
hasHighFrequencyAlertsEntitlement,
hasRealTimeAlertsEntitlement,
}: { hasHighFrequencyAlertsEntitlement: boolean; hasRealTimeAlertsEntitlement: boolean }
): EntitlementResult {
if (interval === AlertCalculationInterval.EVERY_15_MINUTES && !hasHighFrequencyAlertsEntitlement) {
return {
blocked: true,
message: HIGH_FREQUENCY_ALERTS_REQUIRED_MESSAGE,
feature: AvailableFeature.HIGH_FREQUENCY_ALERTS,
}
}
if (interval === AlertCalculationInterval.REAL_TIME && !hasRealTimeAlertsEntitlement) {
return {
blocked: true,
message: 'Real-time alert intervals require a Scale or Enterprise plan.',
feature: AvailableFeature.REAL_TIME_ALERTS,
}
}
return { blocked: false, message: null, feature: null }
}
export function selectAlertCalculationInterval(
value: AlertCalculationInterval,
{
guardAvailableFeature,
onSelect,
hasHighFrequencyAlertsEntitlement,
hasRealTimeAlertsEntitlement,
}: {
guardAvailableFeature: GuardAvailableFeatureFn
onSelect: (interval: AlertCalculationInterval) => void
hasHighFrequencyAlertsEntitlement: boolean
hasRealTimeAlertsEntitlement: boolean
}
): boolean {
if (value === AlertCalculationInterval.REAL_TIME) {
posthog.capture('alert real time interval selected', {
has_entitlement: hasRealTimeAlertsEntitlement,
})
return guardAvailableFeature(AvailableFeature.REAL_TIME_ALERTS, () => {
onSelect(value)
})
}
if (value === AlertCalculationInterval.EVERY_15_MINUTES) {
posthog.capture('alert 15 min interval selected', {
has_entitlement: hasHighFrequencyAlertsEntitlement,
})
return guardAvailableFeature(AvailableFeature.HIGH_FREQUENCY_ALERTS, () => {
onSelect(value)
})
}
onSelect(value)
return true
}