Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions frontend/common/hooks/__tests__/useFeatureStates.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
jest.mock('common/services/useProjectFlag', () => ({
useGetProjectFlagsQuery: jest.fn(),
}))

jest.mock('common/hooks/useProjectEnvironments', () => ({
useProjectEnvironments: jest.fn(),
}))

import { useFeatureStates } from 'common/hooks/useFeatureStates'
import { useGetProjectFlagsQuery } from 'common/services/useProjectFlag'
import { useProjectEnvironments } from 'common/hooks/useProjectEnvironments'
import { ProjectFlag } from 'common/types/responses'

const mockUseGetProjectFlagsQuery =
useGetProjectFlagsQuery as jest.MockedFunction<typeof useGetProjectFlagsQuery>
const mockUseProjectEnvironments =
useProjectEnvironments as jest.MockedFunction<typeof useProjectEnvironments>

const enabledFeature = {
environment_feature_state: { enabled: true },
id: 1,
} as unknown as ProjectFlag

describe('useFeatureStates', () => {
beforeEach(() => {
mockUseProjectEnvironments.mockReturnValue({
error: undefined,
getEnvironmentIdFromKey: () => 2,
isLoading: false,
} as any)
})

it("ignores another environment's list while this one's loads", () => {
// Given
mockUseGetProjectFlagsQuery.mockReturnValue({
currentData: undefined,
data: { results: [enabledFeature] },
isError: false,
isLoading: false,
} as any)

// When
const states = useFeatureStates({ environmentId: 'key', projectId: 1 })

// Then
expect(states.isLoading).toBe(true)
expect(states.features).toEqual([])
})

it('requests project flags for the resolved environment', () => {
// Given
mockUseGetProjectFlagsQuery.mockReturnValue({
currentData: { results: [] },
isError: false,
isLoading: false,
} as any)

// When
useFeatureStates({ environmentId: 'key', projectId: 1 })

// Then
expect(mockUseGetProjectFlagsQuery).toHaveBeenCalledWith(
{ environment: 2, project: '1' },
{ skip: false },
)
})

it("reads this environment's list once loaded", () => {
// Given
mockUseGetProjectFlagsQuery.mockReturnValue({
currentData: { results: [enabledFeature] },
isError: false,
isLoading: false,
} as any)

// When
const states = useFeatureStates({ environmentId: 'key', projectId: 1 })

// Then
expect(states.isLoading).toBe(false)
expect(states.isEnabled(1)).toBe(true)
})
})
31 changes: 16 additions & 15 deletions frontend/common/hooks/useFeatureStates.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useGetFeatureListQuery } from 'common/services/useProjectFlag'
import { useGetProjectFlagsQuery } from 'common/services/useProjectFlag'
import { useProjectEnvironments } from './useProjectEnvironments'
import { ProjectFlag } from 'common/types/responses'

Expand All @@ -12,8 +12,9 @@ type UseFeatureStatesArgs = {
skip?: boolean
}

// Whether each of a project's features is on in one environment, from the
// feature list. getFeatureList takes the numeric environment id, not the key.
// Whether each of a project's features is on in one environment, from every
// page of the feature list, as a feature missing from it reads as off.
// getProjectFlags takes the numeric environment id, not the key.
export const useFeatureStates = ({
environmentId,
projectId,
Expand All @@ -25,22 +26,19 @@ export const useFeatureStates = ({
isLoading: isLoadingEnvironments,
} = useProjectEnvironments(projectId)
const numericEnvId = getEnvironmentIdFromKey(environmentId)
const shouldSkip = skip || !numericEnvId
// currentData, not data, which keeps another environment's list while this
// one's loads.
const {
data,
currentData,
isError: isFeatureListError,
isLoading: isLoadingFeatureList,
} = useGetFeatureListQuery(
{
environmentId: String(numericEnvId ?? ''),
page: 1,
// One page has to cover every feature, or one outside it reads as off.
page_size: 999,
projectId,
},
{ skip: skip || !numericEnvId },
} = useGetProjectFlagsQuery(
{ environment: numericEnvId, project: String(projectId) },
{ skip: shouldSkip },
)

const features = data?.results ?? NO_FEATURES
const features = currentData?.results ?? NO_FEATURES
return {
features,
isEnabled: (featureId: number) =>
Expand All @@ -52,6 +50,9 @@ export const useFeatureStates = ({
// The lookup finished without finding the environment, so the feature
// list will never run and nothing is coming.
(!isLoadingEnvironments && !numericEnvId),
isLoading: isLoadingEnvironments || isLoadingFeatureList,
isLoading:
isLoadingEnvironments ||
isLoadingFeatureList ||
(!shouldSkip && !currentData && !isFeatureListError),
}
}
6 changes: 6 additions & 0 deletions frontend/common/services/useProjectFlag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,12 @@ export const projectFlagService = service
.join('-'),
type: 'ProjectFlag',
},
// Refreshed with the feature list, as it carries the same states.
{
id: `${req?.project}-${req?.environment}`,
type: 'FeatureList',
},
{ id: 'LIST', type: 'FeatureList' },
],
queryFn: async (args, _, _2, baseQuery) => {
return await recursivePageGet<ProjectFlag>(
Expand Down
47 changes: 47 additions & 0 deletions frontend/common/utils/__tests__/recursivePageGet.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { recursivePageGet } from 'common/utils/recursivePageGet'

describe('recursivePageGet', () => {
it('follows next links, concatenating the pages', async () => {
// Given
const baseQuery = jest
.fn()
.mockResolvedValueOnce({
data: {
count: 3,
next: 'items/?page=2',
previous: null,
results: [1, 2],
},
})
.mockResolvedValueOnce({
data: { count: 3, next: null, previous: 'items/?page=1', results: [3] },
})

// When
const res = await recursivePageGet<number>('items/?page=1', null, baseQuery)

// Then
expect(baseQuery.mock.calls.map(([arg]) => arg)).toEqual([
{ method: 'GET', url: 'items/?page=1' },
{ method: 'GET', url: 'items/?page=2' },
])
expect(res.data?.results).toEqual([1, 2, 3])
})

it('returns the error of a failing page', async () => {
// Given
const error = { status: 500 }
const baseQuery = jest
.fn()
.mockResolvedValueOnce({
data: { count: 3, next: 'items/?page=2', previous: null, results: [1] },
})
.mockResolvedValueOnce({ error })

// When
const res = await recursivePageGet<number>('items/?page=1', null, baseQuery)

// Then
expect(res).toEqual({ error })
})
})
28 changes: 25 additions & 3 deletions frontend/e2e/tests/flag-dependencies-test.pw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ test.describe('Flag Dependencies', () => {

const openDependencies = async (feature: string) => {
await gotoFeature(feature)
await page.getByRole('button', { name: 'Dependencies' }).click()
// The tab's name goes on to count the prerequisites met.
await page.getByRole('button', { name: /^Dependencies/ }).click()
}

log('The dependent has no prerequisites yet')
Expand Down Expand Up @@ -66,17 +67,38 @@ test.describe('Flag Dependencies', () => {
log('The prerequisite is off, so the flag is held off')
await expect(row.getByRole('img', { name: 'Off' })).toBeVisible()
await expect(row.getByText('No', { exact: true })).toBeVisible()
await expect(page.getByText(/Serving off in/)).toBeVisible()
// The Value tab's banner stays in the page behind the open tab, and the
// role skips hidden elements, so this only matches the open tab's.
const servingOff = page
.getByRole('status')
.filter({ hasText: /Serving off in/ })
await expect(servingOff).toBeVisible()
await visualSnapshot(page, 'dependencies-blocked', testInfo)

log('The tab counts the prerequisites met, and the Value tab says why')
await expect(
page.getByRole('button', { name: /0 of 1 prerequisites met/ }),
Comment thread
khvn26 marked this conversation as resolved.
Resolved
).toBeVisible()
await page.getByRole('button', { exact: true, name: 'Value' }).click()
await expect(servingOff).toBeVisible()
await visualSnapshot(page, 'dependencies-blocked-value', testInfo)
await page
.getByRole('button', { exact: true, name: 'View dependencies' })
.click()
await expect(page).toHaveURL(/tab=dependencies/)
await expect(row).toBeVisible()

log('Turning the prerequisite on satisfies it')
await closeModal()
await waitForModalToClose()
await toggleFeature(PREREQUISITE, true)
await openDependencies(DEPENDENT)
await expect(row.getByRole('img', { name: 'On' })).toBeVisible()
await expect(row.getByText('Yes', { exact: true })).toBeVisible()
await expect(page.getByText(/Serving off in/)).toBeHidden()
await expect(servingOff).toBeHidden()
await expect(
page.getByRole('button', { name: /1 of 1 prerequisites met/ }),
).toBeVisible()
await visualSnapshot(page, 'dependencies-satisfied', testInfo)

log('The dependency manages its segment override')
Expand Down
43 changes: 31 additions & 12 deletions frontend/web/components/modals/create-feature/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@ import SegmentOverridesTab, {
SegmentOverrideValue,
} from './tabs/SegmentOverridesTab'
import UsageTab from './tabs/UsageTab'
import FeatureDependenciesTab from './tabs/FeatureDependenciesTab'
import FeatureDependenciesTab, {
DependenciesTabLabel,
usePrerequisiteStatus,
} from './tabs/FeatureDependenciesTab'
import { useStagedPrerequisites } from './tabs/FeatureDependenciesTab/hooks/useStagedPrerequisites'
import FeatureLimitAlert from './components/FeatureLimitAlert'
import FeatureUpdateSummary from './components/FeatureUpdateSummary'
Expand Down Expand Up @@ -461,6 +464,16 @@ const CreateFeatureModal: FC<CreateFeatureModalProps> = (props) => {
setSkipSaveProjectFeature(!createFeaturePermission)
}, [createFeaturePermission])

// Shown on the Value tab and the Dependencies tab's label, as
// prerequisites that are off serve the flag off. Dependencies don't apply
// to identity overrides, nor show for change requests.
const prerequisites = usePrerequisiteStatus({
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
environmentId,
featureId: projectFlag.id,
projectId,
skip: !isEdit || !!identity || !!existingChangeRequest,
Comment thread
khvn26 marked this conversation as resolved.
Resolved
})

if (!environment || !project) {
return (
<div className='text-center'>
Expand All @@ -479,6 +492,15 @@ const CreateFeatureModal: FC<CreateFeatureModalProps> = (props) => {
const isVersionedChangeRequest = existingChangeRequest && isVersioned
const hideIdentityOverridesTab = Utils.getShouldHideIdentityOverridesTab()
const isDependenciesTabEnabled = !existingChangeRequest
const onTabChange = () => {
setTabKey((k) => k + 1)
// A save error belongs to the tab it occurred on — the
// other tabs cannot render its shape meaningfully.
if (FeatureListStore.error) {
FeatureListStore.error = null
FeatureListStore.trigger('change')
}
}

// Shows the Dependencies tab, as `Tabs` does when it's clicked.
const showDependencies =
Expand All @@ -490,7 +512,7 @@ const CreateFeatureModal: FC<CreateFeatureModalProps> = (props) => {
pathname: window.location.pathname,
search: searchParams.toString(),
})
setTabKey((k) => k + 1)
onTabChange()
Comment thread
khvn26 marked this conversation as resolved.
Resolved
}
: undefined

Expand Down Expand Up @@ -812,15 +834,7 @@ const CreateFeatureModal: FC<CreateFeatureModalProps> = (props) => {
<Tabs
urlParam='tab'
history={props.history}
onChange={() => {
setTabKey((k) => k + 1)
// A save error belongs to the tab it occurred on — the
// other tabs cannot render its shape meaningfully.
if (FeatureListStore.error) {
FeatureListStore.error = null
FeatureListStore.trigger('change')
}
}}
onChange={onTabChange}
overflowX
>
<TabItem
Expand All @@ -830,6 +844,8 @@ const CreateFeatureModal: FC<CreateFeatureModalProps> = (props) => {
>
<FeatureValueTab
error={error}
prerequisites={prerequisites}
onViewDependencies={showDependencies}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
projectId={projectId}
noPermissions={!!noPermissions}
freeze={freeze}
Expand Down Expand Up @@ -894,7 +910,10 @@ const CreateFeatureModal: FC<CreateFeatureModalProps> = (props) => {
{isDependenciesTabEnabled && (
<TabItem
data-test='feature_dependencies'
tabLabel='Dependencies'
tabLabelString='Dependencies'
tabLabel={
<DependenciesTabLabel prerequisites={prerequisites} />
}
isDirty={dependenciesChanged}
>
<FeatureDependenciesTab
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FC } from 'react'
import { FC, ReactNode } from 'react'
import Banner from 'components/base/Banner'
import {
PrerequisiteRow,
Expand All @@ -9,16 +9,22 @@ import {
type BlockedBannerProps = {
environmentName: string
rows: PrerequisiteRow[]
action?: ReactNode
}

// Only rendered when the flag is held off. A flag serving its own value needs
// no announcement.
const BlockedBanner: FC<BlockedBannerProps> = ({ environmentName, rows }) =>
const BlockedBanner: FC<BlockedBannerProps> = ({
action,
environmentName,
rows,
}) =>
isBlocked(rows) ? (
<Banner
type='warning'
className='mb-3'
title={`Serving off in ${environmentName}`}
action={action}
>
{describeOffCount(rows)}
</Banner>
Expand Down
Loading
Loading