Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix(flags): False positive when variant rule is an async function #876

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
19 changes: 12 additions & 7 deletions blocks/flag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import JsonViewer from "../components/JsonViewer.tsx";
import type { Block, BlockModule, InstanceOf } from "../engine/block.ts";
import { isDeferred } from "../engine/core/resolver.ts";
import { type Device, deviceOf } from "../utils/userAgent.ts";

export type Flag = InstanceOf<typeof flagBlock, "#/root/flags">;

export interface FlagObj<TVariant = unknown> {
Expand Down Expand Up @@ -64,7 +65,7 @@ const flagBlock: Block<BlockModule<FlagFunc>> = {
>(func: {
default: FlagFunc<TConfig>;
}) =>
($live: TConfig, { request }: HttpContext) => {
async ($live: TConfig, { request }: HttpContext) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this will impact tracings as only async functions are included on tracing. This shouldn't be though but we should keep an eye on it.

const flag = func.default($live);
let device: Device | null = null;
const ctx = {
Expand All @@ -75,12 +76,16 @@ const flagBlock: Block<BlockModule<FlagFunc>> = {
},
};
if (isMultivariate(flag)) {
const value = ((flag?.variants ?? []).find((variant) =>
typeof variant?.rule === "function" && variant?.rule(ctx)
) as Variant<unknown>)?.value ??
((flag?.variants ?? [])[flag?.variants?.length - 1] as Variant<unknown>)
?.value;
return isDeferred(value) ? value() : value;
const variants = flag.variants || [];

const results = await Promise.all(
variants.map((variant) =>
typeof variant?.rule === "function" ? variant.rule(ctx) : false
),
);
const match = variants.find((_, index) => results[index]) || variants[0];

return isDeferred(match?.value) ? match?.value() : match?.value;
}
const matchValue = typeof flag?.matcher === "function"
? flag.matcher(ctx)
Expand Down
Loading