Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

12.7 KB
Raw Blame
import { z } from "zod";
import { addMinutes, format } from "date-fns";

// Time-range presets, table aggregation options, and the TimeRange type
// moved to @langfuse/shared (utils/dateRanges); re-exported here for the
// existing web import surface.
export {
  TIME_RANGES,
  TABLE_AGGREGATION_OPTIONS,
  type TableDateRangeAggregationOption,
  type AbsoluteTimeRange,
  type TimeRange,
  rangeToString,
} from "@langfuse/shared";
import {
  TIME_RANGES,
  TABLE_AGGREGATION_OPTIONS,
  type TableDateRangeAggregationOption,
  type TimeRange,
  type TimeRangeDefinition,
  type AbsoluteTimeRange,
} from "@langfuse/shared";

const ABBREVIATION_TO_KEY = new Map(
  Object.entries(TIME_RANGES).map(([key, def]) => [def.abbreviation, key]),
);

export const DEFAULT_DASHBOARD_AGGREGATION_SELECTION = "last1Day" as const;

export const DASHBOARD_AGGREGATION_OPTIONS = [
  "last5Minutes",
  "last30Minutes",
  "last1Hour",
  "last3Hours",
  "last1Day",
  "last7Days",
  "last30Days",
  "last90Days",
  "last1Year",
] as const;

export type DashboardDateRangeAggregationOption =
  (typeof DASHBOARD_AGGREGATION_OPTIONS)[number];

export type TableDateRange = {
  from: Date;
  to?: Date;
};

type DateRangeAggregationOption =
  | DashboardDateRangeAggregationOption
  | TableDateRangeAggregationOption;

export type DashboardDateRangeOptions =
  | DashboardDateRangeAggregationOption
  | "custom";

export type DashboardDateRangeAggregationSettings = Record<
  DashboardDateRangeAggregationOption,
  TimeRangeDefinition
>;

export const dashboardDateRangeAggregationSettings: DashboardDateRangeAggregationSettings =
  Object.fromEntries(
    DASHBOARD_AGGREGATION_OPTIONS.map((option) => [
      option,
      TIME_RANGES[option as keyof typeof TIME_RANGES],
    ]),
  ) as DashboardDateRangeAggregationSettings;

export const SelectedTimeOptionSchema = z
  .discriminatedUnion("filterSource", [
    z.object({
      filterSource: z.literal("TABLE"),
      option: z.enum(TABLE_AGGREGATION_OPTIONS),
    }),
    z.object({
      filterSource: z.literal("DASHBOARD"),
      option: z.enum(DASHBOARD_AGGREGATION_OPTIONS),
    }),
  ])
  .optional();

export const isDashboardDateRangeOptionAvailable = ({
  option,
  limitDays,
}: {
  option: DashboardDateRangeAggregationOption;
  limitDays: number | false;
}) => {
  if (limitDays === false) return true;

  const { minutes } = dashboardDateRangeAggregationSettings[option];
  if (!minutes) return true; // Handle null minutes (like allTime)
  return limitDays >= minutes / (24 * 60);
};

type SelectedTimeOption = z.infer<typeof SelectedTimeOptionSchema>;

const TABLE_DATE_RANGE_AGGREGATION_SETTINGS = new Map<
  TableDateRangeAggregationOption,
  number | null
>(
  TABLE_AGGREGATION_OPTIONS.map((option) => [
    option,
    TIME_RANGES[option].minutes,
  ]),
);

export const getDateFromOption = (
  selectedTimeOption: SelectedTimeOption,
): Date | undefined => {
  if (!selectedTimeOption) return undefined;

  const { filterSource, option } = selectedTimeOption;
  if (filterSource === "TABLE") {
    const setting = TABLE_DATE_RANGE_AGGREGATION_SETTINGS.get(option);
    if (!setting) return undefined;

    return addMinutes(new Date(), -setting);
  } else if (filterSource === "DASHBOARD") {
    const setting =
      dashboardDateRangeAggregationSettings[
        option as keyof typeof dashboardDateRangeAggregationSettings
      ];

    if (!setting.minutes) return undefined; // Handle null minutes (like allTime)
    return addMinutes(new Date(), -setting.minutes);
  }
  return undefined;
};

function getFullTimeRangeFromAbbreviated(
  abbreviated: string,
): DateRangeAggregationOption | null {
  return (
    (ABBREVIATION_TO_KEY.get(abbreviated) as DateRangeAggregationOption) || null
  );
}

export function getTimeRangeLabel(option: string): string {
  return TIME_RANGES[option as keyof typeof TIME_RANGES]?.label || option;
}

export const findClosestDashboardInterval = (
  dateRange: AbsoluteTimeRange,
): DashboardDateRangeAggregationOption | undefined => {
  if (!dateRange.from || !dateRange.to) return undefined;
  const duration = dateRange.to.getTime() - dateRange.from.getTime();

  const diffs = DASHBOARD_AGGREGATION_OPTIONS.map((interval) => {
    const { minutes } = dashboardDateRangeAggregationSettings[interval];
    return {
      interval,
      diff: Math.abs(duration - minutes! * 60 * 1000),
    };
  });

  diffs.sort((a, b) => a.diff - b.diff);

  return diffs[0]?.interval;
};

// Helper function to check if time represents full day
const isFullDay = (date: Date) => {
  return (
    date.getHours() === 0 && date.getMinutes() === 0 && date.getSeconds() === 0
  );
};

// Helper function to check if date range represents full days
const isFullDayRange = (from: Date, to: Date) => {
  return (
    isFullDay(from) &&
    to.getHours() === 23 &&
    to.getMinutes() === 59 &&
    to.getSeconds() === 59
  );
};

// Format date range with smart year display and time inclusion
export const formatDateRange = (from: Date, to: Date) => {
  const currentYear = new Date().getFullYear();
  const fromYear = from.getFullYear();
  const toYear = to.getFullYear();

  const showFromYear = fromYear !== currentYear;
  const showToYear = toYear !== currentYear;

  if (isFullDayRange(from, to)) {
    // Show just dates for full day ranges
    const fromPattern = showFromYear ? "LLL dd, yyyy" : "LLL dd";
    const toPattern = showToYear ? "LLL dd, yyyy" : "LLL dd";
    return `${format(from, fromPattern)} - ${format(to, toPattern)}`;
  }
  // Show dates with times for partial day ranges
  const fromPattern = showFromYear ? "LLL dd yyyy, HH:mm" : "LLL dd, HH:mm";
  const toPattern = showToYear ? "LLL dd yyyy, HH:mm" : "LLL dd, HH:mm";
  return `${format(from, fromPattern)} - ${format(to, toPattern)}`;
};

/**
 * =======================
 * Interval Configuration
 * =======================
 */

/**
 * Supported interval units for time series aggregation
 */
type IntervalUnit = "second" | "minute" | "hour" | "day" | "month" | "year";

/**
 * Interval configuration with count and unit
 * Used for ClickHouse INTERVAL N UNIT queries
 */
export type IntervalConfig = {
  count: number;
  unit: IntervalUnit;
};

/**
 * Allowed intervals - only "clean" values to avoid crooked numbers
 * These are the only intervals that can be selected by the algorithm
 */
const ALLOWED_INTERVALS: readonly IntervalConfig[] = [
  // Seconds
  { count: 1, unit: "second" },
  { count: 5, unit: "second" },
  { count: 10, unit: "second" },
  { count: 30, unit: "second" },
  // Minutes
  { count: 1, unit: "minute" },
  { count: 5, unit: "minute" },
  { count: 10, unit: "minute" },
  { count: 30, unit: "minute" },
  // Hours
  { count: 1, unit: "hour" },
  { count: 3, unit: "hour" },
  { count: 6, unit: "hour" },
  { count: 12, unit: "hour" },
  // Days
  { count: 1, unit: "day" },
  { count: 2, unit: "day" },
  { count: 5, unit: "day" },
  { count: 7, unit: "day" },
  { count: 14, unit: "day" },
  // Months
  { count: 1, unit: "month" },
  { count: 3, unit: "month" },
  { count: 6, unit: "month" },
  // Years
  { count: 1, unit: "year" },
] as const;

export const toAbsoluteTimeRange = (
  timeRange: TimeRange,
): AbsoluteTimeRange | null => {
  if ("from" in timeRange) {
    return timeRange;
  }

  const preset = TIME_RANGES[timeRange.range as keyof typeof TIME_RANGES];

  if (!preset?.minutes) {
    return null;
  }

  return {
    from: addMinutes(new Date(), -preset.minutes),
    to: new Date(),
  };
};

/**
 * =======================
 * Optimal Interval Selection
 * =======================
 */

/**
 * Convert interval configuration to approximate milliseconds
 * Note: Month and year use average durations for calculation purposes
 *
 * @param interval - The interval configuration
 * @returns Approximate duration in milliseconds
 */
function getIntervalDuration(interval: IntervalConfig): number {
  const { count, unit } = interval;

  const MS_PER_UNIT = {
    second: 1000,
    minute: 60 * 1000,
    hour: 60 * 60 * 1000,
    day: 24 * 60 * 60 * 1000,
    month: 30.44 * 24 * 60 * 60 * 1000, // Average month length
    year: 365.25 * 24 * 60 * 60 * 1000, // Account for leap years
  };

  return count * MS_PER_UNIT[unit];
}

/**
 * Select the optimal interval from ALLOWED_INTERVALS to achieve target data points
 *
 * Algorithm:
 * 1. Calculate duration between fromDate and toDate
 * 2. For each allowed interval, calculate how many data points it would produce
 * 3. Score each interval based on proximity to target range (10-16 points, prefer 13)
 * 4. Return the interval with the highest score
 *
 * @param fromDate - Start of the time range
 * @param toDate - End of the time range
 * @param targetPoints - Ideal number of data points (default: 13, middle of 10-16 range)
 * @param minPoints - Minimum acceptable data points (default: 10)
 * @param maxPoints - Maximum acceptable data points (default: 16)
 * @returns The optimal interval configuration
 */
export function getOptimalInterval(
  fromDate: Date,
  toDate: Date,
  targetPoints = 13,
  minPoints = 10,
  maxPoints = 16,
): IntervalConfig {
  const durationMs = toDate.getTime() - fromDate.getTime();

  // Edge case: invalid or zero duration
  if (durationMs <= 0) {
    return { count: 1, unit: "day" };
  }

  let bestInterval: IntervalConfig = { count: 1, unit: "day" };
  let bestScore = -Infinity;

  for (const interval of ALLOWED_INTERVALS) {
    const intervalMs = getIntervalDuration(interval);
    const dataPoints = Math.floor(durationMs / intervalMs) + 1;

    // Calculate score based on proximity to target range
    let score: number;

    if (dataPoints >= minPoints && dataPoints <= maxPoints) {
      // Within target range - prefer closer to targetPoints
      // Score from 0 to maxPoints (higher is better)
      score = maxPoints - Math.abs(dataPoints - targetPoints);
    } else if (dataPoints < minPoints) {
      // Below minimum - penalize heavily
      // The fewer points, the worse the score
      const deficit = minPoints - dataPoints;
      score = dataPoints - deficit * 2; // Double penalty for being below min
    } else {
      // Above maximum - penalize, but less severely than below minimum
      // Too many points is better than too few
      const excess = dataPoints - maxPoints;
      score = maxPoints - excess * 0.5; // Half penalty for being above max
    }

    // Update best interval if this one scores higher
    if (score > bestScore) {
      bestScore = score;
      bestInterval = interval;
    }
  }

  return bestInterval;
}

/**
 * Parses a string back to a range object with validation
 * - Handles both abbreviated ("7d") and full ("last7Days") named ranges
 * - Handles custom timestamp ranges ("1693872000000-1694131199999")
 * - Returns fallback if parsing fails or range is not in allowedRanges
 */
export function rangeFromString<T extends string>(
  abbreviatedRange: string,
  allowedRanges: readonly T[],
  fallback: T,
): TimeRange {
  // Named range
  const fullRange = getFullTimeRangeFromAbbreviated(abbreviatedRange);
  if (allowedRanges.includes(fullRange as T)) {
    return { range: fullRange as T };
  }

  // Try parsing as custom range
  try {
    const parts = abbreviatedRange.split("-");
    if (parts.length === 2) {
      const fromTimestamp = parseInt(parts[0], 10);
      const toTimestamp = parseInt(parts[1], 10);

      if (!isNaN(fromTimestamp) && !isNaN(toTimestamp)) {
        const from = new Date(fromTimestamp);
        const to = new Date(toTimestamp);

        // Validate dates
        if (!isNaN(from.getTime()) && !isNaN(to.getTime()) && from <= to) {
          return { from, to };
        }
      }
    }
  } catch {
    // Continue to fallback
  }

  return { range: fallback };
}

/**
 * Resolves the active time range from its two possible sources using the
 * presence-XOR rule (no merging):
 * - If the URL carries an explicit `dateRange` value, it wins outright — shared
 *   links are authoritative and we ignore the persisted preference.
 * - Otherwise we fall back to the per-user stored default (relative
 *   meta-format), so clean navigations keep the last chosen range.
 * - Otherwise the view's fallback preset.
 *
 * A stored value that is not valid for this view's `allowedRanges` (e.g. a
 * table-only preset surfacing on a dashboard) degrades to the fallback rather
 * than merging.
 */
export function resolveTimeRange<T extends string>(
  sources: { urlValue?: string | null; storedValue?: string | null },
  allowedRanges: readonly T[],
  fallback: T,
): TimeRange {
  const fromUrl =
    sources.urlValue != null && sources.urlValue !== ""
      ? sources.urlValue
      : null;
  const fromStorage =
    sources.storedValue != null && sources.storedValue !== ""
      ? sources.storedValue
      : null;

  const source = fromUrl ?? fromStorage;
  if (source == null) {
    return { range: fallback };
  }

  return rangeFromString(source, allowedRanges, fallback);
}

// Re-export fillTimeSeriesGaps from its own module