Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Add feature flagging support via PH (#31101)

Joshen Lim3a89c81b634a
diff --git a/apps/studio/components/interfaces/Organization/Documents/DPA.tsx b/apps/studio/components/interfaces/Organization/Documents/DPA.tsx
index d2a119b3292..4a5267dafa5 100644
--- a/apps/studio/components/interfaces/Organization/Documents/DPA.tsx
+++ b/apps/studio/components/interfaces/Organization/Documents/DPA.tsx
@@ -1,9 +1,10 @@
+import { ExternalLink } from 'lucide-react'
+
import {
ScaffoldSection,
ScaffoldSectionContent,
ScaffoldSectionDetail,
} from 'components/layouts/Scaffold'
-import { ExternalLink } from 'lucide-react'
import { Button } from 'ui'
const DPA = () => {
@@ -32,16 +33,16 @@ const DPA = () => {
</div>
</ScaffoldSectionDetail>
<ScaffoldSectionContent className="flex items-center justify-center h-full">
- <a
- href="https://supabase.com/downloads/docs/Supabase+DPA+231211.pdf"
- target="_blank"
- rel="noreferrer noopener"
- download={true}
- >
- <Button type="default" iconRight={<ExternalLink />}>
+ <Button asChild type="default" iconRight={<ExternalLink />}>
+ <a
+ download={true}
+ target="_blank"
+ rel="noreferrer noopener"
+ href="https://supabase.com/downloads/docs/Supabase+DPA+231211.pdf"
+ >
View DPA
- </Button>
- </a>
+ </a>
+ </Button>
</ScaffoldSectionContent>
</ScaffoldSection>
)
diff --git a/apps/studio/components/ui/Flag/FlagContext.ts b/apps/studio/components/ui/Flag/FlagContext.ts
index 6c58ab54c84..a848bb0f63e 100644
--- a/apps/studio/components/ui/Flag/FlagContext.ts
+++ b/apps/studio/components/ui/Flag/FlagContext.ts
@@ -1,5 +1,5 @@
import { createContext } from 'react'
-const FlagContext = createContext({})
+const FlagContext = createContext({ configcat: {}, posthog: {} })
export default FlagContext
diff --git a/apps/studio/components/ui/Flag/FlagProvider.tsx b/apps/studio/components/ui/Flag/FlagProvider.tsx
index c846e102a88..317af7401d4 100644
--- a/apps/studio/components/ui/Flag/FlagProvider.tsx
+++ b/apps/studio/components/ui/Flag/FlagProvider.tsx
@@ -5,6 +5,7 @@ import { PropsWithChildren, useEffect, useState } from 'react'
import { useUser } from 'lib/auth'
import { getFlags } from 'lib/configcat'
import { IS_PLATFORM } from 'lib/constants'
+import { CallFeatureFlagsResponse, getPHFeatureFlags } from 'lib/posthog'
import FlagContext from './FlagContext'
var getCookies = function () {
@@ -19,14 +20,27 @@ var getCookies = function () {
return cookies
}
+export type FlagProviderStore = {
+ configcat: { [key: string]: boolean | string }
+ posthog: CallFeatureFlagsResponse
+}
+
const FlagProvider = ({ children }: PropsWithChildren<{}>) => {
const user = useUser()
const { Provider } = FlagContext
- const [store, setStore] = useState({})
+ const [store, setStore] = useState<FlagProviderStore>({ configcat: {}, posthog: {} })
const processFlags = async (user?: User) => {
- const flagStore: any = {}
+ const flagStore: FlagProviderStore = { configcat: {}, posthog: {} }
+
+ // Load PH flags
+ if (user) {
+ const flags = await getPHFeatureFlags()
+ if (flags) flagStore.posthog = flags
+ }
+
+ // Load ConfigCat flags
const flagValues = await getFlags(user)
let overridesCookieValue: Record<string, boolean> = {}
try {
@@ -35,7 +49,8 @@ const FlagProvider = ({ children }: PropsWithChildren<{}>) => {
} catch {}
flagValues.forEach((item) => {
- flagStore[item.settingKey] = overridesCookieValue[item.settingKey] ?? item.settingValue
+ flagStore['configcat'][item.settingKey] =
+ overridesCookieValue[item.settingKey] ?? item.settingValue
})
setStore(flagStore)
}
@@ -50,7 +65,11 @@ const FlagProvider = ({ children }: PropsWithChildren<{}>) => {
return (
<Provider value={store}>
- <FlagValues values={store} />
+ {/*
+ [Joshen] Just support configcat flags in Vercel flags for now for simplicity
+ although I think it should be fairly simply to support PH too
+ */}
+ <FlagValues values={store.configcat} />
{children}
</Provider>
)
diff --git a/apps/studio/hooks/ui/useFlag.ts b/apps/studio/hooks/ui/useFlag.ts
index 1178ebdefff..798013f0c99 100644
--- a/apps/studio/hooks/ui/useFlag.ts
+++ b/apps/studio/hooks/ui/useFlag.ts
@@ -1,23 +1,65 @@
import { useContext } from 'react'
+import * as Sentry from '@sentry/nextjs'
+
import FlagContext from 'components/ui/Flag/FlagContext'
+import { FlagProviderStore } from 'components/ui/Flag/FlagProvider'
+import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { trackFeatureFlag } from 'lib/posthog'
+
+const isObjectEmpty = (obj: Object) => {
+ return Object.keys(obj).length === 0
+}
export function useFlag<T = boolean>(name: string) {
const project = useSelectedProject()
- const store: any = useContext(FlagContext)
+ const flagStore = useContext(FlagContext) as FlagProviderStore
+
+ const store = flagStore.configcat
// Temporary override as Fly projects are cant seem to upgrade their compute with the new disk UI
if (name === 'diskAndComputeForm' && project?.cloud_provider === 'FLY') {
return false
}
- const isObjectEmpty = (objectName: Object) => {
- return Object.keys(objectName).length === 0
- }
-
if (!isObjectEmpty(store) && store[name] === undefined) {
- console.error(`Flag key "${name}" does not exist in flagStore`)
+ console.error(`Flag key "${name}" does not exist in ConfigCat flag store`)
return false
}
return store[name] as T
}
+
+export function usePHFlag<T = string | boolean>(name: string) {
+ const flagStore = useContext(FlagContext) as FlagProviderStore
+ // [Joshen] Prepend PH flags with "PH" in local storage for easier identification of PH flags
+ const [trackedValue, setTrackedValue] = useLocalStorageQuery(`ph_${name}`, '')
+
+ const store = flagStore.posthog
+ const flagValue = store[name]
+
+ // Flag store has not been initialized
+ if (isObjectEmpty(store)) return undefined
+
+ if (!isObjectEmpty(store) && flagValue === undefined) {
+ console.error(`Flag key "${name}" does not exist in PostHog flag store`)
+ return undefined
+ }
+
+ if (trackedValue !== flagValue) {
+ try {
+ // [Joshen] Only fire the track endpoint once across sessions unless the flag value changes
+ // Note: This cannot guarantee excess calls in the event for e.g user clears local storage or uses incognito
+ // trackFeatureFlag checks for telemetry consent before actually firing the request too
+ trackFeatureFlag({ feature_flag_name: name, feature_flag_value: flagValue })
+ setTrackedValue(flagValue as string)
+ } catch (error: any) {
+ Sentry.withScope((scope) => {
+ scope.setTag('type', 'phTrackFailure')
+ Sentry.captureException(error)
+ })
+ console.error(error.message)
+ }
+ }
+
+ return flagValue as T
+}
diff --git a/apps/studio/lib/posthog.ts b/apps/studio/lib/posthog.ts
new file mode 100644
index 00000000000..5a0797dc5a8
--- /dev/null
+++ b/apps/studio/lib/posthog.ts
@@ -0,0 +1,28 @@
+import { components } from 'api-types'
+import { IS_PLATFORM } from './constants'
+import { handleError, get, post } from 'data/fetchers'
+import { LOCAL_STORAGE_KEYS } from 'common'
+
+type TrackFeatureFlagVariables = components['schemas']['TelemetryFeatureFlagBodyDto']
+export type CallFeatureFlagsResponse = components['schemas']['TelemetryCallFeatureFlagsResponseDto']
+
+export async function getPHFeatureFlags() {
+ if (!IS_PLATFORM) return undefined
+ const { data, error } = await get(`/platform/telemetry/feature-flags`, {})
+
+ if (error) handleError(error)
+ return data as CallFeatureFlagsResponse
+}
+
+export async function trackFeatureFlag(body: TrackFeatureFlagVariables) {
+ const consent =
+ (typeof window !== 'undefined'
+ ? localStorage.getItem(LOCAL_STORAGE_KEYS.TELEMETRY_CONSENT)
+ : null) === 'true'
+
+ if (!consent || !IS_PLATFORM) return undefined
+ const { data, error } = await post(`/platform/telemetry/feature-flags/track`, { body })
+
+ if (error) handleError(error)
+ return data
+}
diff --git a/packages/api-types/types/api.d.ts b/packages/api-types/types/api.d.ts
index 3cb1c88ef2e..afdcc0f3652 100644
--- a/packages/api-types/types/api.d.ts
+++ b/packages/api-types/types/api.d.ts
@@ -1129,6 +1129,14 @@ export interface paths {
/** Sends analytics server event */
post: operations['TelemetryEventController_sendServerEventV2']
}
+ '/platform/telemetry/feature-flags': {
+ /** Call feature flags */
+ get: operations['TelemetryFeatureFlagsController_callFeatureFlag']
+ }
+ '/platform/telemetry/feature-flags/track': {
+ /** Track feature flag called */
+ post: operations['TelemetryFeatureFlagsController_trackFeatureFlag']
+ }
'/platform/telemetry/groups/identify': {
/** Send analytics group identify event */
post: operations['TelemetryGroupsController_groupIdentify']
@@ -1370,6 +1378,10 @@ export interface paths {
/** Reports email abuse from a postmark */
post: operations['ProjectEmailAbuseController_reportEmailAbuseWebhookPostmark']
}
+ '/system/projects/email-abuse/validate': {
+ /** Validates the email address */
+ post: operations['ProjectEmailAbuseController_validateEmailAddress']
+ }
'/system/stripe/webhooks': {
/** Processes Stripe event */
post: operations['StripeWebhooksController_processEvent']
@@ -2079,6 +2091,13 @@ export interface paths {
*/
patch: operations['v1-update-a-branch-config']
}
+ '/v1/branches/{branch_id}/push': {
+ /**
+ * Pushes a database branch
+ * @description Pushes the specified database branch
+ */
+ post: operations['v1-push-a-branch']
+ }
'/v1/branches/{branch_id}/reset': {
/**
* Resets a database branch
@@ -2090,6 +2109,10 @@ export interface paths {
/** [Beta] Authorize user through oauth */
get: operations['v1-authorize-user']
}
+ '/v1/oauth/revoke': {
+ /** [Beta] Revoke oauth app authorization and it's corresponding tokens */
+ post: operations['v1-revoke-token']
+ }
'/v1/oauth/token': {
/** [Beta] Exchange auth code for user's access and refresh token */
post: operations['v1-exchange-oauth-token']
@@ -2301,6 +2324,10 @@ export interface paths {
/** [Beta] Updates project's network restrictions */
post: operations['v1-update-network-restrictions']
}
+ '/v1/projects/{ref}/pause': {
+ /** Pauses the given project */
+ post: operations['v1-pause-a-project']
+ }
'/v1/projects/{ref}/pgsodium': {
/** [Beta] Gets project's pgsodium config */
get: operations['v1-get-pgsodium-config']
@@ -2795,16 +2822,15 @@ export interface components {
| 'PAUSE_FAILED'
| 'RESIZING'
}
- BranchResetResponse: {
- message: string
- workflow_run_id: string
- }
BranchResponse: {
created_at: string
git_branch?: string
id: string
is_default: boolean
- /** Format: int64 */
+ /**
+ * @deprecated
+ * @description This field is deprecated and will not be populated.
+ */
latest_check_run_id?: number
name: string
parent_project_ref: string
@@ -2812,7 +2838,6 @@ export interface components {
/** Format: int32 */
pr_number?: number
project_ref: string
- reset_on_push: boolean
/** @enum {string} */
status:
| 'CREATING_PROJECT'
@@ -2823,6 +2848,10 @@ export interface components {
| 'FUNCTIONS_FAILED'
updated_at: string
}
+ BranchUpdateResponse: {
+ message: string
+ workflow_run_id: string
+ }
Buffer: Record<string, never>
BulkDeleteUserContentResponse: {
id: string
@@ -3843,11 +3872,6 @@ export interface components {
}
projects: components['schemas']['IntegrationVercelProject'][]
}
- GitConfig: {
- owner: string
- ref: string
- repo: string
- }
GitHubAuthorization: {
id: number
sender_id: number
@@ -4351,6 +4375,12 @@ export interface components {
)[]
website: string
}
+ OAuthRevokeTokenBodyDto: {
+ /** Format: uuid */
+ client_id: string
+ client_secret: string
+ refresh_token: string
+ }
OAuthTokenBody: {
client_id: string
client_secret: string
@@ -5888,6 +5918,9 @@ export interface components {
TaxIdResponse: {
tax_id: components['schemas']['TaxId'] | null
}
+ TelemetryCallFeatureFlagsResponseDto: {
+ [key: string]: unknown
+ }
TelemetryEventBodyV2: {
action: string
custom_properties: Record<string, never>
@@ -5904,6 +5937,10 @@ export interface components {
viewport_height: number
viewport_width: number
}
+ TelemetryFeatureFlagBodyDto: {
+ feature_flag_name: string
+ feature_flag_value?: unknown
+ }
TelemetryGroupsIdentityBody: {
organization_slug?: string
project_ref?: string
@@ -6174,6 +6211,10 @@ export interface components {
branch_name?: string
git_branch?: string
persistent?: boolean
+ /**
+ * @deprecated
+ * @description This field is deprecated and will be ignored. Use v1-reset-a-branch endpoint directly instead.
+ */
reset_on_push?: boolean
/** @enum {string} */
status?:
@@ -6477,7 +6518,7 @@ export interface components {
/** Format: email */
billing_email?: string
name?: string
- opt_in_tags: 'AI_SQL_GENERATOR_OPT_IN'[]
+ opt_in_tags?: 'AI_SQL_GENERATOR_OPT_IN'[]
}
UpdateOrganizationResponse: {
billing_email?: string
@@ -6641,12 +6682,15 @@ export interface components {
}
UpdateSubscriptionV2AdminBody: {
payment_method?: string
+ price?: number
price_id?: string
skip_free_plan_validations?: boolean
skip_outstanding_invoice_check?: boolean
skip_payment_method_available_check?: boolean
+ skip_project_updates_enabled_check?: boolean
/** @enum {string} */
tier: 'tier_payg' | 'tier_pro' | 'tier_free' | 'tier_team' | 'tier_enterprise'
+ usage_discounts?: Record<string, never>[]
}
UpdateSupavisorConfigBody: {
default_pool_size?: number | null
@@ -7111,6 +7155,10 @@ export interface components {
name?: string
verify_jwt?: boolean
}
+ ValidateEmailBodyDto: {
+ /** Format: email */
+ email: string
+ }
ValidateQueryBody: {
query: string
}
@@ -7168,7 +7216,7 @@ export interface components {
branch_id: string
check_run_id: number | null
created_at: string
- git_config: components['schemas']['GitConfig'] | null
+ git_config: unknown
id: string
/** @enum {string} */
status:
@@ -14485,6 +14533,38 @@ export interface operations {
}
}
}
+ /** Call feature flags */
+ TelemetryFeatureFlagsController_callFeatureFlag: {
+ responses: {
+ /** @description Feature flags called */
+ 200: {
+ content: {
+ 'application/json': components['schemas']['TelemetryCallFeatureFlagsResponseDto']
+ }
+ }
+ /** @description Failed to call feature flags */
+ 500: {
+ content: never
+ }
+ }
+ }
+ /** Track feature flag called */
+ TelemetryFeatureFlagsController_trackFeatureFlag: {
+ requestBody: {
+ content: {
+ 'application/json': components['schemas']['TelemetryFeatureFlagBodyDto']
+ }
+ }
+ responses: {
+ 201: {
+ content: never
+ }
+ /** @description Failed to track feature flag called */
+ 500: {
+ content: never
+ }
+ }
+ }
/** Send analytics group identify event */
TelemetryGroupsController_groupIdentify: {
requestBody: {
@@ -15014,7 +15094,7 @@ export interface operations {
}
}
responses: {
- 200: {
+ 204: {
content: never
}
/** @description Failed to update subscription */
@@ -15781,6 +15861,28 @@ export interface operations {
}
}
}
+ /** Validates the email address */
+ ProjectEmailAbuseController_validateEmailAddress: {
+ parameters: {
+ header: {
+ apikey: string
+ }
+ }
+ requestBody: {
+ content: {
+ 'application/json': components['schemas']['ValidateEmailBodyDto']
+ }
+ }
+ responses: {
+ 201: {
+ content: never
+ }
+ /** @description Failed to validate email address */
+ 500: {
+ content: never
+ }
+ }
+ }
/** Processes Stripe event */
StripeWebhooksController_processEvent: {
parameters: {
@@ -15896,6 +15998,29 @@ export interface operations {
}
}
}
+ /**
+ * Pushes a database branch
+ * @description Pushes the specified database branch
+ */
+ 'v1-push-a-branch': {
+ parameters: {
+ path: {
+ /** @description Branch ID */
+ branch_id: string
+ }
+ }
+ responses: {
+ 201: {
+ content: {
+ 'application/json': components['schemas']['BranchUpdateResponse']
+ }
+ }
+ /** @description Failed to push database branch */
+ 500: {
+ content: never
+ }
+ }
+ }
/**
* Resets a database branch
* @description Resets the specified database branch
@@ -15910,7 +16035,7 @@ export interface operations {
responses: {
201: {
content: {
- 'application/json': components['schemas']['BranchResetResponse']
+ 'application/json': components['schemas']['BranchUpdateResponse']
}
}
/** @description Failed to reset database branch */
@@ -15939,6 +16064,19 @@ export interface operations {
}
}
}
+ /** [Beta] Revoke oauth app authorization and it's corresponding tokens */
+ 'v1-revoke-token': {
+ requestBody: {
+ content: {
+ 'application/json': components['schemas']['OAuthRevokeTokenBodyDto']
+ }
+ }
+ responses: {
+ 204: {
+ content: never
+ }
+ }
+ }
/** [Beta] Exchange auth code for user's access and refresh token */
'v1-exchange-oauth-token': {
requestBody: {
@@ -16988,6 +17126,23 @@ export interface operations {
}
}
}
+ /** Pauses the given project */
+ 'v1-pause-a-project': {
+ parameters: {
+ path: {
+ /** @description Project ref */
+ ref: string
+ }
+ }
+ responses: {
+ 200: {
+ content: never
+ }
+ 403: {
+ content: never
+ }
+ }
+ }
/** [Beta] Gets project's pgsodium config */
'v1-get-pgsodium-config': {
parameters: {