Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Fix the feature flags in production on hydration (#4084)
Olga Bulat63af1afe32e0
diff --git a/frontend/feat/feature-flags.json b/frontend/feat/feature-flags.jsonindex 3883fd282..a697f30ac 100644--- a/frontend/feat/feature-flags.json+++ b/frontend/feat/feature-flags.json@@ -10,10 +10,7 @@"storage": "cookie"},"additional_search_views": {- "status": {- "staging": "switchable",- "production": "switchable"- },+ "status": "switchable","description": "Toggle additional search views for tag/creator/source.","defaultState": "on","storage": "cookie"diff --git a/frontend/nuxt.config.ts b/frontend/nuxt.config.tsindex a010c68a9..c03f6a165 100644--- a/frontend/nuxt.config.ts+++ b/frontend/nuxt.config.ts@@ -346,6 +346,7 @@ const config: NuxtConfig = {environment: process.env.SENTRY_ENVIRONMENT,},},+ deploymentEnv: process.env.DEPLOYMENT_ENV ?? "local",},}diff --git a/frontend/src/pages/preferences.vue b/frontend/src/pages/preferences.vueindex cd8019dac..4c260b3b5 100644--- a/frontend/src/pages/preferences.vue+++ b/frontend/src/pages/preferences.vue@@ -30,7 +30,7 @@v-if="isFlagName(name) && isSwitchable(name)":id="name"class="flex-row items-center"- :checked="featureState(name) === ON"+ :checked="isOn(name)"is-switch@change="handleChange">{{ $t(`prefPage.features.${name}`) }}</VCheckbox@@ -51,28 +51,26 @@{{ $t(`prefPage.${isFlagSwitchable ? "s" : "nonS"}witchable.desc`) }}</p><ul>- <template v-for="(feature, name) in flags">- <li- v-if="(getFlagStatus(feature) === SWITCHABLE) === isFlagSwitchable"- :key="name"- class="mb-4 flex flex-row items-center last:mb-0"+ <li+ v-for="[name, feature] in getFlagsBySwitchable(isFlagSwitchable)"+ :key="name"+ class="mb-4 flex flex-row items-center last:mb-0"+ >+ <VCheckbox+ :id="name"+ class="flex-row items-center"+ :checked="isOn(name)"+ :disabled="!isFlagSwitchable"+ is-switch+ @change="handleChange">- <VCheckbox- :id="name"- class="flex-row items-center"- :checked="featureState(name) === ON"- :disabled="!isFlagSwitchable"- is-switch- @change="handleChange"- >- <div>- <strong>{{ name }}</strong>- <br />- {{ feature.description }}- </div>- </VCheckbox>- </li>- </template>+ <div>+ <strong>{{ name }}</strong>+ <br />+ {{ feature.description }}+ </div>+ </VCheckbox>+ </li></ul></div>@@ -87,15 +85,9 @@ import { defineComponent } from "@nuxtjs/composition-api"import featureData from "~~/feat/feature-flags.json"-import {- useFeatureFlagStore,- getFlagStatus,- isFlagName,-} from "~/stores/feature-flag"+import { useFeatureFlagStore, isFlagName } from "~/stores/feature-flag"import { SWITCHABLE, ON, OFF, FEATURE_STATES } from "~/constants/feature-flag"-import type { FeatureFlag } from "~/types/feature-flag"-import VContentPage from "~/components/VContentPage.vue"import VCheckbox from "~/components/VCheckbox/VCheckbox.vue"@@ -131,16 +123,28 @@ export default defineComponent({featureFlagStore.toggleFeature(name, checked ? ON : OFF)}+ const isOn = (name: string) => {+ if (!isFlagName(name)) {+ throw new Error(+ `Cannot check the state of flag ${name}: it does not exist.`+ )+ }+ return featureFlagStore.isOn(name)+ }+const isSwitchable = (name: string) => {if (!isFlagName(name)) {throw new Error(- `Error getting switchable status for flag ${name}: it does not exist.`+ `Cannot check the switchability of flag ${name}: it does not exist.`)}- // TS does not convert the statuses for flag from string to FlagStatus.- // It parses the JSON values for env-based statuses as { staging: string; production: string; }- const flag = featureData.features[name] as FeatureFlag- return getFlagStatus(flag) === SWITCHABLE+ return featureFlagStore.isSwitchable(name)+ }++ const getFlagsBySwitchable = (switchable: boolean) => {+ return Object.entries(flags.value).filter(+ ([name]) => isSwitchable(name) === switchable+ )}return {@@ -150,15 +154,15 @@ export default defineComponent({FEATURE_STATES,flags,- featureState: featureFlagStore.featureState,+ isOn,+ isSwitchable,handleChange,- getFlagStatus,- isSwitchable,+ isFlagName,featureData,+ getFlagsBySwitchable,}},- methods: { isFlagName },})</script>diff --git a/frontend/src/stores/feature-flag.ts b/frontend/src/stores/feature-flag.tsindex ba4c8bf61..bfbf79f26 100644--- a/frontend/src/stores/feature-flag.ts+++ b/frontend/src/stores/feature-flag.ts@@ -19,11 +19,11 @@ import {COOKIE,SESSION,} from "~/constants/feature-flag"-import { LOCAL, DEPLOY_ENVS, DeployEnv } from "~/constants/deploy-env"+import { DEPLOY_ENVS, DeployEnv } from "~/constants/deploy-env"import type { Dictionary } from "vue-router/types/router"-type FlagName = keyof (typeof featureData)["features"]+export type FlagName = keyof (typeof featureData)["features"]export const isFlagName = (name: string): name is FlagName => {return Object.keys(featureData.features).includes(name)@@ -32,17 +32,7 @@ export interface FeatureFlagState {flags: Record<FlagName, FeatureFlag>}-const FEATURE_FLAG = "feature_flag"--/**- * Get the status of the flag. If the flag status is environment dependent, this- * function will use the flag status for the current environment based on the- * `DEPLOYMENT_ENV` environment variable.- *- * @param flag - the flag for which to get the status- */-export const getFlagStatus = (flag: FeatureFlag): FlagStatus => {- const deployEnv = (process.env.DEPLOYMENT_ENV ?? LOCAL) as DeployEnv+export const _getFlagStatus = (flag: FeatureFlag, deployEnv: DeployEnv) => {if (typeof flag.status === "string") {return flag.status} else {@@ -56,22 +46,7 @@ export const getFlagStatus = (flag: FeatureFlag): FlagStatus => {return DISABLED}-/**- * Get the state of the feature based on the status of the feature flag and the- * preferences of the user.- *- * @param flag - the flag for which to get the state- */-const getFeatureState = (flag: FeatureFlag): FeatureState => {- const status = getFlagStatus(flag)- if (status === SWITCHABLE) {- return flag.preferredState ?? flag.defaultState ?? OFF- }- if (status === ENABLED) {- return ON- }- return OFF-}+const FEATURE_FLAG = "feature_flag"export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {state: () =>@@ -79,45 +54,9 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {flags: featureData.features,}) as FeatureFlagState,getters: {- /**- * Get the state of the named feature, based on config and cookie.- *- * Prefer `isOn` for most use cases.- */- featureState:- (state: FeatureFlagState) =>- (name: FlagName): FeatureState => {- if (name in state.flags) {- return getFeatureState(state.flags[name])- } else {- warn(`Invalid feature flag accessed: ${name}`)- return ON- }- },- /**- * Proxy for `featureState` to simplify the majority of flag state checks.- *- * Prefer this for most use cases over using `featureState` directly.- *- * @returns `true` if the flag is on, false otherwise- */- isOn() {- return (name: FlagName): boolean => this.featureState(name) === ON+ deploymentEnv(): DeployEnv {+ return this.$nuxt.$config.deploymentEnv},- /**- * Get the mapping of switchable features to their preferred states.- */- flagStateMap:- (state: FeatureFlagState) =>- (dest: string): Record<string, FeatureState> => {- const featureMap: Record<string, FeatureState> = {}- Object.entries(state.flags).forEach(([name, flag]) => {- if (getFlagStatus(flag) === SWITCHABLE && flag.storage === dest) {- featureMap[name] = getFeatureState(flag)- }- })- return featureMap- },},actions: {/**@@ -131,7 +70,7 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {initFromCookies(cookies: Record<string, FeatureState>) {Object.entries(cookies).forEach(([name, state]) => {const flag = this.flags[name as FlagName]- if (flag && getFlagStatus(flag) === SWITCHABLE) {+ if (flag && this.getFlagStatus(flag) === SWITCHABLE) {Vue.set(flag, "preferredState", state)}})@@ -188,7 +127,7 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {const flagName = name.substring(3) as FlagNameconst flag = this.flags[flagName]if (- getFlagStatus(flag) === SWITCHABLE &&+ this.getFlagStatus(flag) === SWITCHABLE &&flag.supportsQuery !== false) {Vue.set(flag, "preferredState", state)@@ -203,7 +142,7 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {*/toggleFeature(name: FlagName, targetState: FeatureState) {const flag = this.flags[name]- if (getFlagStatus(flag) === SWITCHABLE) {+ if (this.getFlagStatus(flag) === SWITCHABLE) {flag.preferredState = targetStatethis.writeToCookie()this.writeToSession()@@ -222,7 +161,82 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {syncAnalyticsWithLocalStorage() {const storage = useStorage<boolean | null>("plausible_ignore", null)storage.value =- getFeatureState(this.flags["analytics"]) === ON ? null : true+ this.getFeatureState(this.flags["analytics"]) === ON ? null : true+ },++ /**+ * Get the status of the flag. If the flag status is environment dependent, this+ * function will use the flag status for the current environment based on the+ * `DEPLOYMENT_ENV` environment variable.+ *+ * @param flag - the flag for which to get the status+ */+ getFlagStatus(flag: FeatureFlag): FlagStatus {+ return _getFlagStatus(flag, this.deploymentEnv)+ },++ /**+ * Get the mapping of switchable features to their preferred states.+ */+ flagStateMap(dest: string): Record<string, FeatureState> {+ const featureMap: Record<string, FeatureState> = {}+ Object.entries(this.flags).forEach(([name, flag]) => {+ if (this.getFlagStatus(flag) === SWITCHABLE && flag.storage === dest) {+ featureMap[name] = this.getFeatureState(flag)+ }+ })+ return featureMap+ },++ isSwitchable(name: string): boolean {+ if (!isFlagName(name)) {+ throw new Error(+ `Error getting switchable status for flag ${name}: it does not exist.`+ )+ }+ return this.getFlagStatus(this.flags[name]) === SWITCHABLE+ },++ /**+ * Get the state of the feature based on the status of the feature flag and the+ * preferences of the user.+ *+ * @param flag - the flag for which to get the state+ */+ getFeatureState(flag: FeatureFlag): FeatureState {+ const status = this.getFlagStatus(flag)+ if (status === SWITCHABLE) {+ return flag.preferredState ?? flag.defaultState ?? OFF+ }+ if (status === ENABLED) {+ return ON+ }+ return OFF+ },++ /**+ * Get the state of the named feature, based on config and cookie.+ *+ * Prefer `isOn` for most use cases.+ */+ featureState(name: FlagName): FeatureState {+ if (name in this.flags) {+ return this.getFeatureState(this.flags[name])+ } else {+ warn(`Invalid feature flag accessed: ${name}`)+ return ON+ }+ },++ /**+ * Proxy for `featureState` to simplify the majority of flag state checks.+ *+ * Prefer this for most use cases over using `featureState` directly.+ *+ * @returns `true` if the flag is on, false otherwise+ */+ isOn(name: FlagName): boolean {+ return this.featureState(name) === ON},},})diff --git a/frontend/test/playwright/e2e/preferences.spec.ts b/frontend/test/playwright/e2e/preferences.spec.tsnew file mode 100644index 000000000..3cdd3ef05--- /dev/null+++ b/frontend/test/playwright/e2e/preferences.spec.ts@@ -0,0 +1,95 @@+import { test, expect, Page } from "@playwright/test"++import { preparePageForTests } from "~~/test/playwright/utils/navigation"++import featureData from "~~/feat/feature-flags.json"++import { _getFlagStatus, type FlagName } from "~/stores/feature-flag"+import type { FeatureFlag } from "~/types/feature-flag"++const deployEnv = "staging" as const++const getFeatureCookies = async (page: Page, cookieName: string) => {+ const cookies = await page.context().cookies()+ const cookieValue = cookies.find(+ (cookie) => cookie.name === cookieName+ )?.value+ if (!cookieValue) {+ return {}+ }+ return JSON.parse(decodeURIComponent(cookieValue))+}++/**+ * Ensure that the features to be tested are not out of sync with the feature flags.+ */+const getFeaturesToTest = () => {+ const testableFeatures = {+ fetch_sensitive: "off",+ additional_search_views: "on",+ } as const+ for (const [name, state] of Object.entries(testableFeatures)) {+ const flag = featureData.features[name as FlagName] as FeatureFlag+ if (_getFlagStatus(flag, deployEnv) !== "switchable") {+ throw new Error(`Feature ${name} is not switchable`)+ }+ if (flag.defaultState !== state) {+ throw new Error(`Feature ${name} is not in the expected state ${state}`)+ }+ }+ return testableFeatures+}++const features = getFeaturesToTest()++const getSwitchableInput = async (+ page: Page,+ name: string,+ checked: boolean+) => {+ const checkbox = page.locator(`input[type=checkbox]#${name}`).first()+ await expect(checkbox).toBeEnabled()+ if (checked) {+ await expect(checkbox).toBeChecked()+ } else {+ await expect(checkbox).not.toBeChecked()+ }+ return checkbox+}++test.describe("switchable features", () => {+ test.beforeEach(async ({ page }) => {+ await preparePageForTests(page, "xl")+ })++ for (const [name, defaultState] of Object.entries(features)) {+ const checked = defaultState === "on"++ test(`can switch ${name} from ${defaultState}`, async ({ page }) => {+ await page.goto(`/preferences`)+ const featureFlag = await getSwitchableInput(page, name, checked)+ await featureFlag.click()++ // eslint-disable-next-line playwright/no-conditional-in-test+ if (checked) {+ await expect(featureFlag).not.toBeChecked()+ } else {+ await expect(featureFlag).toBeChecked()+ }+ })++ test(`switching ${name} from ${defaultState} saves state in a cookie`, async ({+ page,+ }) => {+ await page.goto(`/preferences`)+ const featureFlag = await getSwitchableInput(page, name, checked)+ await featureFlag.click()++ const storageCookie = { cookie: "features", session: "sessionFeatures" }[+ featureData.features[name as FlagName].storage as "cookie" | "session"+ ]+ const featureCookie = await getFeatureCookies(page, storageCookie)+ expect(featureCookie[name]).toEqual(defaultState === "on" ? "off" : "on")+ })+ }+})diff --git a/frontend/test/playwright/utils/navigation.ts b/frontend/test/playwright/utils/navigation.tsindex d61f946b1..9a16bbf2d 100644--- a/frontend/test/playwright/utils/navigation.ts+++ b/frontend/test/playwright/utils/navigation.ts@@ -204,30 +204,28 @@ export const preparePageForTests = async (}> = {}) => {const { dismissBanners = true, dismissFilter = true } = options- const defaultFeatures: Record<string, "on" | "off"> = {- fetch_sensitive: "off",- fake_sensitive: "off",- analytics: "on",- additional_search_types: "off",- additional_search_views: "off",- }- const features = {- ...defaultFeatures,- ...options.features,- }- const featuresCookie: Record<string, "on" | "off"> = {}- for (const [feature, status] of Object.entries(features)) {- featuresCookie[feature] = status- }- await setCookies(page.context(), {- features: featuresCookie,+ const cookiesToSet: CookieMap = {ui: {dismissedBanners: dismissBanners ? ALL_TEST_BANNERS : [],isFilterDismissed: dismissFilter ?? false,breakpoint,},- })+ }+ if (options.features) {+ const features: Record<string, "on" | "off"> = {+ fetch_sensitive: "off",+ fake_sensitive: "off",+ analytics: "on",+ additional_search_types: "off",+ additional_search_views: "on",+ }+ for (const [feature, status] of Object.entries(options.features)) {+ features[feature] = status+ }+ cookiesToSet.features = features+ }+ await setCookies(page.context(), cookiesToSet)}export const goToSearchTerm = async (diff --git a/frontend/test/unit/specs/stores/feature-flag-store.spec.js b/frontend/test/unit/specs/stores/feature-flag-store.spec.jsindex bffb87439..cce69b7e4 100644--- a/frontend/test/unit/specs/stores/feature-flag-store.spec.js+++ b/frontend/test/unit/specs/stores/feature-flag-store.spec.js@@ -1,6 +1,6 @@import { setActivePinia, createPinia } from "~~/test/unit/test-utils/pinia"-import { useFeatureFlagStore, getFlagStatus } from "~/stores/feature-flag"+import { useFeatureFlagStore } from "~/stores/feature-flag"import { OFF, COOKIE, SESSION } from "~/constants/feature-flag"jest.mock(@@ -145,20 +145,14 @@ describe("Feature flag store", () => {`("returns $expectedState for $environment",({ environment, featureState }) => {- // Back up value of `DEPLOYMENT_ENV` and replace it- const old_env = process.env.DEPLOYMENT_ENV- process.env.DEPLOYMENT_ENV = environment-const featureFlagStore = useFeatureFlagStore()+ featureFlagStore.$nuxt.$config.deploymentEnv = environmentexpect(featureFlagStore.featureState("feat_env_specific")).toEqual(featureState)expect(featureFlagStore.isOn("feat_env_specific")).toEqual(featureState === "on")-- // Restore `DEPLOYMENT_ENV` value- process.env.DEPLOYMENT_ENV = old_env})@@ -170,16 +164,13 @@ describe("Feature flag store", () => {`("handles fallback for missing $environment",({ environment, flagStatus }) => {- // Back up value of `DEPLOYMENT_ENV` and replace it- const old_env = process.env.DEPLOYMENT_ENV- process.env.DEPLOYMENT_ENV = environment-- expect(getFlagStatus({ status: { staging: "switchable" } })).toEqual(- flagStatus- )-- // Restore `DEPLOYMENT_ENV` value- process.env.DEPLOYMENT_ENV = old_env+ const featureFlagStore = useFeatureFlagStore()+ featureFlagStore.$nuxt.$config.deploymentEnv = environment+ expect(+ useFeatureFlagStore().getFlagStatus({+ status: { staging: "switchable" },+ })+ ).toEqual(flagStatus)})diff --git a/frontend/test/unit/test-utils/pinia.js b/frontend/test/unit/test-utils/pinia.jsindex e2614f25c..3387969aa 100644--- a/frontend/test/unit/test-utils/pinia.js+++ b/frontend/test/unit/test-utils/pinia.js@@ -6,6 +6,9 @@ import { normalizeFetchingError } from "~/plugins/errors"export const createPinia = () =>pinia.createPinia().use(() => ({$nuxt: {+ $config: {+ deploymentEnv: "staging",+ },$openverseApiToken: "",$processFetchingError: jest.fn(normalizeFetchingError),$sentry: {