Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Create a proof-of-concept for feature flags (#1270)
Dhruv Bhanushalica08f8ab5950
diff --git a/feat/feature-flags.json b/feat/feature-flags.jsonnew file mode 100644index 000000000..204d169a1--- /dev/null+++ b/feat/feature-flags.json@@ -0,0 +1,17 @@+{+ "features": {+ "feat_disabled": {+ "status": "disabled",+ "description": "Will always be disabled"+ },+ "feat_enabled": {+ "status": "enabled",+ "description": "Will always be enabled"+ },+ "feat_switchable": {+ "status": "switchable",+ "description": "Can be switched between on and off",+ "defaultState": "on"+ }+ }+}diff --git a/nuxt.config.ts b/nuxt.config.tsindex c8d3939a6..5e90fac01 100644--- a/nuxt.config.ts+++ b/nuxt.config.ts@@ -192,6 +192,7 @@ const config: NuxtConfig = {'@nuxtjs/redirect-module','@nuxtjs/sentry','@nuxtjs/sitemap',+ 'cookie-universal-nuxt',],serverMiddleware: [{ path: '/healthcheck', handler: '~/server-middleware/healthcheck.js' },diff --git a/package.json b/package.jsonindex 872d01aad..6560adb00 100644--- a/package.json+++ b/package.json@@ -75,6 +75,7 @@"build-url": "^6.0.1","case": "^1.6.3","clipboard": "^2.0.8",+ "cookie-universal-nuxt": "^2.1.5","core-js": "^3.16.1","express-useragent": "^1.0.15","focus-trap": "^6.7.1",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 49e6a2d52..1a4cb9150 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -45,6 +45,7 @@ specifiers:build-url: ^6.0.1case: ^1.6.3clipboard: ^2.0.8+ cookie-universal-nuxt: ^2.1.5core-js: ^3.16.1eslint: ^8.11.0eslint-config-prettier: ^8.5.0@@ -115,6 +116,7 @@ dependencies:build-url: 6.0.1case: 1.6.3clipboard: 2.0.8+ cookie-universal-nuxt: 2.1.5core-js: 3.21.1express-useragent: 1.0.15focus-trap: 6.7.1@@ -5566,6 +5568,10 @@ packages:'@types/node': 16.11.13dev: true+ /@types/cookie/0.3.3:+ resolution: {integrity: sha512-LKVP3cgXBT9RYj+t+9FDKwS5tdI+rPBXaNSkma7hvqy35lc7mAokC2zsqWJH0LaqIt3B962nuYI77hsJoT1gow==}+ dev: false+/@types/eslint/7.29.0:resolution: {integrity: sha512-VNcvioYDH8/FxaeTKkM4/TiTwt6pBV9E3OfGmvaw8tPl0rrHCJ4Ll15HRT+pMiFAf/MLQvAzC+6RzUMEL9Ceng==}dependencies:@@ -8213,6 +8219,20 @@ packages:resolution: {integrity: sha1-4wOogrNCzD7oylE6eZmXNNqzriw=}dev: true+ /cookie-universal-nuxt/2.1.5:+ resolution: {integrity: sha512-P0WCTKIyemWNtHi9lxrS5cxZmieOIEjt28B7Alu6cdSB9RqtUtpkqYyV9PRK6oJrT5eIPDYjHsJQlh6SUrFJOg==}+ dependencies:+ '@types/cookie': 0.3.3+ cookie-universal: 2.1.5+ dev: false++ /cookie-universal/2.1.5:+ resolution: {integrity: sha512-nqOOmEkovCQxNYGIyzhcwsmh4c7xnxe7RWdiYFOoml9MP4L32IlU3LdPC7r7nQEnnM+9Uxlk/UhtvBl5is6M/w==}+ dependencies:+ '@types/cookie': 0.3.3+ cookie: 0.4.2+ dev: false+/cookie/0.3.1:resolution: {integrity: sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=}engines: {node: '>= 0.6'}diff --git a/src/components/VCheckbox/VCheckbox.vue b/src/components/VCheckbox/VCheckbox.vueindex 44b6d11e3..ffe99d141 100644--- a/src/components/VCheckbox/VCheckbox.vue+++ b/src/components/VCheckbox/VCheckbox.vue@@ -132,6 +132,7 @@ export default VCheckbox@apply focus:outline-none focus:ring focus:ring-offset-2 focus:ring-pink;@apply disabled:bg-dark-charcoal-10 disabled:border-dark-charcoal-40;@apply checked:bg-dark-charcoal;+ @apply checked:disabled:bg-dark-charcoal-40;}.checkmark {@apply absolute start-0 w-5 h-5 text-white;diff --git a/src/constants/deploy-env.ts b/src/constants/deploy-env.tsnew file mode 100644index 000000000..c90a9f43f--- /dev/null+++ b/src/constants/deploy-env.ts@@ -0,0 +1,10 @@+export const LOCAL = 'local'+export const DEVELOPMENT = 'development'+export const STAGING = 'staging'+export const PRODUCTION = 'production'++// The order of the environments is important. They should be arranged in+// increasing order of code-readiness, from local to production.+export const DEPLOY_ENVS = [LOCAL, DEVELOPMENT, STAGING, PRODUCTION] as const++export type DeployEnv = typeof DEPLOY_ENVS[number]diff --git a/src/constants/feature-flag.ts b/src/constants/feature-flag.tsnew file mode 100644index 000000000..67f7f0743--- /dev/null+++ b/src/constants/feature-flag.ts@@ -0,0 +1,14 @@+export const ENABLED = 'enabled'+export const DISABLED = 'disabled'+export const SWITCHABLE = 'switchable'++export const FLAG_STATUSES = [ENABLED, DISABLED, SWITCHABLE] as const++export type FlagStatus = typeof FLAG_STATUSES[number]++export const ON = 'on'+export const OFF = 'off'++export const FEATURE_STATES = [ON, OFF] as const++export type FeatureState = typeof FEATURE_STATES[number]diff --git a/src/locales/en.json b/src/locales/en.jsonindex e47b2f3c4..53e50122e 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -630,5 +630,19 @@"see-image": "See all images","see-audio": "See all audio"},- "skip-to-content": "Skip to content"+ "skip-to-content": "Skip to content",+ "pref-page": {+ "title": "Preferences",+ "non-switchable": {+ "title": "Non-switchable features",+ "desc": "You cannot modify the status of these features."+ },+ "switchable": {+ "title": "Switchable features",+ "desc": "You can toggle these features on or off as you like and your preferences will be saved in a cookie."+ },+ "store-state": "Store state",+ "content-filtering": "Content filtering",+ "explanation": "Shown because {feat-name} is {feat-state}"+ }}diff --git a/src/locales/po-files/openverse.pot b/src/locales/po-files/openverse.potindex 1df0ed411..092e379db 100644--- a/src/locales/po-files/openverse.pot+++ b/src/locales/po-files/openverse.pot@@ -23,6 +23,43 @@ msgctxt "skip-to-content"msgid "Skip to content"msgstr ""+#: src/pages/preferences.vue:3+msgctxt "pref-page.title"+msgid "Preferences"+msgstr ""++#: src/pages/preferences.vue:37+msgctxt "pref-page.store-state"+msgid "Store state"+msgstr ""++#: src/pages/preferences.vue:40+msgctxt "pref-page.content-filtering"+msgid "Content filtering"+msgstr ""++#. Do not translate words between ### ###.+#: src/pages/preferences.vue:44+msgctxt "pref-page.explanation"+msgid "Shown because ###feat-name### is ###feat-state###"+msgstr ""++msgctxt "pref-page.switchable.title"+msgid "Switchable features"+msgstr ""++msgctxt "pref-page.switchable.desc"+msgid "You can toggle these features on or off as you like and your preferences will be saved in a cookie."+msgstr ""++msgctxt "pref-page.non-switchable.title"+msgid "Non-switchable features"+msgstr ""++msgctxt "pref-page.non-switchable.desc"+msgid "You cannot modify the status of these features."+msgstr ""+msgctxt "search-type.image"msgid "Images"msgstr ""diff --git a/src/middleware/middleware.ts b/src/middleware/middleware.tsindex f0cd9dee9..4135ad405 100644--- a/src/middleware/middleware.ts+++ b/src/middleware/middleware.ts@@ -1,6 +1,7 @@import { sendWindowMessage } from '~/utils/send-message'import { useNavigationStore } from '~/stores/navigation'import { useProviderStore } from '~/stores/provider'+import { useFeatureFlagStore } from '~/stores/feature-flag'import type { Middleware } from '@nuxt/types'@@ -17,7 +18,9 @@ import type { Middleware } from '@nuxt/types'* Currently, one event type is used:* - `urlChange` sends the relative path of the URL on every URL change.*/-const middleware: Middleware = async ({ query, route, $pinia }) => {+const middleware: Middleware = async ({ app, query, route, $pinia }) => {+ /* Nav store */+const navigationStore = useNavigationStore($pinia)if ('embedded' in query) {@@ -33,7 +36,15 @@ const middleware: Middleware = async ({ query, route, $pinia }) => {if (process.client && navigationStore.isReferredFromCc) {navigationStore.setIsReferredFromCc(false)}++ /* Provider store */+const providerStore = useProviderStore($pinia)await providerStore.fetchMediaProviders()++ /* Feature flag store */++ const featureFlagStore = useFeatureFlagStore($pinia)+ featureFlagStore.initFromCookies(app.$cookies.get('features') ?? {})}export default middlewarediff --git a/src/pages/preferences.vue b/src/pages/preferences.vuenew file mode 100644index 000000000..fd9d42f22--- /dev/null+++ b/src/pages/preferences.vue@@ -0,0 +1,125 @@+<template>+ <VContentPage>+ <h1>{{ $t('pref-page.title') }}</h1>++ <div v-for="isSwitchable in [false, true]" :key="isSwitchable">+ <h2>+ {{ $t(`pref-page.${isSwitchable ? '' : 'non-'}switchable.title`) }}+ </h2>+ <p>+ {{ $t(`pref-page.${isSwitchable ? '' : 'non-'}switchable.desc`) }}+ </p>+ <ul class="!ps-0">+ <template v-for="(feature, name) in flags">+ <li+ v-if="(feature.status === SWITCHABLE) === isSwitchable"+ :key="name"+ class="flex flex-row items-center"+ >+ <VCheckbox+ :id="name"+ class="flex-row items-center"+ :checked="featureState(name) === ON"+ :disabled="!isSwitchable"+ @change="handleChange"+ >+ <div>+ <strong>{{ name }}</strong>+ <br />+ {{ feature.description }}+ </div>+ </VCheckbox>+ </li>+ </template>+ </ul>+ </div>++ <h2>{{ $t('pref-page.store-state') }}</h2>+ <pre><code>{{ flags }}</code></pre>++ <h2>{{ $t('pref-page.content-filtering') }}</h2>+ <ul>+ <template v-for="(_, featName) in flags">+ <template v-for="featState in FEATURE_STATES">+ <i18n+ v-if="featureState(featName) === featState"+ :key="`${featName}-${featState}`"+ path="pref-page.explanation"+ tag="li"+ >+ <template #feat-name+ ><code>{{ featName }}</code></template+ >+ <template #feat-state+ ><code>{{ featState }}</code></template+ >+ </i18n>+ </template>+ </template>+ <i18n+ v-if="featureState('feat_nonexistent') === ON"+ path="pref-page.explanation"+ tag="li"+ >+ <template #feat-name+ ><code>{{ $t('feat_nonexistent') }}</code></template+ >+ <template #feat-state+ ><code>{{ $t(ON) }}</code></template+ >+ </i18n>+ </ul>+ </VContentPage>+</template>++<script lang="ts">+import { computed, defineComponent, useContext } from '@nuxtjs/composition-api'++import { useFeatureFlagStore } from '~/stores/feature-flag'+import { SWITCHABLE, ON, OFF, FEATURE_STATES } from '~/constants/feature-flag'++import VContentPage from '~/components/VContentPage.vue'+import VCheckbox from '~/components/VCheckbox/VCheckbox.vue'++export default defineComponent({+ name: 'VPreferences',+ components: {+ VContentPage,+ VCheckbox,+ },+ setup() {+ const { app } = useContext()+ const featureFlagStore = useFeatureFlagStore()++ const flags = computed(() => featureFlagStore.flags)++ /**+ * Toggle the state of the switchable flag to the preferred value.+ * @param name+ * @param checked+ */+ const handleChange = ({+ name,+ checked,+ }: {+ name: string+ checked: boolean+ }) => {+ featureFlagStore.toggleFeature(name, checked ? ON : OFF)+ app.$cookies.set('features', featureFlagStore.flagStateMap)+ }++ return {+ ON,+ OFF,+ SWITCHABLE,+ FEATURE_STATES,++ flags,+ featureState: featureFlagStore.featureState,++ handleChange,+ }+ },+})+</script>diff --git a/src/stores/feature-flag.ts b/src/stores/feature-flag.tsnew file mode 100644index 000000000..75d504ced--- /dev/null+++ b/src/stores/feature-flag.ts@@ -0,0 +1,115 @@+import { defineStore } from 'pinia'++import featureData from '~~/feat/feature-flags.json'++import { warn } from '~/utils/console'++import type { FeatureFlag } from '~/types/feature-flag'+import type { FeatureState, FlagStatus } from '~/constants/feature-flag'+import {+ ENABLED,+ SWITCHABLE,+ ON,+ OFF,+ DISABLED,+} from '~/constants/feature-flag'+import { LOCAL, DEPLOY_ENVS, DeployEnv } from '~/constants/deploy-env'++export interface FeatureFlagState {+ flags: Record<keyof typeof featureData['features'], 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+ if (typeof flag.status === 'string') return flag.status+ 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]]+ }+ }+ 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+}++export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {+ state: () =>+ ({+ flags: featureData.features,+ } as FeatureFlagState),+ getters: {+ /**+ * Get the state of the named feature, based on config and cookie.+ */+ featureState:+ (state: FeatureFlagState) =>+ (name: keyof typeof featureData['features']): FeatureState => {+ if (name in state.flags) return getFeatureState(state.flags[name])+ else {+ warn(`Invalid feature flag accessed: ${name}`)+ return ON+ }+ },+ /**+ * Get the mapping of switchable features to their preferred states.+ */+ flagStateMap: (state: FeatureFlagState): Record<string, FeatureState> => {+ const featureMap: Record<string, FeatureState> = {}+ Object.entries(state.flags).forEach(([name, flag]) => {+ if (getFlagStatus(flag) === SWITCHABLE)+ featureMap[name] = getFeatureState(flag)+ })+ return featureMap+ },+ },+ actions: {+ /**+ * Given a list of key value pairs of flags and their preferred states,+ * populate the store state to match the cookie.+ *+ * @param cookies - mapping of feature flags and their preferred states+ */+ initFromCookies(cookies: Record<string, FeatureState>) {+ Object.entries(this.flags).forEach(([name, flag]) => {+ if (getFlagStatus(flag) === SWITCHABLE)+ flag.preferredState = cookies[name]+ })+ },+ /**+ * 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: keyof typeof featureData['features'],+ targetState: FeatureState+ ) {+ const flag = this.flags[name]+ if (getFlagStatus(flag) === SWITCHABLE) flag.preferredState = targetState+ else warn(`Cannot set preferred state for non-switchable flag: ${name}`)+ },+ },+})diff --git a/src/types/feature-flag.ts b/src/types/feature-flag.tsnew file mode 100644index 000000000..211cbeaa4--- /dev/null+++ b/src/types/feature-flag.ts@@ -0,0 +1,11 @@+import type { FeatureState, FlagStatus } from '~/constants/feature-flag'+import type { DeployEnv } from '~/constants/deploy-env'++export interface FeatureFlag {+ status: FlagStatus | Record<DeployEnv, FlagStatus>+ description?: string+ data?: unknown++ defaultState?: FeatureState+ preferredState?: FeatureState // only set for switchable flag with known preference+}diff --git a/test/unit/specs/stores/feature-flag-store.spec.js b/test/unit/specs/stores/feature-flag-store.spec.jsnew file mode 100644index 000000000..c92e8f9a0--- /dev/null+++ b/test/unit/specs/stores/feature-flag-store.spec.js@@ -0,0 +1,136 @@+import { setActivePinia, createPinia } from 'pinia'++import { useFeatureFlagStore, getFlagStatus } from '~/stores/feature-flag'+import { OFF, ON } from '~/constants/feature-flag'++jest.mock(+ '~~/feat/feature-flags.json',+ () => ({+ features: {+ feat_enabled: {+ status: 'enabled',+ description: 'Will always be enabled',+ },+ feat_disabled: {+ status: 'disabled',+ description: 'Will always be disabled',+ },+ feat_switchable_optout: {+ status: 'switchable',+ description: 'Can be switched between on and off',+ defaultState: 'on',+ },+ feat_switchable_optin: {+ status: 'switchable',+ description: 'Can be switched between on and off',+ defaultState: 'off',+ },+ feat_env_specific: {+ status: {+ local: 'enabled',+ staging: 'switchable',+ production: 'disabled',+ },+ description: 'Depends on the environment',+ defaultState: 'off',+ },+ },+ }),+ { virtual: true }+)++describe('Feature flag store', () => {+ beforeEach(() => {+ setActivePinia(createPinia())+ })++ it('initialises state from JSON', () => {+ const featureFlagStore = useFeatureFlagStore()+ expect(Object.keys(featureFlagStore.flags).length).toBe(5)+ })++ it.each`+ flagName | featureState+ ${'feat_enabled'} | ${'on'}+ ${'feat_disabled'} | ${'off'}+ `(+ 'does not allow modification of fixed flags',+ ({ flagName, featureState }) => {+ const featureFlagStore = useFeatureFlagStore()+ expect(featureFlagStore.featureState(flagName)).toEqual(featureState)+ }+ )++ it.each`+ flagName | doCookieInit | featureState+ ${'feat_switchable_optout'} | ${false} | ${'on'}+ ${'feat_switchable_optin'} | ${false} | ${'off'}+ ${'feat_switchable_optout'} | ${true} | ${'off'}+ ${'feat_switchable_optin'} | ${true} | ${'on'}+ `(+ 'cascades flag $flagName from cookies',+ ({ flagName, doCookieInit, featureState }) => {+ const featureFlagStore = useFeatureFlagStore()+ if (doCookieInit)+ featureFlagStore.initFromCookies({+ feat_switchable_optout: OFF,+ feat_switchable_optin: ON,+ })+ expect(featureFlagStore.featureState(flagName)).toEqual(featureState)+ }+ )++ it.each`+ environment | featureState+ ${'local'} | ${'on'}+ ${'staging'} | ${'off'}+ ${'production'} | ${'off'}+ `(+ '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()+ expect(featureFlagStore.featureState('feat_env_specific')).toEqual(+ featureState+ )++ // Restore `DEPLOYMENT_ENV` value+ process.env.DEPLOYMENT_ENV = old_env+ }+ )++ it.each`+ environment | flagStatus+ ${'local'} | ${'switchable'}+ ${'staging'} | ${'switchable'}+ ${'production'} | ${'disabled'}+ `(+ '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+ }+ )++ it('returns mapping of switchable flags', () => {+ const featureFlagStore = useFeatureFlagStore()+ const flagStateMap = featureFlagStore.flagStateMap++ expect(flagStateMap).toHaveProperty('feat_switchable_optout')+ expect(flagStateMap).toHaveProperty('feat_switchable_optin')++ expect(flagStateMap).not.toHaveProperty('feat_enabled')+ expect(flagStateMap).not.toHaveProperty('feat_disabled')+ })+})