Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -1,5 +1,5 @@
{
"name": "@toolctrl/feature-flags",
"name": "@hivegrid/feature-flags",
"version": "0.0.0",
"private": true,
"type": "module",
@@ -15,10 +15,10 @@
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"@toolctrl/shared-store": "workspace:*"
"@hivegrid/shared-store": "workspace:*"
},
"devDependencies": {
"@toolctrl/logger": "workspace:*",
"@hivegrid/logger": "workspace:*",
"@types/node": "^25.6.0",
"@types/react": "^18.3.27",
"@types/react-dom": "^18.3.7",
@@ -28,11 +28,11 @@
"vitest": "^3.2.4"
},
"peerDependencies": {
"@toolctrl/logger": "workspace:*",
"@hivegrid/logger": "workspace:*",
"react": "^18.3.1"
},
"peerDependenciesMeta": {
"@toolctrl/logger": {
"@hivegrid/logger": {
"optional": true
},
"react": {
@@ -1,5 +1,5 @@
import { describe, expect, it, beforeEach } from "vitest";
import { createSharedStore, createTwoTierCache } from "@toolctrl/shared-store";
import { createSharedStore, createTwoTierCache } from "@hivegrid/shared-store";
import { buildCacheKey, createFlagEvalCache, hashContext } from "./cache.js";
import type { EvaluateFlagResult } from "./evaluate.js";
@@ -17,7 +17,7 @@
* which is correct because flag mutations are rare (~ minutes).
*/
import type { TwoTierCache } from "@toolctrl/shared-store";
import type { TwoTierCache } from "@hivegrid/shared-store";
import { createHash } from "node:crypto";
import type { EvaluateFlagResult } from "./evaluate.js";
import type { EvaluationContext } from "./targeting/types.js";
@@ -0,0 +1,195 @@
/**
* Edge-path coverage for `evaluateFlag`:
* - variant selection fallbacks (even distribution, invalid weights,
* tenant/anonymous bucketing, malformed variant entries),
* - defensive `parseRule` handling of malformed stored rules,
* - parent time-window gating and explicit `maxDepth`.
*
* These assert the engine fails *closed* on dependency problems and
* fails *open* (flag stays on) when the stored rules JSON is junk —
* matching the documented contract in evaluate.ts.
*/
import { describe, expect, it } from "vitest";
import { evaluateFlag, getFeatureFlagVariant, type StoredFeatureFlag } from "./evaluate.js";
function mkFlag(overrides: Partial<StoredFeatureFlag> = {}): StoredFeatureFlag {
return {
id: overrides.id ?? "flag_1",
name: overrides.name ?? "test-flag",
enabled: overrides.enabled ?? true,
rules: overrides.rules ?? null,
variants: overrides.variants ?? [],
enabledFrom: overrides.enabledFrom ?? null,
enabledUntil: overrides.enabledUntil ?? null,
parentFlagId: overrides.parentFlagId ?? null,
};
}
function mkLoader(flags: StoredFeatureFlag[]) {
const byKey = new Map<string, StoredFeatureFlag>();
for (const f of flags) {
byKey.set(f.name, f);
byKey.set(f.id, f);
}
return async (key: string) => byKey.get(key) ?? null;
}
describe("evaluateFlag — variant weighting fallbacks", () => {
it("all-zero weights → even distribution, still sticky per user", async () => {
const variants = [
{ key: "A", weight: 0 },
{ key: "B", weight: 0 },
{ key: "C", weight: 0 },
];
const flag = mkFlag({ name: "even", variants });
const r1 = await evaluateFlag("even", { flagName: "even", userId: "u_77" }, { load: mkLoader([flag]) });
const r2 = await evaluateFlag("even", { flagName: "even", userId: "u_77" }, { load: mkLoader([flag]) });
expect(r1.variant?.key).toMatch(/^[ABC]$/);
expect(r1.variant?.key).toBe(r2.variant?.key);
});
it("negative weights are coerced to zero so that variant is never picked", async () => {
const variants = [
{ key: "loser", weight: -5 },
{ key: "winner", weight: 3 },
];
const flag = mkFlag({ name: "neg", variants });
// With one weight clamped to 0, the whole probability mass sits on
// "winner" — deterministically chosen regardless of bucket key.
for (const userId of ["a", "b", "c", "zzz", "user_999"]) {
const r = await evaluateFlag("neg", { flagName: "neg", userId }, { load: mkLoader([flag]) });
expect(r.variant?.key).toBe("winner");
}
});
it("non-finite weights (NaN / Infinity) are coerced to zero", async () => {
const variants = [
{ key: "nan", weight: Number.NaN },
{ key: "inf", weight: Number.POSITIVE_INFINITY },
{ key: "real", weight: 4 },
];
const flag = mkFlag({ name: "nonfinite", variants });
const r = await evaluateFlag("nonfinite", { flagName: "nonfinite", userId: "x" }, { load: mkLoader([flag]) });
expect(r.variant?.key).toBe("real");
});
it("buckets by tenantId when no userId is present", async () => {
const variants = [
{ key: "A", weight: 1 },
{ key: "B", weight: 1 },
];
const flag = mkFlag({ name: "tenant-bucket", variants });
const r1 = await evaluateFlag("tenant-bucket", { flagName: "tenant-bucket", tenantId: "t_5" }, { load: mkLoader([flag]) });
const r2 = await evaluateFlag("tenant-bucket", { flagName: "tenant-bucket", tenantId: "t_5" }, { load: mkLoader([flag]) });
expect(r1.variant?.key).toMatch(/^[AB]$/);
expect(r1.variant?.key).toBe(r2.variant?.key);
});
it("buckets by flag name for anonymous traffic (no userId, no tenantId)", async () => {
const variants = [
{ key: "A", weight: 1 },
{ key: "B", weight: 1 },
];
const flag = mkFlag({ name: "anon", variants });
const r1 = await evaluateFlag("anon", { flagName: "anon" }, { load: mkLoader([flag]) });
const r2 = await evaluateFlag("anon", { flagName: "anon" }, { load: mkLoader([flag]) });
expect(r1.variant?.key).toMatch(/^[AB]$/);
// Anonymous traffic must collapse to a single deterministic variant.
expect(r1.variant?.key).toBe(r2.variant?.key);
});
it("skips malformed variant entries; none valid → enabled with no variant", async () => {
const variants = [null, 42, "nope", { weight: 1 }, { value: "x" }];
const flag = mkFlag({ name: "junk-variants", variants });
const r = await evaluateFlag("junk-variants", { flagName: "junk-variants", userId: "u" }, { load: mkLoader([flag]) });
expect(r).toEqual({ enabled: true, reason: "matched" });
});
it("filters junk entries but keeps the single valid variant", async () => {
const variants = [null, { key: "only", value: { n: 1 } }, 99];
const flag = mkFlag({ name: "one-valid", variants });
const r = await evaluateFlag("one-valid", { flagName: "one-valid", userId: "u" }, { load: mkLoader([flag]) });
expect(r.variant?.key).toBe("only");
expect(r.variant?.value).toEqual({ n: 1 });
});
});
describe("evaluateFlag — malformed stored rules fail open", () => {
it("treats a non-object rules value as no-rules (flag stays on)", async () => {
const r = await evaluateFlag(
"f",
{ flagName: "f" },
{ load: mkLoader([mkFlag({ name: "f", rules: "garbage-string" })]) },
);
expect(r).toEqual({ enabled: true, reason: "matched" });
});
it("treats an object without a `type` field as no-rules", async () => {
const r = await evaluateFlag(
"f",
{ flagName: "f" },
{ load: mkLoader([mkFlag({ name: "f", rules: { foo: "bar" } })]) },
);
expect(r).toEqual({ enabled: true, reason: "matched" });
});
it("treats an explicit undefined rules value as no-rules", async () => {
const r = await evaluateFlag(
"f",
{ flagName: "f" },
{ load: mkLoader([mkFlag({ name: "f", rules: undefined })]) },
);
expect(r).toEqual({ enabled: true, reason: "matched" });
});
});
describe("evaluateFlag — parent time-window gating", () => {
it("parent enabledFrom in the future → child parent-disabled", async () => {
const parent = mkFlag({ id: "p", name: "p", enabledFrom: new Date("2030-01-01T00:00:00Z") });
const child = mkFlag({ id: "c", name: "c", parentFlagId: "p" });
const r = await evaluateFlag(
"c",
{ flagName: "c", now: new Date("2026-01-01T00:00:00Z") },
{ load: mkLoader([parent, child]) },
);
expect(r.reason).toBe("parent-disabled");
expect(r.enabled).toBe(false);
});
it("parent enabledUntil in the past → child parent-disabled", async () => {
const parent = mkFlag({ id: "p", name: "p", enabledUntil: new Date("2020-01-01T00:00:00Z") });
const child = mkFlag({ id: "c", name: "c", parentFlagId: "p" });
const r = await evaluateFlag(
"c",
{ flagName: "c", now: new Date("2026-01-01T00:00:00Z") },
{ load: mkLoader([parent, child]) },
);
expect(r.reason).toBe("parent-disabled");
});
});
describe("evaluateFlag — explicit maxDepth guard", () => {
it("a chain deeper than maxDepth fails closed as parent-disabled", async () => {
const a = mkFlag({ id: "a", name: "a", parentFlagId: "b" });
const b = mkFlag({ id: "b", name: "b", parentFlagId: "c" });
const c = mkFlag({ id: "c", name: "c" });
const r = await evaluateFlag(
"a",
{ flagName: "a" },
{ load: mkLoader([a, b, c]), maxDepth: 1 },
);
expect(r.reason).toBe("parent-disabled");
expect(r.enabled).toBe(false);
});
});
describe("getFeatureFlagVariant — no-variant matched flag", () => {
it("returns null when the flag is enabled but has no variants", async () => {
const v = await getFeatureFlagVariant(
"novar",
{ flagName: "novar", userId: "u" },
{ load: mkLoader([mkFlag({ name: "novar", variants: [] })]) },
);
expect(v).toBeNull();
});
});
@@ -4,7 +4,7 @@
* `evaluateFlag(name, ctx)` orchestrates:
*
* 1. Storage-load (delegated to a {@link FlagLoader} callback — keeps
* this package decoupled from `@toolctrl/db`).
* this package decoupled from `@hivegrid/db`).
* 2. Time-window check (`enabledFrom`/`enabledUntil`).
* 3. Dependency-resolution — parent flag must itself be enabled.
* 4. Targeting-rule evaluation via {@link evaluateRule}.
@@ -0,0 +1,51 @@
/**
* Public-API barrel contract.
*
* Asserts the documented exports are wired through the three entry
* points declared in package.json (`.`, `./targeting`, `./client`).
* Catches a broken re-export (typo / removed symbol) before it reaches
* a consumer, which a unit test on the underlying module would miss.
*/
import { describe, expect, it } from "vitest";
import * as root from "./index.js";
import * as targeting from "./targeting/index.js";
import * as client from "./client/index.js";
describe("root barrel (@hivegrid/feature-flags)", () => {
it("re-exports the evaluation + cache + publisher functions", () => {
expect(typeof root.evaluateFlag).toBe("function");
expect(typeof root.getFeatureFlagVariant).toBe("function");
expect(typeof root.createFlagEvalCache).toBe("function");
expect(typeof root.buildCacheKey).toBe("function");
expect(typeof root.hashContext).toBe("function");
expect(typeof root.publishFeatureFlagInvalidationOnce).toBe("function");
expect(typeof root.publishFeatureFlagInvalidationViaStore).toBe("function");
});
it("exposes the invalidation channel constant", () => {
expect(root.FEATURE_FLAGS_INVALIDATION_CHANNEL).toBe("feature-flags:invalidate");
});
it("transitively re-exports the targeting helpers via `export *`", () => {
expect(typeof root.evaluateRule).toBe("function");
expect(typeof root.computeBucket).toBe("function");
expect(typeof root.isInRolloutBucket).toBe("function");
});
});
describe("targeting barrel (@hivegrid/feature-flags/targeting)", () => {
it("exposes the evaluator and percentage helpers", () => {
expect(typeof targeting.evaluateRule).toBe("function");
expect(typeof targeting.computeBucket).toBe("function");
expect(typeof targeting.isInRolloutBucket).toBe("function");
});
});
describe("client barrel (@hivegrid/feature-flags/client)", () => {
it("exposes the provider and hooks", () => {
expect(typeof client.FeatureFlagProvider).toBe("function");
expect(typeof client.useFeatureFlag).toBe("function");
expect(typeof client.useFeatureFlagEnabled).toBe("function");
expect(typeof client.useFeatureFlagVariant).toBe("function");
});
});
@@ -0,0 +1,112 @@
/**
* Covers the one-shot publisher's close-error swallow path and the
* `CACHE_INVALIDATION_ENABLED=0` kill-switch alias.
*
* The whole `@hivegrid/shared-store` module is mocked here so we can
* force `SharedStore.close()` to reject — something the real in-memory
* adapter never does — and assert the helper logs-and-continues instead
* of letting the rejection escape the calling (often exiting) process.
*/
import { afterEach, describe, expect, it, vi } from "vitest";
const closeMock = vi.hoisted(() => vi.fn());
const invalidateMock = vi.hoisted(() => vi.fn());
vi.mock("@hivegrid/shared-store", () => ({
createSharedStore: vi.fn(() => ({ close: closeMock })),
createTwoTierCache: vi.fn(() => ({ invalidate: invalidateMock })),
}));
import { publishFeatureFlagInvalidationOnce } from "./publisher.js";
afterEach(() => {
vi.clearAllMocks();
delete process.env.CACHE_INVALIDATION_ENABLED;
});
describe("publishFeatureFlagInvalidationOnce — close error handling", () => {
it("logs a warning (with Error message) when store.close() rejects, without throwing", async () => {
delete process.env.CACHE_INVALIDATION_ENABLED;
closeMock.mockRejectedValueOnce(new Error("redis quit failed"));
const warn = vi.fn();
await expect(
publishFeatureFlagInvalidationOnce({
flagName: "billing.beta",
sharedStoreNamespace: "ns",
redisUrl: undefined,
logger: { warn },
}),
).resolves.toBeUndefined();
expect(closeMock).toHaveBeenCalledTimes(1);
expect(warn).toHaveBeenCalledTimes(1);
expect(warn).toHaveBeenCalledWith(
expect.objectContaining({ component: "feature-flags-publisher", err: "redis quit failed" }),
expect.stringContaining("close failed"),
);
});
it("stringifies a non-Error close rejection", async () => {
delete process.env.CACHE_INVALIDATION_ENABLED;
closeMock.mockRejectedValueOnce("socket hang up");
const warn = vi.fn();
await publishFeatureFlagInvalidationOnce({
flagName: "billing.beta",
sharedStoreNamespace: "ns",
redisUrl: undefined,
logger: { warn },
});
expect(warn).toHaveBeenCalledWith(
expect.objectContaining({ err: "socket hang up" }),
expect.any(String),
);
});
it("swallows the close error silently when no logger is supplied", async () => {
delete process.env.CACHE_INVALIDATION_ENABLED;
closeMock.mockRejectedValueOnce(new Error("boom"));
await expect(
publishFeatureFlagInvalidationOnce({
flagName: "billing.beta",
sharedStoreNamespace: "ns",
redisUrl: undefined,
}),
).resolves.toBeUndefined();
expect(closeMock).toHaveBeenCalledTimes(1);
});
it("does not warn when close() succeeds", async () => {
delete process.env.CACHE_INVALIDATION_ENABLED;
closeMock.mockResolvedValueOnce(undefined);
const warn = vi.fn();
await publishFeatureFlagInvalidationOnce({
flagName: "billing.beta",
sharedStoreNamespace: "ns",
redisUrl: undefined,
logger: { warn },
});
expect(closeMock).toHaveBeenCalledTimes(1);
expect(warn).not.toHaveBeenCalled();
});
it("treats CACHE_INVALIDATION_ENABLED=0 as kill-switch: never opens a store", async () => {
process.env.CACHE_INVALIDATION_ENABLED = "0";
await expect(
publishFeatureFlagInvalidationOnce({
flagName: "billing.beta",
sharedStoreNamespace: "ns",
redisUrl: undefined,
}),
).resolves.toBeUndefined();
// Early return before constructing the SharedStore → close untouched.
expect(closeMock).not.toHaveBeenCalled();
});
});
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createSharedStore } from "@toolctrl/shared-store";
import { createSharedStore } from "@hivegrid/shared-store";
import {
publishFeatureFlagInvalidationOnce,
publishFeatureFlagInvalidationViaStore,
@@ -2,7 +2,7 @@
* One-shot publisher for `feature-flags:invalidate` events.
*
* Phase 03 #39 wires the two-tier cache + per-replica subscriber in the
* web app, but the operator-side `toolctrl-cli feature-flags ...`
* web app, but the operator-side `hivegrid-cli feature-flags ...`
* commands (`enable`, `disable`, `set-rules`) mutate flags directly in
* the DB without going through the web action handler — so without this
* publisher web replicas keep serving the previous evaluation from L1
@@ -21,7 +21,7 @@
* should use `getFeatureFlagCache().invalidateFlag(flagName)` directly
* instead.
*/
import { createSharedStore, createTwoTierCache, type SharedStore } from "@toolctrl/shared-store";
import { createSharedStore, createTwoTierCache, type SharedStore } from "@hivegrid/shared-store";
import { createFlagEvalCache } from "./cache.js";
import type { EvaluateFlagResult } from "./evaluate.js";
@@ -0,0 +1,92 @@
/**
* Defensive-branch coverage for the pure rule evaluator.
*
* Covers the "fail-closed on unknown input" exhaustiveness defaults
* (a newer rule type / composite operator stored by a future version and
* read by older code must evaluate to `false`, never throw) plus the
* remaining missing-context and empty-list branches that the happy-path
* suite does not exercise.
*/
import { describe, expect, it } from "vitest";
import { evaluateRule } from "./evaluator.js";
import type { EvaluationContext, TargetingRule } from "./types.js";
const ctx: EvaluationContext = {
flagName: "test-flag",
tenantId: "tenant_a",
userId: "user_1",
email: "alice@example.com",
planTier: "pro",
roles: ["admin"],
};
describe("evaluateRule — unknown rule type", () => {
it("returns false for an unrecognised rule type instead of throwing", () => {
const rogue = { type: "quantum-rollout" } as unknown as TargetingRule;
expect(evaluateRule(rogue, ctx)).toBe(false);
});
});
describe("evaluateRule — unknown composite operator", () => {
it("returns false for an unrecognised composite operator", () => {
const rogue = {
type: "composite",
op: "XOR",
children: [{ type: "boolean", value: true }],
} as unknown as TargetingRule;
expect(evaluateRule(rogue, ctx)).toBe(false);
});
});
describe("evaluateRule — allowlist missing-context branches", () => {
it("returns false when userIds is set but ctx.userId is null", () => {
const rule: TargetingRule = { type: "allowlist", userIds: ["user_1"] };
expect(evaluateRule(rule, { ...ctx, userId: null })).toBe(false);
});
it("returns false when emails is set but ctx.email is null", () => {
const rule: TargetingRule = { type: "allowlist", emails: ["alice@example.com"] };
expect(evaluateRule(rule, { ...ctx, email: null })).toBe(false);
});
it("returns false when ctx.email is present but not on the list", () => {
const rule: TargetingRule = { type: "allowlist", emails: ["someone-else@example.com"] };
expect(evaluateRule(rule, ctx)).toBe(false);
});
it("returns false for an empty allowlist (no populated lists)", () => {
const rule: TargetingRule = { type: "allowlist" };
expect(evaluateRule(rule, ctx)).toBe(false);
});
});
describe("evaluateRule — empty target lists", () => {
it("plan-tier with empty plans never matches", () => {
const rule: TargetingRule = { type: "plan-tier", plans: [] };
expect(evaluateRule(rule, ctx)).toBe(false);
});
it("role-based with empty roles never matches", () => {
const rule: TargetingRule = { type: "role-based", roles: [] };
expect(evaluateRule(rule, ctx)).toBe(false);
});
});
describe("evaluateRule — time-based with malformed bounds", () => {
it("ignores an unparseable enabledFrom and still matches", () => {
const rule: TargetingRule = { type: "time-based", enabledFrom: "not-a-real-date" };
expect(evaluateRule(rule, { ...ctx, now: new Date("2026-06-01T00:00:00Z") })).toBe(true);
});
it("ignores an unparseable enabledUntil and still matches", () => {
const rule: TargetingRule = { type: "time-based", enabledUntil: "🙈" };
expect(evaluateRule(rule, { ...ctx, now: new Date("2026-06-01T00:00:00Z") })).toBe(true);
});
});
describe("evaluateRule — composite NOT with no children", () => {
it("returns false when a NOT node has no first child", () => {
const rule: TargetingRule = { type: "composite", op: "NOT", children: [] };
expect(evaluateRule(rule, ctx)).toBe(false);
});
});