feat: Unleash feature flags via src/lib/flags.ts, hello-banner on GET /
Some checks failed
/ checks (push) Successful in 37s
/ deploy (push) Has been cancelled

Ported from service-template-express 9b63993.
This commit is contained in:
nholtware 2026-11-05 11:07:38 -06:00
parent 28ec495a98
commit ec4b769be2
12 changed files with 675 additions and 17 deletions

View file

@ -1,15 +1,24 @@
import { z } from "zod";
const schema = z.object({
PORT: z.coerce.number().int().positive().default(3000),
SERVICE_NAME: z.string().min(1, "SERVICE_NAME is required"),
LOG_LEVEL: z
.enum(["fatal", "error", "warn", "info", "debug", "trace", "silent"])
.default("info"),
GIT_SHA: z.string().default("dev"),
DATABASE_URL: z.string().url().optional(),
REDIS_URL: z.string().url().optional(),
});
const schema = z
.object({
PORT: z.coerce.number().int().positive().default(3000),
SERVICE_NAME: z.string().min(1, "SERVICE_NAME is required"),
LOG_LEVEL: z
.enum(["fatal", "error", "warn", "info", "debug", "trace", "silent"])
.default("info"),
GIT_SHA: z.string().default("dev"),
DATABASE_URL: z.string().url().optional(),
REDIS_URL: z.string().url().optional(),
// Feature flags (Unleash). Unset UNLEASH_URL = every flag reads false.
UNLEASH_URL: z.string().url().optional(),
UNLEASH_API_TOKEN: z.string().min(1).optional(),
UNLEASH_REFRESH_MS: z.coerce.number().int().positive().default(5000),
})
.refine((c) => !c.UNLEASH_URL || c.UNLEASH_API_TOKEN, {
message: "UNLEASH_API_TOKEN is required when UNLEASH_URL is set",
path: ["UNLEASH_API_TOKEN"],
});
export type Config = z.infer<typeof schema>;

86
src/lib/flags.test.ts Normal file
View file

@ -0,0 +1,86 @@
import { EventEmitter } from "node:events";
import { beforeEach, describe, expect, it, vi } from "vitest";
import pino from "pino";
// Mock the Unleash SDK: no network, full control over flag state.
const sdk = vi.hoisted(() => ({
initialize: vi.fn(),
enabled: new Set<string>(),
}));
vi.mock("unleash-client", () => ({ initialize: sdk.initialize }));
import { createFlags } from "./flags.js";
function fakeUnleash() {
const emitter = new EventEmitter();
return Object.assign(emitter, {
isEnabled: vi.fn((name: string) => sdk.enabled.has(name)),
getVariant: vi.fn((name: string, _ctx: unknown, fallback: unknown) =>
sdk.enabled.has(name)
? { name: "blue", enabled: true, feature_enabled: true }
: fallback,
),
destroy: vi.fn(),
});
}
const base = {
SERVICE_NAME: "test-svc",
UNLEASH_REFRESH_MS: 5000,
} as const;
describe("createFlags", () => {
beforeEach(() => {
sdk.initialize.mockReset();
sdk.enabled.clear();
});
it("without UNLEASH_URL: all flags off, logs once, never touches the SDK", () => {
const lines: { msg: string }[] = [];
const logger = pino(
{},
{ write: (l: string) => lines.push(JSON.parse(l)) },
);
const flags = createFlags(base, logger);
expect(flags.isEnabled("hello-banner")).toBe(false);
expect(flags.isEnabled("hello-banner")).toBe(false);
expect(flags.getVariant("hello-banner").enabled).toBe(false);
expect(sdk.initialize).not.toHaveBeenCalled();
expect(lines.filter((l) => /flags disabled/.test(l.msg))).toHaveLength(1);
});
it("with UNLEASH_URL: initializes the SDK and delegates", async () => {
const unleash = fakeUnleash();
sdk.initialize.mockReturnValue(unleash);
const flags = createFlags(
{
...base,
UNLEASH_URL: "http://unleash.test/api",
UNLEASH_API_TOKEN: "*:development.abc",
},
pino({ level: "silent" }),
);
expect(sdk.initialize).toHaveBeenCalledWith({
url: "http://unleash.test/api",
appName: "test-svc",
customHeaders: { Authorization: "*:development.abc" },
refreshInterval: 5000,
});
expect(flags.isEnabled("hello-banner")).toBe(false);
sdk.enabled.add("hello-banner");
expect(flags.isEnabled("hello-banner", { userId: "u1" })).toBe(true);
expect(unleash.isEnabled).toHaveBeenLastCalledWith(
"hello-banner",
{ userId: "u1" },
false,
);
expect(flags.getVariant("hello-banner").name).toBe("blue");
// SDK errors are logged, not thrown (no unhandled 'error' event).
expect(() => unleash.emit("error", new Error("down"))).not.toThrow();
await flags.close();
expect(unleash.destroy).toHaveBeenCalled();
});
});

64
src/lib/flags.ts Normal file
View file

@ -0,0 +1,64 @@
import { initialize, type Context, type Variant } from "unleash-client";
import type { Logger } from "pino";
import type { Config } from "./config.js";
export type { Context as FlagContext, Variant as FlagVariant };
/**
* Thin wrapper over the Unleash Node SDK. Routes depend on this interface,
* not on unleash-client, so tests can pass a fake and the SDK can be swapped.
*/
export interface Flags {
isEnabled(name: string, context?: Context): boolean;
getVariant(name: string, context?: Context): Variant;
close(): Promise<void>;
}
const DISABLED: Variant = { name: "disabled", enabled: false };
/** Every flag off. Used when UNLEASH_URL is unset (local dev, tests). */
export function disabledFlags(): Flags {
return {
isEnabled: () => false,
getVariant: () => ({ ...DISABLED, feature_enabled: false }),
close: async () => {},
};
}
export function createFlags(
config: Pick<
Config,
"SERVICE_NAME" | "UNLEASH_URL" | "UNLEASH_API_TOKEN" | "UNLEASH_REFRESH_MS"
>,
logger: Logger,
): Flags {
if (!config.UNLEASH_URL) {
logger.info("feature flags disabled: UNLEASH_URL unset, all flags off");
return disabledFlags();
}
const unleash = initialize({
url: config.UNLEASH_URL,
appName: config.SERVICE_NAME,
customHeaders: { Authorization: config.UNLEASH_API_TOKEN ?? "" },
refreshInterval: config.UNLEASH_REFRESH_MS,
});
// An EventEmitter 'error' with no listener would crash the process.
// Unleash being down must never take the service down: flags read false
// (or their last fetched value) until it comes back.
unleash.on("error", (err: Error) =>
logger.warn({ err }, "unleash client error"),
);
unleash.on("warn", (msg: string) => logger.warn({ msg }, "unleash warning"));
unleash.once("synchronized", () =>
logger.info({ url: config.UNLEASH_URL }, "feature flags synchronized"),
);
return {
isEnabled: (name, context) => unleash.isEnabled(name, context, false),
getVariant: (name, context) => unleash.getVariant(name, context, DISABLED),
async close() {
unleash.destroy();
},
};
}