📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Feature flag improvements
Blue Mouseef17058b0f97
diff --git a/backend/apps/cloud/src/feature-flag/dto/feature-flag.dto.ts b/backend/apps/cloud/src/feature-flag/dto/feature-flag.dto.tsindex 83e49d533..a0faad078 100644--- a/backend/apps/cloud/src/feature-flag/dto/feature-flag.dto.ts+++ b/backend/apps/cloud/src/feature-flag/dto/feature-flag.dto.ts@@ -14,9 +14,15 @@ import {Matches,ArrayMaxSize,IsIn,+ IsDateString,} from 'class-validator'import { Type } from 'class-transformer'-import { FeatureFlagType, TargetingRule } from '../entity/feature-flag.entity'+import {+ FeatureFlagSchedule,+ FeatureFlagType,+ TargetingRule,+} from '../entity/feature-flag.entity'+import { FeatureFlagStaleReason, FeatureFlagStatus } from '../evaluation'// Valid targeting rule columns (attribute keys)const VALID_TARGETING_COLUMNS = [@@ -51,6 +57,39 @@ class TargetingRuleDto implements TargetingRule {isExclusive: boolean}+class FeatureFlagScheduleDto implements FeatureFlagSchedule {+ @ApiPropertyOptional({+ description: 'Whether the flag should be enabled after the scheduled time',+ })+ @IsOptional()+ @IsBoolean()+ enabled?: boolean++ @ApiPropertyOptional({+ description: 'Rollout percentage to apply after the scheduled time',+ })+ @IsOptional()+ @IsNumber()+ @Min(0)+ @Max(100)+ rolloutPercentage?: number++ @ApiProperty({ description: 'ISO date and time when the change applies' })+ @IsDateString()+ applyAt: string+}++export class KillFeatureFlagDto {+ @ApiPropertyOptional({+ description:+ 'Value to force for every visitor while the kill switch is active',+ default: false,+ })+ @IsOptional()+ @IsBoolean()+ killSwitchValue?: boolean+}+export class CreateFeatureFlagDto {@ApiProperty({ description: 'Project ID the flag belongs to' })@IsString()@@ -115,6 +154,16 @@ export class CreateFeatureFlagDto {@IsOptional()@IsBoolean()enabled?: boolean++ @ApiPropertyOptional({+ type: FeatureFlagScheduleDto,+ nullable: true,+ description: 'One pending scheduled change for this flag',+ })+ @IsOptional()+ @ValidateNested()+ @Type(() => FeatureFlagScheduleDto)+ scheduledChange?: FeatureFlagScheduleDto | null}export class UpdateFeatureFlagDto {@@ -168,6 +217,16 @@ export class UpdateFeatureFlagDto {@IsOptional()@IsBoolean()enabled?: boolean++ @ApiPropertyOptional({+ type: FeatureFlagScheduleDto,+ nullable: true,+ description: 'One pending scheduled change for this flag',+ })+ @IsOptional()+ @ValidateNested()+ @Type(() => FeatureFlagScheduleDto)+ scheduledChange?: FeatureFlagScheduleDto | null}export class EvaluateFeatureFlagsDto {@@ -208,11 +267,41 @@ export class FeatureFlagDto {@ApiProperty()enabled: boolean+ @ApiProperty({ type: FeatureFlagScheduleDto, nullable: true })+ scheduledChange: FeatureFlagScheduleDto | null++ @ApiProperty()+ killSwitchActive: boolean++ @ApiProperty()+ killSwitchValue: boolean++ @ApiProperty({ nullable: true })+ experimentId: string | null++ @ApiProperty({ nullable: true })+ killedAt: Date | null++ @ApiProperty({ nullable: true })+ targetingUpdatedAt: Date | null+@ApiProperty()pid: string@ApiProperty()created: Date++ @ApiProperty()+ updated: Date++ @ApiProperty({ nullable: true })+ lastEvaluatedAt: string | null++ @ApiProperty({ enum: FeatureFlagStatus })+ status: FeatureFlagStatus++ @ApiProperty({ enum: FeatureFlagStaleReason, isArray: true })+ staleReasons: FeatureFlagStaleReason[]}export class FeatureFlagStatsDto {diff --git a/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts b/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.tsindex f5926b994..c68a8ad96 100644--- a/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts+++ b/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts@@ -6,13 +6,18 @@ import {ManyToOne,PrimaryGeneratedColumn,Unique,+ UpdateDateColumn,} from 'typeorm'import { ApiProperty } from '@nestjs/swagger'import { Project } from '../../project/entity/project.entity'-import { FeatureFlagType, TargetingRule } from '../evaluation'+import {+ FeatureFlagSchedule,+ FeatureFlagType,+ TargetingRule,+} from '../evaluation'// Re-export types for backward compatibility-export { FeatureFlagType, TargetingRule }+export { FeatureFlagSchedule, FeatureFlagType, TargetingRule }@Entity()@Unique(['project', 'key'])@@ -45,6 +50,26 @@ export class FeatureFlag {@Column('json', { nullable: true })targetingRules: TargetingRule[] | null+ @ApiProperty()+ @Column('json', { nullable: true })+ scheduledChange: FeatureFlagSchedule | null++ @ApiProperty()+ @Column('boolean', { default: false })+ killSwitchActive: boolean++ @ApiProperty()+ @Column('boolean', { default: false })+ killSwitchValue: boolean++ @ApiProperty()+ @Column('datetime', { nullable: true })+ killedAt: Date | null++ @ApiProperty()+ @Column('datetime', { nullable: true })+ targetingUpdatedAt: Date | null+@ApiProperty()@Column({type: 'boolean',@@ -64,4 +89,8 @@ export class FeatureFlag {@ApiProperty()@CreateDateColumn()created: Date++ @ApiProperty()+ @UpdateDateColumn()+ updated: Date}diff --git a/backend/apps/cloud/src/feature-flag/evaluation.ts b/backend/apps/cloud/src/feature-flag/evaluation.tsindex e627ac87c..b488bcf2c 100644--- a/backend/apps/cloud/src/feature-flag/evaluation.ts+++ b/backend/apps/cloud/src/feature-flag/evaluation.ts@@ -17,6 +17,27 @@ export interface TargetingRule {isExclusive: boolean // true = exclude, false = include}+export interface FeatureFlagSchedule {+ enabled?: boolean+ rolloutPercentage?: number+ applyAt: string | Date+}++export enum FeatureFlagStatus {+ ENABLED = 'enabled',+ DISABLED = 'disabled',+ SCHEDULED = 'scheduled',+ KILLED = 'killed',+ STALE = 'stale',+}++export enum FeatureFlagStaleReason {+ NOT_EVALUATED_RECENTLY = 'not_evaluated_recently',+ PERMANENT_ROLLOUT = 'permanent_rollout',+ TARGETING_UNCHANGED = 'targeting_unchanged',+ COMPLETED_EXPERIMENT = 'completed_experiment',+}+/*** Minimal feature flag interface required for evaluation* Both cloud (TypeORM entity) and community (ClickHouse) flags should satisfy this@@ -27,6 +48,9 @@ interface EvaluatableFeatureFlag {flagType: FeatureFlagTyperolloutPercentage: numbertargetingRules: TargetingRule[] | null+ scheduledChange?: FeatureFlagSchedule | null+ killSwitchActive?: boolean+ killSwitchValue?: boolean}/**@@ -54,13 +78,19 @@ export function evaluateFlag(profileId: string,attributes?: Record<string, string>,): boolean {- if (!flag.enabled) {+ if (flag.killSwitchActive) {+ return Boolean(flag.killSwitchValue)+ }++ const effectiveFlag = applyDueScheduledChange(flag)++ if (!effectiveFlag.enabled) {return false}- if (flag.targetingRules && flag.targetingRules.length > 0) {+ if (effectiveFlag.targetingRules && effectiveFlag.targetingRules.length > 0) {const matchesTargeting = matchesTargetingRules(- flag.targetingRules,+ effectiveFlag.targetingRules,attributes,)if (!matchesTargeting) {@@ -68,17 +98,57 @@ export function evaluateFlag(}}- if (flag.flagType === FeatureFlagType.BOOLEAN) {+ if (effectiveFlag.flagType === FeatureFlagType.BOOLEAN) {return true}- if (flag.flagType === FeatureFlagType.ROLLOUT) {- return isInRolloutPercentage(flag.key, flag.rolloutPercentage, profileId)+ if (effectiveFlag.flagType === FeatureFlagType.ROLLOUT) {+ return isInRolloutPercentage(+ effectiveFlag.key,+ effectiveFlag.rolloutPercentage,+ profileId,+ )}return false}+export function applyDueScheduledChange<T extends EvaluatableFeatureFlag>(+ flag: T,+ now = new Date(),+): T {+ if (!isScheduledChangeDue(flag.scheduledChange, now)) {+ return flag+ }++ const scheduledChange = flag.scheduledChange++ return {+ ...flag,+ enabled: scheduledChange.enabled ?? flag.enabled,+ rolloutPercentage:+ scheduledChange.rolloutPercentage ?? flag.rolloutPercentage,+ scheduledChange: null,+ }+}++export function isScheduledChangeDue(+ scheduledChange?: FeatureFlagSchedule | null,+ now = new Date(),+): scheduledChange is FeatureFlagSchedule {+ if (!scheduledChange?.applyAt) {+ return false+ }++ const applyAt = new Date(scheduledChange.applyAt)++ if (Number.isNaN(applyAt.getTime())) {+ return false+ }++ return applyAt.getTime() <= now.getTime()+}+/*** Checks if visitor attributes match the targeting rules* Rules are evaluated as AND (all rules must match)diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts b/backend/apps/cloud/src/feature-flag/feature-flag.controller.tsindex 1efe4ba28..bb05d6895 100644--- a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts+++ b/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts@@ -47,6 +47,7 @@ import {FeatureFlagStatsDto,EvaluatedFlagsResponseDto,FeatureFlagProfilesResponseDto,+ KillFeatureFlagDto,} from './dto/feature-flag.dto'import { FeatureFlagService } from './feature-flag.service'import { ExperimentService } from '../experiment/experiment.service'@@ -56,11 +57,21 @@ import {} from '../experiment/entity/experiment.entity'import { clickhouse } from '../common/integrations/clickhouse'import { checkRateLimit, getIPFromHeaders, getIPDetails } from '../common/utils'-import { getExperimentVariant } from './evaluation'+import {+ FeatureFlagSchedule,+ FeatureFlagStaleReason,+ FeatureFlagStatus,+ applyDueScheduledChange,+ getExperimentVariant,+ isScheduledChangeDue,+} from './evaluation'import { trackCustom } from '../common/analytics'const FEATURE_FLAGS_MAXIMUM = 50 // Maximum feature flags per projectconst FEATURE_FLAGS_PAGINATION_MAX_TAKE = 100+const FEATURE_FLAG_EVALUATION_STALE_DAYS = 30+const FEATURE_FLAG_TARGETING_STALE_DAYS = 90+const DAY_IN_MS = 24 * 60 * 60 * 1000@ApiTags('Feature Flag')@Controller(['feature-flag', 'v1/feature-flag'])@@ -74,6 +85,164 @@ export class FeatureFlagController {private readonly experimentService: ExperimentService,) {}+ private validateScheduledChange(+ scheduledChange?: FeatureFlagSchedule | null,+ ) {+ if (!scheduledChange) {+ return+ }++ if (+ scheduledChange.enabled === undefined &&+ scheduledChange.rolloutPercentage === undefined+ ) {+ throw new BadRequestException(+ 'Scheduled change must include enabled or rolloutPercentage',+ )+ }++ const applyAt = new Date(scheduledChange.applyAt)++ if (Number.isNaN(applyAt.getTime())) {+ throw new BadRequestException('Scheduled change date is invalid')+ }++ if (applyAt.getTime() <= Date.now()) {+ throw new BadRequestException('Scheduled change must be in the future')+ }+ }++ private hasTargetingRulesChanged(+ current: FeatureFlag['targetingRules'],+ next?: FeatureFlag['targetingRules'],+ ) {+ if (next === undefined) {+ return false+ }++ return JSON.stringify(current || []) !== JSON.stringify(next || [])+ }++ private getAgeInDays(value?: Date | string | null) {+ if (!value) {+ return Number.POSITIVE_INFINITY+ }++ const date = new Date(value)++ if (Number.isNaN(date.getTime())) {+ return Number.POSITIVE_INFINITY+ }++ return (Date.now() - date.getTime()) / DAY_IN_MS+ }++ private getStaleReasons(+ flag: FeatureFlag,+ lastEvaluatedAt: string | null,+ completedExperimentIds: Set<string>,+ ) {+ const reasons: FeatureFlagStaleReason[] = []+ const createdAge = this.getAgeInDays(flag.created)+ const updatedAge = this.getAgeInDays(flag.updated || flag.created)+ const targetingAge = this.getAgeInDays(+ flag.targetingUpdatedAt || flag.created,+ )++ if (!lastEvaluatedAt && createdAge >= FEATURE_FLAG_EVALUATION_STALE_DAYS) {+ reasons.push(FeatureFlagStaleReason.NOT_EVALUATED_RECENTLY)+ } else if (+ lastEvaluatedAt &&+ this.getAgeInDays(lastEvaluatedAt) >= FEATURE_FLAG_EVALUATION_STALE_DAYS+ ) {+ reasons.push(FeatureFlagStaleReason.NOT_EVALUATED_RECENTLY)+ }++ if (+ flag.flagType === 'rollout' &&+ (flag.rolloutPercentage === 0 || flag.rolloutPercentage === 100) &&+ updatedAge >= FEATURE_FLAG_EVALUATION_STALE_DAYS+ ) {+ reasons.push(FeatureFlagStaleReason.PERMANENT_ROLLOUT)+ }++ if (+ flag.targetingRules?.length > 0 &&+ targetingAge >= FEATURE_FLAG_TARGETING_STALE_DAYS+ ) {+ reasons.push(FeatureFlagStaleReason.TARGETING_UNCHANGED)+ }++ if (flag.experimentId && completedExperimentIds.has(flag.experimentId)) {+ reasons.push(FeatureFlagStaleReason.COMPLETED_EXPERIMENT)+ }++ return reasons+ }++ private getFlagStatus(+ flag: FeatureFlag,+ staleReasons: FeatureFlagStaleReason[],+ ) {+ if (flag.killSwitchActive) {+ return FeatureFlagStatus.KILLED+ }++ if (!isScheduledChangeDue(flag.scheduledChange) && flag.scheduledChange) {+ return FeatureFlagStatus.SCHEDULED+ }++ if (staleReasons.length > 0) {+ return FeatureFlagStatus.STALE+ }++ return flag.enabled ? FeatureFlagStatus.ENABLED : FeatureFlagStatus.DISABLED+ }++ private async decorateFeatureFlags(projectId: string, flags: FeatureFlag[]) {+ const lastEvaluatedAtByFlag =+ await this.featureFlagService.getLastEvaluatedAtByFlagIds(+ projectId,+ flags.map((flag) => flag.id),+ )+ const experimentIds = flags+ .map((flag) => flag.experimentId)+ .filter((id): id is string => Boolean(id))+ const completedExperimentIds = new Set<string>()++ if (experimentIds.length > 0) {+ const experiments = await this.experimentService.findByProject(projectId)++ for (const experiment of experiments) {+ if (+ experiment.status === ExperimentStatus.COMPLETED &&+ experimentIds.includes(experiment.id)+ ) {+ completedExperimentIds.add(experiment.id)+ }+ }+ }++ return _map(flags, (flag) => {+ const effectiveFlag = applyDueScheduledChange(flag)+ const lastEvaluatedAt =+ lastEvaluatedAtByFlag.get(effectiveFlag.id) || null+ const staleReasons = this.getStaleReasons(+ effectiveFlag,+ lastEvaluatedAt,+ completedExperimentIds,+ )++ return {+ ..._omit(effectiveFlag, ['project']),+ pid: projectId,+ lastEvaluatedAt,+ staleReasons,+ status: this.getFlagStatus(effectiveFlag, staleReasons),+ }+ })+ }+@ApiBearerAuth()@Get('/project/:projectId')@Auth(true, true)@@ -106,17 +275,18 @@ export class FeatureFlagController {const safeSkip =typeof skip === 'number' && Number.isFinite(skip) ? Math.max(skip, 0) : 0+ await this.featureFlagService.applyDueScheduledChanges(projectId)+const result = await this.featureFlagService.paginate({ take: safeTake, skip: safeSkip },projectId,search,)- // @ts-expect-error- result.results = _map(result.results, (flag) => ({- ..._omit(flag, ['project']),- pid: projectId,- }))+ result.results = (await this.decorateFeatureFlags(+ projectId,+ result.results,+ )) as anyreturn result}@@ -145,10 +315,18 @@ export class FeatureFlagController {this.projectService.allowedToView(project, userId)- return {- ..._omit(flag, ['project']),- pid: flag.project.id,- }+ await this.featureFlagService.applyDueScheduledChanges(flag.project.id)++ const freshFlag =+ (await this.featureFlagService.findOne({+ where: { id: flagId },+ relations: ['project'],+ })) || flag+ const [decoratedFlag] = await this.decorateFeatureFlags(flag.project.id, [+ freshFlag,+ ])++ return decoratedFlag}@ApiBearerAuth()@@ -226,6 +404,8 @@ export class FeatureFlagController {)}+ this.validateScheduledChange(flagDto.scheduledChange)+try {const flag = new FeatureFlag()flag.key = flagDto.key@@ -234,6 +414,11 @@ export class FeatureFlagController {flag.rolloutPercentage = flagDto.rolloutPercentage ?? 100flag.targetingRules = flagDto.targetingRules || nullflag.enabled = flagDto.enabled ?? true+ flag.scheduledChange = flagDto.scheduledChange || null+ flag.killSwitchActive = false+ flag.killSwitchValue = false+ flag.killedAt = null+ flag.targetingUpdatedAt = new Date()flag.project = projectconst newFlag = await this.featureFlagService.create(flag)@@ -242,10 +427,11 @@ export class FeatureFlagController {ev: 'FEATURE_FLAG_CREATED',})- return {- ..._omit(newFlag, ['project']),- pid: flagDto.pid,- }+ const [decoratedFlag] = await this.decorateFeatureFlags(flagDto.pid, [+ newFlag,+ ])++ return decoratedFlag} catch (reason) {this.logger.error({ reason }, 'Error while creating feature flag')throw new BadRequestException(@@ -317,6 +503,8 @@ export class FeatureFlagController {const { country, city, region } = getIPDetails(ip)this.analyticsService.checkCountryBlacklist(project, country)+ await this.featureFlagService.applyDueScheduledChanges(evaluateDto.pid)+const flags = await this.featureFlagService.findByProject(evaluateDto.pid)const { deviceType, browserName, osName } =@@ -532,6 +720,8 @@ export class FeatureFlagController {}}+ this.validateScheduledChange(flagDto.scheduledChange)+const updatePayload: Partial<FeatureFlag> = {..._pick(flagDto, ['key',@@ -540,9 +730,16 @@ export class FeatureFlagController {'rolloutPercentage','targetingRules','enabled',+ 'scheduledChange',]),}+ if (+ this.hasTargetingRulesChanged(flag.targetingRules, flagDto.targetingRules)+ ) {+ updatePayload.targetingUpdatedAt = new Date()+ }+await this.featureFlagService.update(id, updatePayload)const updatedFlag = await this.featureFlagService.findOne({ where: { id } })@@ -550,10 +747,111 @@ export class FeatureFlagController {throw new NotFoundException('Feature flag not found after update')}- return {- ..._omit(updatedFlag, ['project']),- pid: flag.project.id,+ const [decoratedFlag] = await this.decorateFeatureFlags(flag.project.id, [+ updatedFlag,+ ])++ return decoratedFlag+ }++ @ApiBearerAuth()+ @Put('/:id/kill')+ @Auth()+ @ApiResponse({ status: 200, type: FeatureFlagDto })+ @ApiOperation({ summary: 'Activate the feature flag kill switch' })+ async killFeatureFlag(+ @Param('id') id: string,+ @Body() killDto: KillFeatureFlagDto,+ @CurrentUserId() uid: string,+ @Headers() headers: Record<string, string>,+ @Ip() requestIp: string,+ ) {+ this.logger.log({ id, uid }, 'PUT /feature-flag/:id/kill')+ const ip = getIPFromHeaders(headers) || requestIp || ''++ const flag = await this.featureFlagService.findOneWithRelations(id)++ if (_isEmpty(flag)) {+ throw new NotFoundException()+ }++ this.projectService.allowedToManage(+ flag.project,+ uid,+ 'You are not allowed to manage this feature flag',+ )++ await this.featureFlagService.applyDueScheduledChanges(flag.project.id)++ await this.featureFlagService.update(id, {+ killSwitchActive: true,+ killSwitchValue: killDto.killSwitchValue ?? false,+ killedAt: new Date(),+ })++ await trackCustom(ip, headers['user-agent'], {+ ev: 'FEATURE_FLAG_KILLED',+ })++ const updatedFlag = await this.featureFlagService.findOne({ where: { id } })+ if (!updatedFlag) {+ throw new NotFoundException('Feature flag not found after update')}++ const [decoratedFlag] = await this.decorateFeatureFlags(flag.project.id, [+ updatedFlag,+ ])++ return decoratedFlag+ }++ @ApiBearerAuth()+ @Put('/:id/release-kill-switch')+ @Auth()+ @ApiResponse({ status: 200, type: FeatureFlagDto })+ @ApiOperation({ summary: 'Release the feature flag kill switch' })+ async releaseFeatureFlagKillSwitch(+ @Param('id') id: string,+ @CurrentUserId() uid: string,+ @Headers() headers: Record<string, string>,+ @Ip() requestIp: string,+ ) {+ this.logger.log({ id, uid }, 'PUT /feature-flag/:id/release-kill-switch')+ const ip = getIPFromHeaders(headers) || requestIp || ''++ const flag = await this.featureFlagService.findOneWithRelations(id)++ if (_isEmpty(flag)) {+ throw new NotFoundException()+ }++ this.projectService.allowedToManage(+ flag.project,+ uid,+ 'You are not allowed to manage this feature flag',+ )++ await this.featureFlagService.applyDueScheduledChanges(flag.project.id)++ await this.featureFlagService.update(id, {+ killSwitchActive: false,+ killedAt: null,+ })++ await trackCustom(ip, headers['user-agent'], {+ ev: 'FEATURE_FLAG_KILL_SWITCH_RELEASED',+ })++ const updatedFlag = await this.featureFlagService.findOne({ where: { id } })+ if (!updatedFlag) {+ throw new NotFoundException('Feature flag not found after update')+ }++ const [decoratedFlag] = await this.decorateFeatureFlags(flag.project.id, [+ updatedFlag,+ ])++ return decoratedFlag}@ApiBearerAuth()diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.service.ts b/backend/apps/cloud/src/feature-flag/feature-flag.service.tsindex 6ceb4c47f..10c08f984 100644--- a/backend/apps/cloud/src/feature-flag/feature-flag.service.ts+++ b/backend/apps/cloud/src/feature-flag/feature-flag.service.ts@@ -9,10 +9,12 @@ import {UpdateResult,} from 'typeorm'import { Pagination, PaginationOptionsInterface } from '../common/pagination'+import { clickhouse } from '../common/integrations/clickhouse'import { FeatureFlag } from './entity/feature-flag.entity'import {evaluateFlag as sharedEvaluateFlag,evaluateFlags as sharedEvaluateFlags,+ isScheduledChangeDue,} from './evaluation'@Injectable()@@ -92,6 +94,66 @@ export class FeatureFlagService {})}+ async applyDueScheduledChanges(projectId: string): Promise<void> {+ const flags = await this.featureFlagRepository.find({+ where: { project: { id: projectId } },+ })++ await Promise.all(+ flags+ .filter((flag) => isScheduledChangeDue(flag.scheduledChange))+ .map((flag) =>+ this.featureFlagRepository.update(flag.id, {+ enabled: flag.scheduledChange?.enabled ?? flag.enabled,+ rolloutPercentage:+ flag.scheduledChange?.rolloutPercentage ?? flag.rolloutPercentage,+ scheduledChange: null,+ }),+ ),+ )+ }++ async getLastEvaluatedAtByFlagIds(+ projectId: string,+ flagIds: string[],+ ): Promise<Map<string, string>> {+ const result = new Map<string, string>()++ if (flagIds.length === 0) {+ return result+ }++ const query = `+ SELECT+ flagId,+ max(created) as lastEvaluatedAt+ FROM feature_flag_evaluations+ WHERE+ pid = {pid:FixedString(12)}+ AND flagId IN {flagIds:Array(String)}+ GROUP BY flagId+ `++ try {+ const { data } = await clickhouse+ .query({+ query,+ query_params: { pid: projectId, flagIds },+ })+ .then((resultSet) =>+ resultSet.json<{ flagId: string; lastEvaluatedAt: string }>(),+ )++ for (const row of data) {+ result.set(row.flagId, row.lastEvaluatedAt)+ }+ } catch {+ return result+ }++ return result+ }+async create(flagData: Partial<FeatureFlag>,manager?: EntityManager,diff --git a/backend/apps/community/src/feature-flag/dto/feature-flag.dto.ts b/backend/apps/community/src/feature-flag/dto/feature-flag.dto.tsindex 6237e8737..58eb30333 100644--- a/backend/apps/community/src/feature-flag/dto/feature-flag.dto.ts+++ b/backend/apps/community/src/feature-flag/dto/feature-flag.dto.ts@@ -14,9 +14,16 @@ import {Matches,ArrayMaxSize,IsIn,+ IsDateString,} from 'class-validator'import { Type } from 'class-transformer'-import { FeatureFlagType, TargetingRule } from '../entity/feature-flag.entity'+import {+ FeatureFlagSchedule,+ FeatureFlagStaleReason,+ FeatureFlagStatus,+ FeatureFlagType,+ TargetingRule,+} from '../entity/feature-flag.entity'// Valid targeting rule columns (attribute keys)const VALID_TARGETING_COLUMNS = [@@ -51,6 +58,39 @@ class TargetingRuleDto implements TargetingRule {isExclusive: boolean}+class FeatureFlagScheduleDto implements FeatureFlagSchedule {+ @ApiPropertyOptional({+ description: 'Whether the flag should be enabled after the scheduled time',+ })+ @IsOptional()+ @IsBoolean()+ enabled?: boolean++ @ApiPropertyOptional({+ description: 'Rollout percentage to apply after the scheduled time',+ })+ @IsOptional()+ @IsNumber()+ @Min(0)+ @Max(100)+ rolloutPercentage?: number++ @ApiProperty({ description: 'ISO date and time when the change applies' })+ @IsDateString()+ applyAt: string+}++export class KillFeatureFlagDto {+ @ApiPropertyOptional({+ description:+ 'Value to force for every visitor while the kill switch is active',+ default: false,+ })+ @IsOptional()+ @IsBoolean()+ killSwitchValue?: boolean+}+export class CreateFeatureFlagDto {@ApiProperty({ description: 'Project ID the flag belongs to' })@IsString()@@ -115,6 +155,16 @@ export class CreateFeatureFlagDto {@IsOptional()@IsBoolean()enabled?: boolean++ @ApiPropertyOptional({+ type: FeatureFlagScheduleDto,+ nullable: true,+ description: 'One pending scheduled change for this flag',+ })+ @IsOptional()+ @ValidateNested()+ @Type(() => FeatureFlagScheduleDto)+ scheduledChange?: FeatureFlagScheduleDto | null}export class UpdateFeatureFlagDto {@@ -168,6 +218,16 @@ export class UpdateFeatureFlagDto {@IsOptional()@IsBoolean()enabled?: boolean++ @ApiPropertyOptional({+ type: FeatureFlagScheduleDto,+ nullable: true,+ description: 'One pending scheduled change for this flag',+ })+ @IsOptional()+ @ValidateNested()+ @Type(() => FeatureFlagScheduleDto)+ scheduledChange?: FeatureFlagScheduleDto | null}export class EvaluateFeatureFlagsDto {@@ -208,14 +268,41 @@ export class FeatureFlagDto {@ApiProperty()enabled: boolean+ @ApiProperty({ type: FeatureFlagScheduleDto, nullable: true })+ scheduledChange: FeatureFlagScheduleDto | null++ @ApiProperty()+ killSwitchActive: boolean++ @ApiProperty()+ killSwitchValue: boolean+@ApiProperty()experimentId: string | null+ @ApiProperty({ nullable: true })+ killedAt: string | null++ @ApiProperty({ nullable: true })+ targetingUpdatedAt: string | null+@ApiProperty()pid: string@ApiProperty()created: Date++ @ApiProperty()+ updated: string++ @ApiProperty({ nullable: true })+ lastEvaluatedAt: string | null++ @ApiProperty({ enum: FeatureFlagStatus })+ status: FeatureFlagStatus++ @ApiProperty({ enum: FeatureFlagStaleReason, isArray: true })+ staleReasons: FeatureFlagStaleReason[]}export class FeatureFlagStatsDto {diff --git a/backend/apps/community/src/feature-flag/entity/feature-flag.entity.ts b/backend/apps/community/src/feature-flag/entity/feature-flag.entity.tsindex 326442bd1..a05e28ffa 100644--- a/backend/apps/community/src/feature-flag/entity/feature-flag.entity.ts+++ b/backend/apps/community/src/feature-flag/entity/feature-flag.entity.ts@@ -1,18 +1,33 @@import {+ FeatureFlagSchedule,+ FeatureFlagStaleReason,+ FeatureFlagStatus,FeatureFlagType,TargetingRule,EvaluatableFeatureFlag,} from '../evaluation'// Re-export types for backward compatibility-export { FeatureFlagType, TargetingRule }+export {+ FeatureFlagSchedule,+ FeatureFlagStaleReason,+ FeatureFlagStatus,+ FeatureFlagType,+ TargetingRule,+}export interface FeatureFlag extends EvaluatableFeatureFlag {id: stringdescription: string | nullexperimentId: string | null+ scheduledChange: FeatureFlagSchedule | null+ killSwitchActive: boolean+ killSwitchValue: boolean+ killedAt: string | null+ targetingUpdatedAt: string | nullprojectId: stringcreated: string+ updated: string}export interface ClickhouseFeatureFlag {@@ -24,6 +39,12 @@ export interface ClickhouseFeatureFlag {targetingRules: string | null // JSON string in ClickHouseenabled: number // Int8 in ClickHouseexperimentId: string | null+ scheduledChange: string | null+ killSwitchActive: number+ killSwitchValue: number+ killedAt: string | null+ targetingUpdatedAt: string | nullprojectId: stringcreated: string+ updated: string}diff --git a/backend/apps/community/src/feature-flag/evaluation.ts b/backend/apps/community/src/feature-flag/evaluation.tsindex 692b79280..1b0e9c9f3 100644--- a/backend/apps/community/src/feature-flag/evaluation.ts+++ b/backend/apps/community/src/feature-flag/evaluation.ts@@ -17,6 +17,27 @@ export interface TargetingRule {isExclusive: boolean // true = exclude, false = include}+export interface FeatureFlagSchedule {+ enabled?: boolean+ rolloutPercentage?: number+ applyAt: string | Date+}++export enum FeatureFlagStatus {+ ENABLED = 'enabled',+ DISABLED = 'disabled',+ SCHEDULED = 'scheduled',+ KILLED = 'killed',+ STALE = 'stale',+}++export enum FeatureFlagStaleReason {+ NOT_EVALUATED_RECENTLY = 'not_evaluated_recently',+ PERMANENT_ROLLOUT = 'permanent_rollout',+ TARGETING_UNCHANGED = 'targeting_unchanged',+ COMPLETED_EXPERIMENT = 'completed_experiment',+}+/*** Minimal feature flag interface required for evaluation* Both cloud (TypeORM entity) and community (ClickHouse) flags should satisfy this@@ -27,6 +48,9 @@ export interface EvaluatableFeatureFlag {flagType: FeatureFlagTyperolloutPercentage: numbertargetingRules: TargetingRule[] | null+ scheduledChange?: FeatureFlagSchedule | null+ killSwitchActive?: boolean+ killSwitchValue?: boolean}interface ExperimentVariant {@@ -59,15 +83,19 @@ export function evaluateFlag(profileId: string,attributes?: Record<string, string>,): boolean {- // If flag is disabled, always return false- if (!flag.enabled) {+ if (flag.killSwitchActive) {+ return Boolean(flag.killSwitchValue)+ }++ const effectiveFlag = applyDueScheduledChange(flag)++ if (!effectiveFlag.enabled) {return false}- // Check targeting rules if any exist- if (flag.targetingRules && flag.targetingRules.length > 0) {+ if (effectiveFlag.targetingRules && effectiveFlag.targetingRules.length > 0) {const matchesTargeting = matchesTargetingRules(- flag.targetingRules,+ effectiveFlag.targetingRules,attributes,)if (!matchesTargeting) {@@ -75,19 +103,57 @@ export function evaluateFlag(}}- // For boolean flags, return true if enabled and targeting matches- if (flag.flagType === FeatureFlagType.BOOLEAN) {+ if (effectiveFlag.flagType === FeatureFlagType.BOOLEAN) {return true}- // For rollout flags, use percentage-based rollout- if (flag.flagType === FeatureFlagType.ROLLOUT) {- return isInRolloutPercentage(flag.key, flag.rolloutPercentage, profileId)+ if (effectiveFlag.flagType === FeatureFlagType.ROLLOUT) {+ return isInRolloutPercentage(+ effectiveFlag.key,+ effectiveFlag.rolloutPercentage,+ profileId,+ )}return false}+export function applyDueScheduledChange<T extends EvaluatableFeatureFlag>(+ flag: T,+ now = new Date(),+): T {+ if (!isScheduledChangeDue(flag.scheduledChange, now)) {+ return flag+ }++ const scheduledChange = flag.scheduledChange++ return {+ ...flag,+ enabled: scheduledChange.enabled ?? flag.enabled,+ rolloutPercentage:+ scheduledChange.rolloutPercentage ?? flag.rolloutPercentage,+ scheduledChange: null,+ }+}++export function isScheduledChangeDue(+ scheduledChange?: FeatureFlagSchedule | null,+ now = new Date(),+): scheduledChange is FeatureFlagSchedule {+ if (!scheduledChange?.applyAt) {+ return false+ }++ const applyAt = new Date(scheduledChange.applyAt)++ if (Number.isNaN(applyAt.getTime())) {+ return false+ }++ return applyAt.getTime() <= now.getTime()+}+/*** Checks if visitor attributes match the targeting rules* Rules are evaluated as AND (all rules must match)@@ -108,15 +174,11 @@ function matchesTargetingRules(const matches = matchesRule(attributeValue, rule.filter)- // If isExclusive (exclude), we want the rule to NOT match- // If not isExclusive (include), we want the rule to matchif (rule.isExclusive) {- // Exclude: if it matches, targeting failsif (matches) {return false}} else {- // Include: if it doesn't match, targeting failsif (!matches) {return false}@@ -131,7 +193,6 @@ function matchesTargetingRules(* Supports case-insensitive matching*/function matchesRule(attributeValue: string, filterValue: string): boolean {- // Case-insensitive exact matchreturn attributeValue.toLowerCase() === filterValue.toLowerCase()}@@ -151,17 +212,13 @@ function isInRolloutPercentage(return false}- // Create a consistent hash based on flag key and profile ID- // Using SHA-256 for better cryptographic propertiesconst hash = crypto.createHash('sha256').update(`${flagKey}:${profileId}`).digest('hex')- // Convert first 8 hex characters to a number (0 to 2^32-1)const hashValue = parseInt(hash.substring(0, 8), 16)- // Normalize to 0-100 rangeconst normalizedValue = (hashValue / 0xffffffff) * 100return normalizedValue < percentagediff --git a/backend/apps/community/src/feature-flag/feature-flag.controller.ts b/backend/apps/community/src/feature-flag/feature-flag.controller.tsindex 36596ae30..5088883ec 100644--- a/backend/apps/community/src/feature-flag/feature-flag.controller.ts+++ b/backend/apps/community/src/feature-flag/feature-flag.controller.ts@@ -41,16 +41,30 @@ import {FeatureFlagStatsDto,EvaluatedFlagsResponseDto,FeatureFlagProfilesResponseDto,+ KillFeatureFlagDto,} from './dto/feature-flag.dto'import { FeatureFlagService } from './feature-flag.service'import { clickhouse } from '../common/integrations/clickhouse'import { checkRateLimit, getIPFromHeaders, getIPDetails } from '../common/utils'import { ExperimentService } from '../experiment/experiment.service'-import { ExposureTrigger } from '../experiment/entity/experiment.entity'-import { getExperimentVariant } from './evaluation'+import {+ ExperimentStatus,+ ExposureTrigger,+} from '../experiment/entity/experiment.entity'+import {+ FeatureFlagSchedule,+ FeatureFlagStaleReason,+ FeatureFlagStatus,+ applyDueScheduledChange,+ getExperimentVariant,+ isScheduledChangeDue,+} from './evaluation'const FEATURE_FLAGS_MAXIMUM = 50 // Maximum feature flags per projectconst FEATURE_FLAGS_PAGINATION_MAX_TAKE = 100+const FEATURE_FLAG_EVALUATION_STALE_DAYS = 30+const FEATURE_FLAG_TARGETING_STALE_DAYS = 90+const DAY_IN_MS = 24 * 60 * 60 * 1000@ApiTags('Feature Flag')@Controller(['feature-flag', 'v1/feature-flag'])@@ -63,6 +77,164 @@ export class FeatureFlagController {private readonly experimentService: ExperimentService,) {}+ private validateScheduledChange(+ scheduledChange?: FeatureFlagSchedule | null,+ ) {+ if (!scheduledChange) {+ return+ }++ if (+ scheduledChange.enabled === undefined &&+ scheduledChange.rolloutPercentage === undefined+ ) {+ throw new BadRequestException(+ 'Scheduled change must include enabled or rolloutPercentage',+ )+ }++ const applyAt = new Date(scheduledChange.applyAt)++ if (Number.isNaN(applyAt.getTime())) {+ throw new BadRequestException('Scheduled change date is invalid')+ }++ if (applyAt.getTime() <= Date.now()) {+ throw new BadRequestException('Scheduled change must be in the future')+ }+ }++ private hasTargetingRulesChanged(+ current: FeatureFlag['targetingRules'],+ next?: FeatureFlag['targetingRules'],+ ) {+ if (next === undefined) {+ return false+ }++ return JSON.stringify(current || []) !== JSON.stringify(next || [])+ }++ private getAgeInDays(value?: Date | string | null) {+ if (!value) {+ return Number.POSITIVE_INFINITY+ }++ const date = new Date(value)++ if (Number.isNaN(date.getTime())) {+ return Number.POSITIVE_INFINITY+ }++ return (Date.now() - date.getTime()) / DAY_IN_MS+ }++ private getStaleReasons(+ flag: FeatureFlag,+ lastEvaluatedAt: string | null,+ completedExperimentIds: Set<string>,+ ) {+ const reasons: FeatureFlagStaleReason[] = []+ const createdAge = this.getAgeInDays(flag.created)+ const updatedAge = this.getAgeInDays(flag.updated || flag.created)+ const targetingAge = this.getAgeInDays(+ flag.targetingUpdatedAt || flag.created,+ )++ if (!lastEvaluatedAt && createdAge >= FEATURE_FLAG_EVALUATION_STALE_DAYS) {+ reasons.push(FeatureFlagStaleReason.NOT_EVALUATED_RECENTLY)+ } else if (+ lastEvaluatedAt &&+ this.getAgeInDays(lastEvaluatedAt) >= FEATURE_FLAG_EVALUATION_STALE_DAYS+ ) {+ reasons.push(FeatureFlagStaleReason.NOT_EVALUATED_RECENTLY)+ }++ if (+ flag.flagType === 'rollout' &&+ (flag.rolloutPercentage === 0 || flag.rolloutPercentage === 100) &&+ updatedAge >= FEATURE_FLAG_EVALUATION_STALE_DAYS+ ) {+ reasons.push(FeatureFlagStaleReason.PERMANENT_ROLLOUT)+ }++ if (+ flag.targetingRules?.length > 0 &&+ targetingAge >= FEATURE_FLAG_TARGETING_STALE_DAYS+ ) {+ reasons.push(FeatureFlagStaleReason.TARGETING_UNCHANGED)+ }++ if (flag.experimentId && completedExperimentIds.has(flag.experimentId)) {+ reasons.push(FeatureFlagStaleReason.COMPLETED_EXPERIMENT)+ }++ return reasons+ }++ private getFlagStatus(+ flag: FeatureFlag,+ staleReasons: FeatureFlagStaleReason[],+ ) {+ if (flag.killSwitchActive) {+ return FeatureFlagStatus.KILLED+ }++ if (!isScheduledChangeDue(flag.scheduledChange) && flag.scheduledChange) {+ return FeatureFlagStatus.SCHEDULED+ }++ if (staleReasons.length > 0) {+ return FeatureFlagStatus.STALE+ }++ return flag.enabled ? FeatureFlagStatus.ENABLED : FeatureFlagStatus.DISABLED+ }++ private async decorateFeatureFlags(projectId: string, flags: FeatureFlag[]) {+ const lastEvaluatedAtByFlag =+ await this.featureFlagService.getLastEvaluatedAtByFlagIds(+ projectId,+ flags.map((flag) => flag.id),+ )+ const experimentIds = flags+ .map((flag) => flag.experimentId)+ .filter((id): id is string => Boolean(id))+ const completedExperimentIds = new Set<string>()++ if (experimentIds.length > 0) {+ const experiments = await this.experimentService.findByProject(projectId)++ for (const experiment of experiments) {+ if (+ experiment.status === ExperimentStatus.COMPLETED &&+ experimentIds.includes(experiment.id)+ ) {+ completedExperimentIds.add(experiment.id)+ }+ }+ }++ return _map(flags, (flag) => {+ const effectiveFlag = applyDueScheduledChange(flag)+ const lastEvaluatedAt =+ lastEvaluatedAtByFlag.get(effectiveFlag.id) || null+ const staleReasons = this.getStaleReasons(+ effectiveFlag,+ lastEvaluatedAt,+ completedExperimentIds,+ )++ return {+ ...effectiveFlag,+ pid: projectId,+ lastEvaluatedAt,+ staleReasons,+ status: this.getFlagStatus(effectiveFlag, staleReasons),+ }+ })+ }+@ApiBearerAuth()@Get('/project/:projectId')@Auth(false, true)@@ -95,16 +267,18 @@ export class FeatureFlagController {const safeSkip =typeof skip === 'number' && Number.isFinite(skip) ? Math.max(skip, 0) : 0+ await this.featureFlagService.applyDueScheduledChanges(projectId)+const result = await this.featureFlagService.paginate({ take: safeTake, skip: safeSkip },projectId,search,)- result.results = _map(result.results, (flag) => ({- ...flag,- pid: flag.projectId,- })) as any+ result.results = (await this.decorateFeatureFlags(+ projectId,+ result.results,+ )) as anyreturn result}@@ -130,10 +304,14 @@ export class FeatureFlagController {this.projectService.allowedToView(project, userId)- return {- ...flag,- pid: flag.projectId,- }+ await this.featureFlagService.applyDueScheduledChanges(flag.projectId)++ const freshFlag = (await this.featureFlagService.findOne(flagId)) || flag+ const [decoratedFlag] = await this.decorateFeatureFlags(flag.projectId, [+ freshFlag,+ ])++ return decoratedFlag}@ApiBearerAuth()@@ -179,6 +357,8 @@ export class FeatureFlagController {)}+ this.validateScheduledChange(flagDto.scheduledChange)+try {const newFlag = await this.featureFlagService.create({key: flagDto.key,@@ -187,13 +367,19 @@ export class FeatureFlagController {rolloutPercentage: flagDto.rolloutPercentage ?? 100,targetingRules: flagDto.targetingRules || null,enabled: flagDto.enabled ?? true,+ scheduledChange: flagDto.scheduledChange || null,+ killSwitchActive: false,+ killSwitchValue: false,+ killedAt: null,+ targetingUpdatedAt: new Date().toISOString(),projectId: flagDto.pid,})- return {- ...newFlag,- pid: flagDto.pid,- }+ const [decoratedFlag] = await this.decorateFeatureFlags(flagDto.pid, [+ newFlag,+ ])++ return decoratedFlag} catch (reason) {this.logger.error({ reason }, 'Error while creating feature flag')throw new BadRequestException(@@ -268,9 +454,9 @@ export class FeatureFlagController {const { country, city, region } = getIPDetails(ip)this.analyticsService.checkCountryBlacklist(project, country)- const flags = await this.featureFlagService.findEnabledByProject(- evaluateDto.pid,- )+ await this.featureFlagService.applyDueScheduledChanges(evaluateDto.pid)++ const flags = await this.featureFlagService.findByProject(evaluateDto.pid)const { deviceType, browserName, osName } =await this.analyticsService.getRequestInformation(headers)@@ -482,6 +668,8 @@ export class FeatureFlagController {}}+ this.validateScheduledChange(flagDto.scheduledChange)+const updatePayload: Partial<FeatureFlag> = {..._pick(flagDto, ['key',@@ -490,19 +678,115 @@ export class FeatureFlagController {'rolloutPercentage','targetingRules','enabled',+ 'scheduledChange',]),}+ if (+ this.hasTargetingRulesChanged(flag.targetingRules, flagDto.targetingRules)+ ) {+ updatePayload.targetingUpdatedAt = new Date().toISOString()+ }+const updatedFlag = await this.featureFlagService.update(id, updatePayload)if (!updatedFlag) {throw new NotFoundException('Feature flag not found after update')}- return {- ...updatedFlag,- pid: flag.projectId,+ const [decoratedFlag] = await this.decorateFeatureFlags(flag.projectId, [+ updatedFlag,+ ])++ return decoratedFlag+ }++ @ApiBearerAuth()+ @Put('/:id/kill')+ @Auth()+ @ApiResponse({ status: 200, type: FeatureFlagDto })+ @ApiOperation({ summary: 'Activate the feature flag kill switch' })+ async killFeatureFlag(+ @Param('id') id: string,+ @Body() killDto: KillFeatureFlagDto,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ id, uid }, 'PUT /feature-flag/:id/kill')++ const flag = await this.featureFlagService.findOne(id)++ if (_isEmpty(flag)) {+ throw new NotFoundException()+ }++ const project = await this.projectService.getFullProject(flag.projectId)++ this.projectService.allowedToManage(+ project,+ uid,+ 'You are not allowed to manage this feature flag',+ )++ await this.featureFlagService.applyDueScheduledChanges(flag.projectId)++ const updatedFlag = await this.featureFlagService.update(id, {+ killSwitchActive: true,+ killSwitchValue: killDto.killSwitchValue ?? false,+ killedAt: new Date().toISOString(),+ })++ if (!updatedFlag) {+ throw new NotFoundException('Feature flag not found after update')+ }++ const [decoratedFlag] = await this.decorateFeatureFlags(flag.projectId, [+ updatedFlag,+ ])++ return decoratedFlag+ }++ @ApiBearerAuth()+ @Put('/:id/release-kill-switch')+ @Auth()+ @ApiResponse({ status: 200, type: FeatureFlagDto })+ @ApiOperation({ summary: 'Release the feature flag kill switch' })+ async releaseFeatureFlagKillSwitch(+ @Param('id') id: string,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ id, uid }, 'PUT /feature-flag/:id/release-kill-switch')++ const flag = await this.featureFlagService.findOne(id)++ if (_isEmpty(flag)) {+ throw new NotFoundException()+ }++ const project = await this.projectService.getFullProject(flag.projectId)++ this.projectService.allowedToManage(+ project,+ uid,+ 'You are not allowed to manage this feature flag',+ )++ await this.featureFlagService.applyDueScheduledChanges(flag.projectId)++ const updatedFlag = await this.featureFlagService.update(id, {+ killSwitchActive: false,+ killedAt: null,+ })++ if (!updatedFlag) {+ throw new NotFoundException('Feature flag not found after update')}++ const [decoratedFlag] = await this.decorateFeatureFlags(flag.projectId, [+ updatedFlag,+ ])++ return decoratedFlag}@ApiBearerAuth()diff --git a/backend/apps/community/src/feature-flag/feature-flag.service.ts b/backend/apps/community/src/feature-flag/feature-flag.service.tsindex 2d376575b..5caf1b10b 100644--- a/backend/apps/community/src/feature-flag/feature-flag.service.ts+++ b/backend/apps/community/src/feature-flag/feature-flag.service.ts@@ -21,6 +21,7 @@ import { PaginationOptionsInterface } from '../common/pagination/pagination.resuimport {evaluateFlag as sharedEvaluateFlag,evaluateFlags as sharedEvaluateFlags,+ isScheduledChangeDue,} from './evaluation'dayjs.extend(utc)@@ -33,6 +34,21 @@ const ALLOWED_FLAG_KEYS = ['targetingRules','enabled','experimentId',+ 'scheduledChange',+ 'killSwitchActive',+ 'killSwitchValue',+ 'killedAt',+ 'targetingUpdatedAt',+ 'updated',+]++const NULLABLE_FLAG_KEYS = [+ 'description',+ 'targetingRules',+ 'experimentId',+ 'scheduledChange',+ 'killedAt',+ 'targetingUpdatedAt',]@Injectable()@@ -51,6 +67,15 @@ export class FeatureFlagService {}}+ let scheduledChange = null+ if (flag.scheduledChange) {+ try {+ scheduledChange = JSON.parse(flag.scheduledChange)+ } catch {+ scheduledChange = null+ }+ }+return {id: flag.id,key: flag.key,@@ -60,8 +85,14 @@ export class FeatureFlagService {targetingRules,enabled: Boolean(flag.enabled),experimentId: flag.experimentId || null,+ scheduledChange,+ killSwitchActive: Boolean(flag.killSwitchActive),+ killSwitchValue: Boolean(flag.killSwitchValue),+ killedAt: flag.killedAt || null,+ targetingUpdatedAt: flag.targetingUpdatedAt || null,projectId: flag.projectId,created: flag.created,+ updated: flag.updated || flag.created,}}@@ -76,10 +107,24 @@ export class FeatureFlagService {: null}+ if (flag.scheduledChange !== undefined) {+ result.scheduledChange = flag.scheduledChange+ ? JSON.stringify(flag.scheduledChange)+ : null+ }+if (flag.enabled !== undefined) {result.enabled = flag.enabled ? 1 : 0}+ if (flag.killSwitchActive !== undefined) {+ result.killSwitchActive = flag.killSwitchActive ? 1 : 0+ }++ if (flag.killSwitchValue !== undefined) {+ result.killSwitchValue = flag.killSwitchValue ? 1 : 0+ }+return result}@@ -262,10 +307,16 @@ export class FeatureFlagService {const description = flagData.description || nullconst targetingRules = flagData.targetingRules || nullconst experimentId = flagData.experimentId || null+ const scheduledChange = flagData.scheduledChange || null+ const killSwitchActive = flagData.killSwitchActive ?? false+ const killSwitchValue = flagData.killSwitchValue ?? falseconst formattedFlag = this.formatFlagToClickhouse({...flagData,enabled,+ scheduledChange,+ killSwitchActive,+ killSwitchValue,})await clickhouse.insert({@@ -281,8 +332,14 @@ export class FeatureFlagService {targetingRules: formattedFlag.targetingRules || null,enabled: formattedFlag.enabled ?? 1,experimentId: formattedFlag.experimentId || null,+ scheduledChange: formattedFlag.scheduledChange || null,+ killSwitchActive: formattedFlag.killSwitchActive ?? 0,+ killSwitchValue: formattedFlag.killSwitchValue ?? 0,+ killedAt: formattedFlag.killedAt || null,+ targetingUpdatedAt: formattedFlag.targetingUpdatedAt || created,projectId: flagData.projectId,created,+ updated: created,},],})@@ -299,8 +356,14 @@ export class FeatureFlagService {targetingRules,enabled,experimentId,+ scheduledChange,+ killSwitchActive,+ killSwitchValue,+ killedAt: flagData.killedAt || null,+ targetingUpdatedAt: flagData.targetingUpdatedAt || created,projectId: flagData.projectId,created,+ updated: created,}}@@ -336,6 +399,9 @@ export class FeatureFlagService {return existingFlag}+ filtered.updated = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')+ columns.push('updated')+const formattedData = this.formatFlagToClickhouse(filtered as Partial<FeatureFlag>,)@@ -350,18 +416,24 @@ export class FeatureFlagService {return `${col}={${col}:Int8}`}+ if (col === 'killSwitchActive' || col === 'killSwitchValue') {+ return `${col}={${col}:Int8}`+ }+if (col === 'rolloutPercentage') {return `${col}={${col}:UInt8}`}- // Handle nullable string columns+ if (value === null && NULLABLE_FLAG_KEYS.includes(col)) {+ return `${col}=NULL`+ }+if (- value === null &&- (col === 'description' ||- col === 'targetingRules' ||- col === 'experimentId')+ col === 'killedAt' ||+ col === 'targetingUpdatedAt' ||+ col === 'updated') {- return `${col}=NULL`+ return `${col}={${col}:DateTime}`}return `${col}={${col}:String}`@@ -400,6 +472,63 @@ export class FeatureFlagService {})}+ async applyDueScheduledChanges(projectId: string): Promise<void> {+ const flags = await this.findByProject(projectId)+ const dueFlags = flags.filter((flag) =>+ isScheduledChangeDue(flag.scheduledChange),+ )++ await Promise.all(+ dueFlags.map((flag) =>+ this.update(flag.id, {+ enabled: flag.scheduledChange?.enabled ?? flag.enabled,+ rolloutPercentage:+ flag.scheduledChange?.rolloutPercentage ?? flag.rolloutPercentage,+ scheduledChange: null,+ }),+ ),+ )+ }++ async getLastEvaluatedAtByFlagIds(+ projectId: string,+ flagIds: string[],+ ): Promise<Map<string, string>> {+ const result = new Map<string, string>()++ if (flagIds.length === 0) {+ return result+ }++ try {+ const { data } = await clickhouse+ .query({+ query: `+ SELECT+ flagId,+ max(created) as lastEvaluatedAt+ FROM feature_flag_evaluations+ WHERE+ pid = {pid:FixedString(12)}+ AND flagId IN {flagIds:Array(String)}+ GROUP BY flagId+ `,+ query_params: { pid: projectId, flagIds },+ })+ .then((resultSet) =>+ resultSet.json<{ flagId: string; lastEvaluatedAt: string }>(),+ )++ for (const row of data) {+ result.set(row.flagId, row.lastEvaluatedAt)+ }+ } catch {+ return result+ }++ return result+ }+/*** Evaluates all feature flags for a project given visitor attributes*/diff --git a/backend/migrations/clickhouse/initialise_selfhosted.js b/backend/migrations/clickhouse/initialise_selfhosted.jsindex 999162eba..be488a023 100644--- a/backend/migrations/clickhouse/initialise_selfhosted.js+++ b/backend/migrations/clickhouse/initialise_selfhosted.js@@ -89,8 +89,14 @@ const CLICKHOUSE_INIT_QUERIES = [targetingRules Nullable(String),enabled Int8 DEFAULT 1,experimentId Nullable(String),+ scheduledChange Nullable(String),+ killSwitchActive Int8 DEFAULT 0,+ killSwitchValue Int8 DEFAULT 0,+ killedAt Nullable(DateTime('UTC')),+ targetingUpdatedAt Nullable(DateTime('UTC')),projectId FixedString(12),- created DateTime('UTC')+ created DateTime('UTC'),+ updated DateTime('UTC') DEFAULT created)ENGINE = ReplacingMergeTree(created)ORDER BY (projectId, id)diff --git a/backend/migrations/clickhouse/selfhosted_2025_12_10_feature_flags.js b/backend/migrations/clickhouse/selfhosted_2025_12_10_feature_flags.jsindex 78600636a..884233950 100644--- a/backend/migrations/clickhouse/selfhosted_2025_12_10_feature_flags.js+++ b/backend/migrations/clickhouse/selfhosted_2025_12_10_feature_flags.js@@ -12,8 +12,14 @@ const queries = [rolloutPercentage UInt8 DEFAULT 100,targetingRules Nullable(String),enabled Int8 DEFAULT 1,+ scheduledChange Nullable(String),+ killSwitchActive Int8 DEFAULT 0,+ killSwitchValue Int8 DEFAULT 0,+ killedAt Nullable(DateTime('UTC')),+ targetingUpdatedAt Nullable(DateTime('UTC')),projectId FixedString(12),- created DateTime('UTC')+ created DateTime('UTC'),+ updated DateTime('UTC') DEFAULT created)ENGINE = ReplacingMergeTree(created)ORDER BY (projectId, id)diff --git a/backend/migrations/clickhouse/selfhosted_2026_05_24_feature_flag_operations.js b/backend/migrations/clickhouse/selfhosted_2026_05_24_feature_flag_operations.jsnew file mode 100644index 000000000..1d5ca1902--- /dev/null+++ b/backend/migrations/clickhouse/selfhosted_2026_05_24_feature_flag_operations.js@@ -0,0 +1,13 @@+const { queriesRunner, dbName } = require('./setup')++const queries = [+ `ALTER TABLE ${dbName}.feature_flag ADD COLUMN IF NOT EXISTS scheduledChange Nullable(String) AFTER experimentId;`,+ `ALTER TABLE ${dbName}.feature_flag ADD COLUMN IF NOT EXISTS killSwitchActive Int8 DEFAULT 0 AFTER scheduledChange;`,+ `ALTER TABLE ${dbName}.feature_flag ADD COLUMN IF NOT EXISTS killSwitchValue Int8 DEFAULT 0 AFTER killSwitchActive;`,+ `ALTER TABLE ${dbName}.feature_flag ADD COLUMN IF NOT EXISTS killedAt Nullable(DateTime('UTC')) AFTER killSwitchValue;`,+ `ALTER TABLE ${dbName}.feature_flag ADD COLUMN IF NOT EXISTS targetingUpdatedAt Nullable(DateTime('UTC')) AFTER killedAt;`,+ `ALTER TABLE ${dbName}.feature_flag ADD COLUMN IF NOT EXISTS updated DateTime('UTC') DEFAULT created AFTER created;`,+ `ALTER TABLE ${dbName}.feature_flag UPDATE targetingUpdatedAt = created WHERE targetingUpdatedAt IS NULL;`,+]++queriesRunner(queries)diff --git a/backend/migrations/mysql/2026_05_24_feature_flag_operations.sql b/backend/migrations/mysql/2026_05_24_feature_flag_operations.sqlnew file mode 100644index 000000000..20fad419b--- /dev/null+++ b/backend/migrations/mysql/2026_05_24_feature_flag_operations.sql@@ -0,0 +1,8 @@+ALTER TABLE `feature_flag` ADD COLUMN `scheduledChange` json DEFAULT NULL;+ALTER TABLE `feature_flag` ADD COLUMN `killSwitchActive` tinyint(1) NOT NULL DEFAULT 0;+ALTER TABLE `feature_flag` ADD COLUMN `killSwitchValue` tinyint(1) NOT NULL DEFAULT 0;+ALTER TABLE `feature_flag` ADD COLUMN `killedAt` datetime(6) DEFAULT NULL;+ALTER TABLE `feature_flag` ADD COLUMN `targetingUpdatedAt` datetime(6) DEFAULT NULL;+ALTER TABLE `feature_flag` ADD COLUMN `updated` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);++UPDATE `feature_flag` SET `targetingUpdatedAt` = `created` WHERE `targetingUpdatedAt` IS NULL;diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.tsindex b415d6ca3..8d13a12c5 100644--- a/web/app/api/api.server.ts+++ b/web/app/api/api.server.ts@@ -1326,6 +1326,25 @@ export interface TargetingRule {isExclusive: boolean}+export interface FeatureFlagSchedule {+ enabled?: boolean+ rolloutPercentage?: number+ applyAt: string+}++export type FeatureFlagStatus =+ | 'enabled'+ | 'disabled'+ | 'scheduled'+ | 'killed'+ | 'stale'++export type FeatureFlagStaleReason =+ | 'not_evaluated_recently'+ | 'permanent_rollout'+ | 'targeting_unchanged'+ | 'completed_experiment'+export interface ProjectFeatureFlag {id: stringkey: string@@ -1334,9 +1353,18 @@ export interface ProjectFeatureFlag {rolloutPercentage: numbertargetingRules: TargetingRule[] | nullenabled: boolean+ scheduledChange: FeatureFlagSchedule | null+ killSwitchActive: boolean+ killSwitchValue: boolean+ killedAt: string | null+ targetingUpdatedAt: string | nullexperimentId: string | nullpid: stringcreated: string+ updated: string+ lastEvaluatedAt: string | null+ status: FeatureFlagStatus+ staleReasons: FeatureFlagStaleReason[]}export interface FeatureFlagsResponse {diff --git a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsx b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsxindex 214e4e08b..8722e79c4 100644--- a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsx+++ b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsx@@ -10,6 +10,7 @@ import {Transition,} from '@headlessui/react'import cx from 'clsx'+import dayjs from 'dayjs'import _map from 'lodash/map'import {TrashIcon,@@ -19,19 +20,23 @@ import {CaretUpDownIcon,CheckIcon,XIcon,- ClipboardIcon,} from '@phosphor-icons/react'import { useState, useEffect, useCallback, Fragment, useRef } from 'react'import { useTranslation } from 'react-i18next'import { useFetcher } from 'react-router'import { toast } from 'sonner'-import type { ProjectFeatureFlag, TargetingRule } from '~/api/api.server'+import type {+ FeatureFlagSchedule,+ ProjectFeatureFlag,+ TargetingRule,+} from '~/api/api.server'import { useFiltersProxy } from '~/hooks/useAnalyticsProxy'import { useTheme } from '~/providers/ThemeProvider'import type { ProjectViewActionData } from '~/routes/projects.$id'import Button from '~/ui/Button'import Checkbox from '~/ui/Checkbox'+import CodeBlock from '~/ui/CodeBlock'import FilterValueInput, { filterCategoryIcons } from '~/ui/FilterValueInput'import Input from '~/ui/Input'import Loader from '~/ui/Loader'@@ -53,6 +58,13 @@ const TARGETING_COLUMNS = [{ value: 'os', label: 'OS' },]+const toDateTimeLocal = (value?: string | Date | null) => {+ if (!value) return ''++ const date = dayjs(value)+ return date.isValid() ? date.format('YYYY-MM-DDTHH:mm') : ''+}+interface FeatureFlagSettingsModalProps {isOpen: booleanonClose: () => void@@ -80,7 +92,6 @@ const FeatureFlagSettingsModal = ({const [isLoading, setIsLoading] = useState(false)const [showImplementation, setShowImplementation] = useState(false)- const [copiedCode, setCopiedCode] = useState<string | null>(null)// Filter values cache for targeting rulesconst [filterValuesCache, setFilterValuesCache] = useState<@@ -95,6 +106,11 @@ const FeatureFlagSettingsModal = ({const [rolloutPercentage, setRolloutPercentage] = useState(100)const [targetingRules, setTargetingRules] = useState<TargetingRule[]>([])const [enabled, setEnabled] = useState(true)+ const [scheduleChangeEnabled, setScheduleChangeEnabled] = useState(false)+ const [scheduledApplyAt, setScheduledApplyAt] = useState('')+ const [scheduledEnabled, setScheduledEnabled] = useState(true)+ const [scheduledRolloutPercentage, setScheduledRolloutPercentage] =+ useState(100)const isSaving = fetcher.state === 'submitting' || fetcher.state === 'loading'@@ -105,6 +121,10 @@ const FeatureFlagSettingsModal = ({setRolloutPercentage(100)setTargetingRules([])setEnabled(true)+ setScheduleChangeEnabled(false)+ setScheduledApplyAt('')+ setScheduledEnabled(true)+ setScheduledRolloutPercentage(100)setShowImplementation(false)}@@ -174,6 +194,12 @@ const FeatureFlagSettingsModal = ({setRolloutPercentage(flag.rolloutPercentage)setTargetingRules(flag.targetingRules || [])setEnabled(flag.enabled)+ setScheduleChangeEnabled(Boolean(flag.scheduledChange))+ setScheduledApplyAt(toDateTimeLocal(flag.scheduledChange?.applyAt))+ setScheduledEnabled(flag.scheduledChange?.enabled ?? flag.enabled)+ setScheduledRolloutPercentage(+ flag.scheduledChange?.rolloutPercentage ?? flag.rolloutPercentage,+ )} else if (fetcher.data.error) {toast.error(fetcher.data.error)onClose()@@ -208,6 +234,30 @@ const FeatureFlagSettingsModal = ({e.preventDefault()lastHandledData.current = null+ if (scheduleChangeEnabled) {+ if (!scheduledApplyAt) {+ toast.error(t('featureFlags.scheduleDateRequired'))+ return+ }++ const applyAt = new Date(scheduledApplyAt)++ if (Number.isNaN(applyAt.getTime()) || applyAt.getTime() <= Date.now()) {+ toast.error(t('featureFlags.scheduleDateInPast'))+ return+ }+ }++ const scheduledChange: FeatureFlagSchedule | null = scheduleChangeEnabled+ ? {+ applyAt: new Date(scheduledApplyAt).toISOString(),+ enabled: scheduledEnabled,+ ...(flagType === 'rollout'+ ? { rolloutPercentage: scheduledRolloutPercentage }+ : {}),+ }+ : null+if (isNew) {fetcher.submit({@@ -222,6 +272,7 @@ const FeatureFlagSettingsModal = ({targetingRules.length > 0 ? targetingRules : [],),enabled: String(enabled),+ scheduledChange: JSON.stringify(scheduledChange),},{ method: 'POST' },)@@ -240,6 +291,7 @@ const FeatureFlagSettingsModal = ({targetingRules.length > 0 ? targetingRules : [],),enabled: String(enabled),+ scheduledChange: JSON.stringify(scheduledChange),},{ method: 'POST' },)@@ -295,16 +347,6 @@ const FeatureFlagSettingsModal = ({setKey(value)}- const copyToClipboard = async (code: string, id: string) => {- try {- await navigator.clipboard.writeText(code)- setCopiedCode(id)- setTimeout(() => setCopiedCode(null), 2000)- } catch {- toast.error('Failed to copy to clipboard')- }- }-const jsAllFlagsCode = `// Fetch all feature flagsconst flags = await swetrix.getFeatureFlags({profileId: 'user-123',@@ -503,7 +545,9 @@ const flags = await swetrix.getFeatureFlags(undefined, true)`<spanclassName={cx('flex items-center gap-2',- { 'font-medium': selected },+ {+ 'font-medium': selected,+ },)}><span className='shrink-0 text-gray-500 dark:text-gray-400'>@@ -585,7 +629,9 @@ const flags = await swetrix.getFeatureFlags(undefined, true)`<spanclassName={cx('block truncate',- { 'font-medium': selected },+ {+ 'font-medium': selected,+ },)}>{t('featureFlags.is')}@@ -617,7 +663,9 @@ const flags = await swetrix.getFeatureFlags(undefined, true)`<spanclassName={cx('block truncate',- { 'font-medium': selected },+ {+ 'font-medium': selected,+ },)}>{t('featureFlags.isNot')}@@ -680,6 +728,64 @@ const flags = await swetrix.getFeatureFlags(undefined, true)`hint={t('featureFlags.enableFlagHint')}/>+ <div className='rounded-lg bg-gray-50 p-3 ring-1 ring-gray-200/80 dark:bg-slate-900/50 dark:ring-slate-700/60'>+ <Checkbox+ checked={scheduleChangeEnabled}+ onChange={setScheduleChangeEnabled}+ label={t('featureFlags.scheduleChange')}+ hint={t('featureFlags.scheduleChangeHint')}+ />++ {scheduleChangeEnabled ? (+ <div className='mt-3 grid gap-3 sm:grid-cols-2'>+ <Input+ type='datetime-local'+ label={t('featureFlags.scheduleAt')}+ value={scheduledApplyAt}+ min={dayjs().format('YYYY-MM-DDTHH:mm')}+ onChange={(e) =>+ setScheduledApplyAt(e.target.value)+ }+ required+ />+ <div className='flex items-end pb-2'>+ <Checkbox+ checked={scheduledEnabled}+ onChange={setScheduledEnabled}+ label={t('featureFlags.scheduleTargetEnabled')}+ hint={t('featureFlags.scheduleTargetEnabledHint')}+ />+ </div>++ {flagType === 'rollout' ? (+ <div className='sm:col-span-2'>+ <label className='mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300'>+ {t('featureFlags.scheduleRolloutPercentage')} (+ {scheduledRolloutPercentage}%)+ </label>+ <input+ type='range'+ min='0'+ max='100'+ value={scheduledRolloutPercentage}+ onChange={(e) =>+ setScheduledRolloutPercentage(+ Number(e.target.value),+ )+ }+ className='w-full'+ />+ <div className='mt-1 flex justify-between text-xs text-gray-500'>+ <span>0%</span>+ <span>50%</span>+ <span>100%</span>+ </div>+ </div>+ ) : null}+ </div>+ ) : null}+ </div>+{/* How to implement section */}<div className='border-t border-gray-200 pt-4 dark:border-slate-700'><button@@ -711,84 +817,40 @@ const flags = await swetrix.getFeatureFlags(undefined, true)`{t('featureFlags.implementationDescription')}</Text>- {/* JavaScript SDK */}<div>- <div className='mb-2 flex items-center justify-between'>- <Text as='span' size='sm' weight='medium'>- Fetch all flags- </Text>- <button- type='button'- onClick={() =>- copyToClipboard(jsAllFlagsCode, 'js-all')- }- className='flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700'- >- {copiedCode === 'js-all' ? (- <CheckIcon className='size-4 text-green-500' />- ) : (- <ClipboardIcon className='size-4' />- )}- {copiedCode === 'js-all' ? 'Copied!' : 'Copy'}- </button>- </div>- <pre className='overflow-x-auto rounded-lg bg-gray-900 p-3 text-xs text-gray-100'>- <code>{jsAllFlagsCode}</code>- </pre>+ <Text+ as='p'+ size='sm'+ weight='medium'+ className='mb-2'+ >+ {t('featureFlags.fetchAllFlags')}+ </Text>+ <CodeBlock code={jsAllFlagsCode} /></div>- {/* Single flag */}<div>- <div className='mb-2 flex items-center justify-between'>- <Text as='span' size='sm' weight='medium'>- Single flag- </Text>- <button- type='button'- onClick={() =>- copyToClipboard(jsSingleFlagCode, 'js-single')- }- className='flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700'- >- {copiedCode === 'js-single' ? (- <CheckIcon className='size-4 text-green-500' />- ) : (- <ClipboardIcon className='size-4' />- )}- {copiedCode === 'js-single'- ? 'Copied!'- : 'Copy'}- </button>- </div>- <pre className='overflow-x-auto rounded-lg bg-gray-900 p-3 text-xs text-gray-100'>- <code>{jsSingleFlagCode}</code>- </pre>+ <Text+ as='p'+ size='sm'+ weight='medium'+ className='mb-2'+ >+ {t('featureFlags.singleFlag')}+ </Text>+ <CodeBlock code={jsSingleFlagCode} /></div>- {/* Cache control */}<div>- <div className='mb-2 flex items-center justify-between'>- <Text as='span' size='sm' weight='medium'>- Cache control- </Text>- <button- type='button'- onClick={() =>- copyToClipboard(jsCacheCode, 'js-cache')- }- className='flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700'- >- {copiedCode === 'js-cache' ? (- <CheckIcon className='size-4 text-green-500' />- ) : (- <ClipboardIcon className='size-4' />- )}- {copiedCode === 'js-cache' ? 'Copied!' : 'Copy'}- </button>- </div>- <pre className='overflow-x-auto rounded-lg bg-gray-900 p-3 text-xs text-gray-100'>- <code>{jsCacheCode}</code>- </pre>+ <Text+ as='p'+ size='sm'+ weight='medium'+ className='mb-2'+ >+ {t('featureFlags.cacheControl')}+ </Text>+ <CodeBlock code={jsCacheCode} /></div></div>) : null}diff --git a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsxindex 874876eba..86c9205ec 100644--- a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx+++ b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx@@ -16,6 +16,8 @@ import {CaretDownIcon,CheckIcon,XIcon,+ WarningOctagonIcon,+ ArrowCounterClockwiseIcon,} from '@phosphor-icons/react'import {useState,@@ -41,6 +43,8 @@ import type {ProjectFeatureFlag,FeatureFlagStats,FeatureFlagProfile,+ FeatureFlagStaleReason,+ FeatureFlagStatus,} from '~/api/api.server'import {useFeatureFlagStatsProxy,@@ -66,6 +70,7 @@ import Modal from '~/ui/Modal'import StatusPage from '~/ui/StatusPage'import { Switch } from '~/ui/Switch'import { Text } from '~/ui/Text'+import Tooltip from '~/ui/Tooltip'import { nFormatter } from '~/utils/generic'import { getProfileDisplayName, ProfileAvatar } from '~/utils/profileAvatars'import routes from '~/utils/routes'@@ -78,6 +83,24 @@ dayjs.extend(relativeTime)const DEFAULT_FEATURE_FLAGS_TAKE = 20const DEFAULT_FEATURE_FLAG_PROFILES_TAKE = 15+const STATUS_BADGE: Record<+ FeatureFlagStatus,+ { colour: 'red' | 'yellow' | 'green' | 'slate' | 'sky'; labelKey: string }+> = {+ enabled: { colour: 'green', labelKey: 'featureFlags.enabled' },+ disabled: { colour: 'slate', labelKey: 'featureFlags.disabled' },+ scheduled: { colour: 'sky', labelKey: 'featureFlags.scheduled' },+ killed: { colour: 'red', labelKey: 'featureFlags.killed' },+ stale: { colour: 'yellow', labelKey: 'featureFlags.stale' },+}++const STALE_REASON_LABEL_KEYS: Record<FeatureFlagStaleReason, string> = {+ not_evaluated_recently: 'featureFlags.staleReasonNotEvaluated',+ permanent_rollout: 'featureFlags.staleReasonPermanentRollout',+ targeting_unchanged: 'featureFlags.staleReasonTargetingUnchanged',+ completed_experiment: 'featureFlags.staleReasonCompletedExperiment',+}+interface FeatureFlagProfileRowProps {profile: FeatureFlagProfiletimeFormat: '12-hour' | '24-hour'@@ -179,6 +202,8 @@ interface FeatureFlagRowProps {onDelete: (id: string) => voidonEdit: (id: string) => voidonToggle: (id: string, enabled: boolean) => void+ onKill: (id: string) => void+ onReleaseKillSwitch: (id: string) => voidonToggleExpand: (id: string) => voidonLoadMoreProfiles: (id: string) => voidonResultFilterChange: (id: string, filter: boolean) => void@@ -197,14 +222,21 @@ const FeatureFlagRow = ({onDelete,onEdit,onToggle,+ onKill,+ onReleaseKillSwitch,onToggleExpand,onLoadMoreProfiles,onResultFilterChange,timeFormat,}: FeatureFlagRowProps) => {- const { t } = useTranslation()+ const {+ t,+ i18n: { language },+ } = useTranslation()const location = useLocation()const [showDeleteModal, setShowDeleteModal] = useState(false)+ const [showKillModal, setShowKillModal] = useState(false)+ const [showReleaseModal, setShowReleaseModal] = useState(false)const targetingRulesCount = flag.targetingRules?.length || 0const experimentSearch = useMemo(() => {@@ -214,6 +246,56 @@ const FeatureFlagRow = ({params.set('experimentId', flag.experimentId)return params.toString()}, [flag.experimentId, location.search])+ const statusMeta = STATUS_BADGE[flag.status] || STATUS_BADGE.disabled+ const scheduledAtText = useMemo(() => {+ if (!flag.scheduledChange?.applyAt) return null++ return dayjs(flag.scheduledChange.applyAt)+ .toDate()+ .toLocaleDateString(language, {+ day: 'numeric',+ month: 'short',+ hour: 'numeric',+ minute: 'numeric',+ hourCycle: timeFormat === '12-hour' ? 'h12' : 'h23',+ })+ }, [flag.scheduledChange?.applyAt, language, timeFormat])+ const scheduledDetails = useMemo(() => {+ const details: string[] = []++ if (!flag.scheduledChange) return ''++ if (flag.scheduledChange.enabled !== undefined) {+ details.push(+ flag.scheduledChange.enabled+ ? t('featureFlags.scheduledEnable')+ : t('featureFlags.scheduledDisable'),+ )+ }++ if (flag.scheduledChange.rolloutPercentage !== undefined) {+ details.push(+ t('featureFlags.scheduledRollout', {+ percentage: flag.scheduledChange.rolloutPercentage,+ }),+ )+ }++ return details.join(', ')+ }, [flag.scheduledChange, t])+ const staleReasons = useMemo(+ () =>+ (flag.staleReasons || [])+ .map((reason) => t(STALE_REASON_LABEL_KEYS[reason] || reason))+ .join(', '),+ [flag.staleReasons, t],+ )+ const toggleActionLabel = flag.enabled+ ? t('featureFlags.disable')+ : t('featureFlags.enable')+ const killSwitchActionLabel = flag.killSwitchActive+ ? t('featureFlags.releaseKillSwitch')+ : t('featureFlags.killSwitch')return (<>@@ -245,31 +327,27 @@ const FeatureFlagRow = ({<ToggleRightIcon className='size-4 text-indigo-600 dark:text-indigo-500' /><span>{flag.key}</span></Text>- {/* Status badge */}- <Badge- label={- flag.enabled- ? t('featureFlags.enabled')- : t('featureFlags.disabled')- }- colour={flag.enabled ? 'green' : 'slate'}- className='text-[0.625rem] leading-3'- />- {/* Flag type badge */}- <Badge- label={- flag.flagType === 'rollout' ? (- `${flag.rolloutPercentage}%`- ) : (- <span className='flex items-center gap-1'>- <ToggleRightIcon className='size-3' />- {t('featureFlags.boolean')}- </span>- )- }- colour='sky'- className='text-[0.625rem] leading-3'- />+ {flag.status !== 'enabled' ? (+ <Badge+ label={t(statusMeta.labelKey)}+ colour={statusMeta.colour}+ className='text-[0.625rem] leading-3'+ />+ ) : null}+ {flag.status !== 'stale' && flag.staleReasons?.length > 0 ? (+ <Badge+ label={t('featureFlags.stale')}+ colour='yellow'+ className='text-[0.625rem] leading-3'+ />+ ) : null}+ {flag.flagType === 'rollout' ? (+ <Badge+ label={`${flag.rolloutPercentage}%`}+ colour='sky'+ className='text-[0.625rem] leading-3'+ />+ ) : null}{flag.experimentId ? (<Linkto={{ search: experimentSearch }}@@ -294,6 +372,32 @@ const FeatureFlagRow = ({{t('featureFlags.experimentLinkedHint')}</Text>) : null}+ {flag.killSwitchActive ? (+ <Text className='mt-1' as='p' size='xs' colour='error'>+ {t('featureFlags.killSwitchActiveHint', {+ value: flag.killSwitchValue ? 'true' : 'false',+ })}+ </Text>+ ) : null}+ {flag.scheduledChange && scheduledAtText ? (+ <Text className='mt-1' as='p' size='xs' colour='muted'>+ {t('featureFlags.scheduledFor', {+ date: scheduledAtText,+ })}+ {scheduledDetails+ ? ` · ${t('featureFlags.scheduledChangeSummary', {+ details: scheduledDetails,+ })}`+ : ''}+ </Text>+ ) : null}+ {staleReasons ? (+ <Text className='mt-1' as='p' size='xs' colour='muted'>+ {t('featureFlags.staleReasons', {+ reasons: staleReasons,+ })}+ </Text>+ ) : null}{targetingRulesCount > 0 ? (<Text className='mt-1' as='p' size='xs' colour='muted'>{t('featureFlags.targetingRulesCount', {@@ -372,57 +476,114 @@ const FeatureFlagRow = ({</Text>)}</div>- {/* Action buttons */}<div className='flex items-center gap-1'>- <button- type='button'- onClick={(e) => {- e.preventDefault()- e.stopPropagation()- onToggle(flag.id, !flag.enabled)- }}- aria-label={- flag.enabled- ? t('featureFlags.disable')- : t('featureFlags.enable')+ <Tooltip+ text={toggleActionLabel}+ ariaLabel={toggleActionLabel}+ asChild+ disableHoverableContent+ tooltipNode={+ <button+ type='button'+ aria-disabled={flag.killSwitchActive}+ onClick={(e) => {+ e.preventDefault()+ e.stopPropagation()+ if (flag.killSwitchActive) return+ onToggle(flag.id, !flag.enabled)+ }}+ aria-label={toggleActionLabel}+ className={cx(+ 'inline-flex size-8 items-center justify-center rounded-md border border-transparent transition-colors aria-disabled:cursor-not-allowed aria-disabled:opacity-40',+ flag.enabled+ ? 'text-green-600 hover:border-green-300 hover:bg-green-50 dark:text-green-400 hover:dark:border-green-700/80 dark:hover:bg-green-900/30'+ : 'text-gray-400 hover:border-gray-300 hover:bg-gray-50 dark:text-gray-500 hover:dark:border-slate-700/80 dark:hover:bg-slate-900',+ )}+ >+ {flag.enabled ? (+ <ToggleRightIcon className='size-5' aria-hidden />+ ) : (+ <ToggleLeftIcon className='size-5' aria-hidden />+ )}+ </button>}- className={cx(- 'rounded-md border border-transparent p-1.5 transition-colors',- flag.enabled- ? 'text-green-600 hover:border-green-300 hover:bg-green-50 dark:text-green-400 hover:dark:border-green-700/80 dark:hover:bg-green-900/30'- : 'text-gray-400 hover:border-gray-300 hover:bg-gray-50 dark:text-gray-500 hover:dark:border-slate-700/80 dark:hover:bg-slate-900',- )}- >- {flag.enabled ? (- <ToggleRightIcon className='size-5' />- ) : (- <ToggleLeftIcon className='size-5' />- )}- </button>- <button- type='button'- onClick={(e) => {- e.preventDefault()- e.stopPropagation()- onEdit(flag.id)- }}- aria-label={t('common.edit')}- className='rounded-md border border-transparent p-1.5 text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-400 hover:dark:border-slate-700/80 dark:hover:bg-slate-900 dark:hover:text-slate-300'- >- <PencilIcon className='size-4' />- </button>- <button- type='button'- onClick={(e) => {- e.preventDefault()- e.stopPropagation()- setShowDeleteModal(true)- }}- aria-label={t('common.delete')}- className='rounded-md border border-transparent p-1.5 text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-400 hover:dark:border-slate-700/80 dark:hover:bg-slate-900 dark:hover:text-slate-300'- >- <TrashIcon className='size-4' />- </button>+ />+ <Tooltip+ text={killSwitchActionLabel}+ ariaLabel={killSwitchActionLabel}+ asChild+ disableHoverableContent+ tooltipNode={+ <button+ type='button'+ onClick={(e) => {+ e.preventDefault()+ e.stopPropagation()+ if (flag.killSwitchActive) {+ setShowReleaseModal(true)+ } else {+ setShowKillModal(true)+ }+ }}+ aria-label={killSwitchActionLabel}+ className={cx(+ 'inline-flex size-8 items-center justify-center rounded-md border border-transparent transition-colors',+ flag.killSwitchActive+ ? 'text-sky-600 hover:border-sky-300 hover:bg-sky-50 dark:text-sky-300 hover:dark:border-sky-700/80 dark:hover:bg-sky-900/30'+ : 'text-red-600 hover:border-red-300 hover:bg-red-50 dark:text-red-400 hover:dark:border-red-700/80 dark:hover:bg-red-900/30',+ )}+ >+ {flag.killSwitchActive ? (+ <ArrowCounterClockwiseIcon+ className='size-4'+ aria-hidden+ />+ ) : (+ <WarningOctagonIcon className='size-4' aria-hidden />+ )}+ </button>+ }+ />+ <Tooltip+ text={t('common.edit')}+ ariaLabel={t('common.edit')}+ asChild+ disableHoverableContent+ tooltipNode={+ <button+ type='button'+ onClick={(e) => {+ e.preventDefault()+ e.stopPropagation()+ onEdit(flag.id)+ }}+ aria-label={t('common.edit')}+ className='inline-flex size-8 items-center justify-center rounded-md border border-transparent text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-400 hover:dark:border-slate-700/80 dark:hover:bg-slate-900 dark:hover:text-slate-300'+ >+ <PencilIcon className='size-4' aria-hidden />+ </button>+ }+ />+ <Tooltip+ text={t('common.delete')}+ ariaLabel={t('common.delete')}+ asChild+ disableHoverableContent+ tooltipNode={+ <button+ type='button'+ onClick={(e) => {+ e.preventDefault()+ e.stopPropagation()+ setShowDeleteModal(true)+ }}+ aria-label={t('common.delete')}+ className='inline-flex size-8 items-center justify-center rounded-md border border-transparent text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-400 hover:dark:border-slate-700/80 dark:hover:bg-slate-900 dark:hover:text-slate-300'+ >+ <TrashIcon className='size-4' aria-hidden />+ </button>+ }+ /><CaretDownIconclassName={cx('size-5 text-gray-500 transition-transform dark:text-gray-400',@@ -495,6 +656,33 @@ const FeatureFlagRow = ({type='error'isOpened={showDeleteModal}/>+ <Modal+ onClose={() => setShowKillModal(false)}+ onSubmit={() => {+ onKill(flag.id)+ setShowKillModal(false)+ }}+ submitText={t('featureFlags.killSwitchSubmit')}+ closeText={t('common.close')}+ title={t('featureFlags.killSwitchConfirmTitle')}+ message={t('featureFlags.killSwitchConfirmMessage')}+ submitType='danger'+ type='warning'+ isOpened={showKillModal}+ />+ <Modal+ onClose={() => setShowReleaseModal(false)}+ onSubmit={() => {+ onReleaseKillSwitch(flag.id)+ setShowReleaseModal(false)+ }}+ submitText={t('featureFlags.releaseKillSwitchSubmit')}+ closeText={t('common.close')}+ title={t('featureFlags.releaseKillSwitchConfirmTitle')}+ message={t('featureFlags.releaseKillSwitchConfirmMessage')}+ type='info'+ isOpened={showReleaseModal}+ /></>)}@@ -705,6 +893,24 @@ const FeatureFlagsViewInner = ({} else if (actionFetcher.data.error) {toast.error(actionFetcher.data.error)}+ } else if (actionFetcher.data.intent === 'kill-feature-flag') {+ if (actionFetcher.data.success && actionFetcher.data.data) {+ const updated = actionFetcher.data.data as ProjectFeatureFlag+ toast.success(t('featureFlags.killSwitchActivated'))+ setFlags((prev) => prev.map((f) => (f.id === updated.id ? updated : f)))+ } else if (actionFetcher.data.error) {+ toast.error(actionFetcher.data.error)+ }+ } else if (+ actionFetcher.data.intent === 'release-feature-flag-kill-switch'+ ) {+ if (actionFetcher.data.success && actionFetcher.data.data) {+ const updated = actionFetcher.data.data as ProjectFeatureFlag+ toast.success(t('featureFlags.killSwitchReleased'))+ setFlags((prev) => prev.map((f) => (f.id === updated.id ? updated : f)))+ } else if (actionFetcher.data.error) {+ toast.error(actionFetcher.data.error)+ }}}, [actionFetcher.data,@@ -953,6 +1159,32 @@ const FeatureFlagsViewInner = ({[actionFetcher],)+ const handleKillFlag = useCallback(+ (flagId: string) => {+ processedActionRef.current = null+ actionFetcher.submit(+ {+ intent: 'kill-feature-flag',+ flagId,+ killSwitchValue: 'false',+ },+ { method: 'POST' },+ )+ },+ [actionFetcher],+ )++ const handleReleaseKillSwitch = useCallback(+ (flagId: string) => {+ processedActionRef.current = null+ actionFetcher.submit(+ { intent: 'release-feature-flag-kill-switch', flagId },+ { method: 'POST' },+ )+ },+ [actionFetcher],+ )+const canLoadMoreFlags = flags.length < totalconst loadMoreFlags = useCallback(() => {if (isLoading || !canLoadMoreFlags) {@@ -1053,6 +1285,8 @@ const FeatureFlagsViewInner = ({onDelete={handleDeleteFlag}onEdit={handleEditFlag}onToggle={handleToggleFlag}+ onKill={handleKillFlag}+ onReleaseKillSwitch={handleReleaseKillSwitch}onToggleExpand={handleToggleExpand}onLoadMoreProfiles={handleLoadMoreProfiles}onResultFilterChange={handleResultFilterChange}diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsxindex 4fcd07e1e..37e1e54aa 100644--- a/web/app/routes/projects.$id.tsx+++ b/web/app/routes/projects.$id.tsx@@ -1735,6 +1735,10 @@ export async function action({ request, params }: ActionFunctionArgs) {formData.get('targetingRules')?.toString() || '[]',)const enabled = formData.get('enabled') === 'true'+ const scheduledChangeRaw = formData.get('scheduledChange')?.toString()+ const scheduledChange = scheduledChangeRaw+ ? JSON.parse(scheduledChangeRaw)+ : nullconst result = await serverFetch(request, 'feature-flag', {method: 'POST',@@ -1746,6 +1750,7 @@ export async function action({ request, params }: ActionFunctionArgs) {rolloutPercentage,targetingRules,enabled,+ scheduledChange,},})@@ -1776,6 +1781,11 @@ export async function action({ request, params }: ActionFunctionArgs) {const enabled = formData.has('enabled')? formData.get('enabled') === 'true': undefined+ const scheduledChange = formData.has('scheduledChange')+ ? formData.get('scheduledChange')?.toString() === 'null'+ ? null+ : JSON.parse(formData.get('scheduledChange')!.toString())+ : undefinedconst body: Record<string, unknown> = {}if (key !== undefined) body.key = key@@ -1785,6 +1795,7 @@ export async function action({ request, params }: ActionFunctionArgs) {body.rolloutPercentage = rolloutPercentageif (targetingRules !== undefined) body.targetingRules = targetingRulesif (enabled !== undefined) body.enabled = enabled+ if (scheduledChange !== undefined) body.scheduledChange = scheduledChangeconst result = await serverFetch(request, `feature-flag/${flagId}`, {method: 'PUT',@@ -1804,6 +1815,52 @@ export async function action({ request, params }: ActionFunctionArgs) {)}+ case 'kill-feature-flag': {+ const flagId = formData.get('flagId')?.toString()+ const killSwitchValue = formData.get('killSwitchValue') === 'true'++ const result = await serverFetch(request, `feature-flag/${flagId}/kill`, {+ method: 'PUT',+ body: { killSwitchValue },+ })++ if (result.error) {+ return data<ProjectViewActionData>(+ { intent, error: result.error as string },+ { status: 400 },+ )+ }++ return data<ProjectViewActionData>(+ { intent, success: true, data: result.data },+ { headers: createHeadersWithCookies(result.cookies) },+ )+ }++ case 'release-feature-flag-kill-switch': {+ const flagId = formData.get('flagId')?.toString()++ const result = await serverFetch(+ request,+ `feature-flag/${flagId}/release-kill-switch`,+ {+ method: 'PUT',+ },+ )++ if (result.error) {+ return data<ProjectViewActionData>(+ { intent, error: result.error as string },+ { status: 400 },+ )+ }++ return data<ProjectViewActionData>(+ { intent, success: true, data: result.data },+ { headers: createHeadersWithCookies(result.cookies) },+ )+ }+case 'delete-feature-flag': {const flagId = formData.get('flagId')?.toString()diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex c14040982..7da75f31c 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -1401,10 +1401,42 @@"enableFlagHint": "When disabled, the flag will always return false.","enabled": "Enabled","disabled": "Disabled",+ "scheduled": "Scheduled",+ "killed": "Killed",+ "stale": "Stale","enable": "Enable","disable": "Disable","flagEnabled": "Feature flag enabled","flagDisabled": "Feature flag disabled",+ "scheduleChange": "Schedule change",+ "scheduleChangeHint": "Apply a future enabled state or rollout percentage without changing the current serving rules.",+ "scheduleAt": "Apply at",+ "scheduleTargetEnabled": "Enabled after schedule",+ "scheduleTargetEnabledHint": "When off, the flag will return false after the scheduled time.",+ "scheduleRolloutPercentage": "Scheduled rollout percentage",+ "scheduleDateRequired": "Choose when the scheduled change should run",+ "scheduleDateInPast": "Scheduled changes must be in the future",+ "scheduledFor": "Scheduled for {{date}}",+ "scheduledChangeSummary": "change to {{details}}",+ "scheduledEnable": "enable flag",+ "scheduledDisable": "disable flag",+ "scheduledRollout": "{{percentage}}% rollout",+ "killSwitch": "Kill switch",+ "killSwitchActiveHint": "Serving is forced to {{value}} for every visitor until released.",+ "killSwitchConfirmTitle": "Force this flag off for everyone?",+ "killSwitchConfirmMessage": "This overrides targeting rules and rollout percentage immediately. Use it only to stop unsafe behavior.",+ "killSwitchSubmit": "Force off now",+ "killSwitchActivated": "Kill switch activated",+ "releaseKillSwitch": "Release kill switch",+ "releaseKillSwitchConfirmTitle": "Release the kill switch?",+ "releaseKillSwitchConfirmMessage": "The flag will return to its saved rollout and targeting rules.",+ "releaseKillSwitchSubmit": "Release override",+ "killSwitchReleased": "Feature flag override released",+ "staleReasons": "Stale because: {{reasons}}",+ "staleReasonNotEvaluated": "not evaluated recently",+ "staleReasonPermanentRollout": "fixed at 0% or 100% for a long time",+ "staleReasonTargetingUnchanged": "targeting unchanged for a long time",+ "staleReasonCompletedExperiment": "linked experiment is completed","evaluations": "Evaluations","users": "Users","trueRate": "True rate",@@ -1412,6 +1444,9 @@"targetingRulesCount": "{{count}} targeting rule(s)","howToImplement": "How to implement","implementationDescription": "Use the code snippets below to check feature flags in your application.",+ "fetchAllFlags": "Fetch all flags",+ "singleFlag": "Single flag",+ "cacheControl": "Cache control","noProfiles": "No profiles have evaluated this flag yet","loadMore": "Load more","xEvaluations": "{{count}} evaluation(s)",