budibase/packages/backend-core/src/features/index.ts

230 lines
6.8 KiB
TypeScript
Raw Normal View History

import env from "../environment"
import * as context from "../context"
2024-08-07 17:59:33 +02:00
import { PostHog, PostHogOptions } from "posthog-node"
import { IdentityType, UserCtx } from "@budibase/types"
2024-08-07 18:50:39 +02:00
import tracer from "dd-trace"
let posthog: PostHog | undefined
2024-08-07 17:59:33 +02:00
export function init(opts?: PostHogOptions) {
if (env.POSTHOG_TOKEN && env.POSTHOG_API_HOST) {
posthog = new PostHog(env.POSTHOG_TOKEN, {
host: env.POSTHOG_API_HOST,
2024-08-07 17:59:33 +02:00
...opts,
})
}
}
2023-11-20 21:52:29 +01:00
export abstract class Flag<T> {
static boolean(defaultValue: boolean): Flag<boolean> {
return new BooleanFlag(defaultValue)
}
2024-08-07 17:59:33 +02:00
static string(defaultValue: string): Flag<string> {
return new StringFlag(defaultValue)
}
static number(defaultValue: number): Flag<number> {
return new NumberFlag(defaultValue)
}
protected constructor(public defaultValue: T) {}
abstract parse(value: any): T
}
type UnwrapFlag<F> = F extends Flag<infer U> ? U : never
export type FlagValues<T> = {
[K in keyof T]: UnwrapFlag<T[K]>
}
type KeysOfType<T, U> = {
[K in keyof T]: T[K] extends Flag<U> ? K : never
}[keyof T]
class BooleanFlag extends Flag<boolean> {
parse(value: any) {
if (typeof value === "string") {
return ["true", "t", "1"].includes(value.toLowerCase())
}
if (typeof value === "boolean") {
return value
}
throw new Error(`could not parse value "${value}" as boolean`)
}
}
2024-08-07 17:59:33 +02:00
class StringFlag extends Flag<string> {
parse(value: any) {
if (typeof value === "string") {
return value
}
throw new Error(`could not parse value "${value}" as string`)
}
}
class NumberFlag extends Flag<number> {
parse(value: any) {
if (typeof value === "number") {
return value
}
if (typeof value === "string") {
const parsed = parseFloat(value)
if (!isNaN(parsed)) {
return parsed
}
}
throw new Error(`could not parse value "${value}" as number`)
}
}
export class FlagSet<V extends Flag<any>, T extends { [key: string]: V }> {
2024-08-12 10:58:44 +02:00
constructor(private readonly flagSchema: T) {}
defaults(): FlagValues<T> {
2024-08-12 10:58:44 +02:00
return Object.keys(this.flagSchema).reduce((acc, key) => {
const typedKey = key as keyof T
2024-08-12 10:58:44 +02:00
acc[typedKey] = this.flagSchema[key].defaultValue
return acc
}, {} as FlagValues<T>)
}
isFlagName(name: string | number | symbol): name is keyof T {
2024-08-12 10:58:44 +02:00
return this.flagSchema[name as keyof T] !== undefined
}
async get<K extends keyof T>(
key: K,
ctx?: UserCtx
): Promise<FlagValues<T>[K]> {
const flags = await this.fetch(ctx)
return flags[key]
}
async isEnabled<K extends KeysOfType<T, boolean>>(
key: K,
ctx?: UserCtx
): Promise<boolean> {
const flags = await this.fetch(ctx)
return flags[key]
}
async fetch(ctx?: UserCtx): Promise<FlagValues<T>> {
return await tracer.trace("features.fetch", async span => {
const tags: Record<string, any> = {}
2024-08-12 10:58:44 +02:00
const flagValues = this.defaults()
const currentTenantId = context.getTenantId()
const specificallySetFalse = new Set<string>()
const split = (env.TENANT_FEATURE_FLAGS || "")
.split(",")
.map(x => x.split(":"))
for (const [tenantId, ...features] of split) {
if (!tenantId || (tenantId !== "*" && tenantId !== currentTenantId)) {
2024-08-07 18:50:39 +02:00
continue
}
for (let feature of features) {
let value = true
if (feature.startsWith("!")) {
feature = feature.slice(1)
value = false
specificallySetFalse.add(feature)
}
2024-08-07 18:50:39 +02:00
if (!this.isFlagName(feature)) {
throw new Error(`Feature: ${feature} is not an allowed option`)
}
2024-08-12 10:58:44 +02:00
if (typeof flagValues[feature] !== "boolean") {
throw new Error(`Feature: ${feature} is not a boolean`)
}
2024-08-07 18:50:39 +02:00
2024-08-12 10:58:44 +02:00
// @ts-expect-error - TS does not like you writing into a generic type,
// but we know that it's okay in this case because it's just an object.
flagValues[feature] = value
tags[`flags.${feature}.source`] = "environment"
2024-08-07 18:50:39 +02:00
}
}
const license = ctx?.user?.license
if (license) {
for (const feature of license.features) {
2024-08-12 10:58:44 +02:00
if (!this.isFlagName(feature)) {
continue
}
2024-08-12 10:58:44 +02:00
if (
flagValues[feature] === true ||
specificallySetFalse.has(feature)
) {
// If the flag is already set to through environment variables, we
// don't want to override it back to false here.
continue
}
2024-08-12 10:58:44 +02:00
// @ts-expect-error - TS does not like you writing into a generic type,
// but we know that it's okay in this case because it's just an object.
flagValues[feature] = true
tags[`flags.${feature}.source`] = "license"
}
}
const identity = context.getIdentity()
if (posthog && identity?.type === IdentityType.USER) {
const posthogFlags = await posthog.getAllFlagsAndPayloads(identity._id)
for (const [name, value] of Object.entries(posthogFlags.featureFlags)) {
2024-08-12 10:58:44 +02:00
if (!this.isFlagName(name)) {
// We don't want an unexpected PostHog flag to break the app, so we
// just log it and continue.
console.warn(`Unexpected posthog flag "${name}": ${value}`)
continue
}
2024-08-12 10:58:44 +02:00
if (flagValues[name] === true || specificallySetFalse.has(name)) {
// If the flag is already set to through environment variables, we
// don't want to override it back to false here.
continue
}
const payload = posthogFlags.featureFlagPayloads?.[name]
2024-08-12 10:58:44 +02:00
const flag = this.flagSchema[name]
try {
2024-08-12 10:58:44 +02:00
// @ts-expect-error - TS does not like you writing into a generic
// type, but we know that it's okay in this case because it's just
// an object.
flagValues[name] = flag.parse(payload || value)
tags[`flags.${name}.source`] = "posthog"
} catch (err) {
// We don't want an invalid PostHog flag to break the app, so we just
// log it and continue.
console.warn(`Error parsing posthog flag "${name}": ${value}`, err)
}
}
}
2024-08-07 18:50:39 +02:00
2024-08-12 10:58:44 +02:00
for (const [key, value] of Object.entries(flagValues)) {
tags[`flags.${key}.value`] = value
}
span?.addTags(tags)
2024-08-12 10:58:44 +02:00
return flagValues
})
}
}
// This is the primary source of truth for feature flags. If you want to add a
// new flag, add it here and use the `fetch` and `get` functions to access it.
// All of the machinery in this file is to make sure that flags have their
// default values set correctly and their types flow through the system.
export const flags = new FlagSet({
LICENSING: Flag.boolean(false),
GOOGLE_SHEETS: Flag.boolean(false),
USER_GROUPS: Flag.boolean(false),
ONBOARDING_TOUR: Flag.boolean(false),
})