Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

8.5 KB
Raw Blame
import type { ReactNode } from "react";
import { useMemo } from "react";
import { t } from "ttag";

import { useListApiKeysQuery } from "metabase/admin/settings/api/api-key";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import {
  type PillTab,
  PillTabNavigation,
} from "metabase/common/components/PillTabNavigation";
import { useUrlState } from "metabase/common/hooks/use-url-state";
import { MonitorHeaderTitle } from "metabase/monitor/components/MonitorHeaderTitle";
import { MonitorMain } from "metabase/monitor/components/MonitorLayout";
import { Outlet, useLocation } from "metabase/router";
import { useSetting } from "metabase/settings";
import { Flex, Loader, Stack } from "metabase/ui";
import * as Urls from "metabase/urls";
import { NewQuestionButton } from "metabase-enterprise/monitor/ai-auditing/components/NewQuestionButton";
import { useAuditRowCount } from "metabase-enterprise/monitor/ai-auditing/hooks/useAuditRowCount";
import {
  ConversationFilters as ApiKeyUsageFilterBar,
  parseId,
  useFilterOptions,
} from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationFilters";
import { useAuditTable } from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/hooks/useAuditTable";
import {
  VIEW_API_KEY_USAGE,
  VIEW_GROUP_MEMBERS,
} from "metabase-enterprise/monitor/api-key-usage/constants";
import { useApiKeyUsageHasData } from "metabase-enterprise/monitor/api-key-usage/hooks/useApiKeyUsageHasData";
import { isKeyOutsideGroup } from "metabase-enterprise/monitor/api-key-usage/query-utils";
import { apiKeyUsageUrlStateConfig } from "metabase-enterprise/monitor/api-key-usage/url-state";

import { ApiKeyFilterSelect } from "./ApiKeyFilterSelect";
import { ApiKeyUsageEmptyState } from "./ApiKeyUsageEmptyState";
import {
  ApiKeyUsageContextProvider,
  type ApiKeyUsageContextValue,
} from "./context";

type RouteContentProps = {
  children: ReactNode;
  error: unknown;
  isInitialLoading: boolean;
};

function RouteContent({
  children,
  error,
  isInitialLoading,
}: RouteContentProps) {
  if (error !== undefined && error !== null) {
    return (
      <Flex mih="60vh" align="center" justify="center">
        <LoadingAndErrorWrapper loading={false} error={error} />
      </Flex>
    );
  }

  if (isInitialLoading) {
    return (
      <Flex mih="60vh" align="center" justify="center">
        <Loader size="lg" />
      </Flex>
    );
  }

  return children;
}

export function ApiKeyUsageSectionLayout() {
  const location = useLocation();
  const [
    { date, user, group, tenant, api_key, page, sort_column, sort_direction },
    { patchUrlState },
  ] = useUrlState(location, apiKeyUsageUrlStateConfig);

  const { dateFilter, userId, groupId, groupNoFilterValue, groupOptions } =
    useFilterOptions({ date, user, group, tenant });

  const { data: apiKeys } = useListApiKeysQuery();
  const selectedApiKey = useMemo(
    () => apiKeys?.find((apiKey) => apiKey.id === parseId(api_key)),
    [apiKeys, api_key],
  );
  // Group and API key work like State and City: Group is only ever set by the user, the key list
  // is narrowed to the chosen group, and picking another group clears a key that isn't in it. The
  // UI can't produce a key outside the group, but a stale or hand-edited URL can — ignore the key
  // then, rather than let the two filters silently return nothing.
  const keyOutsideGroup = isKeyOutsideGroup(selectedApiKey, groupId);
  const apiKeyId = keyOutsideGroup ? undefined : parseId(api_key);

  const hasPii = useSetting("analytics-pii-retention-enabled") === true;
  const usageAudit = useAuditTable(VIEW_API_KEY_USAGE);
  const groupMembersAudit = useAuditTable(VIEW_GROUP_MEMBERS);
  const tabCount = useAuditRowCount(usageAudit, { dateColumn: "occurred_at" });

  const dataSources = useMemo(
    () => ({
      provider: usageAudit.provider,
      table: usageAudit.table,
      groupMembersTable: groupMembersAudit.table,
    }),
    [usageAudit.provider, usageAudit.table, groupMembersAudit.table],
  );
  const chartFilters = useMemo(
    () => ({ dateFilter, apiKeyId, userId, groupId }),
    [apiKeyId, dateFilter, groupId, userId],
  );
  const sortingOptions = useMemo(
    () => ({ sort_column, sort_direction }),
    [sort_column, sort_direction],
  );

  const {
    isInitialLoading,
    isRefetching,
    hasData,
    count,
    error,
    tablesMissing,
  } = useApiKeyUsageHasData({
    ...dataSources,
    ...chartFilters,
    isLoadingTables: usageAudit.isLoading || groupMembersAudit.isLoading,
  });
  // `tablesMissing` wins over `hasData`: the charts and tables below can't do anything useful
  // with a null table either — they'd just sit on their own skeletons forever — so show the
  // empty state instead of rendering them once the lookup has settled as missing.
  const showEmpty =
    !isInitialLoading && !isRefetching && (!hasData || tablesMissing);

  const usagePath = Urls.monitorApiKeyUsageOverview();
  const eventsPath = Urls.monitorApiKeyUsageEvents();
  const tabs: PillTab[] = [
    {
      label: t`Usage`,
      to: `${usagePath}${location.search}`,
      isSelected: (pathname) => pathname === usagePath,
    },
    {
      label: t`Events`,
      count: tabCount,
      to: `${eventsPath}${location.search}`,
      isSelected: (pathname) => pathname === eventsPath,
    },
  ];

  const isTableRoute = location.pathname === eventsPath;
  const outletContext = useMemo<ApiKeyUsageContextValue>(
    () => ({
      dataSources,
      chartFilters,
      hasPii,
      page,
      total: count,
      onPageChange: (newPage) =>
        patchUrlState({ page: newPage }, { immediate: true }),
      sortingOptions,
      onSortingOptionsChange: (newSorting) =>
        patchUrlState({
          sort_column: newSorting.sort_column,
          sort_direction: newSorting.sort_direction,
          page: 0,
        }),
    }),
    [
      chartFilters,
      count,
      dataSources,
      hasPii,
      page,
      patchUrlState,
      sortingOptions,
    ],
  );

  // Tabs + filters stay outside the scrollable area below (rendered once per branch, same
  // elements, just never scrolled past) so they're always visible regardless of page length.
  const tabsAndFilters = (
    <>
      <PillTabNavigation tabs={tabs} />
      <Flex justify="space-between" align="center" gap="md">
        <ApiKeyUsageFilterBar
          date={date}
          onDateChange={(val) => patchUrlState({ date: val, page: 0 })}
          groupFilter={{
            value: group,
            options: groupOptions,
            noFilterValue: groupNoFilterValue,
            onChange: (val) =>
              patchUrlState({
                group: val,
                // Like picking a new State: a key that isn't in the new group is cleared.
                ...(isKeyOutsideGroup(
                  selectedApiKey,
                  val == null ? null : Number(val),
                )
                  ? { api_key: null }
                  : {}),
                page: 0,
              }),
          }}
          extraFilter={
            <ApiKeyFilterSelect
              value={keyOutsideGroup ? null : api_key}
              onChange={(val) => patchUrlState({ api_key: val, page: 0 })}
              groupId={groupId}
            />
          }
        />
        <NewQuestionButton viewName={VIEW_API_KEY_USAGE} />
      </Flex>
    </>
  );

  const pageContent = (
    <RouteContent
      error={error ?? usageAudit.error ?? groupMembersAudit.error}
      isInitialLoading={isInitialLoading}
    >
      {showEmpty ? (
        <ApiKeyUsageEmptyState />
      ) : (
        <ApiKeyUsageContextProvider value={outletContext}>
          <Outlet />
        </ApiKeyUsageContextProvider>
      )}
    </RouteContent>
  );

  if (isTableRoute) {
    return (
      <Flex h="100%" wrap="nowrap">
        <MonitorMain>
          <Stack gap="xl" flex={1} mih={0}>
            <MonitorHeaderTitle>{t`API key usage`}</MonitorHeaderTitle>
            {tabsAndFilters}
            <Stack
              gap="lg"
              flex={1}
              mih={0}
              display="flex"
              style={{ flexDirection: "column" }}
            >
              {pageContent}
            </Stack>
          </Stack>
        </MonitorMain>
      </Flex>
    );
  }

  return (
    <Flex h="100%" wrap="nowrap">
      <MonitorMain>
        <Stack gap="xl" flex={1} mih={0}>
          <MonitorHeaderTitle>{t`API key usage`}</MonitorHeaderTitle>
          {tabsAndFilters}
          <Stack gap="lg" flex={1} mih={0} style={{ overflowY: "auto" }}>
            {pageContent}
          </Stack>
        </Stack>
      </MonitorMain>
    </Flex>
  );
}