caelum0x f4486bda26 feat(flags): targeting by property, cohort or segment and % rollouts on a stable hash (QY1.3, I10, A19)
- packages/openfeature-railyard/src/targeting.mjs: one dependency-free
  evaluator (sync SHA-1, rollout hash = parseInt(sha1("<flag>.<id>")[0:15])
  / 0xfffffffffffffff, inside when <= rollout/100; ordered rules, all
  conditions of a rule must match, first match wins with its own value).
  Property operators follow the reference matcher of posthog-node (MIT):
  exact/is_not (lists, true/false by truthiness), icontains, regex, gt/gte/
  lt/lte (numeric, else text), is_set/is_not_set. Segments are named sets of
  property conditions per environment (Flagsmith segment shape, BSD-3);
  cohorts are product analytics cohort ids. Byte copies with .d.mts types in
  apps/console/lib/flags and apps/product-analytics/src/flags (drift test).
- Console: rules and segments live in Railyard's store for both backends
  (migration 0009: railyard.flag_targeting, railyard.flag_segments, bounded
  checks, cascade, RLS, no anon), so the table fallback and the Flagsmith
  backend have the same rule features. setFlag validates rules and segment
  references; a used segment cannot be removed; branches copy rules and
  segments. The read endpoint takes ?id, ?props (JSON, 2 KB) and ?cohorts,
  answers each flag for that person and ships {on, value, rules} plus the
  segments used, so SDKs evaluate locally; without a person a targeted flag
  reads off (old clients stay safe). Flags screen: rules per flag (everyone,
  a property, a segment; cohorts only with RAILYARD_REPLAY_LIVE) with a
  share, and segments. POST /api/flags/segments.
- Product analytics /flags: evaluates targeted flags with the person's
  stored properties (request person_properties override) and cohort
  membership (through person overrides).
- OpenFeature providers and the client: evaluation context targetingKey +
  attributes (+ cohorts) resolve per person; cached starts keep rules.
- Contract fixture: flags items carry targeting (additive, version 2).

Tests
- openfeature 16/16: SHA-1 vs node crypto, rollout shares within bounds
  over 10 000 ids and monotonic growth, operators, rules, validation, read
  answer, client and both providers vs the evaluator, cached start, drift.
- console 142/142 incl. both backends with the same 20 rule sets, segments,
  isolation, read-endpoint context, 0009 migration on a scratch PG, and
  10 000 ids x 20 rule sets: provider local == read endpoint (0 mismatches).
- product analytics test/qy 10/10 incl. 10 000 ids x 20 rule sets: provider
  local == /flags from stored people and cohorts (0 mismatches), and the
  unmodified posthog-node local evaluation agreeing on all 18 non-cohort
  sets for 10 000 ids (0 mismatches, 0 undecided); a3 experiments unchanged.
- contract 6/6; console and PA tsc clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:09:54 +03:00

218 lines
10 KiB
TypeScript

// Railyard Flags service (Wave P PY2.1): environments, flags and the public
// evaluation the SDK polls. Every write names its org; a client key reads one
// environment only (tenant isolation, PY2.1 acceptance 3).
//
// Targeting (Wave Q QY1.3): a flag may carry ordered rules (person property,
// cohort or segment conditions, each with a % rollout on a stable hash).
// Rules and segments live in Railyard's store for both backends; the read
// endpoint answers each flag for the caller's own context and ships the rules
// so the SDK can answer for any person locally with the same code
// (targeting.mjs, shared byte for byte with the SDK and product analytics).
import { randomToken } from "../crypto.ts";
import type { FlagsStore } from "./store.ts";
import { answerFlag, MAX_SEGMENTS, parseSegment, parseTargeting, referencedSegments, segmentRefs, type AnsweredFlag, type SegmentMap, type TargetingContext } from "./targeting.mjs";
import { FlagsBackendError } from "./flagsmith-backend.ts";
import {
CLIENT_KEY,
ENV_NAME,
FLAG_KEY,
MAX_DESCRIPTION,
MAX_FLAGS_PER_ENV,
MAX_VALUE,
type BackendName,
type Flag,
type FlagEnv,
type FlagInput,
type FlagsBackend,
type SegmentRow,
type Targeting,
} from "./types.ts";
export const MAX_ENVS_PER_ORG = 500;
/** How long an evaluation may be cached (the SDK polls every 30 s: a flip shows within 60 s). */
export const EVAL_MAX_AGE_SECONDS = 15;
export interface FlagsDeps {
store: FlagsStore;
/** The backend new environments use. */
backend: FlagsBackend;
/** Every backend this deployment can serve (an env keeps the backend it was made on). */
backends: Partial<Record<BackendName, FlagsBackend>>;
}
export class FlagsError extends Error {
readonly status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
const APP = /^[a-z0-9][a-z0-9-]{0,39}$/;
export function newClientKey(): string {
return `ry_flags_${randomToken(24)}`;
}
function backendFor(deps: FlagsDeps, env: FlagEnv): FlagsBackend {
const b = deps.backends[env.backend];
if (!b) throw new FlagsError(503, "Flags are being set up on this deployment. Nothing was changed.");
return b;
}
async function wrap<T>(work: () => Promise<T>): Promise<T> {
try {
return await work();
} catch (e) {
if (e instanceof FlagsBackendError) {
console.error(`flags backend: ${e.message}`);
throw new FlagsError(502, "The flags service did not answer. Nothing was changed; try again shortly.");
}
throw e;
}
}
/** Validates a flag write from any caller (console, bridge). */
export function parseFlagInput(raw: unknown): FlagInput | string {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return "the flag must be an object";
const b = raw as Record<string, unknown>;
if (typeof b.key !== "string" || !FLAG_KEY.test(b.key)) return "key must start with a letter and use lowercase letters, digits and underscores (64 at most)";
if (typeof b.enabled !== "boolean") return "enabled must be true or false";
const out: FlagInput = { key: b.key, enabled: b.enabled };
if (b.value !== undefined) {
if (b.value !== null && (typeof b.value !== "string" || b.value.length > MAX_VALUE)) return `value must be text of at most ${MAX_VALUE} characters, or null`;
out.value = b.value as string | null;
}
if (b.description !== undefined) {
if (b.description !== null && (typeof b.description !== "string" || b.description.length > MAX_DESCRIPTION)) return `description must be at most ${MAX_DESCRIPTION} characters`;
out.description = b.description as string | null;
}
if (b.targeting !== undefined) {
// Segment references are checked against the environment in setFlag.
const t = parseTargeting(b.targeting);
if (typeof t === "string") return t;
out.targeting = t;
}
return out;
}
/** The environment's row, created (and seeded from `copyFrom`) on first use. */
export async function ensureEnv(
deps: FlagsDeps,
input: { orgId: string; orgName: string; app: string; env: string; copyFrom?: string | null },
now: Date,
): Promise<{ env: FlagEnv; created: boolean }> {
if (!APP.test(input.app)) throw new FlagsError(400, "app must be a project name (lowercase letters, digits, dashes)");
if (!ENV_NAME.test(input.env)) throw new FlagsError(400, "env must be an environment or branch name");
const existing = await deps.store.findEnv(input.orgId, input.app, input.env);
if (existing) return { env: existing, created: false };
const siblings = await deps.store.listEnvs(input.orgId);
if (siblings.length >= MAX_ENVS_PER_ORG) throw new FlagsError(409, `An organization can have ${MAX_ENVS_PER_ORG} flag environments. Remove old branches first.`);
const refs = await wrap(() => deps.backend.prepare({ org_id: input.orgId, app: input.app, env: input.env }, input.orgName, siblings));
const parent = input.copyFrom && input.copyFrom !== input.env ? siblings.find((e) => e.app === input.app && e.env === input.copyFrom) ?? null : null;
const env = await deps.store.createEnv({
org_id: input.orgId,
app: input.app,
env: input.env,
client_key: newClientKey(),
backend: deps.backend.name,
...refs,
copied_from: parent?.id ?? null,
});
if (parent) {
// A branch starts with its parent's flags, rules and segments, then changes on its own.
for (const seg of await deps.store.listSegments(parent.id)) {
await deps.store.upsertSegment(env.id, { key: seg.key, name: seg.name, conditions: seg.conditions }, "branch-copy", now.toISOString());
}
const flags = await listFlags(deps, parent);
for (const f of flags) {
await wrap(() => backendFor(deps, env).set(env, { key: f.key, enabled: f.enabled, value: f.value, description: f.description }, "branch-copy", now));
if (f.targeting) await deps.store.setTargeting(env.id, f.key, f.targeting, "branch-copy", now.toISOString());
}
}
return { env, created: true };
}
/** The environment's flags, each with its rules (null for a plain flag). */
export async function listFlags(deps: FlagsDeps, env: FlagEnv): Promise<Flag[]> {
const [flags, rules] = await Promise.all([wrap(() => backendFor(deps, env).list(env)), deps.store.listTargeting(env.id)]);
return flags.map((f) => ({ ...f, targeting: rules[f.key] ?? null }));
}
export function listSegments(deps: FlagsDeps, env: FlagEnv): Promise<SegmentRow[]> {
return deps.store.listSegments(env.id);
}
/** Creates or changes one segment of one environment (a named set of property conditions). */
export async function setSegment(deps: FlagsDeps, env: FlagEnv, raw: unknown, actor: string, now: Date): Promise<SegmentRow> {
const seg = parseSegment(raw);
if (typeof seg === "string") throw new FlagsError(400, seg);
const existing = await deps.store.listSegments(env.id);
if (!existing.some((s) => s.key === seg.key) && existing.length >= MAX_SEGMENTS) throw new FlagsError(409, `An environment can have ${MAX_SEGMENTS} segments.`);
return deps.store.upsertSegment(env.id, seg, actor, now.toISOString());
}
/** Removes a segment no flag rule uses. */
export async function deleteSegment(deps: FlagsDeps, env: FlagEnv, key: string): Promise<boolean> {
const rules = await deps.store.listTargeting(env.id);
const users = Object.entries(rules).filter(([, t]) => segmentRefs(t).has(key)).map(([k]) => k);
if (users.length) throw new FlagsError(409, `The segment is used by ${users.join(", ")}. Change those rules first.`);
return deps.store.deleteSegment(env.id, key);
}
/** Creates or changes one flag of one environment. */
export async function setFlag(deps: FlagsDeps, env: FlagEnv, raw: unknown, actor: string, now: Date): Promise<Flag> {
const input = parseFlagInput(raw);
if (typeof input === "string") throw new FlagsError(400, input);
const backend = backendFor(deps, env);
const current = await wrap(() => backend.list(env));
if (!current.some((f) => f.key === input.key) && current.length >= MAX_FLAGS_PER_ENV) {
throw new FlagsError(409, `An environment can have ${MAX_FLAGS_PER_ENV} flags.`);
}
if (input.targeting) {
const known = new Set((await deps.store.listSegments(env.id)).map((s) => s.key));
const checked = parseTargeting(input.targeting, known);
if (typeof checked === "string") throw new FlagsError(400, checked);
}
const { targeting, ...plain } = input;
const saved = await wrap(() => backend.set(env, plain, actor, now));
if (targeting !== undefined) await deps.store.setTargeting(env.id, input.key, targeting, actor, now.toISOString());
const rules = targeting !== undefined ? targeting : ((await deps.store.listTargeting(env.id))[input.key] ?? null);
return { ...saved, targeting: rules };
}
export interface Evaluation {
env: string;
/** Each flag for the caller's context; targeted flags also carry their rules. */
flags: Record<string, AnsweredFlag>;
/** The segments the rules use (property conditions), for local evaluation. */
segments: SegmentMap;
fetched_at: string;
}
/**
* What an app reads with its public client key. `ctx` is the caller's own
* person (id, properties, cohorts), optional: without it a targeted flag
* answers as for an anonymous person. Records the environment's first read
* (the slot's proof).
*/
export async function evaluate(deps: FlagsDeps, clientKey: string | null, now: Date, ctx: TargetingContext = {}): Promise<Evaluation> {
if (!clientKey || !CLIENT_KEY.test(clientKey)) throw new FlagsError(401, "A valid flags key is required.");
const env = await deps.store.findEnvByClientKey(clientKey);
if (!env) throw new FlagsError(401, "A valid flags key is required.");
const [flags, segRows] = await Promise.all([listFlags(deps, env), deps.store.listSegments(env.id)]);
if (!env.first_read_at) await deps.store.markFirstRead(env.id, now.toISOString());
const all: SegmentMap = Object.fromEntries(segRows.map((s) => [s.key, { conditions: s.conditions }]));
const answered = Object.fromEntries(flags.map((f) => [f.key, answerFlag(f.key, { enabled: f.enabled, value: f.value, targeting: f.targeting ?? null }, ctx, all)]));
return { env: env.env, flags: answered, segments: referencedSegments(answered, all), fetched_at: now.toISOString() };
}
export type { Targeting };
/** The flags slot's proof: the first read of any environment's flags by an app. */
export async function firstRead(store: FlagsStore, orgId: string): Promise<{ kind: string; id: string; at: string } | null> {
const read = (await store.listEnvs(orgId)).filter((e) => e.first_read_at).sort((a, b) => (a.first_read_at! < b.first_read_at! ? -1 : 1))[0];
return read ? { kind: "first_flag_read", id: `${read.app}/${read.env}`, at: read.first_read_at! } : null;
}