feat(flags): real feature-flag system with bulk eval + operator UI
Real backend for the flags page (was pure mock). Built so it's ready for
the first risky rollout (likely the Stalwart JMAP client or the Stripe
billing engine).
services/platform-api:
- Flag schema (key, description, state, pct, scope.{plans, tenantSlugs,
partnerSlugs, environments}, embedded history capped at 20)
- FlagsService with CRUD + evaluateAll(tenantSlug) → { key: bool }
Eval algorithm:
off → false; on → true
targeted → require non-empty scope (empty allowlist means "nobody"),
then match every non-empty axis
rollout → match scope, then sha256(`${tenantId}:${key}`) % 100 < pct
Hash-based rollout is deterministic: bumping pct only flips the new
slice. Pure helpers (matchesScope, hasAnyScope, inRolloutBucket) are
exported for future unit tests.
- FlagsController exposes GET /flags, GET /flags/:key, POST /flags/evaluate
(JwtAuthGuard); POST/PATCH/DELETE require OperatorGuard. History entries
capture the actor's email.
- SeedService idempotently creates 10 flag keys mapping to real Dezky
concerns (jmap_native_v2, gdpr_export_v2, new_billing_engine, etc.).
$setOnInsert so operator edits survive restarts.
apps/operator:
- 6 proxies: /api/flags index get/post, [key] get/patch/delete, evaluate post
- types/flag.ts with the shape that mirrors the backend
- pages/flags.vue: useFetch real list, row click opens FlagDetail,
"New flag" opens NewFlagModal, scope summary column shows targeting
at a glance
- FlagDetail.vue: side panel with segmented state, rollout slider with
live "~N of M tenants" preview from /api/tenants, plan/tenant/env chip
pickers, dirty-tracked Save, instant Kill-switch (PATCH state=off+pct=0),
embedded change history
- NewFlagModal.vue: minimal create form (key + description). Everything
else is configured in the detail panel afterward.
- CommandPalette: feature-flag rows now come from /api/flags instead of
the dropped fixture, so newly-created flags are searchable immediately
- data/fixtures.ts: drop FLAGS / FeatureFlag exports (replaced by the
real backend)
Smoke-tested end-to-end: list renders 10 seed flags, opening gdpr_export_v2
and flipping to rollout 25% then saving persists + adds a history entry,
kill-switch sets state=off in one click, /api/flags/evaluate returns the
correct booleans for the seeded tenant, same tenant gets the same answer
on consecutive evals (determinism), and creating + deleting a flag through
the UI roundtrips correctly.
This commit is contained in:
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common'
|
||||
import { ConfigModule } from '@nestjs/config'
|
||||
import { MongooseModule } from '@nestjs/mongoose'
|
||||
import { AuthModule } from './auth/auth.module.js'
|
||||
import { FlagsModule } from './flags/flags.module.js'
|
||||
import { HealthModule } from './health/health.module.js'
|
||||
import { PartnersModule } from './partners/partners.module.js'
|
||||
import { SeedModule } from './seed/seed.module.js'
|
||||
@@ -21,6 +22,7 @@ import { UsersModule } from './users/users.module.js'
|
||||
PartnersModule,
|
||||
UsersModule,
|
||||
SubscriptionsModule,
|
||||
FlagsModule,
|
||||
SeedModule,
|
||||
],
|
||||
})
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import {
|
||||
ArrayUnique,
|
||||
IsArray,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Matches,
|
||||
Max,
|
||||
MaxLength,
|
||||
Min,
|
||||
ValidateNested,
|
||||
} from 'class-validator'
|
||||
import { Type } from 'class-transformer'
|
||||
|
||||
class FlagScopeDto {
|
||||
@IsOptional() @IsArray() @ArrayUnique() @IsString({ each: true })
|
||||
plans?: string[]
|
||||
|
||||
@IsOptional() @IsArray() @ArrayUnique() @IsString({ each: true })
|
||||
tenantSlugs?: string[]
|
||||
|
||||
@IsOptional() @IsArray() @ArrayUnique() @IsString({ each: true })
|
||||
partnerSlugs?: string[]
|
||||
|
||||
@IsOptional() @IsArray() @ArrayUnique()
|
||||
@IsEnum(['prod', 'staging', 'dev'], { each: true })
|
||||
environments?: ('prod' | 'staging' | 'dev')[]
|
||||
}
|
||||
|
||||
export class CreateFlagDto {
|
||||
@IsString()
|
||||
@Matches(/^[a-z][a-z0-9_]{1,62}[a-z0-9]$/, {
|
||||
message: 'key must be lowercase snake_case, 3-64 chars, starts with a letter',
|
||||
})
|
||||
key!: string
|
||||
|
||||
@IsOptional() @IsString() @MaxLength(280)
|
||||
description?: string
|
||||
|
||||
@IsOptional() @IsEnum(['off', 'targeted', 'rollout', 'on'])
|
||||
state?: 'off' | 'targeted' | 'rollout' | 'on'
|
||||
|
||||
@IsOptional() @IsInt() @Min(0) @Max(100)
|
||||
pct?: number
|
||||
|
||||
@IsOptional() @ValidateNested() @Type(() => FlagScopeDto)
|
||||
scope?: FlagScopeDto
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { IsOptional, IsString, MaxLength } from 'class-validator'
|
||||
|
||||
// Evaluation context. We currently only support tenant-level flags, so the
|
||||
// only required input is the tenant slug; we hydrate plan + partnerSlug + env
|
||||
// server-side from the tenant doc + runtime env.
|
||||
export class EvaluateDto {
|
||||
@IsString() @MaxLength(64)
|
||||
tenantSlug!: string
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import {
|
||||
ArrayUnique,
|
||||
IsArray,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Max,
|
||||
MaxLength,
|
||||
Min,
|
||||
ValidateNested,
|
||||
} from 'class-validator'
|
||||
import { Type } from 'class-transformer'
|
||||
|
||||
class FlagScopeDto {
|
||||
@IsOptional() @IsArray() @ArrayUnique() @IsString({ each: true })
|
||||
plans?: string[]
|
||||
|
||||
@IsOptional() @IsArray() @ArrayUnique() @IsString({ each: true })
|
||||
tenantSlugs?: string[]
|
||||
|
||||
@IsOptional() @IsArray() @ArrayUnique() @IsString({ each: true })
|
||||
partnerSlugs?: string[]
|
||||
|
||||
@IsOptional() @IsArray() @ArrayUnique()
|
||||
@IsEnum(['prod', 'staging', 'dev'], { each: true })
|
||||
environments?: ('prod' | 'staging' | 'dev')[]
|
||||
}
|
||||
|
||||
// `key` is immutable after create — rename would silently invalidate every
|
||||
// flag check baked into consumer code.
|
||||
export class UpdateFlagDto {
|
||||
@IsOptional() @IsString() @MaxLength(280)
|
||||
description?: string
|
||||
|
||||
@IsOptional() @IsEnum(['off', 'targeted', 'rollout', 'on'])
|
||||
state?: 'off' | 'targeted' | 'rollout' | 'on'
|
||||
|
||||
@IsOptional() @IsInt() @Min(0) @Max(100)
|
||||
pct?: number
|
||||
|
||||
@IsOptional() @ValidateNested() @Type(() => FlagScopeDto)
|
||||
scope?: FlagScopeDto
|
||||
|
||||
// Optional free-form note attached to the resulting history entry.
|
||||
@IsOptional() @IsString() @MaxLength(280)
|
||||
note?: string
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common'
|
||||
import { CurrentUser } from '../auth/current-user.decorator.js'
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard.js'
|
||||
import { OperatorGuard } from '../auth/operator.guard.js'
|
||||
import type { AuthentikJwtPayload } from '../auth/jwt-payload.interface.js'
|
||||
import { CreateFlagDto } from './dto/create-flag.dto.js'
|
||||
import { EvaluateDto } from './dto/evaluate.dto.js'
|
||||
import { UpdateFlagDto } from './dto/update-flag.dto.js'
|
||||
import { FlagsService } from './flags.service.js'
|
||||
|
||||
// Read access is open to any authed token (eval works for any tenant member);
|
||||
// mutations require an operator-scoped token + platformAdmin. Same shape as
|
||||
// PartnersController so the auth model stays predictable.
|
||||
@Controller('flags')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
export class FlagsController {
|
||||
constructor(private readonly flags: FlagsService) {}
|
||||
|
||||
@Get()
|
||||
findAll() {
|
||||
return this.flags.findAll()
|
||||
}
|
||||
|
||||
@Get(':key')
|
||||
findOne(@Param('key') key: string) {
|
||||
return this.flags.findOne(key)
|
||||
}
|
||||
|
||||
@Post('evaluate')
|
||||
evaluate(@Body() dto: EvaluateDto) {
|
||||
return this.flags.evaluateAll(dto.tenantSlug)
|
||||
}
|
||||
|
||||
@Post()
|
||||
@UseGuards(OperatorGuard)
|
||||
create(@Body() dto: CreateFlagDto, @CurrentUser() jwt: AuthentikJwtPayload) {
|
||||
return this.flags.create(dto, { email: jwt.email })
|
||||
}
|
||||
|
||||
@Patch(':key')
|
||||
@UseGuards(OperatorGuard)
|
||||
update(
|
||||
@Param('key') key: string,
|
||||
@Body() dto: UpdateFlagDto,
|
||||
@CurrentUser() jwt: AuthentikJwtPayload,
|
||||
) {
|
||||
return this.flags.update(key, dto, { email: jwt.email })
|
||||
}
|
||||
|
||||
@Delete(':key')
|
||||
@HttpCode(204)
|
||||
@UseGuards(OperatorGuard)
|
||||
async remove(@Param('key') key: string) {
|
||||
await this.flags.remove(key)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Module } from '@nestjs/common'
|
||||
import { MongooseModule } from '@nestjs/mongoose'
|
||||
import { AuthModule } from '../auth/auth.module.js'
|
||||
import { Flag, FlagSchema } from '../schemas/flag.schema.js'
|
||||
import { Tenant, TenantSchema } from '../schemas/tenant.schema.js'
|
||||
import { FlagsController } from './flags.controller.js'
|
||||
import { FlagsService } from './flags.service.js'
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
AuthModule,
|
||||
MongooseModule.forFeature([
|
||||
{ name: Flag.name, schema: FlagSchema },
|
||||
{ name: Tenant.name, schema: TenantSchema },
|
||||
]),
|
||||
],
|
||||
controllers: [FlagsController],
|
||||
providers: [FlagsService],
|
||||
exports: [FlagsService],
|
||||
})
|
||||
export class FlagsModule {}
|
||||
@@ -0,0 +1,214 @@
|
||||
import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common'
|
||||
import { InjectModel } from '@nestjs/mongoose'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { Model } from 'mongoose'
|
||||
import { Flag, FlagDocument } from '../schemas/flag.schema.js'
|
||||
import { Tenant, TenantDocument } from '../schemas/tenant.schema.js'
|
||||
import type { CreateFlagDto } from './dto/create-flag.dto.js'
|
||||
import type { UpdateFlagDto } from './dto/update-flag.dto.js'
|
||||
|
||||
// Max number of history entries kept embedded on a flag doc. Older entries
|
||||
// get dropped on the next change. If we want unbounded audit, route it to a
|
||||
// separate audit collection (see NEXT-STEPS.md follow-up).
|
||||
const HISTORY_LIMIT = 20
|
||||
|
||||
export interface EvalContext {
|
||||
tenantId: string
|
||||
tenantSlug: string
|
||||
plan: string
|
||||
partnerSlug?: string
|
||||
env: 'prod' | 'staging' | 'dev'
|
||||
}
|
||||
|
||||
export interface ActorRef {
|
||||
userId?: string
|
||||
email?: string
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class FlagsService {
|
||||
private readonly logger = new Logger(FlagsService.name)
|
||||
|
||||
constructor(
|
||||
@InjectModel(Flag.name) private readonly flagModel: Model<FlagDocument>,
|
||||
@InjectModel(Tenant.name) private readonly tenantModel: Model<TenantDocument>,
|
||||
) {}
|
||||
|
||||
async create(dto: CreateFlagDto, actor?: ActorRef): Promise<FlagDocument> {
|
||||
const exists = await this.flagModel.exists({ key: dto.key })
|
||||
if (exists) throw new ConflictException(`Flag "${dto.key}" already exists`)
|
||||
const doc = await this.flagModel.create({
|
||||
key: dto.key,
|
||||
description: dto.description ?? '',
|
||||
state: dto.state ?? 'off',
|
||||
pct: dto.pct ?? 0,
|
||||
scope: dto.scope ?? { plans: [], tenantSlugs: [], partnerSlugs: [], environments: [] },
|
||||
history: [
|
||||
{
|
||||
at: new Date(),
|
||||
byEmail: actor?.email,
|
||||
action: `created · state=${dto.state ?? 'off'}`,
|
||||
},
|
||||
],
|
||||
})
|
||||
return doc
|
||||
}
|
||||
|
||||
findAll(): Promise<FlagDocument[]> {
|
||||
return this.flagModel.find().sort({ key: 1 }).exec()
|
||||
}
|
||||
|
||||
async findOne(key: string): Promise<FlagDocument> {
|
||||
const flag = await this.flagModel.findOne({ key }).exec()
|
||||
if (!flag) throw new NotFoundException(`Flag "${key}" not found`)
|
||||
return flag
|
||||
}
|
||||
|
||||
async update(key: string, dto: UpdateFlagDto, actor?: ActorRef): Promise<FlagDocument> {
|
||||
const flag = await this.findOne(key)
|
||||
|
||||
const actions: string[] = []
|
||||
if (dto.description !== undefined && dto.description !== flag.description) {
|
||||
actions.push('description updated')
|
||||
flag.description = dto.description
|
||||
}
|
||||
if (dto.state !== undefined && dto.state !== flag.state) {
|
||||
actions.push(`state: ${flag.state} → ${dto.state}`)
|
||||
flag.state = dto.state
|
||||
}
|
||||
if (dto.pct !== undefined && dto.pct !== flag.pct) {
|
||||
actions.push(`pct: ${flag.pct}% → ${dto.pct}%`)
|
||||
flag.pct = dto.pct
|
||||
}
|
||||
if (dto.scope !== undefined) {
|
||||
// Replace the scope wholesale (DTO supplies the new shape).
|
||||
flag.scope = {
|
||||
plans: dto.scope.plans ?? flag.scope.plans,
|
||||
tenantSlugs: dto.scope.tenantSlugs ?? flag.scope.tenantSlugs,
|
||||
partnerSlugs: dto.scope.partnerSlugs ?? flag.scope.partnerSlugs,
|
||||
environments: dto.scope.environments ?? flag.scope.environments,
|
||||
}
|
||||
actions.push('scope updated')
|
||||
}
|
||||
|
||||
if (actions.length === 0) return flag // no-op update; don't pollute history
|
||||
|
||||
flag.history.push({
|
||||
at: new Date(),
|
||||
byEmail: actor?.email,
|
||||
action: actions.join(' · '),
|
||||
note: dto.note,
|
||||
})
|
||||
if (flag.history.length > HISTORY_LIMIT) {
|
||||
flag.history.splice(0, flag.history.length - HISTORY_LIMIT)
|
||||
}
|
||||
|
||||
await flag.save()
|
||||
return flag
|
||||
}
|
||||
|
||||
async remove(key: string): Promise<void> {
|
||||
const result = await this.flagModel.deleteOne({ key }).exec()
|
||||
if (result.deletedCount === 0) throw new NotFoundException(`Flag "${key}" not found`)
|
||||
}
|
||||
|
||||
// ── Evaluation ───────────────────────────────────────────────────────────
|
||||
|
||||
async evaluateAll(tenantSlug: string): Promise<Record<string, boolean>> {
|
||||
const tenant = await this.tenantModel.findOne({ slug: tenantSlug }).exec()
|
||||
if (!tenant) throw new NotFoundException(`Tenant "${tenantSlug}" not found`)
|
||||
|
||||
const env = (process.env.DEZKY_ENV ?? 'dev') as 'prod' | 'staging' | 'dev'
|
||||
|
||||
const ctx: EvalContext = {
|
||||
tenantId: String(tenant._id),
|
||||
tenantSlug: tenant.slug,
|
||||
plan: tenant.plan,
|
||||
// partnerId is on Tenant.partnerId; we'd need a lookup for the slug.
|
||||
// Leave as undefined for now — the eval still works (partnerSlugs scope
|
||||
// becomes "no partner" matcher). Hydrate when partner-targeted flags
|
||||
// actually exist.
|
||||
partnerSlug: undefined,
|
||||
env,
|
||||
}
|
||||
|
||||
const flags = await this.flagModel.find().exec()
|
||||
const out: Record<string, boolean> = {}
|
||||
for (const flag of flags) {
|
||||
out[flag.key] = this.evaluateOne(flag, ctx)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
evaluateOne(flag: FlagDocument, ctx: EvalContext): boolean {
|
||||
if (flag.state === 'off') return false
|
||||
if (flag.state === 'on') return true
|
||||
|
||||
// `targeted` is an explicit allowlist. Empty scope = nobody is on the list
|
||||
// yet — evaluating to false is the defensive read. If you wanted "everyone",
|
||||
// you'd flip the state to `on`.
|
||||
if (flag.state === 'targeted') {
|
||||
if (!hasAnyScope(flag.scope)) return false
|
||||
return matchesScope(flag.scope, ctx)
|
||||
}
|
||||
|
||||
// `rollout` filters by scope (empty axes = no restriction on that axis) and
|
||||
// then by deterministic hash bucket within the matching set.
|
||||
if (flag.state === 'rollout') {
|
||||
if (!matchesScope(flag.scope, ctx)) return false
|
||||
return inRolloutBucket(ctx.tenantId, flag.key, flag.pct)
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// ── Pure helpers (exported for tests) ───────────────────────────────────────
|
||||
|
||||
export function hasAnyScope(scope: {
|
||||
plans: string[]
|
||||
tenantSlugs: string[]
|
||||
partnerSlugs: string[]
|
||||
environments: string[]
|
||||
}): boolean {
|
||||
return (
|
||||
scope.plans.length > 0 ||
|
||||
scope.tenantSlugs.length > 0 ||
|
||||
scope.partnerSlugs.length > 0 ||
|
||||
scope.environments.length > 0
|
||||
)
|
||||
}
|
||||
|
||||
export function matchesScope(
|
||||
scope: {
|
||||
plans: string[]
|
||||
tenantSlugs: string[]
|
||||
partnerSlugs: string[]
|
||||
environments: string[]
|
||||
},
|
||||
ctx: EvalContext,
|
||||
): boolean {
|
||||
if (scope.environments.length && !scope.environments.includes(ctx.env)) return false
|
||||
if (scope.plans.length && !scope.plans.includes(ctx.plan)) return false
|
||||
if (scope.tenantSlugs.length && !scope.tenantSlugs.includes(ctx.tenantSlug)) return false
|
||||
if (scope.partnerSlugs.length) {
|
||||
if (!ctx.partnerSlug) return false
|
||||
if (!scope.partnerSlugs.includes(ctx.partnerSlug)) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Deterministic rollout assignment: sha256(`${tenantId}:${flagKey}`) → 0–99
|
||||
// bucket. A given tenant either is or isn't in the rollout for a given flag.
|
||||
// Bumping pct only flips the new slice, never moves existing in/out tenants.
|
||||
export function inRolloutBucket(tenantId: string, flagKey: string, pct: number): boolean {
|
||||
if (pct >= 100) return true
|
||||
if (pct <= 0) return false
|
||||
const hash = createHash('sha256').update(`${tenantId}:${flagKey}`).digest()
|
||||
const bucket = hash.readUInt16BE(0) % 100
|
||||
return bucket < pct
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
|
||||
import { HydratedDocument, Types } from 'mongoose'
|
||||
|
||||
export type FlagDocument = HydratedDocument<Flag>
|
||||
|
||||
export type FlagState = 'off' | 'targeted' | 'rollout' | 'on'
|
||||
|
||||
// Embedded change log on the flag itself. Capped to the last 20 entries via a
|
||||
// guard in FlagsService — keeps the doc small and the side-panel render fast.
|
||||
export interface FlagHistoryEntry {
|
||||
at: Date
|
||||
byUserId?: Types.ObjectId
|
||||
byEmail?: string
|
||||
action: string // e.g. 'created', 'state: off → rollout', 'pct: 25 → 50'
|
||||
note?: string
|
||||
}
|
||||
|
||||
@Schema({ collection: 'flags', timestamps: true })
|
||||
export class Flag {
|
||||
// snake_case identifier used in code paths. Same regex as TenantPlan/slug-ish
|
||||
// — keeps it greppable and unambiguous in audit messages.
|
||||
@Prop({ required: true, unique: true, index: true, lowercase: true, trim: true })
|
||||
key!: string
|
||||
|
||||
// Human label shown in the UI. Optional but recommended.
|
||||
@Prop({ default: '' })
|
||||
description!: string
|
||||
|
||||
@Prop({ enum: ['off', 'targeted', 'rollout', 'on'], default: 'off', index: true })
|
||||
state!: FlagState
|
||||
|
||||
// Only consulted when state === 'rollout'. Hash-based assignment to a bucket
|
||||
// (see FlagsService.evaluate) means a given tenant either is or isn't in the
|
||||
// rollout — flipping the pct only changes the new slice, not existing ones.
|
||||
@Prop({ default: 0, min: 0, max: 100 })
|
||||
pct!: number
|
||||
|
||||
// Targeting axes. All optional; empty/missing = "no restriction on this axis".
|
||||
// For state === 'targeted' / 'rollout', a tenant must match every non-empty
|
||||
// axis to be eligible (intersection, not union).
|
||||
@Prop({
|
||||
type: {
|
||||
plans: { type: [String], default: [] },
|
||||
tenantSlugs: { type: [String], default: [] },
|
||||
partnerSlugs: { type: [String], default: [] },
|
||||
environments: { type: [String], default: [] },
|
||||
},
|
||||
default: () => ({ plans: [], tenantSlugs: [], partnerSlugs: [], environments: [] }),
|
||||
})
|
||||
scope!: {
|
||||
plans: string[]
|
||||
tenantSlugs: string[]
|
||||
partnerSlugs: string[]
|
||||
environments: string[]
|
||||
}
|
||||
|
||||
@Prop({ type: Types.ObjectId, ref: 'User' })
|
||||
createdBy?: Types.ObjectId
|
||||
|
||||
// Capped at last 20 in FlagsService.recordHistory.
|
||||
@Prop({
|
||||
type: [
|
||||
{
|
||||
at: { type: Date, default: () => new Date() },
|
||||
byUserId: { type: Types.ObjectId, ref: 'User' },
|
||||
byEmail: String,
|
||||
action: { type: String, required: true },
|
||||
note: String,
|
||||
},
|
||||
],
|
||||
default: [],
|
||||
})
|
||||
history!: FlagHistoryEntry[]
|
||||
}
|
||||
|
||||
export const FlagSchema = SchemaFactory.createForClass(Flag)
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common'
|
||||
import { MongooseModule } from '@nestjs/mongoose'
|
||||
import { Flag, FlagSchema } from '../schemas/flag.schema.js'
|
||||
import { Subscription, SubscriptionSchema } from '../schemas/subscription.schema.js'
|
||||
import { Tenant, TenantSchema } from '../schemas/tenant.schema.js'
|
||||
import { User, UserSchema } from '../schemas/user.schema.js'
|
||||
@@ -11,6 +12,7 @@ import { SeedService } from './seed.service.js'
|
||||
{ name: Tenant.name, schema: TenantSchema },
|
||||
{ name: User.name, schema: UserSchema },
|
||||
{ name: Subscription.name, schema: SubscriptionSchema },
|
||||
{ name: Flag.name, schema: FlagSchema },
|
||||
]),
|
||||
],
|
||||
providers: [SeedService],
|
||||
|
||||
@@ -2,10 +2,41 @@ import { Injectable, Logger, type OnApplicationBootstrap } from '@nestjs/common'
|
||||
import { ConfigService } from '@nestjs/config'
|
||||
import { InjectModel } from '@nestjs/mongoose'
|
||||
import { Model } from 'mongoose'
|
||||
import { Flag, FlagDocument, type FlagState } from '../schemas/flag.schema.js'
|
||||
import { Subscription, SubscriptionDocument } from '../schemas/subscription.schema.js'
|
||||
import { Tenant, TenantDocument } from '../schemas/tenant.schema.js'
|
||||
import { User, UserDocument } from '../schemas/user.schema.js'
|
||||
|
||||
interface SeedFlag {
|
||||
key: string
|
||||
description: string
|
||||
state: FlagState
|
||||
pct?: number
|
||||
scope?: {
|
||||
plans?: string[]
|
||||
tenantSlugs?: string[]
|
||||
partnerSlugs?: string[]
|
||||
environments?: ('prod' | 'staging' | 'dev')[]
|
||||
}
|
||||
}
|
||||
|
||||
// Initial set of flags. Keys + states map to real Dezky concerns documented
|
||||
// in the operator design — flags here become real switches the operator
|
||||
// can flip once the gated features land. Seeded with $setOnInsert so an
|
||||
// operator editing them later doesn't get clobbered on restart.
|
||||
const FLAG_SEEDS: SeedFlag[] = [
|
||||
{ key: 'jmap_native_v2', state: 'off', description: 'Native JMAP client (replacing the HTTP-stub bridge)', scope: { plans: ['pro', 'enterprise'] } },
|
||||
{ key: 'oci_versioning', state: 'on', description: 'OCIS file versioning enabled' },
|
||||
{ key: 'jitsi_recording_e2ee', state: 'targeted', description: 'E2EE recording in Jitsi (pilot)' },
|
||||
{ key: 'new_billing_engine', state: 'off', description: 'Stripe-backed billing engine — replacing manual invoicing' },
|
||||
{ key: 'gdpr_export_v2', state: 'off', description: 'Self-serve GDPR data export — kept off until reviewed' },
|
||||
{ key: 'whitelabel_cssprops', state: 'on', description: 'Per-partner whitelabel CSS variables' },
|
||||
{ key: 'audit_log_streaming', state: 'off', description: 'Real-time audit log streaming to the operator UI', scope: { plans: ['enterprise'] } },
|
||||
{ key: 'zulip_topic_threading', state: 'off', description: 'Zulip topic threading UI (post deploy)' },
|
||||
{ key: 'tos_2026_acceptance', state: 'on', description: 'Force users to accept the v2026 Terms of Service' },
|
||||
{ key: 'beta_ai_summaries', state: 'off', description: 'AI summaries for inbox + files — killed pending review' },
|
||||
]
|
||||
|
||||
// Idempotent seed: a default 'dezky' tenant + the akadmin user, so the portal can
|
||||
// query non-empty results immediately. Real user records are bootstrapped via
|
||||
// UsersController.me() on each user's first authenticated request.
|
||||
@@ -17,6 +48,7 @@ export class SeedService implements OnApplicationBootstrap {
|
||||
@InjectModel(Tenant.name) private readonly tenantModel: Model<TenantDocument>,
|
||||
@InjectModel(User.name) private readonly userModel: Model<UserDocument>,
|
||||
@InjectModel(Subscription.name) private readonly subModel: Model<SubscriptionDocument>,
|
||||
@InjectModel(Flag.name) private readonly flagModel: Model<FlagDocument>,
|
||||
private readonly config: ConfigService,
|
||||
) {}
|
||||
|
||||
@@ -60,5 +92,44 @@ export class SeedService implements OnApplicationBootstrap {
|
||||
this.logger.log(`Subscription ready for ${tenant.slug}`)
|
||||
|
||||
// No user seeded here — UsersController.me() upserts akadmin on first call.
|
||||
|
||||
// Feature flags. Seeded via $setOnInsert so an operator who later edits a
|
||||
// flag's state through the UI doesn't get their change reverted on the
|
||||
// next bootstrap.
|
||||
let createdFlags = 0
|
||||
for (const seed of FLAG_SEEDS) {
|
||||
const res = await this.flagModel
|
||||
.findOneAndUpdate(
|
||||
{ key: seed.key },
|
||||
{
|
||||
$setOnInsert: {
|
||||
key: seed.key,
|
||||
description: seed.description,
|
||||
state: seed.state,
|
||||
pct: seed.pct ?? 0,
|
||||
scope: {
|
||||
plans: seed.scope?.plans ?? [],
|
||||
tenantSlugs: seed.scope?.tenantSlugs ?? [],
|
||||
partnerSlugs: seed.scope?.partnerSlugs ?? [],
|
||||
environments: seed.scope?.environments ?? [],
|
||||
},
|
||||
history: [{ at: new Date(), action: `seeded · state=${seed.state}` }],
|
||||
},
|
||||
},
|
||||
{ upsert: true, new: true, rawResult: true },
|
||||
)
|
||||
.exec()
|
||||
// Mongoose returns the raw mongo result; lastErrorObject.updatedExisting
|
||||
// is false when it just inserted.
|
||||
if (
|
||||
(res as unknown as { lastErrorObject?: { updatedExisting?: boolean } })
|
||||
.lastErrorObject?.updatedExisting === false
|
||||
) {
|
||||
createdFlags++
|
||||
}
|
||||
}
|
||||
if (createdFlags > 0) {
|
||||
this.logger.log(`Seeded ${createdFlags} new flag(s) (of ${FLAG_SEEDS.length})`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user