Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
"@types/jsdom": "^20.0.1",
"@types/node": "^22.0.0",
"@types/react": "^18.3.0",
"@types/react-dom": "^18.3.7",
"jsdom": "^20.0.3",
"react-dom": "^18.3.1",
"vitest": "^4.1.11"
},
"engines": {
Expand Down
21 changes: 21 additions & 0 deletions packages/evaluator/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024-present Flaggr Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
4 changes: 3 additions & 1 deletion packages/evaluator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ console.log(result.reason) // "TARGETING_MATCH"
- Zero dependencies
- Gives the same results as Flaggr's data plane for the operators it implements: equals, not_equals, in, not_in, contains, starts_with, ends_with, greater_than, less_than, gte, lte, regex, before and after. `isLocallyEvaluable(flag)` tells you whether a flag uses only these. It also evaluates exists and not_exists. Cohort operators need the server.
- Percentage rollouts with deterministic hashing
- Variant assignment for experiments
- Targeting rules match as on the Flaggr data plane. A rule's condition groups, when it has them, decide (a group without conditions matches nobody); otherwise its conditions do, and a rule with no conditions matches everyone, so `conditions: []` with `rolloutPercentage: 10` serves the rule's value to 10% of all users. A context without a `targetingKey` is never in a rollout below 100%. Flaggr stores percentages and weights as whole numbers from 0 to 100. (Deployments of `api.flaggr.dev` from before Flaggr 0.5.0 match a rule with no conditions to nobody.)
- Reads flags as the data plane encodes them (`/api/flags/export`, its SSE configuration events): a field encoded as `null` is unset, as is `""` in `conditionOperator`, `groupOperator` and `variant`. So a rule whose `rolloutPercentage` is `null` serves everyone it matches, and one whose `value` is `null` serves the flag's default. An entry of `targeting` or `overrides` that isn't an object is skipped.
- Variant splits by targeting key (a running Flaggr experiment assigns its variants only on the control plane, not here)
- Type-safe evaluation (boolean, string, number, object)

## Documentation
Expand Down
14 changes: 10 additions & 4 deletions packages/evaluator/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,14 @@
"types": "dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
}
},
"files": [
Expand All @@ -20,7 +25,8 @@
"build": "tsup src/index.ts --format cjs,esm --dts",
"dev": "tsup src/index.ts --format cjs,esm --dts --watch",
"clean": "rm -rf dist",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"devDependencies": {
"tsup": "^8.0.0",
Expand Down
74 changes: 49 additions & 25 deletions packages/evaluator/src/evaluator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,13 @@ export const GO_SUPPORTED_OPERATORS: ReadonlySet<string> = new Set([
* remotely.
*/
export function isLocallyEvaluable(flag: FlagConfig): boolean {
for (const rule of flag.targeting ?? []) {
for (const rule of Array.isArray(flag.targeting) ? flag.targeting : []) {
if (!isObject(rule)) continue;
for (const cond of rule.conditions ?? []) {
if (!GO_SUPPORTED_OPERATORS.has(cond.operator)) return false;
}
for (const group of rule.groups ?? []) {
for (const cond of group.conditions ?? []) {
for (const cond of group?.conditions ?? []) {
if (!GO_SUPPORTED_OPERATORS.has(cond.operator)) return false;
}
}
Expand All @@ -71,6 +72,10 @@ export class Evaluator {
* Evaluates a flag configuration against an evaluation context.
* Order (Go parity): disabled → overrides → targeting rules (schedule →
* conditions/groups → rollout %) → variants → default.
*
* Reads the data plane's JSON (/api/flags/export, its SSE configuration
* events) as the data plane does: a field it encodes as null or "" is unset,
* and an entry of targeting or overrides that isn't an object is skipped.
*/
static evaluate(
flag: FlagConfig,
Expand All @@ -84,10 +89,10 @@ export class Evaluator {
}

// Overrides — identity match, priority-sorted (highest first)
if (flag.overrides && flag.overrides.length > 0 && context.targetingKey) {
const sorted = [...flag.overrides].sort(
(a, b) => (b.priority ?? 0) - (a.priority ?? 0)
);
if (Array.isArray(flag.overrides) && flag.overrides.length > 0 && context.targetingKey) {
const sorted = flag.overrides
.filter(isObject)
.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
for (const override of sorted) {
if (override.identifiers?.includes(context.targetingKey)) {
return { value: override.value, reason: "OVERRIDE" };
Expand All @@ -96,21 +101,23 @@ export class Evaluator {
}

// Targeting rules
if (flag.targeting && flag.targeting.length > 0) {
if (Array.isArray(flag.targeting) && flag.targeting.length > 0) {
for (const rule of flag.targeting) {
// Not an object (null, or junk an import stored): no rule. Read as
// one, it would have no conditions and match everyone.
if (!isObject(rule)) continue;
if (!isWithinSchedule(rule.schedule)) continue;
if (this.evaluateRule(rule, context)) {
if (
rule.rolloutPercentage !== undefined &&
rule.rolloutPercentage != null &&
rule.rolloutPercentage < 100 &&
!isInRollout(flag.key, context.targetingKey ?? "", rule.rolloutPercentage)
) {
continue;
}
const value = rule.value !== undefined ? rule.value : flag.defaultValue;
return {
value,
variant: rule.variant,
value: rule.value != null ? rule.value : flag.defaultValue,
variant: rule.variant || undefined,
reason: "TARGETING_MATCH",
};
}
Expand Down Expand Up @@ -169,47 +176,56 @@ export class Evaluator {
}

/**
* Evaluates a targeting rule against the context.
* Groups take precedence over flat conditions (Go parity).
* Evaluates a targeting rule against the context (Go parity). A rule with
* condition groups is decided by its groups; otherwise its flat conditions
* combine with conditionOperator ("and" by default). A rule with neither
* conditions nor groups matches everyone, so `conditions: []` with a
* rolloutPercentage rolls the rule's value out to that share of all users.
* The cases in test/rule-matching-cases.json pin these semantics for this
* evaluator, the control plane's and the Go data plane's.
*/
private static evaluateRule(
rule: TargetingRule,
context: EvaluationContext
): boolean {
if (rule.groups && rule.groups.length > 0) {
if (Array.isArray(rule.groups) && rule.groups.length > 0) {
return this.evaluateGroups(rule.groups, rule.groupOperator || "or", context);
}

if (!rule.conditions || rule.conditions.length === 0) {
return false;
// No groups and no conditions: the rule matches everyone.
const conditions = rule.conditions;
if (!Array.isArray(conditions) || conditions.length === 0) {
return true;
}

const operator = rule.conditionOperator || "and";

if (operator === "or") {
return rule.conditions.some((condition: Condition) =>
return conditions.some((condition: Condition) =>
this.evaluateCondition(condition, context)
);
}

// Default: AND logic
return rule.conditions.every((condition: Condition) =>
return conditions.every((condition: Condition) =>
this.evaluateCondition(condition, context)
);
}

/**
* Evaluates condition groups: each group ANDs its conditions, groups combine
* with the group operator (default "or") — Go parity.
* with the group operator (default "or") — Go parity. A group without
* conditions matches nobody.
*/
private static evaluateGroups(
groups: ConditionGroup[],
groups: Array<ConditionGroup | null>,
groupOp: string,
context: EvaluationContext
): boolean {
const evalGroup = (g: ConditionGroup): boolean => {
if (!g.conditions || g.conditions.length === 0) return false;
return g.conditions.every((cond) => this.evaluateCondition(cond, context));
const evalGroup = (g: ConditionGroup | null): boolean => {
const conditions = g?.conditions;
if (!Array.isArray(conditions) || conditions.length === 0) return false;
return conditions.every((cond) => this.evaluateCondition(cond, context));
};

if (groupOp === "or") {
Expand Down Expand Up @@ -388,7 +404,9 @@ export function hashString(str: string): number {

/**
* Gradual rollout bucket check — Go parity:
* hash(flagKey + ":rollout:" + targetingKey) % 100 < percentage
* hash(flagKey + ":rollout:" + targetingKey) % 100 < percentage. Without a
* targeting key there is no bucket, so a partial rollout leaves the context
* out.
*/
export function isInRollout(
flagKey: string,
Expand All @@ -397,9 +415,15 @@ export function isInRollout(
): boolean {
if (percentage === 0) return false;
if (percentage >= 100) return true;
if (!targetingKey) return false;
return hashString(`${flagKey}:rollout:${targetingKey}`) % 100 < percentage;
}

/** A JSON object (not null, not an array): what a rule or an override must be. */
function isObject<T>(value: T): value is T & object {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

/**
* Equality with Go evaluator coercion: strings compare as strings, numbers as
* numbers, booleans as booleans; mixed types fall back to string form
Expand Down Expand Up @@ -432,7 +456,7 @@ function parseDate(value: unknown): Date | null {
* Schedule gating — Go parity (IsWithinSchedule). All times are UTC.
*/
export function isWithinSchedule(
schedule: RuleSchedule | undefined,
schedule: RuleSchedule | null | undefined,
now: Date = new Date()
): boolean {
if (!schedule) return true;
Expand Down
35 changes: 22 additions & 13 deletions packages/evaluator/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,18 +70,19 @@ export interface Condition {

/**
* Condition group — conditions AND together, groups combine via the rule's
* groupOperator (Go evaluator parity).
* groupOperator (Go evaluator parity). A group without conditions matches
* nobody.
*/
export interface ConditionGroup {
conditions: Condition[];
conditions: Condition[] | null;
}

/**
* Recurring schedule window (UTC)
*/
export interface ScheduleRecurrence {
type?: string; // "daily" | "weekly"
daysOfWeek?: number[]; // 0=Sunday
daysOfWeek?: number[] | null; // 0=Sunday
startTime?: string; // "HH:MM"
endTime?: string; // "HH:MM"
}
Expand All @@ -92,22 +93,30 @@ export interface ScheduleRecurrence {
export interface RuleSchedule {
startDate?: string; // RFC3339
endDate?: string; // RFC3339
recurrence?: ScheduleRecurrence;
recurrence?: ScheduleRecurrence | null;
}

/**
* Targeting rule with conditions and resulting value/variant
* Targeting rule with conditions and resulting value/variant. Groups, when
* present, decide whether it matches; otherwise its conditions do, and a rule
* with neither (`conditions: []`) matches every context.
*
* The data plane's JSON (/api/flags/export, its SSE configuration events)
* writes every field: an unset one as null, or as "" for conditionOperator,
* groupOperator and variant. Both read as unset.
*/
export interface TargetingRule {
id: string;
conditions: Condition[];
conditions?: Condition[] | null;
conditionOperator?: "and" | "or"; // Default: "and"
groups?: ConditionGroup[];
groups?: ConditionGroup[] | null;
groupOperator?: "and" | "or"; // Default: "or"
variant?: string;
value?: FlagValue;
rolloutPercentage?: number;
schedule?: RuleSchedule;
/** Unset: the rule serves the flag's default value. */
value?: FlagValue | null;
/** Share of targeting keys (0-100, whole numbers) the rule serves; unset serves all. */
rolloutPercentage?: number | null;
schedule?: RuleSchedule | null;
}

/**
Expand All @@ -129,9 +138,9 @@ export interface FlagConfig {
type: FlagType;
enabled: boolean;
defaultValue: FlagValue;
variants?: FlagVariant[];
targeting?: TargetingRule[];
overrides?: FlagOverride[];
variants?: FlagVariant[] | null;
targeting?: TargetingRule[] | null;
overrides?: FlagOverride[] | null;
}

/**
Expand Down
Loading
Loading