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.

feat(data-warehouse): add data ops overview tab (#70572)

Eric Duong81b3f9ed5349
diff --git a/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx b/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx
index c9637d3d6a61..d15398a67f22 100644
--- a/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx
+++ b/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx
@@ -3,6 +3,7 @@ import { useActions, useValues } from 'kea'
import { NotFound } from 'lib/components/NotFound'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
+import { Spinner } from 'lib/lemon-ui/Spinner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
@@ -13,6 +14,7 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { DataWarehouseTab, dataWarehouseSceneLogic } from './dataWarehouseSceneLogic'
import { DataModelingTab } from './scene/DataModelingTab'
+import { OverviewTab } from './scene/OverviewTab'
import { SettingsTab } from './scene/SettingsTab'
export const scene: SceneExport = {
@@ -22,12 +24,15 @@ export const scene: SceneExport = {
}
const TAB_LABELS: Record<DataWarehouseTab, string> = {
+ [DataWarehouseTab.OVERVIEW]: 'Overview',
[DataWarehouseTab.SETTINGS]: 'Settings',
[DataWarehouseTab.MODELING]: 'Modeling',
}
function tabContent(tab: DataWarehouseTab): JSX.Element {
switch (tab) {
+ case DataWarehouseTab.OVERVIEW:
+ return <OverviewTab />
case DataWarehouseTab.SETTINGS:
return <SettingsTab />
case DataWarehouseTab.MODELING:
@@ -37,7 +42,7 @@ function tabContent(tab: DataWarehouseTab): JSX.Element {
export function DataWarehouseScene(): JSX.Element {
const { featureFlags } = useValues(featureFlagLogic)
- const { availableTabs, activeTab } = useValues(dataWarehouseSceneLogic)
+ const { availableTabs, activeTab, warehouseStatusResolved } = useValues(dataWarehouseSceneLogic)
const { setActiveTab } = useActions(dataWarehouseSceneLogic)
// Nothing to show without the scene flag, or when no tab's feature flag is enabled.
@@ -54,7 +59,14 @@ export function DataWarehouseScene(): JSX.Element {
type: sceneConfigurations[Scene.DataOps].iconType || 'default_icon_type',
}}
/>
- {availableTabs.length > 1 ? (
+ {/* Which tabs exist depends on whether a warehouse is ready, so wait for that rather
+ than rendering the setup form and then swapping it for tabs a moment later. */}
+ {!warehouseStatusResolved ? (
+ <div className="mt-4 flex items-center gap-2 text-muted">
+ <Spinner />
+ <span>Loading warehouse...</span>
+ </div>
+ ) : availableTabs.length > 1 ? (
<LemonTabs
activeKey={activeTab}
sceneInset
diff --git a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.test.ts b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.test.ts
index cac67d3fb1b1..e319ea2afe34 100644
--- a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.test.ts
@@ -1,8 +1,11 @@
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { urls } from 'scenes/urls'
+import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { DataWarehouseTab, dataWarehouseSceneLogic } from './dataWarehouseSceneLogic'
@@ -10,27 +13,78 @@ import { DataWarehouseTab, dataWarehouseSceneLogic } from './dataWarehouseSceneL
describe('dataWarehouseSceneLogic', () => {
let logic: ReturnType<typeof dataWarehouseSceneLogic.build>
let flagsLogic: ReturnType<typeof featureFlagLogic.build>
+ let warehouseStatusResponse: [number, Record<string, string>]
+
+ const mountScene = (): void => {
+ logic = dataWarehouseSceneLogic()
+ logic.mount()
+ }
+
+ const waitForWarehouseStatus = async (): Promise<void> => {
+ await expectLogic(logic).toDispatchActions(['loadWarehouseStatusSuccess'])
+ }
beforeEach(() => {
+ warehouseStatusResponse = [404, {}]
+ useMocks({
+ get: {
+ '/api/projects/:team_id/data_warehouse/warehouse_status/': () => warehouseStatusResponse,
+ },
+ })
initKeaTests()
flagsLogic = featureFlagLogic()
flagsLogic.mount()
- logic = dataWarehouseSceneLogic()
- logic.mount()
+ flagsLogic.actions.setFeatureFlags([FEATURE_FLAGS.DATA_WAREHOUSE_SCENE], {
+ [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]: true,
+ })
})
afterEach(() => {
- logic.unmount()
+ logic?.unmount()
flagsLogic.unmount()
})
- it('uses data-warehouse-scene to expose the managed warehouse settings tab', async () => {
- await expectLogic(flagsLogic, () => {
- flagsLogic.actions.setFeatureFlags([FEATURE_FLAGS.DATA_WAREHOUSE_SCENE], {
- [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]: true,
- })
- })
+ // Overview has nothing to report until a warehouse is actually serving. Until then the scene has
+ // to collapse to Settings alone, which is what renders the setup form (with no tab bar).
+ it.each([
+ { name: 'no warehouse provisioned', status: null, expectedTabs: [DataWarehouseTab.SETTINGS] },
+ {
+ name: 'warehouse still provisioning',
+ status: { state: 'provisioning' },
+ expectedTabs: [DataWarehouseTab.SETTINGS],
+ },
+ {
+ name: 'warehouse ready',
+ status: { state: 'ready' },
+ expectedTabs: [DataWarehouseTab.OVERVIEW, DataWarehouseTab.SETTINGS],
+ },
+ ])('$name', async ({ status, expectedTabs }) => {
+ warehouseStatusResponse = status ? [200, status] : [404, {}]
+ mountScene()
+ await waitForWarehouseStatus()
- expect(logic.values.availableTabs).toEqual([DataWarehouseTab.SETTINGS])
+ expect(logic.values.availableTabs).toEqual(expectedTabs)
+ expect(logic.values.activeTab).toBe(expectedTabs[0])
})
+
+ it('leaves the tab set unresolved until the warehouse status lands', () => {
+ warehouseStatusResponse = [200, { state: 'ready' }]
+ mountScene()
+
+ expect(logic.values.warehouseStatusResolved).toBe(false)
+ })
+
+ // The URL is parsed before the warehouse status arrives, so a requested tab has to survive the
+ // wait — clamping it against a tab list that doesn't include Overview yet would drop it.
+ it.each([[DataWarehouseTab.OVERVIEW], [DataWarehouseTab.SETTINGS]])(
+ 'honors a tab requested before the warehouse status resolves (%s)',
+ async (tab) => {
+ warehouseStatusResponse = [200, { state: 'ready' }]
+ mountScene()
+ router.actions.push(urls.dataOps(tab))
+ await waitForWarehouseStatus()
+
+ expect(logic.values.activeTab).toBe(tab)
+ }
+ )
})
diff --git a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts
index 3fb3eabd40f9..2d9d3f93460f 100644
--- a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts
+++ b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts
@@ -8,35 +8,58 @@ import { urls } from 'scenes/urls'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import type { dataWarehouseSceneLogicType } from './dataWarehouseSceneLogicType'
+import { warehouseProvisioningLogic } from './scene/warehouseProvisioningLogic'
export enum DataWarehouseTab {
+ OVERVIEW = 'overview',
SETTINGS = 'settings',
MODELING = 'modeling',
}
+function isDataWarehouseTab(tab: unknown): tab is DataWarehouseTab {
+ return typeof tab === 'string' && (Object.values(DataWarehouseTab) as string[]).includes(tab)
+}
+
// Single source of truth for which tabs the Data ops scene exposes. The scene, the URL
// state, and the default tab all derive from availableTabs / activeTab below.
export const dataWarehouseSceneLogic = kea<dataWarehouseSceneLogicType>([
path(['scenes', 'data-warehouse', 'dataWarehouseSceneLogic']),
connect(() => ({
- values: [featureFlagLogic, ['featureFlags']],
+ values: [featureFlagLogic, ['featureFlags'], warehouseProvisioningLogic, ['warehouseStatus']],
+ actions: [warehouseProvisioningLogic, ['loadWarehouseStatusSuccess', 'loadWarehouseStatusFailure']],
})),
actions({
- setActiveTab: (tab: DataWarehouseTab) => ({ tab }),
+ setActiveTab: (tab: DataWarehouseTab | null) => ({ tab }),
}),
reducers({
+ // Null until the URL or the user picks a tab — activeTab derives the effective one.
selectedTab: [
- DataWarehouseTab.MODELING as DataWarehouseTab,
+ null as DataWarehouseTab | null,
{
setActiveTab: (_, { tab }) => tab,
},
],
+ // warehouseStatus is null both before the first load and when no warehouse exists, so
+ // resolution has to be tracked separately — otherwise "still loading" reads as "no warehouse".
+ warehouseStatusResolved: [
+ false,
+ {
+ loadWarehouseStatusSuccess: () => true,
+ loadWarehouseStatusFailure: () => true,
+ },
+ ],
}),
selectors({
+ // A warehouse that isn't serving yet has nothing to report on, so Overview stays hidden
+ // until it's ready and the scene shows the setup form on its own.
+ warehouseReady: [(s) => [s.warehouseStatus], (warehouseStatus): boolean => warehouseStatus?.state === 'ready'],
availableTabs: [
- (s) => [s.featureFlags],
- (featureFlags): DataWarehouseTab[] => {
+ (s) => [s.featureFlags, s.warehouseReady],
+ (featureFlags, warehouseReady): DataWarehouseTab[] => {
const tabs: DataWarehouseTab[] = []
+ if (featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE] && warehouseReady) {
+ tabs.push(DataWarehouseTab.OVERVIEW)
+ }
if (featureFlags[FEATURE_FLAGS.DATA_MODELING_TAB]) {
tabs.push(DataWarehouseTab.MODELING)
}
@@ -46,11 +69,12 @@ export const dataWarehouseSceneLogic = kea<dataWarehouseSceneLogicType>([
return tabs
},
],
- // The selected tab clamped to what's actually available (null when nothing is).
+ // The selected tab clamped to what's actually available (null when nothing is). Clamping
+ // lives here rather than in urlToAction so it re-derives when the warehouse status lands.
activeTab: [
(s) => [s.selectedTab, s.availableTabs],
(selectedTab, availableTabs): DataWarehouseTab | null =>
- availableTabs.includes(selectedTab) ? selectedTab : (availableTabs[0] ?? null),
+ selectedTab && availableTabs.includes(selectedTab) ? selectedTab : (availableTabs[0] ?? null),
],
[SIDE_PANEL_CONTEXT_KEY]: [
() => [],
@@ -61,18 +85,22 @@ export const dataWarehouseSceneLogic = kea<dataWarehouseSceneLogicType>([
}),
urlToAction(({ actions, values }) => ({
[urls.dataOps()]: (_, searchParams) => {
- const requested = searchParams.tab as DataWarehouseTab | undefined
- const target =
- requested && values.availableTabs.includes(requested)
- ? requested
- : (values.availableTabs[0] ?? DataWarehouseTab.SETTINGS)
- if (target !== values.selectedTab) {
- actions.setActiveTab(target)
+ const requested = isDataWarehouseTab(searchParams.tab) ? searchParams.tab : null
+ if (requested !== values.selectedTab) {
+ actions.setActiveTab(requested)
}
},
})),
actionToUrl(({ values }) => ({
setActiveTab: () => {
+ // Until the warehouse status lands, availableTabs is provisional (Overview may still be
+ // hidden) — canonicalizing against it now could strip a `?tab=` the user asked for and
+ // then re-dispatch setActiveTab(null) via urlToAction, erasing the request. Skipping the
+ // rewrite here (kea-router treats undefined as "don't navigate") leaves the URL alone
+ // until activeTab is derived from the real tab set.
+ if (!values.warehouseStatusResolved) {
+ return
+ }
const searchParams = { ...router.values.searchParams }
// The default (first available) tab is canonical at /data-ops with no ?tab.
if (values.activeTab && values.activeTab !== values.availableTabs[0]) {
diff --git a/frontend/src/scenes/data-warehouse/scene/OverviewTab.tsx b/frontend/src/scenes/data-warehouse/scene/OverviewTab.tsx
new file mode 100644
index 000000000000..a08da3a2ee9e
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/scene/OverviewTab.tsx
@@ -0,0 +1,265 @@
+import { useActions, useValues } from 'kea'
+
+import { IconDatabase, IconPeople, IconRefresh } from '@posthog/icons'
+
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonCard } from 'lib/lemon-ui/LemonCard'
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
+import { Spinner } from 'lib/lemon-ui/Spinner'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+
+import type {
+ ManagedWarehouseDatasetStatusApi,
+ ManagedWarehouseReadinessStateEnumApi,
+ ManagedWarehouseSourceTableStatusApi,
+} from 'products/data_warehouse/frontend/generated/api.schemas'
+
+import { managedWarehouseDataStatusLogic } from './managedWarehouseDataStatusLogic'
+
+const STATUS_LABELS: Record<ManagedWarehouseReadinessStateEnumApi, string> = {
+ not_configured: 'Not configured',
+ waiting: 'Waiting',
+ backfilling: 'Backfilling',
+ catching_up: 'Catching up',
+ up_to_date: 'Up to date',
+ needs_attention: 'Needs attention',
+ unknown: 'Status unavailable',
+}
+
+const STATUS_TAG_TYPES: Record<ManagedWarehouseReadinessStateEnumApi, LemonTagType> = {
+ not_configured: 'muted',
+ waiting: 'warning',
+ backfilling: 'primary',
+ catching_up: 'primary',
+ up_to_date: 'success',
+ needs_attention: 'danger',
+ unknown: 'muted',
+}
+
+function StatusTag({ readinessState }: { readinessState: ManagedWarehouseReadinessStateEnumApi }): JSX.Element {
+ return <LemonTag type={STATUS_TAG_TYPES[readinessState]}>{STATUS_LABELS[readinessState]}</LemonTag>
+}
+
+function DatasetCard({
+ title,
+ description,
+ icon,
+ status,
+}: {
+ title: string
+ description: string
+ icon: JSX.Element
+ status: ManagedWarehouseDatasetStatusApi
+}): JSX.Element {
+ const hasProgress = status.total_partitions !== null && status.total_partitions > 0
+ const progress = hasProgress ? Math.round((status.completed_partitions / status.total_partitions!) * 100) : null
+
+ return (
+ <LemonCard className="p-4 space-y-4">
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex items-start gap-3">
+ <div className="text-xl text-muted mt-0.5">{icon}</div>
+ <div>
+ <h3 className="mb-1">{title}</h3>
+ <p className="text-muted mb-0">{description}</p>
+ </div>
+ </div>
+ <StatusTag readinessState={status.readiness_state} />
+ </div>
+ <div className="border-t pt-4 space-y-3">
+ <p className="mb-0">{status.detail}</p>
+ {progress !== null && (
+ <div className="space-y-1">
+ <div className="flex justify-between text-xs text-muted">
+ <span>Historical backfill</span>
+ <span>
+ {status.completed_partitions} / {status.total_partitions}
+ </span>
+ </div>
+ <LemonProgress percent={progress} />
+ </div>
+ )}
+ {status.current_partition && (
+ <div className="text-xs text-muted">
+ Current partition: <code>{status.current_partition}</code>
+ </div>
+ )}
+ {status.last_updated_at && (
+ <div className="text-xs text-muted">
+ Updated {humanFriendlyDetailedTime(status.last_updated_at)}
+ </div>
+ )}
+ </div>
+ </LemonCard>
+ )
+}
+
+// Most severe first, matching the order the API returns tables in.
+const STATUS_SEVERITY: Record<ManagedWarehouseReadinessStateEnumApi, number> = {
+ needs_attention: 0,
+ backfilling: 1,
+ catching_up: 2,
+ waiting: 3,
+ unknown: 4,
+ up_to_date: 5,
+ not_configured: 6,
+}
+
+const sourceColumns: LemonTableColumns<ManagedWarehouseSourceTableStatusApi> = [
+ {
+ title: 'Source',
+ key: 'source',
+ render: (_, table) => (
+ <div>
+ <div className="font-medium">{table.source_name}</div>
+ <div className="text-xs text-muted">{table.source_type}</div>
+ </div>
+ ),
+ sorter: (a, b) => a.source_name.localeCompare(b.source_name) || a.table_name.localeCompare(b.table_name),
+ },
+ {
+ title: 'Table',
+ dataIndex: 'table_name',
+ render: (tableName) => <code>{tableName}</code>,
+ sorter: (a, b) => a.table_name.localeCompare(b.table_name),
+ },
+ {
+ title: 'Warehouse status',
+ key: 'readiness_state',
+ render: (_, table) => (
+ <div className="space-y-1 max-w-96">
+ <StatusTag readinessState={table.readiness_state} />
+ <div className="text-xs text-muted">{table.detail}</div>
+ </div>
+ ),
+ sorter: (a, b) => STATUS_SEVERITY[a.readiness_state] - STATUS_SEVERITY[b.readiness_state],
+ },
+ {
+ title: 'Backfill',
+ key: 'backfill',
+ render: (_, table) =>
+ table.total_chunks ? `${table.completed_chunks} / ${table.total_chunks} chunks` : 'No active backfill',
+ },
+ {
+ title: 'Pending imports',
+ dataIndex: 'pending_batches',
+ render: (pendingBatches) =>
+ typeof pendingBatches === 'number' ? pendingBatches.toLocaleString() : 'Unavailable',
+ // Unavailable counts sort last rather than as zero, which would read as "nothing pending".
+ sorter: (a, b) => (a.pending_batches ?? -1) - (b.pending_batches ?? -1),
+ },
+ {
+ title: 'Last source import',
+ dataIndex: 'last_synced_at',
+ render: (lastSyncedAt) =>
+ typeof lastSyncedAt === 'string' ? humanFriendlyDetailedTime(lastSyncedAt) : 'Not synced yet',
+ sorter: (a, b) => new Date(a.last_synced_at ?? 0).getTime() - new Date(b.last_synced_at ?? 0).getTime(),
+ },
+]
+
+export function OverviewTab(): JSX.Element {
+ const { managedWarehouseDataStatus, managedWarehouseDataStatusLoading } = useValues(managedWarehouseDataStatusLogic)
+ const { loadManagedWarehouseDataStatus } = useActions(managedWarehouseDataStatusLogic)
+
+ if (managedWarehouseDataStatusLoading && !managedWarehouseDataStatus) {
+ return (
+ <div className="mt-4 flex items-center gap-2 text-muted">
+ <Spinner />
+ <span>Loading warehouse data status...</span>
+ </div>
+ )
+ }
+
+ if (!managedWarehouseDataStatus) {
+ return (
+ <LemonBanner type="error" className="mt-4">
+ <div className="flex items-center justify-between gap-3">
+ <span>Warehouse data status could not be loaded.</span>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconRefresh />}
+ onClick={() => loadManagedWarehouseDataStatus()}
+ loading={managedWarehouseDataStatusLoading}
+ >
+ Try again
+ </LemonButton>
+ </div>
+ </LemonBanner>
+ )
+ }
+
+ const bannerType =
+ managedWarehouseDataStatus.overall_readiness_state === 'needs_attention'
+ ? 'error'
+ : managedWarehouseDataStatus.overall_readiness_state === 'up_to_date'
+ ? 'success'
+ : 'info'
+
+ return (
+ <div className="mt-4 space-y-4">
+ <div className="flex items-center justify-between gap-3">
+ <div>
+ <h2 className="mb-1">Warehouse data readiness</h2>
+ <p className="text-muted mb-0">
+ Track historical backfills and whether recent source imports have reached your warehouse.
+ </p>
+ </div>
+ <LemonButton
+ type="secondary"
+ icon={<IconRefresh />}
+ onClick={() => loadManagedWarehouseDataStatus()}
+ loading={managedWarehouseDataStatusLoading}
+ >
+ Refresh
+ </LemonButton>
+ </div>
+
+ <LemonBanner type={bannerType}>
+ <div className="flex items-center gap-2">
+ <StatusTag readinessState={managedWarehouseDataStatus.overall_readiness_state} />
+ <span>Status checked {humanFriendlyDetailedTime(managedWarehouseDataStatus.generated_at)}</span>
+ </div>
+ </LemonBanner>
+
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
+ <DatasetCard
+ title="Events"
+ description="Historical events and daily warehouse updates"
+ icon={<IconDatabase />}
+ status={managedWarehouseDataStatus.events}
+ />
+ <DatasetCard
+ title="Persons"
+ description="Historical persons and daily warehouse updates"
+ icon={<IconPeople />}
+ status={managedWarehouseDataStatus.persons}
+ />
+ </div>
+
+ <LemonCard className="p-0 overflow-hidden">
+ <div className="p-4 flex items-start justify-between gap-3 border-b">
+ <div>
+ <h3 className="mb-1">Imported source tables</h3>
+ <p className="text-muted mb-0">{managedWarehouseDataStatus.sources.detail}</p>
+ </div>
+ <StatusTag readinessState={managedWarehouseDataStatus.sources.readiness_state} />
+ </div>
+ {managedWarehouseDataStatus.sources.tables.length ? (
+ <LemonTable
+ embedded
+ columns={sourceColumns}
+ dataSource={managedWarehouseDataStatus.sources.tables}
+ rowKey="schema_id"
+ pagination={{ pageSize: 20 }}
+ />
+ ) : (
+ <div className="p-6 text-muted">No imported source tables are configured for this warehouse.</div>
+ )}
+ </LemonCard>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/data-warehouse/scene/managedWarehouseDataStatusLogic.ts b/frontend/src/scenes/data-warehouse/scene/managedWarehouseDataStatusLogic.ts
new file mode 100644
index 000000000000..db98ca55f937
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/scene/managedWarehouseDataStatusLogic.ts
@@ -0,0 +1,64 @@
+import { afterMount, connect, kea, listeners, path, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { dataWarehouseManagedWarehouseDataStatusRetrieve } from 'products/data_warehouse/frontend/generated/api'
+import type {
+ ManagedWarehouseDataStatusResponseApi,
+ ManagedWarehouseReadinessStateEnumApi,
+} from 'products/data_warehouse/frontend/generated/api.schemas'
+
+import type { managedWarehouseDataStatusLogicType } from './managedWarehouseDataStatusLogicType'
+
+const ACTIVE_REFRESH_INTERVAL_MS = 15_000
+const STABLE_REFRESH_INTERVAL_MS = 60_000
+const ACTIVE_STATES: ManagedWarehouseReadinessStateEnumApi[] = ['waiting', 'backfilling', 'catching_up']
+
+export const managedWarehouseDataStatusLogic = kea<managedWarehouseDataStatusLogicType>([
+ path(['scenes', 'data-warehouse', 'scene', 'managedWarehouseDataStatusLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId']],
+ })),
+ loaders(({ values }) => ({
+ managedWarehouseDataStatus: [
+ null as ManagedWarehouseDataStatusResponseApi | null,
+ {
+ loadManagedWarehouseDataStatus: async () => {
+ return await dataWarehouseManagedWarehouseDataStatusRetrieve(String(values.currentTeamId))
+ },
+ },
+ ],
+ })),
+ selectors({
+ hasActiveWork: [
+ (s) => [s.managedWarehouseDataStatus],
+ (managedWarehouseDataStatus): boolean =>
+ managedWarehouseDataStatus !== null &&
+ ACTIVE_STATES.includes(managedWarehouseDataStatus.overall_readiness_state),
+ ],
+ }),
+ listeners(({ actions, values, cache }) => ({
+ loadManagedWarehouseDataStatusSuccess: () => {
+ cache.disposables.add(() => {
+ const timeoutId = window.setTimeout(
+ () => actions.loadManagedWarehouseDataStatus(),
+ values.hasActiveWork ? ACTIVE_REFRESH_INTERVAL_MS : STABLE_REFRESH_INTERVAL_MS
+ )
+ return () => window.clearTimeout(timeoutId)
+ }, 'managedWarehouseDataStatusPoll')
+ },
+ loadManagedWarehouseDataStatusFailure: () => {
+ cache.disposables.add(() => {
+ const timeoutId = window.setTimeout(
+ () => actions.loadManagedWarehouseDataStatus(),
+ STABLE_REFRESH_INTERVAL_MS
+ )
+ return () => window.clearTimeout(timeoutId)
+ }, 'managedWarehouseDataStatusPoll')
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadManagedWarehouseDataStatus()
+ }),
+])