Cross-Language Feature Flag DSL Compiler Design
Overview
This document drafts a compiler for a cross-language Feature Flag DSL called FlagScript . FlagScript allows engineers to define complex feature flags with targeting rules (e.g., user segments, percentages, gradual rollouts) in a single, declarative YAML/JSON-like syntax. The compiler parses FlagScript into an AST , performs static validation, and outputs either:
An interpreter (portable JS runtime evaluating the AST).
A transpiler (generates idiomatic code in target languages: JS/TS, Python, Java, Go, Rust).
Goals :
Single source of truth for flags across services/microservices.
Zero-downtime rollouts with validation.
Extensible for custom predicates (e.g., A/B tests, geo-fencing).
Target Use Cases :
percentage: 10% rollout to users.
and(user.premium = true, geo in ["US", "EU"]).
Gradual rollouts: ramp(0.1/hour).
DSL Syntax (FlagScript)
Human-readable, YAML-inspired grammar (parsed via ANTLR/Peggy.js for multi-lang support).
yaml Copy code
flag: "new-payment-ui"
enabled: ramp(0.1/hour) # Gradual rollout
targets:
- percentage: 10 # 10% of users
and:
- user.segment: "beta"
- geo: ["US", "CA"]
- or:
- user.id: [123, 456]
- experiment: "A"
unless: error_rate > 0.05 # Kill switch
metadata:
owner: "payments-team"
description: "New UI with Stripe integration"
Primitives :
Literals: true, false, null, strings, numbers, arrays.
Predicates: user.prop OP value (OP: =, !=, >, <, in, regex).
Operators: and, or, not.
Functions: percentage(pct), ramp(rate/unit), time(after), experiment(name).
Full grammar in EBNF:
code Copy code
Flag ::= 'flag:' STRING 'enabled:' Expr 'targets?:' [Target]* 'unless?:' Expr
Target ::= Percentage | And | Or | Predicate
Expr ::= Literal | Predicate | And[Expr+] | Or[Expr+] | Not[Expr] | FuncCall
Predicate ::= Ident '.' Ident OP Literal # e.g., user.segment = "beta"
FuncCall ::= 'percentage' '(' NUMBER ')' | 'ramp' '(' NUMBER '/' UNIT ')'
AST Design
AST is language-agnostic, serialized as JSON/Protobuf for interpreter/transpiler. Defined in TypeScript (for the compiler impl).
typescript Copy code
type ASTNode =
| { type: 'Flag'; name: string; enabled: Expr; targets: Target[]; unless?: Expr; metadata: Record<string, any> }
| { type: 'Expr'; ... } // Union below
type Expr =
| { type: 'Literal'; value: any } // bool/num/str/array
| { type: 'Predicate'; subject: string; prop: string; op: Operator; value: Literal }
| { type: 'And'; exprs: Expr[] }
| { type: 'Or'; exprs: Expr[] }
| { type: 'Not'; expr: Expr }
| { type: 'FuncCall'; name: string; args: Literal[] } // e.g., {name: 'percentage', args: [0.1]}
type Operator = '=' | '!=' | '>' | '<' | 'in' | 'regex';
type Target = Percentage | Expr; // Percentage is {type: 'Percentage', pct: number}
Key Design Decisions :
Immutable, recursive structure : Enables easy traversal/walking.
Contextual evaluation : subject (e.g., user) resolved at runtime via context object {user: {id: 123, segment: 'beta'}, request: {...}}.
Extensibility : Plugins for custom nodes (e.g., ml_model(input)).
Size: <1KB serialized for typical flags.
Parser Pipeline :
Lex → Tokens (ANTLR4 target: JS/Python/Java).
Parse → CST.
Semantic analysis → AST (resolve refs, infer types).
Interpreter vs Transpiler Trade-offs
Aspect Interpreter (JS Runtime) Transpiler (Native Code Gen) Portability Excellent: Single bundle (~50KB gzipped), embed anywhere. Poor: N+ codegens (JS/TS, Python, Java, etc.). Performance Good (JIT): <1ms eval/flag. Cacheable. Excellent: Native speed, inlined. Complexity Low: Walk AST recursively. evalFlag(ast, ctx). High: Lang-specific emitters (e.g., Rust macros). Debugging Easy: Stack traces in JS console. Hard: Multi-lang diffs. Startup Cost Low: Instant load. None: Compiled in. Use Case Fit Prototyping, dynamic flags (remote config). Production: High-traffic services. Bundle Size Fixed overhead. Zero runtime overhead. Maintenance Single impl. Updates propagate instantly. N maintainers per lang. Divergence risk.
Recommendation : Hybrid .
Default: Interpreter for 80% cases (SDKs embed it).
Opt-in Transpiler for perf-critical langs (JS/Go first).
Trade-off metric: Transpile if eval_count > 1M/day per flag.
Interpreter Impl Sketch (JS):
js Copy code
function evalExpr(expr, ctx) {
switch (expr.type) {
case 'Predicate':
const val = getNested(ctx, expr.subject, expr.prop);
return applyOp(val, expr.op, expr.value);
case 'And': return expr.exprs.every(e => evalExpr(e, ctx));
// ...
}
}
Transpiler Example (JS output):
js Copy code
function isEnabled(ctx) {
return ctx.user.segment === 'beta' && geoIn(ctx.geo, ['US', 'CA']) && !(error_rate > 0.05);
}
Static Validation
Multi-pass semantic analysis before emit. Errors halt compilation.
Syntax : Parser errors.
Type Checking (inferred schema):
user.segment must be string, error_rate → number.
Schema: {user: {id: number, segment: string}, geo: string[], error_rate: number}.
Report: "Type mismatch: geo expected array, got number".
Logical Validation :
No tautologies: and(true, false) → Warn.
Coverage: targets union >=100%? Warn if partial.
Cycles: No recursive refs.
Safety :
No unbounded loops/recursion.
Kill-switch presence for prod flags.
Linting : Custom rules (e.g., "Avoid >50% ramp without approval").
Impl : Walker visitor pattern.
typescript Copy code
validate(ast: ASTNode, schema: Schema): ValidationResult {
// Recursive typecheck + logical rules
}
Output : {valid: true, warnings: [], fixes?: ASTNode[]} (auto-fix tautologies).
Rollout Strategy
Phased, zero-downtime rollout of the compiler/SDK.
Phase Milestone Duration Success Metrics Rollback Plan 0: Internal Alpha Parse 10 sample flags. Impl interpreter. 2 weeks 100% parse success. N/A 1: Beta SDKs JS/Python interp SDKs. Static val. 4 weeks 50 teams adopt. 99.9% uptime. Fallback to legacy flags. 2: Transpiler JS/Go transpilers. Hybrid mode. 6 weeks Perf: 2x faster evals. 80% migration. Dual-run old/new. 3: Full Multi-Lang Java/Rust. Remote config integration. 8 weeks Cross-lang parity. 100% teams. Feature flag the compiler! 4: Production CI/CD integration (pre-commit val). Ongoing <0.1% invalid flags deployed. Canary per service.
Key Enablers :
Migration Path : Legacy flags → auto-migrate to FlagScript.
Monitoring : Flag eval latency, val errors (Datadog/Prometheus).
AB Test : 10% services get new compiler via meta-flag.
Team : 2 engineers (parser/codegen), 1 PM.
Risks & Mitigations :
Divergent transpilers: Golden AST tests (roundtrip).
Adoption: CLI tool flagscript compile flag.yaml --target=js.
This draft is implementable in ~3 months. Next: Prototype parser in ANTLR. Feedback?