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
2 changes: 1 addition & 1 deletion packages/flag-evaluation/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@bucketco/flag-evaluation",
"version": "0.1.0",
"version": "0.2.0",
"license": "MIT",
"repository": {
"type": "git",
Expand Down
70 changes: 45 additions & 25 deletions packages/flag-evaluation/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { createHash } from "node:crypto";
try {
// crypto not available on globalThis in Node.js v18
// eslint-disable-next-line @typescript-eslint/no-require-imports
globalThis.crypto ??= require("node:crypto").webcrypto;
} catch {
// ignore
}

/**
* Represents a filter class with a specific type property.
Expand Down Expand Up @@ -259,16 +265,20 @@ export function unflattenJSON(data: Record<string, any>): Record<string, any> {
* @param {string} hashInput - The input string used to generate the hash.
* @return {number} A number between 0 and 100000 derived from the hash of the input string.
*/
export function hashInt(hashInput: string): number {
export async function hashInt(hashInput: string): Promise<number> {
// 1. hash the key and the partial rollout attribute
// 2. take 20 bits from the hash and divide by 2^20 - 1 to get a number between 0 and 1
// 3. multiply by 100000 to get a number between 0 and 100000 and compare it to the threshold
//
// we only need 20 bits to get to 100000 because 2^20 is 1048576
const hash =
createHash("sha256").update(hashInput, "utf-8").digest().readUInt32LE(0) &
0xfffff;
return Math.floor((hash / 0xfffff) * 100000);
const msgUint8 = new TextEncoder().encode(hashInput);

// Hash the message
const hashBuffer = await crypto.subtle.digest("SHA-256", msgUint8);

const view = new DataView(hashBuffer);
const value = view.getUint32(0, true) & 0xfffff;
return Math.floor((value / 0xfffff) * 100000);
}

/**
Expand Down Expand Up @@ -341,11 +351,11 @@ export function evaluate(
}
}

function evaluateRecursively(
async function evaluateRecursively(
filter: RuleFilter,
context: Record<string, string>,
missingContextFieldsSet: Set<string>,
): boolean {
): Promise<boolean> {
switch (filter.type) {
case "constant":
return filter.value;
Expand All @@ -366,30 +376,38 @@ function evaluateRecursively(
return false;
}

const hashVal = hashInt(
const hashVal = await hashInt(
`${filter.key}.${context[filter.partialRolloutAttribute]}`,
);

return hashVal < filter.partialRolloutThreshold;
}
case "group":
return filter.filters.reduce((acc, current) => {
if (filter.operator === "and") {
return (
acc &&
evaluateRecursively(current, context, missingContextFieldsSet)
);
case "group": {
const isAnd = filter.operator === "and";
let result = isAnd;
for (const current of filter.filters) {
// short-circuit if we know the result already
// could be simplified to isAnd !== result, but this is more readable
if ((isAnd && !result) || (!isAnd && result)) {
return result;
}
return (
acc || evaluateRecursively(current, context, missingContextFieldsSet)

const newRes = await evaluateRecursively(
current,
context,
missingContextFieldsSet,
);
}, filter.operator === "and");

result = isAnd ? result && newRes : result || newRes;
}
return result;
}
case "negation":
return !evaluateRecursively(
return !(await evaluateRecursively(
filter.filter,
context,
missingContextFieldsSet,
);
));
default:
return false;
}
Expand Down Expand Up @@ -431,16 +449,18 @@ export interface EvaluationResult<T extends RuleValue> {
missingContextFields?: string[];
}

export function evaluateFeatureRules<T extends RuleValue>({
export async function evaluateFeatureRules<T extends RuleValue>({
context,
featureKey,
rules,
}: EvaluationParams<T>): EvaluationResult<T> {
}: EvaluationParams<T>): Promise<EvaluationResult<T>> {
const flatContext = flattenJSON(context);
const missingContextFieldsSet = new Set<string>();

const ruleEvaluationResults = rules.map((rule) =>
evaluateRecursively(rule.filter, flatContext, missingContextFieldsSet),
const ruleEvaluationResults = await Promise.all(
rules.map((rule) =>
evaluateRecursively(rule.filter, flatContext, missingContextFieldsSet),
),
);

const missingContextFields = Array.from(missingContextFieldsSet);
Expand Down
16 changes: 8 additions & 8 deletions packages/flag-evaluation/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const feature = {

describe("evaluate feature targeting integration ", () => {
it("evaluates all kinds of filters", async () => {
const res = evaluateFeatureRules({
const res = await evaluateFeatureRules({
featureKey: "feature",
rules: [
{
Expand Down Expand Up @@ -109,7 +109,7 @@ describe("evaluate feature targeting integration ", () => {
});

it("evaluates flag when there's no matching rule", async () => {
const res = evaluateFeatureRules({
const res = await evaluateFeatureRules({
...feature,
context: {
company: {
Expand Down Expand Up @@ -137,7 +137,7 @@ describe("evaluate feature targeting integration ", () => {
},
};

const res = evaluateFeatureRules({
const res = await evaluateFeatureRules({
...feature,
context,
});
Expand All @@ -155,7 +155,7 @@ describe("evaluate feature targeting integration ", () => {
});

it("evaluates flag with missing values", async () => {
const res = evaluateFeatureRules({
const res = await evaluateFeatureRules({
featureKey: "feature",
rules: [
{
Expand Down Expand Up @@ -198,7 +198,7 @@ describe("evaluate feature targeting integration ", () => {
});

it("returns list of missing context keys ", async () => {
const res = evaluateFeatureRules({
const res = await evaluateFeatureRules({
...feature,
context: {},
});
Expand All @@ -214,7 +214,7 @@ describe("evaluate feature targeting integration ", () => {
});

it("fails evaluation and includes key in missing keys when rollout attribute is missing from context", async () => {
const res = evaluateFeatureRules({
const res = await evaluateFeatureRules({
featureKey: "myfeature",
rules: [
{
Expand Down Expand Up @@ -352,8 +352,8 @@ describe("rollout hash", () => {
] as const;

for (const [input, expected] of tests) {
it(`evaluates '${input}' = ${expected}`, () => {
const res = hashInt(input);
it(`evaluates '${input}' = ${expected}`, async () => {
const res = await hashInt(input);
expect(res).toEqual(expected);
});
}
Expand Down
1 change: 1 addition & 0 deletions packages/node-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export type {
ContextWithTracking,
EmptyFeatureRemoteConfig,
Feature,
FeatureConfigVariant,
FeatureOverride,
FeatureOverrides,
FeatureOverridesFn,
Expand Down
4 changes: 1 addition & 3 deletions packages/node-sdk/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,9 +232,7 @@ export type FeatureOverrides = Partial<
export type FeatureOverridesFn = (context: Context) => FeatureOverrides;

/**
* (Internal) Describes a remote feature config variant.
*
* @internal
* Describes a remote feature config variant.
*/
export type FeatureConfigVariant = {
/**
Expand Down
9 changes: 8 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,14 @@ __metadata:
languageName: unknown
linkType: soft

"@bucketco/flag-evaluation@npm:~0.1.0, @bucketco/flag-evaluation@workspace:packages/flag-evaluation":
"@bucketco/flag-evaluation@npm:~0.1.0":
version: 0.1.0
resolution: "@bucketco/flag-evaluation@npm:0.1.0"
checksum: 10c0/a5d747962d43ce12b194735e92524a576edac9e9ad53c425b4a517123ca9918d3001891cd212f178b7cf6b235c79aa5cfa3942e162187da056c2ae1d5230a984
languageName: node
linkType: hard

"@bucketco/flag-evaluation@workspace:packages/flag-evaluation":
version: 0.0.0-use.local
resolution: "@bucketco/flag-evaluation@workspace:packages/flag-evaluation"
dependencies:
Expand Down