|
| 1 | +import { env } from "cloudflare:workers"; |
| 2 | +import { Data, Effect, Layer, Option, Schema } from "effect"; |
| 3 | +import { |
| 4 | + FeatureFlags, |
| 5 | + type FeatureFlagContext, |
| 6 | + type FeatureFlagsShape, |
| 7 | +} from "@executor-js/host-mcp"; |
| 8 | + |
| 9 | +class PostHogFeatureFlagError extends Data.TaggedError("PostHogFeatureFlagError")<{ |
| 10 | + readonly cause: unknown; |
| 11 | +}> {} |
| 12 | + |
| 13 | +const FeatureFlagsResponse = Schema.Struct({ |
| 14 | + featureFlags: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), |
| 15 | +}); |
| 16 | +const decodeFeatureFlagsResponse = Schema.decodeUnknownOption(FeatureFlagsResponse); |
| 17 | + |
| 18 | +const postHogHost = (): string => (env.POSTHOG_HOST ?? "https://us.i.posthog.com").replace(/\/$/, ""); |
| 19 | + |
| 20 | +const flagValueEnabled = (value: unknown): boolean => |
| 21 | + value !== false && value !== null && value !== undefined; |
| 22 | + |
| 23 | +const distinctIdFor = (context: FeatureFlagContext): string => |
| 24 | + context.distinctId ?? context.accountId ?? context.organizationId ?? "executor-cloud"; |
| 25 | + |
| 26 | +const groupsFor = (context: FeatureFlagContext): Record<string, string> | undefined => { |
| 27 | + const groups = { |
| 28 | + ...(context.groups ?? {}), |
| 29 | + ...(context.organizationId ? { organization: context.organizationId } : {}), |
| 30 | + }; |
| 31 | + return Object.keys(groups).length > 0 ? groups : undefined; |
| 32 | +}; |
| 33 | + |
| 34 | +export const makePostHogFeatureFlags = (): FeatureFlagsShape => ({ |
| 35 | + isEnabled: (flag, context) => |
| 36 | + Effect.gen(function* () { |
| 37 | + const apiKey = env.VITE_PUBLIC_POSTHOG_KEY; |
| 38 | + if (!apiKey) return false; |
| 39 | + |
| 40 | + const response = yield* Effect.tryPromise({ |
| 41 | + try: () => |
| 42 | + fetch(`${postHogHost()}/decide/?v=3`, { |
| 43 | + method: "POST", |
| 44 | + headers: { "content-type": "application/json" }, |
| 45 | + body: JSON.stringify({ |
| 46 | + api_key: apiKey, |
| 47 | + distinct_id: distinctIdFor(context), |
| 48 | + groups: groupsFor(context), |
| 49 | + }), |
| 50 | + }), |
| 51 | + catch: (cause) => new PostHogFeatureFlagError({ cause }), |
| 52 | + }); |
| 53 | + |
| 54 | + if (!response.ok) return false; |
| 55 | + |
| 56 | + const raw = yield* Effect.tryPromise({ |
| 57 | + try: () => response.json(), |
| 58 | + catch: (cause) => new PostHogFeatureFlagError({ cause }), |
| 59 | + }); |
| 60 | + const decoded = decodeFeatureFlagsResponse(raw); |
| 61 | + if (Option.isNone(decoded)) return false; |
| 62 | + return flagValueEnabled(decoded.value.featureFlags?.[flag]); |
| 63 | + }).pipe(Effect.withSpan("feature_flags.posthog.is_enabled", { attributes: { flag } })), |
| 64 | +}); |
| 65 | + |
| 66 | +export const PostHogFeatureFlags = Layer.succeed(FeatureFlags, makePostHogFeatureFlags()); |
0 commit comments