diff --git a/AGENTS.md b/AGENTS.md index 4b1ce02..c9de492 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,10 +77,11 @@ scaffold. ## Where things stand -Phase 3 lands `@pegma/flags-launchdarkly` and -`@pegma/flags-aws-appconfig` beside the Phase 1 packages and -`@pegma/flags-azure-appconfig` at `0.1.0` (unpublished). Remaining -vendor adapters (Cloudflare Flagship, flagd) are still later. +Phase 3 lands `@pegma/flags-launchdarkly`, +`@pegma/flags-aws-appconfig`, and `@pegma/flags-cloudflare-flagship` +beside the Phase 1 packages and `@pegma/flags-azure-appconfig` at +`0.1.0` (unpublished). Remaining vendor adapters (flagd) are still +later. Siblings: [spine](https://github.com/pegma-dev/spine), [health](https://github.com/pegma-dev/health), diff --git a/README.md b/README.md index 57c71b1..f29850f 100644 --- a/README.md +++ b/README.md @@ -75,16 +75,17 @@ const detail = await client.evaluate("checkoutEnabled", { ## Packages -| Package | Responsibility | -| ------------------------------ | -------------------------------------------------- | -| `@pegma/flags-contracts` | Context, detail, reasons, provider port | -| `@pegma/flags-core` | Schema, client, cache, timeout, health helper | -| `@pegma/flags-static` | In-memory provider for tests and local development | -| `@pegma/flags-azure-appconfig` | Azure App Configuration provider | -| `@pegma/flags-aws-appconfig` | AWS AppConfig provider | -| `@pegma/flags-launchdarkly` | LaunchDarkly provider | - -Remaining vendor adapters (Cloudflare Flagship, flagd) are named in +| Package | Responsibility | +| ---------------------------------- | -------------------------------------------------- | +| `@pegma/flags-contracts` | Context, detail, reasons, provider port | +| `@pegma/flags-core` | Schema, client, cache, timeout, health helper | +| `@pegma/flags-static` | In-memory provider for tests and local development | +| `@pegma/flags-azure-appconfig` | Azure App Configuration provider | +| `@pegma/flags-aws-appconfig` | AWS AppConfig provider | +| `@pegma/flags-cloudflare-flagship` | Cloudflare Flagship provider | +| `@pegma/flags-launchdarkly` | LaunchDarkly provider | + +Remaining vendor adapters (flagd) are named in [the plan](docs/PROJECT_PLAN.md) and stay later. ## Development diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index 69cee5a..7dc0cd0 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -2,11 +2,11 @@ ## Status -**Stage:** Phase 3 LaunchDarkly and AWS AppConfig adapters implemented -in-tree; unpublished. Public API unstable (`0.x`). +**Stage:** Phase 3 LaunchDarkly, AWS AppConfig, and Cloudflare Flagship +adapters implemented in-tree; unpublished. Public API unstable (`0.x`). **First named consumers:** RetireGolden.org (Azure App Configuration). -Remaining vendor adapters (Cloudflare Flagship, flagd) are still later. +Remaining vendor adapters (flagd) are still later. **License:** MIT @@ -104,7 +104,7 @@ package here would invite the wrong extractions. - Flag authoring, admin UI, or a Pegma-owned flag store. - A custom expression / rule language or AppConfig document evaluator. -- Cloudflare Flagship or flagd adapter packages in this phase. +- flagd adapter packages in this phase. - Metrics, experiment assignment, or percentage math in the core. ## Package architecture @@ -117,14 +117,14 @@ package here would invite the wrong extractions. | `@pegma/flags-launchdarkly` | LaunchDarkly adapter | 3 | | `@pegma/flags-azure-appconfig` | Azure App Configuration adapter | 2 | | `@pegma/flags-aws-appconfig` | AWS AppConfig adapter | 3 | -| `@pegma/flags-cloudflare-flagship` | Cloudflare Flagship adapter | later | +| `@pegma/flags-cloudflare-flagship` | Cloudflare Flagship adapter | 3 | | `@pegma/flags-flagd` | flagd / OpenFeature adapter | later | Dependencies: `@pegma/spine` pinned exactly. `@pegma/flags-static`, -`@pegma/flags-azure-appconfig`, `@pegma/flags-aws-appconfig`, and -`@pegma/flags-launchdarkly` depend only on `@pegma/flags-contracts` (no -vendor SDK). Adapters pin contracts (and spine, if they need `Logger` / -`Clock`) exactly. +`@pegma/flags-azure-appconfig`, `@pegma/flags-aws-appconfig`, +`@pegma/flags-cloudflare-flagship`, and `@pegma/flags-launchdarkly` +depend only on `@pegma/flags-contracts` (no vendor SDK). Adapters pin +contracts (and spine, if they need `Logger` / `Clock`) exactly. ## Delivery phases @@ -146,13 +146,14 @@ still carries those rules. Do not pre-build the other vendors. ### Phase 3 — remaining adapters -`@pegma/flags-launchdarkly` and `@pegma/flags-aws-appconfig` are -in-tree. Each translates an injected reader result and must pass the -Phase 1 conformance suite. Neither imports a vendor SDK nor evaluates -targeting rules. The AWS adapter maps an already-evaluated value or an -unconditional feature-flag setting and rejects an enabled document that -still carries multi-variant rules. Cloudflare Flagship and flagd remain -later, each as its own package. +`@pegma/flags-launchdarkly`, `@pegma/flags-aws-appconfig`, and +`@pegma/flags-cloudflare-flagship` are in-tree. Each translates an +injected reader result and must pass the Phase 1 conformance suite. +None import a vendor SDK or evaluate targeting rules. The AWS adapter +maps an already-evaluated value or an unconditional feature-flag +setting and rejects an enabled document that still carries +multi-variant rules. The Flagship adapter translates an already-evaluated +`*Details` result. flagd remains later as its own package. ### Phase 4 — publish diff --git a/docs/RELEASING.md b/docs/RELEASING.md index b5f4580..db47097 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,8 +1,9 @@ # Release operations `@pegma/flags-contracts`, `@pegma/flags-core`, `@pegma/flags-static`, -`@pegma/flags-azure-appconfig`, `@pegma/flags-aws-appconfig`, and -`@pegma/flags-launchdarkly` publish +`@pegma/flags-azure-appconfig`, `@pegma/flags-aws-appconfig`, +`@pegma/flags-cloudflare-flagship`, and `@pegma/flags-launchdarkly` +publish only from a stable GitHub release. Merging a pull request never publishes, and the workflow has no manual-dispatch or npm-token fallback. Phase 3 does not publish; this runbook exists so the first @@ -14,7 +15,8 @@ Before the first release through this workflow: - configure `@pegma/flags-contracts`, `@pegma/flags-core`, `@pegma/flags-static`, `@pegma/flags-azure-appconfig`, - `@pegma/flags-aws-appconfig`, and `@pegma/flags-launchdarkly` on npm with + `@pegma/flags-aws-appconfig`, `@pegma/flags-cloudflare-flagship`, + and `@pegma/flags-launchdarkly` on npm with the GitHub Actions trusted publisher `pegma-dev/flags-core`, workflow `publish.yml`, environment `npm-publish`, and allowed action `npm publish`; diff --git a/packages/flags-cloudflare-flagship/LICENSE b/packages/flags-cloudflare-flagship/LICENSE new file mode 100644 index 0000000..897032a --- /dev/null +++ b/packages/flags-cloudflare-flagship/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 RetireGolden, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/flags-cloudflare-flagship/README.md b/packages/flags-cloudflare-flagship/README.md new file mode 100644 index 0000000..1999a0f --- /dev/null +++ b/packages/flags-cloudflare-flagship/README.md @@ -0,0 +1,78 @@ +# `@pegma/flags-cloudflare-flagship` + +Cloudflare Flagship `FlagProvider` for Pegma hosts. + +> [!IMPORTANT] +> Pegma is in early `0.x` development. This package's public API is unstable. + +The host constructs and injects a Flagship reader. This package never +imports the Flagship SDK, never owns a client singleton, and does not +evaluate targeting rules or percentage rollouts. It translates an already +evaluated `*Details` result into a `FlagResolution`. + +```ts +import { + createCloudflareFlagshipFlagProvider, + flagshipEvaluationContext, +} from "@pegma/flags-cloudflare-flagship"; +import { createFlagsClient, declareFlags, flag } from "@pegma/flags-core"; +import type { Logger } from "@pegma/spine"; + +const schema = declareFlags({ + checkoutEnabled: flag.boolean({ defaultValue: false }), +}); + +const logger: Logger = { + log(level, message, fields) { + console.log(level, message, fields); + }, +}; + +const provider = createCloudflareFlagshipFlagProvider({ + reader: { + async getDetails({ flagKey, context, defaultValue, kind }) { + const evaluationContext = flagshipEvaluationContext(context); + switch (kind) { + case "boolean": + return flags.getBooleanDetails( + flagKey, + defaultValue, + evaluationContext, + ); + case "string": + return flags.getStringDetails( + flagKey, + defaultValue, + evaluationContext, + ); + case "number": + return flags.getNumberDetails( + flagKey, + defaultValue, + evaluationContext, + ); + case "json": + return flags.getObjectDetails( + flagKey, + defaultValue, + evaluationContext, + ); + } + }, + }, +}); + +const client = createFlagsClient({ schema, logger, provider }); +``` + +`flags` is the host's Workers binding or OpenFeature client. Import +`flagshipEvaluationContext` when the host wants the documented flat +context (`targetingKey` plus scalar attributes). Hosts that need `userId` +or non-scalar attributes can map `EvaluationContext` themselves inside +the reader. + +A missing flag (`undefined` from the reader, or Flagship +`FLAG_NOT_FOUND`) is `DEFAULT_FALLBACK`. `DISABLED` is `DISABLED`. +`TARGETING_MATCH`, `SPLIT`, `DEFAULT`, and `CACHED` are +`TARGETING_MATCH` — Flagship already evaluated those rules. Other +Flagship `ERROR` codes propagate so the flags client can record `ERROR`. diff --git a/packages/flags-cloudflare-flagship/package.json b/packages/flags-cloudflare-flagship/package.json new file mode 100644 index 0000000..4acbe2f --- /dev/null +++ b/packages/flags-cloudflare-flagship/package.json @@ -0,0 +1,39 @@ +{ + "name": "@pegma/flags-cloudflare-flagship", + "version": "0.1.0", + "description": "Cloudflare Flagship FlagProvider for Pegma hosts.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "publishConfig": { + "access": "public" + }, + "files": [ + "dist/**/*.d.ts", + "dist/**/*.d.ts.map", + "dist/**/*.js", + "dist/**/*.js.map" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "engines": { + "node": ">=22" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/pegma-dev/flags-core.git", + "directory": "packages/flags-cloudflare-flagship" + }, + "dependencies": { + "@pegma/flags-contracts": "0.1.0" + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "check": "tsc -p tsconfig.json --noEmit", + "prepack": "pnpm run build" + } +} diff --git a/packages/flags-cloudflare-flagship/src/index.test.ts b/packages/flags-cloudflare-flagship/src/index.test.ts new file mode 100644 index 0000000..b600bd3 --- /dev/null +++ b/packages/flags-cloudflare-flagship/src/index.test.ts @@ -0,0 +1,426 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it, vi } from "vitest"; + +import type { + EvaluationContext, + FlagResolutionRequest, +} from "@pegma/flags-contracts"; + +import { + FLAGSHIP_ERROR_FLAG_NOT_FOUND, + FLAGSHIP_REASON_CACHED, + FLAGSHIP_REASON_DEFAULT, + FLAGSHIP_REASON_DISABLED, + FLAGSHIP_REASON_ERROR, + FLAGSHIP_REASON_SPLIT, + FLAGSHIP_REASON_TARGETING_MATCH, + createCloudflareFlagshipFlagProvider, + flagshipEvaluationContext, + type FlagshipDetailsRequest, + type FlagshipEvaluationDetails, + type FlagshipReader, +} from "./index.js"; + +const context: EvaluationContext = { targetingKey: "user-1" }; + +function request( + extras: Partial & + Pick, +): FlagResolutionRequest { + return { + context, + ...extras, + }; +} + +function detail( + value: unknown, + reason: string, + extras: { + readonly errorCode?: string; + readonly variant?: string; + } = {}, +): FlagshipEvaluationDetails { + return { + value, + reason, + ...(extras.errorCode === undefined ? {} : { errorCode: extras.errorCode }), + ...(extras.variant === undefined ? {} : { variant: extras.variant }), + }; +} + +function memoryReader( + details: Readonly>, + extras: { + readonly delayMs?: number; + readonly error?: unknown; + readonly onGet?: (request: FlagshipDetailsRequest) => void; + readonly detailsForContext?: ( + context: EvaluationContext, + ) => Readonly>; + } = {}, +): FlagshipReader { + return { + async getDetails(getRequest) { + extras.onGet?.(getRequest); + if (extras.delayMs !== undefined && extras.delayMs > 0) { + await new Promise((resolve) => { + setTimeout(resolve, extras.delayMs); + }); + } + if (extras.error !== undefined) { + throw extras.error; + } + const table = extras.detailsForContext?.(getRequest.context) ?? details; + return Object.hasOwn(table, getRequest.flagKey) + ? table[getRequest.flagKey] + : undefined; + }, + }; +} + +describe("flagshipEvaluationContext", () => { + it("maps targeting key and scalar attributes", () => { + expect( + flagshipEvaluationContext({ + targetingKey: "user-1", + tenant: "acme", + environment: "prod", + principalId: "principal-1" as NonNullable< + EvaluationContext["principalId"] + >, + attributes: { + plan: "pro", + seats: 3, + beta: true, + targetingKey: "should-not-win", + nested: { ignored: true }, + }, + }), + ).toEqual({ + targetingKey: "user-1", + tenant: "acme", + environment: "prod", + principalId: "principal-1", + plan: "pro", + seats: 3, + beta: true, + }); + }); +}); + +describe("createCloudflareFlagshipFlagProvider", () => { + it("requires an injected reader", () => { + expect(() => + createCloudflareFlagshipFlagProvider({} as { reader: FlagshipReader }), + ).toThrow("injected Flagship reader"); + }); + + it("returns DEFAULT_FALLBACK for a missing key", async () => { + const provider = createCloudflareFlagshipFlagProvider({ + reader: memoryReader({}), + }); + await expect( + provider.resolve( + request({ + flagKey: "theme", + kind: "string", + defaultValue: "light", + }), + ), + ).resolves.toEqual({ + value: "light", + reason: "DEFAULT_FALLBACK", + }); + }); + + it("returns DEFAULT_FALLBACK for Flagship FLAG_NOT_FOUND", async () => { + const provider = createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ + theme: detail("light", FLAGSHIP_REASON_ERROR, { + errorCode: FLAGSHIP_ERROR_FLAG_NOT_FOUND, + }), + }), + }); + await expect( + provider.resolve( + request({ flagKey: "theme", kind: "string", defaultValue: "light" }), + ), + ).resolves.toEqual({ + value: "light", + reason: "DEFAULT_FALLBACK", + }); + }); + + it("translates TARGETING_MATCH, SPLIT, DEFAULT, and CACHED as targeting matches", async () => { + const provider = createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ + checkoutEnabled: detail(true, FLAGSHIP_REASON_TARGETING_MATCH, { + variant: "on", + }), + theme: detail("dark", FLAGSHIP_REASON_SPLIT, { + variant: "dark", + }), + maxItems: detail(25, FLAGSHIP_REASON_DEFAULT), + payload: detail({ experiment: "on" }, FLAGSHIP_REASON_CACHED), + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).resolves.toEqual({ + value: true, + reason: "TARGETING_MATCH", + variant: "on", + }); + await expect( + provider.resolve( + request({ flagKey: "theme", kind: "string", defaultValue: "light" }), + ), + ).resolves.toEqual({ + value: "dark", + reason: "TARGETING_MATCH", + variant: "dark", + }); + await expect( + provider.resolve( + request({ flagKey: "maxItems", kind: "number", defaultValue: 10 }), + ), + ).resolves.toEqual({ value: 25, reason: "TARGETING_MATCH" }); + await expect( + provider.resolve( + request({ + flagKey: "payload", + kind: "json", + defaultValue: { experiment: "off" }, + }), + ), + ).resolves.toEqual({ + value: { experiment: "on" }, + reason: "TARGETING_MATCH", + }); + }); + + it("omits variant when Flagship returns an empty variant", async () => { + const provider = createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ + theme: detail("dark", FLAGSHIP_REASON_TARGETING_MATCH, { + variant: "", + }), + }), + }); + await expect( + provider.resolve( + request({ flagKey: "theme", kind: "string", defaultValue: "light" }), + ), + ).resolves.toEqual({ + value: "dark", + reason: "TARGETING_MATCH", + }); + }); + + it("translates DISABLED as DISABLED", async () => { + const provider = createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ + checkoutEnabled: detail(false, FLAGSHIP_REASON_DISABLED, { + variant: "off", + }), + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: true, + }), + ), + ).resolves.toEqual({ + value: false, + reason: "DISABLED", + variant: "off", + }); + }); + + it("does not treat an unknown reason as a targeting match", async () => { + const provider = createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ + checkoutEnabled: detail(true, "PERCENTILE_ROLLOUT"), + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("is not translated"); + }); + + it("propagates Flagship evaluation errors without an errorCode", async () => { + const provider = createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ + checkoutEnabled: detail(false, FLAGSHIP_REASON_ERROR), + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("Flagship evaluation failed for checkoutEnabled"); + }); + + it("propagates Flagship evaluation errors other than FLAG_NOT_FOUND", async () => { + const provider = createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ + checkoutEnabled: detail(false, FLAGSHIP_REASON_ERROR, { + errorCode: "TYPE_MISMATCH", + }), + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("TYPE_MISMATCH"); + }); + + it("does not treat an errorCode on a match as a targeting match", async () => { + const provider = createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ + checkoutEnabled: detail(true, FLAGSHIP_REASON_TARGETING_MATCH, { + errorCode: "GENERAL", + }), + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("GENERAL"); + }); + + it("forwards the targeting key and kind to the reader", async () => { + const seen: FlagshipDetailsRequest[] = []; + const provider = createCloudflareFlagshipFlagProvider({ + reader: memoryReader( + { + theme: detail("dark", FLAGSHIP_REASON_TARGETING_MATCH), + }, + { + onGet(getRequest) { + seen.push(getRequest); + }, + }, + ), + }); + await provider.resolve( + request({ + flagKey: "theme", + kind: "string", + defaultValue: "light", + context: { targetingKey: "user-1" }, + }), + ); + expect(seen[0]?.context.targetingKey).toBe("user-1"); + expect(seen[0]?.defaultValue).toBe("light"); + expect(seen[0]?.kind).toBe("string"); + }); + + it("applies host keyOf without inventing a layout", async () => { + const seen: FlagshipDetailsRequest[] = []; + const provider = createCloudflareFlagshipFlagProvider({ + keyOf: (flagKey) => `app.${flagKey}`, + reader: memoryReader( + { + "app.checkoutEnabled": detail(true, FLAGSHIP_REASON_TARGETING_MATCH), + }, + { + onGet(getRequest) { + seen.push(getRequest); + }, + }, + ), + }); + const resolution = await provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ); + expect(resolution.reason).toBe("TARGETING_MATCH"); + expect(seen[0]?.flagKey).toBe("app.checkoutEnabled"); + }); + + it("throws when a detail is missing a reason", async () => { + const provider = createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ + checkoutEnabled: { + value: true, + reason: "", + }, + }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("reason"); + }); + + it("propagates reader failures", async () => { + const provider = createCloudflareFlagshipFlagProvider({ + reader: memoryReader({}, { error: new Error("flagship unavailable") }), + }); + await expect( + provider.resolve( + request({ + flagKey: "checkoutEnabled", + kind: "boolean", + defaultValue: false, + }), + ), + ).rejects.toThrow("flagship unavailable"); + }); + + it("closes the injected reader", async () => { + const close = vi.fn(); + const provider = createCloudflareFlagshipFlagProvider({ + reader: { ...memoryReader({}), close }, + }); + await provider.close?.(); + expect(close).toHaveBeenCalledOnce(); + }); + + it("does not import a Flagship SDK or call Date.now on the production path", () => { + const source = readFileSync(join(import.meta.dirname, "index.ts"), "utf8"); + expect(source).not.toMatch(/@cloudflare\/flagship/u); + expect(source).not.toMatch(/@cloudflare\/workers-types/u); + expect(source).not.toMatch(/Date\.now\(/u); + }); +}); diff --git a/packages/flags-cloudflare-flagship/src/index.ts b/packages/flags-cloudflare-flagship/src/index.ts new file mode 100644 index 0000000..257aaf9 --- /dev/null +++ b/packages/flags-cloudflare-flagship/src/index.ts @@ -0,0 +1,239 @@ +import type { + EvaluationContext, + FlagProvider, + FlagProviderCapabilities, + FlagResolution, + FlagResolutionRequest, + FlagValueKind, +} from "@pegma/flags-contracts"; + +/** + * Flagship evaluation reasons this adapter translates. + * + * @see https://developers.cloudflare.com/flagship/reference/evaluation-reasons/ + */ +export const FLAGSHIP_REASON_TARGETING_MATCH = "TARGETING_MATCH"; +export const FLAGSHIP_REASON_SPLIT = "SPLIT"; +export const FLAGSHIP_REASON_DEFAULT = "DEFAULT"; +export const FLAGSHIP_REASON_DISABLED = "DISABLED"; +export const FLAGSHIP_REASON_CACHED = "CACHED"; +export const FLAGSHIP_REASON_ERROR = "ERROR"; + +/** Flagship `errorCode` for a flag the app does not define. */ +export const FLAGSHIP_ERROR_FLAG_NOT_FOUND = "FLAG_NOT_FOUND"; + +/** Scalar Flagship targeting attributes. Objects and arrays are omitted. */ +export type FlagshipAttributeValue = string | number | boolean; + +/** + * Flat Flagship / OpenFeature evaluation context. `targetingKey` is the + * primary identifier. Additional attributes must be scalars. + * + * @see https://developers.cloudflare.com/flagship/binding/types/ + */ +export interface FlagshipEvaluationContext { + readonly targetingKey: string; + readonly [attribute: string]: FlagshipAttributeValue | undefined; +} + +/** + * Narrow detail the injected reader returns. Matches Flagship + * `*Details` methods and OpenFeature evaluation details. + */ +export interface FlagshipEvaluationDetails { + readonly value: unknown; + readonly variant?: string; + readonly reason?: string; + readonly errorCode?: string; + readonly flagKey?: string; +} + +export interface FlagshipDetailsRequest { + readonly flagKey: string; + readonly context: EvaluationContext; + readonly defaultValue: unknown; + readonly kind: FlagValueKind; +} + +/** + * Host-injected Flagship lookup. Typically a thin wrapper around a + * Workers `env.FLAGS.get*Details` binding or an OpenFeature client that + * maps a missing flag to `undefined` or returns Flagship's + * `FLAG_NOT_FOUND` detail. This package never imports the Flagship SDK. + */ +export interface FlagshipReader { + getDetails( + request: FlagshipDetailsRequest, + ): Promise; + close?(): void | Promise; +} + +export interface CloudflareFlagshipFlagProviderOptions { + readonly reader: FlagshipReader; + readonly name?: string; + readonly keyOf?: (flagKey: string) => string; +} + +function own(record: object, key: string): unknown { + return Object.hasOwn(record, key) + ? (record as Record)[key] + : undefined; +} + +function isFlagshipAttributeValue( + value: unknown, +): value is FlagshipAttributeValue { + return ( + typeof value === "string" || + typeof value === "number" || + typeof value === "boolean" + ); +} + +/** + * Builds the documented flat Flagship evaluation context for `context`. + * `targetingKey` is the primary identifier. Optional tenant, environment, + * principal, and scalar host attributes are copied as attributes. Hosts + * that need `userId` or non-scalar attributes should map the context + * themselves in the injected reader. + */ +export function flagshipEvaluationContext( + context: EvaluationContext, +): FlagshipEvaluationContext { + const attributes: Record = {}; + for (const [key, value] of Object.entries(context.attributes ?? {})) { + if (isFlagshipAttributeValue(value)) { + attributes[key] = value; + } + } + if (typeof context.principalId === "string") { + attributes.principalId = context.principalId; + } + if (context.tenant !== undefined) { + attributes.tenant = context.tenant; + } + if (context.environment !== undefined) { + attributes.environment = context.environment; + } + return { + ...attributes, + targetingKey: context.targetingKey, + }; +} + +function variantOf( + detail: FlagshipEvaluationDetails, +): { readonly variant: string } | Record { + if (typeof detail.variant !== "string" || detail.variant === "") { + return {}; + } + return { variant: detail.variant }; +} + +function requireReasonKind(detail: FlagshipEvaluationDetails): string { + const reason = own(detail, "reason"); + if (typeof reason !== "string" || reason === "") { + throw new Error("Flagship evaluation detail is missing a reason"); + } + return reason; +} + +function requireErrorCode( + detail: FlagshipEvaluationDetails, +): string | undefined { + const errorCode = own(detail, "errorCode"); + if (errorCode === undefined) { + return undefined; + } + if (typeof errorCode !== "string") { + throw new Error("Flagship evaluation detail has a non-string errorCode"); + } + return errorCode === "" ? undefined : errorCode; +} + +function resolveDetail( + request: FlagResolutionRequest, + detail: FlagshipEvaluationDetails, +): FlagResolution { + const reason = requireReasonKind(detail); + const errorCode = requireErrorCode(detail); + if (errorCode === FLAGSHIP_ERROR_FLAG_NOT_FOUND) { + return { value: request.defaultValue, reason: "DEFAULT_FALLBACK" }; + } + if (reason === FLAGSHIP_REASON_ERROR || errorCode !== undefined) { + throw new Error( + errorCode === undefined + ? `Flagship evaluation failed for ${request.flagKey}` + : `Flagship evaluation failed for ${request.flagKey}: ${errorCode}`, + ); + } + switch (reason) { + case FLAGSHIP_REASON_TARGETING_MATCH: + case FLAGSHIP_REASON_SPLIT: + case FLAGSHIP_REASON_DEFAULT: + case FLAGSHIP_REASON_CACHED: + return { + value: detail.value, + reason: "TARGETING_MATCH", + ...variantOf(detail), + }; + case FLAGSHIP_REASON_DISABLED: + return { + value: detail.value, + reason: "DISABLED", + ...variantOf(detail), + }; + default: + throw new Error( + `Flagship evaluation reason ${reason} is not translated by this adapter`, + ); + } +} + +/** + * Translates Flagship `*Details` results into {@link FlagProvider} + * resolutions. Targeting rules and percentage rollouts are not evaluated + * here — Flagship already did that. The injected reader must return an + * already-evaluated detail. + */ +export function createCloudflareFlagshipFlagProvider( + options: CloudflareFlagshipFlagProviderOptions, +): FlagProvider { + if ( + options.reader === undefined || + typeof options.reader.getDetails !== "function" + ) { + throw new Error( + "createCloudflareFlagshipFlagProvider requires an injected Flagship reader", + ); + } + const name = options.name ?? "cloudflare-flagship"; + const capabilities: FlagProviderCapabilities = { + static: false, + streaming: false, + targeting: true, + }; + + return { + name, + capabilities() { + return capabilities; + }, + async resolve(request) { + const flagKey = options.keyOf?.(request.flagKey) ?? request.flagKey; + const detail = await options.reader.getDetails({ + flagKey, + context: request.context, + defaultValue: request.defaultValue, + kind: request.kind, + }); + if (detail === undefined) { + return { value: request.defaultValue, reason: "DEFAULT_FALLBACK" }; + } + return resolveDetail(request, detail); + }, + async close() { + await options.reader.close?.(); + }, + }; +} diff --git a/packages/flags-cloudflare-flagship/tsconfig.json b/packages/flags-cloudflare-flagship/tsconfig.json new file mode 100644 index 0000000..bc330dd --- /dev/null +++ b/packages/flags-cloudflare-flagship/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "tsBuildInfoFile": "tsconfig.tsbuildinfo", + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"], + "references": [{ "path": "../flags-contracts" }] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5682ade..fd5cf73 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -33,6 +33,12 @@ importers: specifier: 0.1.0 version: link:../flags-contracts + packages/flags-cloudflare-flagship: + dependencies: + '@pegma/flags-contracts': + specifier: 0.1.0 + version: link:../flags-contracts + packages/flags-contracts: dependencies: '@pegma/spine': diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index ca9d72c..d549739 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -47,6 +47,10 @@ export const RELEASE_PACKAGES = [ directory: "flags-aws-appconfig", name: "@pegma/flags-aws-appconfig", }, + { + directory: "flags-cloudflare-flagship", + name: "@pegma/flags-cloudflare-flagship", + }, { directory: "flags-launchdarkly", name: "@pegma/flags-launchdarkly", diff --git a/tests/cloudflare-flagship-conformance.test.ts b/tests/cloudflare-flagship-conformance.test.ts new file mode 100644 index 0000000..e3acd9c --- /dev/null +++ b/tests/cloudflare-flagship-conformance.test.ts @@ -0,0 +1,110 @@ +import { describe, it } from "vitest"; + +import type { EvaluationContext } from "../packages/flags-contracts/src/index.js"; +import { flagConformanceCases } from "../packages/flags-core/src/conformance.js"; +import { + FLAGSHIP_REASON_DISABLED, + FLAGSHIP_REASON_TARGETING_MATCH, + createCloudflareFlagshipFlagProvider, + type FlagshipEvaluationDetails, + type FlagshipReader, +} from "../packages/flags-cloudflare-flagship/src/index.js"; + +function wait(delayMs: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, delayMs); + }); +} + +function detailFor(value: unknown): FlagshipEvaluationDetails { + return { + value, + reason: FLAGSHIP_REASON_TARGETING_MATCH, + }; +} + +function detailsFromFlags( + flags: Readonly>, +): Record { + return Object.fromEntries( + Object.entries(flags).map(([flagKey, value]) => [ + flagKey, + detailFor(value), + ]), + ); +} + +function memoryReader(options: { + readonly details?: Readonly>; + readonly detailsForContext?: ( + context: EvaluationContext, + ) => Readonly>; + readonly delayMs?: number; + readonly error?: unknown; +}): FlagshipReader { + return { + async getDetails(request) { + if (options.delayMs !== undefined && options.delayMs > 0) { + await wait(options.delayMs); + } + if (options.error !== undefined) { + throw options.error; + } + const details = + options.detailsForContext?.(request.context) ?? options.details ?? {}; + return Object.hasOwn(details, request.flagKey) + ? details[request.flagKey] + : undefined; + }, + }; +} + +const cases = flagConformanceCases((scenario) => { + switch (scenario.type) { + case "values": + return createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ details: detailsFromFlags(scenario.flags) }), + }); + case "empty": + return createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ details: {} }), + }); + case "targeted": + return createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ + detailsForContext(context) { + return context.targetingKey === scenario.targetingKey + ? detailsFromFlags(scenario.flags) + : {}; + }, + }), + }); + case "timeout": + return createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ delayMs: scenario.delayMs }), + }); + case "error": + return createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ error: scenario.error }), + }); + case "disabled": + return createCloudflareFlagshipFlagProvider({ + reader: memoryReader({ + details: { + [scenario.flagKey]: { + value: scenario.value, + reason: FLAGSHIP_REASON_DISABLED, + }, + }, + }), + }); + } +}); + +describe("Cloudflare Flagship provider conformance", () => { + for (const testCase of cases) { + it(testCase.name, async () => { + await testCase.run(); + }); + } +}); diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index c0102c3..0b57692 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -47,6 +47,7 @@ describe("release package metadata", () => { "@pegma/flags-static", "@pegma/flags-azure-appconfig", "@pegma/flags-aws-appconfig", + "@pegma/flags-cloudflare-flagship", "@pegma/flags-launchdarkly", ]); }); diff --git a/tsconfig.json b/tsconfig.json index 0fafba7..c7dd4b0 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,6 +6,7 @@ { "path": "./packages/flags-static" }, { "path": "./packages/flags-azure-appconfig" }, { "path": "./packages/flags-aws-appconfig" }, + { "path": "./packages/flags-cloudflare-flagship" }, { "path": "./packages/flags-launchdarkly" } ] }