@ogygia/flags
Decision sources
Let a vendor, a database or any function decide your flags with decide({ source }). The source runs once per request, before anything renders, over every flag the app declares, so every read after it stays synchronous.
Native flags decide from their own shape and need no setup. When the decisions should come from somewhere else, such as a flag vendor’s dashboard, your own database or a config service, you set a source with decide({ source }). It runs once at the start of each request and answers for every flag the app declares. From then on, a source-decided flag reads exactly like a native one: the same call, the same pick, the same exposures and the same federation carry.
import { decide } from '@ogygia/flags';
import * as ogygia from 'ogygia/server';
import { db } from '$lib/server/db';
import '$lib/flags';
decide({
source: async (queries) => {
const rows = await db.flagStates(
queries.map((q) => q.name)
);
return Object.fromEntries(
rows.map((r) => [r.name, r.variant])
);
}
});
export const handle = ogygia.handle();decide
decide(options) configures flags for the whole server. Call it from hooks.server.ts or any module the server loads at startup. With no decide() at all, flags are native, sticky and free.
| Option | Default | What it does |
|---|---|---|
source | none | Where decisions come from: a function, openfeature() or ofrep(). |
overrides | dev only | Whether ?og-exp is honored for a request. Yours replaces the default, in dev too (QA overrides). |
exposure | none | The sink that gets batches of exposure events (Exposures). |
batch | { max: 25, ms: 2000 } | When a batch is sent (Batching). |
You can call decide() more than once, from different modules, and each call changes only the options it names. So decide({ source }) in one file and decide({ exposure }) in another add up. Passing source: undefined or exposure: undefined removes that one. overrides changes only when you pass a function, so close it again with overrides: () => false. A batch you pass resets any field you leave out to its default.
import { decide } from '@ogygia/flags';
import { analytics } from '$lib/server/analytics';
// adds the sink; the source set in hooks.server.ts stays
decide({ exposure: (events) => analytics.track(events) });Source contract
A source is a function (queries, c) => record, and it may be async. queries lists every registered flag as a FlagQuery:
name: the flag’s name;variants: its declared variants, in order (['off', 'on']for a boolean flag);kind:'boolean'for a kill switch, rollout or targeting flag,'variant'for a weighted one.
c is the request context: request, url, cookies, and the visitor a source can see (Sources and exposures).
Return a record keyed by flag name. Each value can take one of three forms:
| You return | It means |
|---|---|
'bold' | the variant named bold |
true or false | 'on' or 'off', for a boolean flag |
{ variant, value? } | a variant, and a payload for .value(c) |
A flag you leave out uses its native rule. A variant the flag doesn’t declare is ignored, and so is a name no flag has, so a typo at the vendor can’t invent a bucket. A source’s answer sits above the native rule and the layer check, and below an override and carried claims (Decision order).
import type { FlagSource, Resolved } from '@ogygia/flags';
// one market sees every feature first; elsewhere each flag keeps its native rule
export const source: FlagSource = (queries, c) => {
if (c.request.headers.get('x-country') !== 'NZ') return {};
const out: Record<string, Resolved> = {};
for (const q of queries) {
const last = q.variants.at(-1); // a boolean flag's is 'on'
if (last) out[q.name] = last;
}
return out;
};Priming
The flags() plugin runs the source for each request inside ogygia.handle(), before the page or a server island renders, and keeps the answer on the request. That’s priming. Every flag read afterwards is synchronous. A request primed twice runs the source once, and a server island’s own request is primed like a page’s.
The source runs on every request the handle sees whenever at least one flag is registered, whether or not the page reads a flag, so its time becomes part of every response’s time to first byte. Keep it fast, and cache inside it when you can. Without the plugin, nothing primes the request: every read ignores the source and the server says flags_source_unprimed once.
Read flags only after ogygia.handle() has run. A flag read before priming, in a handle earlier in sequence(), is decided without the source and stays decided for the rest of that request, so a vendor’s answer, a kill switch included, never reaches it (#2310, Where to read). It also says flags_source_unprimed, whose message asks only for the plugin: if flags() is listed, look for such an early read.
Deadline
A request waits at most 1 second for its source. A source that hasn’t answered by then leaves every flag on its native rule for that request, and the server says flags_source_failed with a TimeoutError. Its work isn’t cancelled. ofrep() gives up sooner, after 800 ms by default.
If your provider can stall, give it a shorter deadline of your own. Returning an empty record when time runs out leaves every flag on its native rule:
import type { FlagSource, Resolved } from '@ogygia/flags';
export const within =
(ms: number, source: FlagSource): FlagSource =>
(queries, c) =>
Promise.race([
Promise.resolve(source(queries, c)),
new Promise<Record<string, Resolved>>((resolve) =>
setTimeout(() => resolve({}), ms)
)
]);Failures
A source that throws or rejects never takes the request down: every flag falls back to its native rule for that request, and the server says flags_source_failed with the error. It says so once per failing streak, and again only after a request the source served without a failure, so a source that stays down doesn’t fill the log. openfeature() reports one flag’s failure the same way while it still answers the others.
Custom sources
A source is an ordinary function, so it can read a database, a config file or a service you run. Two things to keep in mind:
- It runs on every request, over every registered flag. Ask for all of them in one query, and cache the answer for a few seconds if the states change rarely.
- It sees the request before your router or load does. Read a session cookie yourself if decisions depend on the signed-in user.
import type { FlagSource, Resolved } from '@ogygia/flags';
import { db } from '$lib/server/db';
let cached: {
at: number;
states: Record<string, Resolved>;
} | null = null;
export const dbSource: FlagSource = async (queries) => {
if (!cached || Date.now() - cached.at > 5_000) {
const rows = await db.flagStates(
queries.map((q) => q.name)
);
cached = {
at: Date.now(),
states: Object.fromEntries(
rows.map((r) => [r.name, r.variant])
)
};
}
return cached.states;
};Outside a request
The plugin calls two functions for you: prime_flags(c) at the start of each request and flush_exposures() at its end. They’re exported for code that runs outside a request the plugin sees:
prime_flags(c)runs the source for a context, such as one built in a unit test. It never throws, and priming the same request twice does nothing the second time.flush_exposures()sends the queued exposures now, and resolves once they reached the sink or were given up. It returnsundefinedwhen nothing is queued or being sent. Await it before a script or a test exits.
import { expect, test } from 'vitest';
import {
decide,
flush_exposures,
prime_flags,
type ExposureEvent
} from '@ogygia/flags';
import { hero } from '$lib/flags';
test('the source decides, and the read is exposed', async () => {
const sent: ExposureEvent[] = [];
decide({
source: () => ({ hero: 'bold' }),
exposure: (events) => void sent.push(...events)
});
const request = new Request('https://example.com/');
const c = {
request,
url: new URL(request.url),
visitor: { sub: 'user-1' }
};
await prime_flags(c);
expect(hero(c)).toBe('bold');
await flush_exposures();
expect(sent).toEqual([
expect.objectContaining({
name: 'hero',
variant: 'bold',
sub: 'user-1'
})
]);
});