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

189 lines
9.4 KiB
TypeScript

// Storage of flag environments (and, for the table backend, flag values).
// MemoryFlagsStore serves tests and local dev; PostgrestFlagsStore talks to
// the console's Scribase project (schema railyard, migration 0005).
import type { Flag, FlagEnv, FlagInput, Segment, SegmentRow, Targeting } from "./types.ts";
export interface FlagsStore {
findEnv(orgId: string, app: string, env: string): Promise<FlagEnv | null>;
findEnvByClientKey(clientKey: string): Promise<FlagEnv | null>;
listEnvs(orgId: string): Promise<FlagEnv[]>;
/** Inserts; returns the existing row when (org, app, env) is already there. */
createEnv(env: Omit<FlagEnv, "id" | "created_at" | "first_read_at">): Promise<FlagEnv>;
/** Sets first_read_at once; true when this call set it. */
markFirstRead(envId: string, at: string): Promise<boolean>;
// Table backend values.
listFlags(envId: string): Promise<Flag[]>;
upsertFlag(envId: string, input: FlagInput, actor: string, at: string): Promise<Flag>;
// Targeting (QY1.3), for every backend.
listTargeting(envId: string): Promise<Record<string, Targeting>>;
/** Null removes the rules (the flag is plain again). */
setTargeting(envId: string, key: string, targeting: Targeting | null, actor: string, at: string): Promise<void>;
listSegments(envId: string): Promise<SegmentRow[]>;
upsertSegment(envId: string, segment: Segment, actor: string, at: string): Promise<SegmentRow>;
deleteSegment(envId: string, key: string): Promise<boolean>;
}
const clone = <T>(v: T): T => structuredClone(v);
export class MemoryFlagsStore implements FlagsStore {
envs: FlagEnv[] = [];
values = new Map<string, Map<string, Flag>>();
targeting = new Map<string, Map<string, Targeting>>();
segments = new Map<string, Map<string, SegmentRow>>();
async findEnv(orgId: string, app: string, env: string) {
return clone(this.envs.find((e) => e.org_id === orgId && e.app === app && e.env === env) ?? null);
}
async findEnvByClientKey(clientKey: string) {
return clone(this.envs.find((e) => e.client_key === clientKey) ?? null);
}
async listEnvs(orgId: string) {
return clone(this.envs.filter((e) => e.org_id === orgId));
}
async createEnv(input: Omit<FlagEnv, "id" | "created_at" | "first_read_at">) {
const existing = await this.findEnv(input.org_id, input.app, input.env);
if (existing) return existing;
const row: FlagEnv = { ...clone(input), id: crypto.randomUUID(), created_at: new Date().toISOString(), first_read_at: null };
this.envs = [...this.envs, row];
return clone(row);
}
async markFirstRead(envId: string, at: string) {
const row = this.envs.find((e) => e.id === envId);
if (!row || row.first_read_at) return false;
this.envs = this.envs.map((e) => (e.id === envId ? { ...e, first_read_at: at } : e));
return true;
}
async listFlags(envId: string) {
return clone([...(this.values.get(envId)?.values() ?? [])].sort((a, b) => a.key.localeCompare(b.key)));
}
async upsertFlag(envId: string, input: FlagInput, _actor: string, at: string) {
const flags = new Map(this.values.get(envId) ?? []);
const prev = flags.get(input.key);
const row: Flag = {
key: input.key,
enabled: input.enabled,
value: input.value === undefined ? (prev?.value ?? null) : input.value,
description: input.description === undefined ? (prev?.description ?? null) : input.description,
updated_at: at,
};
flags.set(input.key, row);
this.values.set(envId, flags);
return clone(row);
}
async listTargeting(envId: string) {
return clone(Object.fromEntries(this.targeting.get(envId) ?? []));
}
async setTargeting(envId: string, key: string, targeting: Targeting | null) {
const rows = new Map(this.targeting.get(envId) ?? []);
if (targeting === null) rows.delete(key);
else rows.set(key, clone(targeting));
this.targeting.set(envId, rows);
}
async listSegments(envId: string) {
return clone([...(this.segments.get(envId)?.values() ?? [])].sort((a, b) => a.key.localeCompare(b.key)));
}
async upsertSegment(envId: string, segment: Segment, _actor: string, at: string) {
const rows = new Map(this.segments.get(envId) ?? []);
const row: SegmentRow = { ...clone(segment), updated_at: at };
rows.set(segment.key, row);
this.segments.set(envId, rows);
return clone(row);
}
async deleteSegment(envId: string, key: string) {
const rows = new Map(this.segments.get(envId) ?? []);
const had = rows.delete(key);
this.segments.set(envId, rows);
return had;
}
}
type Fetch = typeof fetch;
export class PostgrestFlagsStore implements FlagsStore {
base: string;
key: string;
fetchImpl: Fetch;
constructor(opts: { url: string; serviceRoleKey: string; fetchImpl?: Fetch }) {
this.base = `${opts.url.replace(/\/$/, "")}/rest/v1`;
this.key = opts.serviceRoleKey;
this.fetchImpl = opts.fetchImpl ?? fetch;
}
async req<T>(method: string, path: string, body?: unknown, prefer?: string): Promise<{ status: number; rows: T[] }> {
const headers: Record<string, string> = {
apikey: this.key,
authorization: `Bearer ${this.key}`,
"accept-profile": "railyard",
"content-profile": "railyard",
"content-type": "application/json",
};
if (prefer) headers.prefer = prefer;
const res = await this.fetchImpl(`${this.base}/${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
if (res.status === 409) return { status: 409, rows: [] };
if (!res.ok) throw new Error(`database ${method} ${path.split("?")[0]} failed with ${res.status}`);
const text = await res.text();
return { status: res.status, rows: text ? (JSON.parse(text) as T[]) : [] };
}
async findEnv(orgId: string, app: string, env: string) {
const q = `flag_envs?org_id=eq.${encodeURIComponent(orgId)}&app=eq.${encodeURIComponent(app)}&env=eq.${encodeURIComponent(env)}&limit=1`;
return (await this.req<FlagEnv>("GET", q)).rows[0] ?? null;
}
async findEnvByClientKey(clientKey: string) {
return (await this.req<FlagEnv>("GET", `flag_envs?client_key=eq.${encodeURIComponent(clientKey)}&limit=1`)).rows[0] ?? null;
}
async listEnvs(orgId: string) {
return (await this.req<FlagEnv>("GET", `flag_envs?org_id=eq.${encodeURIComponent(orgId)}&order=app.asc,env.asc`)).rows;
}
async createEnv(input: Omit<FlagEnv, "id" | "created_at" | "first_read_at">) {
const { rows } = await this.req<FlagEnv>("POST", "flag_envs?on_conflict=org_id,app,env", input, "resolution=ignore-duplicates,return=representation");
const row = rows[0] ?? (await this.findEnv(input.org_id, input.app, input.env));
if (!row) throw new Error("could not create the flag environment");
return row;
}
async markFirstRead(envId: string, at: string) {
const { rows } = await this.req<FlagEnv>("PATCH", `flag_envs?id=eq.${encodeURIComponent(envId)}&first_read_at=is.null`, { first_read_at: at }, "return=representation");
return rows.length > 0;
}
async listFlags(envId: string) {
return (await this.req<Flag>("GET", `flags?env_id=eq.${encodeURIComponent(envId)}&select=key,enabled,value,description,updated_at&order=key.asc`)).rows;
}
async upsertFlag(envId: string, input: FlagInput, actor: string, at: string) {
const row: Record<string, unknown> = { env_id: envId, key: input.key, enabled: input.enabled, updated_at: at, updated_by: actor };
if (input.value !== undefined) row.value = input.value;
if (input.description !== undefined) row.description = input.description;
const { rows } = await this.req<Flag>("POST", "flags?on_conflict=env_id,key&select=key,enabled,value,description,updated_at", row, "resolution=merge-duplicates,return=representation");
if (!rows[0]) throw new Error("could not save the flag");
return rows[0];
}
async listTargeting(envId: string) {
const { rows } = await this.req<{ key: string; targeting: Targeting }>("GET", `flag_targeting?env_id=eq.${encodeURIComponent(envId)}&select=key,targeting`);
return Object.fromEntries(rows.map((r) => [r.key, r.targeting]));
}
async setTargeting(envId: string, key: string, targeting: Targeting | null, actor: string, at: string) {
if (targeting === null) {
await this.req("DELETE", `flag_targeting?env_id=eq.${encodeURIComponent(envId)}&key=eq.${encodeURIComponent(key)}`);
return;
}
await this.req("POST", "flag_targeting?on_conflict=env_id,key", { env_id: envId, key, targeting, updated_at: at, updated_by: actor }, "resolution=merge-duplicates,return=minimal");
}
async listSegments(envId: string) {
return (await this.req<SegmentRow>("GET", `flag_segments?env_id=eq.${encodeURIComponent(envId)}&select=key,name,conditions,updated_at&order=key.asc`)).rows;
}
async upsertSegment(envId: string, segment: Segment, actor: string, at: string) {
const { rows } = await this.req<SegmentRow>(
"POST",
"flag_segments?on_conflict=env_id,key&select=key,name,conditions,updated_at",
{ env_id: envId, key: segment.key, name: segment.name, conditions: segment.conditions, updated_at: at, updated_by: actor },
"resolution=merge-duplicates,return=representation",
);
if (!rows[0]) throw new Error("could not save the segment");
return rows[0];
}
async deleteSegment(envId: string, key: string) {
const { rows } = await this.req<{ key: string }>("DELETE", `flag_segments?env_id=eq.${encodeURIComponent(envId)}&key=eq.${encodeURIComponent(key)}&select=key`, undefined, "return=representation");
return rows.length > 0;
}
}