Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Initialize feature flag state on the server (#4295)
Olga Bulat292946e588e8
diff --git a/frontend/src/pages/preferences.vue b/frontend/src/pages/preferences.vueindex 4c260b3b5..96278d8f2 100644--- a/frontend/src/pages/preferences.vue+++ b/frontend/src/pages/preferences.vue@@ -8,8 +8,8 @@it doesn't count as a user preference.--><div- v-for="(group, groupIndex) in featureData.groups"- :key="groupIndex"+ v-for="group in featureGroups"+ :key="group.title"class="not-prose border-b border-dark-charcoal-20 py-6 last-of-type:border-b-0"><h2 class="label-bold mb-2">@@ -22,52 +22,52 @@</p><ul><li- v-for="(name, featureIndex) in group.features"- :key="featureIndex"+ v-for="flag in group.features"+ :key="flag.name"class="mb-4 last:mb-0"><VCheckbox- v-if="isFlagName(name) && isSwitchable(name)"- :id="name"+ v-if="flag.status === SWITCHABLE"+ :id="flag.name"class="flex-row items-center"- :checked="isOn(name)"+ :checked="flag.state === ON"is-switch@change="handleChange"- >{{ $t(`prefPage.features.${name}`) }}</VCheckbox+ >{{ $t(`prefPage.features.${flag.name}`) }}</VCheckbox></li></ul></div><div- v-for="isFlagSwitchable in [false, true]"- :key="`${isFlagSwitchable}`"+ v-for="isSwitchable in [false, true]"+ :key="`${isSwitchable}`"class="not-prose border-b border-dark-charcoal-20 py-6 last-of-type:border-b-0"><h2 class="label-bold mb-2">- {{ $t(`prefPage.${isFlagSwitchable ? "s" : "nonS"}witchable.title`) }}+ {{ $t(`prefPage.${isSwitchable ? "s" : "nonS"}witchable.title`) }}</h2><p class="label-regular mb-4">- {{ $t(`prefPage.${isFlagSwitchable ? "s" : "nonS"}witchable.desc`) }}+ {{ $t(`prefPage.${isSwitchable ? "s" : "nonS"}witchable.desc`) }}</p><ul><li- v-for="[name, feature] in getFlagsBySwitchable(isFlagSwitchable)"- :key="name"+ v-for="flag in flagsBySwitchable[`${isSwitchable}`]"+ :key="flag.name"class="mb-4 flex flex-row items-center last:mb-0"><VCheckbox- :id="name"+ :id="flag.name"class="flex-row items-center"- :checked="isOn(name)"- :disabled="!isFlagSwitchable"+ :checked="flag.state === ON"+ :disabled="flag.status !== SWITCHABLE"is-switch@change="handleChange"><div>- <strong>{{ name }}</strong>+ <strong>{{ flag.name }}</strong><br />- {{ feature.description }}+ {{ flag.description }}</div></VCheckbox></li>@@ -83,9 +83,7 @@import { computed } from "vue"import { defineComponent } from "@nuxtjs/composition-api"-import featureData from "~~/feat/feature-flags.json"--import { useFeatureFlagStore, isFlagName } from "~/stores/feature-flag"+import { useFeatureFlagStore } from "~/stores/feature-flag"import { SWITCHABLE, ON, OFF, FEATURE_STATES } from "~/constants/feature-flag"import VContentPage from "~/components/VContentPage.vue"@@ -115,37 +113,19 @@ export default defineComponent({name: stringchecked?: boolean}) => {- if (!isFlagName(name)) {- throw new Error(- `Cannot change the state of flag ${name}: it does not exist.`- )- }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.`- )+ const flagsBySwitchable = computed(() => {+ return {+ true: featureFlagStore.getFlagsBySwitchable(true),+ false: featureFlagStore.getFlagsBySwitchable(false),}- return featureFlagStore.isOn(name)- }+ })- const isSwitchable = (name: string) => {- if (!isFlagName(name)) {- throw new Error(- `Cannot check the switchability of flag ${name}: it does not exist.`- )- }- return featureFlagStore.isSwitchable(name)- }-- const getFlagsBySwitchable = (switchable: boolean) => {- return Object.entries(flags.value).filter(- ([name]) => isSwitchable(name) === switchable- )- }+ const featureGroups = computed(() => {+ return featureFlagStore.getFeatureGroups()+ })return {ON,@@ -154,14 +134,11 @@ export default defineComponent({FEATURE_STATES,flags,- isOn,- isSwitchable,handleChange,- isFlagName,- featureData,- getFlagsBySwitchable,+ flagsBySwitchable,+ featureGroups,}},})diff --git a/frontend/src/stores/feature-flag.ts b/frontend/src/stores/feature-flag.tsindex bfbf79f26..7aaaa25a7 100644--- a/frontend/src/stores/feature-flag.ts+++ b/frontend/src/stores/feature-flag.ts@@ -1,4 +1,3 @@-import Vue from "vue"import { defineStore } from "pinia"import { useStorage } from "@vueuse/core"@@ -7,24 +6,27 @@ import featureData from "~~/feat/feature-flags.json"import { warn } from "~/utils/console"import { cookieOptions } from "~/utils/cookies"-import type { FeatureFlag } from "~/types/feature-flag"+import type {+ FeatureFlag,+ FeatureFlagRecord,+ FlagName,+} from "~/types/feature-flag"import {+ COOKIE,+ DISABLED,+ ENABLED,FeatureState,+ FLAG_STATUSES,FlagStatus,- ENABLED,- SWITCHABLE,- ON,OFF,- DISABLED,- COOKIE,+ ON,SESSION,+ SWITCHABLE,} from "~/constants/feature-flag"-import { DEPLOY_ENVS, DeployEnv } from "~/constants/deploy-env"+import { DEPLOY_ENVS, DeployEnv, LOCAL } from "~/constants/deploy-env"import type { Dictionary } from "vue-router/types/router"-export type FlagName = keyof (typeof featureData)["features"]-export const isFlagName = (name: string): name is FlagName => {return Object.keys(featureData.features).includes(name)}@@ -32,33 +34,148 @@ export interface FeatureFlagState {flags: Record<FlagName, FeatureFlag>}-export const _getFlagStatus = (flag: FeatureFlag, deployEnv: DeployEnv) => {+interface FeatureGroup {+ title: string+ features: FeatureFlag[]+}++/**+ * 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: FeatureFlagRecord): FlagStatus => {+ const deployEnv = (process.env.DEPLOYMENT_ENV ?? LOCAL) as DeployEnvif (typeof flag.status === "string") {- return flag.status+ if (!FLAG_STATUSES.includes(flag.status as FlagStatus)) {+ warn(`Invalid ${flag.description} flag status: ${flag.status}`)+ return DISABLED+ }+ return flag.status as FlagStatus} else {const envIndex = DEPLOY_ENVS.indexOf(deployEnv)for (let i = envIndex; i < DEPLOY_ENVS.length; i += 1) {if (DEPLOY_ENVS[i] in flag.status) {- return flag.status[DEPLOY_ENVS[i]]+ if (+ !FLAG_STATUSES.includes(flag.status[DEPLOY_ENVS[i]] as FlagStatus)+ ) {+ warn(+ `Invalid ${flag.description} flag status: ${flag.status[DEPLOY_ENVS[i]]}`+ )+ return DISABLED+ }+ return flag.status[DEPLOY_ENVS[i]] as 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 | FeatureFlagRecord+): FeatureState => {+ const status = getFlagStatus(flag)+ if (status === SWITCHABLE) {+ if ("preferredState" in flag) {+ return (flag.preferredState as FeatureState) ?? flag.defaultState ?? OFF+ }+ return flag.defaultState ?? OFF+ }+ if (status === ENABLED) {+ return ON+ }+ return OFF+}++const initializeFlagState = () => {+ // Resolve the status of the feature flags based on the current environment+ const features: Record<FlagName, FeatureFlag> = Object.entries(+ featureData.features as Record<FlagName, FeatureFlagRecord>+ ).reduce(+ (acc, [name, flag]) => {+ acc[name as FlagName] = {+ ...flag,+ name: name as FlagName,+ state: getFeatureState(flag),+ status: getFlagStatus(flag),+ preferredState: undefined,+ }+ return acc+ },+ {} as Record<FlagName, FeatureFlag>+ )+ return { flags: features, groups: featureData.groups }+}+const FEATURE_FLAG = "feature_flag"export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {- state: () =>- ({- flags: featureData.features,- }) as FeatureFlagState,+ state: () => {+ return initializeFlagState()+ },getters: {- deploymentEnv(): DeployEnv {- return this.$nuxt.$config.deploymentEnv- },+ /**+ * 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 (!isFlagName(name)) {+ warn(`Invalid feature flag accessed: ${name}`)+ return ON+ }+ return state.flags[name].state+ },++ /**+ * 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 (+ flag.status === SWITCHABLE &&+ flag.preferredState !== undefined &&+ flag.storage === dest+ ) {+ featureMap[name] = flag.state+ }+ })+ return featureMap+ },},actions: {+ getFlagsBySwitchable(switchable: boolean): FeatureFlag[] {+ return Object.entries(this.flags)+ .filter((feature) => (feature[1].status === SWITCHABLE) === switchable)+ .map((feature) => feature[1])+ },++ getFeatureGroups() {+ const result: FeatureGroup[] = []+ for (const { title, features } of this.groups) {+ if (features.length === 0) {+ continue+ }+ result.push({+ title,+ features: features.map((name) => this.flags[name as FlagName]),+ })+ }+ return result+ },/*** Given a list of key value pairs of flags and their preferred states,* populate the store state to match the cookie. The cookie may be@@ -70,8 +187,8 @@ 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 && this.getFlagStatus(flag) === SWITCHABLE) {- Vue.set(flag, "preferredState", state)+ if (flag && flag.status === SWITCHABLE) {+ this.setPreferredState(name as FlagName, state)}})},@@ -126,29 +243,43 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {// TODO: type `FlagName` should be inferred by TSconst flagName = name.substring(3) as FlagNameconst flag = this.flags[flagName]- if (- this.getFlagStatus(flag) === SWITCHABLE &&- flag.supportsQuery !== false- ) {- Vue.set(flag, "preferredState", state)+ if (flag.status === SWITCHABLE && flag.supportsQuery !== false) {+ this.setPreferredState(flagName, state)}})},+ setPreferredState(name: FlagName, toState: FeatureState) {+ const flag = this.flags[name]+ if (flag.status === SWITCHABLE) {+ flag.preferredState = toState+ flag.state = toState+ }+ },+ updateStorage(name: FlagName) {+ const flag = this.flags[name]+ if (flag.storage === COOKIE) {+ this.writeToCookie()+ } else if (flag.storage === SESSION) {+ this.writeToSession()+ }+ if (name === "analytics") {+ this.syncAnalyticsWithLocalStorage()+ }+ },/*** Toggle the feature flag of the given name to the given preferred state.** @param name - the name of the flag to toggle* @param targetState - the desired state of the feature flag*/- toggleFeature(name: FlagName, targetState: FeatureState) {+ toggleFeature(name: string, targetState: FeatureState) {+ if (!isFlagName(name)) {+ throw new Error(`Toggling invalid feature flag: ${name}`)+ }const flag = this.flags[name]- if (this.getFlagStatus(flag) === SWITCHABLE) {- flag.preferredState = targetState- this.writeToCookie()- this.writeToSession()- if (name === "analytics") {- this.syncAnalyticsWithLocalStorage()- }+ if (flag.status === SWITCHABLE) {+ this.setPreferredState(name, targetState)+ this.updateStorage(name)} else {warn(`Cannot set preferred state for non-switchable flag: ${name}`)}@@ -160,74 +291,15 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {*/syncAnalyticsWithLocalStorage() {const storage = useStorage<boolean | null>("plausible_ignore", null)- storage.value =- 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+ storage.value = this.flags.analytics.state === ON ? null : true},- isSwitchable(name: string): boolean {+ isSwitchable(name: string) {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+ throw new Error(`Invalid feature flag accessed: ${name}`)}- return OFF+ return this.flags[name].status === SWITCHABLE},-- /**- * 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.*@@ -235,8 +307,11 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {** @returns `true` if the flag is on, false otherwise*/- isOn(name: FlagName): boolean {- return this.featureState(name) === ON+ isOn(name: string) {+ if (!isFlagName(name)) {+ throw new Error(`Invalid feature flag accessed: ${name}`)+ }+ return this.flags[name].state === ON},},})diff --git a/frontend/src/types/feature-flag.ts b/frontend/src/types/feature-flag.tsindex 8fe6ab4e4..7af6b6a93 100644--- a/frontend/src/types/feature-flag.ts+++ b/frontend/src/types/feature-flag.ts@@ -1,3 +1,5 @@+import featureData from "~~/feat/feature-flags.json"+import type {FeatureState,FlagStatus,@@ -5,15 +7,30 @@ import type {} from "~/constants/feature-flag"import type { DeployEnv } from "~/constants/deploy-env"-export interface FeatureFlag {- status: FlagStatus | Record<DeployEnv, FlagStatus>+export type FlagName = keyof (typeof featureData)["features"]++export type FlagStatusRecord = string | Partial<Record<DeployEnv, string>>+/**+ * The record of a feature flag from the json file.+ */+export interface FeatureFlagRecord {+ status: FlagStatusRecorddescription?: stringdata?: unknowndefaultState?: FeatureState- preferredState?: FeatureState // only set for switchable flag with known preferencesupportsQuery?: boolean // default: truestorage: Storage}++/**+ * The feature flag with the status resolved based on the current environment.+ */+export type FeatureFlag = Omit<FeatureFlagRecord, "status"> & {+ name: keyof (typeof featureData)["features"]+ status: FlagStatus+ state: FeatureState+ preferredState: FeatureState | undefined+}diff --git a/frontend/test/playwright/e2e/preferences.spec.ts b/frontend/test/playwright/e2e/preferences.spec.tsindex 3fe87d8ab..b06eeea6d 100644--- a/frontend/test/playwright/e2e/preferences.spec.ts+++ b/frontend/test/playwright/e2e/preferences.spec.ts@@ -4,10 +4,8 @@ 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+import { getFlagStatus } from "~/stores/feature-flag"+import type { FeatureFlag, FlagName } from "~/types/feature-flag"const getFeatureCookies = async (page: Page, cookieName: string) => {const cookies = await page.context().cookies()@@ -30,7 +28,7 @@ const getFeaturesToTest = () => {} as constfor (const [name, state] of Object.entries(testableFeatures)) {const flag = featureData.features[name as FlagName] as FeatureFlag- if (_getFlagStatus(flag, deployEnv) !== "switchable") {+ if (getFlagStatus(flag) !== "switchable") {throw new Error(`Feature ${name} is not switchable`)}if (flag.defaultState !== state) {diff --git a/frontend/test/unit/specs/stores/feature-flag-store.spec.js b/frontend/test/unit/specs/stores/feature-flag-store.spec.jsindex cce69b7e4..1beb75826 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 } from "~/stores/feature-flag"+import { getFlagStatus, useFeatureFlagStore } from "~/stores/feature-flag"import { OFF, COOKIE, SESSION } from "~/constants/feature-flag"jest.mock(@@ -51,8 +51,14 @@ jest.mock()describe("Feature flag store", () => {+ let initialEnvbeforeEach(() => {setActivePinia(createPinia())+ initialEnv = process.env.DEPLOYMENT_ENV+ })++ afterEach(() => {+ process.env.DEPLOYMENT_ENV = initialEnv})it("initialises state from JSON", () => {@@ -143,10 +149,12 @@ describe("Feature flag store", () => {${"staging"} | ${"off"}${"production"} | ${"off"}`(- "returns $expectedState for $environment",+ "returns $featureState for $environment",({ environment, featureState }) => {+ // The value is cleaned up in afterEach+ process.env.DEPLOYMENT_ENV = environmentconst featureFlagStore = useFeatureFlagStore()- featureFlagStore.$nuxt.$config.deploymentEnv = environment+expect(featureFlagStore.featureState("feat_env_specific")).toEqual(featureState)@@ -164,13 +172,12 @@ describe("Feature flag store", () => {`("handles fallback for missing $environment",({ environment, flagStatus }) => {- const featureFlagStore = useFeatureFlagStore()- featureFlagStore.$nuxt.$config.deploymentEnv = environment- expect(- useFeatureFlagStore().getFlagStatus({- status: { staging: "switchable" },- })- ).toEqual(flagStatus)+ // The value is cleaned up in afterEach+ process.env.DEPLOYMENT_ENV = environment+ const actualStatus = getFlagStatus({+ status: { staging: "switchable" },+ })+ expect(actualStatus).toEqual(flagStatus)})@@ -180,8 +187,11 @@ describe("Feature flag store", () => {${SESSION} | ${"feat_switchable_optin"}`("returns mapping of switchable flags", ({ storage, flagName }) => {const featureFlagStore = useFeatureFlagStore()- const flagStateMap = featureFlagStore.flagStateMap(storage)+ featureFlagStore.initFromCookies({+ [flagName]: featureFlagStore.flags[flagName].defaultState,+ })+ const flagStateMap = featureFlagStore.flagStateMap(storage)expect(flagStateMap).toHaveProperty(flagName)expect(flagStateMap).not.toHaveProperty("feat_enabled")diff --git a/frontend/test/unit/specs/stores/search-store.spec.js b/frontend/test/unit/specs/stores/search-store.spec.jsindex e6deeb8cc..8daa2d5f6 100644--- a/frontend/test/unit/specs/stores/search-store.spec.js+++ b/frontend/test/unit/specs/stores/search-store.spec.js@@ -491,12 +491,14 @@ describe("Search Store", () => {`("changing searchType from $searchType clears all but $expectedFilterCount $nextSearchType filters",async ({ searchType, nextSearchType, expectedFilterCount }) => {- const searchStore = useSearchStore()- searchStore.setSearchType(searchType)-+ // We need to switch on the additional_search_types feature flag+ // to be able to switch to video.const featureFlagStore = useFeatureFlagStore()featureFlagStore.toggleFeature("additional_search_types", "on")+ const searchStore = useSearchStore()+ searchStore.setSearchType(searchType)+// Set all filters to checkedfor (let ft in searchStore.filters) {for (let f of searchStore.filters[ft]) {