Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -20,16 +20,16 @@
"devDependencies": {
"@hivegrid/logger": "workspace:*",
"@types/node": "^25.6.0",
"@types/react": "^18.3.27",
"@types/react-dom": "^18.3.7",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"react": "19.2.3",
"react-dom": "19.2.3",
"typescript": "^5.3.2",
"vitest": "^3.2.4"
},
"peerDependencies": {
"@hivegrid/logger": "workspace:*",
"react": "^18.3.1"
"react": ">=18.3.1 <20"
},
"peerDependenciesMeta": {
"@hivegrid/logger": {
@@ -1,17 +1,17 @@
import { describe, expect, it, beforeEach } from "vitest";
import { createSharedStore, createTwoTierCache } from "@hivegrid/shared-store";
import { createSharedStore, createTwoTierCache, MemoryAdapter } from "@hivegrid/shared-store";
import { buildCacheKey, createFlagEvalCache, hashContext } from "./cache.js";
import type { EvaluateFlagResult } from "./evaluate.js";
function mkStore() {
const store = createSharedStore({ namespace: "ff-test" });
const store = createSharedStore({ namespace: "ff-test", adapter: new MemoryAdapter() });
const tier = createTwoTierCache<EvaluateFlagResult>({
store,
namespace: "feature-flags",
ttlSeconds: 60,
pubsubEnabled: false,
});
return tier;
return { store, tier };
}
describe("hashContext", () => {
@@ -46,10 +46,11 @@ describe("buildCacheKey", () => {
describe("createFlagEvalCache", () => {
let cache: ReturnType<typeof createFlagEvalCache>;
let tier: ReturnType<typeof mkStore>;
let tier: ReturnType<typeof mkStore>["tier"];
beforeEach(() => {
tier = mkStore();
cache = createFlagEvalCache(tier);
const built = mkStore();
tier = built.tier;
cache = createFlagEvalCache(tier, built.store);
});
it("set then get returns the same value", async () => {
@@ -69,21 +70,81 @@ describe("createFlagEvalCache", () => {
await cache.set("flag1", { flagName: "flag1", userId: "u1" }, result);
expect(await cache.get("flag1", { flagName: "flag1", userId: "u1" })).toEqual(result);
await cache.invalidateAll();
// After flush, L1 is empty. L2 still has the entry (TTL-based) but
// a different namespace would have to look it up; with pubsub off
// we only flush local, so L2 still has it.
expect(tier.l1.get(buildCacheKey("flag1", { flagName: "flag1", userId: "u1" }))).toBeUndefined();
expect(await cache.get("flag1", { flagName: "flag1", userId: "u1" })).toBeNull();
});
it("invalidateFlag publishes a token that flushes L1", async () => {
it("invalidateFlag makes old L1 and L2 evaluations unreachable", async () => {
const result: EvaluateFlagResult = { enabled: true, reason: "matched" };
await cache.set("flag1", { flagName: "flag1" }, result);
await cache.invalidateFlag("flag1");
// local L1 entry remains because the wildcard is not '*' — verify
// the L1 still holds 'flag1' (specific-key invalidation only purges
// the exact key, not by prefix). This documents current behaviour:
// we publish a sentinel and rely on subscribers to flush local L1
// entirely on receipt — see subscribeAndFlushOnInvalidate.
expect(tier.l1.get(buildCacheKey("flag1", { flagName: "flag1" }))).toEqual(result);
expect(await cache.get("flag1", { flagName: "flag1" })).toBeNull();
});
it("invalidates two replica caches without mixing tenant contexts", async () => {
const adapter = new MemoryAdapter();
const storeA = createSharedStore({ namespace: "ff-replicas", adapter });
const storeB = createSharedStore({ namespace: "ff-replicas", adapter });
const tierA = createTwoTierCache<EvaluateFlagResult>({
store: storeA,
namespace: "feature-flags",
ttlSeconds: 60,
});
const tierB = createTwoTierCache<EvaluateFlagResult>({
store: storeB,
namespace: "feature-flags",
ttlSeconds: 60,
});
const replicaA = createFlagEvalCache(tierA, storeA);
const replicaB = createFlagEvalCache(tierB, storeB);
const dispose = await tierB.subscribe((token) => replicaB.handleInvalidation(token));
const tenantA = { flagName: "billing.beta", tenantId: "tenant-a" };
const tenantB = { flagName: "billing.beta", tenantId: "tenant-b" };
await replicaA.set("billing.beta", tenantA, { enabled: true, reason: "matched" });
await replicaA.set("billing.beta", tenantB, { enabled: false, reason: "disabled" });
expect(await replicaB.get("billing.beta", tenantA)).toEqual({ enabled: true, reason: "matched" });
expect(await replicaB.get("billing.beta", tenantB)).toEqual({ enabled: false, reason: "disabled" });
await replicaA.invalidateFlag("billing.beta");
await Promise.resolve();
await Promise.resolve();
expect(await replicaB.get("billing.beta", tenantA)).toBeNull();
expect(await replicaB.get("billing.beta", tenantB)).toBeNull();
await replicaA.set("billing.beta", tenantA, { enabled: false, reason: "no-match" });
expect(await replicaB.get("billing.beta", tenantA)).toEqual({ enabled: false, reason: "no-match" });
await dispose();
await storeA.close();
});
it("self-heals from a missed pub/sub event after the generation TTL", async () => {
let now = 0;
const adapter = new MemoryAdapter({ now: () => now });
const storeA = createSharedStore({ namespace: "ff-missed-event", adapter });
const storeB = createSharedStore({ namespace: "ff-missed-event", adapter });
const tierA = createTwoTierCache<EvaluateFlagResult>({
store: storeA,
namespace: "feature-flags",
ttlSeconds: 60,
l1Now: () => now,
pubsubEnabled: false,
});
const tierB = createTwoTierCache<EvaluateFlagResult>({
store: storeB,
namespace: "feature-flags",
ttlSeconds: 60,
l1Now: () => now,
pubsubEnabled: false,
});
const replicaA = createFlagEvalCache(tierA, storeA, { generationTtlMs: 10, now: () => now });
const replicaB = createFlagEvalCache(tierB, storeB, { generationTtlMs: 10, now: () => now });
const context = { flagName: "billing.beta", tenantId: "tenant-a" };
await replicaA.set("billing.beta", context, { enabled: true, reason: "matched" });
expect(await replicaB.get("billing.beta", context)).toEqual({ enabled: true, reason: "matched" });
await replicaA.invalidateFlag("billing.beta");
expect(await replicaB.get("billing.beta", context)).toEqual({ enabled: true, reason: "matched" });
now = 11;
expect(await replicaB.get("billing.beta", context)).toBeNull();
await storeA.close();
});
});
@@ -1,29 +1,35 @@
/**
* Eval-cache for the feature-flags engine.
* Generation-aware evaluation cache for the feature-flags engine.
*
* Wraps the shared-store two-tier cache (#39) with a key-shape and
* invalidation surface specific to flag evaluation. Cache-key is
* `<flagName>:<hash(ctx)>` so different evaluation contexts (tenant,
* user, plan) get distinct entries.
*
* Invalidation: when a flag mutates (admin save) the API calls
* `invalidateFlag(flagName)`. The two-tier cache publishes on the
* pub/sub channel — every replica drops its L1 entries for the flag.
*
* Note: the two-tier cache deletes ONE key per invalidate-call. Because
* a single flag can have many context-hashed entries we publish a
* wildcard `<flagName>:*` token and listen for it on the subscriber.
* Receiving replicas wipe their L1 entirely (cheap — L1 is a small Map),
* which is correct because flag mutations are rare (~ minutes).
* L1/L2 values are immutable per generation. Mutations increment a durable
* SharedStore generation before publishing, so a replica that misses pub/sub
* cannot make an old L2 value current again. Pub/sub remains the fast path;
* the short generation-cache TTL is the self-healing path.
*/
import type { TwoTierCache } from "@hivegrid/shared-store";
import type { SharedStore, TwoTierCache } from "@hivegrid/shared-store";
import { createHash } from "node:crypto";
import type { EvaluateFlagResult } from "./evaluate.js";
import type { EvaluationContext } from "./targeting/types.js";
export const FEATURE_FLAGS_INVALIDATION_CHANNEL = "feature-flags:invalidate";
interface CacheGeneration {
global: number;
flag: number;
}
interface CachedGeneration extends CacheGeneration {
expiresAt: number;
}
export interface FlagEvalCacheOptions {
/** Maximum staleness after a missed pub/sub event. Defaults to 1 second. */
generationTtlMs?: number;
/** Deterministic clock seam. */
now?: () => number;
}
/** Stable hash over the subset of ctx fields that influence eval. */
export function hashContext(ctx: EvaluationContext): string {
const parts = [
@@ -36,46 +42,91 @@ export function hashContext(ctx: EvaluationContext): string {
return createHash("sha1").update(parts.join("|")).digest("hex").slice(0, 16);
}
export function buildCacheKey(flagName: string, ctx: EvaluationContext): string {
return `ff:${flagName}:${hashContext(ctx)}`;
export function buildCacheKey(
flagName: string,
ctx: EvaluationContext,
generation: CacheGeneration = { global: 0, flag: 0 },
): string {
return `ff:${flagName}:g${generation.global}.${generation.flag}:${hashContext(ctx)}`;
}
export interface FlagEvalCache {
get(flagName: string, ctx: EvaluationContext): Promise<EvaluateFlagResult | null>;
set(flagName: string, ctx: EvaluationContext, result: EvaluateFlagResult): Promise<void>;
/**
* Drop every cached evaluation for `flagName` across replicas.
* Publishes a wildcard token on the invalidation channel.
*/
/** Increment this flag's durable generation, then notify replicas. */
invalidateFlag(flagName: string): Promise<void>;
/** Drop everything (e.g. admin "rebuild cache" button). */
/** Increment the durable global generation, then notify replicas. */
invalidateAll(): Promise<void>;
/** Apply a pub/sub notification received by this process. */
handleInvalidation(token: string): void;
}
/**
* Build a flag-eval cache on top of an existing TwoTierCache. The
* cache must be configured with `namespace: "feature-flags"` so its
* pub/sub channel matches what the publishers send.
*/
export function createFlagEvalCache(
store: TwoTierCache<EvaluateFlagResult>,
tier: TwoTierCache<EvaluateFlagResult>,
backingStore: SharedStore,
options: FlagEvalCacheOptions = {},
): FlagEvalCache {
const generationTtlMs = options.generationTtlMs ?? 1_000;
if (!Number.isFinite(generationTtlMs) || generationTtlMs < 0) {
throw new Error("createFlagEvalCache: generationTtlMs must be >= 0");
}
const clock = options.now ?? (() => Date.now());
const generations = new Map<string, CachedGeneration>();
const resolveGeneration = async (flagName: string): Promise<CacheGeneration> => {
const cached = generations.get(flagName);
const now = clock();
if (cached && cached.expiresAt > now) return cached;
const [globalRaw, flagRaw] = await backingStore.mget([GLOBAL_GENERATION_KEY, flagGenerationKey(flagName)]);
const generation = {
global: parseGeneration(globalRaw),
flag: parseGeneration(flagRaw),
expiresAt: now + generationTtlMs,
};
generations.set(flagName, generation);
return generation;
};
const handleInvalidation = (): void => {
generations.clear();
tier.flushLocal();
};
return {
async get(flagName, ctx) {
return store.get(buildCacheKey(flagName, ctx));
return tier.get(buildCacheKey(flagName, ctx, await resolveGeneration(flagName)));
},
async set(flagName, ctx, result) {
await store.set(buildCacheKey(flagName, ctx), result);
const generation = await resolveGeneration(flagName);
await tier.set(buildCacheKey(flagName, ctx, generation), result);
},
async invalidateFlag(flagName) {
// The wildcard sentinel makes subscribers flush their L1 entirely,
// which is correct because we don't index L1 entries by flag-name
// prefix. Publish via the underlying two-tier cache's invalidate
// wildcard so peer L1s flush.
await store.invalidate(`ff-flag:${flagName}`);
const next = await backingStore.incr(flagGenerationKey(flagName));
handleInvalidation();
await tier.invalidate(`ff-gen:${encodeFlagName(flagName)}:${next}`);
},
async invalidateAll() {
await store.invalidate("*");
const next = await backingStore.incr(GLOBAL_GENERATION_KEY);
handleInvalidation();
await tier.invalidate(`ff-global:${next}`);
},
handleInvalidation,
};
}
const GLOBAL_GENERATION_KEY = "cache:feature-flags:generation:global";
function flagGenerationKey(flagName: string): string {
const digest = createHash("sha256").update(flagName).digest("hex");
return `cache:feature-flags:generation:flag:${digest}`;
}
function parseGeneration(raw: string | null): number {
if (raw === null) return 0;
const parsed = Number.parseInt(raw, 10);
return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : 0;
}
function encodeFlagName(flagName: string): string {
return Buffer.from(flagName, "utf8").toString("base64url");
}
@@ -17,7 +17,7 @@
* new flag is referenced.
*/
import { createContext, useContext, useMemo, type ReactNode } from "react";
import { createContext, useContext, useMemo, type ReactElement, type ReactNode } from "react";
import type { EvaluateFlagResult } from "../evaluate.js";
export type FeatureFlagsHydration = Readonly<Record<string, EvaluateFlagResult>>;
@@ -39,7 +39,7 @@ export interface FeatureFlagProviderProps {
}
/** Wraps the React tree and exposes the hydrated flag map to {@link useFeatureFlag}. */
export function FeatureFlagProvider(props: FeatureFlagProviderProps): JSX.Element {
export function FeatureFlagProvider(props: FeatureFlagProviderProps): ReactElement {
const value = useMemo<FeatureFlagContextValue>(() => ({ flags: props.flags }), [props.flags]);
return <Context.Provider value={value}>{props.children}</Context.Provider>;
}
@@ -21,3 +21,15 @@ export {
publishFeatureFlagInvalidationViaStore,
type PublishFeatureFlagInvalidationOptions,
} from "./publisher.js";
export {
buildFeatureFlagRolloutPreview,
evaluateFeatureFlagRollout,
matchesFeatureFlagCriteria,
type FeatureFlagRolloutCriteria,
type FeatureFlagRolloutDecision,
type FeatureFlagRolloutFilter,
type FeatureFlagRolloutOverride,
type FeatureFlagRolloutPreview,
type FeatureFlagRolloutTenant,
type FeatureFlagTenantSize,
} from "./rollout.js";
@@ -20,6 +20,8 @@ describe("root barrel (@hivegrid/feature-flags)", () => {
expect(typeof root.hashContext).toBe("function");
expect(typeof root.publishFeatureFlagInvalidationOnce).toBe("function");
expect(typeof root.publishFeatureFlagInvalidationViaStore).toBe("function");
expect(typeof root.evaluateFeatureFlagRollout).toBe("function");
expect(typeof root.buildFeatureFlagRolloutPreview).toBe("function");
});
it("exposes the invalidation channel constant", () => {
@@ -11,10 +11,11 @@ import { afterEach, describe, expect, it, vi } from "vitest";
const closeMock = vi.hoisted(() => vi.fn());
const invalidateMock = vi.hoisted(() => vi.fn());
const incrMock = vi.hoisted(() => vi.fn().mockResolvedValue(1));
vi.mock("@hivegrid/shared-store", () => ({
createSharedStore: vi.fn(() => ({ close: closeMock })),
createTwoTierCache: vi.fn(() => ({ invalidate: invalidateMock })),
createSharedStore: vi.fn(() => ({ close: closeMock, incr: incrMock })),
createTwoTierCache: vi.fn(() => ({ invalidate: invalidateMock, flushLocal: vi.fn() })),
}));
import { publishFeatureFlagInvalidationOnce } from "./publisher.js";
@@ -22,7 +22,7 @@ describe("publishFeatureFlagInvalidationViaStore", () => {
await new Promise((resolve) => setImmediate(resolve));
expect(received.length).toBeGreaterThanOrEqual(1);
expect(received.some((msg) => msg.includes("billing.beta"))).toBe(true);
expect(received.some((msg) => msg.startsWith("ff-gen:"))).toBe(true);
await unsubscribe();
await store.close();
@@ -76,7 +76,7 @@ export async function publishFeatureFlagInvalidationViaStore(
ttlSeconds,
pubsubEnabled: true,
});
const cache = createFlagEvalCache(tier);
const cache = createFlagEvalCache(tier, store);
await cache.invalidateFlag(flagName);
}
@@ -0,0 +1,121 @@
import { describe, expect, it } from "vitest";
import {
buildFeatureFlagRolloutPreview,
evaluateFeatureFlagRollout,
matchesFeatureFlagCriteria,
type FeatureFlagRolloutFilter,
type FeatureFlagRolloutTenant,
} from "./rollout.js";
const tenant: FeatureFlagRolloutTenant = {
id: "tenant-a",
createdAt: "2026-01-15T00:00:00.000Z",
size: "51-100",
industry: "shk",
status: "active",
subscriptionProductIds: ["pro"],
};
const filters: FeatureFlagRolloutFilter[] = [
{
id: "newer",
name: "Newer",
priority: 10,
value: false,
active: true,
createdAt: "2026-01-02T00:00:00.000Z",
criteria: { tenantIndustry: "shk" },
},
{
id: "older",
name: "Older",
priority: 10,
value: true,
active: true,
createdAt: "2026-01-01T00:00:00.000Z",
criteria: { tenantIndustry: "shk" },
},
];
describe("feature flag rollout evaluation", () => {
it("applies Override > highest-priority oldest Filter > Default deterministically", () => {
expect(evaluateFeatureFlagRollout({ tenant, defaultValue: false, filters })).toEqual({
value: true,
source: "filter",
filterId: "older",
});
expect(
evaluateFeatureFlagRollout({
tenant,
defaultValue: false,
filters,
override: { tenantId: tenant.id, value: false },
})
).toEqual({ value: false, source: "override", filterId: null });
expect(
evaluateFeatureFlagRollout({
tenant: { ...tenant, industry: "software" },
defaultValue: true,
filters,
})
).toEqual({ value: true, source: "default", filterId: null });
});
it("ignores expired overrides before choosing the matching filter", () => {
expect(
evaluateFeatureFlagRollout({
tenant,
defaultValue: false,
filters,
override: { tenantId: tenant.id, value: false, expiresAt: "2026-01-31T00:00:00.000Z" },
now: new Date("2026-02-01T00:00:00.000Z"),
})
).toMatchObject({ source: "filter", value: true });
});
it("matches every configured criterion with AND semantics", () => {
expect(
matchesFeatureFlagCriteria(tenant, {
tenantSize: "51-100",
tenantIndustry: "shk",
tenantStatus: "active",
subscriptionProductId: "pro",
tenantCreatedAfter: "2026-01-01T00:00:00.000Z",
tenantCreatedBefore: "2026-02-01T00:00:00.000Z",
tenantIdIn: ["tenant-a"],
tenantIdNotIn: ["tenant-b"],
})
).toBe(true);
expect(matchesFeatureFlagCriteria(tenant, { tenantIdNotIn: ["tenant-a"] })).toBe(false);
});
it("builds stable effective-value statistics", () => {
const preview = buildFeatureFlagRolloutPreview({
tenants: [tenant, { ...tenant, id: "tenant-b", industry: "software" }],
defaultValue: false,
filters,
overrides: [{ tenantId: "tenant-b", value: true }],
now: new Date("2026-02-01T00:00:00.000Z"),
});
expect(preview).toMatchObject({
enabled: 2,
disabled: 0,
overrides: 1,
filtered: 1,
defaulted: 0,
});
expect(preview.rows.map((row) => row.tenantId)).toEqual(["tenant-a", "tenant-b"]);
});
it("fails closed on invalid persisted timestamps", () => {
expect(() =>
evaluateFeatureFlagRollout({
tenant,
defaultValue: false,
filters,
override: { tenantId: tenant.id, value: true, expiresAt: "not-a-date" },
})
).toThrow(/valid ISO timestamp/u);
});
});
@@ -0,0 +1,146 @@
export type FeatureFlagTenantSize = "1-10" | "11-25" | "26-50" | "51-100" | "100+";
export type FeatureFlagRolloutTenant = {
readonly id: string;
readonly createdAt: string;
readonly size?: FeatureFlagTenantSize | null;
readonly industry?: string | null;
readonly status?: string | null;
readonly subscriptionProductIds?: readonly string[];
};
export type FeatureFlagRolloutCriteria = {
readonly tenantSize?: FeatureFlagTenantSize;
readonly tenantIndustry?: string;
readonly tenantStatus?: string;
readonly subscriptionProductId?: string;
readonly tenantCreatedAfter?: string;
readonly tenantCreatedBefore?: string;
readonly tenantIdIn?: readonly string[];
readonly tenantIdNotIn?: readonly string[];
};
export type FeatureFlagRolloutFilter = {
readonly id: string;
readonly name: string;
readonly priority: number;
readonly value: boolean;
readonly active: boolean;
readonly createdAt: string;
readonly criteria: FeatureFlagRolloutCriteria;
};
export type FeatureFlagRolloutOverride = {
readonly tenantId: string;
readonly value: boolean;
readonly expiresAt?: string | null;
};
export type FeatureFlagRolloutDecision = {
readonly value: boolean;
readonly source: "override" | "filter" | "default";
readonly filterId: string | null;
};
export type FeatureFlagRolloutPreview = {
readonly enabled: number;
readonly disabled: number;
readonly overrides: number;
readonly filtered: number;
readonly defaulted: number;
readonly rows: readonly {
readonly tenantId: string;
readonly decision: FeatureFlagRolloutDecision;
}[];
};
export function evaluateFeatureFlagRollout(input: {
readonly tenant: FeatureFlagRolloutTenant;
readonly defaultValue: boolean;
readonly filters: readonly FeatureFlagRolloutFilter[];
readonly override?: FeatureFlagRolloutOverride | null;
readonly now?: Date;
}): FeatureFlagRolloutDecision {
const now = input.now ?? new Date();
if (input.override && !isExpired(input.override.expiresAt, now)) {
return { value: input.override.value, source: "override", filterId: null };
}
const matchingFilter = [...input.filters]
.filter((filter) => filter.active && matchesFeatureFlagCriteria(input.tenant, filter.criteria))
.sort(compareFilters)[0];
if (matchingFilter) {
return { value: matchingFilter.value, source: "filter", filterId: matchingFilter.id };
}
return { value: input.defaultValue, source: "default", filterId: null };
}
export function buildFeatureFlagRolloutPreview(input: {
readonly tenants: readonly FeatureFlagRolloutTenant[];
readonly defaultValue: boolean;
readonly filters: readonly FeatureFlagRolloutFilter[];
readonly overrides: readonly FeatureFlagRolloutOverride[];
readonly now?: Date;
}): FeatureFlagRolloutPreview {
const now = input.now ?? new Date();
const overrideByTenant = new Map(input.overrides.map((override) => [override.tenantId, override]));
const rows = [...input.tenants]
.sort((left, right) => left.id.localeCompare(right.id))
.map((tenant) => ({
tenantId: tenant.id,
decision: evaluateFeatureFlagRollout({
tenant,
defaultValue: input.defaultValue,
filters: input.filters,
override: overrideByTenant.get(tenant.id),
now,
}),
}));
return {
enabled: rows.filter((row) => row.decision.value).length,
disabled: rows.filter((row) => !row.decision.value).length,
overrides: rows.filter((row) => row.decision.source === "override").length,
filtered: rows.filter((row) => row.decision.source === "filter").length,
defaulted: rows.filter((row) => row.decision.source === "default").length,
rows,
};
}
export function matchesFeatureFlagCriteria(tenant: FeatureFlagRolloutTenant, criteria: FeatureFlagRolloutCriteria): boolean {
if (criteria.tenantSize !== undefined && tenant.size !== criteria.tenantSize) return false;
if (criteria.tenantIndustry !== undefined && tenant.industry !== criteria.tenantIndustry) return false;
if (criteria.tenantStatus !== undefined && tenant.status !== criteria.tenantStatus) return false;
if (
criteria.subscriptionProductId !== undefined &&
!(tenant.subscriptionProductIds ?? []).includes(criteria.subscriptionProductId)
) {
return false;
}
if (criteria.tenantCreatedAfter !== undefined && compareIso(tenant.createdAt, criteria.tenantCreatedAfter) <= 0) return false;
if (criteria.tenantCreatedBefore !== undefined && compareIso(tenant.createdAt, criteria.tenantCreatedBefore) >= 0) return false;
if (criteria.tenantIdIn !== undefined && !criteria.tenantIdIn.includes(tenant.id)) return false;
if (criteria.tenantIdNotIn !== undefined && criteria.tenantIdNotIn.includes(tenant.id)) return false;
return true;
}
function compareFilters(left: FeatureFlagRolloutFilter, right: FeatureFlagRolloutFilter): number {
return right.priority - left.priority || compareIso(left.createdAt, right.createdAt) || left.id.localeCompare(right.id);
}
function compareIso(left: string, right: string): number {
const leftTime = Date.parse(left);
const rightTime = Date.parse(right);
if (!Number.isFinite(leftTime) || !Number.isFinite(rightTime)) {
throw new Error("Feature flag rollout dates must be valid ISO timestamps");
}
return leftTime - rightTime;
}
function isExpired(expiresAt: string | null | undefined, now: Date): boolean {
if (!expiresAt) return false;
const timestamp = Date.parse(expiresAt);
if (!Number.isFinite(timestamp)) throw new Error("Feature flag override expiry must be a valid ISO timestamp");
return timestamp <= now.getTime();
}